qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
11,200 | <p>I'm guessing it needs to be something like:</p>
<pre><code>CONVERT(CHAR(24), lastModified, 101)
</code></pre>
<p>However I'm not sure of the right value for the third parameter.</p>
<p>Thanks!</p>
<hr>
<p>Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway.</p>
| [
{
"answer_id": 11213,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>Define \"last epoch\". Does this come close?</p>\n\n<p>Select Cast(lastModified As Integer)</p>\n"
},
{
"answer_id": 11216,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Last epoch is when 1970 GMT?</p>\n\n<pre><code>SELECT DATEDIFF(s,'19700101 05:00:00:000',lastModified)\n</code></pre>\n\n<p>See also <a href=\"http://wiki.lessthandot.com/index.php/Epoch_Date\" rel=\"nofollow noreferrer\">Epoch Date</a></p>\n"
},
{
"answer_id": 11229,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>If you store them as varchar, store them as YYYYMMDD. That way you CAN sort by them later if you want to.</p>\n"
},
{
"answer_id": 11234,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>SQL server has only 2 failsafe date formats</p>\n\n<p>ISO = YYYYMMDD, run this to see that </p>\n\n<pre><code> select convert(varchar(10),getdate(),112)\n</code></pre>\n\n<p>ISO8601 = yyyy-mm-dd Thh:mm:ss:mmm(no spaces) run this to see that </p>\n\n<pre><code>select convert(varchar(30),getdate(),126)\n</code></pre>\n\n<p>To learn more about how dates are stored in SQL server I wrote <a href=\"http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-are-dates-stored-in-sql-server\" rel=\"nofollow noreferrer\">How Are Dates Stored In SQL Server?</a></p>\n"
},
{
"answer_id": 11240,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 2,
"selected": true,
"text": "<p>I wound up using format 120 in MS SQL: </p>\n\n<pre><code>convert(char(24), lastModified, 120)\n</code></pre>\n\n<p>Each time I needed to a select a date in SQLite for non-display purposes I used:</p>\n\n<pre><code>strftime(\\\"%Y-%m-%d %H:%M:%S\\\", dateModified) as dateModified\n</code></pre>\n\n<p>Now I just need a readable/friendly way to display the date to the user!</p>\n\n<p>edit: accept answer goes to whoever shows me how to display the date nicely from sqlite ;p</p>\n"
},
{
"answer_id": 4820954,
"author": "Noah",
"author_id": 12113,
"author_profile": "https://Stackoverflow.com/users/12113",
"pm_score": 2,
"selected": false,
"text": "<p>sqlite> <strong>select datetime();</strong><br>\n2011-01-27 19:32:57</p>\n\n<p>sqlite> <strong>select strftime('%Y-%m-%d %H:%M:%S','now');</strong><br>\n2011-01-27 19:33:57 </p>\n\n<p><strong>REFERENCE:</strong><br>\n(Date time Functions)[http://sqlite.org/lang_datefunc.html]</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I'm guessing it needs to be something like:
```
CONVERT(CHAR(24), lastModified, 101)
```
However I'm not sure of the right value for the third parameter.
Thanks!
---
Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway. | I wound up using format 120 in MS SQL:
```
convert(char(24), lastModified, 120)
```
Each time I needed to a select a date in SQLite for non-display purposes I used:
```
strftime(\"%Y-%m-%d %H:%M:%S\", dateModified) as dateModified
```
Now I just need a readable/friendly way to display the date to the user!
edit: accept answer goes to whoever shows me how to display the date nicely from sqlite ;p |
11,219 | <p>I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages.</p>
<p>I haven't the slightest idea how to do that. </p>
| [
{
"answer_id": 11237,
"author": "SitWalkStand",
"author_id": 509,
"author_profile": "https://Stackoverflow.com/users/509",
"pm_score": 3,
"selected": false,
"text": "<p>Here are a few articles describing how to call a web service from a class ASP page:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/20210125161040/http://www.4guysfromrolla.com/webtech/070302-1.shtml\" rel=\"nofollow noreferrer\">Integrating ASP.NET XML Web Services with 'Classic' ASP Applications</a> </li>\n<li><a href=\"http://www.dotnetjunkies.com/Tutorial/99CA4563-FBD4-411F-A9C6-FF9E8A0E664F.dcik\" rel=\"nofollow noreferrer\">Consuming XML Web Services in Classic ASP</a></li>\n<li><a href=\"http://www.aspfree.com/c/a/ASP/Consuming-a-WSDL-Webservice-from-ASP/\" rel=\"nofollow noreferrer\">Consuming a WSDL Webservice from ASP</a></li>\n</ul>\n"
},
{
"answer_id": 11238,
"author": "KP.",
"author_id": 439,
"author_profile": "https://Stackoverflow.com/users/439",
"pm_score": 6,
"selected": true,
"text": "<p>You could use a combination of JQuery with JSON calls to consume REST services from the client</p>\n\n<p>or</p>\n\n<p>if you need to interact with the REST services from the ASP layer you can use</p>\n\n<p>MSXML2.ServerXMLHTTP</p>\n\n<p>like:</p>\n\n<pre><code>Set HttpReq = Server.CreateObject(\"MSXML2.ServerXMLHTTP\")\nHttpReq.open \"GET\", \"Rest_URI\", False\nHttpReq.send\n</code></pre>\n"
},
{
"answer_id": 11242,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 0,
"selected": false,
"text": "<p>All you need is an HTTP client. In .Net, WebRequest works well. For classic ASP, you will need a specific component like <a href=\"http://web.archive.org/web/20140829190201/http://www.coalesys.com/products/httpclient/features/default.asp\" rel=\"nofollow noreferrer\">this one</a>.</p>\n"
},
{
"answer_id": 11251,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/11219/calling-rest-web-services-from-a-classic-asp-page#11238\">KP</a></p>\n\n<p>You should actually use <code>MSXML2.ServerXMLHTTP</code> from ASP/server side applications. <code>XMLHTTP</code> should only be used client side because it uses WinInet which is not supported for use in server/service apps. </p>\n\n<p>See <a href=\"http://support.microsoft.com/kb/290761\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/290761</a>, questions 3, 4 & 5 and</p>\n\n<p><a href=\"http://support.microsoft.com/kb/238425/\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/238425/</a>. </p>\n\n<p>This is quite important, otherwise you'll experience your web app hanging and all sorts of strange nonsense going on.</p>\n"
},
{
"answer_id": 60343,
"author": "garretmagin",
"author_id": 6208,
"author_profile": "https://Stackoverflow.com/users/6208",
"pm_score": 0,
"selected": false,
"text": "<p>Another possibility is to use the WinHttp COM object <a href=\"http://msdn.microsoft.com/en-us/library/aa384079(VS.85).aspx\" rel=\"nofollow noreferrer\">Using the WinHttpRequest COM Object</a>.</p>\n\n<p>WinHttp was designed to be used from server code.</p>\n"
},
{
"answer_id": 4670659,
"author": "ianmayo",
"author_id": 92441,
"author_profile": "https://Stackoverflow.com/users/92441",
"pm_score": 2,
"selected": false,
"text": "<p>A number of the answers presented here appear to cover how ClassicASP can be used to consume web-services & REST calls.</p>\n\n<p>In my opinion a tidier solution may be for your ClassicASP to just serve data in REST formats. Let your browser-based client code handle the 'mashup' if possible. You should be able to do this without incorporating any other ASP components.</p>\n\n<p>So, here's how I would mockup shiny new REST support in ClassicASP:</p>\n\n<ol>\n<li>provide a single ASP web page that acts as a landing pad</li>\n<li>The landing pad will handle two parameters: verb and URL, plus a set of form contents</li>\n<li>Use some kind of switch block inspect the URL and direct the verb (and form contents) to a relevant handler</li>\n<li>The handler will then process the verb (PUT/POST/GET/DELETE) together with the form contents, returning a success/failure code plus data as appropriate.</li>\n<li>Your landing pad will inspect the success/failure code and return the respective HTTP status plus any returned data</li>\n</ol>\n\n<p>You would benefit from a support class that decodes/encodes the form data from/to JSON, since that will ease your client-side implementation (and potentially streamline the volume of data passed). See the conversation here at <a href=\"https://stackoverflow.com/questions/1019223/any-good-libraries-for-parsing-json-in-classic-asp\">Any good libraries for parsing JSON in Classic ASP?</a></p>\n\n<p>Lastly, at the client-side, provide a method that takes a Verb, Url and data payload. In the short-term the method will collate the parameters and forward them to your landing pad. In the longer term (once you switch away from Classic ASP) your method can send the data to the 'real' url.</p>\n\n<p>Good luck...</p>\n"
},
{
"answer_id": 47422679,
"author": "grahamesd",
"author_id": 441729,
"author_profile": "https://Stackoverflow.com/users/441729",
"pm_score": 1,
"selected": false,
"text": "<p>Another possible solution is to write a .NET DLL that makes the calls and returns the results (maybe wrap something like RESTSharp - give it a simple API customized to your needs). Then you register the DLL as a COM DLL and use it in your ASP code via the CreateObject method. </p>\n\n<p>I've done this for things like creating signed JWTs and salting and hashing passwords. It works nicely (while you work like crazy to rewrite the ASP).</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160/"
] | I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages.
I haven't the slightest idea how to do that. | You could use a combination of JQuery with JSON calls to consume REST services from the client
or
if you need to interact with the REST services from the ASP layer you can use
MSXML2.ServerXMLHTTP
like:
```
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.open "GET", "Rest_URI", False
HttpReq.send
``` |
11,267 | <h1>Outline</h1>
<p>OK, I have Google'd this and already expecting a big fat <strong>NO!!</strong> But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^_^</p>
<p>I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be. </p>
<p><strong>NOTE:</strong> This is a standard User Control (.ascx), <em>NOT</em> a custom rendered control.</p>
<h2>Current Code</h2>
<p>Here is the class & event definition:</p>
<pre><code>[System.ComponentModel.DefaultEvent("OKClicked")]
public partial class AddressBox : System.Web.UI.UserControl
{
public event EventHandler OKClicked;
</code></pre>
<h2>Current Result</h2>
<p>Now, when I double click the the control when it is on a ASPX page, the following is created:</p>
<pre><code> protected void AddressBox1_Load(object sender, EventArgs e)
{
}
</code></pre>
<p>Not quite what I was expecting! So, my question:</p>
<h2>Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason?</h2>
<hr>
<p><strong>Side Note</strong>: How do we put underscores in code? I cant seem to put and escape char in?</p>
| [
{
"answer_id": 11271,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": true,
"text": "<p>I think to be honest you a better just boning up on your standard design patterns and applying them to the individual problems that you face in developing your UI.</p>\n<p>While there are common UI "themes" (such as dealing with modifier keys) the actual implementation may vary widely.</p>\n<p>I have O'Reilly's <a href=\"http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns%2Fdp%2F0596007124%2Fref%3Dpd_bbs_sr_1%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-1&tag=robcthegeek-21&linkCode=ur2&camp=1634&creative=6738\" rel=\"nofollow noreferrer\">Head First Design Patterns</a> and <a href=\"http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns-Poster%2Fdp%2F0596102143%2Fref%3Dpd_bbs_sr_3%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-3&tag=robcthegeek-21&linkCode=ur2&camp=1634&creative=6738\" rel=\"nofollow noreferrer\">The Poster</a>, which I have found invaluable!</p>\n<h3>Shameless Plug : These links are using my associates ID.</h3>\n"
},
{
"answer_id": 11274,
"author": "Antonio Haley",
"author_id": 390,
"author_profile": "https://Stackoverflow.com/users/390",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think the that benefit of design patterns come from trying to find a design pattern to fit a problem. You can however use some heuristics to help clean up your design in this quite a bit, like keeping the UI as decoupled as possible from the rest of the objects in your system.</p>\n\n<p>There is a pattern that might help out in this case, the <a href=\"http://en.wikipedia.org/wiki/Observer_pattern\" rel=\"nofollow noreferrer\">Observer Pattern</a>.</p>\n"
},
{
"answer_id": 221216,
"author": "Micha",
"author_id": 29893,
"author_profile": "https://Stackoverflow.com/users/29893",
"pm_score": 2,
"selected": false,
"text": "<p>perhaps you're looking for something like the 'MouseTrap' which I saw in some articles on codeproject (search for UI Platform)?</p>\n\n<p>I also found this series very useful <a href=\"http://codebetter.com/jeremymiller/2007/07/26/the-build-your-own-cab-series-table-of-contents/\" rel=\"nofollow noreferrer\">http://codebetter.com/jeremymiller/2007/07/26/the-build-your-own-cab-series-table-of-contents/</a> where you might have a look at embedded controllers etc.</p>\n\n<p>Micha.</p>\n"
},
{
"answer_id": 321973,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 2,
"selected": false,
"text": "<p>I know you said not as global as MVC, but there are some variations on MVC - specifically HMVC and PAC - which I think can answer questions such as the ones you pose.</p>\n\n<p>Other than that, try to write new code \"in the spirit\" of existing patterns even if you don't apply them directly.</p>\n"
},
{
"answer_id": 2999391,
"author": "DTS",
"author_id": 270699,
"author_profile": "https://Stackoverflow.com/users/270699",
"pm_score": 3,
"selected": false,
"text": "<p>Object-Oriented Design and Patterns by Cay Horstmann has a chapter entitled \"Patterns and GUI Programming\". In that chapter, Horstmann touches on the following patterns:</p>\n\n<ul>\n<li>Observer Layout Managers and the</li>\n<li>Strategy Pattern Components,</li>\n<li>Containers, and the Composite Pattern</li>\n<li>Scroll Bars and the Decorator Pattern</li>\n</ul>\n"
},
{
"answer_id": 11825280,
"author": "ISTB",
"author_id": 1452934,
"author_profile": "https://Stackoverflow.com/users/1452934",
"pm_score": 2,
"selected": false,
"text": "<p>You are looking at a professional application programming. I searched for tips and tricks a long time, without success. Unfortunately you will not find anything useful, it is a complicated topic and only with many years of experience you will be able to understand how to write efficiently an application. For example, almost every program opens a file, extracts information, shows it in different forms, allow processing, saving, ... but nobody explains exactly what the good strategy is and so on. Further, if you are writing a big application, you need to look at some strategies to reduce your compilation time (otherwise you will wait hours at every compilation). Impls idioms in C++ help you for example. And then there is a lot more. For this reason software developers are well paid and there are so many jobs :-)</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | Outline
=======
OK, I have Google'd this and already expecting a big fat **NO!!** But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^\_^
I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be.
**NOTE:** This is a standard User Control (.ascx), *NOT* a custom rendered control.
Current Code
------------
Here is the class & event definition:
```
[System.ComponentModel.DefaultEvent("OKClicked")]
public partial class AddressBox : System.Web.UI.UserControl
{
public event EventHandler OKClicked;
```
Current Result
--------------
Now, when I double click the the control when it is on a ASPX page, the following is created:
```
protected void AddressBox1_Load(object sender, EventArgs e)
{
}
```
Not quite what I was expecting! So, my question:
Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason?
--------------------------------------------------------------------------------------------------------------------
---
**Side Note**: How do we put underscores in code? I cant seem to put and escape char in? | I think to be honest you a better just boning up on your standard design patterns and applying them to the individual problems that you face in developing your UI.
While there are common UI "themes" (such as dealing with modifier keys) the actual implementation may vary widely.
I have O'Reilly's [Head First Design Patterns](http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns%2Fdp%2F0596007124%2Fref%3Dpd_bbs_sr_1%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-1&tag=robcthegeek-21&linkCode=ur2&camp=1634&creative=6738) and [The Poster](http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns-Poster%2Fdp%2F0596102143%2Fref%3Dpd_bbs_sr_3%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-3&tag=robcthegeek-21&linkCode=ur2&camp=1634&creative=6738), which I have found invaluable!
### Shameless Plug : These links are using my associates ID. |
11,279 | <p>I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the <strong>Publish</strong> properties of the project, I have it set to <em>Automatically increment revision with each publish</em>.</p>
<p>The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from <em>My.Application.Info.Version</em>.</p>
<p>What should I be using instead so that my automatically incrementing revision number shows up in the about box?</p>
| [
{
"answer_id": 11284,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*?\nThis should increase the revision number (at least it does in the AssemblyInfo.cs in C#).</p>\n"
},
{
"answer_id": 11286,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 0,
"selected": false,
"text": "<p>The option you select is only to update the setup number. To update the program number you have to modify the AssemblyInfo. </p>\n\n<p>C#\n[assembly: AssemblyVersion(\"X.Y.<em>\")]\n[assembly: AssemblyFileVersion(\"X.Y.</em>\")]</p>\n\n<p>VB.NET\nAssembly: AssemblyVersion(\"X.Y.*\")</p>\n"
},
{
"answer_id": 11297,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": true,
"text": "<p>Change the code for the About box to </p>\n\n<pre><code>Me.LabelVersion.Text = String.Format(\"Version {0}\", My.Application.Deployment.CurrentVersion.ToString)\n</code></pre>\n\n<p>Please note that all the other answers are correct for \"how do I get my assembly version\", not the stated question \"how do I show my publish version\".</p>\n"
},
{
"answer_id": 11304,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 1,
"selected": false,
"text": "<p>It took me a second to find this, but I believe this is what you are looking for:</p>\n\n<pre><code>using System;\nusing System.Reflection;\npublic class VersionNumber\n{\n public static void Main()\n {\n System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\n Version version = assembly.GetName().Version;\n Console.WriteLine (\"Version: {0}\", version);\n Console.WriteLine (\"Major: {0}\", version.Major);\n Console.WriteLine (\"Minor: {0}\", version.Minor);\n Console.WriteLine (\"Build: {0}\", version.Build);\n Console.WriteLine (\"Revision: {0}\", version.Revision);\n Console.Read();\n }\n}\n</code></pre>\n\n<p>It was based upon the code provided at the following site - <a href=\"http://en.csharp-online.net/Display_type_version_number\" rel=\"nofollow noreferrer\">http://en.csharp-online.net/Display_type_version_number</a></p>\n"
},
{
"answer_id": 11334,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "<p>It's a maximum of 65535 for each of the 4 values, but when using 1.0.* or 1.0.*.*, the Assembly Linker will use a coded timestamp (so it's not a simple auto-increment, and it can repeat!) that will fit 65535.</p>\n\n<p>See my answer to <a href=\"https://stackoverflow.com/questions/650/automatically-update-version-number#655\">this question</a> for more links and details.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the **Publish** properties of the project, I have it set to *Automatically increment revision with each publish*.
The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from *My.Application.Info.Version*.
What should I be using instead so that my automatically incrementing revision number shows up in the about box? | Change the code for the About box to
```
Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString)
```
Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version". |
11,288 | <p>So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. </p>
<p>There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).</p>
<p>One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. </p>
<pre><code>class MyCompositeObject
{
enum ObjectType;
DateTime CreatedDate;
string SomeAttribute;
myObjectType1 Obj1;
myObjectType2 Obj2;
{
class MyCompositeObjects : List<MyCompositeObject> { }
</code></pre>
<p>And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.</p>
<p>What suggestions are there for doing this in a more elegant way?</p>
| [
{
"answer_id": 11284,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*?\nThis should increase the revision number (at least it does in the AssemblyInfo.cs in C#).</p>\n"
},
{
"answer_id": 11286,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 0,
"selected": false,
"text": "<p>The option you select is only to update the setup number. To update the program number you have to modify the AssemblyInfo. </p>\n\n<p>C#\n[assembly: AssemblyVersion(\"X.Y.<em>\")]\n[assembly: AssemblyFileVersion(\"X.Y.</em>\")]</p>\n\n<p>VB.NET\nAssembly: AssemblyVersion(\"X.Y.*\")</p>\n"
},
{
"answer_id": 11297,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": true,
"text": "<p>Change the code for the About box to </p>\n\n<pre><code>Me.LabelVersion.Text = String.Format(\"Version {0}\", My.Application.Deployment.CurrentVersion.ToString)\n</code></pre>\n\n<p>Please note that all the other answers are correct for \"how do I get my assembly version\", not the stated question \"how do I show my publish version\".</p>\n"
},
{
"answer_id": 11304,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 1,
"selected": false,
"text": "<p>It took me a second to find this, but I believe this is what you are looking for:</p>\n\n<pre><code>using System;\nusing System.Reflection;\npublic class VersionNumber\n{\n public static void Main()\n {\n System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\n Version version = assembly.GetName().Version;\n Console.WriteLine (\"Version: {0}\", version);\n Console.WriteLine (\"Major: {0}\", version.Major);\n Console.WriteLine (\"Minor: {0}\", version.Minor);\n Console.WriteLine (\"Build: {0}\", version.Build);\n Console.WriteLine (\"Revision: {0}\", version.Revision);\n Console.Read();\n }\n}\n</code></pre>\n\n<p>It was based upon the code provided at the following site - <a href=\"http://en.csharp-online.net/Display_type_version_number\" rel=\"nofollow noreferrer\">http://en.csharp-online.net/Display_type_version_number</a></p>\n"
},
{
"answer_id": 11334,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "<p>It's a maximum of 65535 for each of the 4 values, but when using 1.0.* or 1.0.*.*, the Assembly Linker will use a coded timestamp (so it's not a simple auto-increment, and it can repeat!) that will fit 65535.</p>\n\n<p>See my answer to <a href=\"https://stackoverflow.com/questions/650/automatically-update-version-number#655\">this question</a> for more links and details.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1346/"
] | So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem.
There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).
One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type.
```
class MyCompositeObject
{
enum ObjectType;
DateTime CreatedDate;
string SomeAttribute;
myObjectType1 Obj1;
myObjectType2 Obj2;
{
class MyCompositeObjects : List<MyCompositeObject> { }
```
And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.
What suggestions are there for doing this in a more elegant way? | Change the code for the About box to
```
Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString)
```
Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version". |
11,291 | <p>I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? </p>
| [
{
"answer_id": 11312,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 5,
"selected": true,
"text": "<p>Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function.</p>\n\n<p>So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this:</p>\n\n<pre><code>- (void)keyUp:(NSEvent *)theEvent\n</code></pre>\n\n<p>Note that this is an inherited NSResponder method, not a NSTextView method.</p>\n"
},
{
"answer_id": 11999,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>It's important to tell us what you're really trying to accomplish — the higher-level goal that you think capturing key events in an NSTextView will address.</p>\n\n<p>For example, when someone asks me how to capture key events in an NSText<strong>Field</strong> what they really want to know is how to validate input in the field. That's done by setting the field's formatter to an instance of NSFormatter (whether one of the formatters included in Cocoa or a custom one), not by processing keystrokes directly.</p>\n\n<p>So given that example, what are you really trying to accomplish?</p>\n"
},
{
"answer_id": 12874,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>I've done some hard digging, and I did find an answer to my own question. I'll get at it below, but thanks to the two fellas who replied. I think that Stack Overflow is a fantastic site already--I hope more Mac developers find their way in once the beta is over--this could be a great resource for other developers looking to transition to the platform.</p>\n\n<p>So, I did, as suggested by Danny, find my answer in delegation. What I didn't understand from Danny's post was that there are a set of delegate-enabled methods in the delegating object, and that the delegate must implement said events. And so for a TextView, I was able to find the method textDidChange, which accomplished what I wanted in an even better way than simply capturing key presses would have done. So if I implement this in my controller:</p>\n\n<pre><code>- (void)textDidChange:(NSNotification *)aNotification;\n</code></pre>\n\n<p>I can respond to the text being edited. There are, of course, other methods available, and I'm excited to play with them, because I know I'll learn a whole lot as I do. Thanks again, guys.</p>\n"
},
{
"answer_id": 13088,
"author": "alextgordon",
"author_id": 1165750,
"author_profile": "https://Stackoverflow.com/users/1165750",
"pm_score": 3,
"selected": false,
"text": "<p>Just a tip for syntax highlighting:</p>\n\n<p>Don't highlight the whole text view at once - it's <em>very</em> slow. Also don't highlight the last edited text using -editedRange - it's very slow too if the user pastes a large body of text into the text view.</p>\n\n<p>Instead you need to highlight the visible text which is done like this:</p>\n\n<pre><code>NSRect visibleRect = [[[textView enclosingScrollView] contentView] documentVisibleRect];\nNSRange visibleRange = [[textView layoutManager] glyphRangeForBoundingRect:visibleRect inTextContainer:[textView textContainer]];\n</code></pre>\n\n<p>Then you feed visibleRange to your highlighting code.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
] | I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? | Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function.
So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this:
```
- (void)keyUp:(NSEvent *)theEvent
```
Note that this is an inherited NSResponder method, not a NSTextView method. |
11,305 | <p>I work in VBA, and want to parse a string eg</p>
<pre><code><PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<X>24.365</X>
<Y>78.63</Y>
</PointN>
</code></pre>
<p>and get the X & Y values into two separate integer variables.</p>
<p>I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.</p>
<p>How do I do this?</p>
| [
{
"answer_id": 11325,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 7,
"selected": true,
"text": "<p>This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.</p>\n\n<p>You can find more on MSXML2.DOMDocument at the following sites:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/20161217090033/http://en.allexperts.com/q/XML-1469/Manipulating-XML-files-Excel.htm\" rel=\"noreferrer\">Manipulating XML files with Excel VBA & Xpath</a></li>\n<li>MSXML - <a href=\"http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx</a></li>\n<li><a href=\"https://web.archive.org/web/20161030020427/http://www.xml.com:80/lpt/a/979\" rel=\"noreferrer\">An Overview of MSXML 4.0</a></li>\n</ul>\n"
},
{
"answer_id": 11406,
"author": "Devdatta Tengshe",
"author_id": 895,
"author_profile": "https://Stackoverflow.com/users/895",
"pm_score": 6,
"selected": false,
"text": "<p>Thanks for the pointers.</p>\n<p>I don't know, whether this is the best approach to the problem or not, but here is how I got it to work.\nI referenced the Microsoft XML, v2.6 dll in my VBA, and then the following code snippet, gives me the required values</p>\n \n<pre class=\"lang-vb prettyprint-override\"><code>Dim objXML As MSXML2.DOMDocument\n\nSet objXML = New MSXML2.DOMDocument\n\nIf Not objXML.loadXML(strXML) Then 'strXML is the string with XML'\n Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason\nEnd If\n \nDim point As IXMLDOMNode\nSet point = objXML.firstChild\n\nDebug.Print point.selectSingleNode("X").Text\nDebug.Print point.selectSingleNode("Y").Text\n</code></pre>\n"
},
{
"answer_id": 2796385,
"author": "DK.",
"author_id": 336474,
"author_profile": "https://Stackoverflow.com/users/336474",
"pm_score": 3,
"selected": false,
"text": "<p>This is an example OPML parser working with FeedDemon opml files:</p>\n\n \n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub debugPrintOPML()\n\n' http://msdn.microsoft.com/en-us/library/ms763720(v=VS.85).aspx\n' http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx\n' http://msdn.microsoft.com/en-us/library/ms256086(v=VS.85).aspx ' expressions\n' References: Microsoft XML\n\nDim xmldoc As New DOMDocument60\nDim oNodeList As IXMLDOMSelection\nDim oNodeList2 As IXMLDOMSelection\nDim curNode As IXMLDOMNode\nDim n As Long, n2 As Long, x As Long\n\nDim strXPathQuery As String\nDim attrLength As Byte\nDim FilePath As String\n\nFilePath = \"rss.opml\"\n\nxmldoc.Load CurrentProject.Path & \"\\\" & FilePath\n\nstrXPathQuery = \"opml/body/outline\"\nSet oNodeList = xmldoc.selectNodes(strXPathQuery)\n\nFor n = 0 To (oNodeList.length - 1)\n Set curNode = oNodeList.Item(n)\n attrLength = curNode.Attributes.length\n If attrLength > 1 Then ' or 2 or 3\n Call processNode(curNode)\n Else\n Call processNode(curNode)\n strXPathQuery = \"opml/body/outline[position() = \" & n + 1 & \"]/outline\"\n Set oNodeList2 = xmldoc.selectNodes(strXPathQuery)\n For n2 = 0 To (oNodeList2.length - 1)\n Set curNode = oNodeList2.Item(n2)\n Call processNode(curNode)\n Next\n End If\n Debug.Print \"----------------------\"\nNext\n\nSet xmldoc = Nothing\n\nEnd Sub\n\nSub processNode(curNode As IXMLDOMNode)\n\nDim sAttrName As String\nDim sAttrValue As String\nDim attrLength As Byte\nDim x As Long\n\nattrLength = curNode.Attributes.length\n\nFor x = 0 To (attrLength - 1)\n sAttrName = curNode.Attributes.Item(x).nodeName\n sAttrValue = curNode.Attributes.Item(x).nodeValue\n Debug.Print sAttrName & \" = \" & sAttrValue\nNext\n Debug.Print \"-----------\"\n\nEnd Sub\n</code></pre>\n\n<p>This one takes multilevel trees of folders (Awasu, NewzCrawler):</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>...\nCall xmldocOpen4\nCall debugPrintOPML4(Null)\n...\n\nDim sText4 As String\n\nSub debugPrintOPML4(strXPathQuery As Variant)\n\nDim xmldoc4 As New DOMDocument60\n'Dim xmldoc4 As New MSXML2.DOMDocument60 ' ?\nDim oNodeList As IXMLDOMSelection\nDim curNode As IXMLDOMNode\nDim n4 As Long\n\nIf IsNull(strXPathQuery) Then strXPathQuery = \"opml/body/outline\"\n\n' http://msdn.microsoft.com/en-us/library/ms754585(v=VS.85).aspx\nxmldoc4.async = False\nxmldoc4.loadXML sText4\nIf (xmldoc4.parseError.errorCode <> 0) Then\n Dim myErr\n Set myErr = xmldoc4.parseError\n MsgBox (\"You have error \" & myErr.reason)\nElse\n' MsgBox xmldoc4.xml\nEnd If\n\nSet oNodeList = xmldoc4.selectNodes(strXPathQuery)\n\nFor n4 = 0 To (oNodeList.length - 1)\n Set curNode = oNodeList.Item(n4)\n Call processNode4(strXPathQuery, curNode, n4)\nNext\n\nSet xmldoc4 = Nothing\n\nEnd Sub\n\nSub processNode4(strXPathQuery As Variant, curNode As IXMLDOMNode, n4 As Long)\n\nDim sAttrName As String\nDim sAttrValue As String\nDim x As Long\n\nFor x = 0 To (curNode.Attributes.length - 1)\n sAttrName = curNode.Attributes.Item(x).nodeName\n sAttrValue = curNode.Attributes.Item(x).nodeValue\n 'If sAttrName = \"text\"\n Debug.Print strXPathQuery & \" :: \" & sAttrName & \" = \" & sAttrValue\n 'End If\nNext\n Debug.Print \"\"\n\nIf curNode.childNodes.length > 0 Then\n Call debugPrintOPML4(strXPathQuery & \"[position() = \" & n4 + 1 & \"]/\" & curNode.nodeName)\nEnd If\n\nEnd Sub\n\nSub xmldocOpen4()\n\nDim oFSO As New FileSystemObject ' Microsoft Scripting Runtime Reference\nDim oFS\nDim FilePath As String\n\nFilePath = \"rss_awasu.opml\"\nSet oFS = oFSO.OpenTextFile(CurrentProject.Path & \"\\\" & FilePath)\nsText4 = oFS.ReadAll\noFS.Close\n\nEnd Sub\n</code></pre>\n\n<p>or better:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub xmldocOpen4()\n\nDim FilePath As String\n\nFilePath = \"rss.opml\"\n\n' function ConvertUTF8File(sUTF8File):\n' http://www.vbmonster.com/Uwe/Forum.aspx/vb/24947/How-to-read-UTF-8-chars-using-VBA\n' loading and conversion from Utf-8 to UTF\nsText8 = ConvertUTF8File(CurrentProject.Path & \"\\\" & FilePath)\n\nEnd Sub\n</code></pre>\n\n<p>but I don't understand, why xmldoc4 should be loaded each time.</p>\n"
},
{
"answer_id": 5747032,
"author": "Tommie C.",
"author_id": 608991,
"author_profile": "https://Stackoverflow.com/users/608991",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Update</strong></p>\n<p>The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a <a href=\"https://msdn.microsoft.com/en-us/library/Aa468547.aspx\" rel=\"nofollow noreferrer\">beginners guide of the XML DOM</a>.</p>\n \n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub LoadDocument()\n Dim xDoc As MSXML.DOMDocument\n Set xDoc = New MSXML.DOMDocument\n xDoc.validateOnParse = False\n If xDoc.Load("C:\\My Documents\\sample.xml") Then\n ' The document loaded successfully.\n ' Now do something intersting.\n DisplayNode xDoc.childNodes, 0\n Else\n ' The document failed to load.\n ' See the previous listing for error information.\n End If\nEnd Sub\n\nPublic Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _\n ByVal Indent As Integer)\n\n Dim xNode As MSXML.IXMLDOMNode\n Indent = Indent + 2\n\n For Each xNode In Nodes\n If xNode.nodeType = NODE_TEXT Then\n Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _\n ":" & xNode.nodeValue\n End If\n\n If xNode.hasChildNodes Then\n DisplayNode xNode.childNodes, Indent\n End If\n Next xNode\nEnd Sub\n</code></pre>\n<blockquote>\n<p><strong>Nota Bene</strong> - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) .\nNaturally using the XML facilities built into the VBA XML Dom would be\nmuch better. See the updates above.</p>\n</blockquote>\n<p><strong>Original Response</strong></p>\n<p>I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.</p>\n<p>This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.</p>\n<p><img src=\"https://i.stack.imgur.com/taSSE.png\" alt=\"sample function\" /></p>\n<pre class=\"lang-vb prettyprint-override\"><code>\nopenTag = \"\"\ncloseTag = \"\" \n<br>' Locate the position of the enclosing tags\nstartPos = InStr(1, temp, openTag)\nendPos = InStr(1, temp, closeTag)\nstartTagPos = InStr(startPos, temp, \">\") + 1\n' Parse xml for returned value\nData = Mid(temp, startTagPos, endPos - startTagPos)\n</pre></code>\n"
},
{
"answer_id": 27704551,
"author": "mvanle",
"author_id": 1213722,
"author_profile": "https://Stackoverflow.com/users/1213722",
"pm_score": 4,
"selected": false,
"text": "<p>You can use a XPath Query: </p>\n\n \n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim objDom As Object '// DOMDocument\nDim xmlStr As String, _\n xPath As String\n\nxmlStr = _\n \"<PointN xsi:type='typens:PointN' \" & _\n \"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \" & _\n \"xmlns:xs='http://www.w3.org/2001/XMLSchema'> \" & _\n \" <X>24.365</X> \" & _\n \" <Y>78.63</Y> \" & _\n \"</PointN>\"\n\nSet objDom = CreateObject(\"Msxml2.DOMDocument.3.0\") '// Using MSXML 3.0\n\n'/* Load XML */\nobjDom.LoadXML xmlStr\n\n'/*\n' * XPath Query\n' */ \n\n'/* Get X */\nxPath = \"/PointN/X\"\nDebug.Print objDom.SelectSingleNode(xPath).text\n\n'/* Get Y */\nxPath = \"/PointN/Y\"\nDebug.Print objDom.SelectSingleNode(xPath).text\n</code></pre>\n"
},
{
"answer_id": 27908457,
"author": "Bob Wheatley",
"author_id": 4446538,
"author_profile": "https://Stackoverflow.com/users/4446538",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a short sub to parse a MicroStation Triforma XML file that contains data for structural steel shapes.</p>\n\n \n\n<pre class=\"lang-vb prettyprint-override\"><code>'location of triforma structural files\n'c:\\programdata\\bentley\\workspace\\triforma\\tf_imperial\\data\\us.xml\n\nSub ReadTriformaImperialData()\nDim txtFileName As String\nDim txtFileLine As String\nDim txtFileNumber As Long\n\nDim Shape As String\nShape = \"w12x40\"\n\ntxtFileNumber = FreeFile\ntxtFileName = \"c:\\programdata\\bentley\\workspace\\triforma\\tf_imperial\\data\\us.xml\"\n\nOpen txtFileName For Input As #txtFileNumber\n\nDo While Not EOF(txtFileNumber)\nLine Input #txtFileNumber, txtFileLine\n If InStr(1, UCase(txtFileLine), UCase(Shape)) Then\n P1 = InStr(1, UCase(txtFileLine), \"D=\")\n D = Val(Mid(txtFileLine, P1 + 3))\n\n P2 = InStr(1, UCase(txtFileLine), \"TW=\")\n TW = Val(Mid(txtFileLine, P2 + 4))\n\n P3 = InStr(1, UCase(txtFileLine), \"WIDTH=\")\n W = Val(Mid(txtFileLine, P3 + 7))\n\n P4 = InStr(1, UCase(txtFileLine), \"TF=\")\n TF = Val(Mid(txtFileLine, P4 + 4))\n\n Close txtFileNumber\n Exit Do\n End If\nLoop\nEnd Sub\n</code></pre>\n\n<p>From here you can use the values to draw the shape in MicroStation 2d or do it in 3d and extrude it to a solid.</p>\n"
},
{
"answer_id": 33103998,
"author": "No Name",
"author_id": 1188613,
"author_profile": "https://Stackoverflow.com/users/1188613",
"pm_score": 4,
"selected": false,
"text": "<p>Add reference Project->References Microsoft XML, 6.0 and you can use example code:</p>\n\n \n\n<pre class=\"lang-vb prettyprint-override\"><code> Dim xml As String\n\n xml = \"<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> \"\n Dim oXml As MSXML2.DOMDocument60\n Set oXml = New MSXML2.DOMDocument60\n oXml.loadXML xml\n Dim oSeqNodes, oSeqNode As IXMLDOMNode\n\n Set oSeqNodes = oXml.selectNodes(\"//root/person\")\n If oSeqNodes.length = 0 Then\n 'show some message\n Else\n For Each oSeqNode In oSeqNodes\n Debug.Print oSeqNode.selectSingleNode(\"name\").Text\n Next\n End If \n</code></pre>\n\n<p>be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode(\"Name\").text is not same with selectSingleNode(\"name\").text</p>\n"
},
{
"answer_id": 40899195,
"author": "TJ Wilkinson",
"author_id": 6813795,
"author_profile": "https://Stackoverflow.com/users/6813795",
"pm_score": 0,
"selected": false,
"text": "<p>Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.</p>\n\n<pre><code>Cell A1: {your XML here}\nCell B1: <X>\nCell C1: </X>\nCell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,\"\")\nCell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,\"\")\n</code></pre>\n\n<p>And the result line E1 will have your parsed value:</p>\n\n<pre><code>Cell A1: {your XML here}\nCell B1: <X>\nCell C1: </X>\nCell D1: 24.365<X><Y>78.68</Y></PointN>\nCell E1: 24.365\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/895/"
] | I work in VBA, and want to parse a string eg
```
<PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<X>24.365</X>
<Y>78.63</Y>
</PointN>
```
and get the X & Y values into two separate integer variables.
I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.
How do I do this? | This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.
You can find more on MSXML2.DOMDocument at the following sites:
* [Manipulating XML files with Excel VBA & Xpath](https://web.archive.org/web/20161217090033/http://en.allexperts.com/q/XML-1469/Manipulating-XML-files-Excel.htm)
* MSXML - <http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx>
* [An Overview of MSXML 4.0](https://web.archive.org/web/20161030020427/http://www.xml.com:80/lpt/a/979) |
11,311 | <p>Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.</p>
<p>For example:</p>
<pre><code>Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text."
</code></pre>
<p>Which would produce the text in the label as:</p>
<blockquote>
<p>This is <strong>bold</strong> text. This is
<em>italicized</em> text.</p>
</blockquote>
| [
{
"answer_id": 11320,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 1,
"selected": false,
"text": "<p>I Would also be interested in finding out if it is possible.</p>\n\n<p>When we couldn't find a solution we resorted to Component Ones 'SuperLabel' control which allows HTML markup in a label.</p>\n"
},
{
"answer_id": 11323,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 5,
"selected": true,
"text": "<p>That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options:</p>\n\n<ol>\n<li>Use separate labels</li>\n<li>Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text</li>\n<li>Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2.</li>\n</ol>\n"
},
{
"answer_id": 11342,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 4,
"selected": false,
"text": "<p>Not really, but you could fake it with a read-only RichTextBox without borders. RichTextBox supports Rich Text Format (rtf).</p>\n"
},
{
"answer_id": 1602169,
"author": "Phil",
"author_id": 193962,
"author_profile": "https://Stackoverflow.com/users/193962",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>Create the text as a RTF file in wordpad</li>\n<li>Create Rich text control with no borders and editable = false</li>\n<li>Add the RTF file to the project as a resource</li>\n<li><p>In the Form1_load do</p>\n\n<p>myRtfControl.Rtf = Resource1.MyRtfControlText</p></li>\n</ol>\n"
},
{
"answer_id": 8677531,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 2,
"selected": false,
"text": "<p>There is an excellent article from 2009 on Code Project named \"<a href=\"http://www.codeproject.com/KB/GDI-plus/HtmlRenderer.aspx\" rel=\"nofollow\">A Professional HTML Renderer You Will Use</a>\" which implements something similar to what the original poster wants.</p>\n\n<p>I use it successfully within several projects of us.</p>\n"
},
{
"answer_id": 22073163,
"author": "pKami",
"author_id": 2588964,
"author_profile": "https://Stackoverflow.com/users/2588964",
"pm_score": 1,
"selected": false,
"text": "<p>Realising this is an old question, my answer is more for those, like me, who still may be looking for such solutions and stumble upon this question.</p>\n\n<p>Apart from what was already mentioned, DevExpress's <a href=\"https://documentation.devexpress.com/#windowsforms/clsDevExpressXtraEditorsLabelControltopic\" rel=\"nofollow\">LabelControl</a> is a label that supports this behaviour - <a href=\"https://documentation.devexpress.com/#windowsforms/CustomDocument9536\" rel=\"nofollow\">demo here</a>. Alas, it is part of a paid library.</p>\n\n<p>If you're looking for free solutions, I believe <a href=\"http://htmlrenderer.codeplex.com/\" rel=\"nofollow\">HTML Renderer</a> is the next best thing.</p>\n"
},
{
"answer_id": 23114093,
"author": "user3541933",
"author_id": 3541933,
"author_profile": "https://Stackoverflow.com/users/3541933",
"pm_score": 2,
"selected": false,
"text": "<p>Very simple solution:</p>\n\n<ol>\n<li>Add 2 labels on the form, LabelA and LabelB</li>\n<li>Go to properties for LabelA and dock it to left.</li>\n<li>Go to properties for LabelB and dock it to left as well. </li>\n<li>Set Font to bold for LabelA . </li>\n</ol>\n\n<p>Now the LabelB will shift depending on length of text of LabelA.</p>\n\n<p>That's all.</p>\n"
},
{
"answer_id": 24207716,
"author": "Geoff",
"author_id": 55487,
"author_profile": "https://Stackoverflow.com/users/55487",
"pm_score": 4,
"selected": false,
"text": "<p>Another workaround, late to the party: if you don't want to use a third party control, and you're just looking to call attention to some of the text in your label, <em>and</em> you're ok with underlines, you can use a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.linklabel(v=vs.110).aspx\" rel=\"noreferrer\">LinkLabel</a>. </p>\n\n<p>Note that many consider this a '<a href=\"https://ux.stackexchange.com/a/18088\">usability crime</a>', but if you're not designing something for end user consumption then it may be something you're prepared to have on your conscience.</p>\n\n<p>The trick is to add disabled links to the parts of your text that you want underlined, and then globally set the link colors to match the rest of the label. You can set almost all the necessary properties at design-time apart from the <code>Links.Add()</code> piece, but here they are in code:</p>\n\n<pre><code>linkLabel1.Text = \"You are accessing a government system, and all activity \" +\n \"will be logged. If you do not wish to continue, log out now.\";\nlinkLabel1.AutoSize = false;\nlinkLabel1.Size = new Size(365, 50);\nlinkLabel1.TextAlign = ContentAlignment.MiddleCenter;\nlinkLabel1.Links.Clear();\nlinkLabel1.Links.Add(20, 17).Enabled = false; // \"government system\"\nlinkLabel1.Links.Add(105, 11).Enabled = false; // \"log out now\"\nlinkLabel1.LinkColor = linkLabel1.ForeColor;\nlinkLabel1.DisabledLinkColor = linkLabel1.ForeColor;\n</code></pre>\n\n<p>Result:</p>\n\n<p><img src=\"https://i.stack.imgur.com/7gLgn.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 25527349,
"author": "jakebic",
"author_id": 3293976,
"author_profile": "https://Stackoverflow.com/users/3293976",
"pm_score": 1,
"selected": false,
"text": "<p>A FlowLayoutPanel works well for your problem. If you add labels to the flow panel and format each label's font and margin properties, then you can have different font styles. Pretty quick and easy solution to get working.</p>\n"
},
{
"answer_id": 28728824,
"author": "Nigrimmist",
"author_id": 1151741,
"author_profile": "https://Stackoverflow.com/users/1151741",
"pm_score": 4,
"selected": false,
"text": "<p>Worked solution for me - using custom RichEditBox. With right properties it will be looked as simple label with bold support.</p>\n<p><strong>1)</strong> First, add your custom RichTextLabel class with disabled caret :</p>\n<pre><code>public class RichTextLabel : RichTextBox\n{\n public RichTextLabel()\n {\n base.ReadOnly = true;\n base.BorderStyle = BorderStyle.None;\n base.TabStop = false;\n base.SetStyle(ControlStyles.Selectable, false);\n base.SetStyle(ControlStyles.UserMouse, true);\n base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);\n\n base.MouseEnter += delegate(object sender, EventArgs e)\n {\n this.Cursor = Cursors.Default;\n };\n }\n\n protected override void WndProc(ref Message m)\n {\n if (m.Msg == 0x204) return; // WM_RBUTTONDOWN\n if (m.Msg == 0x205) return; // WM_RBUTTONUP\n base.WndProc(ref m);\n }\n}\n</code></pre>\n<p><strong>2)</strong> Split you sentence to words with IsSelected flag, that determine if that word should be bold or no :</p>\n<pre><code> private void AutocompleteItemControl_Load(object sender, EventArgs e)\n {\n RichTextLabel rtl = new RichTextLabel();\n rtl.Font = new Font("MS Reference Sans Serif", 15.57F);\n StringBuilder sb = new StringBuilder();\n sb.Append(@"{\\rtf1\\ansi ");\n foreach (var wordPart in wordParts)\n {\n if (wordPart.IsSelected)\n {\n sb.Append(@"\\b ");\n }\n sb.Append(ConvertString2RTF(wordPart.WordPart));\n if (wordPart.IsSelected)\n {\n sb.Append(@"\\b0 ");\n }\n }\n sb.Append(@"}");\n\n rtl.Rtf = sb.ToString();\n rtl.Width = this.Width;\n this.Controls.Add(rtl);\n }\n</code></pre>\n<p><strong>3)</strong> Add function for convert you text to valid rtf (with unicode support!) :</p>\n<pre><code> private string ConvertString2RTF(string input)\n {\n //first take care of special RTF chars\n StringBuilder backslashed = new StringBuilder(input);\n backslashed.Replace(@"\\", @"\\\\");\n backslashed.Replace(@"{", @"\\{");\n backslashed.Replace(@"}", @"\\}");\n\n //then convert the string char by char\n StringBuilder sb = new StringBuilder();\n foreach (char character in backslashed.ToString())\n {\n if (character <= 0x7f)\n sb.Append(character);\n else\n sb.Append("\\\\u" + Convert.ToUInt32(character) + "?");\n }\n return sb.ToString();\n }\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/4rwhv.png\" alt=\"Sample\" /></p>\n<p>Works like a charm for me!\nSolutions compiled from :</p>\n<p><a href=\"https://stackoverflow.com/questions/4795709/how-to-convert-a-string-to-rtf-in-c\">How to convert a string to RTF in C#?</a></p>\n<p><a href=\"https://stackoverflow.com/questions/4077582/format-text-in-rich-text-box\">Format text in Rich Text Box</a></p>\n<p><a href=\"https://stackoverflow.com/questions/582312/how-to-hide-the-caret-in-a-richtextbox\">How to hide the caret in a RichTextBox?</a></p>\n"
},
{
"answer_id": 29395208,
"author": "Marinpietri",
"author_id": 3124522,
"author_profile": "https://Stackoverflow.com/users/3124522",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah.\nYou can implements, using HTML Render.\nFor you see, click on the link: <a href=\"https://htmlrenderer.codeplex.com/\" rel=\"nofollow\">https://htmlrenderer.codeplex.com/</a>\nI hope this is useful.</p>\n"
},
{
"answer_id": 33211471,
"author": "Martin Braun",
"author_id": 1540350,
"author_profile": "https://Stackoverflow.com/users/1540350",
"pm_score": 2,
"selected": false,
"text": "<h1>AutoRichLabel</h1>\n\n<p> <a href=\"https://i.stack.imgur.com/cETHe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cETHe.png\" alt=\"AutoRichLabel with formatted RTF content\"></a></p>\n\n<p>I was solving this problem by building an <code>UserControl</code> that contains a <code>TransparentRichTextBox</code> that is readonly. The <code>TransparentRichTextBox</code> is a <code>RichTextBox</code> that allows to be transparent:</p>\n\n<p>TransparentRichTextBox.cs: </p>\n\n<pre><code>public class TransparentRichTextBox : RichTextBox\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n static extern IntPtr LoadLibrary(string lpFileName);\n\n protected override CreateParams CreateParams\n {\n get\n {\n CreateParams prams = base.CreateParams;\n if (TransparentRichTextBox.LoadLibrary(\"msftedit.dll\") != IntPtr.Zero)\n {\n prams.ExStyle |= 0x020; // transparent \n prams.ClassName = \"RICHEDIT50W\";\n }\n return prams;\n }\n }\n}\n</code></pre>\n\n<p>The final <code>UserControl</code> acts as wrapper of the <code>TransparentRichTextBox</code>. Unfortunately, I had to limit it to <code>AutoSize</code> on my own way, because the <code>AutoSize</code> of the <code>RichTextBox</code> became broken.</p>\n\n<p>AutoRichLabel.designer.cs: </p>\n\n<pre><code>partial class AutoRichLabel\n{\n /// <summary> \n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary> \n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Component Designer generated code\n\n /// <summary> \n /// Required method for Designer support - do not modify \n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.rtb = new TransparentRichTextBox();\n this.SuspendLayout();\n // \n // rtb\n // \n this.rtb.BorderStyle = System.Windows.Forms.BorderStyle.None;\n this.rtb.Dock = System.Windows.Forms.DockStyle.Fill;\n this.rtb.Location = new System.Drawing.Point(0, 0);\n this.rtb.Margin = new System.Windows.Forms.Padding(0);\n this.rtb.Name = \"rtb\";\n this.rtb.ReadOnly = true;\n this.rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;\n this.rtb.Size = new System.Drawing.Size(46, 30);\n this.rtb.TabIndex = 0;\n this.rtb.Text = \"\";\n this.rtb.WordWrap = false;\n this.rtb.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.rtb_ContentsResized);\n // \n // AutoRichLabel\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;\n this.BackColor = System.Drawing.Color.Transparent;\n this.Controls.Add(this.rtb);\n this.Name = \"AutoRichLabel\";\n this.Size = new System.Drawing.Size(46, 30);\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private TransparentRichTextBox rtb;\n}\n</code></pre>\n\n<p>AutoRichLabel.cs: </p>\n\n<pre><code>/// <summary>\n/// <para>An auto sized label with the ability to display text with formattings by using the Rich Text Format.</para>\n/// <para></para>\n/// <para>Short RTF syntax examples: </para>\n/// <para></para>\n/// <para>Paragraph: </para>\n/// <para>{\\pard This is a paragraph!\\par}</para>\n/// <para></para>\n/// <para>Bold / Italic / Underline: </para>\n/// <para>\\b bold text\\b0</para>\n/// <para>\\i italic text\\i0</para>\n/// <para>\\ul underline text\\ul0</para>\n/// <para></para>\n/// <para>Alternate color using color table: </para>\n/// <para>{\\colortbl ;\\red0\\green77\\blue187;}{\\pard The word \\cf1 fish\\cf0 is blue.\\par</para>\n/// <para></para>\n/// <para>Additional information: </para>\n/// <para>Always wrap every text in a paragraph. </para>\n/// <para>Different tags can be stacked (i.e. \\pard\\b\\i Bold and Italic\\i0\\b0\\par)</para>\n/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \\pard The word \\bBOLD\\0 is bold.\\par)</para>\n/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>\n/// </summary>\npublic partial class AutoRichLabel : UserControl\n{\n /// <summary>\n /// The rich text content. \n /// <para></para>\n /// <para>Short RTF syntax examples: </para>\n /// <para></para>\n /// <para>Paragraph: </para>\n /// <para>{\\pard This is a paragraph!\\par}</para>\n /// <para></para>\n /// <para>Bold / Italic / Underline: </para>\n /// <para>\\b bold text\\b0</para>\n /// <para>\\i italic text\\i0</para>\n /// <para>\\ul underline text\\ul0</para>\n /// <para></para>\n /// <para>Alternate color using color table: </para>\n /// <para>{\\colortbl ;\\red0\\green77\\blue187;}{\\pard The word \\cf1 fish\\cf0 is blue.\\par</para>\n /// <para></para>\n /// <para>Additional information: </para>\n /// <para>Always wrap every text in a paragraph. </para>\n /// <para>Different tags can be stacked (i.e. \\pard\\b\\i Bold and Italic\\i0\\b0\\par)</para>\n /// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \\pard The word \\bBOLD\\0 is bold.\\par)</para>\n /// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>\n /// </summary>\n [Browsable(true)]\n public string RtfContent\n {\n get\n {\n return this.rtb.Rtf;\n }\n set\n {\n this.rtb.WordWrap = false; // to prevent any display bugs, word wrap must be off while changing the rich text content. \n this.rtb.Rtf = value.StartsWith(@\"{\\rtf1\") ? value : @\"{\\rtf1\" + value + \"}\"; // Setting the rich text content will trigger the ContentsResized event. \n this.Fit(); // Override width and height. \n this.rtb.WordWrap = this.WordWrap; // Set the word wrap back. \n }\n }\n\n /// <summary>\n /// Dynamic width of the control. \n /// </summary>\n [Browsable(false)]\n public new int Width\n {\n get\n {\n return base.Width;\n } \n }\n\n /// <summary>\n /// Dynamic height of the control. \n /// </summary>\n [Browsable(false)]\n public new int Height\n {\n get\n {\n return base.Height;\n }\n }\n\n /// <summary>\n /// The measured width based on the content. \n /// </summary>\n public int DesiredWidth { get; private set; }\n\n /// <summary>\n /// The measured height based on the content. \n /// </summary>\n public int DesiredHeight { get; private set; }\n\n /// <summary>\n /// Determines the text will be word wrapped. This is true, when the maximum size has been set. \n /// </summary>\n public bool WordWrap { get; private set; }\n\n /// <summary>\n /// Constructor. \n /// </summary>\n public AutoRichLabel()\n {\n InitializeComponent();\n }\n\n /// <summary>\n /// Overrides the width and height with the measured width and height\n /// </summary>\n public void Fit()\n {\n base.Width = this.DesiredWidth;\n base.Height = this.DesiredHeight;\n }\n\n /// <summary>\n /// Will be called when the rich text content of the control changes. \n /// </summary>\n private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e)\n {\n this.AutoSize = false; // Disable auto size, else it will break everything\n this.WordWrap = this.MaximumSize.Width > 0; // Enable word wrap when the maximum width has been set. \n this.DesiredWidth = this.rtb.WordWrap ? this.MaximumSize.Width : e.NewRectangle.Width; // Measure width. \n this.DesiredHeight = this.MaximumSize.Height > 0 && this.MaximumSize.Height < e.NewRectangle.Height ? this.MaximumSize.Height : e.NewRectangle.Height; // Measure height. \n this.Fit(); // Override width and height. \n }\n}\n</code></pre>\n\n<p>The syntax of the rich text format is quite simple: </p>\n\n<p>Paragraph: </p>\n\n<pre><code>{\\pard This is a paragraph!\\par}\n</code></pre>\n\n<p>Bold / Italic / Underline text: </p>\n\n<pre><code>\\b bold text\\b0\n\\i italic text\\i0\n\\ul underline text\\ul0\n</code></pre>\n\n<p>Alternate color using color table: </p>\n\n<pre><code>{\\colortbl ;\\red0\\green77\\blue187;}\n{\\pard The word \\cf1 fish\\cf0 is blue.\\par\n</code></pre>\n\n<p>But please note: Always wrap every text in a paragraph. Also, different tags can be stacked (i.e. <code>\\pard\\b\\i Bold and Italic\\i0\\b0\\par</code>) and the space character behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. <code>\\pard The word \\bBOLD\\0 is bold.\\par</code>). To escape <code>\\</code> or <code>{</code> or <code>}</code>, please use a leading <code>\\</code>. \nFor more information there is a <a href=\"http://www.biblioscape.com/rtf15_spec.htm\" rel=\"nofollow noreferrer\">full specification of the rich text format online</a>. </p>\n\n<p>Using this quite simple syntax you can produce something like you can see in the first image. The rich text content that was attached to the <code>RtfContent</code> property of my <code>AutoRichLabel</code> in the first image was: </p>\n\n<pre><code>{\\colortbl ;\\red0\\green77\\blue187;}\n{\\pard\\b BOLD\\b0 \\i ITALIC\\i0 \\ul UNDERLINE\\ul0 \\\\\\{\\}\\par}\n{\\pard\\cf1\\b BOLD\\b0 \\i ITALIC\\i0 \\ul UNDERLINE\\ul0\\cf0 \\\\\\{\\}\\par}\n</code></pre>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/cETHe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cETHe.png\" alt=\"AutoRichLabel with formatted RTF content\"></a></p>\n</blockquote>\n\n<p>If you want to enable word wrap, please set the maximum width to a desired size. However, this will fix the width to the maximum width, even when the text is shorter. </p>\n\n<p>Have fun! </p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] | Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.
For example:
```
Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text."
```
Which would produce the text in the label as:
>
> This is **bold** text. This is
> *italicized* text.
>
>
> | That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options:
1. Use separate labels
2. Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text
3. Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2. |
11,318 | <p>Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation?</p>
<ul>
<li>Invalidate the Form as soon as you are done drawing?</li>
<li>Setup a second timer and invalidate the form on a regular interval?</li>
<li>Perhaps there is a common pattern for this thing?</li>
<li>Are there any useful .NET classes to help out?</li>
</ul>
<p>Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community?</p>
| [
{
"answer_id": 11329,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>What you're doing is the only solution I've ever used in WinForms (a timer with constant redrawings). There are a bunch of techniques that you can use to make the user's experience with it smoother (such as double-buffering).</p>\n\n<p>You might want to give WPF a try. There are built-in facilities for doing animations in WPF, and they're much smoother (and require less code and no synchronization on your part) than a timer-based solution.</p>\n\n<p>Note that you do not need to use WPF throughout your whole app for that solution; it's possible to pack this functionality into a WPF control and embed the control in a WinForms application (or an unmanaged app, for that matter):</p>\n\n<p><a href=\"http://www.codeproject.com/KB/WPF/WPF_UserControls.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/WPF/WPF_UserControls.aspx</a></p>\n"
},
{
"answer_id": 11404,
"author": "Peteter",
"author_id": 1192,
"author_profile": "https://Stackoverflow.com/users/1192",
"pm_score": 4,
"selected": true,
"text": "<p>In some situations, it's faster and more convenient to not draw using the paint event, but getting the Graphics object from the control/form and painting \"on\" that. This may give some troubles with opacity/anti aliasing/text etc, but could be worth the trouble in terms of not having to repaint the whole shabang. Something along the lines of:</p>\n\n<pre><code>private void AnimationTimer_Tick(object sender, EventArgs args)\n{\n // First paint background, like Clear(Control.Background), or by\n // painting an image you have previously buffered that was the background.\n animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++])); \n}\n</code></pre>\n\n<p>I use this in some Controls myself, and have buffered images to \"clear\" the background with, when the object of interest moves or need to be removed.</p>\n"
},
{
"answer_id": 1155969,
"author": "Richard Shepherd",
"author_id": 141066,
"author_profile": "https://Stackoverflow.com/users/141066",
"pm_score": 6,
"selected": false,
"text": "<p>I've created a library that might help with this. It's called Transitions, and can be found here: <a href=\"https://github.com/UweKeim/dot-net-transitions\" rel=\"nofollow noreferrer\">https://github.com/UweKeim/dot-net-transitions</a>. Available on nuget as the <a href=\"https://www.nuget.org/packages/dot-net-transitions/\" rel=\"nofollow noreferrer\">dot-net-transitions package</a></p>\n\n<p>It uses timers running on a background thread to animate the objects. The library is open-source, so if it is any use to you, you can look at the code to see what it's doing.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
] | Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation?
* Invalidate the Form as soon as you are done drawing?
* Setup a second timer and invalidate the form on a regular interval?
* Perhaps there is a common pattern for this thing?
* Are there any useful .NET classes to help out?
Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community? | In some situations, it's faster and more convenient to not draw using the paint event, but getting the Graphics object from the control/form and painting "on" that. This may give some troubles with opacity/anti aliasing/text etc, but could be worth the trouble in terms of not having to repaint the whole shabang. Something along the lines of:
```
private void AnimationTimer_Tick(object sender, EventArgs args)
{
// First paint background, like Clear(Control.Background), or by
// painting an image you have previously buffered that was the background.
animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++]));
}
```
I use this in some Controls myself, and have buffered images to "clear" the background with, when the object of interest moves or need to be removed. |
11,330 | <p>Let's say I'm creating a chess program. I have a function</p>
<pre><code>void foreachMove( void (*action)(chess_move*), chess_game* game);
</code></pre>
<p>which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:</p>
<pre><code>chess_move getNextMove(chess_game* game, int depth){
//for each valid move, determine how good the move is
foreachMove(moveHandler, game);
}
void moveHandler(chess_move* move){
//uh oh, now I need the variables "game" and "depth" from the above function
}
</code></pre>
<p>Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.</p>
<p>How can I pass extra parameters to a function that I'm calling through a pointer?</p>
| [
{
"answer_id": 11335,
"author": "Antonio Haley",
"author_id": 390,
"author_profile": "https://Stackoverflow.com/users/390",
"pm_score": 3,
"selected": false,
"text": "<p>You'd probably need to redefine the function pointer to take additional arguments.</p>\n\n<pre><code>void foreachMove( void (*action)(chess_move*, int), chess_game* game )\n</code></pre>\n"
},
{
"answer_id": 11363,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Ah, if only C supported closures...</p>\n\n<p>Antonio is right; if you need to pass extra parameters, you'll need to redefine your function pointer to accept the additional arguments. If you don't know exactly what parameters you'll need, then you have at least three choices:</p>\n\n<ol>\n<li>Have the last argument in your prototype be a void*. This gives you flexibility of passing in anything else that you need, but it definitely isn't type-safe.</li>\n<li>Use variadic parameters (...). Given my lack of experience with variadic parameters in C, I'm not sure if you can use this with a function pointer, but this gives even more flexibility than the first solution, albeit still with the lack of type safety.</li>\n<li>Upgrade to C++ and use <a href=\"http://en.wikipedia.org/wiki/Function_object\" rel=\"noreferrer\">function objects</a>.</li>\n</ol>\n"
},
{
"answer_id": 11379,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading this right, what I'd suggest is to make your function take a pointer to a struct as an argument. Then, your struct can have \"game\" and \"depth\" when it needs them, and just leave them set to 0 or Null when you don't need them. </p>\n\n<p>What is going on in that function? Do you have a conditional that says, </p>\n\n<pre><code>if (depth > -1) //some default\n {\n //do something\n }\n</code></pre>\n\n<p>Does the function always REQUIRE \"game\" and \"depth\"? Then, they should always be arguments, and that can go into your prototypes. </p>\n\n<p>Are you indicating that the function only sometimes requires \"game\" and \"depth\"? Well, maybe make two functions and use each one when you need to. </p>\n\n<p>But, having a structure as the argument is probably the easiest thing.</p>\n"
},
{
"answer_id": 11395,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 2,
"selected": false,
"text": "<p>If you're willing to use some C++, you can use a \"function object\":</p>\n\n<pre><code>struct MoveHandler {\n chess_game *game;\n int depth;\n\n MoveHandler(chess_game *g, int d): game(g), depth(d) {}\n\n void operator () (chess_move*) {\n // now you can use the game and the depth\n }\n};\n</code></pre>\n\n<p>and turn your <code>foreachMove</code> into a template:</p>\n\n<pre><code>template <typename T>\nvoid foreachMove(T action, chess_game* game);\n</code></pre>\n\n<p>and you can call it like this:</p>\n\n<pre><code>chess_move getNextMove(chess_game* game, int depth){\n //for each valid move, determine how good the move is\n foreachMove(MoveHandler(game, depth), game);\n}\n</code></pre>\n\n<p>but it won't disrupt your other uses of <code>MoveHandler</code>.</p>\n"
},
{
"answer_id": 11442,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest using an array of void*, with the last entry always void.\nsay you need 3 parameters you could do this:</p>\n\n<pre><code>void MoveHandler (void** DataArray)\n{\n // data1 is always chess_move\n chess_move data1 = DataArray[0]? (*(chess_move*)DataArray[0]) : NULL; \n // data2 is always float\n float data1 = DataArray[1]? (*(float*)DataArray[1]) : NULL; \n // data3 is always char\n char data1 = DataArray[2]? (*(char*)DataArray[2]) : NULL; \n //etc\n}\n\nvoid foreachMove( void (*action)(void**), chess_game* game);\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>chess_move getNextMove(chess_game* game, int depth){\n //for each valid move, determine how good the move is\n void* data[4];\n data[0] = &chess_move;\n float f1;\n char c1;\n data[1] = &f1;\n data[2] = &c1;\n data[3] = NULL;\n foreachMove(moveHandler, game);\n}\n</code></pre>\n\n<p>If all the parameters are the same type then you can avoid the void* array and just send a NULL-terminated array of whatever type you need.</p>\n"
},
{
"answer_id": 11475,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>+1 to Antonio. You need to change your function pointer declaration to accept additional parameters.</p>\n\n<p>Also, please don't start passing around void pointers or (especially) arrays of void pointers. That's just asking for trouble. If you start passing void pointers, you're going to also have to pass some kind of message to indicate what the pointer type is (or types are). This technique is <em>rarely</em> appropriate.</p>\n\n<p>If your parameters are always the same, just add them to your function pointer arguments (or possibly pack them into a struct and use that as the argument if there are a lot of parameters). If your parameters change, then consider using multiple function pointers for the multiple call scenarios instead of passing void pointers.</p>\n"
},
{
"answer_id": 11661,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>If your parameters change, I would change the function pointer declaration to use the \"...\" technique to set up a variable number of arguments. It could save you in readability and also having to make a change for each parameter you want to pass to the function. It is definately a lot safer than passing void around.</p>\n\n<p><a href=\"http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html\" rel=\"nofollow noreferrer\">http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html</a></p>\n\n<p>Just an FYI, about the example code in the link: some places they have “n args” and others it is “n_args” with the underscore. They should all have the underscore. I thought the syntax looked a little funny until I realized they had dropped the underscore in some places.</p>\n"
},
{
"answer_id": 73263,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 0,
"selected": false,
"text": "<p>Use a typedef for the function pointer. See my <a href=\"https://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c#9421\">answer</a> for <a href=\"https://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c\">this question</a></p>\n"
},
{
"answer_id": 15871673,
"author": "luser droog",
"author_id": 733077,
"author_profile": "https://Stackoverflow.com/users/733077",
"pm_score": 0,
"selected": false,
"text": "<p>Another option would be to modify the <code>chess_move</code> structure instead of the function prototype. The structure is presumably defined in only one place already. Add the members to the structure, and fill the structure with appropriate data before any call which uses it.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | Let's say I'm creating a chess program. I have a function
```
void foreachMove( void (*action)(chess_move*), chess_game* game);
```
which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:
```
chess_move getNextMove(chess_game* game, int depth){
//for each valid move, determine how good the move is
foreachMove(moveHandler, game);
}
void moveHandler(chess_move* move){
//uh oh, now I need the variables "game" and "depth" from the above function
}
```
Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.
How can I pass extra parameters to a function that I'm calling through a pointer? | Ah, if only C supported closures...
Antonio is right; if you need to pass extra parameters, you'll need to redefine your function pointer to accept the additional arguments. If you don't know exactly what parameters you'll need, then you have at least three choices:
1. Have the last argument in your prototype be a void\*. This gives you flexibility of passing in anything else that you need, but it definitely isn't type-safe.
2. Use variadic parameters (...). Given my lack of experience with variadic parameters in C, I'm not sure if you can use this with a function pointer, but this gives even more flexibility than the first solution, albeit still with the lack of type safety.
3. Upgrade to C++ and use [function objects](http://en.wikipedia.org/wiki/Function_object). |
11,345 | <p>What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace: </p>
<pre><code><foo xmlns="uri" />
</code></pre>
<p>It appears as though some of the XPath processor libraries won't recognize <code>//foo</code> because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.</p>
<p>Is there a standard that applies to this?</p>
<p>My approach is a bit hackish but it seems to work fine; I remove the <code>xmlns</code> declaration with a search/replace and then apply XPath.</p>
<pre><code>string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty );
</code></pre>
<p>Is that a fair approach or has anyone solved this differently?</p>
| [
{
"answer_id": 11351,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 4,
"selected": false,
"text": "<p>You need local-name():</p>\n<p><a href=\"http://www.w3.org/TR/xpath#function-local-name\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/xpath#function-local-name</a></p>\n<p>To crib from <a href=\"http://web.archive.org/web/20100810142303/http://jcooney.net:80/archive/2005/08/09/6517.aspx\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20100810142303/http://jcooney.net:80/archive/2005/08/09/6517.aspx</a>:</p>\n<pre><code><foo xmlns='urn:foo'>\n <bar>\n <asdf/>\n </bar> \n</foo>\n</code></pre>\n<p>This expression will match the “bar” element:</p>\n<pre><code> //*[local-name()='bar'] \n</code></pre>\n<p>This one won't:</p>\n<pre><code> //bar\n</code></pre>\n"
},
{
"answer_id": 11370,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to use xslt you can add the namespace in to the stylesheet declaration. If you do that, you must make sure that there is a prefix or it will not work. If the source XML does not have a prefix, that is still fine, you add your own prefix in the stylesheet. </p>\n\n<p><em>Stylesheet</em></p>\n\n<pre><code><xsl:stylesheet\n xmlns:fb=\"uri\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n\n <xsl:template match=\"fb:foo/bar\">\n <!-- do stuff here -->\n </xsl:template>\n</xsl:stylsheet>\n</code></pre>\n\n<p>Or something like that.</p>\n"
},
{
"answer_id": 16294,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>The issue is that an element without a namespace is declared to be in the NULL namespace - therefore if //foo matched against the namespace you consider to be the 'default' there would be no way to refer to an element in the null namespace.</p>\n\n<p>Remember as well that the prefix for a namespace is only a shorthand convention, the real element name (Qualified Name, or QName for short) consists of the full namespace and the local name. Changing the prefix for a namespace does not change the 'identity' of an element - if it is in the same namespace and same local name then it is the same kind of element, even if the prefix is different.</p>\n\n<p>XPath 2.0 (or rather XSLT 2.0) has the concept of the 'default xpath namespace'. You can set the xpath-default-namespace attribute on the xsl:stylesheet element.</p>\n"
},
{
"answer_id": 149088,
"author": "Andrew Cowenhoven",
"author_id": 12281,
"author_profile": "https://Stackoverflow.com/users/12281",
"pm_score": 4,
"selected": true,
"text": "<p>I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.LoadXml(xmlWithBogusNamespace); \nXmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable);\nnSpace.AddNamespace(\"myNs\", \"http://theirUri\");\n\nXmlNodeList nodes = doc.SelectNodes(\"//myNs:NodesIWant\",nSpace);\n//etc\n</code></pre>\n"
},
{
"answer_id": 49044337,
"author": "crazy dev",
"author_id": 9427549,
"author_profile": "https://Stackoverflow.com/users/9427549",
"pm_score": 0,
"selected": false,
"text": "<p>Using libxml it seems this works:</p>\n\n<p><a href=\"http://xmlsoft.org/examples/xpath1.c\" rel=\"nofollow noreferrer\">http://xmlsoft.org/examples/xpath1.c</a></p>\n\n<pre><code> int \nregister_namespaces(xmlXPathContextPtr xpathCtx, const xmlChar* nsList) {\n xmlChar* nsListDup;\n xmlChar* prefix;\n xmlChar* href;\n xmlChar* next;\n\n assert(xpathCtx);\n assert(nsList);\n\n nsListDup = xmlStrdup(nsList);\n if(nsListDup == NULL) {\n fprintf(stderr, \"Error: unable to strdup namespaces list\\n\");\n return(-1); \n }\n\n next = nsListDup; \n while(next != NULL) {\n /* skip spaces */\n while((*next) == ' ') next++;\n if((*next) == '\\0') break;\n\n /* find prefix */\n prefix = next;\n next = (xmlChar*)xmlStrchr(next, '=');\n if(next == NULL) {\n fprintf(stderr,\"Error: invalid namespaces list format\\n\");\n xmlFree(nsListDup);\n return(-1); \n }\n *(next++) = '\\0'; \n\n /* find href */\n href = next;\n next = (xmlChar*)xmlStrchr(next, ' ');\n if(next != NULL) {\n *(next++) = '\\0'; \n }\n\n /* do register namespace */\n if(xmlXPathRegisterNs(xpathCtx, prefix, href) != 0) {\n fprintf(stderr,\"Error: unable to register NS with prefix=\\\"%s\\\" and href=\\\"%s\\\"\\n\", prefix, href);\n xmlFree(nsListDup);\n return(-1); \n }\n }\n\n xmlFree(nsListDup);\n return(0);\n}\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64/"
] | What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace:
```
<foo xmlns="uri" />
```
It appears as though some of the XPath processor libraries won't recognize `//foo` because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.
Is there a standard that applies to this?
My approach is a bit hackish but it seems to work fine; I remove the `xmlns` declaration with a search/replace and then apply XPath.
```
string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty );
```
Is that a fair approach or has anyone solved this differently? | I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so:
```
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlWithBogusNamespace);
XmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable);
nSpace.AddNamespace("myNs", "http://theirUri");
XmlNodeList nodes = doc.SelectNodes("//myNs:NodesIWant",nSpace);
//etc
``` |
11,405 | <p>The following code doesn't compile with gcc, but does with Visual Studio:</p>
<pre><code>template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>test.cpp: In member function ‘void B::bar()’:</p>
<p>test.cpp:11: error: ‘foo’ was not declared in this scope</p>
</blockquote>
<p>But it should be! If I change <code>bar</code> to</p>
<pre><code>void bar() { cout << this->foo << endl; }
</code></pre>
<p>then it <em>does</em> compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk?</p>
| [
{
"answer_id": 11414,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 5,
"selected": true,
"text": "<p>This changed in <a href=\"http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus\" rel=\"noreferrer\">gcc-3.4</a>. The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases.</p>\n"
},
{
"answer_id": 11425,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>Wow. C++ never ceases to surprise me with its weirdness.</p>\n\n<blockquote>\n <p>In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,</p>\n</blockquote>\n\n<pre><code>template <typename T> struct B {\n int m;\n int n;\n int f ();\n int g ();\n};\nint n;\nint g ();\ntemplate <typename T> struct C : B<T> {\n void h ()\n {\n m = 0; // error\n f (); // error\n n = 0; // ::n is modified\n g (); // ::g is called\n }\n};\n</code></pre>\n\n<blockquote>\n <p>You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,</p>\n</blockquote>\n\n<pre><code>template <typename T> void C<T>::h ()\n{\n this->m = 0;\n this->f ();\n this->n = 0\n this->g ();\n}\n</code></pre>\n\n<blockquote>\n <p>As an alternative solution (unfortunately not backwards compatible with GCC 3.3), you may use using declarations instead of this->:</p>\n</blockquote>\n\n<pre><code>template <typename T> struct C : B<T> {\n using B<T>::m;\n using B<T>::f;\n using B<T>::n;\n using B<T>::g;\n void h ()\n {\n m = 0;\n f ();\n n = 0;\n g ();\n }\n};\n</code></pre>\n\n<p>That's just all kinds of crazy. Thanks, David.</p>\n\n<p>Here's the \"temp.dep/3\" section of the standard [ISO/IEC 14882:2003] that they are referring to:</p>\n\n<blockquote>\n <p>In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member. [Example: </p>\n</blockquote>\n\n<pre><code>typedef double A; \ntemplate<class T> class B { \n typedef int A; \n}; \ntemplate<class T> struct X : B<T> { \n A a; // a has typedouble \n}; \n</code></pre>\n\n<blockquote>\n <p>The type name <code>A</code> in the definition of <code>X<T></code> binds to the typedef name defined in the global namespace scope, not to the typedef name defined in the base class <code>B<T></code>. ] [Example: </p>\n</blockquote>\n\n<pre><code>struct A { \n struct B { /* ... */ }; \n int a; \n int Y; \n}; \nint a; \ntemplate<class T> struct Y : T { \n struct B { /* ... */ }; \n B b; //The B defined in Y \n void f(int i) { a = i; } // ::a \n Y* p; // Y<T> \n}; \nY<A> ya; \n</code></pre>\n\n<blockquote>\n <p>The members <code>A::B</code>, <code>A::a</code>, and <code>A::Y</code> of the template argument <code>A</code> do not affect the binding of names in <code>Y<A></code>. ] </p>\n</blockquote>\n"
},
{
"answer_id": 11435,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 5,
"selected": false,
"text": "<p>David Joyner had the history, here is the reason.</p>\n\n<p>The problem when compiling <code>B<T></code> is that its base class <code>A<T></code> is unknown from the compiler, being a template class, so no way for the compiler to know any members from the base class.</p>\n\n<p>Earlier versions did some inference by actually parsing the base template class, but ISO C++ stated that this inference can lead to conflicts where there should not be.</p>\n\n<p>The solution to reference a base class member in a template is to use <code>this</code> (like you did) or specifically name the base class:</p>\n\n<pre><code>template <typename T> class A {\npublic:\n T foo;\n};\n\ntemplate <typename T> class B: public A <T> {\npublic:\n void bar() { cout << A<T>::foo << endl; }\n};\n</code></pre>\n\n<p>More information in <a href=\"http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Name-lookup.html\" rel=\"nofollow noreferrer\">gcc manual</a>.</p>\n"
},
{
"answer_id": 11703,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "<p>The main reason C++ cannot assume anything here is that the base template can be specialized for a type later. Continuing the original example:</p>\n\n<pre><code>template<>\nclass A<int> {};\n\nB<int> x; \nx.bar();//this will fail because there is no member foo in A<int>\n</code></pre>\n"
},
{
"answer_id": 212084,
"author": "hschober",
"author_id": 28906,
"author_profile": "https://Stackoverflow.com/users/28906",
"pm_score": 2,
"selected": false,
"text": "<p>VC doesn't implemented two-phase lookup, while GCC does. So GCC parses templates before they are instantiated and thus finds more errors than VC. \nIn your example, foo is a dependent name, since it depends on 'T'. Unless you tell the compiler where it comes from, it cannot check the validity of the template at all, before you instantiate it. \nThat's why you have to tell the compiler where it comes from. </p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
] | The following code doesn't compile with gcc, but does with Visual Studio:
```
template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
```
I get the error:
>
> test.cpp: In member function ‘void B::bar()’:
>
>
> test.cpp:11: error: ‘foo’ was not declared in this scope
>
>
>
But it should be! If I change `bar` to
```
void bar() { cout << this->foo << endl; }
```
then it *does* compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk? | This changed in [gcc-3.4](http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus). The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases. |
11,491 | <p>What is the best way people have found to do String to Lower case / Upper case in C++?</p>
<p>The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?</p>
| [
{
"answer_id": 11502,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 6,
"selected": true,
"text": "<pre><code>#include <algorithm>\nstd::string data = \"Abc\";\nstd::transform(data.begin(), data.end(), data.begin(), ::toupper);\n</code></pre>\n\n<p><a href=\"http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/\" rel=\"noreferrer\">http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/</a></p>\n\n<p>Also, CodeProject article for common string methods: <a href=\"http://www.codeproject.com/KB/stl/STL_string_util.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/stl/STL_string_util.aspx</a></p>\n"
},
{
"answer_id": 13341,
"author": "Rob Thomas",
"author_id": 803,
"author_profile": "https://Stackoverflow.com/users/803",
"pm_score": 2,
"selected": false,
"text": "<p>You should also review <a href=\"https://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c\">this question</a>. Basically the problem is that the standard C/C++ libraries weren't built to handle Unicode data, so you will have to look to other libraries. </p>\n\n<p>This may change as the C++ standard is updated. I know the next compiler from Borland (CodeGear) will have Unicode support, and I would guess Microsoft's C++ compiler will have, or already has string libraries that support Unicode.</p>\n"
},
{
"answer_id": 13624,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 2,
"selected": false,
"text": "<p>As Darren told you, the easiest method is to use std::transform. </p>\n\n<p>But beware that in some language, like German for instance, there isn't always a one to one mapping between lower and uppercase. The \"esset\" lowercase character (look like the Greek character beta) is transformed to \"SS\" in uppercase.</p>\n"
},
{
"answer_id": 21395,
"author": "Nic Strong",
"author_id": 2281,
"author_profile": "https://Stackoverflow.com/users/2281",
"pm_score": 4,
"selected": false,
"text": "<pre><code>> std::string data = “Abc”; \n> std::transform(data.begin(), data.end(), data.begin(), ::toupper);\n</code></pre>\n\n<p>This will work, but this will use the standard \"C\" locale. You can use facets if you need to get a tolower for another locale. The above code using facets would be:</p>\n\n<pre><code>locale loc(\"\");\nconst ctype<char>& ct = use_facet<ctype<char> >(loc);\ntransform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));\n</code></pre>\n"
},
{
"answer_id": 28849,
"author": "axs6791",
"author_id": 3081,
"author_profile": "https://Stackoverflow.com/users/3081",
"pm_score": 0,
"selected": false,
"text": "<p>What Steve says is right, but I guess that if your code had to support several languages, you could have a factory method that encapsulates a set of methods that do the relevant toUpper or toLower based on that language.</p>\n"
},
{
"answer_id": 1724567,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>For copy-pasters hoping to use Nic Strong's answer, note the spelling error in \"use_factet\" and the missing third parameter to std::transform:</p>\n\n<pre><code>locale loc(\"\");\nconst ctype<char>& ct = use_factet<ctype<char> >(loc);\ntransform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>locale loc(\"\");\nconst ctype<char>& ct = use_facet<ctype<char> >(loc);\ntransform(str.begin(), str.end(), str.begin(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));\n</code></pre>\n"
},
{
"answer_id": 4336156,
"author": "yasouser",
"author_id": 338913,
"author_profile": "https://Stackoverflow.com/users/338913",
"pm_score": 2,
"selected": false,
"text": "<p>If you have Boost, then it has the simplest way. Have a look at <a href=\"http://www.boost.org/doc/libs/1_45_0/doc/html/string_algo/usage.html#id2570604\" rel=\"nofollow\">to_upper()/to_lower() in Boost string algorithms</a>.</p>\n"
},
{
"answer_id": 15151222,
"author": "NoOne",
"author_id": 964053,
"author_profile": "https://Stackoverflow.com/users/964053",
"pm_score": 1,
"selected": false,
"text": "<p>I have found a way to convert the case of unicode (and multilingual) characters, but you need to know/find (somehow) the locale of the character:</p>\n\n<pre><code>#include <locale.h>\n\n_locale_t locale = _create_locale(LC_CTYPE, \"Greek\");\nAfxMessageBox((CString)\"\"+(TCHAR)_totupper_l(_T('α'), locale));\n_free_locale(locale);\n</code></pre>\n\n<p>I haven't found a way to do that yet... I someone knows how, let me know.</p>\n\n<p>Setting locale to NULL doesn't work...</p>\n"
},
{
"answer_id": 21387775,
"author": "James Oravec",
"author_id": 1190934,
"author_profile": "https://Stackoverflow.com/users/1190934",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>VCL</code> has a <code>SysUtils.hpp</code> which has <code>LowerCase(unicodeStringVar)</code> and <code>UpperCase(unicodeStringVar)</code> which might work for you. I use this in C++ Builder 2009.</p>\n"
},
{
"answer_id": 64410355,
"author": "Joma",
"author_id": 3158594,
"author_profile": "https://Stackoverflow.com/users/3158594",
"pm_score": 0,
"selected": false,
"text": "<p>Based on <a href=\"https://stackoverflow.com/users/1689664/kyle-the-hacker\">Kyle_the_hacker's</a> -----> <a href=\"https://stackoverflow.com/a/17993266/3158594\">answer</a> with my extras.</p>\n<h1>Ubuntu</h1>\n<p>In terminal\nList all locales<br />\n<code>locale -a</code></p>\n<p>Install all locales<br />\n<code>sudo apt-get install -y locales locales-all</code></p>\n<p>Compile main.cpp<br />\n<code>$ g++ main.cpp </code></p>\n<p>Run compiled program<br />\n<code>$ ./a.out </code></p>\n<p><strong>Results</strong></p>\n<pre><code>Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/9KdHH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9KdHH.png\" alt=\"Ubuntu Linux - WSL from VSCODE\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/wRHnw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wRHnw.png\" alt=\"Ubuntu Linux - WSL\" /></a></p>\n<h1>Windows</h1>\n<p>In cmd run VCVARS developer tools<br />\n<code>"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\\vcvars64.bat" </code></p>\n<p>Compile main.cpp<br />\n<code>> cl /EHa main.cpp /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /std:c++17 /DYNAMICBASE "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /MTd</code></p>\n<pre><code>Compilador de optimización de C/C++ de Microsoft (R) versión 19.27.29111 para x64\n(C) Microsoft Corporation. Todos los derechos reservados.\n\nmain.cpp\nMicrosoft (R) Incremental Linker Version 14.27.29111.0\nCopyright (C) Microsoft Corporation. All rights reserved.\n\n/out:main.exe\nmain.obj\nkernel32.lib\nuser32.lib\ngdi32.lib\nwinspool.lib\ncomdlg32.lib\nadvapi32.lib\nshell32.lib\nole32.lib\noleaut32.lib\nuuid.lib\nodbc32.lib\nodbccp32.lib\n</code></pre>\n<p>Run main.exe<br />\n<code>>main.exe</code></p>\n<p><strong>Results</strong></p>\n<pre><code>Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/c1Kpn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c1Kpn.png\" alt=\"Windows\" /></a></p>\n<h2>The code - main.cpp</h2>\n<blockquote>\n<p><strong>This code was only tested on Windows x64 and Ubuntu Linux x64.</strong></p>\n</blockquote>\n<pre class=\"lang-cpp prettyprint-override\"><code>/*\n * Filename: c:\\Users\\x\\Cpp\\main.cpp\n * Path: c:\\Users\\x\\Cpp\n * Filename: /home/x/Cpp/main.cpp\n * Path: /home/x/Cpp\n * Created Date: Saturday, October 17th 2020, 10:43:31 pm\n * Author: Joma\n *\n * No Copyright 2020\n */\n\n\n#include <iostream>\n#include <set>\n#include <string>\n#include <locale>\n\n// WINDOWS\n#if (_WIN32)\n#include <Windows.h>\n#include <conio.h>\n#define WINDOWS_PLATFORM 1\n#define DLLCALL STDCALL\n#define DLLIMPORT _declspec(dllimport)\n#define DLLEXPORT _declspec(dllexport)\n#define DLLPRIVATE\n#define NOMINMAX\n\n//EMSCRIPTEN\n#elif defined(__EMSCRIPTEN__)\n#include <emscripten/emscripten.h>\n#include <emscripten/bind.h>\n#include <unistd.h>\n#include <termios.h>\n#define EMSCRIPTEN_PLATFORM 1\n#define DLLCALL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility("default")))\n#define DLLPRIVATE __attribute__((visibility("hidden")))\n\n// LINUX - Ubuntu, Fedora, , Centos, Debian, RedHat\n#elif (__LINUX__ || __gnu_linux__ || __linux__ || __linux || linux)\n#define LINUX_PLATFORM 1\n#include <unistd.h>\n#include <termios.h>\n#define DLLCALL CDECL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility("default")))\n#define DLLPRIVATE __attribute__((visibility("hidden")))\n#define CoTaskMemAlloc(p) malloc(p)\n#define CoTaskMemFree(p) free(p)\n\n//ANDROID\n#elif (__ANDROID__ || ANDROID)\n#define ANDROID_PLATFORM 1\n#define DLLCALL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility("default")))\n#define DLLPRIVATE __attribute__((visibility("hidden")))\n\n//MACOS\n#elif defined(__APPLE__)\n#include <unistd.h>\n#include <termios.h>\n#define DLLCALL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility("default")))\n#define DLLPRIVATE __attribute__((visibility("hidden")))\n#include "TargetConditionals.h"\n#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR\n#define IOS_SIMULATOR_PLATFORM 1\n#elif TARGET_OS_IPHONE\n#define IOS_PLATFORM 1\n#elif TARGET_OS_MAC\n#define MACOS_PLATFORM 1\n#else\n\n#endif\n\n#endif\n\n\n\ntypedef std::string String;\ntypedef std::wstring WString;\n\n#define EMPTY_STRING u8""s\n#define EMPTY_WSTRING L""s\n\nusing namespace std::literals::string_literals;\n\nclass Strings\n{\npublic:\n static String WideStringToString(const WString& wstr)\n {\n if (wstr.empty())\n {\n return String();\n }\n size_t pos;\n size_t begin = 0;\n String ret;\n\n#if WINDOWS_PLATFORM\n int size;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n while (pos != WString::npos && begin < wstr.length())\n {\n WString segment = WString(&wstr[begin], pos - begin);\n size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);\n String converted = String(size, 0);\n WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n }\n if (begin <= wstr.length())\n {\n WString segment = WString(&wstr[begin], wstr.length() - begin);\n size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);\n String converted = String(size, 0);\n WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);\n ret.append(converted);\n }\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n size_t size;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n while (pos != WString::npos && begin < wstr.length())\n {\n WString segment = WString(&wstr[begin], pos - begin);\n size = wcstombs(nullptr, segment.c_str(), 0);\n String converted = String(size, 0);\n wcstombs(&converted[0], segment.c_str(), converted.size());\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n }\n if (begin <= wstr.length())\n {\n WString segment = WString(&wstr[begin], wstr.length() - begin);\n size = wcstombs(nullptr, segment.c_str(), 0);\n String converted = String(size, 0);\n wcstombs(&converted[0], segment.c_str(), converted.size());\n ret.append(converted);\n }\n#else\n static_assert(false, "Unknown Platform");\n#endif\n return ret;\n }\n\n static WString StringToWideString(const String& str)\n {\n if (str.empty())\n {\n return WString();\n }\n\n size_t pos;\n size_t begin = 0;\n WString ret;\n#ifdef WINDOWS_PLATFORM\n int size = 0;\n pos = str.find(static_cast<char>(0), begin);\n while (pos != std::string::npos) {\n std::string segment = std::string(&str[begin], pos - begin);\n std::wstring converted = std::wstring(segment.size() + 1, 0);\n size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.length());\n converted.resize(size);\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = str.find(static_cast<char>(0), begin);\n }\n if (begin < str.length()) {\n std::string segment = std::string(&str[begin], str.length() - begin);\n std::wstring converted = std::wstring(segment.size() + 1, 0);\n size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, segment.c_str(), segment.size(), &converted[0], converted.length());\n converted.resize(size);\n ret.append(converted);\n }\n\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n size_t size;\n pos = str.find(static_cast<char>(0), begin);\n while (pos != String::npos)\n {\n String segment = String(&str[begin], pos - begin);\n WString converted = WString(segment.size(), 0);\n size = mbstowcs(&converted[0], &segment[0], converted.size());\n converted.resize(size);\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = str.find(static_cast<char>(0), begin);\n }\n if (begin < str.length())\n {\n String segment = String(&str[begin], str.length() - begin);\n WString converted = WString(segment.size(), 0);\n size = mbstowcs(&converted[0], &segment[0], converted.size());\n converted.resize(size);\n ret.append(converted);\n }\n#else\n static_assert(false, "Unknown Platform");\n#endif\n return ret;\n }\n\n\n static WString ToUpper(const WString& data)\n {\n WString result = data;\n auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());\n\n f.toupper(&result[0], &result[0] + result.size());\n return result;\n }\n\n static String ToUpper(const String& data)\n {\n return WideStringToString(ToUpper(StringToWideString(data)));\n }\n\n static WString ToLower(const WString& data)\n {\n WString result = data;\n auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());\n f.tolower(&result[0], &result[0] + result.size());\n return result;\n }\n\n static String ToLower(const String& data)\n {\n return WideStringToString(ToLower(StringToWideString(data)));\n }\n\n};\n\nenum class ConsoleTextStyle\n{\n DEFAULT = 0,\n BOLD = 1,\n FAINT = 2,\n ITALIC = 3,\n UNDERLINE = 4,\n SLOW_BLINK = 5,\n RAPID_BLINK = 6,\n REVERSE = 7,\n};\n\nenum class ConsoleForeground\n{\n DEFAULT = 39,\n BLACK = 30,\n DARK_RED = 31,\n DARK_GREEN = 32,\n DARK_YELLOW = 33,\n DARK_BLUE = 34,\n DARK_MAGENTA = 35,\n DARK_CYAN = 36,\n GRAY = 37,\n DARK_GRAY = 90,\n RED = 91,\n GREEN = 92,\n YELLOW = 93,\n BLUE = 94,\n MAGENTA = 95,\n CYAN = 96,\n WHITE = 97\n};\n\nenum class ConsoleBackground\n{\n DEFAULT = 49,\n BLACK = 40,\n DARK_RED = 41,\n DARK_GREEN = 42,\n DARK_YELLOW = 43,\n DARK_BLUE = 44,\n DARK_MAGENTA = 45,\n DARK_CYAN = 46,\n GRAY = 47,\n DARK_GRAY = 100,\n RED = 101,\n GREEN = 102,\n YELLOW = 103,\n BLUE = 104,\n MAGENTA = 105,\n CYAN = 106,\n WHITE = 107\n};\n\nclass Console\n{\nprivate:\n static void EnableVirtualTermimalProcessing()\n {\n#if defined WINDOWS_PLATFORM\n HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);\n DWORD dwMode = 0;\n GetConsoleMode(hOut, &dwMode);\n if (!(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))\n {\n dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;\n SetConsoleMode(hOut, dwMode);\n }\n#endif\n }\n\n static void ResetTerminalFormat()\n {\n std::cout << u8"\\033[0m";\n }\n\n static void SetVirtualTerminalFormat(ConsoleForeground foreground, ConsoleBackground background, std::set<ConsoleTextStyle> styles)\n {\n String format = u8"\\033[";\n format.append(std::to_string(static_cast<int>(foreground)));\n format.append(u8";");\n format.append(std::to_string(static_cast<int>(background)));\n if (styles.size() > 0)\n {\n for (auto it = styles.begin(); it != styles.end(); ++it)\n {\n format.append(u8";");\n format.append(std::to_string(static_cast<int>(*it)));\n }\n }\n format.append(u8"m");\n std::cout << format;\n }\npublic:\n static void Clear()\n {\n\n#ifdef WINDOWS_PLATFORM\n std::system(u8"cls");\n#elif LINUX_PLATFORM || defined MACOS_PLATFORM\n std::system(u8"clear");\n#elif EMSCRIPTEN_PLATFORM\n emscripten::val::global()["console"].call<void>(u8"clear");\n#else\n static_assert(false, "Unknown Platform");\n#endif\n }\n\n static void Write(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n#ifndef EMSCRIPTEN_PLATFORM\n EnableVirtualTermimalProcessing();\n SetVirtualTerminalFormat(foreground, background, styles);\n#endif\n String str = s;\n#ifdef WINDOWS_PLATFORM\n WString unicode = Strings::StringToWideString(str);\n WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), unicode.c_str(), static_cast<DWORD>(unicode.length()), nullptr, nullptr);\n#elif defined LINUX_PLATFORM || defined MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n std::cout << str;\n#else\n static_assert(false, "Unknown Platform");\n#endif\n\n#ifndef EMSCRIPTEN_PLATFORM\n ResetTerminalFormat();\n#endif\n }\n\n static void WriteLine(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n Write(s, foreground, background, styles);\n std::cout << std::endl;\n }\n\n static void Write(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n#ifndef EMSCRIPTEN_PLATFORM\n EnableVirtualTermimalProcessing();\n SetVirtualTerminalFormat(foreground, background, styles);\n#endif\n WString str = s;\n\n#ifdef WINDOWS_PLATFORM\n WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), str.c_str(), static_cast<DWORD>(str.length()), nullptr, nullptr);\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n std::cout << Strings::WideStringToString(str);\n#else\n static_assert(false, "Unknown Platform");\n#endif\n\n#ifndef EMSCRIPTEN_PLATFORM\n ResetTerminalFormat();\n#endif\n }\n\n static void WriteLine(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n Write(s, foreground, background, styles);\n std::cout << std::endl;\n }\n\n static void WriteLine()\n {\n std::cout << std::endl;\n }\n\n static void Pause()\n {\n char c;\n do\n {\n c = getchar();\n std::cout << "Press Key " << std::endl;\n } while (c != 64);\n std::cout << "KeyPressed" << std::endl;\n }\n\n static int PauseAny(bool printWhenPressed = false, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n int ch;\n#ifdef WINDOWS_PLATFORM\n ch = _getch();\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n struct termios oldt, newt;\n tcgetattr(STDIN_FILENO, &oldt);\n newt = oldt;\n newt.c_lflag &= ~(ICANON | ECHO);\n tcsetattr(STDIN_FILENO, TCSANOW, &newt);\n ch = getchar();\n tcsetattr(STDIN_FILENO, TCSANOW, &oldt);\n#else\n static_assert(false, "Unknown Platform");\n#endif\n if (printWhenPressed)\n {\n Console::Write(String(1, ch), foreground, background, styles);\n }\n return ch;\n }\n};\n\n\n\nint main()\n{\n std::locale::global(std::locale(u8"en_US.UTF-8"));\n String dataStr = u8"Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë";\n WString dataWStr = L"Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë";\n std::string locale = u8"";\n //std::string locale = u8"de_DE.UTF-8";\n //std::string locale = u8"en_US.UTF-8";\n Console::WriteLine(dataStr);\n Console::WriteLine(dataWStr);\n dataStr = Strings::ToUpper(dataStr);\n dataWStr = Strings::ToUpper(dataWStr);\n Console::WriteLine(dataStr);\n Console::WriteLine(dataWStr);\n dataStr = Strings::ToLower(dataStr);\n dataWStr = Strings::ToLower(dataWStr);\n Console::WriteLine(dataStr);\n Console::WriteLine(dataWStr);\n \n \n Console::WriteLine(u8"Press any key to exit"s, ConsoleForeground::DARK_GRAY);\n Console::PauseAny();\n\n return 0;\n}\n\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | What is the best way people have found to do String to Lower case / Upper case in C++?
The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method? | ```
#include <algorithm>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
```
<http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/>
Also, CodeProject article for common string methods: <http://www.codeproject.com/KB/stl/STL_string_util.aspx> |
11,532 | <p>How can I find any unused functions in a PHP project?</p>
<p>Are there features or APIs built into PHP that will allow me to analyse my codebase - for example <a href="http://ie.php.net/manual/en/language.oop5.reflection.php" rel="noreferrer">Reflection</a>, <a href="http://php.net/manual/en/function.token-get-all.php" rel="noreferrer"><code>token_get_all()</code></a>?</p>
<p>Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis?</p>
| [
{
"answer_id": 14625,
"author": "Stacey Richards",
"author_id": 1142,
"author_profile": "https://Stackoverflow.com/users/1142",
"pm_score": 6,
"selected": true,
"text": "<p>Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution:</p>\n\n<pre><code><?php\n $functions = array();\n $path = \"/path/to/my/php/project\";\n define_dir($path, $functions);\n reference_dir($path, $functions);\n echo\n \"<table>\" .\n \"<tr>\" .\n \"<th>Name</th>\" .\n \"<th>Defined</th>\" .\n \"<th>Referenced</th>\" .\n \"</tr>\";\n foreach ($functions as $name => $value) {\n echo\n \"<tr>\" . \n \"<td>\" . htmlentities($name) . \"</td>\" .\n \"<td>\" . (isset($value[0]) ? count($value[0]) : \"-\") . \"</td>\" .\n \"<td>\" . (isset($value[1]) ? count($value[1]) : \"-\") . \"</td>\" .\n \"</tr>\";\n }\n echo \"</table>\";\n function define_dir($path, &$functions) {\n if ($dir = opendir($path)) {\n while (($file = readdir($dir)) !== false) {\n if (substr($file, 0, 1) == \".\") continue;\n if (is_dir($path . \"/\" . $file)) {\n define_dir($path . \"/\" . $file, $functions);\n } else {\n if (substr($file, - 4, 4) != \".php\") continue;\n define_file($path . \"/\" . $file, $functions);\n }\n }\n } \n }\n function define_file($path, &$functions) {\n $tokens = token_get_all(file_get_contents($path));\n for ($i = 0; $i < count($tokens); $i++) {\n $token = $tokens[$i];\n if (is_array($token)) {\n if ($token[0] != T_FUNCTION) continue;\n $i++;\n $token = $tokens[$i];\n if ($token[0] != T_WHITESPACE) die(\"T_WHITESPACE\");\n $i++;\n $token = $tokens[$i];\n if ($token[0] != T_STRING) die(\"T_STRING\");\n $functions[$token[1]][0][] = array($path, $token[2]);\n }\n }\n }\n function reference_dir($path, &$functions) {\n if ($dir = opendir($path)) {\n while (($file = readdir($dir)) !== false) {\n if (substr($file, 0, 1) == \".\") continue;\n if (is_dir($path . \"/\" . $file)) {\n reference_dir($path . \"/\" . $file, $functions);\n } else {\n if (substr($file, - 4, 4) != \".php\") continue;\n reference_file($path . \"/\" . $file, $functions);\n }\n }\n } \n }\n function reference_file($path, &$functions) {\n $tokens = token_get_all(file_get_contents($path));\n for ($i = 0; $i < count($tokens); $i++) {\n $token = $tokens[$i];\n if (is_array($token)) {\n if ($token[0] != T_STRING) continue;\n if ($tokens[$i + 1] != \"(\") continue;\n $functions[$token[1]][1][] = array($path, $token[2]);\n }\n }\n }\n?>\n</code></pre>\n\n<p>I'll probably spend some more time on it so I can quickly find the files and line numbers of the function definitions and references; this information is being gathered, just not displayed.</p>\n"
},
{
"answer_id": 693991,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<p>If I remember correctly you can use <a href=\"http://phpcallgraph.sourceforge.net/\" rel=\"nofollow noreferrer\">phpCallGraph</a> to do that. It'll generate a nice graph (image) for you with all the methods involved. If a method is not connected to any other, that's a good sign that the method is orphaned.</p>\n\n<p>Here's an example: <a href=\"http://phpcallgraph.sourceforge.net/examples/refactoring-candidates/class_GallerySystem.png\" rel=\"nofollow noreferrer\">classGallerySystem.png</a></p>\n\n<p>The method <code>getKeywordSetOfCategories()</code> is orphaned.</p>\n\n<p>Just by the way, you don't have to take an image -- phpCallGraph can also <em>generate</em> a text file, or a PHP array, etc..</p>\n"
},
{
"answer_id": 2946691,
"author": "webbiedave",
"author_id": 294972,
"author_profile": "https://Stackoverflow.com/users/294972",
"pm_score": 2,
"selected": false,
"text": "<p>Because PHP functions/methods can be dynamically invoked, there is no programmatic way to know with certainty if a function will never be called.</p>\n\n<p>The only certain way is through manual analysis.</p>\n"
},
{
"answer_id": 2948406,
"author": "symcbean",
"author_id": 223992,
"author_profile": "https://Stackoverflow.com/users/223992",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://phpxref.sourceforge.net/\" rel=\"nofollow noreferrer\">phpxref</a> will identify where functions are called from which would facilitate the analysis - but there's still a certain amount of manual effort involved.</p>\n"
},
{
"answer_id": 2953417,
"author": "manuel aldana",
"author_id": 236370,
"author_profile": "https://Stackoverflow.com/users/236370",
"pm_score": -1,
"selected": false,
"text": "<p>afaik there is no way. To know which functions \"are belonging to whom\" you would need to execute the system (runtime late binding function lookup). </p>\n\n<p>But Refactoring tools are based on static code analysis. I really like dynamic typed languages, but in my view they are difficult to scale. The lack of safe refactorings in large codebases and dynamic typed languages is a major drawback for maintainability and handling software evolution.</p>\n"
},
{
"answer_id": 4791987,
"author": "Gordon",
"author_id": 208809,
"author_profile": "https://Stackoverflow.com/users/208809",
"pm_score": 5,
"selected": false,
"text": "<p>You can try Sebastian Bergmann's Dead Code Detector:</p>\n\n<blockquote>\n <p><code>phpdcd</code> is a Dead Code Detector (DCD) for PHP code. It scans a PHP project for all declared functions and methods and reports those as being \"dead code\" that are not called at least once.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://github.com/sebastianbergmann/phpdcd\" rel=\"nofollow noreferrer\">https://github.com/sebastianbergmann/phpdcd</a></p>\n\n<p>Note that it's a static code analyzer, so it might give false positives for methods that only called dynamically, e.g. it cannot detect <code>$foo = 'fn'; $foo();</code></p>\n\n<p>You can install it via PEAR:</p>\n\n<pre><code>pear install phpunit/phpdcd-beta\n</code></pre>\n\n<p>After that you can use with the following options:</p>\n\n<pre><code>Usage: phpdcd [switches] <directory|file> ...\n\n--recursive Report code as dead if it is only called by dead code.\n\n--exclude <dir> Exclude <dir> from code analysis.\n--suffixes <suffix> A comma-separated list of file suffixes to check.\n\n--help Prints this usage information.\n--version Prints the version and exits.\n\n--verbose Print progress bar.\n</code></pre>\n\n<p>More tools:</p>\n\n<ul>\n<li><a href=\"https://phpqa.io/\" rel=\"nofollow noreferrer\">https://phpqa.io/</a></li>\n</ul>\n\n<hr>\n\n<p><strong>Note:</strong> as per the repository notice, <em>this project is no longer maintained and its repository is only kept for archival purposes</em>. So your mileage may vary.</p>\n"
},
{
"answer_id": 7133253,
"author": "Andrey Butov",
"author_id": 137484,
"author_profile": "https://Stackoverflow.com/users/137484",
"pm_score": 3,
"selected": false,
"text": "<p>USAGE: <strong>find_unused_functions.php <root_directory></strong></p>\n<p>NOTE: This is a ‘quick-n-dirty’ approach to the problem. This script only performs a lexical pass over the files, and does not respect situations where different modules define identically named functions or methods. If you use an IDE for your PHP development, it may offer a more comprehensive solution.</p>\n<p>Requires PHP 5</p>\n<p>To save you a copy and paste, a direct download, and any new versions, are <strong><a href=\"https://github.com/andreybutov/find-unused-php-functions\" rel=\"nofollow noreferrer\">available here</a></strong>.</p>\n<pre><code>#!/usr/bin/php -f\n \n<?php\n \n// ============================================================================\n//\n// find_unused_functions.php\n//\n// Find unused functions in a set of PHP files.\n// version 1.3\n//\n// ============================================================================\n//\n// Copyright (c) 2011, Andrey Butov. All Rights Reserved.\n// This script is provided as is, without warranty of any kind.\n//\n// http://www.andreybutov.com\n//\n// ============================================================================\n \n// This may take a bit of memory...\nini_set('memory_limit', '2048M');\n \nif ( !isset($argv[1]) ) \n{\n usage();\n}\n \n$root_dir = $argv[1];\n \nif ( !is_dir($root_dir) || !is_readable($root_dir) )\n{\n echo "ERROR: '$root_dir' is not a readable directory.\\n";\n usage();\n}\n \n$files = php_files($root_dir);\n$tokenized = array();\n \nif ( count($files) == 0 )\n{\n echo "No PHP files found.\\n";\n exit;\n}\n \n$defined_functions = array();\n \nforeach ( $files as $file )\n{\n $tokens = tokenize($file);\n \n if ( $tokens )\n {\n // We retain the tokenized versions of each file,\n // because we'll be using the tokens later to search\n // for function 'uses', and we don't want to \n // re-tokenize the same files again.\n \n $tokenized[$file] = $tokens;\n \n for ( $i = 0 ; $i < count($tokens) ; ++$i )\n {\n $current_token = $tokens[$i];\n $next_token = safe_arr($tokens, $i + 2, false);\n \n if ( is_array($current_token) && $next_token && is_array($next_token) )\n {\n if ( safe_arr($current_token, 0) == T_FUNCTION )\n {\n // Find the 'function' token, then try to grab the \n // token that is the name of the function being defined.\n // \n // For every defined function, retain the file and line\n // location where that function is defined. Since different\n // modules can define a functions with the same name,\n // we retain multiple definition locations for each function name.\n \n $function_name = safe_arr($next_token, 1, false);\n $line = safe_arr($next_token, 2, false);\n \n if ( $function_name && $line )\n {\n $function_name = trim($function_name);\n if ( $function_name != "" )\n {\n $defined_functions[$function_name][] = array('file' => $file, 'line' => $line);\n }\n }\n }\n }\n }\n }\n}\n \n// We now have a collection of defined functions and\n// their definition locations. Go through the tokens again, \n// and find 'uses' of the function names. \n \nforeach ( $tokenized as $file => $tokens )\n{\n foreach ( $tokens as $token )\n {\n if ( is_array($token) && safe_arr($token, 0) == T_STRING )\n {\n $function_name = safe_arr($token, 1, false);\n $function_line = safe_arr($token, 2, false);;\n \n if ( $function_name && $function_line )\n {\n $locations_of_defined_function = safe_arr($defined_functions, $function_name, false);\n \n if ( $locations_of_defined_function )\n {\n $found_function_definition = false;\n \n foreach ( $locations_of_defined_function as $location_of_defined_function )\n {\n $function_defined_in_file = $location_of_defined_function['file'];\n $function_defined_on_line = $location_of_defined_function['line'];\n \n if ( $function_defined_in_file == $file && \n $function_defined_on_line == $function_line )\n {\n $found_function_definition = true;\n break;\n }\n }\n \n if ( !$found_function_definition )\n {\n // We found usage of the function name in a context\n // that is not the definition of that function. \n // Consider the function as 'used'.\n \n unset($defined_functions[$function_name]);\n }\n }\n }\n }\n }\n}\n \n \nprint_report($defined_functions); \nexit;\n \n \n// ============================================================================\n \nfunction php_files($path) \n{\n // Get a listing of all the .php files contained within the $path\n // directory and its subdirectories.\n \n $matches = array();\n $folders = array(rtrim($path, DIRECTORY_SEPARATOR));\n \n while( $folder = array_shift($folders) ) \n {\n $matches = array_merge($matches, glob($folder.DIRECTORY_SEPARATOR."*.php", 0));\n $moreFolders = glob($folder.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);\n $folders = array_merge($folders, $moreFolders);\n }\n \n return $matches;\n}\n \n// ============================================================================\n \nfunction safe_arr($arr, $i, $default = "")\n{\n return isset($arr[$i]) ? $arr[$i] : $default;\n}\n \n// ============================================================================\n \nfunction tokenize($file)\n{\n $file_contents = file_get_contents($file);\n \n if ( !$file_contents )\n {\n return false;\n }\n \n $tokens = token_get_all($file_contents);\n return ($tokens && count($tokens) > 0) ? $tokens : false;\n}\n \n// ============================================================================\n \nfunction usage()\n{\n global $argv;\n $file = (isset($argv[0])) ? basename($argv[0]) : "find_unused_functions.php";\n die("USAGE: $file <root_directory>\\n\\n");\n}\n \n// ============================================================================\n \nfunction print_report($unused_functions)\n{\n if ( count($unused_functions) == 0 )\n {\n echo "No unused functions found.\\n";\n }\n \n $count = 0;\n foreach ( $unused_functions as $function => $locations )\n {\n foreach ( $locations as $location )\n {\n echo "'$function' in {$location['file']} on line {$location['line']}\\n";\n $count++;\n }\n }\n \n echo "=======================================\\n";\n echo "Found $count unused function" . (($count == 1) ? '' : 's') . ".\\n\\n";\n}\n \n// ============================================================================\n \n/* EOF */\n</code></pre>\n"
},
{
"answer_id": 9979425,
"author": "Tim Cullen",
"author_id": 1088372,
"author_profile": "https://Stackoverflow.com/users/1088372",
"pm_score": 4,
"selected": false,
"text": "<p>This bit of bash scripting might help:</p>\n\n<pre><code>grep -rhio ^function\\ .*\\( .|awk -F'[( ]' '{print \"echo -n \" $2 \" && grep -rin \" $2 \" .|grep -v function|wc -l\"}'|bash|grep 0\n</code></pre>\n\n<p>This basically recursively greps the current directory for function definitions, passes the hits to awk, which forms a command to do the following:</p>\n\n<ul>\n<li>print the function name</li>\n<li>recursively grep for it again</li>\n<li>piping that output to grep -v to filter out function definitions so as to retain calls to the function</li>\n<li>pipes this output to wc -l which prints the line count</li>\n</ul>\n\n<p>This command is then sent for execution to bash and the output is grepped for 0, which would indicate 0 calls to the function.</p>\n\n<p>Note that this will <em>not</em> solve the problem calebbrown cites above, so there might be some false positives in the output.</p>\n"
},
{
"answer_id": 55196470,
"author": "Tomas Votruba",
"author_id": 1348344,
"author_profile": "https://Stackoverflow.com/users/1348344",
"pm_score": 2,
"selected": false,
"text": "<h2>2019+ Update</h2>\n\n<p>I got inspied by <a href=\"https://stackoverflow.com/questions/11532/how-can-i-find-unused-functions-in-a-php-project/7133253#7133253\">Andrey's answer</a> and turned this into a coding standard sniff.</p>\n\n<p>The detection is very simple yet powerful:</p>\n\n<ul>\n<li>finds all methods <code>public function someMethod()</code></li>\n<li>then find all method calls <code>${anything}->someMethod()</code></li>\n<li>and simply <strong>reports those public functions that were never called</strong></li>\n</ul>\n\n<p>It helped me to remove <a href=\"https://github.com/Symplify/Symplify/commit/fa21855694d933716117b2a2db13acac55b86d69\" rel=\"nofollow noreferrer\">over</a> <a href=\"https://github.com/Symplify/Symplify/commit/3f08ed1fb2f22dd6c4a7b46d680adf4ab5a0907d\" rel=\"nofollow noreferrer\">20+ methods</a> I would have to maintain and test.</p>\n\n<p><br></p>\n\n<h2>3 Steps to Find them</h2>\n\n<p>Install ECS:</p>\n\n<pre><code>composer require symplify/easy-coding-standard --dev\n</code></pre>\n\n<p>Set up <code>ecs.yaml</code> config:</p>\n\n<pre><code># ecs.yaml\nservices:\n Symplify\\CodingStandard\\Sniffs\\DeadCode\\UnusedPublicMethodSniff: ~\n</code></pre>\n\n<p>Run the command:</p>\n\n<pre><code>vendor/bin/ecs check src\n</code></pre>\n\n<p>See reported methods and remove those you don't fine useful </p>\n\n<hr>\n\n<p>You can read more about it here: <a href=\"https://www.tomasvotruba.cz/blog/2019/03/14/remove-dead-public-methdos-from-your-code/\" rel=\"nofollow noreferrer\">Remove Dead Public Methods from Your Code</a></p>\n"
},
{
"answer_id": 64443364,
"author": "Sandy Garrido",
"author_id": 7696704,
"author_profile": "https://Stackoverflow.com/users/7696704",
"pm_score": 3,
"selected": false,
"text": "<h1>2020 Update</h1>\n<p>I have used the other methods outlined above, even the <strong>2019 update answer here is outdated</strong>.</p>\n<p>Tomáš Votruba's answer led me to find Phan as the ECS route has now been deprecated. Symplify have removed the dead public method checker.</p>\n<h2>Phan is a static analyzer for PHP</h2>\n<p>We can utilise Phan to search for dead code. Here are the steps to take using composer to install. These steps are also found on the <a href=\"https://github.com/phan/phan\" rel=\"noreferrer\">git repo for phan</a>. These instructions assume you're at the root of your project.</p>\n<h2>Step 1 - Install Phan w/ composer</h2>\n<pre><code>composer require phan/phan\n</code></pre>\n<h2>Step 2 - Install php-ast</h2>\n<p><code>PHP-AST</code> is a requirement for Phan\nAs I'm using WSL, I've been able to use PECL to install, however, other install methods for <code>php-ast</code> can be found in a git repo</p>\n<pre><code>pecl install ast\n</code></pre>\n<h2>Step 3 - Locate and edit php.ini to use php-ast</h2>\n<p>Locate current <code>php.ini</code></p>\n<pre><code>php -i | grep 'php.ini'\n</code></pre>\n<p>Now take that file location and nano (or whichever of your choice to edit this doc). Locate the area of all extensions and ADD the following line:</p>\n<pre><code>extension=ast.so\n</code></pre>\n<h2>Step 4 - create a config file for Phan</h2>\n<p>Steps on config file can be found in Phan's documentation on <a href=\"https://github.com/phan/phan/wiki/Getting-Started#creating-a-config-file\" rel=\"noreferrer\">how to create a config file</a>\nYou'll want to use their sample one as it's a good starting point. Edit the following arrays to add your own paths on both\n<code>directory_list</code> & <code>exclude_analysis_directory_list</code>.\nPlease note that <code>exclude_analysis_directory_list</code> will still be parsed but not validated eg. adding Wordpress directory here would mean, false positives for called wordpress functions in your theme would not appear as it found the function in wordpress but at the same time it'll not validate functions in wordpress' folder.\nMine looked like this</p>\n<pre><code>......\n\n'directory_list' => [\n 'public_html'\n],\n\n......\n\n'exclude_analysis_directory_list' => [\n 'vendor/',\n 'public_html/app/plugins',\n 'public_html/app/mu-plugins',\n 'public_html/admin'\n],\n......\n</code></pre>\n<h2>Step 5 - Run Phan with dead code detection</h2>\n<p>Now that we've installed phan and ast, configured the folders we wish to parse, it's time to run Phan. We'll be passing an argument to phan <code>--dead-code-detection</code> which is self explanatory.</p>\n<pre><code>./vendor/bin/phan --dead-code-detection\n</code></pre>\n<p>This output will need verifying with a fine tooth comb but it's certainly the best place to start</p>\n<p>The output will look like this in console</p>\n<pre><code>the/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\nthe/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\nthe/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\nthe/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\n</code></pre>\n<p>Please feel free to add to this answer or correct my mistakes :)</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142/"
] | How can I find any unused functions in a PHP project?
Are there features or APIs built into PHP that will allow me to analyse my codebase - for example [Reflection](http://ie.php.net/manual/en/language.oop5.reflection.php), [`token_get_all()`](http://php.net/manual/en/function.token-get-all.php)?
Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis? | Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution:
```
<?php
$functions = array();
$path = "/path/to/my/php/project";
define_dir($path, $functions);
reference_dir($path, $functions);
echo
"<table>" .
"<tr>" .
"<th>Name</th>" .
"<th>Defined</th>" .
"<th>Referenced</th>" .
"</tr>";
foreach ($functions as $name => $value) {
echo
"<tr>" .
"<td>" . htmlentities($name) . "</td>" .
"<td>" . (isset($value[0]) ? count($value[0]) : "-") . "</td>" .
"<td>" . (isset($value[1]) ? count($value[1]) : "-") . "</td>" .
"</tr>";
}
echo "</table>";
function define_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
define_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
define_file($path . "/" . $file, $functions);
}
}
}
}
function define_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_FUNCTION) continue;
$i++;
$token = $tokens[$i];
if ($token[0] != T_WHITESPACE) die("T_WHITESPACE");
$i++;
$token = $tokens[$i];
if ($token[0] != T_STRING) die("T_STRING");
$functions[$token[1]][0][] = array($path, $token[2]);
}
}
}
function reference_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
reference_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
reference_file($path . "/" . $file, $functions);
}
}
}
}
function reference_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_STRING) continue;
if ($tokens[$i + 1] != "(") continue;
$functions[$token[1]][1][] = array($path, $token[2]);
}
}
}
?>
```
I'll probably spend some more time on it so I can quickly find the files and line numbers of the function definitions and references; this information is being gathered, just not displayed. |
11,561 | <p>I've used Apache CXF to expose about ten java classes as web services.</p>
<p>I've generated clients using CXF, Axis, and .NET.</p>
<p>In Axis and CXF a "Service" or "Locator" is generated.
From this service you can get a "Port".
The "Port" is used to make individual calls to the methods exposed by the web service.</p>
<p>In .NET the "Service" directly exposes the calls to the web service.</p>
<p>Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services?</p>
<p>Axis:</p>
<pre><code>PatientServiceImplServiceLocator locator =
new PatientServiceImplServiceLocator();
PatientService service = locator.getPatientServiceImplPort();
</code></pre>
<p>CXF:</p>
<pre><code>PatientServiceImplService locator = new PatientServiceImplService();
PatientService service = locator.getPatientServiceImplPort();
</code></pre>
<p>.net:</p>
<pre><code>PatientServiceImplService service = new PatientServiceImplService();
</code></pre>
| [
{
"answer_id": 11567,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<p>As you already mentioned, those terms mean different things in different stacks - there is no one right generic answer for web services.</p>\n"
},
{
"answer_id": 11619,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 4,
"selected": true,
"text": "<p>I'd hop over to <a href=\"http://www.w3.org/TR/wsdl.html\" rel=\"noreferrer\">http://www.w3.org/TR/wsdl.html</a> which I think explains Port, Service and Endpoint reasonably well. A locator is an implementation specific mechanism that some WS stacks use to provide access to service endpoints.</p>\n"
},
{
"answer_id": 11639,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 5,
"selected": false,
"text": "<p>I found the information based on Kevin Kenny's answer, but I figured I'd post it here for others.</p>\n\n<p>A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:</p>\n\n<ul>\n<li><strong>Types</strong>– a container for data type definitions using some type system (such as XSD).</li>\n<li><strong>Message</strong>– an abstract, typed definition of the data being communicated.</li>\n<li><strong>Operation</strong>– an abstract description of an action supported by the service.</li>\n<li><strong>Port Type</strong>–an abstract set of operations supported by one or more endpoints.</li>\n<li><strong>Binding</strong>– a concrete protocol and data format specification for a particular port type.</li>\n<li><strong>Port</strong>– a single endpoint defined as a combination of a binding and a network address.</li>\n<li><strong>Service</strong>– a collection of related endpoints.</li>\n</ul>\n"
},
{
"answer_id": 23066361,
"author": "pHneutre",
"author_id": 1585148,
"author_profile": "https://Stackoverflow.com/users/1585148",
"pm_score": 2,
"selected": false,
"text": "<p>I would like to add that <code><port></code> and <code><endpoint></code> serve the same purpose, but <code>port</code> is used by WSDL 1.1 and <code>endpoint</code> by WSDL 2.0.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | I've used Apache CXF to expose about ten java classes as web services.
I've generated clients using CXF, Axis, and .NET.
In Axis and CXF a "Service" or "Locator" is generated.
From this service you can get a "Port".
The "Port" is used to make individual calls to the methods exposed by the web service.
In .NET the "Service" directly exposes the calls to the web service.
Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services?
Axis:
```
PatientServiceImplServiceLocator locator =
new PatientServiceImplServiceLocator();
PatientService service = locator.getPatientServiceImplPort();
```
CXF:
```
PatientServiceImplService locator = new PatientServiceImplService();
PatientService service = locator.getPatientServiceImplPort();
```
.net:
```
PatientServiceImplService service = new PatientServiceImplService();
``` | I'd hop over to <http://www.w3.org/TR/wsdl.html> which I think explains Port, Service and Endpoint reasonably well. A locator is an implementation specific mechanism that some WS stacks use to provide access to service endpoints. |
11,562 | <p><code>std::swap()</code> is used by many std containers (such as <code>std::list</code> and <code>std::vector</code>) during sorting and even assignment.</p>
<p>But the std implementation of <code>swap()</code> is very generalized and rather inefficient for custom types.</p>
<p>Thus efficiency can be gained by overloading <code>std::swap()</code> with a custom type specific implementation. But how can you implement it so it will be used by the std containers?</p>
| [
{
"answer_id": 11599,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 6,
"selected": false,
"text": "<p>You're not allowed (by the C++ standard) to overload std::swap, however you are specifically allowed to add template specializations for your own types to the std namespace. E.g.</p>\n\n<pre><code>namespace std\n{\n template<>\n void swap(my_type& lhs, my_type& rhs)\n {\n // ... blah\n }\n}\n</code></pre>\n\n<p>then the usages in the std containers (and anywhere else) will pick your specialization instead of the general one.</p>\n\n<p>Also note that providing a base class implementation of swap isn't good enough for your derived types. E.g. if you have</p>\n\n<pre><code>class Base\n{\n // ... stuff ...\n}\nclass Derived : public Base\n{\n // ... stuff ...\n}\n\nnamespace std\n{\n template<>\n void swap(Base& lha, Base& rhs)\n {\n // ...\n }\n}\n</code></pre>\n\n<p>this will work for Base classes, but if you try to swap two Derived objects it will use the generic version from std because the templated swap is an exact match (and it avoids the problem of only swapping the 'base' parts of your derived objects).</p>\n\n<p>NOTE: I've updated this to remove the wrong bits from my last answer. D'oh! (thanks puetzk and j_random_hacker for pointing it out)</p>\n"
},
{
"answer_id": 109613,
"author": "puetzk",
"author_id": 14312,
"author_profile": "https://Stackoverflow.com/users/14312",
"pm_score": 5,
"selected": false,
"text": "<p>While it's correct that one shouldn't generally add stuff to the std:: namespace, adding template specializations for user-defined types is specifically allowed. Overloading the functions is not. This is a subtle difference :-)</p>\n\n<blockquote>\n <p>17.4.3.1/1\n It is undefined for a C++ program to add declarations or definitions\n to namespace std or namespaces with namespace std unless otherwise\n specified. A program may add template specializations for any\n standard library template to namespace std. Such a specialization\n (complete or partial) of a standard library results in undefined\n behaviour unless the declaration depends on a user-defined name of\n external linkage and unless the template specialization meets the\n standard library requirements for the original template. </p>\n</blockquote>\n\n<p>A specialization of std::swap would look like:</p>\n\n<pre><code>namespace std\n{\n template<>\n void swap(myspace::mytype& a, myspace::mytype& b) { ... }\n}\n</code></pre>\n\n<p>Without the template<> bit it would be an overload, which is undefined, rather than a specialization, which is permitted. @Wilka's suggest approach of changing the default namespace may work with user code (due to Koenig lookup preferring the namespace-less version) but it's not guaranteed to, and in fact isn't really supposed to (the STL implementation ought to use the fully-qualified std::swap).</p>\n\n<p>There is a <a href=\"http://groups.google.ca/group/comp.lang.c++.moderated/browse_thread/thread/b396fedad7dcdc81\" rel=\"noreferrer\">thread on comp.lang.c++.moderated</a> with a <strong>long</strong> dicussion of the topic. Most of it is about partial specialization, though (which there's currently no good way to do).</p>\n"
},
{
"answer_id": 2684544,
"author": "Dave Abrahams",
"author_id": 125349,
"author_profile": "https://Stackoverflow.com/users/125349",
"pm_score": 8,
"selected": true,
"text": "<p>The right way to overload <code>std::swap</code>'s implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via <a href=\"https://en.cppreference.com/w/cpp/language/adl\" rel=\"noreferrer\">argument-dependent lookup (ADL)</a>. One particularly easy thing to do is:</p>\n<pre><code>class X\n{\n // ...\n friend void swap(X& a, X& b)\n {\n using std::swap; // bring in swap for built-in types\n\n swap(a.base1, b.base1);\n swap(a.base2, b.base2);\n // ...\n swap(a.member1, b.member1);\n swap(a.member2, b.member2);\n // ...\n }\n};\n</code></pre>\n"
},
{
"answer_id": 8439357,
"author": "Howard Hinnant",
"author_id": 576911,
"author_profile": "https://Stackoverflow.com/users/576911",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Attention Mozza314</strong></p>\n\n<p>Here is a simulation of the effects of a generic <code>std::algorithm</code> calling <code>std::swap</code>, and having the user provide their swap in namespace std. As this is an experiment, this simulation uses <code>namespace exp</code> instead of <code>namespace std</code>.</p>\n\n<pre><code>// simulate <algorithm>\n\n#include <cstdio>\n\nnamespace exp\n{\n\n template <class T>\n void\n swap(T& x, T& y)\n {\n printf(\"generic exp::swap\\n\");\n T tmp = x;\n x = y;\n y = tmp;\n }\n\n template <class T>\n void algorithm(T* begin, T* end)\n {\n if (end-begin >= 2)\n exp::swap(begin[0], begin[1]);\n }\n\n}\n\n// simulate user code which includes <algorithm>\n\nstruct A\n{\n};\n\nnamespace exp\n{\n void swap(A&, A&)\n {\n printf(\"exp::swap(A, A)\\n\");\n }\n\n}\n\n// exercise simulation\n\nint main()\n{\n A a[2];\n exp::algorithm(a, a+2);\n}\n</code></pre>\n\n<p>For me this prints out: </p>\n\n<pre><code>generic exp::swap\n</code></pre>\n\n<p>If your compiler prints out something different then it is not correctly implementing \"two-phase lookup\" for templates.</p>\n\n<p>If your compiler is conforming (to any of C++98/03/11), then it will give the same output I show. And in that case exactly what you fear will happen, does happen. And putting your <code>swap</code> into namespace <code>std</code> (<code>exp</code>) did not stop it from happening.</p>\n\n<p>Dave and I are both committee members and have been working this area of the standard for a decade (and not always in agreement with each other). But this issue has been settled for a long time, and we both agree on how it has been settled. Disregard Dave's expert opinion/answer in this area at your own peril.</p>\n\n<p>This issue came to light after C++98 was published. Starting about 2001 Dave and I began to <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2001/n1289.html\">work this area</a>. And this is the modern solution:</p>\n\n<pre><code>// simulate <algorithm>\n\n#include <cstdio>\n\nnamespace exp\n{\n\n template <class T>\n void\n swap(T& x, T& y)\n {\n printf(\"generic exp::swap\\n\");\n T tmp = x;\n x = y;\n y = tmp;\n }\n\n template <class T>\n void algorithm(T* begin, T* end)\n {\n if (end-begin >= 2)\n swap(begin[0], begin[1]);\n }\n\n}\n\n// simulate user code which includes <algorithm>\n\nstruct A\n{\n};\n\nvoid swap(A&, A&)\n{\n printf(\"swap(A, A)\\n\");\n}\n\n// exercise simulation\n\nint main()\n{\n A a[2];\n exp::algorithm(a, a+2);\n}\n</code></pre>\n\n<p>Output is:</p>\n\n<pre><code>swap(A, A)\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>An observation has been made that:</p>\n\n<pre><code>namespace exp\n{ \n template <>\n void swap(A&, A&)\n {\n printf(\"exp::swap(A, A)\\n\");\n }\n\n}\n</code></pre>\n\n<p>works! So why not use that?</p>\n\n<p>Consider the case that your <code>A</code> is a class template:</p>\n\n<pre><code>// simulate user code which includes <algorithm>\n\ntemplate <class T>\nstruct A\n{\n};\n\nnamespace exp\n{\n\n template <class T>\n void swap(A<T>&, A<T>&)\n {\n printf(\"exp::swap(A, A)\\n\");\n }\n\n}\n\n// exercise simulation\n\nint main()\n{\n A<int> a[2];\n exp::algorithm(a, a+2);\n}\n</code></pre>\n\n<p>Now it doesn't work again. :-(</p>\n\n<p>So you could put <code>swap</code> in namespace std and have it work. But you'll need to remember to put <code>swap</code> in <code>A</code>'s namespace for the case when you have a template: <code>A<T></code>. And since both cases will work if you put <code>swap</code> in <code>A</code>'s namespace, it is just easier to remember (and to teach others) to just do it that one way.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | `std::swap()` is used by many std containers (such as `std::list` and `std::vector`) during sorting and even assignment.
But the std implementation of `swap()` is very generalized and rather inefficient for custom types.
Thus efficiency can be gained by overloading `std::swap()` with a custom type specific implementation. But how can you implement it so it will be used by the std containers? | The right way to overload `std::swap`'s implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via [argument-dependent lookup (ADL)](https://en.cppreference.com/w/cpp/language/adl). One particularly easy thing to do is:
```
class X
{
// ...
friend void swap(X& a, X& b)
{
using std::swap; // bring in swap for built-in types
swap(a.base1, b.base1);
swap(a.base2, b.base2);
// ...
swap(a.member1, b.member1);
swap(a.member2, b.member2);
// ...
}
};
``` |
11,574 | <p>I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes .5 seconds. The entire script takes several hours to complete.</p>
<p>I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide.</p>
<p>[edit]
The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element.</p>
<p>I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended.</p>
<p>Here's the code:</p>
<pre><code>repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat
</code></pre>
<p>EDIT: I've rephrased the question to better reflect the correct answer.</p>
| [
{
"answer_id": 11580,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide.</p>\n</blockquote>\n\n<p>The code you post as an example can be as specific as you (or your boss) is comfortable with - more often than not, it's easier to help you with more specific details.</p>\n"
},
{
"answer_id": 11581,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>If the inner loop code is a reasonable length, I don't see any reason you can't post it. I think Stack Overflow is intended to encompass both general and specific questions.</p>\n"
},
{
"answer_id": 28629,
"author": "Mike Heinz",
"author_id": 1565,
"author_profile": "https://Stackoverflow.com/users/1565",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is almost certainly the select. Is there anyway you could extract all the text at once then iterate over internal variables?</p>\n"
},
{
"answer_id": 50651,
"author": "Eric",
"author_id": 5277,
"author_profile": "https://Stackoverflow.com/users/5277",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using InDesign or InDesign Server? How many pages is your document (or what other information can you tell us about your document/ID setup)?</p>\n\n<p>I do a lot of InDesign Server development. You could be seeing slow-downs for a couple of reasons that aren't necessarily code related.</p>\n\n<p>Right now, I'm generating 100-300 page documents almost completely from script/xml in about 100 seconds (you may be doing something much larger).</p>\n"
},
{
"answer_id": 230204,
"author": "JPLemme",
"author_id": 1019,
"author_profile": "https://Stackoverflow.com/users/1019",
"pm_score": 2,
"selected": true,
"text": "<p>I figured this one out.</p>\n\n<p>The document contains a bunch of data tables. In all, there are about 7,000 data points that need to be exported. I was creating one root element with 7,000 children.</p>\n\n<p>Don't do that. Adding each child to the root element got slower and slower until at about 5,000 children AppleScript timed out and the program aborted.</p>\n\n<p>The solution was to make my code more brittle by creating ~480 children off the root, with each child having about 16 grandchildren. Same number of nodes, but the code now runs fast enough. (It still takes about 40 minutes to process the document, but that's infinitely less time than infinity.)</p>\n\n<p>Incidentally, the original 7,000 children plan wasn't as stupid or as lazy as it appears. The new solution is forcing me to link the two tables together using data in the tables that I don't control. The program will now break if there's so much as a space where there shouldn't be one. (But it works.)</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019/"
] | I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes .5 seconds. The entire script takes several hours to complete.
I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide.
[edit]
The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element.
I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended.
Here's the code:
```
repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat
```
EDIT: I've rephrased the question to better reflect the correct answer. | I figured this one out.
The document contains a bunch of data tables. In all, there are about 7,000 data points that need to be exported. I was creating one root element with 7,000 children.
Don't do that. Adding each child to the root element got slower and slower until at about 5,000 children AppleScript timed out and the program aborted.
The solution was to make my code more brittle by creating ~480 children off the root, with each child having about 16 grandchildren. Same number of nodes, but the code now runs fast enough. (It still takes about 40 minutes to process the document, but that's infinitely less time than infinity.)
Incidentally, the original 7,000 children plan wasn't as stupid or as lazy as it appears. The new solution is forcing me to link the two tables together using data in the tables that I don't control. The program will now break if there's so much as a space where there shouldn't be one. (But it works.) |
11,585 | <p>For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...</p>
<pre><code><%@OutputCache Duration="600" VaryByParam="*" %>
</code></pre>
<p>However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.</p>
<p>How do I do this in ASP.Net C#?</p>
| [
{
"answer_id": 11611,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm. You can specify a VaryByCustom attribute on the OutputCache item. The value of this is passed as a parameter to the GetVaryByCustomString method that you can implement in global.asax. The value returned by this method is used as an index into the cached items - if you return the number of comments on the page, for instance, each time a comment is added a new page will be cached.</p>\n\n<p>The caveat to this is that this does not actually clear the cache. If a blog entry gets heavy comment usage, your cache could explode in size with this method.</p>\n\n<p>Alternatively, you could implement the non-changeable bits of the page (the navigation, ads, the actual blog entry) as user controls and implement partial page caching on each of those user controls.</p>\n"
},
{
"answer_id": 11621,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 1,
"selected": false,
"text": "<p>If you change \"*\" to just the parameters the cache should vary on (PostID?) you can do something like this:</p>\n\n<pre><code>//add dependency\nstring key = \"post.aspx?id=\" + PostID.ToString();\nCache[key] = new object();\nResponse.AddCacheItemDependency(key);\n</code></pre>\n\n<p>and when someone adds a comment...</p>\n\n<pre><code>Cache.Remove(key);\n</code></pre>\n\n<p>I guess this would work even with VaryByParam *, since all requests would be tied to the same cache dependency.</p>\n"
},
{
"answer_id": 11641,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 7,
"selected": true,
"text": "<p>I've found the answer I was looking for:</p>\n\n<pre><code>HttpResponse.RemoveOutputCacheItem(\"/caching/CacheForever.aspx\");\n</code></pre>\n"
},
{
"answer_id": 416601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Using Response.AddCacheItemDependency to clear all outputcaches.</p>\n\n<pre><code> public class Page : System.Web.UI.Page\n {\n protected override void OnLoad(EventArgs e)\n {\n try\n {\n string cacheKey = \"cacheKey\";\n object cache = HttpContext.Current.Cache[cacheKey];\n if (cache == null)\n {\n HttpContext.Current.Cache[cacheKey] = DateTime.UtcNow.ToString();\n }\n\n Response.AddCacheItemDependency(cacheKey);\n }\n catch (Exception ex)\n {\n throw new SystemException(ex.Message);\n }\n\n base.OnLoad(e);\n } \n }\n\n\n\n // Clear All OutPutCache Method \n\n public void ClearAllOutPutCache()\n {\n string cacheKey = \"cacheKey\";\n HttpContext.Cache.Remove(cacheKey);\n }\n</code></pre>\n\n<p>This is also can be used in ASP.NET MVC's OutputCachedPage.</p>\n"
},
{
"answer_id": 1990123,
"author": "Brian Scott",
"author_id": 135731,
"author_profile": "https://Stackoverflow.com/users/135731",
"pm_score": 1,
"selected": false,
"text": "<p>why not use the sqlcachedependency on the posts table?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178604.aspx\" rel=\"nofollow noreferrer\">sqlcachedependency msdn</a></p>\n\n<p>This way your not implementing custom cache clearing code and simply refreshing the cache as the content changes in the db?</p>\n"
},
{
"answer_id": 2876701,
"author": "Kevin",
"author_id": 153942,
"author_profile": "https://Stackoverflow.com/users/153942",
"pm_score": 5,
"selected": false,
"text": "<p>The above are fine if you know what pages you want to clear the cache for. In my instance (ASP.NET MVC) I referenced the same data from all over. Therefore, when I did a [save] I wanted to clear cache site wide. This is what worked for me: <a href=\"http://aspalliance.com/668\" rel=\"noreferrer\">http://aspalliance.com/668</a></p>\n\n<p>This is done in the context of an OnActionExecuting filter. It could just as easily be done by overriding OnActionExecuting in a BaseController or something.</p>\n\n<pre><code>HttpContextBase httpContext = filterContext.HttpContext;\nhttpContext.Response.AddCacheItemDependency(\"Pages\");\n</code></pre>\n\n<p>Setup:</p>\n\n<pre><code>protected void Application_Start()\n{\n HttpRuntime.Cache.Insert(\"Pages\", DateTime.Now);\n}\n</code></pre>\n\n<p>Minor Tweak:\nI have a helper which adds \"flash messages\" (Error messages, success messages - \"This item has been successfully saved\", etc). In order to avoid the flash message from showing up on every subsequent GET, I had to invalidate after writing the flash message.</p>\n\n<p>Clearing Cache:</p>\n\n<pre><code>HttpRuntime.Cache.Insert(\"Pages\", DateTime.Now);\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 4727875,
"author": "Julien",
"author_id": 280617,
"author_profile": "https://Stackoverflow.com/users/280617",
"pm_score": -1,
"selected": false,
"text": "<p><code>HttpRuntime.Close()</code> .. I try all method and this is the only that work for me</p>\n"
},
{
"answer_id": 6439754,
"author": "Mohd Adil",
"author_id": 810324,
"author_profile": "https://Stackoverflow.com/users/810324",
"pm_score": 2,
"selected": false,
"text": "<p>On the master page load event, please write the following:</p>\n\n<pre><code>Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));\nResponse.Cache.SetCacheability(HttpCacheability.NoCache);\nResponse.Cache.SetNoStore();\n</code></pre>\n\n<p>and in the logout button click:</p>\n\n<pre><code>Session.Abandon();\nSession.Clear();\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...
```
<%@OutputCache Duration="600" VaryByParam="*" %>
```
However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.
How do I do this in ASP.Net C#? | I've found the answer I was looking for:
```
HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
``` |
11,620 | <p>I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.</p>
<p>How can I kill all the connections to the database so that I can rename it?</p>
| [
{
"answer_id": 11623,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 2,
"selected": false,
"text": "<p>In MS SQL Server Management Studio on the object explorer, right click on the database. In the context menu that follows select 'Tasks -> Take Offline'</p>\n"
},
{
"answer_id": 11624,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 10,
"selected": true,
"text": "<p>The reason that the approach that <a href=\"https://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database/11627#11627\">Adam suggested</a> won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback:</p>\n\n<pre><code>-- set your current connection to use master otherwise you might get an error\n\nuse master\nALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE \n\n--do you stuff here \n\nALTER DATABASE YourDatabase SET MULTI_USER\n</code></pre>\n"
},
{
"answer_id": 11627,
"author": "Adam",
"author_id": 1341,
"author_profile": "https://Stackoverflow.com/users/1341",
"pm_score": 7,
"selected": false,
"text": "<p>Script to accomplish this, replace 'DB_NAME' with the database to kill all connections to:</p>\n\n<pre><code>USE master\nGO\n\nSET NOCOUNT ON\nDECLARE @DBName varchar(50)\nDECLARE @spidstr varchar(8000)\nDECLARE @ConnKilled smallint\nSET @ConnKilled=0\nSET @spidstr = ''\n\nSet @DBName = 'DB_NAME'\nIF db_id(@DBName) < 4\nBEGIN\nPRINT 'Connections to system databases cannot be killed'\nRETURN\nEND\nSELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '\nFROM master..sysprocesses WHERE dbid=db_id(@DBName)\n\nIF LEN(@spidstr) > 0\nBEGIN\nEXEC(@spidstr)\nSELECT @ConnKilled = COUNT(1)\nFROM master..sysprocesses WHERE dbid=db_id(@DBName)\nEND\n</code></pre>\n"
},
{
"answer_id": 11629,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 5,
"selected": false,
"text": "<p>Using SQL Management Studio Express:</p>\n\n<p>In the Object Explorer tree drill down under Management to \"Activity Monitor\" (if you cannot find it there then right click on the database server and select \"Activity Monitor\"). Opening the Activity Monitor, you can view all process info. You should be able to find the locks for the database you're interested in and kill those locks, which will also kill the connection.</p>\n\n<p>You should be able to rename after that. </p>\n"
},
{
"answer_id": 11630,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>ALTER DATABASE [DATABASE_NAME]\nSET SINGLE_USER\nWITH ROLLBACK IMMEDIATE\n</code></pre>\n"
},
{
"answer_id": 11633,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 5,
"selected": false,
"text": "<p>I've always used:</p>\n\n<pre><code>\nALTER DATABASE DB_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE \nGO \nSP_RENAMEDB 'DB_NAME','DB_NAME_NEW'\nGo \nALTER DATABASE DB_NAME_NEW SET MULTI_USER -- set back to multi user \nGO \n</code></pre>\n"
},
{
"answer_id": 12413,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 3,
"selected": false,
"text": "<p>I usually run into that error when I am trying to restore a database I usually just go to the top of the tree in Management Studio and right click and restart the database server (because it's on a development machine, this might not be ideal in production). This is close all database connections.</p>\n"
},
{
"answer_id": 2817992,
"author": "btk",
"author_id": 289255,
"author_profile": "https://Stackoverflow.com/users/289255",
"pm_score": 6,
"selected": false,
"text": "<p>Kill it, and kill it with fire:</p>\n\n<pre><code>USE master\ngo\n\nDECLARE @dbname sysname\nSET @dbname = 'yourdbname'\n\nDECLARE @spid int\nSELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)\nWHILE @spid IS NOT NULL\nBEGIN\nEXECUTE ('KILL ' + @spid)\nSELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid\nEND\n</code></pre>\n"
},
{
"answer_id": 4161622,
"author": "alirobe",
"author_id": 114149,
"author_profile": "https://Stackoverflow.com/users/114149",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how to reliably this sort of thing in MS SQL Server Management Studio 2008 (may work for other versions too):</p>\n\n<ol>\n<li>In the Object Explorer Tree, right click the root database server (with the green arrow), then click activity monitor.</li>\n<li>Open the processes tab in the activity monitor, select the 'databases' drop down menu, and filter by the database you want.</li>\n<li>Right click the DB in Object Explorer and start a 'Tasks -> Take Offline' task. Leave this running in the background while you...</li>\n<li>Safely shut down whatever you can.</li>\n<li>Kill all remaining processes from the process tab.</li>\n<li>Bring the DB back online.</li>\n<li>Rename the DB.</li>\n<li>Bring your service back online and point it to the new DB.</li>\n</ol>\n"
},
{
"answer_id": 4183746,
"author": "Sanjay Saxena",
"author_id": 508165,
"author_profile": "https://Stackoverflow.com/users/508165",
"pm_score": 2,
"selected": false,
"text": "<p>Right click on the database name, click on Property to get property window, Open the Options tab and change the \"Restrict Access\" property from Multi User to Single User. When you hit on OK button, it will prompt you to closes all open connection, select \"Yes\" and you are set to rename the database....</p>\n"
},
{
"answer_id": 4605373,
"author": "NJV",
"author_id": 564076,
"author_profile": "https://Stackoverflow.com/users/564076",
"pm_score": 4,
"selected": false,
"text": "<p>Take offline takes a while and sometimes I experience some problems with that..</p>\n\n<p>Most solid way in my opinion:</p>\n\n<p><strong>Detach</strong>\nRight click DB -> Tasks -> Detach...\ncheck \"Drop Connections\" \nOk</p>\n\n<p><strong>Reattach</strong>\nRight click Databases -> Attach..\nAdd... -> select your database, and change the Attach As column to your desired database name.\nOk</p>\n"
},
{
"answer_id": 7114816,
"author": "aikeru",
"author_id": 76840,
"author_profile": "https://Stackoverflow.com/users/76840",
"pm_score": 2,
"selected": false,
"text": "<p>Another \"kill it with fire\" approach is to just restart the MSSQLSERVER service.\nI like to do stuff from the commandline. Pasting this exactly into CMD will do it:\nNET STOP MSSQLSERVER & NET START MSSQLSERVER</p>\n\n<p>Or open \"services.msc\" and find \"SQL Server (MSSQLSERVER)\" and right-click, select \"restart\".</p>\n\n<p>This will \"for sure, for sure\" kill ALL connections to ALL databases running on that instance.</p>\n\n<p>(I like this better than many approaches that change and change back the configuration on the server/database)</p>\n"
},
{
"answer_id": 8653964,
"author": "Lars Timenes",
"author_id": 1118999,
"author_profile": "https://Stackoverflow.com/users/1118999",
"pm_score": 2,
"selected": false,
"text": "<p>The option working for me in this scenario is as follows: </p>\n\n<ol>\n<li>Start the \"Detach\" operation on the database in question. This wil open a window (in SQL 2005) displaying the active connections that prevents actions on the DB. </li>\n<li>Kill the active connections, cancel the detach-operation. </li>\n<li>The database should now be available for restoring.</li>\n</ol>\n"
},
{
"answer_id": 9093487,
"author": "Talha",
"author_id": 1023687,
"author_profile": "https://Stackoverflow.com/users/1023687",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Select 'Kill '+ CAST(p.spid AS VARCHAR)KillCommand into #temp\nfrom master.dbo.sysprocesses p (nolock)\njoin master..sysdatabases d (nolock) on p.dbid = d.dbid\nWhere d.[name] = 'your db name'\n\nDeclare @query nvarchar(max)\n--Select * from #temp\nSelect @query =STUFF(( \n select ' ' + KillCommand from #temp\n FOR XML PATH('')),1,1,'') \nExecute sp_executesql @query \nDrop table #temp\n</code></pre>\n\n<p>use the 'master' database and run this query, it will kill all the active connections from your database.</p>\n"
},
{
"answer_id": 10393091,
"author": "The Coder",
"author_id": 1129108,
"author_profile": "https://Stackoverflow.com/users/1129108",
"pm_score": 2,
"selected": false,
"text": "<p>These didn't work for me (SQL2008 Enterprise), I also couldn't see any running processes or users connected to the DB. Restarting the server (Right click on Sql Server in Management Studio and pick Restart) allowed me to restore the DB.</p>\n"
},
{
"answer_id": 10995373,
"author": "Ilmar",
"author_id": 1451048,
"author_profile": "https://Stackoverflow.com/users/1451048",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using SQL Server 2008 R2, my DB was already set for single user and there was a connection that restricted any action on the database. Thus the recommended <a href=\"https://stackoverflow.com/a/11624/1451048\">SQLMenace's</a> solution responded with error. <a href=\"http://blog.tech-cats.com/2008/01/kill-all-database-connections-to-sql.html\" rel=\"nofollow noreferrer\">Here is one that worked in my case</a>.</p>\n"
},
{
"answer_id": 11536813,
"author": "santhosh kumar",
"author_id": 1534044,
"author_profile": "https://Stackoverflow.com/users/1534044",
"pm_score": 4,
"selected": false,
"text": "<pre><code>ALTER DATABASE [Test]\nSET OFFLINE WITH ROLLBACK IMMEDIATE\n\nALTER DATABASE [Test]\nSET ONLINE\n</code></pre>\n"
},
{
"answer_id": 23991847,
"author": "mehdi lotfi",
"author_id": 1407421,
"author_profile": "https://Stackoverflow.com/users/1407421",
"pm_score": -1,
"selected": false,
"text": "<p>You can Use SP_Who command and kill all process that use your database and then rename your database.</p>\n"
},
{
"answer_id": 30097342,
"author": "Ray Krungkaew",
"author_id": 1554116,
"author_profile": "https://Stackoverflow.com/users/1554116",
"pm_score": 0,
"selected": false,
"text": "<p>I use sp_who to get list of all process in database. This is better because you may want to review which process to kill.</p>\n\n<pre><code>declare @proc table(\n SPID bigint,\n Status nvarchar(255),\n Login nvarchar(255),\n HostName nvarchar(255),\n BlkBy nvarchar(255),\n DBName nvarchar(255),\n Command nvarchar(MAX),\n CPUTime bigint,\n DiskIO bigint,\n LastBatch nvarchar(255),\n ProgramName nvarchar(255),\n SPID2 bigint,\n REQUESTID bigint\n)\n\ninsert into @proc\nexec sp_who2\n\nselect *, KillCommand = concat('kill ', SPID, ';')\nfrom @proc\n</code></pre>\n\n<p><strong>Result</strong><br>\nYou can use command in KillCommand column to kill the process you want to.</p>\n\n<pre><code>SPID KillCommand\n26 kill 26;\n27 kill 27;\n28 kill 28;\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] | I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.
How can I kill all the connections to the database so that I can rename it? | The reason that the approach that [Adam suggested](https://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database/11627#11627) won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback:
```
-- set your current connection to use master otherwise you might get an error
use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do you stuff here
ALTER DATABASE YourDatabase SET MULTI_USER
``` |
11,635 | <p>What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?</p>
<p>Please indicate whether the methods are Unicode-friendly and how portable they are.</p>
| [
{
"answer_id": 11653,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you are looking for a method and not a magic function that already exists, there is frankly no better way. We could all write code snippets with clever tricks for limited character sets, but at the end of the day at somepoint you have to convert the characters.</p>\n\n<p>The best approach for this conversion is to do so prior to the comparison. This allows you a good deal of flexibility when it comes to encoding schemes, which your actual comparison operator should be ignorant of.</p>\n\n<p>You can of course 'hide' this conversion behind your own string function or class, but you still need to convert the strings prior to comparison.</p>\n"
},
{
"answer_id": 11654,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 4,
"selected": false,
"text": "<p>Visual C++ string functions supporting unicode: <a href=\"http://msdn.microsoft.com/en-us/library/cc194799.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/cc194799.aspx</a></p>\n\n<p>the one you are probably looking for is <code>_wcsnicmp</code></p>\n"
},
{
"answer_id": 11669,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 4,
"selected": false,
"text": "<p>FYI, <code>strcmp()</code> and <code>stricmp()</code> are vulnerable to buffer overflow, since they just process until they hit a null terminator. It's safer to use <code>_strncmp()</code> and <a href=\"http://msdn.microsoft.com/en-us/library/chd90w8e(VS.80).aspx\" rel=\"noreferrer\"><code>_strnicmp()</code></a>.</p>\n"
},
{
"answer_id": 11670,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": false,
"text": "<p>I've had good experience using the <a href=\"http://icu-project.org/userguide/\" rel=\"nofollow noreferrer\">International Components for Unicode libraries</a> - they're extremely powerful, and provide methods for conversion, locale support, date and time rendering, case mapping (which you don't seem to want), and <a href=\"http://icu-project.org/userguide/Collate_Intro.html\" rel=\"nofollow noreferrer\">collation</a>, which includes case- and accent-insensitive comparison (and more). I've only used the C++ version of the libraries, but they appear to have a Java version as well. </p>\n\n<p>Methods exist to perform normalized compares as referred to by @Coincoin, and can even account for locale - for example (and this a sorting example, not strictly equality), traditionally in Spanish (in Spain), the letter combination \"ll\" sorts between \"l\" and \"m\", so \"lz\" < \"ll\" < \"ma\".</p>\n"
},
{
"answer_id": 11675,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 6,
"selected": false,
"text": "<p>Are you talking about a dumb case insensitive compare or a full normalized Unicode compare?</p>\n\n<p>A dumb compare will not find strings that might be the same but are not binary equal. </p>\n\n<p>Example:</p>\n\n<pre><code>U212B (ANGSTROM SIGN)\nU0041 (LATIN CAPITAL LETTER A) + U030A (COMBINING RING ABOVE)\nU00C5 (LATIN CAPITAL LETTER A WITH RING ABOVE).\n</code></pre>\n\n<p>Are all equivalent but they also have different binary representations.</p>\n\n<p>That said, <a href=\"http://unicode.org/reports/tr15/\" rel=\"nofollow noreferrer\">Unicode Normalization</a> should be a mandatory read especially if you plan on supporting Hangul, Thaï and other asian languages.</p>\n\n<p>Also, IBM pretty much patented most optimized Unicode algorithms and made them publicly available. They also maintain an implementation : <a href=\"http://site.icu-project.org/\" rel=\"nofollow noreferrer\">IBM ICU</a></p>\n"
},
{
"answer_id": 11679,
"author": "Adam",
"author_id": 1366,
"author_profile": "https://Stackoverflow.com/users/1366",
"pm_score": 4,
"selected": false,
"text": "<p>I'm trying to cobble together a good answer from all the posts, so help me edit this:</p>\n\n<p>Here is a method of doing this, although it does transforming the strings, and is not Unicode friendly, it should be portable which is a plus:</p>\n\n<pre><code>bool caseInsensitiveStringCompare( const std::string& str1, const std::string& str2 ) {\n std::string str1Cpy( str1 );\n std::string str2Cpy( str2 );\n std::transform( str1Cpy.begin(), str1Cpy.end(), str1Cpy.begin(), ::tolower );\n std::transform( str2Cpy.begin(), str2Cpy.end(), str2Cpy.begin(), ::tolower );\n return ( str1Cpy == str2Cpy );\n}\n</code></pre>\n\n<p>From what I have read this is more portable than stricmp() because stricmp() is not in fact part of the std library, but only implemented by most compiler vendors.</p>\n\n<p>To get a truly Unicode friendly implementation it appears you must go outside the std library. One good 3rd party library is the <a href=\"http://www.icu-project.org/\" rel=\"noreferrer\">IBM ICU (International Components for Unicode)</a></p>\n\n<p>Also <strong>boost::iequals</strong> provides a fairly good utility for doing this sort of comparison.</p>\n"
},
{
"answer_id": 11685,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 6,
"selected": false,
"text": "<p>If you are on a POSIX system, you can use <a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/strcasecmp.html\" rel=\"noreferrer\">strcasecmp</a>. This function is not part of standard C, though, nor is it available on Windows. This will perform a case-insensitive comparison on 8-bit chars, so long as the locale is POSIX. If the locale is not POSIX, the results are undefined (so it might do a localized compare, or it might not). A wide-character equivalent is not available.</p>\n\n<p>Failing that, a large number of historic C library implementations have the functions stricmp() and strnicmp(). Visual C++ on Windows renamed all of these by prefixing them with an underscore because they aren’t part of the ANSI standard, so on that system they’re called <a href=\"http://msdn.microsoft.com/en-us/library/k59z8dwe.aspx\" rel=\"noreferrer\">_stricmp or _strnicmp</a>. Some libraries may also have wide-character or multibyte equivalent functions (typically named e.g. wcsicmp, mbcsicmp and so on).</p>\n\n<p>C and C++ are both largely ignorant of internationalization issues, so there's no good solution to this problem, except to use a third-party library. Check out <a href=\"http://www.icu-project.org/\" rel=\"noreferrer\">IBM ICU (International Components for Unicode)</a> if you need a robust library for C/C++. ICU is for both Windows and Unix systems.</p>\n"
},
{
"answer_id": 27813,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 5,
"selected": false,
"text": "<p>My first thought for a non-unicode version was to do something like this:</p>\n<pre><code>bool caseInsensitiveStringCompare(const string& str1, const string& str2) {\n if (str1.size() != str2.size()) {\n return false;\n }\n for (string::const_iterator c1 = str1.begin(), c2 = str2.begin(); c1 != str1.end(); ++c1, ++c2) {\n if (tolower(static_cast<unsigned char>(*c1)) != tolower(static_cast<unsigned char>(*c2))) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 297355,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a case-insensitive version of char_traits for use with std::basic_string in order to generate a std::string that is not case-sensitive when doing comparisons, searches, etc using the built-in std::basic_string member functions.</p>\n\n<p>So in other words, I wanted to do something like this.</p>\n\n<pre><code>std::string a = \"Hello, World!\";\nstd::string b = \"hello, world!\";\n\nassert( a == b );\n</code></pre>\n\n<p>...which std::string can't handle. Here's the usage of my new char_traits:</p>\n\n<pre><code>std::istring a = \"Hello, World!\";\nstd::istring b = \"hello, world!\";\n\nassert( a == b );\n</code></pre>\n\n<p>...and here's the implementation:</p>\n\n<pre><code>/* ---\n\n Case-Insensitive char_traits for std::string's\n\n Use:\n\n To declare a std::string which preserves case but ignores case in comparisons & search,\n use the following syntax:\n\n std::basic_string<char, char_traits_nocase<char> > noCaseString;\n\n A typedef is declared below which simplifies this use for chars:\n\n typedef std::basic_string<char, char_traits_nocase<char> > istring;\n\n --- */\n\n template<class C>\n struct char_traits_nocase : public std::char_traits<C>\n {\n static bool eq( const C& c1, const C& c2 )\n { \n return ::toupper(c1) == ::toupper(c2); \n }\n\n static bool lt( const C& c1, const C& c2 )\n { \n return ::toupper(c1) < ::toupper(c2);\n }\n\n static int compare( const C* s1, const C* s2, size_t N )\n {\n return _strnicmp(s1, s2, N);\n }\n\n static const char* find( const C* s, size_t N, const C& a )\n {\n for( size_t i=0 ; i<N ; ++i )\n {\n if( ::toupper(s[i]) == ::toupper(a) ) \n return s+i ;\n }\n return 0 ;\n }\n\n static bool eq_int_type( const int_type& c1, const int_type& c2 )\n { \n return ::toupper(c1) == ::toupper(c2) ; \n } \n };\n\n template<>\n struct char_traits_nocase<wchar_t> : public std::char_traits<wchar_t>\n {\n static bool eq( const wchar_t& c1, const wchar_t& c2 )\n { \n return ::towupper(c1) == ::towupper(c2); \n }\n\n static bool lt( const wchar_t& c1, const wchar_t& c2 )\n { \n return ::towupper(c1) < ::towupper(c2);\n }\n\n static int compare( const wchar_t* s1, const wchar_t* s2, size_t N )\n {\n return _wcsnicmp(s1, s2, N);\n }\n\n static const wchar_t* find( const wchar_t* s, size_t N, const wchar_t& a )\n {\n for( size_t i=0 ; i<N ; ++i )\n {\n if( ::towupper(s[i]) == ::towupper(a) ) \n return s+i ;\n }\n return 0 ;\n }\n\n static bool eq_int_type( const int_type& c1, const int_type& c2 )\n { \n return ::towupper(c1) == ::towupper(c2) ; \n } \n };\n\n typedef std::basic_string<char, char_traits_nocase<char> > istring;\n typedef std::basic_string<wchar_t, char_traits_nocase<wchar_t> > iwstring;\n</code></pre>\n"
},
{
"answer_id": 315463,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 9,
"selected": true,
"text": "<p>Boost includes a handy algorithm for this:</p>\n\n<pre><code>#include <boost/algorithm/string.hpp>\n// Or, for fewer header dependencies:\n//#include <boost/algorithm/string/predicate.hpp>\n\nstd::string str1 = \"hello, world!\";\nstd::string str2 = \"HELLO, WORLD!\";\n\nif (boost::iequals(str1, str2))\n{\n // Strings are identical\n}\n</code></pre>\n"
},
{
"answer_id": 316573,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 2,
"selected": false,
"text": "<p>Just a note on whatever method you finally choose, if that method happens to include the use of <code>strcmp</code> that some answers suggest:</p>\n\n<p><code>strcmp</code> doesn't work with Unicode data in general. In general, it doesn't even work with byte-based Unicode encodings, such as utf-8, since <code>strcmp</code> only makes byte-per-byte comparisons and Unicode code points encoded in utf-8 can take more than 1 byte. The only specific Unicode case <code>strcmp</code> properly handle is when a string encoded with a byte-based encoding contains only code points below U+00FF - then the byte-per-byte comparison is enough.</p>\n"
},
{
"answer_id": 332713,
"author": "bradtgmurray",
"author_id": 1546,
"author_profile": "https://Stackoverflow.com/users/1546",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <code>strcasecmp</code> on Unix, or <code>stricmp</code> on Windows.</p>\n\n<p>One thing that hasn't been mentioned so far is that if you are using stl strings with these methods, it's useful to first compare the length of the two strings, since this information is already available to you in the string class. This could prevent doing the costly string comparison if the two strings you are comparing aren't even the same length in the first place.</p>\n"
},
{
"answer_id": 2886502,
"author": "Dean Harding",
"author_id": 241462,
"author_profile": "https://Stackoverflow.com/users/241462",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://www.boost.org/doc/libs/1_43_0/doc/html/string_algo.html\" rel=\"noreferrer\">Boost.String</a> library has a lot of algorithms for doing case-insenstive comparisons and so on.</p>\n\n<p>You could implement your own, but why bother when it's already been done?</p>\n"
},
{
"answer_id": 2886589,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 7,
"selected": false,
"text": "<p>Take advantage of the standard <code>char_traits</code>. Recall that a <code>std::string</code> is in fact a typedef for <code>std::basic_string<char></code>, or more explicitly, <code>std::basic_string<char, std::char_traits<char> ></code>. The <code>char_traits</code> type describes how characters compare, how they copy, how they cast etc. All you need to do is typedef a new string over <code>basic_string</code>, and provide it with your own custom <code>char_traits</code> that compare case insensitively.</p>\n\n<pre><code>struct ci_char_traits : public char_traits<char> {\n static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }\n static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }\n static bool lt(char c1, char c2) { return toupper(c1) < toupper(c2); }\n static int compare(const char* s1, const char* s2, size_t n) {\n while( n-- != 0 ) {\n if( toupper(*s1) < toupper(*s2) ) return -1;\n if( toupper(*s1) > toupper(*s2) ) return 1;\n ++s1; ++s2;\n }\n return 0;\n }\n static const char* find(const char* s, int n, char a) {\n while( n-- > 0 && toupper(*s) != toupper(a) ) {\n ++s;\n }\n return s;\n }\n};\n\ntypedef std::basic_string<char, ci_char_traits> ci_string;\n</code></pre>\n\n<p>The details are on <a href=\"http://www.gotw.ca/gotw/029.htm\" rel=\"noreferrer\">Guru of The Week number 29</a>.</p>\n"
},
{
"answer_id": 4119881,
"author": "Timmmm",
"author_id": 265521,
"author_profile": "https://Stackoverflow.com/users/265521",
"pm_score": 7,
"selected": false,
"text": "<p>The trouble with boost is that you have to link with and depend on boost. Not easy in some cases (e.g. android).</p>\n<p>And using char_traits means <em>all</em> your comparisons are case insensitive, which isn't usually what you want.</p>\n<p>This should suffice. It should be reasonably efficient. Doesn't handle unicode or anything though.</p>\n<pre><code>bool iequals(const string& a, const string& b)\n{\n unsigned int sz = a.size();\n if (b.size() != sz)\n return false;\n for (unsigned int i = 0; i < sz; ++i)\n if (tolower(a[i]) != tolower(b[i]))\n return false;\n return true;\n}\n</code></pre>\n<p>Update: Bonus C++14 version (<code>#include <algorithm></code>):</p>\n<pre><code>bool iequals(const string& a, const string& b)\n{\n return std::equal(a.begin(), a.end(),\n b.begin(), b.end(),\n [](char a, char b) {\n return tolower(a) == tolower(b);\n });\n}\n</code></pre>\n<hr />\n<p>Update: C++20 version using <code>std::ranges</code>:</p>\n<pre><code>#include <ranges>\n#include <algorithm>\n#include <string>\n\nbool iequals(const std::string_view& lhs, const std::string_view& rhs) {\n auto to_lower{ std::ranges::views::transform(std::tolower) };\n return std::ranges::equal(lhs | to_lower, rhs | to_lower);\n}\n</code></pre>\n"
},
{
"answer_id": 10330109,
"author": "Igor Milyakov",
"author_id": 1358161,
"author_profile": "https://Stackoverflow.com/users/1358161",
"pm_score": 5,
"selected": false,
"text": "<p>boost::iequals is not utf-8 compatible in the case of string.\nYou can use <a href=\"http://www.boost.org/doc/libs/1_49_0/libs/locale/doc/html/index.html\">boost::locale</a>.</p>\n\n<pre><code>comparator<char,collator_base::secondary> cmpr;\ncout << (cmpr(str1, str2) ? \"str1 < str2\" : \"str1 >= str2\") << endl;\n</code></pre>\n\n<ul>\n<li>Primary -- ignore accents and character case, comparing base letters only. For example \"facade\" and \"Façade\" are the same.</li>\n<li>Secondary -- ignore character case but consider accents. \"facade\" and \"façade\" are different but \"Façade\" and \"façade\" are the same.</li>\n<li>Tertiary -- consider both case and accents: \"Façade\" and \"façade\" are different. Ignore punctuation.</li>\n<li>Quaternary -- consider all case, accents, and punctuation. The words must be identical in terms of Unicode representation.</li>\n<li>Identical -- as quaternary, but compare code points as well.</li>\n</ul>\n"
},
{
"answer_id": 15748771,
"author": "michaelhanson",
"author_id": 448891,
"author_profile": "https://Stackoverflow.com/users/448891",
"pm_score": 2,
"selected": false,
"text": "<p>As of early 2013, the ICU project, maintained by IBM, is a pretty good answer to this.</p>\n\n<p><a href=\"http://site.icu-project.org/\" rel=\"nofollow\">http://site.icu-project.org/</a></p>\n\n<p>ICU is a \"complete, portable Unicode library that closely tracks industry standards.\" For the specific problem of string comparison, the Collation object does what you want.</p>\n\n<p>The Mozilla Project adopted ICU for internationalization in Firefox in mid-2012; you can track the engineering discussion, including issues of build systems and data file size, here:</p>\n\n<ul>\n<li><a href=\"https://groups.google.com/forum/#!topic/mozilla.dev.platform/sVVpS2sKODw\" rel=\"nofollow\">https://groups.google.com/forum/#!topic/mozilla.dev.platform/sVVpS2sKODw</a></li>\n<li><a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=724529\" rel=\"nofollow\">https://bugzilla.mozilla.org/show_bug.cgi?id=724529</a> (tracker)</li>\n<li><a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=724531\" rel=\"nofollow\">https://bugzilla.mozilla.org/show_bug.cgi?id=724531</a> (build system)</li>\n</ul>\n"
},
{
"answer_id": 17330790,
"author": "Neutrino",
"author_id": 954927,
"author_profile": "https://Stackoverflow.com/users/954927",
"pm_score": 3,
"selected": false,
"text": "<p>For my basic case insensitive string comparison needs I prefer not to have to use an external library, nor do I want a separate string class with case insensitive traits that is incompatible with all my other strings.</p>\n\n<p>So what I've come up with is this:</p>\n\n\n\n<pre><code>bool icasecmp(const string& l, const string& r)\n{\n return l.size() == r.size()\n && equal(l.cbegin(), l.cend(), r.cbegin(),\n [](string::value_type l1, string::value_type r1)\n { return toupper(l1) == toupper(r1); });\n}\n\nbool icasecmp(const wstring& l, const wstring& r)\n{\n return l.size() == r.size()\n && equal(l.cbegin(), l.cend(), r.cbegin(),\n [](wstring::value_type l1, wstring::value_type r1)\n { return towupper(l1) == towupper(r1); });\n}\n</code></pre>\n\n<p>A simple function with one overload for char and another for whar_t. Doesn't use anything non-standard so should be fine on any platform.</p>\n\n<p>The equality comparison won't consider issues like variable length encoding and Unicode normalization, but basic_string has no support for that that I'm aware of anyway and it isn't normally an issue.</p>\n\n<p>In cases where more sophisticated lexicographical manipulation of text is required, then you simply have to use a third party library like Boost, which is to be expected.</p>\n"
},
{
"answer_id": 17866339,
"author": "reubenjohn",
"author_id": 2110869,
"author_profile": "https://Stackoverflow.com/users/2110869",
"pm_score": 2,
"selected": false,
"text": "<p>Just use <code>strcmp()</code> for case sensitive and <code>strcmpi()</code> or <code>stricmp()</code> for case insensitive comparison. Which are both in the header file <code><string.h></code></p>\n\n<p><strong>format:</strong></p>\n\n<pre><code>int strcmp(const char*,const char*); //for case sensitive\nint strcmpi(const char*,const char*); //for case insensitive\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>string a=\"apple\",b=\"ApPlE\",c=\"ball\";\nif(strcmpi(a.c_str(),b.c_str())==0) //(if it is a match it will return 0)\n cout<<a<<\" and \"<<b<<\" are the same\"<<\"\\n\";\nif(strcmpi(a.c_str(),b.c_str()<0)\n cout<<a[0]<<\" comes before ball \"<<b[0]<<\", so \"<<a<<\" comes before \"<<b;\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<p><em>apple and ApPlE are the same</em></p>\n\n<p><em>a comes before b, so apple comes before ball</em></p>\n"
},
{
"answer_id": 28869082,
"author": "user4578093",
"author_id": 4578093,
"author_profile": "https://Stackoverflow.com/users/4578093",
"pm_score": -1,
"selected": false,
"text": "<pre class=\"lang-c++ prettyprint-override\"><code>bool insensitive_c_compare(char A, char B){\n static char mid_c = ('Z' + 'a') / 2 + 'Z';\n static char up2lo = 'A' - 'a'; /// the offset between upper and lowers\n\n if ('a' >= A and A >= 'z' or 'A' >= A and 'Z' >= A)\n if ('a' >= B and B >= 'z' or 'A' >= B and 'Z' >= B)\n /// check that the character is infact a letter\n /// (trying to turn a 3 into an E would not be pretty!)\n {\n if (A > mid_c and B > mid_c or A < mid_c and B < mid_c)\n {\n return A == B;\n }\n else\n {\n if (A > mid_c)\n A = A - 'a' + 'A'; \n if (B > mid_c)/// convert all uppercase letters to a lowercase ones\n B = B - 'a' + 'A';\n /// this could be changed to B = B + up2lo;\n return A == B;\n }\n }\n}\n</code></pre>\n\n<p>this could probably be made much more efficient, but here is a bulky version with all its bits bare.</p>\n\n<p>not all that portable, but works well with whatever is on my computer (no idea, I am of pictures not words)</p>\n"
},
{
"answer_id": 28900301,
"author": "smibe",
"author_id": 2239672,
"author_profile": "https://Stackoverflow.com/users/2239672",
"pm_score": 0,
"selected": false,
"text": "<p>If you have to compare a source string more often with other strings one elegant solution is to use regex.</p>\n\n<pre><code>std::wstring first = L\"Test\";\nstd::wstring second = L\"TEST\";\n\nstd::wregex pattern(first, std::wregex::icase);\nbool isEqual = std::regex_match(second, pattern);\n</code></pre>\n"
},
{
"answer_id": 30193591,
"author": "Craig Stoddard",
"author_id": 4891847,
"author_profile": "https://Stackoverflow.com/users/4891847",
"pm_score": -1,
"selected": false,
"text": "<p>An easy way to compare strings that are only different by lowercase and capitalized characters is to do an ascii comparison. All capital and lowercase letters differ by 32 bits in the ascii table, using this information we have the following...</p>\n\n<pre><code> for( int i = 0; i < string2.length(); i++)\n {\n if (string1[i] == string2[i] || int(string1[i]) == int(string2[j])+32 ||int(string1[i]) == int(string2[i])-32) \n {\n count++;\n continue;\n }\n else \n {\n break;\n }\n if(count == string2.length())\n {\n //then we have a match\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32619426,
"author": "Brian Rodriguez",
"author_id": 4859885,
"author_profile": "https://Stackoverflow.com/users/4859885",
"pm_score": 4,
"selected": false,
"text": "<p>See <a href=\"http://www.cplusplus.com/reference/algorithm/lexicographical_compare/\" rel=\"noreferrer\"><code>std::lexicographical_compare</code></a>:</p>\n\n<pre><code>// lexicographical_compare example\n#include <iostream> // std::cout, std::boolalpha\n#include <algorithm> // std::lexicographical_compare\n#include <cctype> // std::tolower\n\n// a case-insensitive comparison function:\nbool mycomp (char c1, char c2) {\n return std::tolower(c1) < std::tolower(c2);\n}\n\nint main () {\n char foo[] = \"Apple\";\n char bar[] = \"apartment\";\n\n std::cout << std::boolalpha;\n\n std::cout << \"Comparing foo and bar lexicographically (foo < bar):\\n\";\n\n std::cout << \"Using default comparison (operator<): \";\n std::cout << std::lexicographical_compare(foo, foo + 5, bar, bar + 9);\n std::cout << '\\n';\n\n std::cout << \"Using mycomp as comparison object: \";\n std::cout << std::lexicographical_compare(foo, foo + 5, bar, bar + 9, mycomp);\n std::cout << '\\n';\n\n return 0;\n}\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/d38d82d1255c8f71\" rel=\"noreferrer\">Demo</a></p>\n"
},
{
"answer_id": 32833792,
"author": "Simon Richter",
"author_id": 613064,
"author_profile": "https://Stackoverflow.com/users/613064",
"pm_score": 2,
"selected": false,
"text": "<p>Late to the party, but here is a variant that uses <code>std::locale</code>, and thus correctly handles Turkish:</p>\n\n<pre><code>auto tolower = std::bind1st(\n std::mem_fun(\n &std::ctype<char>::tolower),\n &std::use_facet<std::ctype<char> >(\n std::locale()));\n</code></pre>\n\n<p>gives you a functor that uses the active locale to convert characters to lowercase, which you can then use via <code>std::transform</code> to generate lower-case strings:</p>\n\n<pre><code>std::string left = \"fOo\";\ntransform(left.begin(), left.end(), left.begin(), tolower);\n</code></pre>\n\n<p>This also works for <code>wchar_t</code> based strings.</p>\n"
},
{
"answer_id": 34739420,
"author": "DavidS",
"author_id": 2338792,
"author_profile": "https://Stackoverflow.com/users/2338792",
"pm_score": 3,
"selected": false,
"text": "<p>Doing this without using Boost can be done by getting the C string pointer with <code>c_str()</code> and using <code>strcasecmp</code>:</p>\n\n<pre><code>std::string str1 =\"aBcD\";\nstd::string str2 = \"AbCd\";;\nif (strcasecmp(str1.c_str(), str2.c_str()) == 0)\n{\n //case insensitive equal \n}\n</code></pre>\n"
},
{
"answer_id": 39795447,
"author": "kyb",
"author_id": 3743145,
"author_profile": "https://Stackoverflow.com/users/3743145",
"pm_score": 4,
"selected": false,
"text": "<p>Short and nice. No other dependencies, than <em>extended</em> std C lib.</p>\n\n<pre><code>strcasecmp(str1.c_str(), str2.c_str()) == 0\n</code></pre>\n\n<p>returns <strong>true</strong> if <code>str1</code> and <code>str2</code> are equal.\n<code>strcasecmp</code> may not exist, there could be analogs <code>stricmp</code>, <code>strcmpi</code>, etc.</p>\n\n<p>Example code:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <string.h> //For strcasecmp(). Also could be found in <mem.h>\n\nusing namespace std;\n\n/// Simple wrapper\ninline bool str_ignoreCase_cmp(std::string const& s1, std::string const& s2) {\n if(s1.length() != s2.length())\n return false; // optimization since std::string holds length in variable.\n return strcasecmp(s1.c_str(), s2.c_str()) == 0;\n}\n\n/// Function object - comparator\nstruct StringCaseInsensetiveCompare {\n bool operator()(std::string const& s1, std::string const& s2) {\n if(s1.length() != s2.length())\n return false; // optimization since std::string holds length in variable.\n return strcasecmp(s1.c_str(), s2.c_str()) == 0;\n }\n bool operator()(const char *s1, const char * s2){ \n return strcasecmp(s1,s2)==0;\n }\n};\n\n\n/// Convert bool to string\ninline char const* bool2str(bool b){ return b?\"true\":\"false\"; }\n\nint main()\n{\n cout<< bool2str(strcasecmp(\"asd\",\"AsD\")==0) <<endl;\n cout<< bool2str(strcasecmp(string{\"aasd\"}.c_str(),string{\"AasD\"}.c_str())==0) <<endl;\n StringCaseInsensetiveCompare cmp;\n cout<< bool2str(cmp(\"A\",\"a\")) <<endl;\n cout<< bool2str(cmp(string{\"Aaaa\"},string{\"aaaA\"})) <<endl;\n cout<< bool2str(str_ignoreCase_cmp(string{\"Aaaa\"},string{\"aaaA\"})) <<endl;\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>true\ntrue\ntrue\ntrue\ntrue\n</code></pre>\n"
},
{
"answer_id": 43226907,
"author": "vine'th",
"author_id": 478028,
"author_profile": "https://Stackoverflow.com/users/478028",
"pm_score": 4,
"selected": false,
"text": "<pre><code>str1.size() == str2.size() && std::equal(str1.begin(), str1.end(), str2.begin(), [](auto a, auto b){return std::tolower(a)==std::tolower(b);})\n</code></pre>\n\n<p>You can use the above code in C++14 if you are not in a position to use boost. You have to use <code>std::towlower</code> for wide chars.</p>\n"
},
{
"answer_id": 45899185,
"author": "Jagadeesh Pulamarasetti",
"author_id": 4439625,
"author_profile": "https://Stackoverflow.com/users/4439625",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like above solutions aren't using compare method and implementing total again so here is my solution and hope it works for you (It's working fine).</p>\n\n<pre><code>#include<iostream>\n#include<cstring>\n#include<cmath>\nusing namespace std;\nstring tolow(string a)\n{\n for(unsigned int i=0;i<a.length();i++)\n {\n a[i]=tolower(a[i]);\n }\n return a;\n}\nint main()\n{\n string str1,str2;\n cin>>str1>>str2;\n int temp=tolow(str1).compare(tolow(str2));\n if(temp>0)\n cout<<1;\n else if(temp==0)\n cout<<0;\n else\n cout<<-1;\n}\n</code></pre>\n"
},
{
"answer_id": 49896180,
"author": "DAme",
"author_id": 7814722,
"author_profile": "https://Stackoverflow.com/users/7814722",
"pm_score": 2,
"selected": false,
"text": "<p>A simple way to compare two string in c++ (tested for windows) is using <strong>_stricmp</strong></p>\n\n<pre><code>// Case insensitive (could use equivalent _stricmp) \nresult = _stricmp( string1, string2 ); \n</code></pre>\n\n<p>If you are looking to use with std::string, an example:</p>\n\n<pre><code>std::string s1 = string(\"Hello\");\nif ( _stricmp(s1.c_str(), \"HELLO\") == 0)\n std::cout << \"The string are equals.\";\n</code></pre>\n\n<p>For more information here: <a href=\"https://msdn.microsoft.com/it-it/library/e0z9k731.aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/it-it/library/e0z9k731.aspx</a></p>\n"
},
{
"answer_id": 50052242,
"author": "Haseeb Mir",
"author_id": 6219626,
"author_profile": "https://Stackoverflow.com/users/6219626",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use <strong>Boost library</strong> then here is solution to it using only C++ standard io header.</p>\n\n<pre><code>#include <iostream>\n\nstruct iequal\n{\n bool operator()(int c1, int c2) const\n {\n // case insensitive comparison of two characters.\n return std::toupper(c1) == std::toupper(c2);\n }\n};\n\nbool iequals(const std::string& str1, const std::string& str2)\n{\n // use std::equal() to compare range of characters using the functor above.\n return std::equal(str1.begin(), str1.end(), str2.begin(), iequal());\n}\n\nint main(void)\n{\n std::string str_1 = \"HELLO\";\n std::string str_2 = \"hello\";\n\n if(iequals(str_1,str_2))\n {\n std::cout<<\"String are equal\"<<std::endl; \n }\n\n else\n {\n std::cout<<\"String are not equal\"<<std::endl;\n }\n\n\n return 0;\n}\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?
Please indicate whether the methods are Unicode-friendly and how portable they are. | Boost includes a handy algorithm for this:
```
#include <boost/algorithm/string.hpp>
// Or, for fewer header dependencies:
//#include <boost/algorithm/string/predicate.hpp>
std::string str1 = "hello, world!";
std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2))
{
// Strings are identical
}
``` |
11,665 | <p>Here is the sample code for my accordion:</p>
<pre><code><mx:Accordion x="15" y="15" width="230" height="599" styleName="myAccordion">
<mx:Canvas id="pnlSpotlight" label="SPOTLIGHT" height="100%" width="100%" horizontalScrollPolicy="off">
<mx:VBox width="100%" height="80%" paddingTop="2" paddingBottom="1" verticalGap="1">
<mx:Repeater id="rptrSpotlight" dataProvider="{aSpotlight}">
<sm:SmallCourseListItem
viewClick="PlayFile(event.currentTarget.getRepeaterItem().fileID);"
Description="{rptrSpotlight.currentItem.fileDescription}"
FileID = "{rptrSpotlight.currentItem.fileID}"
detailsClick="{detailsView.SetFile(event.currentTarget.getRepeaterItem().fileID,this)}"
Title="{rptrSpotlight.currentItem.fileTitle}"
FileIcon="{iconLibrary.getIcon(rptrSpotlight.currentItem.fileExtension)}" />
</mx:Repeater>
</mx:VBox>
</mx:Canvas>
</mx:Accordion>
</code></pre>
<p>I would like to include a button in each header like so:</p>
<p><img src="https://i.stack.imgur.com/EN3kP.jpg" alt="wishful" onclick="alert('xss')"></p>
| [
{
"answer_id": 12266,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>You will have to create a custom header renderer, add a button to it and position it manually. Try something like this:</p>\n\n<pre><code><mx:Accordion>\n <mx:headerRenderer>\n <mx:Component>\n <AccordionHeader xmlns=\"mx.containers.accordionClasses.*\">\n <mx:Script>\n <![CDATA[\n\n import mx.controls.Button;\n\n\n private var extraButton : Button;\n\n\n override protected function createChildren( ) : void {\n super.createChildren();\n\n if ( extraButton == null ) {\n extraButton = new Button();\n\n addChild(extraButton);\n }\n }\n\n override protected function updateDisplayList( unscaledWidth : Number, unscaledHeight : Number ) : void {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n extraButton.setActualSize(unscaledHeight - 6, unscaledHeight - 6);\n extraButton.move(unscaledWidth - extraButton.width - 3, (unscaledHeight - extraButton.height)/2);\n }\n\n ]]>\n </mx:Script>\n </AccordionHeader>\n </mx:Component>\n </mx:headerRenderer>\n\n <mx:HBox label=\"1\"><Label text=\"Text 1\"/></HBox>\n <mx:HBox label=\"1\"><Label text=\"Text 2\"/></HBox>\n <mx:HBox label=\"1\"><Label text=\"Text 3\"/></HBox>\n</mx:Accordion>\n</code></pre>\n"
},
{
"answer_id": 12310,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 3,
"selected": true,
"text": "<p>Thanks, I got it working using <a href=\"http://code.google.com/p/flexlib/\" rel=\"nofollow noreferrer\">FlexLib</a>'s CanvasButtonAccordionHeader.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | Here is the sample code for my accordion:
```
<mx:Accordion x="15" y="15" width="230" height="599" styleName="myAccordion">
<mx:Canvas id="pnlSpotlight" label="SPOTLIGHT" height="100%" width="100%" horizontalScrollPolicy="off">
<mx:VBox width="100%" height="80%" paddingTop="2" paddingBottom="1" verticalGap="1">
<mx:Repeater id="rptrSpotlight" dataProvider="{aSpotlight}">
<sm:SmallCourseListItem
viewClick="PlayFile(event.currentTarget.getRepeaterItem().fileID);"
Description="{rptrSpotlight.currentItem.fileDescription}"
FileID = "{rptrSpotlight.currentItem.fileID}"
detailsClick="{detailsView.SetFile(event.currentTarget.getRepeaterItem().fileID,this)}"
Title="{rptrSpotlight.currentItem.fileTitle}"
FileIcon="{iconLibrary.getIcon(rptrSpotlight.currentItem.fileExtension)}" />
</mx:Repeater>
</mx:VBox>
</mx:Canvas>
</mx:Accordion>
```
I would like to include a button in each header like so:
 | Thanks, I got it working using [FlexLib](http://code.google.com/p/flexlib/)'s CanvasButtonAccordionHeader. |
11,689 | <p>I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers.</p>
<p>I'm in the middle of designing an app that does something like portfolio management. The design I have so far is</p>
<ul>
<li>Problem: a problem that needs to be solved</li>
<li>Solution: a proposed solution to one or more problems</li>
<li>Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into:
<ul>
<li>Parent-child - some sort of categorization / tree hierarchy</li>
<li>Overlap - the degree to which two solutions or two problems really address the same concept</li>
<li>Addresses - the degree to which a problem addresses a solution</li>
</ul></li>
</ul>
<p>My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve.</p>
<p>So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio?</p>
<p><em>Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up.</em></p>
<p>I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better?</p>
<h2>1: Problems (and separately, Solutions) are self-referential in versioning.</h2>
<pre><code>table problems
int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id
</code></pre>
<p>This is problematic because every time I want a new version, I have to duplicate the entire row, including that long <code>description</code> column.</p>
<h2>2: Create a new Relationship type: Version.</h2>
<pre><code>table problems
int id | string name | text description | datetime created_at
</code></pre>
<p>This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept.</p>
<h2>3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them.</h2>
<pre><code>table problems
int id
table attributes
int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id
foreign key previous_version_id -> attributes.id
</code></pre>
<p>This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That <code>value</code> column has to be free-text. I can make the <code>name</code> column a reference into a separate <code>attribute_names</code> table that has a <code>type</code> column, but that doesn't <em>force</em> the correct type in the <code>attributes</code> table.</p>
<p><em>later still: response to @Eric Beard's comments about multi-table foreign keys:</em></p>
<p>Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be <em>extremely</em> wasteful to do combine them into one table.</p>
| [
{
"answer_id": 11694,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": true,
"text": "<p>Hmm, sounds kind of like this site...</p>\n\n<p>As far as a database design would go, a versioning system kind of like SVN, where you never actually do any updates, just inserts (with a version number) when things change, might be what you need. This is called MVCC, Multi-Value Concurrency Control. A wiki is another good example of this.</p>\n"
},
{
"answer_id": 12231,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>@Gaius</p>\n\n<pre><code>foreign key (thing_id, thing_type) -> problems.id or solutions.id\n</code></pre>\n\n<p>Be careful with these kinds of \"multidirectional\" foreign keys. My experience has shown that query performance suffers dramatically when your join condition has to check the type before figuring out which table to join on. It doesn't seem as elegant but nullable </p>\n\n<pre><code>problem_id and solution_id \n</code></pre>\n\n<p>will work much better.</p>\n\n<p>Of course, query performance will also suffer with an MVCC design when you have to add the check to get the latest version of a record. The tradeoff is that you never have to worry about contention with updates.</p>\n"
},
{
"answer_id": 12278,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose there's</p>\n\n<h2>Option 4: the hybrid</h2>\n\n<p>Move the common Thing attributes into a single-inheritance table, then add an <code>custom_attributes</code> table. This makes foreign-keys simpler, reduces duplication, and allows flexibility. It doesn't solve the problems of type-safety for the additional attributes. It also adds a little complexity since there are two ways for a Thing to have an attribute now.</p>\n\n<p>If <code>description</code> and other large fields stay in the Things table, though, it also doesn't solve the duplication-space problem.</p>\n\n<pre><code>table things\n int id | int type | string name | text description | datetime created_at | other common fields...\n foreign key type -> thing_types.id\n\ntable custom_attributes\n int id | int thing_id | string name | string value\n foreign key thing_id -> things.id\n</code></pre>\n"
},
{
"answer_id": 214780,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>How do you think about this:</p>\n\n<p>table problems<br>\n int id | string name | text description | datetime created_at </p>\n\n<p>table problems_revisions<br>\n int revision | int id | string name | text description | datetime created_at<br>\n foreign key id -> problems.id</p>\n\n<p>Before updates you have to perform an additional insert in the revision table. This additional insert is fast, however, this is what you have to pay for </p>\n\n<ol>\n<li>efficient access to the current version - select problems as usual</li>\n<li>a schema that is intuitive and close to the reality you want to model</li>\n<li>joins between tables in your schema keep efficient</li>\n<li>using a revision number per busines transaction you can do versioning over table records like SVN does over files.</li>\n</ol>\n"
},
{
"answer_id": 252983,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 0,
"selected": false,
"text": "<p>It's a good idea to choose a data structure that makes common questions that you ask of the model easy to answer. It's most likely that you're interested in the current position most of the time. On occasion, you will want to drill into the history for particular problems and solutions.</p>\n\n<p>I would have tables for problem, solution, and relationship that represent the current position. There would also be a <code>problem_history</code>, <code>solution_history</code>, etc table. These would be child tables of problem but also contain extra columns for <code>VersionNumber</code> and <code>EffectiveDate</code>. The key would be (<code>ProblemId</code>, <code>VersionNumber</code>).</p>\n\n<p>When you update a problem, you would write the old values into the <code>problem_history</code> table. Point in time queries are therefore possible as you can pick out the <code>problem_history</code> record that is valid as-at a particular date.</p>\n\n<p>Where I've done this before, I have also created a view to UNION <code>problem</code> and <code>problem_history</code> as this is sometimes useful in various queries.</p>\n\n<p>Option 1 makes it difficult to query the current situation, as all your historic data is mixed in with your current data.</p>\n\n<p>Option 3 is going to be bad for query performance and nasty to code against as you'll be accessing lots of rows for what should just be a simple query.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers.
I'm in the middle of designing an app that does something like portfolio management. The design I have so far is
* Problem: a problem that needs to be solved
* Solution: a proposed solution to one or more problems
* Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into:
+ Parent-child - some sort of categorization / tree hierarchy
+ Overlap - the degree to which two solutions or two problems really address the same concept
+ Addresses - the degree to which a problem addresses a solution
My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve.
So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio?
*Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up.*
I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better?
1: Problems (and separately, Solutions) are self-referential in versioning.
---------------------------------------------------------------------------
```
table problems
int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id
```
This is problematic because every time I want a new version, I have to duplicate the entire row, including that long `description` column.
2: Create a new Relationship type: Version.
-------------------------------------------
```
table problems
int id | string name | text description | datetime created_at
```
This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept.
3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them.
-------------------------------------------------------------------------------------------------------------------------
```
table problems
int id
table attributes
int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id
foreign key previous_version_id -> attributes.id
```
This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That `value` column has to be free-text. I can make the `name` column a reference into a separate `attribute_names` table that has a `type` column, but that doesn't *force* the correct type in the `attributes` table.
*later still: response to @Eric Beard's comments about multi-table foreign keys:*
Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be *extremely* wasteful to do combine them into one table. | Hmm, sounds kind of like this site...
As far as a database design would go, a versioning system kind of like SVN, where you never actually do any updates, just inserts (with a version number) when things change, might be what you need. This is called MVCC, Multi-Value Concurrency Control. A wiki is another good example of this. |
11,699 | <p>I'm getting notifications to back up my encryption key for EFS in Vista, however i haven't enabled bit locker or drive encryption.</p>
<p>Anyone know how to find out what files may be encrypted or have an explanation for why it would notify me?</p>
| [
{
"answer_id": 11709,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Clippy noticed that you have sensitive information in your files and automatically encrypted them.</p>\n\n<p>Are you sure it's for EFS? I've had things prompt me to backup my keys before, but I didn't know exactly what they were to. I was assuming it was like a DRM protected file or something. It was a while ago so i don't remember exactly what the specific details were. I never backed it up and haven't been locked out of anything.</p>\n"
},
{
"answer_id": 11732,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": false,
"text": "<p>Yes it's EFS:</p>\n\n<p>[Window Title]\nEncrypting File System</p>\n\n<p>[Main Instruction]\nBack up your file encryption certificate and key</p>\n\n<p>[Content]\nCreating this backup file helps you avoid permanently losing access to your encrypted files if the original certificate and key are lost or corrupted.</p>\n\n<p>[Back up now (recommended)] [Back up later] [Never back up] [Cancel]</p>\n\n<p>[Footer]\nWhy should I backup the certificate and key?</p>\n"
},
{
"answer_id": 232734,
"author": "ParanoidMike",
"author_id": 452120,
"author_profile": "https://Stackoverflow.com/users/452120",
"pm_score": 5,
"selected": false,
"text": "<p>To find out which files on your system have been encrypted with EFS, you can simply run this command:</p>\n\n<pre><code>CIPHER.EXE /U /N\n</code></pre>\n"
},
{
"answer_id": 688126,
"author": "pngaz",
"author_id": 10972,
"author_profile": "https://Stackoverflow.com/users/10972",
"pm_score": 2,
"selected": false,
"text": "<p>EFS encryption is typically achieved via the \"Advanced\" tab of the \"File Properties\" dialog and it's best to do it at the folder-level.<br>\nBut on Vista I remember seeing this message on my new computer, definitely never having encrypted a single file. So I AGREE it's confusing to ask you to back up the key, until the FIRST USE of EFS. Windows-7 has never asked me, so probably that's the way it works in the future.</p>\n"
},
{
"answer_id": 3620281,
"author": "rfeague",
"author_id": 75346,
"author_profile": "https://Stackoverflow.com/users/75346",
"pm_score": 2,
"selected": false,
"text": "<p>I just got this same message for the first time after using Windows 7 for many months. Running cipher.exe as noted above revealed that a font file I downloaded (<a href=\"http://www.ms-studio.com/FontSales/anonymouspro.html\" rel=\"nofollow noreferrer\">Anonymous Pro</a>) had the encryption attribute set (right-click the file, properties, General Tab, click Advanced). It also had security settings granting an unknown account read and execute permissions. (!) I don't know why a font file would have the encryption flag set.</p>\n\n<p>If you just got this message out of the blue, perhaps it is in response to something you just downloaded.</p>\n"
},
{
"answer_id": 4094489,
"author": "Fabrizio Accatino",
"author_id": 21145,
"author_profile": "https://Stackoverflow.com/users/21145",
"pm_score": 1,
"selected": false,
"text": "<p>I've got the same message after un-zipping DroidDraw (http://www.droiddraw.org/).\nIt's a normal (I think) zip file. Right click on it, extrat all. The resulting folder/files were encrypted. Immediatelly Win prompted me to backup EFS keys.<br>\nSame behaviour on Win Vista and Win 7.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | I'm getting notifications to back up my encryption key for EFS in Vista, however i haven't enabled bit locker or drive encryption.
Anyone know how to find out what files may be encrypted or have an explanation for why it would notify me? | To find out which files on your system have been encrypted with EFS, you can simply run this command:
```
CIPHER.EXE /U /N
``` |
11,720 | <p>What I would like to do is create a clean virtual machine image as the output of a build of an application.</p>
<p>So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run.</p>
<p>I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc...</p>
<p>Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process.</p>
<p>Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this?</p>
| [
{
"answer_id": 11709,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Clippy noticed that you have sensitive information in your files and automatically encrypted them.</p>\n\n<p>Are you sure it's for EFS? I've had things prompt me to backup my keys before, but I didn't know exactly what they were to. I was assuming it was like a DRM protected file or something. It was a while ago so i don't remember exactly what the specific details were. I never backed it up and haven't been locked out of anything.</p>\n"
},
{
"answer_id": 11732,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": false,
"text": "<p>Yes it's EFS:</p>\n\n<p>[Window Title]\nEncrypting File System</p>\n\n<p>[Main Instruction]\nBack up your file encryption certificate and key</p>\n\n<p>[Content]\nCreating this backup file helps you avoid permanently losing access to your encrypted files if the original certificate and key are lost or corrupted.</p>\n\n<p>[Back up now (recommended)] [Back up later] [Never back up] [Cancel]</p>\n\n<p>[Footer]\nWhy should I backup the certificate and key?</p>\n"
},
{
"answer_id": 232734,
"author": "ParanoidMike",
"author_id": 452120,
"author_profile": "https://Stackoverflow.com/users/452120",
"pm_score": 5,
"selected": false,
"text": "<p>To find out which files on your system have been encrypted with EFS, you can simply run this command:</p>\n\n<pre><code>CIPHER.EXE /U /N\n</code></pre>\n"
},
{
"answer_id": 688126,
"author": "pngaz",
"author_id": 10972,
"author_profile": "https://Stackoverflow.com/users/10972",
"pm_score": 2,
"selected": false,
"text": "<p>EFS encryption is typically achieved via the \"Advanced\" tab of the \"File Properties\" dialog and it's best to do it at the folder-level.<br>\nBut on Vista I remember seeing this message on my new computer, definitely never having encrypted a single file. So I AGREE it's confusing to ask you to back up the key, until the FIRST USE of EFS. Windows-7 has never asked me, so probably that's the way it works in the future.</p>\n"
},
{
"answer_id": 3620281,
"author": "rfeague",
"author_id": 75346,
"author_profile": "https://Stackoverflow.com/users/75346",
"pm_score": 2,
"selected": false,
"text": "<p>I just got this same message for the first time after using Windows 7 for many months. Running cipher.exe as noted above revealed that a font file I downloaded (<a href=\"http://www.ms-studio.com/FontSales/anonymouspro.html\" rel=\"nofollow noreferrer\">Anonymous Pro</a>) had the encryption attribute set (right-click the file, properties, General Tab, click Advanced). It also had security settings granting an unknown account read and execute permissions. (!) I don't know why a font file would have the encryption flag set.</p>\n\n<p>If you just got this message out of the blue, perhaps it is in response to something you just downloaded.</p>\n"
},
{
"answer_id": 4094489,
"author": "Fabrizio Accatino",
"author_id": 21145,
"author_profile": "https://Stackoverflow.com/users/21145",
"pm_score": 1,
"selected": false,
"text": "<p>I've got the same message after un-zipping DroidDraw (http://www.droiddraw.org/).\nIt's a normal (I think) zip file. Right click on it, extrat all. The resulting folder/files were encrypted. Immediatelly Win prompted me to backup EFS keys.<br>\nSame behaviour on Win Vista and Win 7.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] | What I would like to do is create a clean virtual machine image as the output of a build of an application.
So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run.
I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc...
Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process.
Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this? | To find out which files on your system have been encrypted with EFS, you can simply run this command:
```
CIPHER.EXE /U /N
``` |
11,761 | <p>I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service? </p>
<p><strong>Update:</strong>
Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file.</p>
| [
{
"answer_id": 11779,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>ASP.NET caching works just as well with Web services so you can implement regular caching as explained here: <a href=\"http://msdn.microsoft.com/en-us/library/aa478965.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa478965.aspx</a></p>\n"
},
{
"answer_id": 11789,
"author": "Hertanto Lie",
"author_id": 1381,
"author_profile": "https://Stackoverflow.com/users/1381",
"pm_score": 2,
"selected": false,
"text": "<p>What about using a global or static collection object? Is that a good idea?</p>\n"
},
{
"answer_id": 11826,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 4,
"selected": true,
"text": "<p>Extending on <a href=\"https://stackoverflow.com/questions/11761/persisting-data-in-net-web-service-memory#11779\">Ice^^Heat</a>'s idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so: </p>\n\n<pre><code>Context.Cache.Insert(\"foo\", _\n Foo, _\n Nothing, _\n DateAdd(DateInterval.Minute, 30, Now()), _\n System.Web.Caching.Cache.NoSlidingExpiration)\n</code></pre>\n\n<p>And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition: </p>\n\n<pre><code><WebMethod(CacheDuration:=60)> _\nPublic Function HelloWorld() As String\n Return \"Hello World\"\nEnd Function\n</code></pre>\n\n<p>Info gathered from <a href=\"http://msdn.microsoft.com/en-us/library/aa480499.aspx\" rel=\"nofollow noreferrer\">XML Web Service Caching Strategies</a>.</p>\n"
},
{
"answer_id": 11904,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 2,
"selected": false,
"text": "<p>To echo <a href=\"https://stackoverflow.com/questions/11761/persisting-data-in-net-web-service-memory#11789\">klughing</a>, if your JSON data isn't expected to change often, I think the simplest way to cache it is to use a static collection of some kind - perhaps a DataTable.</p>\n\n<p>First, parse your JSON data into a System.Data.DataTable, and make it static in your Web service class. Then, access the static object. The data should stay cached until IIS recycles your application pool.</p>\n\n<pre><code>public class WebServiceClass\n{\n private static DataTable _myData = null;\n public static DataTable MyData\n {\n get\n {\n if (_myData == null)\n {\n _myData = ParseJsonDataReturnDT();\n }\n return _myData;\n }\n }\n\n [WebMethod]\n public string GetData()\n {\n //... do some stuff with MyData and return a string ...\n return MyData.Rows[0][\"MyColumn\"].ToString();\n }\n}\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1381/"
] | I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service?
**Update:**
Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file. | Extending on [Ice^^Heat](https://stackoverflow.com/questions/11761/persisting-data-in-net-web-service-memory#11779)'s idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so:
```
Context.Cache.Insert("foo", _
Foo, _
Nothing, _
DateAdd(DateInterval.Minute, 30, Now()), _
System.Web.Caching.Cache.NoSlidingExpiration)
```
And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition:
```
<WebMethod(CacheDuration:=60)> _
Public Function HelloWorld() As String
Return "Hello World"
End Function
```
Info gathered from [XML Web Service Caching Strategies](http://msdn.microsoft.com/en-us/library/aa480499.aspx). |
11,762 | <p>I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from <a href="http://www.codeproject.com/KB/security/DotNetCrypto.aspx" rel="noreferrer">here</a>):</p>
<pre><code> // create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
</code></pre>
<p>The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. </p>
<p>example code:</p>
<pre><code> string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
</code></pre>
<p>My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.</p>
| [
{
"answer_id": 11776,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, this is to be expected, or at least, its exactly what happens when our crypto routines get non-decryptable data</p>\n"
},
{
"answer_id": 26283,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 6,
"selected": true,
"text": "<p>Although this have been already answered I think it would be a good idea to explain <strong>why</strong> it is to be expected.</p>\n\n<p>A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the <a href=\"http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding\" rel=\"noreferrer\">OAEP</a> padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or <a href=\"http://en.wikipedia.org/wiki/Blinding_(cryptography)\" rel=\"noreferrer\">blinding</a>).</p>\n\n<p>A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation):</p>\n\n<ol>\n<li>Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number.</li>\n<li>Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent.</li>\n</ol>\n\n<p>That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key)</p>\n"
},
{
"answer_id": 3404132,
"author": "R D",
"author_id": 410571,
"author_profile": "https://Stackoverflow.com/users/410571",
"pm_score": 1,
"selected": false,
"text": "<p>There may be some unread bytes in the CryptoStream. Closing before reading the stream completely was causing the error in my program.</p>\n"
},
{
"answer_id": 14971080,
"author": "jbtule",
"author_id": 637783,
"author_profile": "https://Stackoverflow.com/users/637783",
"pm_score": 3,
"selected": false,
"text": "<p>If you want your usage to be correct, you should add <a href=\"http://en.wikipedia.org/wiki/Authenticated_encryption\" rel=\"nofollow noreferrer\">authentication</a> to your ciphertext so that you can verify that it is the correct pasword or that the ciphertext hasn't been modified. The padding you are using <a href=\"http://en.wikipedia.org/wiki/Padding_%28cryptography%29#ISO_10126\" rel=\"nofollow noreferrer\">ISO10126</a> will only throw an exception if the last byte doesn't decrypt as one of 16 valid values for padding (0x01-0x10). So you have a 1/16 chance of it NOT throwing the exception with the wrong password, where if you authenticate it you have a deterministic way to tell if your decryption is valid.</p>\n\n<p>Using crypto api's while seemingly easy, actually is rather is easy to make mistakes. For example you use a fixed salt for for you key and iv derivation, that means every ciphertext encrypted with the same password will reuse it's IV with that key, that breaks semantic security with CBC mode, the IV needs to be both unpredictable and unique for a given key.</p>\n\n<p>For that reason of easy to make mistakes, I have a code snippet, that I try to keep reviewed and up to date (comments, issues welcome):</p>\n\n<p><a href=\"https://stackoverflow.com/a/10366194/637783\">Modern Examples of Symmetric Authenticated Encryption of a string C#.</a></p>\n\n<p>If you use it's <code>AESThenHMAC.AesSimpleDecryptWithPassword(ciphertext, password)</code> when the wrong password is used, <code>null</code> is returned, if the ciphertext or iv has been modified post encryption <code>null</code> is returned, you will never get junk data back, or a padding exception.</p>\n"
},
{
"answer_id": 19835066,
"author": "Yaniv",
"author_id": 2964625,
"author_profile": "https://Stackoverflow.com/users/2964625",
"pm_score": 4,
"selected": false,
"text": "<p>I experienced a similar \"Padding is invalid and cannot be removed.\" exception, but in my case the key IV and padding were correct.</p>\n\n<p>It turned out that flushing the crypto stream is all that was missing.</p>\n\n<p>Like this:</p>\n\n<pre><code> MemoryStream msr3 = new MemoryStream();\n CryptoStream encStream = new CryptoStream(msr3, RijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);\n encStream.Write(bar2, 0, bar2.Length);\n // unless we flush the stream we would get \"Padding is invalid and cannot be removed.\" exception when decoding\n encStream.FlushFinalBlock();\n byte[] bar3 = msr3.ToArray();\n</code></pre>\n"
},
{
"answer_id": 28277552,
"author": "Mina Wissa",
"author_id": 235123,
"author_profile": "https://Stackoverflow.com/users/235123",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem, the issue in decrypt method was initializing an empty memory stream. when it worked when I initialized it with the cipher text byte array like this:</p>\n\n<pre><code>MemoryStream ms = new MemoryStream(cipherText)\n</code></pre>\n"
},
{
"answer_id": 29659976,
"author": "RoopzD",
"author_id": 2537096,
"author_profile": "https://Stackoverflow.com/users/2537096",
"pm_score": -1,
"selected": false,
"text": "<p>The answer updated by the user \"atconway\" worked for me.</p>\n\n<p>The problem was not with the padding but the key which was different during encryption and decryption.\nThe key and iv should be same during encypting and decrypting the same value.</p>\n"
},
{
"answer_id": 39956449,
"author": "Denis Tikhomirov",
"author_id": 752435,
"author_profile": "https://Stackoverflow.com/users/752435",
"pm_score": 2,
"selected": false,
"text": "<p>Another reason of the exception might be a race condition between several threads using decryption logic - native implementations of ICryptoTransform are <em>not thread-safe</em> (e.g. SymmetricAlgorithm), so it should be put to exclusive section, e.g. using <em>lock</em>.\nPlease refer here for more details: <a href=\"http://www.make-awesome.com/2011/07/system-security-cryptography-and-thread-safety/\" rel=\"nofollow\">http://www.make-awesome.com/2011/07/system-security-cryptography-and-thread-safety/</a></p>\n"
},
{
"answer_id": 40018716,
"author": "Marc L.",
"author_id": 85269,
"author_profile": "https://Stackoverflow.com/users/85269",
"pm_score": 2,
"selected": false,
"text": "<p>If you've ruled out key-mismatch, then besides <code>FlushFinalBlock()</code> (see Yaniv's answer), calling <code>Close()</code> on the <code>CryptoStream</code> will also suffice. </p>\n\n<p>If you are cleaning up resources strictly with <code>using</code> blocks, be sure to nest the block for the <code>CryptoStream</code> itself:</p>\n\n<pre><code>using (MemoryStream ms = new MemoryStream())\nusing (var enc = RijndaelAlg.CreateEncryptor())\n{\n using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))\n {\n encStream.Write(bar2, 0, bar2.Length);\n } // implicit close\n byte[] encArray = ms.ToArray();\n}\n</code></pre>\n\n<p>I've been bitten by this (or similar):</p>\n\n<pre><code>using (MemoryStream ms = new MemoryStream())\nusing (var enc = RijndaelAlg.CreateEncryptor())\nusing (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))\n{\n encStream.Write(bar2, 0, bar2.Length);\n byte[] encArray = ms.ToArray();\n} // implicit close -- too late!\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from [here](http://www.codeproject.com/KB/security/DotNetCrypto.aspx)):
```
// create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
```
The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString.
example code:
```
string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
```
My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception. | Although this have been already answered I think it would be a good idea to explain **why** it is to be expected.
A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the [OAEP](http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding) padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or [blinding](http://en.wikipedia.org/wiki/Blinding_(cryptography))).
A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation):
1. Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number.
2. Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent.
That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key) |
11,806 | <p>I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account?</p>
<p>Basically, the script that I have so far looks something like this:</p>
<pre><code>RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
{
pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
foreach (object item in pipeline.Error.ReadToEnd())
resultString += "Error: " + item.ToString() + "\n";
}
runspace.Close();
foreach (PSObject obj in results)
resultString += obj.ToString();
}
return resultString;
</code></pre>
| [
{
"answer_id": 11811,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>In your ASP.NET app, you will need to impersonate a valid AD account with the correct permissions:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/306158\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/306158</a></p>\n"
},
{
"answer_id": 12554,
"author": "Otto",
"author_id": 519,
"author_profile": "https://Stackoverflow.com/users/519",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a class that I use to impersonate a user.</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Web.UI.HtmlControls;\n\nnamespace orr.Tools\n{\n\n #region Using directives.\n using System.Security.Principal;\n using System.Runtime.InteropServices;\n using System.ComponentModel;\n #endregion\n\n /// <summary>\n /// Impersonation of a user. Allows to execute code under another\n /// user context.\n /// Please note that the account that instantiates the Impersonator class\n /// needs to have the 'Act as part of operating system' privilege set.\n /// </summary>\n /// <remarks> \n /// This class is based on the information in the Microsoft knowledge base\n /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158\n /// \n /// Encapsulate an instance into a using-directive like e.g.:\n /// \n /// ...\n /// using ( new Impersonator( \"myUsername\", \"myDomainname\", \"myPassword\" ) )\n /// {\n /// ...\n /// [code that executes under the new context]\n /// ...\n /// }\n /// ...\n /// \n /// Please contact the author Uwe Keim (mailto:[email protected])\n /// for questions regarding this class.\n /// </remarks>\n public class Impersonator :\n IDisposable\n {\n #region Public methods.\n /// <summary>\n /// Constructor. Starts the impersonation with the given credentials.\n /// Please note that the account that instantiates the Impersonator class\n /// needs to have the 'Act as part of operating system' privilege set.\n /// </summary>\n /// <param name=\"userName\">The name of the user to act as.</param>\n /// <param name=\"domainName\">The domain name of the user to act as.</param>\n /// <param name=\"password\">The password of the user to act as.</param>\n public Impersonator(\n string userName,\n string domainName,\n string password)\n {\n ImpersonateValidUser(userName, domainName, password);\n }\n\n // ------------------------------------------------------------------\n #endregion\n\n #region IDisposable member.\n\n public void Dispose()\n {\n UndoImpersonation();\n }\n\n // ------------------------------------------------------------------\n #endregion\n\n #region P/Invoke.\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int LogonUser(\n string lpszUserName,\n string lpszDomain,\n string lpszPassword,\n int dwLogonType,\n int dwLogonProvider,\n ref IntPtr phToken);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern int DuplicateToken(\n IntPtr hToken,\n int impersonationLevel,\n ref IntPtr hNewToken);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool RevertToSelf();\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n private static extern bool CloseHandle(\n IntPtr handle);\n\n private const int LOGON32_LOGON_INTERACTIVE = 2;\n private const int LOGON32_PROVIDER_DEFAULT = 0;\n\n // ------------------------------------------------------------------\n #endregion\n\n #region Private member.\n // ------------------------------------------------------------------\n\n /// <summary>\n /// Does the actual impersonation.\n /// </summary>\n /// <param name=\"userName\">The name of the user to act as.</param>\n /// <param name=\"domainName\">The domain name of the user to act as.</param>\n /// <param name=\"password\">The password of the user to act as.</param>\n private void ImpersonateValidUser(\n string userName,\n string domain,\n string password)\n {\n WindowsIdentity tempWindowsIdentity = null;\n IntPtr token = IntPtr.Zero;\n IntPtr tokenDuplicate = IntPtr.Zero;\n\n try\n {\n if (RevertToSelf())\n {\n if (LogonUser(\n userName,\n domain,\n password,\n LOGON32_LOGON_INTERACTIVE,\n LOGON32_PROVIDER_DEFAULT,\n ref token) != 0)\n {\n if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)\n {\n tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);\n impersonationContext = tempWindowsIdentity.Impersonate();\n }\n else\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n else\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n else\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n finally\n {\n if (token != IntPtr.Zero)\n {\n CloseHandle(token);\n }\n if (tokenDuplicate != IntPtr.Zero)\n {\n CloseHandle(tokenDuplicate);\n }\n }\n }\n\n /// <summary>\n /// Reverts the impersonation.\n /// </summary>\n private void UndoImpersonation()\n {\n if (impersonationContext != null)\n {\n impersonationContext.Undo();\n }\n }\n\n private WindowsImpersonationContext impersonationContext = null;\n\n // ------------------------------------------------------------------\n #endregion\n }\n}\n</code></pre>\n"
},
{
"answer_id": 448051,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 2,
"selected": true,
"text": "<p>Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then access this webservice to get access to powershell. Please remember to add the necessary security because this could potentially be a huge security hole.</p>\n"
},
{
"answer_id": 1499913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You might need a patch.</p>\n\n<p>From: <a href=\"http://support.microsoft.com/kb/943937\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/943937</a></p>\n\n<blockquote>\n <p><strong>An application cannot impersonate a\n user and then run Windows PowerShell\n commands in an Exchange Server 2007\n environment</strong></p>\n \n <p>To resolve this problem, install\n Update Rollup 1 for Exchange Server\n 2007 Service Pack 1.</p>\n</blockquote>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account?
Basically, the script that I have so far looks something like this:
```
RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
{
pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
foreach (object item in pipeline.Error.ReadToEnd())
resultString += "Error: " + item.ToString() + "\n";
}
runspace.Close();
foreach (PSObject obj in results)
resultString += obj.ToString();
}
return resultString;
``` | Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then access this webservice to get access to powershell. Please remember to add the necessary security because this could potentially be a huge security hole. |
11,809 | <p>The only thing I've found has been;</p>
<pre class="lang-css prettyprint-override"><code>.hang {
text-indent: -3em;
margin-left: 3em;
}
</code></pre>
<p>The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a <code><span class="hang"></span></code> type of thing.</p>
<p>I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work.</p>
| [
{
"answer_id": 11815,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p><code><span></code> is an inline element. The term <em>hanging indent</em> is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on <code><p></code> or <code><div></code> or any other block element to get rid of extra vertical space between paragraphs.</p>\n\n<p>You may want something like <code>display: run-in</code>, where the tag will become either block or inline depending on context... sadly, this is <a href=\"http://quirksmode.org/css/css2/display.html\" rel=\"noreferrer\">not yet universally supported by browsers</a>.</p>\n"
},
{
"answer_id": 8090502,
"author": "David Barnett",
"author_id": 1008297,
"author_profile": "https://Stackoverflow.com/users/1008297",
"pm_score": 4,
"selected": false,
"text": "<p>Found a cool way to do just that, minus the nasty span.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>p {\n padding-left: 20px; \n} \n\np:first-letter {\n margin-left: -20px;\n}\n</code></pre>\n\n<p>Nice and simple :D</p>\n\n<p>If the newlines are bothering you in p blocks, you can add</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>p {\n margin-top: 0px;\n margin-bottom: 0px;\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/agweber/9dmtfhw2/\" rel=\"noreferrer\">JSFiddle Example</a></p>\n"
},
{
"answer_id": 29932188,
"author": "JCH2",
"author_id": 4844225,
"author_profile": "https://Stackoverflow.com/users/4844225",
"pm_score": 2,
"selected": false,
"text": "<p>ysth's answer is best with one debatable exception; the unit of measure should correspond to the size of the font.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>p {\n text-indent: -2en; \n padding-left: 2en;\n}\n</code></pre>\n\n<p>\"3\" would also work adequately well; \"em\" is not recommended as it is wider than the average character in an alphabetic set. \"px\" should only be used if you intended to align hangs of text blocks with differing font sizes.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362/"
] | The only thing I've found has been;
```css
.hang {
text-indent: -3em;
margin-left: 3em;
}
```
The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a `<span class="hang"></span>` type of thing.
I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work. | `<span>` is an inline element. The term *hanging indent* is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on `<p>` or `<div>` or any other block element to get rid of extra vertical space between paragraphs.
You may want something like `display: run-in`, where the tag will become either block or inline depending on context... sadly, this is [not yet universally supported by browsers](http://quirksmode.org/css/css2/display.html). |
11,820 | <p>This <a href="https://stackoverflow.com/questions/11782/file-uploads-via-web-services">question and answer</a> shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<bytes>
<byte>16</byte>
<byte>28</byte>
<byte>127</byte>
...
</bytes>
</code></pre>
<p>If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services?</p>
| [
{
"answer_id": 11830,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<p>I use this method for some internal corporate webservices, and I haven't noticed any major slow-downs (but that doesn't mean it's not there). </p>\n\n<p>You could probably use any of the numerous network traffic analysis tools to measure the size of the data, and make a judgment call based off that.</p>\n"
},
{
"answer_id": 11832,
"author": "Kevin Dente",
"author_id": 9,
"author_profile": "https://Stackoverflow.com/users/9",
"pm_score": 5,
"selected": true,
"text": "<p>Typically a byte array is sent as a <code>base64</code> encoded string, not as individual bytes in tags. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Base64\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Base64</a></p>\n\n<p>The <code>base64</code> encoded version is about <strong>137%</strong> of the size of the original content.</p>\n"
},
{
"answer_id": 11834,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure about all the details (compressing, encoding, etc) but I usually just use <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">WireShark</a> to analyze the network traffic (while trying various methods) which then allows you to see exactly how it's sent.</p>\n\n<p>For example, if it's compressed the data block of the packet shouldn't be readable as plain text...however if it's uncompressed, you will just see plain old xml text...like you would see with HTTP traffic, or even FTP in certain cases.</p>\n"
},
{
"answer_id": 11840,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>To echo what Kevin said, in .net web services if you have a byte array it is sent as a base64 encoded string by default. You can also specify the encoding of the byte array beforehand. </p>\n\n<p>Obviously, once it gets to the server (or client) you need to manually decode the string back into a byte array as this isn't done automagically for you unfortunately.</p>\n"
},
{
"answer_id": 24522,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "<p>The main performance hit isn't going to be from the transfer of the encoded file, it's going to be in the processing that the server has to do to encode the file pre-transfer (unless the files don't change often and the encoded version can be cached somehow).</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | This [question and answer](https://stackoverflow.com/questions/11782/file-uploads-via-web-services) shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:
```
<?xml version="1.0" encoding="UTF-8" ?>
<bytes>
<byte>16</byte>
<byte>28</byte>
<byte>127</byte>
...
</bytes>
```
If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services? | Typically a byte array is sent as a `base64` encoded string, not as individual bytes in tags.
<http://en.wikipedia.org/wiki/Base64>
The `base64` encoded version is about **137%** of the size of the original content. |
11,854 | <p>In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the <em>is a</em> relationship, rather than the <em>has a</em> relationship. For example, several objects <em>have a</em> damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an <em>is a</em> relationship which wouldn't be true. (A person <em>is not a</em> damage counter.)</p>
<p>The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the <em>is a</em> / <em>has a</em> ideal in exchange for ease of programming?</p>
<p>Edit:
To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use.</p>
| [
{
"answer_id": 11859,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes it's worth giving up the ideal for the realistic. If it's going to cause a massive problem to \"do it right\" with no real benefit, then I would do it wrong. With that said, I often think it's worth taking the time to do it right, because unnecessary multiple inheritance increases complexity, and it <em>can</em> contribute to the system being less maintainable. You really have to decide what's best for your circumstance.</p>\n\n<p>One option would be to have these objects implement a <code>Damageable</code> interface, rather than inheriting from <code>DamageCounter</code>. This way, a person <em>has-a</em> damage counter, but <em>is</em> damageable. (I often find interfaces make a lot more sense as adjective than nouns.) Then you could have a consistent damage interface on <code>Damageable</code> objects, and not expose that a damage counter is the underlying implementation (unless you need to).</p>\n\n<p>If you want to go the template route (assuming C++ or similar), you could do this with mixins, but that can get ugly really quickly if done poorly.</p>\n"
},
{
"answer_id": 11860,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>Normally when we talk about 'is a' vs 'has a' we're talking about Inheritance vs Composition.</p>\n\n<p>Um...damage counter would just be attribute of one of your derived classes and wouldn't really be discussed in terms of 'A person is a damage counter' with respect to your question.</p>\n\n<p>See this:</p>\n\n<p><a href=\"http://www.artima.com/designtechniques/compoinh.html\" rel=\"nofollow noreferrer\">http://www.artima.com/designtechniques/compoinh.html</a></p>\n\n<p>Which might help you along the way.</p>\n\n<p>@<strong><a href=\"https://stackoverflow.com/questions/11854/inheritance-and-polymorphism-ease-of-use-vs-purity#11864\">Derek</a></strong>: From the wording, I assumed there <em>was</em> a base clase, having re-read the question I kinda now see what he's getting at. </p>\n"
},
{
"answer_id": 11862,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 0,
"selected": false,
"text": "<p>This question is really confusing :/</p>\n\n<p>Your question in bold is very open-ended and has an answer of \"it depends\", but your example doesn't really give much information about the context from which you are asking. These lines confuse me;</p>\n\n<blockquote>\n <blockquote>\n <p>sets of data that should all be processed in a similar way</p>\n </blockquote>\n</blockquote>\n\n<p>What way? Are the sets processed by a function? Another class? Via a virtual function on the data?</p>\n\n<blockquote>\n <blockquote>\n <p>In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism</p>\n </blockquote>\n</blockquote>\n\n<p>The ideal of \"acting the same\" and polymorphism are absolutely unrelated. How does polymorphism make it easy to achieve?</p>\n"
},
{
"answer_id": 11864,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>@Kevin</p>\n<blockquote>\n<p>Normally when we talk about 'is a' vs 'has a' we're talking about Inheritance vs Composition.</p>\n<p>Um...damage counter would just be attribute of one of your derived classes and wouldn't really be discussed in terms of 'A person is a damage counter' with respect to your question.</p>\n</blockquote>\n<p>Having the damage counter as an attribute doesn't allow him to diverse objects with damage counters into a collection. For example, a person and a car might both have damage counters, but you can't have a <code>vector<Person|Car></code> or a <code>vector<with::getDamage()></code> or anything similar in most languages. If you have a common Object base class, then you can shove them in that way, but then you can't access the <code>getDamage()</code> method generically.</p>\n<p>That was the essence of his question, as I read it. "Should I violate <code>is-a</code> and <code>has-a</code> for the sake of treating certain objects as if they are the same, even though they aren't?"</p>\n"
},
{
"answer_id": 11868,
"author": "Andrew",
"author_id": 1389,
"author_profile": "https://Stackoverflow.com/users/1389",
"pm_score": 0,
"selected": false,
"text": "<p>\"Doing it right\" will have benefits in the long run, if only because someone maintaining the system later will find it easier to comprehend if it was done right to begin with.</p>\n\n<p>Depending on the language, you may well have the option of multiple inheritance, but normally simple interfaces make the most sense. By \"simple\" I mean make an interface that isn't trying to be too much. Better to have lots of simple interfaces and a few monolithic ones. Of course, there is always a trade off, and too many interfaces would probably lead to ones being \"forgotten\" about...</p>\n"
},
{
"answer_id": 11869,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>@Andrew</p>\n\n<blockquote>\n <p>The ideal of \"acting the same\" and polymorphism are absolutely unrelated. How does polymorphism make it easy to achieve?</p>\n</blockquote>\n\n<p>They all have, e.g., one function in common. Let's call it <code>addDamage()</code>. If you want to do something like this:</p>\n\n<pre><code>foreach (obj in mylist)\n obj.addDamage(1)\n</code></pre>\n\n<p>Then you need either a dynamic language, or you need them to extend from a common parent class (or interface). e.g.:</p>\n\n<pre><code>class Person : DamageCounter {}\nclass Car : DamageCounter {}\n\nforeach (DamageCounter d in mylist)\n d.addDamage(1)\n</code></pre>\n\n<p>Then, you can treat <code>Person</code> and <code>Car</code> the same in certain very useful circumstances.</p>\n"
},
{
"answer_id": 11881,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>I think you should be implementing interfaces to be able to enforce your <em>has a</em> relationships (am doing this in C#):</p>\n\n<pre><code>public interface IDamageable\n{\n void AddDamage(int i);\n int DamageCount {get;}\n}\n</code></pre>\n\n<p>You could implement this in your objects:</p>\n\n<pre><code>public class Person : IDamageable\n\npublic class House : IDamageable\n</code></pre>\n\n<p>And you'd be sure that the DamageCount property and has a method to allow you to add damage, without implying that a person and a house are related to each other in some sort of heirarchy.</p>\n"
},
{
"answer_id": 11935,
"author": "Brian",
"author_id": 725,
"author_profile": "https://Stackoverflow.com/users/725",
"pm_score": 3,
"selected": true,
"text": "<p>This can be accomplished using multiple inheritance. In your specific case (C++), you can use pure virtual classes as interfaces. This allows you to have multiple inheritance without creating scope/ambiguity problems. Example:</p>\n\n<pre><code>class Damage {\n virtual void addDamage(int d) = 0;\n virtual int getDamage() = 0;\n};\n\nclass Person : public virtual Damage {\n void addDamage(int d) {\n // ...\n damage += d * 2;\n }\n\n int getDamage() {\n return damage;\n }\n};\n\nclass Car : public virtual Damage {\n void addDamage(int d) {\n // ...\n damage += d;\n }\n\n int getDamage() {\n return damage;\n }\n};\n</code></pre>\n\n<p>Now both Person and Car 'is-a' Damage, meaning, they implement the Damage interface. The use of pure virtual classes (so that they are like interfaces) is key and should be used frequently. It insulates future changes from altering the entire system. Read up on the Open-Closed Principle for more information.</p>\n"
},
{
"answer_id": 70856,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Jon, but assuming you still have need for a separate damage counter class, you can do:</p>\n\n<pre><code>class IDamageable {\n virtual DamageCounter* damage_counter() = 0;\n};\nclass DamageCounter {\n ...\n};\n</code></pre>\n\n<p>Each damageable class then needs to provide their own damage_counter() member function. The downside of this is that it creates a vtable for each damageable class. You can instead use:</p>\n\n<pre><code>class Damageable {\n public:\n DamageCounter damage_counter() { return damage_counter_; }\n private:\n DamageCounter damage_counter_;\n};\n</code></pre>\n\n<p>But many people are <strong>Not Cool</strong> with multiple inheritance when multiple parents have member variables.</p>\n"
},
{
"answer_id": 2089354,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>Polymorphism <em>does not require inheritance</em>. Polymorphism is what you get when multiple objects implement the same message signature (method).</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256/"
] | In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the *is a* relationship, rather than the *has a* relationship. For example, several objects *have a* damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an *is a* relationship which wouldn't be true. (A person *is not a* damage counter.)
The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the *is a* / *has a* ideal in exchange for ease of programming?
Edit:
To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use. | This can be accomplished using multiple inheritance. In your specific case (C++), you can use pure virtual classes as interfaces. This allows you to have multiple inheritance without creating scope/ambiguity problems. Example:
```
class Damage {
virtual void addDamage(int d) = 0;
virtual int getDamage() = 0;
};
class Person : public virtual Damage {
void addDamage(int d) {
// ...
damage += d * 2;
}
int getDamage() {
return damage;
}
};
class Car : public virtual Damage {
void addDamage(int d) {
// ...
damage += d;
}
int getDamage() {
return damage;
}
};
```
Now both Person and Car 'is-a' Damage, meaning, they implement the Damage interface. The use of pure virtual classes (so that they are like interfaces) is key and should be used frequently. It insulates future changes from altering the entire system. Read up on the Open-Closed Principle for more information. |
11,879 | <p>Instead of returning a common string, is there a way to return classic objects?
If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? </p>
| [
{
"answer_id": 11883,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>Yes: in .NET they call this serialization, where objects are serialized into XML and then reconstructed by the consuming service back into its original object type or a surrogate with the same data structure.</p>\n"
},
{
"answer_id": 11884,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "<p>If the object can be serialised to XML and can be described in WSDL then yes it is possible to return objects from a webservice.</p>\n"
},
{
"answer_id": 11899,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 4,
"selected": true,
"text": "<p>As mentioned, you can do this in .net via serialization. By default all native types are serializable so this happens automagically for you.</p>\n\n<p>However if you have complex types, you need to mark the object with the [Serializable] attribute. The same goes with complex types as properties.</p>\n\n<p>So for example you need to have:</p>\n\n<pre><code>[Serializable]\npublic class MyClass\n{\n public string MyString {get; set;}\n\n [Serializable]\n public MyOtherClass MyOtherClassProperty {get; set;}\n}\n</code></pre>\n"
},
{
"answer_id": 11900,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 1,
"selected": false,
"text": "<p>.NET automatically does this with objects that are serializable. I'm pretty sure Java works the same way.</p>\n\n<p>Here is an article that talks about object serialization in .NET:\n<a href=\"http://www.codeguru.com/Csharp/Csharp/cs_syntax/serialization/article.php/c7201/\" rel=\"nofollow noreferrer\">http://www.codeguru.com/Csharp/Csharp/cs_syntax/serialization/article.php/c7201</a></p>\n"
},
{
"answer_id": 11902,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 2,
"selected": false,
"text": "<p>Where possible, I transpose the objects into XML - this means that the Web Service is more portable - I can then access the service in whatever language, I just need to create the parser/object transposer in that language.</p>\n\n<p>Because we have WSDL files describing the service, this is almost automated in some systems.</p>\n\n<p>(For example, we have a server written in pure python which is replacing a server written in C, a client written in C++/gSOAP, and a client written in Cocoa/Objective-C. We use soapUI as a testing framework, which is written in Java).</p>\n"
},
{
"answer_id": 11923,
"author": "Brian",
"author_id": 725,
"author_profile": "https://Stackoverflow.com/users/725",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to return objects from a web service using XML. But Web Services are supposed to be platform and operating system agnostic. Serializing an object simply allows you to store and retrieve an object from a byte stream, such as a file. For instance, you can serialize a Java object, convert that binary stream (perhaps via a Base 64 encoding into a CDATA field) and transfer that to service's client.</p>\n\n<p>But the client would only be able to restore that object if it were Java-based. Moreover, a deep copy is required to serialize an object and have it restored exactly. Deep copies can be expensive.</p>\n\n<p>Your best route is to create an XML schema that represents the document and create an instance of that schema with the object specifics.</p>\n"
},
{
"answer_id": 11929,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>@Brian: I don't know how things work in Java, but in .net objects get serialized down to XML, not base64 strings. The webservice publishes a wsdl file that contains the method and object definitions required for your webservice.</p>\n\n<p>I would hope that nobody creates webservices that simply create a base64 string</p>\n"
},
{
"answer_id": 14102,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "<p>As others have said, it is possible. However, if both the service and client use an object that has the exact same domain behavior on both sides, you probably didn't need a service in the first place. </p>\n"
},
{
"answer_id": 15503,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>As others have said, it is possible.\n However, if both the service and\n client use an object that has the\n exact same domain behavior on both\n sides, you probably didn't need a\n service in the first place.</p>\n</blockquote>\n\n<p>I have to disagree with this as it's a somewhat narrow comment. Using a webservice that can serialize domain objects to XML means that it makes it easy for clients that work with the same domain objects, but it also means that those clients are restricted to using that particular web service you've exposed and it also works in reverse by allowing other clients to have no knowledge of your domain objects but still interact with your service via XML.</p>\n"
},
{
"answer_id": 20251,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p><strong>Daniel Auger:</strong><br>\n As others have said, it is possible.\n However, if both the service and\n client use an object that has the\n exact same domain behavior on both\n sides, you probably didn't need a\n service in the first place.</p>\n </blockquote>\n \n <p><strong>lomax:</strong>\n I have to disagree with this as it's a\n somewhat narrow comment. Using a\n webservice that can serialize domain\n objects to XML means that it makes it\n easy for clients that work with the\n same domain objects, but it also means\n that those clients are restricted to\n using that particular web service\n you've exposed and it also works in\n reverse by allowing other clients to\n have no knowledge of your domain\n objects but still interact with your\n service via XML.</p>\n</blockquote>\n\n<p>@ Lomax: You've described two scenarios. <strong>Scenario 1:</strong> The client is rehydrating the xml message back into the exact same domain object. I consider this to be \"returning an object\". In my experience this is a bad choice and I'll explain this below. <strong>Scenario 2:</strong> The client rehydrates the xml message into something other than the exact same domain object: I am 100% behind this, however I don't consider this to be returning a domain object. It's really sending a message or DTO.</p>\n\n<p>Now let me explain why true/pure/not DTO object serialization across a web service is <em>usually</em> a bad idea. An assertion: in order to do this in the first place, you either have to be the owner of both the client and the service, or provide the client with a library to use so that they can rehydrate the object back into it's true type. The problem: This domain object as a type now exists in and belongs to two semi-related domains. Over time, behaviors may need to be added in one domain that make no sense in the other domain and this leads to pollution and potentially painful problems. </p>\n\n<p>I usually default to scenario 2. I only use scenario 1 when there is an overwhelming reason to do so.</p>\n\n<p>I apologize for being so terse with my initial reply. I hope this clears things up to a degree as far as what my opinion is. Lomax, it would seem we half agree ;).</p>\n"
},
{
"answer_id": 20401,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 1,
"selected": false,
"text": "<p>JSON is a pretty standard way to pass objects around the web (as a subset of javascript). Many languages feature a library which will convert JSON code into a native object - see for example <a href=\"http://undefined.org/python/#simplejson\" rel=\"nofollow noreferrer\">simplejson</a> in Python.</p>\n\n<p>For more libraries for JSON use, see the <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON webpage</a></p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391/"
] | Instead of returning a common string, is there a way to return classic objects?
If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? | As mentioned, you can do this in .net via serialization. By default all native types are serializable so this happens automagically for you.
However if you have complex types, you need to mark the object with the [Serializable] attribute. The same goes with complex types as properties.
So for example you need to have:
```
[Serializable]
public class MyClass
{
public string MyString {get; set;}
[Serializable]
public MyOtherClass MyOtherClassProperty {get; set;}
}
``` |
11,887 | <p>I get an Access is Denied error message when I use the strong name tool to create a new key to sign a .NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine.</p>
<pre><code>PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied.
</code></pre>
<p>What causes this problem and how can I fix it?</p>
<hr>
<blockquote>
<p>Are you running your PowerShell or
Command Prompt as an Administrator? I
found this to be the first place to
look until you get used to User Access
Control or by turning User Access
Control off.</p>
</blockquote>
<p>Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up.</p>
| [
{
"answer_id": 11891,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look until you get used to User Access Control or by turning User Access Control off.</p>\n"
},
{
"answer_id": 11898,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>Yes I have tried running PS and the\n regular command prompt as\n administrator. The same error message\n comes up.</p>\n</blockquote>\n\n<p>Another possible solution could be that you need to give your user account access to the key container located at C:\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Crypto\\RSA\\MachineKeys</p>\n"
},
{
"answer_id": 11936,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>Why not fire up sysinternals Process Monitor too see what you can see, it's the first thing I always do when I get any kind of access denied message?</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx</a></p>\n"
},
{
"answer_id": 580612,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Some people rebuild their machines to resolve this problem, but it can be solved by giving user access to the key container <strong>C:\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Crypto\\RSA\\MachineKeys</strong>\nEach container created using sn.exe -i is located in the MachineKeys directory (unless you specify elsewhere). The default key container that is used by sn.exe is also in that location.</p>\n\n<p>In case you reset your key container to a new one, and forget where it is.. you can reset the key container for the strong name utility using sn.exe -c. So, if the account access fix doesn't work, you may be using an alternate key store so a reset may be in order.</p>\n"
},
{
"answer_id": 1816786,
"author": "ChrisWue",
"author_id": 220986,
"author_profile": "https://Stackoverflow.com/users/220986",
"pm_score": 2,
"selected": false,
"text": "<p>Just to update this a bit: I ran into the same problem on Vista. My local user on the PC had no problem but then we switched to a domain and my domain user (albeit having local admin rights) got \"Access Denied\".\nI granted my domain user access rights to <strong>C:\\Users\\All Users\\Microsoft\\Crypto\\RSA\\MachineKeys</strong> and that fixed it.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254/"
] | I get an Access is Denied error message when I use the strong name tool to create a new key to sign a .NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine.
```
PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied.
```
What causes this problem and how can I fix it?
---
>
> Are you running your PowerShell or
> Command Prompt as an Administrator? I
> found this to be the first place to
> look until you get used to User Access
> Control or by turning User Access
> Control off.
>
>
>
Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up. | >
> Yes I have tried running PS and the
> regular command prompt as
> administrator. The same error message
> comes up.
>
>
>
Another possible solution could be that you need to give your user account access to the key container located at C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys |
11,926 | <p>I'm new to MVC (and ASP.Net routing). I'm trying to map <code>*.aspx</code> to a controller called <code>PageController</code>. </p>
<pre><code>routes.MapRoute(
"Page",
"{name}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
</code></pre>
<p>Wouldn't the code above map *.aspx to <code>PageController</code>? When I run this and type in any .aspx page I get the following error:</p>
<blockquote>
<p>The controller for path '/Page.aspx' could not be found or it does not implement the IController interface.
Parameter name: controllerType</p>
</blockquote>
<p>Is there something I'm not doing here?</p>
| [
{
"answer_id": 11937,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure how your controller looks, the error seems to be pointing to the fact that it can't find the controller. Did you inherit off of Controller after creating the PageController class? Is the PageController located in the Controllers directory?</p>\n\n<p>Here is my route in the Global.asax.cs</p>\n\n<pre><code>routes.MapRoute(\n \"Page\", \n \"{Page}.aspx\", \n new { controller = \"Page\", action = \"Index\", id = \"\" }\n);\n</code></pre>\n\n<p>Here is my controller, which is located in the Controllers folder:</p>\n\n<pre><code>using System.Web.Mvc;\n\nnamespace MvcApplication1.Controllers\n{\n public class PageController : Controller\n {\n public void Index()\n {\n Response.Write(\"Page.aspx content.\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11946,
"author": "Ryan Eastabrook",
"author_id": 105,
"author_profile": "https://Stackoverflow.com/users/105",
"pm_score": 3,
"selected": false,
"text": "<p>I just answered my own question. I had the routes backwards (Default was above page). Below is the correct order. So this brings up the next question... how does the \"Default\" route match (I assume they use regular expressions here) the \"Page\" route?</p>\n\n<pre><code>routes.MapRoute(\n \"Page\",\n \"{Name}.aspx\",\n new { controller = \"Page\", action = \"Display\", id = \"\" }\n );\n\n routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n );\n</code></pre>\n"
},
{
"answer_id": 11957,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>I just answered my own question. I had\n the routes backwards (Default was\n above page).</p>\n</blockquote>\n\n<p>Yeah, you have to put all custom routes above the Default route.</p>\n\n<blockquote>\n <p>So this brings up the next question...\n how does the \"Default\" route match (I\n assume they use regular expressions\n here) the \"Page\" route?</p>\n</blockquote>\n\n<p>The Default route matches based on what we call Convention over Configuration. Scott Guthrie explains it well in his first blog post on ASP.NET MVC. I recommend that you read through it and also his other posts. Keep in mind that these were posted based on the first CTP and the framework has changed. You can also find web cast on ASP.NET MVC on the asp.net site by Scott Hanselman.</p>\n\n<ul>\n<li><a href=\"http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx</a></li>\n<li><a href=\"http://www.asp.net/MVC/\" rel=\"noreferrer\">http://www.asp.net/MVC/</a></li>\n</ul>\n"
},
{
"answer_id": 11962,
"author": "Chris Farmer",
"author_id": 404,
"author_profile": "https://Stackoverflow.com/users/404",
"pm_score": 1,
"selected": false,
"text": "<p>On one of Rob Conery's MVC Storefront <a href=\"http://www.asp.net/learn/3.5-SP1/video-356.aspx\" rel=\"nofollow noreferrer\">screencasts</a>, he encounters this exact issue. It's at around the 23 minute mark if you're interested.</p>\n"
},
{
"answer_id": 4840639,
"author": "Dayi Chen",
"author_id": 595443,
"author_profile": "https://Stackoverflow.com/users/595443",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public class AspxRouteConstraint : IRouteConstraint\n{\n #region IRouteConstraint Members\n\n public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n {\n return values[\"aspx\"].ToString().EndsWith(\".aspx\");\n }\n\n #endregion\n}\n</code></pre>\n\n<p>register the route for all aspx</p>\n\n<pre><code> routes.MapRoute(\"all\", \n \"{*aspx}\",//catch all url \n new { Controller = \"Page\", Action = \"index\" }, \n new AspxRouteConstraint() //return true when the url is end with \".aspx\"\n );\n</code></pre>\n\n<p>And you can test the routes by <a href=\"http://mvcroutevisualizer.codeplex.com\" rel=\"nofollow\">MvcRouteVisualizer</a> </p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] | I'm new to MVC (and ASP.Net routing). I'm trying to map `*.aspx` to a controller called `PageController`.
```
routes.MapRoute(
"Page",
"{name}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
```
Wouldn't the code above map \*.aspx to `PageController`? When I run this and type in any .aspx page I get the following error:
>
> The controller for path '/Page.aspx' could not be found or it does not implement the IController interface.
> Parameter name: controllerType
>
>
>
Is there something I'm not doing here? | >
> I just answered my own question. I had
> the routes backwards (Default was
> above page).
>
>
>
Yeah, you have to put all custom routes above the Default route.
>
> So this brings up the next question...
> how does the "Default" route match (I
> assume they use regular expressions
> here) the "Page" route?
>
>
>
The Default route matches based on what we call Convention over Configuration. Scott Guthrie explains it well in his first blog post on ASP.NET MVC. I recommend that you read through it and also his other posts. Keep in mind that these were posted based on the first CTP and the framework has changed. You can also find web cast on ASP.NET MVC on the asp.net site by Scott Hanselman.
* <http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx>
* <http://www.asp.net/MVC/> |
11,930 | <p>How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?</p>
<p>This is somewhat easy in .NET if you know your way around. But how do you do it in Java?</p>
| [
{
"answer_id": 11943,
"author": "Brian",
"author_id": 725,
"author_profile": "https://Stackoverflow.com/users/725",
"pm_score": 1,
"selected": false,
"text": "<p>That is not as easy as it sounds. Java is platform independent, so I am not sure how to do it in Java. I am <em>guessing</em> that .NET contacts some web site which reports it back. There are a couple ways to go. First, a deeper look into the ICMP protocol may give you the information you need. You can also trace the IP you go through (your route). When you encounter an IP that is not in the following ranges:</p>\n\n<ul>\n<li>10.0.0.0 – 10.255.255.255</li>\n<li>172.16.0.0 – 172.31.255.255</li>\n<li>192.168.0.0 – 192.168.255.255</li>\n</ul>\n\n<p>it is the IP one hop away from yours, and probably shares a few octets of information with your IP.</p>\n\n<p>Best of luck. I'll be curious to hear a definitive answer to this question.</p>\n"
},
{
"answer_id": 11960,
"author": "Nick Brosnahan",
"author_id": 528,
"author_profile": "https://Stackoverflow.com/users/528",
"pm_score": 1,
"selected": false,
"text": "<p>Try shelling out to traceroute if you have it.</p>\n\n<p>'traceroute -m 1 www.amazon.com' will emit something like this:</p>\n\n<pre><code>traceroute to www.amazon.com (72.21.203.1), 1 hops max, 40 byte packets\n 1 10.0.1.1 (10.0.1.1) 0.694 ms 0.445 ms 0.398 ms\n</code></pre>\n\n<p>Parse the second line. Yes, it's ugly, but it'll get you going until someone posts something nicer.</p>\n"
},
{
"answer_id": 12013,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 2,
"selected": false,
"text": "<p>You may be better off using something like checkmyip.org, which will determine your public IP address - not necessarily your first hop router: at Uni I have a \"real\" IP address, whereas at home it is my local router's public IP address.</p>\n\n<p>You can parse the page that returns, or find another site that allows you to just get the IP address back as the only string.</p>\n\n<p>(I'm meaning load this URL in Java/whatever, and then get the info you need).</p>\n\n<p>This should be totally platform independent.</p>\n"
},
{
"answer_id": 12027,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "<p>Matthew: Yes, that is what I meant by \"I can get my internet IP using a service on a website.\" Sorry about being glib.</p>\n\n<p>Brian/Nick: Traceroute would be fine except for the fact that lots of these routers have ICMP disabled and thus it always stalls.</p>\n\n<p>I think a combination of traceroute and uPnP will work out. That is what I was planning on doing, I as just hoping I was missing something obvious.</p>\n\n<p>Thank you everyone for your comments, so it sounds like I'm not missing anything obvious. I have begun implementing some bits of uPnP in order to discover the gateway.</p>\n"
},
{
"answer_id": 12030,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 5,
"selected": true,
"text": "<p>Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did:</p>\n\n<pre><code>import java.io.*;\nimport java.util.*;\n\npublic class ExecTest {\n public static void main(String[] args) throws IOException {\n Process result = Runtime.getRuntime().exec(\"traceroute -m 1 www.amazon.com\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n String thisLine = output.readLine();\n StringTokenizer st = new StringTokenizer(thisLine);\n st.nextToken();\n String gateway = st.nextToken();\n System.out.printf(\"The gateway is %s\\n\", gateway);\n }\n}\n</code></pre>\n\n<p>This presumes that the gateway is the second token and not the third. If it is, you need to add an extra <code>st.nextToken();</code> to advance the tokenizer one more spot.</p>\n"
},
{
"answer_id": 46957,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 2,
"selected": false,
"text": "<p>Regarding UPnP: be aware that not all routers support UPnP. And if they do it could be switched off (for security reasons). So your solution might not always work.</p>\n\n<p>You should also have a look at NatPMP.</p>\n\n<p>A simple library for UPnP can be found at <a href=\"http://miniupnp.free.fr/\" rel=\"nofollow noreferrer\">http://miniupnp.free.fr/</a>, though it's in C...</p>\n"
},
{
"answer_id": 61288,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 2,
"selected": false,
"text": "<p>To overcome the issues mentioned with traceroute (ICMP-based, wide area hit) you could consider:</p>\n\n<ol>\n<li>traceroute to your public IP (avoids wide-area hit, but still ICMP)</li>\n<li>Use a non-ICMP utility like ifconfig/ipconfig (portability issues with this though).</li>\n<li>What seems the best and most portable solution for now is to shell & parse netstat (see the code example <a href=\"http://forums.sun.com/thread.jspa?threadID=5289135\" rel=\"nofollow noreferrer\">here</a>) </li>\n</ol>\n"
},
{
"answer_id": 61308,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 3,
"selected": false,
"text": "<p>On windows parsing the output of IPConfig will get you the default gateway, without waiting for a trace.</p>\n"
},
{
"answer_id": 247216,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": false,
"text": "<p>On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using </p>\n\n<pre><code>netstat -rn\n</code></pre>\n\n<p>in place of a <code>traceroute</code> command.</p>\n\n<p>Your gateway's IP address will appear in the second field of the line that starts either <code>default</code> or <code>0.0.0.0</code>.</p>\n\n<p>This gets around a number of problems with trying to use <code>traceroute</code>:</p>\n\n<ol>\n<li>on Windows <code>traceroute</code> is actually <code>tracert.exe</code>, so there's no need for O/S dependencies in the code</li>\n<li>it's a quick command to run - it gets information from the O/S, not from the network</li>\n<li><code>traceroute</code> is sometimes blocked by the network</li>\n</ol>\n\n<p>The only downside is that it will be necessary to keep reading lines from the <code>netstat</code> output until the right line is found, since there'll be more than one line of output.</p>\n\n<p><strong>EDIT:</strong> The Default Gateway's IP Address is in the second field of the line that starts with 'default' if you are on a MAC (tested on Lion), or in the <strong>third field</strong> of the line that starts with '0.0.0.0' (tested on Windows 7)</p>\n\n<p>Windows:</p>\n\n<blockquote>\n <blockquote>\n <p>Network Destination Netmask Gateway Interface Metric</p>\n \n <p>0.0.0.0 0.0.0.0 <strong>192.168.2.254</strong> 192.168.2.46 10</p>\n </blockquote>\n</blockquote>\n\n<p>Mac:</p>\n\n<blockquote>\n <blockquote>\n <p>Destination Gateway Flags Refs Use Netif Expire</p>\n \n <p>default <strong>192.168.2.254</strong> UGSc 104 4 en1</p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 248179,
"author": "Hamza Yerlikaya",
"author_id": 29742,
"author_profile": "https://Stackoverflow.com/users/29742",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-java prettyprint-override\"><code> try{\n String gateway;\n Process result = Runtime.getRuntime().exec(\"netstat -rn\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n\n String line = output.readLine();\n while(line != null){\n if ( line.trim().startsWith(\"default\") == true || line.trim().startsWith(\"0.0.0.0\") == true )\n break; \n line = output.readLine();\n }\n if(line==null) //gateway not found;\n return;\n\n StringTokenizer st = new StringTokenizer( line );\n st.nextToken();\n st.nextToken();\n gateway = st.nextToken();\n System.out.println(\"gateway is: \"+gateway);\n\n\n } catch( Exception e ) { \n System.out.println( e.toString() );\n gateway = new String();\n adapter = new String();\n }\n</code></pre>\n"
},
{
"answer_id": 274999,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can query the URL \"<a href=\"http://whatismyip.com/automation/n09230945.asp\" rel=\"nofollow noreferrer\">http://whatismyip.com/automation/n09230945.asp</a>\".\nFor example:</p>\n\n<pre><code> BufferedReader buffer = null;\n try {\n URL url = new URL(\"http://whatismyip.com/automation/n09230945.asp\");\n InputStreamReader in = new InputStreamReader(url.openStream());\n buffer = new BufferedReader(in);\n\n String line = buffer.readLine();\n System.out.println(line);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (buffer != null) {\n buffer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 781223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>output of netstat -rn is locale specific.\non my system (locale=de) the output looks like:\n...\nStandardgateway: 10.22.0.1</p>\n\n<p>so there is no line starting with 'default'.</p>\n\n<p>so using netstat might be no good idea.</p>\n"
},
{
"answer_id": 9005568,
"author": "Loki Nightray",
"author_id": 1169530,
"author_profile": "https://Stackoverflow.com/users/1169530",
"pm_score": 2,
"selected": false,
"text": "<p>This Version connects to www.whatismyip.com, reads the content of the site and searches via regular expressions the ip adress and prints it to the cmd. Its a little improvement of MosheElishas Code</p>\n\n<pre><code>import java.io.BufferedReader; \nimport java.io.IOException; \nimport java.io.InputStreamReader; \nimport java.net.URL; \nimport java.util.regex.Matcher; \nimport java.util.regex.Pattern; \n\npublic class Main {\n\n public static void main(String[] args) {\n BufferedReader buffer = null;\n try {\n URL url = new URL(\n \"http://www.whatismyip.com/tools/ip-address-lookup.asp\");\n InputStreamReader in = new InputStreamReader(url.openStream());\n buffer = new BufferedReader(in);\n String line = buffer.readLine();\n Pattern pattern = Pattern\n .compile(\"(.*)value=\\\"(\\\\d+).(\\\\d+).(\\\\d+).(\\\\d+)\\\"(.*)\");\n Matcher matcher;\n while (line != null) {\n matcher = pattern.matcher(line);\n if (matcher.matches()) {\n line = matcher.group(2) + \".\" + matcher.group(3) + \".\"\n + matcher.group(4) + \".\" + matcher.group(5);\n System.out.println(line);\n }\n line = buffer.readLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n\n } finally {\n try {\n if (buffer != null) {\n buffer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n\nimport java.io.BufferedReader; \nimport java.io.IOException; \nimport java.io.InputStreamReader; \nimport java.net.URL; \nimport java.util.regex.Matcher; \nimport java.util.regex.Pattern; \n\npublic class Main {\n\n public static void main(String[] args) {\n BufferedReader buffer = null;\n try {\n URL url = new URL(\n \"http://www.whatismyip.com/tools/ip-address-lookup.asp\");\n InputStreamReader in = new InputStreamReader(url.openStream());\n buffer = new BufferedReader(in);\n String line = buffer.readLine();\n Pattern pattern = Pattern\n .compile(\"(.*)value=\\\"(\\\\d+).(\\\\d+).(\\\\d+).(\\\\d+)\\\"(.*)\");\n Matcher matcher;\n while (line != null) {\n matcher = pattern.matcher(line);\n if (matcher.matches()) {\n line = matcher.group(2) + \".\" + matcher.group(3) + \".\"\n + matcher.group(4) + \".\" + matcher.group(5);\n System.out.println(line);\n }\n line = buffer.readLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n\n } finally {\n try {\n if (buffer != null) {\n buffer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20806279,
"author": "ZZ 5",
"author_id": 1646298,
"author_profile": "https://Stackoverflow.com/users/1646298",
"pm_score": 1,
"selected": false,
"text": "<p>In windows you can just use the following command:</p>\n\n<pre><code>ipconfig | findstr /i \"Gateway\"\n</code></pre>\n\n<p>Which will give you output like:</p>\n\n<pre><code>Default Gateway . . . . . . . . . : 192.168.2.1\nDefault Gateway . . . . . . . . . : ::\n</code></pre>\n\n<p>However I can't run this command with Java, gonna post when I figure this out.</p>\n"
},
{
"answer_id": 36679773,
"author": "chandan",
"author_id": 6216657,
"author_profile": "https://Stackoverflow.com/users/6216657",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>netstat -rn</code> command which is available on Windows, OSX, Linux, etc platform. Here is my code:</p>\n\n<pre><code>private String getDefaultAddress() {\n String defaultAddress = \"\";\n try {\n Process result = Runtime.getRuntime().exec(\"netstat -rn\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(\n result.getInputStream()));\n\n String line = output.readLine();\n while (line != null) {\n if (line.contains(\"0.0.0.0\")) {\n\n StringTokenizer stringTokenizer = new StringTokenizer(line);\n stringTokenizer.nextElement(); // first element is 0.0.0.0\n stringTokenizer.nextElement(); // second element is 0.0.0.0\n defaultAddress = (String) stringTokenizer.nextElement();\n break;\n }\n\n line = output.readLine();\n\n } // while\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n return defaultAddress;\n\n} // getDefaultAddress\n</code></pre>\n"
},
{
"answer_id": 54699876,
"author": "PCK4D",
"author_id": 5750738,
"author_profile": "https://Stackoverflow.com/users/5750738",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if it works on every system but at least here I found this:</p>\n\n<pre><code>import java.net.InetAddress;\nimport java.net.UnknownHostException;\npublic class Main\n{\n public static void main(String[] args)\n {\n try\n {\n //Variables to find out the Default Gateway IP(s)\n String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();\n String hostName = InetAddress.getLocalHost().getHostName();\n\n //\"subtract\" the hostName from the canonicalHostName, +1 due to the \".\" in there\n String defaultGatewayLeftover = canonicalHostName.substring(hostName.length() + 1);\n\n //Info printouts\n System.out.println(\"Info:\\nCanonical Host Name: \" + canonicalHostName + \"\\nHost Name: \" + hostName + \"\\nDefault Gateway Leftover: \" + defaultGatewayLeftover + \"\\n\");\n System.out.println(\"Default Gateway Addresses:\\n\" + printAddresses(InetAddress.getAllByName(defaultGatewayLeftover)));\n } catch (UnknownHostException e)\n {\n e.printStackTrace();\n }\n }\n //simple combined string out of the address array\n private static String printAddresses(InetAddress[] allByName)\n {\n if (allByName.length == 0)\n {\n return \"\";\n } else\n {\n String str = \"\";\n int i = 0;\n while (i < allByName.length - 1)\n {\n str += allByName[i] + \"\\n\";\n i++;\n }\n return str + allByName[i];\n }\n }\n}\n</code></pre>\n\n<p>For me this produces:</p>\n\n<pre><code>Info:\nCanonical Host Name: PCK4D-PC.speedport.ip\nHost Name: PCK4D-PC\nDefault Gateway Leftover: speedport.ip\n\nDefault Gateway Addresses:\nspeedport.ip/192.168.2.1\nspeedport.ip/fe80:0:0:0:0:0:0:1%12\n</code></pre>\n\n<p>I'd require more tests on other Systems/Configurations/PC-Gateway-Setups to confirm if it works everywhere. Kind of doubt it but this was the first I found.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?
This is somewhat easy in .NET if you know your way around. But how do you do it in Java? | Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did:
```
import java.io.*;
import java.util.*;
public class ExecTest {
public static void main(String[] args) throws IOException {
Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");
BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
String thisLine = output.readLine();
StringTokenizer st = new StringTokenizer(thisLine);
st.nextToken();
String gateway = st.nextToken();
System.out.printf("The gateway is %s\n", gateway);
}
}
```
This presumes that the gateway is the second token and not the third. If it is, you need to add an extra `st.nextToken();` to advance the tokenizer one more spot. |
11,974 | <p>Basically, something better than this:</p>
<pre><code><input type="file" name="myfile" size="50">
</code></pre>
<p>First of all, the <code>browse</code> button looks different on every browser. Unlike the <code>submit</code> button on a form, you have to come up with some <a href="http://www.quirksmode.org/dom/inputfile.html" rel="nofollow noreferrer">hack-y</a> way to style it.</p>
<p>Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning.</p>
<p>Are there any good solutions to this that don't use Flash or Java?</p>
<p><a href="https://stackoverflow.com/questions/11974/what-is-the-best-way-to-upload-a-file-via-an-http-post-with-a-web-form#12005">Yaakov</a>: That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for <code>ASP.NET.</code> Are there any open source projects that cover the same or similar functionality?</p>
| [
{
"answer_id": 12005,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 0,
"selected": false,
"text": "<p>It is true, the file upload control is definitely behind the times. Hopefully this will be addressed in a future asp.net version.</p>\n\n<p>Though it costs some money, I have found the <a href=\"http://www.telerik.com/products/aspnet-ajax/controls/upload/overview.aspx\" rel=\"nofollow noreferrer\">Telerik upload control</a> to have all of the functionality that you are looking for, including styling and progress updates (it also optimizes memory for large uploads).</p>\n"
},
{
"answer_id": 12057,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 4,
"selected": true,
"text": "<p>File upload boxes is where we're currently at if you don't want to involve other technologies like Flash, Java or ActiveX.</p>\n\n<p>With plain HTML you are pretty much limited to the experience you've described (no progress bar, double submits, etc). If you are willing to use some javascript, you can solve some of the problems by giving feedback that the upload is in progress and even <a href=\"http://www.raditha.com/php/progress.php\" rel=\"noreferrer\">showing the upload progress</a> (it is a hack because you shouldn't have to do a full round-trip to the server and back, but at least it works).</p>\n\n<p>If you are willing to use Flash (which is available pretty much anywhere and on many platforms), you can overcome pretty much all of these problems. A quick googling turned up <a href=\"http://www.downloadsquad.com/2006/11/16/swfupload-open-source-flash-multi-file-upload/\" rel=\"noreferrer\">two</a> <a href=\"http://www.codeproject.com/KB/aspnet/FlashUpload.aspx\" rel=\"noreferrer\">such</a> components, both of them free <em>and</em> open source. I never used any of them, but they look good. BTW, Flash isn't without its problems either, for example when using the multi-file uploader for slide share, the browser kept constantly crashing on me :-(</p>\n\n<p>Probably the best solution currently is to detect dynamically if the user has Flash, and if it's the case, give her the flash version of the uploader, while still making it possible to choose the basic HTML one.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 12058,
"author": "DylanJ",
"author_id": 87,
"author_profile": "https://Stackoverflow.com/users/87",
"pm_score": 1,
"selected": false,
"text": "<p>You could have a look at the <a href=\"http://digitarald.de/project/fancyupload/\" rel=\"nofollow noreferrer\">Fancy Upload</a> script. Though it uses flash it still looks great.</p>\n"
},
{
"answer_id": 12087,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>The problem here is that the browsers specifically work to block anything that changes the basic file upload input control. You can't change it with javascript for instance.</p>\n\n<p>The reason is security - if I could script it I could build a page that when you visited it sent me various files from your hard disk. Not nice.</p>\n\n<p>There are various workarounds at the moment, but they're different between IE and FX (I don't know about Safari, Opera, etc).</p>\n\n<p>Look at what <a href=\"http://www.gmail.com\" rel=\"nofollow noreferrer\">http://www.gmail.com</a> does in IE and FX when you attach something to an e-mail.</p>\n\n<p>I want to see that rubbish \"Browse\" button - it tells me that I'm not letting anything unexpected in.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/11974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396/"
] | Basically, something better than this:
```
<input type="file" name="myfile" size="50">
```
First of all, the `browse` button looks different on every browser. Unlike the `submit` button on a form, you have to come up with some [hack-y](http://www.quirksmode.org/dom/inputfile.html) way to style it.
Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning.
Are there any good solutions to this that don't use Flash or Java?
[Yaakov](https://stackoverflow.com/questions/11974/what-is-the-best-way-to-upload-a-file-via-an-http-post-with-a-web-form#12005): That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for `ASP.NET.` Are there any open source projects that cover the same or similar functionality? | File upload boxes is where we're currently at if you don't want to involve other technologies like Flash, Java or ActiveX.
With plain HTML you are pretty much limited to the experience you've described (no progress bar, double submits, etc). If you are willing to use some javascript, you can solve some of the problems by giving feedback that the upload is in progress and even [showing the upload progress](http://www.raditha.com/php/progress.php) (it is a hack because you shouldn't have to do a full round-trip to the server and back, but at least it works).
If you are willing to use Flash (which is available pretty much anywhere and on many platforms), you can overcome pretty much all of these problems. A quick googling turned up [two](http://www.downloadsquad.com/2006/11/16/swfupload-open-source-flash-multi-file-upload/) [such](http://www.codeproject.com/KB/aspnet/FlashUpload.aspx) components, both of them free *and* open source. I never used any of them, but they look good. BTW, Flash isn't without its problems either, for example when using the multi-file uploader for slide share, the browser kept constantly crashing on me :-(
Probably the best solution currently is to detect dynamically if the user has Flash, and if it's the case, give her the flash version of the uploader, while still making it possible to choose the basic HTML one.
HTH |
12,009 | <p>How can I pipe the new password to smbpasswd so I can automate my installation process.</p>
| [
{
"answer_id": 12016,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": -1,
"selected": false,
"text": "<p>using either <a href=\"http://en.wikipedia.org/wiki/Pipeline_(Unix)\" rel=\"nofollow noreferrer\">pipelines</a> or <a href=\"http://en.wikipedia.org/wiki/Redirection_(Unix)\" rel=\"nofollow noreferrer\">redirection</a>.</p>\n"
},
{
"answer_id": 12026,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": false,
"text": "<p>Try something like this:</p>\n\n<pre><code>(echo oldpasswd; echo newpasswd) | smbpasswd -s\n</code></pre>\n"
},
{
"answer_id": 12032,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 7,
"selected": true,
"text": "<p>Thanks to Mark I found the answer:</p>\n\n<pre><code>(echo newpassword; echo confirmNewPassword) | smbpasswd -s\n</code></pre>\n\n<p>BTW: (echo oldpasswd; echo newpasswd) | smbpasswd -s does not work.</p>\n"
},
{
"answer_id": 62796,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 5,
"selected": false,
"text": "<p>I use the following in one of my scripts: </p>\n\n<pre><code> echo -ne \"$PASS\\n$PASS\\n\" | smbpasswd -a -s $LOGIN\n</code></pre>\n\n<p>With echo:</p>\n\n<p>-e : escape sequences, like \\n</p>\n\n<p>-n : don't add implicit newline at end</p>\n\n<p>With smbpasswd:</p>\n\n<p>-a : add new user</p>\n\n<p>-s : silent</p>\n"
},
{
"answer_id": 15841153,
"author": "Charles Prince",
"author_id": 2001428,
"author_profile": "https://Stackoverflow.com/users/2001428",
"pm_score": 1,
"selected": false,
"text": "<p>This unfortunately is not desirable for two reasons:\n1) if the user uses a combination of '\\n' in the password there will be a mismatch in the input\n2) if there are unix users on the system, then a user using the utility ps may see the password</p>\n\n<p>A better way would be to put the names in a file and read from the file and use python pexpect to read them, not like below, but the simple script is enough to see how to use pexpect</p>\n\n<pre><code>#!/usr/bin/python\n#converted from: http://pexpect.sourceforge.net/pexpect.html\n#child = pexpect.spawn('scp foo [email protected]:.')\n#child.expect ('Password:')\n#child.sendline (mypassword)\nimport pexpect\nimport sys\nuser=sys.argv[1]\npasswd=sys.argv[2]\nchild = pexpect.spawn('/usr/bin/smbpasswd -a '+str(user))\nchild.expect('New SMB password:')\nchild.sendline (passwd)\nchild.expect ('Retype new SMB password:')\nchild.sendline (passwd)\n</code></pre>\n\n<p>then try: ./smbpasswd.py userName1 'f#@(&*(_\\n895'</p>\n"
},
{
"answer_id": 19770281,
"author": "ReklatsMasters",
"author_id": 1556249,
"author_profile": "https://Stackoverflow.com/users/1556249",
"pm_score": 3,
"selected": false,
"text": "<p>Use this\n<code>echo 'somepassword' | tee - | smbpasswd -s</code></p>\n"
},
{
"answer_id": 53428249,
"author": "Samuli Seppänen",
"author_id": 2543558,
"author_profile": "https://Stackoverflow.com/users/2543558",
"pm_score": 2,
"selected": false,
"text": "<p>I had to create a new Samba user in a Puppet 5.x Exec resource and for various reasons none of the above worked. Fortunately this rather silly-looking command worked:</p>\n\n<pre><code>yes vagrant|head -n 2|smbpasswd -a -s vagrant\n</code></pre>\n\n<p>Password here is of course \"vagrant\".</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | How can I pipe the new password to smbpasswd so I can automate my installation process. | Thanks to Mark I found the answer:
```
(echo newpassword; echo confirmNewPassword) | smbpasswd -s
```
BTW: (echo oldpasswd; echo newpasswd) | smbpasswd -s does not work. |
12,039 | <p>I have an application that sometimes causes a BSOD on a Win XP machine. Trying to find out more, I loaded up the resulting *.dmp file (from C:\Windows\Minidump), but get this message when in much of the readout when doing so:</p>
<pre><code>*********************************************************************
* Symbols can not be loaded because symbol path is not initialized. *
* *
* The Symbol Path can be set by: *
* using the _NT_SYMBOL_PATH environment variable. *
* using the -y <symbol_path> argument when starting the debugger. *
* using .sympath and .sympath+ *
*********************************************************************
</code></pre>
<p>What does this mean, and how do I "fix" it?</p>
| [
{
"answer_id": 12043,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>you actually need to either download the symbols to your computer, or configure it to download as you go if you are online while debugging.</p>\n\n<p>Here's the link that talks about this in detail: <a href=\"http://www.microsoft.com/whdc/DevTools/Debugging/debugstart.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/whdc/DevTools/Debugging/debugstart.mspx</a></p>\n"
},
{
"answer_id": 12071,
"author": "staffan",
"author_id": 988,
"author_profile": "https://Stackoverflow.com/users/988",
"pm_score": 3,
"selected": false,
"text": "<p>Quick answer is to </p>\n\n<p>c:\\> set _NT_SYMBOL_PATH=SRV*C:\\WINDOWS\\Symbols*http://msdl.microsoft.com/download/symbols</p>\n\n<p>before starting windbg.</p>\n"
},
{
"answer_id": 12132,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>I usually go to the System control panel, then Advanced tab, then Environment. You can then add the requisite <code>_NT_SYMBOL_PATH</code> variable. Then you don't have to do anything on the command-line before running WinDbg.</p>\n\n<p>The setting of <code>srv*C:\\Windows\\Symbols*http</code>:<code>//msdl.microsoft.com/download/symbols</code> as suggested by staffan is fine. I usually prefer to use my own profile for storing symbols though (so that I don't need to edit the permissions for <code>C:\\Windows\\Symbols</code>, since I intentionally run as a limited user, for good security hygiene). Thus (in my case) my <code>_NT_SYMBOL_PATH</code> is <code>srv*C:\\Documents and Settings\\cky\\symbols*http</code>:<code>//msdl.microsoft.com/download/symbols</code>.</p>\n\n<p>Hope this helps. :-)</p>\n"
},
{
"answer_id": 92760,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 1,
"selected": false,
"text": "<p>As @Vaibhav noted, you actually need to download the symbols and configure windbg to use them.</p>\n\n<p>Also note the following:\n!sym noisy -- Activates noisy symbol loading\nlm v -- Use with \"m\" parameter to look at information for a loaded module.\nlme D sm - List all modules w/o symbols.</p>\n"
},
{
"answer_id": 1493488,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Quicker answer:</p>\n\n<pre><code>!symfix\n</code></pre>\n\n<p>But it only affects the current windbg/ntsd/cdb/kd.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have an application that sometimes causes a BSOD on a Win XP machine. Trying to find out more, I loaded up the resulting \*.dmp file (from C:\Windows\Minidump), but get this message when in much of the readout when doing so:
```
*********************************************************************
* Symbols can not be loaded because symbol path is not initialized. *
* *
* The Symbol Path can be set by: *
* using the _NT_SYMBOL_PATH environment variable. *
* using the -y <symbol_path> argument when starting the debugger. *
* using .sympath and .sympath+ *
*********************************************************************
```
What does this mean, and how do I "fix" it? | Quick answer is to
c:\> set \_NT\_SYMBOL\_PATH=SRV\*C:\WINDOWS\Symbols\*http://msdl.microsoft.com/download/symbols
before starting windbg. |
12,051 | <p>If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?</p>
<p>For example, if I inherit from the Exception class I want to do something like this:</p>
<pre><code>class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
</code></pre>
<p>Basically what I want is to be able to pass the string message to the base Exception class.</p>
| [
{
"answer_id": 12052,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 12,
"selected": true,
"text": "<p>Modify your constructor to the following so that it calls the base class constructor properly:</p>\n\n<pre><code>public class MyExceptionClass : Exception\n{\n public MyExceptionClass(string message, string extrainfo) : base(message)\n {\n //other stuff here\n }\n}\n</code></pre>\n\n<p>Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.</p>\n"
},
{
"answer_id": 1844965,
"author": "SnowBEE",
"author_id": 224505,
"author_profile": "https://Stackoverflow.com/users/224505",
"pm_score": 5,
"selected": false,
"text": "<pre><code>public class MyExceptionClass : Exception\n{\n public MyExceptionClass(string message,\n Exception innerException): base(message, innerException)\n {\n //other stuff here\n }\n}\n</code></pre>\n\n<p>You can pass inner exception to one of the constructors.</p>\n"
},
{
"answer_id": 2731807,
"author": "Axl",
"author_id": 16605,
"author_profile": "https://Stackoverflow.com/users/16605",
"pm_score": 9,
"selected": false,
"text": "<p>Note that you can use <strong>static</strong> methods within the call to the base constructor.</p>\n\n<pre><code>class MyExceptionClass : Exception\n{\n public MyExceptionClass(string message, string extraInfo) : \n base(ModifyMessage(message, extraInfo))\n {\n }\n\n private static string ModifyMessage(string message, string extraInfo)\n {\n Trace.WriteLine(\"message was \" + message);\n return message.ToLowerInvariant() + Environment.NewLine + extraInfo;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15103087,
"author": "aalimian",
"author_id": 1490214,
"author_profile": "https://Stackoverflow.com/users/1490214",
"pm_score": 7,
"selected": false,
"text": "<p>If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.</p>\n\n<pre><code>public class MyClass : BaseClass\n{\n private MyClass(string someString) : base(someString)\n {\n //your code goes in here\n }\n\n public static MyClass FactoryMethod(string someString)\n {\n //whatever you want to do with your string before passing it in\n return new MyClass(someString);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19905310,
"author": "Janus Pedersen",
"author_id": 1032159,
"author_profile": "https://Stackoverflow.com/users/1032159",
"pm_score": 5,
"selected": false,
"text": "<p>It is true use the <code>base</code> (something) to call the base class constructor, but in case of overloading use the <code>this</code> keyword</p>\n\n<pre><code>public ClassName() : this(par1,par2)\n{\n// do not call the constructor it is called in the this.\n// the base key- word is used to call a inherited constructor \n} \n\n// Hint used overload as often as needed do not write the same code 2 or more times\n</code></pre>\n"
},
{
"answer_id": 34973293,
"author": "Fab",
"author_id": 5328150,
"author_profile": "https://Stackoverflow.com/users/5328150",
"pm_score": 5,
"selected": false,
"text": "<p><strong>From <a href=\"https://books.google.co.th/books?id=39d1wZ598ecC&pg=PT394&lpg=PT394&dq=exception%20fxcop&source=bl&ots=bO6nGDVi4f&sig=DFZ7ucCPK__LvIzTVaTSZ2rlXpY&hl=fr&sa=X&ved=0ahUKEwi88-qO9MHKAhUPH44KHVmdCh8Q6AEIUDAG#v=onepage&q=exception%20fxcop&f=false\">Framework Design Guidelines</a> and FxCop rules.</strong>:</p>\n\n<p><strong>1. Custom Exception should have a name that ends with Exception</strong></p>\n\n<pre><code> class MyException : Exception\n</code></pre>\n\n<p><strong>2. Exception should be public</strong></p>\n\n<pre><code> public class MyException : Exception\n</code></pre>\n\n<p><strong>3. <a href=\"https://msdn.microsoft.com/en-us/library/ms182151.aspx\">CA1032: Exception should implements standard constructors.</a></strong></p>\n\n<ul>\n<li>A public parameterless constructor.</li>\n<li>A public constructor with one string argument.</li>\n<li>A public constructor with one string and Exception (as it can wrap another Exception).</li>\n<li><p>A serialization constructor protected if the type is not sealed and private if the type is sealed. \nBased on <a href=\"https://msdn.microsoft.com/en-us/library/ms182151.aspx\">MSDN</a>:</p>\n\n<pre><code>[Serializable()]\npublic class MyException : Exception\n{\n public MyException()\n {\n // Add any type-specific logic, and supply the default message.\n }\n\n public MyException(string message): base(message) \n {\n // Add any type-specific logic.\n }\n public MyException(string message, Exception innerException): \n base (message, innerException)\n {\n // Add any type-specific logic for inner exceptions.\n }\n protected MyException(SerializationInfo info, \n StreamingContext context) : base(info, context)\n {\n // Implement type-specific serialization constructor logic.\n }\n} \n</code></pre></li>\n</ul>\n\n<p>or</p>\n\n<pre><code> [Serializable()]\n public sealed class MyException : Exception\n {\n public MyException()\n {\n // Add any type-specific logic, and supply the default message.\n }\n\n public MyException(string message): base(message) \n {\n // Add any type-specific logic.\n }\n public MyException(string message, Exception innerException): \n base (message, innerException)\n {\n // Add any type-specific logic for inner exceptions.\n }\n private MyException(SerializationInfo info, \n StreamingContext context) : base(info, context)\n {\n // Implement type-specific serialization constructor logic.\n }\n } \n</code></pre>\n"
},
{
"answer_id": 36475682,
"author": "Donat Sasin",
"author_id": 5097657,
"author_profile": "https://Stackoverflow.com/users/5097657",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public class MyException : Exception\n{\n public MyException() { }\n public MyException(string msg) : base(msg) { }\n public MyException(string msg, Exception inner) : base(msg, inner) { }\n}\n</code></pre>\n"
},
{
"answer_id": 37492479,
"author": "dynamiclynk",
"author_id": 1427166,
"author_profile": "https://Stackoverflow.com/users/1427166",
"pm_score": 4,
"selected": false,
"text": "<p>You can also do a conditional check with parameters in the constructor, which allows some flexibility.</p>\n\n<pre><code>public MyClass(object myObject=null): base(myObject ?? new myOtherObject())\n{\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 42786257,
"author": "CShark",
"author_id": 3033876,
"author_profile": "https://Stackoverflow.com/users/3033876",
"pm_score": 4,
"selected": false,
"text": "<p>As per some of the other answers listed here, you can pass parameters into the base class constructor. It is advised to call your base class constructor at the beginning of the constructor for your inherited class.</p>\n\n<pre><code>public class MyException : Exception\n{\n public MyException(string message, string extraInfo) : base(message)\n {\n }\n}\n</code></pre>\n\n<p>I note that in your example you never made use of the <code>extraInfo</code> parameter, so I assumed you might want to concatenate the <code>extraInfo</code> string parameter to the <code>Message</code> property of your exception (it seems that this is being ignored in the accepted answer and the code in your question).</p>\n\n<p>This is simply achieved by invoking the base class constructor, and then updating the Message property with the extra info.</p>\n\n<pre><code>public class MyException: Exception\n{\n public MyException(string message, string extraInfo) : base($\"{message} Extra info: {extraInfo}\")\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 60657371,
"author": "springy76",
"author_id": 442376,
"author_profile": "https://Stackoverflow.com/users/442376",
"pm_score": 3,
"selected": false,
"text": "<p>Using newer C# features, namely <code>out var</code>, you can get rid of the static factory-method.\nI just found out (by accident) that out var parameter of methods called inse base-\"call\" flow to the constructor body.</p>\n\n<p>Example, using this base class you want to derive from:</p>\n\n<pre><code>public abstract class BaseClass\n{\n protected BaseClass(int a, int b, int c)\n {\n }\n}\n</code></pre>\n\n<p>The non-compiling pseudo code you want to execute:</p>\n\n<pre><code>public class DerivedClass : BaseClass\n{\n private readonly object fatData;\n\n public DerivedClass(int m)\n {\n var fd = new { A = 1 * m, B = 2 * m, C = 3 * m };\n base(fd.A, fd.B, fd.C); // base-constructor call\n this.fatData = fd;\n }\n}\n</code></pre>\n\n<p>And the solution by using a static private helper method which produces all required base arguments (plus additional data if needed) and without using a static factory method, just plain constructor to the outside:</p>\n\n<pre><code>public class DerivedClass : BaseClass\n{\n private readonly object fatData;\n\n public DerivedClass(int m)\n : base(PrepareBaseParameters(m, out var b, out var c, out var fatData), b, c)\n {\n this.fatData = fatData;\n Console.WriteLine(new { b, c, fatData }.ToString());\n }\n\n private static int PrepareBaseParameters(int m, out int b, out int c, out object fatData)\n {\n var fd = new { A = 1 * m, B = 2 * m, C = 3 * m };\n (b, c, fatData) = (fd.B, fd.C, fd); // Tuples not required but nice to use\n return fd.A;\n }\n}\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?
For example, if I inherit from the Exception class I want to do something like this:
```
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
```
Basically what I want is to be able to pass the string message to the base Exception class. | Modify your constructor to the following so that it calls the base class constructor properly:
```
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
```
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body. |
12,095 | <p>Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution.</p>
<p>The main sealed class 'ImportController' that does the work declares the following delegate event:</p>
<pre><code>public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e);
public static event ImportProgressEventHandler importProgressEvent;
</code></pre>
<p>The main window starts a static method in that class using a new thread:</p>
<pre><code>Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData));
dataProcessingThread.Name = "Data Importer: Data Processing Thread";
dataProcessingThread.Start(settings);
</code></pre>
<p>the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event:</p>
<pre><code>ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent);
</code></pre>
<p>And responds to the event in this manner using it's own delegate:</p>
<pre><code> private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e)
{
this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax);
}
</code></pre>
<p>Finally the progress bar and listbox are updated:</p>
<pre><code>private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax)
{
string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items)
{
this.lstTasks.Items.Add(item);
}
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax)
{
this.ImportProgressBar.Maximum = progressMax;
this.ImportProgressBar.Value = currentProgress;
}
}
</code></pre>
<p>The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway ??? what gives ?</p>
| [
{
"answer_id": 12104,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you can try the BackgroundWorker component. It makes threading easier. Examples here:</p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx\" rel=\"nofollow noreferrer\">BackgroundWorker Threads and Supporting Cancel</a></li>\n<li><a href=\"http://www.c-sharpcorner.com/UploadFile/LivMic/BGWorker07032007000515AM/BGWorker.aspx\" rel=\"nofollow noreferrer\">Using the BackgroundWorker Component in .NET 2 applications</a></li>\n<li><a href=\"http://www.danielmoth.com/Blog/2004/12/backgroundworker-sample.html\" rel=\"nofollow noreferrer\">BackgroundWorker Sample</a></li>\n</ul>\n"
},
{
"answer_id": 12109,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": -1,
"selected": false,
"text": "<p>Are you sure that the UI thread is running freely during all this process? i.e. it's not sitting blocked-up on a Join or some other wait? That's what it looks like to me.</p>\n\n<p>The suggestion of using BackgroundWorker is a good one - definitely superior to trying to sledge-hammer your way out of the problem with a load of Refresh/Update calls.</p>\n\n<p>And BackgroundWorker will use a pool thread, which is a friendlier way to behave than creating your own short-lived thread.</p>\n"
},
{
"answer_id": 12115,
"author": "Peteter",
"author_id": 1192,
"author_profile": "https://Stackoverflow.com/users/1192",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe outside of the scope but, to sometimes its useful to do an <code>Application.DoEvents();</code> to make the gui parts react to user input, such as pressing the cancel-button on a status bar dialog.</p>\n"
},
{
"answer_id": 12118,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>Do you by any chance run Windows Vista? I've noticed the exactly same thing in some work related applications. Somehow, there seem to be a delay when the progress bar \"animates\".</p>\n"
},
{
"answer_id": 12119,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 1,
"selected": true,
"text": "<p>@John</p>\n\n<p>Thanks for the links. </p>\n\n<p>@Will</p>\n\n<p>There's no gain from threadpooling as I know it will only ever spawn one thread. The use of a thread is purely to have a responsive UI while SQL Server is being pounded with reads and writes. It's certainly not a short lived thread.</p>\n\n<p>Regarding sledge-hammers you're right. But, as it turns out my problem was between screen and chair after all. I seem to have an unusal batch of data that has many many many more foreign key records than the other batches and just happens to get selected early in the process meaning the currentProgress doesn't get ++'d for a good 10 seconds. </p>\n\n<p>@All</p>\n\n<p>Thanks for all your input, it got me thinking, which got me looking elsewhere in the code, which led to my ahaa moment of humility where I prove yet again the error is usually human :)</p>\n"
},
{
"answer_id": 12125,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>There's no gain from threadpooling as\n I know it will only ever spawn one\n thread. The use of a thread is purely\n to have a responsive UI while SQL\n Server is being pounded with reads and\n writes. It's certainly not a short\n lived thread.</p>\n</blockquote>\n\n<p>OK, I appreciate that, and glad you found your bug, but have you looked at BackgroundWorker? It does pretty much exactly what you're doing, but in a standardised fashion (i.e. without your own delegates) and without the need to create a new thread - both of which are (perhaps small, but maybe still useful) advantages.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083160/"
] | Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution.
The main sealed class 'ImportController' that does the work declares the following delegate event:
```
public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e);
public static event ImportProgressEventHandler importProgressEvent;
```
The main window starts a static method in that class using a new thread:
```
Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData));
dataProcessingThread.Name = "Data Importer: Data Processing Thread";
dataProcessingThread.Start(settings);
```
the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event:
```
ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent);
```
And responds to the event in this manner using it's own delegate:
```
private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e)
{
this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax);
}
```
Finally the progress bar and listbox are updated:
```
private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax)
{
string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items)
{
this.lstTasks.Items.Add(item);
}
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax)
{
this.ImportProgressBar.Maximum = progressMax;
this.ImportProgressBar.Value = currentProgress;
}
}
```
The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway ??? what gives ? | @John
Thanks for the links.
@Will
There's no gain from threadpooling as I know it will only ever spawn one thread. The use of a thread is purely to have a responsive UI while SQL Server is being pounded with reads and writes. It's certainly not a short lived thread.
Regarding sledge-hammers you're right. But, as it turns out my problem was between screen and chair after all. I seem to have an unusal batch of data that has many many many more foreign key records than the other batches and just happens to get selected early in the process meaning the currentProgress doesn't get ++'d for a good 10 seconds.
@All
Thanks for all your input, it got me thinking, which got me looking elsewhere in the code, which led to my ahaa moment of humility where I prove yet again the error is usually human :) |
12,103 | <p>When I am running the following statement:</p>
<pre><code>@filtered = map {s/&nbsp;//g} @outdata;
</code></pre>
<p>it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of <code>&nbsp;</code> from an array of string (which is an XML file).</p>
<p>Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?</p>
| [
{
"answer_id": 12108,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>@filtered = map {s/&nbsp;//g; $_} @outdata;\n</code></pre>\n\n<p>The problem is the s operator in perl modifies $_ but actually returns the number of changes it made. So, the extra $_ at the end causes perl to return the modified string for each element of @outdata.</p>\n"
},
{
"answer_id": 13685,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": 2,
"selected": false,
"text": "<p>As a counterpoint to Greg's answer, you could misuse grep:</p>\n\n<pre><code>@filtered = grep {s/&nbsp;//g; 1} @outdata;\n</code></pre>\n\n<p><strong>Don't do this.</strong></p>\n"
},
{
"answer_id": 21792,
"author": "Tithonium",
"author_id": 2425,
"author_profile": "https://Stackoverflow.com/users/2425",
"pm_score": 4,
"selected": false,
"text": "<p>Note that map is going to modify your source array as well. So you could either do:</p>\n\n<pre><code>map {s/&nbsp;//g} @outdata;\n</code></pre>\n\n<p>and skip the @filtered variable altogether, or if you need to retain the originals,</p>\n\n<pre><code>@filtered = @outdata;\nmap {s/&nbsp;//g} @filtered;\n</code></pre>\n\n<p>Although, in that case, it might be more readable to use foreach:</p>\n\n<pre><code>s/&nbsp;//g foreach @filtered;\n</code></pre>\n"
},
{
"answer_id": 63167,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 3,
"selected": false,
"text": "<p>To follow up on Tithonium's point, this will also do the trick:</p>\n\n<pre><code>@filtered = map {local $_=$_; s/&nbsp;//g; $_} @outdata;\n</code></pre>\n\n<p>The \"local\" ensures you're working on a copy, not the original. </p>\n"
},
{
"answer_id": 63314,
"author": "Shlomi Fish",
"author_id": 7709,
"author_profile": "https://Stackoverflow.com/users/7709",
"pm_score": 3,
"selected": false,
"text": "<p>Greg's answer has the problem that it will modify the original array as the $_ are passed aliased. You need:</p>\n\n<pre><code>@filtered = map { (my $new = $_) =~ s/&nbsp;//g; $new} @outdata;\n</code></pre>\n"
},
{
"answer_id": 329969,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "<pre><code>use Algorithm::Loops \"Filter\";\n@filtered = Filter { s/&nbsp;//g } @outdata;\n</code></pre>\n"
},
{
"answer_id": 10657173,
"author": "pasja",
"author_id": 944375,
"author_profile": "https://Stackoverflow.com/users/944375",
"pm_score": 3,
"selected": false,
"text": "<p>In perl 5.14 you could use the <em>/r</em> regex modifier to <a href=\"http://perldoc.perl.org/perl5140delta.html#Regular-Expressions\">make non-destructive substitution</a>.</p>\n\n<pre><code>@filtered = map {s/&nbsp;//gr} @outdata;\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] | When I am running the following statement:
```
@filtered = map {s/ //g} @outdata;
```
it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of ` ` from an array of string (which is an XML file).
Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is? | Try this:
```
@filtered = map {s/ //g; $_} @outdata;
```
The problem is the s operator in perl modifies $\_ but actually returns the number of changes it made. So, the extra $\_ at the end causes perl to return the modified string for each element of @outdata. |
12,135 | <p>I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll</p>
<pre><code>XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) );
return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) );
</code></pre>
<p>This throws a caught <code>FileNotFoundException</code> when the assembly is loaded:</p>
<blockquote>
<p>"Could not load file or assembly
'mscorlib.XmlSerializers,
Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or
one of its dependencies. The system
cannot find the file specified."</p>
</blockquote>
<p>FusionLog:</p>
<pre><code>=== Pre-bind state information ===
LOG: User = ###
LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
(Fully-specified)
LOG: Appbase = file:///C:/localdir
LOG: Initial PrivatePath = NULL
Calling assembly : System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config
LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE.
</code></pre>
<p>As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by .Net looking for the serializer. </p>
<p>You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it.</p>
<p>The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point.</p>
<p>Any ideas how to avoid this or speed it up?</p>
| [
{
"answer_id": 12136,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>The delay is because, having been unable to find the custom serializer dll, the system is building the equivalent code (which is very time-consuming) on the fly.</p>\n\n<p>The way to avoid the delay is to have the system build the DLL, and make sure it's available to the .EXE - have you tried this?</p>\n"
},
{
"answer_id": 12160,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 3,
"selected": true,
"text": "<p>I'm guessing now. but:</p>\n\n<ol>\n<li>The system might be generating a serializer for the whole of mscorlib, which could be very slow.</li>\n<li>You could probably avoid this by wrapping the system type in your own type and serialising that instead - then you'd get a serializer for your own assembly.</li>\n<li>You might be able to build the serializer for mscorlib with sgen.exe, which was the old way of building serializer dlls before it got integrated into VS.</li>\n</ol>\n"
},
{
"answer_id": 953571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, so I ran into this problem and have found a solution for it specific to my area.</p>\n\n<p>This occurred because I was trying to serialize a list into an XML document (file) without an XML root attribute. Once I added the following files, the error goes away.</p>\n\n<pre><code>XmlRootAttribute rootAttribute = new XmlRootAttribute();\nrootAttribute.ElementName = \"SomeRootName\";\nrootAttribute.IsNullable = true;\n</code></pre>\n\n<p>Dunno if it'll fix your problem, but it fixed mine.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll
```
XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) );
return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) );
```
This throws a caught `FileNotFoundException` when the assembly is loaded:
>
> "Could not load file or assembly
> 'mscorlib.XmlSerializers,
> Version=2.0.0.0, Culture=neutral,
> PublicKeyToken=b77a5c561934e089' or
> one of its dependencies. The system
> cannot find the file specified."
>
>
>
FusionLog:
```
=== Pre-bind state information ===
LOG: User = ###
LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
(Fully-specified)
LOG: Appbase = file:///C:/localdir
LOG: Initial PrivatePath = NULL
Calling assembly : System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config
LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE.
```
As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by .Net looking for the serializer.
You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it.
The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point.
Any ideas how to avoid this or speed it up? | I'm guessing now. but:
1. The system might be generating a serializer for the whole of mscorlib, which could be very slow.
2. You could probably avoid this by wrapping the system type in your own type and serialising that instead - then you'd get a serializer for your own assembly.
3. You might be able to build the serializer for mscorlib with sgen.exe, which was the old way of building serializer dlls before it got integrated into VS. |
12,140 | <p>A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.</p>
<p>The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).</p>
<p>This works better, in any case much better than having all those objects need some global <em>Settings</em> object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.</p>
<p><strong>So the general question is</strong>: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...</p>
<p>(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)</p>
| [
{
"answer_id": 12161,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 0,
"selected": false,
"text": "<p>Usually this is handled by an ini file or XML configuration file. Then you just have a class that reads the setting when neeed.</p>\n\n<p>.NET has this built in with the ConfigurationManager classes, but it's quite easy to implement, just read text files, or load XML into DOM or parse them by hand in code.</p>\n\n<p>Having config files in the database is ok, but it does tie you to the database, and creates an extra dependancy for your app that ini/xml files solve.</p>\n"
},
{
"answer_id": 12183,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "<p>I did this:</p>\n\n<pre><code>public class MySettings\n{\n public static double Setting1\n { get { return SettingsCache.Instance.GetDouble(\"Setting1\"); } }\n\n public static string Setting2\n { get { return SettingsCache.Instance.GetString(\"Setting2\"); } }\n}\n</code></pre>\n\n<p>I put this in a separate infrastructure module to remove any issues with circular dependencies.<br>\nDoing this I am not tied to any specific configuration method, and have no strings running havoc in my applications code.</p>\n"
},
{
"answer_id": 12185,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": 2,
"selected": true,
"text": "<p>You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:</p>\n\n<pre><code>class ServiceLocator {\n private static $soleInstance;\n private $globalSettings;\n\n public static function load($locator) {\n self::$soleInstance = $locator;\n }\n\n public static function globalSettings() {\n if (!isset(self::$soleInstance->globalSettings)) {\n self::$soleInstance->setGlobalSettings(new GlobalSettings());\n }\n return self::$soleInstance->globalSettings;\n }\n}\n</code></pre>\n\n<p>Your production code then initializes the service locator like this:</p>\n\n<pre><code>ServiceLocator::load(new ServiceLocator());\n</code></pre>\n\n<p>In your test-code, you insert your mock-settings like this:</p>\n\n<pre><code>ServiceLocator s = new ServiceLocator();\ns->setGlobalSettings(new MockGlobalSettings());\nServiceLocator::load(s);\n</code></pre>\n\n<p>It's a repository for singletons that can be exchanged for testing purposes.</p>\n"
},
{
"answer_id": 12210,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>I like to model my configuration access off of the Service Locator pattern. This gives me a single point to get any configuration value that I need and by putting it outside the application in a separate library, it allows reuse and testability. Here is some sample code, I am not sure what language you are using, but I wrote it in C#.</p>\n\n<p>First I create a generic class that will models my ConfigurationItem.</p>\n\n<pre><code>public class ConfigurationItem<T>\n{\n private T item;\n\n public ConfigurationItem(T item)\n {\n this.item = item;\n }\n\n public T GetValue()\n {\n return item;\n }\n}\n</code></pre>\n\n<p>Then I create a class that exposes public static readonly variables for the configuration item. Here I am just reading the ConnectionStringSettings from a config file, which is just xml. Of course for more items, you can read the values from any source.</p>\n\n<pre><code>public class ConfigurationItems\n{\n public static ConfigurationItem<ConnectionStringSettings> ConnectionSettings = new ConfigurationItem<ConnectionStringSettings>(RetrieveConnectionString());\n\n private static ConnectionStringSettings RetrieveConnectionString()\n {\n // In .Net, we store our connection string in the application/web config file.\n // We can access those values through the ConfigurationManager class.\n return ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings[\"ConnectionKey\"]];\n }\n}\n</code></pre>\n\n<p>Then when I need a ConfigurationItem for use, I call it like this:</p>\n\n<pre><code>ConfigurationItems.ConnectionSettings.GetValue();\n</code></pre>\n\n<p>And it will return me a type safe value, which I can then cache or do whatever I want with.</p>\n\n<p>Here's a sample test:</p>\n\n<pre><code>[TestFixture]\npublic class ConfigurationItemsTest\n{\n [Test]\n public void ShouldBeAbleToAccessConnectionStringSettings()\n {\n ConnectionStringSettings item = ConfigurationItems.ConnectionSettings.GetValue();\n Assert.IsNotNull(item);\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037/"
] | A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.
The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).
This works better, in any case much better than having all those objects need some global *Settings* object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.
**So the general question is**: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...
(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences) | You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:
```
class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
```
Your production code then initializes the service locator like this:
```
ServiceLocator::load(new ServiceLocator());
```
In your test-code, you insert your mock-settings like this:
```
ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
```
It's a repository for singletons that can be exchanged for testing purposes. |
12,141 | <p>For example: Updating all rows of the customer table because you forgot to add the where clause.</p>
<ol>
<li>What was it like, realizing it and reporting it to your coworkers or customers? </li>
<li>What were the lessons learned?</li>
</ol>
| [
{
"answer_id": 12143,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I dropped the live database and deleted it.</p>\n\n<p>Lesson learned: ensure you know your SQL - and make sure that you back up before you touch stuff.</p>\n"
},
{
"answer_id": 12145,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>A junior DBA meant to do:</p>\n\n<pre><code>delete from [table] where [condition]\n</code></pre>\n\n<p>Instead they typed:</p>\n\n<pre><code>delete [table] where [condition]\n</code></pre>\n\n<p>Which is valid T-Sql but basically ignores the where [condition] bit completely (at least it did back then on MSSQL 2000/97 - I forget which) and wipes the entire table.</p>\n\n<p>That was fun :-/</p>\n"
},
{
"answer_id": 12146,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>I discovered I didn't understand Oracle redo log files (terminology? it was a long time ago) and lost a weeks' trade data, which had to be manually re-keyed from paper tickets.</p>\n\n<p>There <em>was</em> a silver lining - during the weekend I spent inputting, I learned a lot about the useability of my trade input screen, which improved dramatically thereafter.</p>\n"
},
{
"answer_id": 12149,
"author": "Surgical Coder",
"author_id": 1276,
"author_profile": "https://Stackoverflow.com/users/1276",
"pm_score": 4,
"selected": false,
"text": "<p>I think my worst mistake was</p>\n\n<pre><code>truncate table Customers\ntruncate table Transactions\n</code></pre>\n\n<p>I didnt see what MSSQL server I was logged into, I wanted to clear my local copy out...The familiar \"OH s**t\" when it was taking significantly longer than about half a second to delete, my boss noticed I went visibily white, and asked what I just did. About half a mintue later, our site monitor went nuts and started emailing us saying the site was down. </p>\n\n<p>Lesson learned? Never keep a connection open to live DB longer than absolutly needed.</p>\n\n<p>Was only up till 4am restoring the data from the backups too! My boss felt sorry for me, and bought me dinner...</p>\n"
},
{
"answer_id": 12150,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 1,
"selected": false,
"text": "<p>Worst case scenario for most people is production data loss, but if they're not running nightly backups or replicating data to a DR site, then they deserve everything they get!</p>\n\n<p>@<a href=\"https://stackoverflow.com/questions/12141/whats-your-worst-database-accident-happened-in-production#12145\">Keith</a> in T-SQL, isn't the FROM keyword optional for a DELETE? Both of those statements do exactly the same thing...</p>\n"
},
{
"answer_id": 12227,
"author": "Marshall",
"author_id": 1302,
"author_profile": "https://Stackoverflow.com/users/1302",
"pm_score": 3,
"selected": false,
"text": "<p>I work for a small e-commerce company, there's 2 developers and a DBA, me being one of the developers. I'm normally not in the habit of updating production data on the fly, if we have stored procedures we've changed we put them through source control and have an officially deployment routine setup.</p>\n\n<p>Well anyways a user came to me needing an update done to our contact database, batch updating a bunch of facilities. So I wrote out the query in our test environment, something like</p>\n\n<pre><code>update facilities set address1 = '123 Fake Street'\n where facilityid in (1, 2, 3)\n</code></pre>\n\n<p>Something like that. Ran it in test, 3 rows updated. Copied it to clipboard, pasted it in terminal services on our production sql box, ran it, watched in horror as it took 5 seconds to execute and updated 100000 rows. Somehow I copied the first line and not the second, and wasn't paying attention as I <kbd>CTRL</kbd> + <kbd>V</kbd>, <kbd>CTRL</kbd> + <kbd>E</kbd>'d.</p>\n\n<p>My DBA, an older Greek gentleman, probably the grumpiest person I've met was not thrilled. Luckily we had a backup, and it didn't break any pages, luckily that field is only really for display purposes (and billing/shipping).</p>\n\n<p>Lesson learned was pay attention to what you're copying and pasting, probably some others too.</p>\n"
},
{
"answer_id": 12233,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 1,
"selected": false,
"text": "<p>The worst thing that happened to me was that a Production server consume all the space in the HD. I was using SQL Server so I see the database files and see that the log was about 10 Gb so I decide to do what I always do when I want to trunc a Log file. I did a Detach the delete the log file and then attach again. Well I realize that if the log file is not close properly this procedure does not work. so I end up with a mdf file and no log file. Thankfully I went to the Microsoft site I get a way to restore the database as recovery and move to another database.</p>\n"
},
{
"answer_id": 12280,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 2,
"selected": false,
"text": "<pre><code>update Customers set ModifyUser = 'Terrapin'\n</code></pre>\n\n<p>I forgot the where clause - pretty innocent, but on a table with 5000+ customers, my name will be on every record for a while...</p>\n\n<p>Lesson learned: use transaction commit and rollback!</p>\n"
},
{
"answer_id": 12299,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>I once managed to write an updating cursor that never exited. On a 2M+ row table. The locks just escalated and escalated until this 16-core, 8GB RAM (in 2002!) box actually ground to a halt (of the blue screen variety).</p>\n"
},
{
"answer_id": 12404,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>About 7 years ago, I was generating a change script for a client's DB after working late. I had only changed stored procedures but when I generated the SQL I had \"script dependent objects\" checked. I ran it on my local machine and all appeared to work well. I ran it on the client's server and the script succeeded. </p>\n\n<p>Then I loaded the web site and the site was empty. To my horror, the \"script dependent objects\" setting did a <code>DROP TABLE</code> for every table that my stored procedures touched. </p>\n\n<p>I immediately called the lead dev and boss letting them know what happened and asking where the latest backup of the DB could be located. 2 other devs were conferenced in and the conclusion we came to was that no backup system was even in place and no data could be restored. The client lost their entire website's content and I was the root cause. The result was a <strong>$5000</strong> credit given to our client.</p>\n\n<p>For me it was a great lesson, and now I am super-cautious about running any change scripts, and backing up DBs first. I'm still with the same company today, and whenever the jokes come up about backups or database scripts someone always brings up the famous \"DROP TABLE\" incident.</p>\n"
},
{
"answer_id": 12419,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 2,
"selected": false,
"text": "<p>I thought I was working in the testing DB (which wasn't the case apparently), so when I finished 'testing' I run a script to reset <em>all</em> data back to the standard test data we use... ouch!<br>\nLuckily this happened on a database that had backups in place, so after figuring out I did something wrong we could easily bring back the original database.</p>\n\n<p>However this incident did teach the company I worked for to <em>realy</em> seperate the production and the test environment.</p>\n"
},
{
"answer_id": 12559,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>We were trying to fix a busted node on an Oracle cluster.</p>\n\n<p>The storage management module was having problems, so we clicked the un-install button with the intention of re-installing and copying the configuration over from another node.</p>\n\n<p>Hmm, it turns out the un-install button applied to the entire cluster, so it cheerfully removed the storage management module from all the nodes in the system.</p>\n\n<p>Causing every node in the production cluster to crash. And since none of the nodes had a storage manager, they wouldn't come up!</p>\n\n<p>Here's an interesting fact about backups... the oldest backups get rotated off-site, and you know what your oldest files on a database are? The configuration files that got set up when the system was installed.</p>\n\n<p>So we had to have the offsite people send a courier with that tape, and a couple of hours later we had everything reinstalled and running. Now we keep local copies of the installation and configuration files!</p>\n"
},
{
"answer_id": 21832,
"author": "vikramjb",
"author_id": 2245,
"author_profile": "https://Stackoverflow.com/users/2245",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Updating all rows of the customer table because you forgot to add the where clause.</p>\n</blockquote>\n\n<p>That was exactly i did :| . I had updated the password column for all users to a sample string i had typed onto the console. The worst part of it was i was accessing the production server and i was checking out some queries when i did this. My seniors then had to revert an old backup and had to field some calls from some really disgruntled customers. Ofcourse there is another time when i did use the delete statement, which i don't even want to talk about ;-)</p>\n"
},
{
"answer_id": 36677,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Truncate table T_DAT_STORE</p>\n</blockquote>\n\n<p>T_DAT_STORE was the fact table of the department I work in. I think I was connected to the development database. Fortunately, we have a daily backup, which hasn't been used until that day, and the data was restored in six hours.</p>\n\n<p>Since then I revise everything before a truncate, and periodically I ask for a backup restoration of minor tables only to check the backup is doing well (Backup isn't done by my department)</p>\n"
},
{
"answer_id": 128358,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 2,
"selected": false,
"text": "<p>I don't remember all the sql statements that ran out of control but I have one lesson learned - <strong>do it in a transaction</strong> if you can (beware of the big logfiles!). </p>\n\n<p>In production, if you can, proceed the old fashioned way:</p>\n\n<ol>\n<li>Use a maintenance window</li>\n<li>Backup</li>\n<li>Perform your change</li>\n<li><strong>verify</strong></li>\n<li>restore if something went wrong</li>\n</ol>\n\n<p>Pretty uncool, but generally working and even possible to give this procedure to somebody else to run it during their night shift while you're getting your well deserved sleep :-)</p>\n"
},
{
"answer_id": 312935,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This didn't happen to me, just a customer of ours whos mess I had to clean up.</p>\n\n<p>They had a SQL server running on a RAID5 disk array - nice hotswap drives complete with lighted disk status indicators. Green = Good, Red = Bad.</p>\n\n<p>One of their drives turned from green to red and the genius who was told to pull and replace the (Red) bad drive takes a (Green) good one out instead. Well this didn't quite manage to bring down the raid set completely - opting for the somewhat readable (Red) vs unavaliable (Green) for several minutes.. after realizing the mistake and swapping the drives back any data blocks that were written during this time became jyberish as disk synchronization was lost) ... 24-straight hours later writing meta programs to recover readable data and reconstruct a medium sized schema they were back up and running.</p>\n\n<p>Morals of this story include...Never use RAID5, always maintain backups, careful who you hire.</p>\n\n<p>I made a major mistake on a customers production system once -- luckily while wondering why the command was taking so long to execute realized what I had done and canceled it before the world came to an end.</p>\n\n<p>Moral of this story include ... always start a new transaction before changing ANYTHING, test the results are what you expect and then and only then commit the transaction.</p>\n\n<p>As a general observation many classes of rm -rf / type errors can be prevented by properly defining foreign key constraints on your schema and staying far away from any command labled 'CASCADE'</p>\n"
},
{
"answer_id": 313022,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 2,
"selected": false,
"text": "<p>I did exactly what you suggested. I updated all the rows in a table that held customer documents because I forgot to add the \"where ID = 5\" at the end. That was a mistake.</p>\n\n<p>But I was smart and paranoid. I knew I would screw up one day. I had issued a \"start transaction\". I issued a rollback and then checked the table was OK.</p>\n\n<p><strong>It wasn't.</strong></p>\n\n<p>Lesson learned in production: despite the fact we like to use InnoDB tables in MySQL for many MANY reasons... be SURE you haven't managed to find one of the few MyISAM tables that doesn't respect transactions and you can't roll back on. Don't trust MySQL under any circumstances, and habitually issuing a \"start transaction\" is a good thing. Even in the worst case scenario (what happened here) it didn't hurt anything and it would have protected me on the InnoDB tables.</p>\n\n<p>I had to restore the table from a backup. Luckily we have nightly backups, the data almost never changes, and the table is a few dozen rows so it was near instantaneous. For reference, no one knew that we still had non-InnoDB tables around, we thought we converted them all long ago. No one told me to look out for this gotcha, no one knew it was there. My boss would have done the same exact thing (if he had hit enter too early before typing the where clause too).</p>\n"
},
{
"answer_id": 313038,
"author": "Jordan Stewart",
"author_id": 33338,
"author_profile": "https://Stackoverflow.com/users/33338",
"pm_score": 3,
"selected": false,
"text": "<p>Something to the effect of:</p>\n\n<blockquote>\n <p><code>update email set processedTime=null,sentTime=null</code></p>\n</blockquote>\n\n<p>on a production newsletter database, resending every email in the database.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/990/"
] | For example: Updating all rows of the customer table because you forgot to add the where clause.
1. What was it like, realizing it and reporting it to your coworkers or customers?
2. What were the lessons learned? | I think my worst mistake was
```
truncate table Customers
truncate table Transactions
```
I didnt see what MSSQL server I was logged into, I wanted to clear my local copy out...The familiar "OH s\*\*t" when it was taking significantly longer than about half a second to delete, my boss noticed I went visibily white, and asked what I just did. About half a mintue later, our site monitor went nuts and started emailing us saying the site was down.
Lesson learned? Never keep a connection open to live DB longer than absolutly needed.
Was only up till 4am restoring the data from the backups too! My boss felt sorry for me, and bought me dinner... |
12,176 | <p>Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev</p>
<p>I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:</p>
<pre><code>#define MAJORVER 4
#define MINORVER 23
#define SOURCEVER 965
</code></pre>
<p>We would then use these defines to generate the version string.</p>
<p>Is something like this possible for .NET?</p>
| [
{
"answer_id": 12189,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": true,
"text": "<p>Have a look at SubWCRev - <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html\" rel=\"noreferrer\">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html</a></p>\n\n<p>The assembly version numbers are usually in assemblyinfo.cs</p>\n"
},
{
"answer_id": 12261,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 2,
"selected": false,
"text": "<p>svn info, tells you the version you are on, you can make a \"pre-build\" event in VS on your project to generate the assemblyinfo.cs by running svn info and parsing its results with a home grown command line app.</p>\n\n<p>I have done this before, but quickly switched to just having ccnet pass it as a variable to nant.</p>\n"
},
{
"answer_id": 58379,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to update the version number in a projects AssemblyInfo.cs you may be interested in this article:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/architecture/svn_visual_studio.aspx\" rel=\"nofollow noreferrer\">CodeProject: Use Subversion Revision numbers in your Visual Studio Projects</a></p>\n\n<blockquote>\n <p>If you enable SVN Keywords then every time you check in the project Subversion scans your files for certain \"keywords\" and replaces the keywords with some information.</p>\n \n <p>For example, At the top of my source files I would create a header contain the following keywords:</p>\n \n <p>'$Author:$<br>\n '$Id:$<br>\n '$Rev:$</p>\n \n <p>When I check this file into Subversion these keywords are replaced with the following:</p>\n \n <p>'$Author: paulbetteridge $<br>\n '$Id: myfile.vb 145 2008-07-16 15:24:29Z paulbetteridge $<br>\n '$Rev: 145 $ </p>\n</blockquote>\n"
},
{
"answer_id": 653382,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Read/skim these docs:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/library/subversion_using_dotsvn.aspx?display=PrintAll\" rel=\"noreferrer\">Accessing the Subversion repository from .NET using DotSVN</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/t9883dzc.aspx\" rel=\"noreferrer\">How to: Write a Task</a></p>\n\n<p><a href=\"http://florent.clairambault.fr/insert-svn-version-and-build-number-in-your-c-assemblyinfo-file\" rel=\"noreferrer\">Insert SVN version and Build number in your C# AssemblyInfo file</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163589.aspx\" rel=\"noreferrer\">Compiling Apps With Custom Tasks For The Microsoft Build Engine</a></p>\n\n<p>The MSBuildCommunityTasks svnversion mentioned in third reference would not perform with svn on Mac 10.5.6 and VS2008 C# project build inside Parallels hosting Vista (ie., across OS).</p>\n\n<p>Write your own task to retrieve revision from repository using DotSVN:</p>\n\n<pre><code>using System;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Utilities;\nusing DotSVN.Common;\nusing DotSVN.Common.Entities;\nusing DotSVN.Common.Util;\nusing DotSVN.Server.RepositoryAccess;\n\nnamespace GetSVNVersion\n{\n public class GetRevision : Task\n {\n [Required]\n public string Repository { get; set; }\n [Output]\n public string Revision { get; set; }\n\n public override bool Execute()\n {\n ISVNRepository repo;\n bool connected = true;\n try\n {\n repo = SVNRepositoryFactory.Create(new SVNURL(Repository));\n repo.OpenRepository();\n Revision = repo.GetLatestRevision().ToString();\n Log.LogCommandLine(Repository + \" is revision \" + Revision);\n repo.CloseRepository();\n }\n catch(Exception e)\n {\n Log.LogError(\"Error retrieving revision number for \" + Repository + \": \" + e.Message);\n connected = false;\n }\n return connected;\n }\n }\n}\n</code></pre>\n\n<p>This way allows the repository path to be \"file:///Y:/repo\" where Y: is a Mac directory mapped into Vista.</p>\n"
},
{
"answer_id": 654344,
"author": "Wim Coenen",
"author_id": 52626,
"author_profile": "https://Stackoverflow.com/users/52626",
"pm_score": 3,
"selected": false,
"text": "<p>It is possible but you shouldn't: the components of the assembly version string are limited to 16-bit numbers (max 65535). Subversion revision numbers can easily become bigger than that so at some point the compiler is suddenly going to complain.</p>\n"
},
{
"answer_id": 965790,
"author": "ferventcoder",
"author_id": 18475,
"author_profile": "https://Stackoverflow.com/users/18475",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a shared Assembly Version file that you can reference in all of your projects.</p>\n\n<p><a href=\"http://uppercut.googlecode.com\" rel=\"nofollow noreferrer\">UppercuT</a> does this - <a href=\"http://ferventcoder.com/archive/2009/05/21/uppercut---automated-builds---versionbuilder.aspx\" rel=\"nofollow noreferrer\">http://ferventcoder.com/archive/2009/05/21/uppercut---automated-builds---versionbuilder.aspx</a></p>\n\n<p>This will give you an idea of what you can do to get versions in your assemblies.</p>\n"
},
{
"answer_id": 9237374,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 2,
"selected": false,
"text": "<p>Another answer mentioned that SVN revision number might not be a good idea because of the limit on the size of the number. </p>\n\n<p>The following link provides not only an SNV revision number, but also a date version info template. </p>\n\n<p>Adding this to a .NET project is simple - very little work needs to be done.</p>\n\n<p>Here is a github project that addresses this\n<a href=\"https://github.com/AndrewFreemantle/When-The-Version/downloads\" rel=\"nofollow\">https://github.com/AndrewFreemantle/When-The-Version/downloads</a></p>\n\n<p>The following url may load slowly but is a step-by-step explanation of how to make this work (easy and short 3 or 4 steps)</p>\n\n<p><a href=\"http://www.fatlemon.co.uk/2011/11/wtv-automatic-date-based-version-numbering-for-net-with-whentheversion/\" rel=\"nofollow\">http://www.fatlemon.co.uk/2011/11/wtv-automatic-date-based-version-numbering-for-net-with-whentheversion/</a></p>\n"
},
{
"answer_id": 14195519,
"author": "R. Schreurs",
"author_id": 456456,
"author_profile": "https://Stackoverflow.com/users/456456",
"pm_score": 5,
"selected": false,
"text": "<p>Here's and C# example for updating the revision info in the assembly automatically. It is based on the answer by Will Dean, which is not very elaborate.</p>\n\n<p>Example :</p>\n\n<ol>\n<li>Copy AssemblyInfo.cs to AssemblyInfoTemplate.cs in the project's\nfolder <em>Properties</em>.</li>\n<li>Change the <em>Build Action</em> to <em>None</em> for AssemblyInfoTemplate.cs.</li>\n<li><p>Modify the line with the AssemblyFileVersion to: </p>\n\n<p><code>[assembly: AssemblyFileVersion(\"1.0.0.$WCREV$\")]</code></p></li>\n<li><p>Consider adding: </p>\n\n<p><code>[assembly: AssemblyInformationalVersion(\"Build date: $WCNOW=%Y-%m-%d %H:%M:%S$; Revision date: $WCDATE=%Y-%m-%d %H:%M:%S$; Revision(s) in working copy: $WCRANGE$$WCMODS?; WARNING working copy had uncommitted modifications:$.\")]</code>, </p>\n\n<p>which will give details about the revision status of the source the assembly was build from.</p></li>\n<li><p>Add the following Pre-build event to the project file properties:</p>\n\n<p><code>subwcrev \"$(SolutionDir).\" \"$(ProjectDir)Properties\\AssemblyInfoTemplate.cs\" \"$(ProjectDir)Properties\\AssemblyInfo.cs\" -f</code></p></li>\n<li><p>Consider adding AssemblyInfo.cs to the svn ignore list. Substituted revision numbers and dates will modify the file, which results in insignificant changes and revisions and $WCMODS$ will evaluate to true. AssemblyInfo.cs must, of course, be included in the project.</p></li>\n</ol>\n\n<p>In response to the objections by Wim Coenen, I noticed that, in contrast to what was suggested by Darryl, the AssemblyFileVersion also does <strong>not</strong> support numbers above 2^16. The build will complete, but the property <em>File Version</em> in the actual assembly will be AssemblyFileVersion modulo 65536. Thus, 1.0.0.65536 as well as 1.0.0.131072 will yield 1.0.0.0, etc. In this example, there is always the true revision number in the AssemblyInformationalVersion property. You could leave out step 3, if you consider this a significant issue.</p>\n\n<p>Edit: some additional info after having used this solution for a while.</p>\n\n<ol>\n<li>It now use AssemblyInfo.cst rather than AssemblyInfoTemplate.cs, because it will automatically have <em>Build Action</em> option <em>None</em>, and it will not clutter you Error list, but you'll loose syntax highlighting.</li>\n<li><p>I've added two tests to my AssemblyInfo.cst files:</p>\n\n<pre><code>#if(!DEBUG) \n $WCMODS?#error Working copy has uncommitted modifications, please commit all modifications before creating a release build.:$ \n#endif \n#if(!DEBUG) \n $WCMIXED?#error Working copy has multiple revisions, please update to the latest revision before creating a release build.:$ \n#endif\n</code></pre>\n\n<p>Using this, you will normally have to perform a complete SVN Update, after a commit and before you can do a successful release build. Otherwise, $WCMIXED will be true. This seems to be caused by the fact that the committed files re at head revision after the commit, but other files not.</p></li>\n<li>I have had some doubts whether the first parameter to subwcrev, \"$(SolutionDir)\", which sets the scope for checking svn version info, does always work as desired. Maybe, it should be $(ProjectDir), if you are content if each individual assembly is in a consistent revision.</li>\n</ol>\n\n<p><strong>Addition</strong>\n<em>To answer the comment by @tommylux.</em></p>\n\n<p>SubWcRev can be used for any file in you project. If you want to display revision info in a web page, you could use this VersionInfo template:</p>\n\n<pre><code>public class VersionInfo\n{ \n public const int RevisionNumber = $WCREV$;\n public const string BuildDate = \"$WCNOW=%Y-%m-%d %H:%M:%S$\";\n public const string RevisionDate = \"$WCDATE=%Y-%m-%d %H:%M:%S$\";\n public const string RevisionsInWorkingCopy = \"$WCRANGE$\";\n public const bool UncommitedModification = $WCMODS?true:false$;\n}\n</code></pre>\n\n<p>Add a pre-build event just like the one for AssemblyInfo.cst and you will have easy access to all relevant SubVersion info.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev
I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:
```
#define MAJORVER 4
#define MINORVER 23
#define SOURCEVER 965
```
We would then use these defines to generate the version string.
Is something like this possible for .NET? | Have a look at SubWCRev - <http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html>
The assembly version numbers are usually in assemblyinfo.cs |
12,225 | <p>I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary. </p>
<p>How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox.</p>
<p>Thanks.</p>
| [
{
"answer_id": 12257,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>Are you referring to the asp.Net Ajax toolkit extensions at:</p>\n\n<p><a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/MaskedEdit/MaskedEdit.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/AjaxControlToolkit/Samples/MaskedEdit/MaskedEdit.aspx</a></p>\n\n<p>If so have you checked that your data is coming back in the correct format? It will have to match your date format in order to be displayed.</p>\n"
},
{
"answer_id": 16718,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 2,
"selected": true,
"text": "<p>We found out this morning why our code was mishandling the extender. Since the db was handling the date as a date/time it was returning the date in this format 99/99/9999 99:99:99 but we had the extender mask looking for this format 99/99/9999 99:99 </p>\n\n<pre><code>Mask=\"99/99/9999 99:99:99\"</code></pre> \n\n<p>the above code fixed the problem.\nthanks to everyone for their help.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary.
How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox.
Thanks. | We found out this morning why our code was mishandling the extender. Since the db was handling the date as a date/time it was returning the date in this format 99/99/9999 99:99:99 but we had the extender mask looking for this format 99/99/9999 99:99
```
Mask="99/99/9999 99:99:99"
```
the above code fixed the problem.
thanks to everyone for their help. |
12,271 | <p>I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#".</p>
| [
{
"answer_id": 12292,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>Categorization of templates depends on settings (for example, if you choose \"C#\" settings, all of a sudden all other languages move to an \"other languages\" tree).</p>\n\n<p>What folder is your template in?</p>\n"
},
{
"answer_id": 12491,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 4,
"selected": true,
"text": "<p>Check out MSDN \"<a href=\"http://msdn.microsoft.com/en-us/library/y3kkate1.aspx\" rel=\"noreferrer\">How to: Locate and Organize Project and Item Templates</a>\"</p>\n\n<p>Create a folder within one of these</p>\n\n<pre><code><VisualStudioInstallDir>\\Common7\\IDE\\ItemTemplates\\CSharp\\\nMy Documents\\Visual Studio 2008\\Templates\\ProjectTemplates\\CSharp\\\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214/"
] | I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#". | Check out MSDN "[How to: Locate and Organize Project and Item Templates](http://msdn.microsoft.com/en-us/library/y3kkate1.aspx)"
Create a folder within one of these
```
<VisualStudioInstallDir>\Common7\IDE\ItemTemplates\CSharp\
My Documents\Visual Studio 2008\Templates\ProjectTemplates\CSharp\
``` |
12,297 | <p>I've got a Repeater that lists all the <code>web.sitemap</code> child pages on an ASP.NET page. Its <code>DataSource</code> is a <code>SiteMapNodeCollection</code>. But, I don't want my registration form page to show up there.</p>
<pre><code>Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection
For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes
If n.Url = "/Registration.aspx" Then
Children.Remove(n)
End If
Next
RepeaterSubordinatePages.DataSource = Children
</code></pre>
<p>The <code>SiteMapNodeCollection.Remove()</code> method throws a </p>
<blockquote>
<p>NotSupportedException: "Collection is read-only".</p>
</blockquote>
<p>How can I remove the node from the collection before DataBinding the Repeater?</p>
| [
{
"answer_id": 12303,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>Using Linq and .Net 3.5:</p>\n\n<pre><code>//this will now be an enumeration, rather than a read only collection\nDim children = SiteMap.CurrentNode.ChildNodes.Where( _\n Function (x) x.Url <> \"/Registration.aspx\" )\n\nRepeaterSubordinatePages.DataSource = children \n</code></pre>\n\n<p>Without Linq, but using .Net 2:</p>\n\n<pre><code>Function IsShown( n as SiteMapNode ) as Boolean\n Return n.Url <> \"/Registration.aspx\"\nEnd Function\n\n...\n\n//get a generic list\nDim children as List(Of SiteMapNode) = _\n New List(Of SiteMapNode) ( SiteMap.CurrentNode.ChildNodes )\n\n//use the generic list's FindAll method\nRepeaterSubordinatePages.DataSource = children.FindAll( IsShown )\n</code></pre>\n\n<p>Avoid removing items from collections as that's always slow. Unless you're going to be looping through multiple times you're better off filtering.</p>\n"
},
{
"answer_id": 12362,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<p>I got it to work with code below:</p>\n\n<pre><code>Dim children = From n In SiteMap.CurrentNode.ChildNodes _\n Where CType(n, SiteMapNode).Url <> \"/Registration.aspx\" _\n Select n\nRepeaterSubordinatePages.DataSource = children\n</code></pre>\n\n<p>Is there a better way where I don't have to use the <code>CType()</code>?</p>\n\n<p>Also, this sets children to a <code>System.Collections.Generic.IEnumerable(Of Object)</code>. Is there a good way to get back something more strongly typed like a <code>System.Collections.Generic.IEnumerable(Of System.Web.SiteMapNode)</code> or even better a <code>System.Web.SiteMapNodeCollection</code>?</p>\n"
},
{
"answer_id": 12373,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": true,
"text": "<p>Your shouldn't need CType</p>\n\n<pre><code>Dim children = _\n From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _\n Where n.Url <> \"/Registration.aspx\" _\n Select n\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I've got a Repeater that lists all the `web.sitemap` child pages on an ASP.NET page. Its `DataSource` is a `SiteMapNodeCollection`. But, I don't want my registration form page to show up there.
```
Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection
For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes
If n.Url = "/Registration.aspx" Then
Children.Remove(n)
End If
Next
RepeaterSubordinatePages.DataSource = Children
```
The `SiteMapNodeCollection.Remove()` method throws a
>
> NotSupportedException: "Collection is read-only".
>
>
>
How can I remove the node from the collection before DataBinding the Repeater? | Your shouldn't need CType
```
Dim children = _
From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _
Where n.Url <> "/Registration.aspx" _
Select n
``` |
12,304 | <p>This is a problem I have seen other people besides myself having, and I haven't found a good explanation.</p>
<p>Let's say you have a maintenance plan with a task to check the database, something like this:</p>
<pre><code>USE [MyDb]
GO
DBCC CHECKDB with no_infomsgs, all_errormsgs
</code></pre>
<p>If you go look in your logs after the task executes, you might see something like this:</p>
<pre><code>08/15/2008 06:00:22,spid55,Unknown,DBCC CHECKDB (mssqlsystemresource) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
08/15/2008 06:00:21,spid55,Unknown,DBCC CHECKDB (master) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
</code></pre>
<p>Instead of checking MyDb, it checked master and msssqlsystemresource.</p>
<p>Why?</p>
<p>My workaround is to create a Sql Server Agent Job with this:</p>
<pre><code>dbcc checkdb ('MyDb') with no_infomsgs, all_errormsgs;
</code></pre>
<p>That always works fine.</p>
<pre><code>08/15/2008 04:26:04,spid54,Unknown,DBCC CHECKDB (MyDb) WITH all_errormsgs<c/> no_infomsgs executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 26 minutes 3 seconds.
</code></pre>
| [
{
"answer_id": 12320,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>For starters, always remember that <code>GO</code> is not a SQL keyword; it is merely a batch separator that is (generally) implemented/recognized by the client, not the server. So, depending on context and client, there really is no guarantee that the current database is preserved between batches.</p>\n"
},
{
"answer_id": 12384,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using a maintenance plan you'd probably be better off use the check database integrity task. If you really want to run you own maintenance written in t-sql then run it using a step in a job, not in a maintenance plan and the code above will work ok. Like Stu said the GO statement is client directive not a sql keyword and only seems to be respected by isql, wsql, osql, etc, clients and the sql agent. I think it works in DTS packages. Obviously, not in DTSX, though. </p>\n"
},
{
"answer_id": 12623,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 0,
"selected": false,
"text": "<p>You have a check datasbase integrity task and you double-clicked it choose MyDb and when the plan runs it only checks master?? weird. Are you sure you don't another plan running? </p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | This is a problem I have seen other people besides myself having, and I haven't found a good explanation.
Let's say you have a maintenance plan with a task to check the database, something like this:
```
USE [MyDb]
GO
DBCC CHECKDB with no_infomsgs, all_errormsgs
```
If you go look in your logs after the task executes, you might see something like this:
```
08/15/2008 06:00:22,spid55,Unknown,DBCC CHECKDB (mssqlsystemresource) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
08/15/2008 06:00:21,spid55,Unknown,DBCC CHECKDB (master) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
```
Instead of checking MyDb, it checked master and msssqlsystemresource.
Why?
My workaround is to create a Sql Server Agent Job with this:
```
dbcc checkdb ('MyDb') with no_infomsgs, all_errormsgs;
```
That always works fine.
```
08/15/2008 04:26:04,spid54,Unknown,DBCC CHECKDB (MyDb) WITH all_errormsgs<c/> no_infomsgs executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 26 minutes 3 seconds.
``` | For starters, always remember that `GO` is not a SQL keyword; it is merely a batch separator that is (generally) implemented/recognized by the client, not the server. So, depending on context and client, there really is no guarantee that the current database is preserved between batches. |
12,306 | <p>I'm trying to serialize a Type object in the following way:</p>
<pre><code>Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
</code></pre>
<p>When I do this, the call to Serialize throws the following exception: </p>
<blockquote>
<p>"The type System.Text.StringBuilder was not expected. Use the
XmlInclude or SoapInclude attribute to specify types that are not
known statically."</p>
</blockquote>
<p>Is there a way for me to serialize the <code>Type</code> object? Note that I am not trying to serialize the <code>StringBuilder</code> itself, but the <code>Type</code> object containing the metadata about the <code>StringBuilder</code> class.</p>
| [
{
"answer_id": 12314,
"author": "AdamSane",
"author_id": 805,
"author_profile": "https://Stackoverflow.com/users/805",
"pm_score": 1,
"selected": false,
"text": "<p>Just looked at its definition, it is not marked as Serializable. If you really need this data to be serialize, then you may have to convert it to a custom class that is marked as such.</p>\n\n<pre><code>public abstract class Type : System.Reflection.MemberInfo\n Member of System\n\nSummary:\nRepresents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.\n\nAttributes:\n[System.Runtime.InteropServices.ClassInterfaceAttribute(0),\nSystem.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type),\nSystem.Runtime.InteropServices.ComVisibleAttribute(true)]\n</code></pre>\n"
},
{
"answer_id": 12315,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "<p>According to the MSDN documentation of System.Type [1] you should be able to serialize the System.Type object. However, as the error is explicitly referring to System.Text.StringBuilder, that is likely the class that is causing the serialization error.</p>\n\n<p>[1] Type Class (System) - <a href=\"http://msdn.microsoft.com/en-us/library/system.type.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.type.aspx</a></p>\n"
},
{
"answer_id": 12342,
"author": "Brian Sullivan",
"author_id": 767,
"author_profile": "https://Stackoverflow.com/users/767",
"pm_score": 8,
"selected": true,
"text": "<p>I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:</p>\n\n<pre><code>string typeName = typeof (StringBuilder).FullName;\n</code></pre>\n\n<p>You can then persist this string however needed, then reconstruct the type like this:</p>\n\n<pre><code>Type t = Type.GetType(typeName);\n</code></pre>\n\n<p>If you need to create an instance of the type, you can do this:</p>\n\n<pre><code>object o = Activator.CreateInstance(t);\n</code></pre>\n\n<p>If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.</p>\n"
},
{
"answer_id": 9809872,
"author": "hypehuman",
"author_id": 1269598,
"author_profile": "https://Stackoverflow.com/users/1269598",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same problem, and my solution was to create a SerializableType class. It freely converts to and from System.Type, but it serializes as a string. All you have to do is declare the variable as a SerializableType, and from then on you can refer to it as System.Type.</p>\n\n<p>Here is the class:</p>\n\n<pre><code>// a version of System.Type that can be serialized\n[DataContract]\npublic class SerializableType\n{\n public Type type;\n\n // when serializing, store as a string\n [DataMember]\n string TypeString\n {\n get\n {\n if (type == null)\n return null;\n return type.FullName;\n }\n set\n {\n if (value == null)\n type = null;\n else\n {\n type = Type.GetType(value);\n }\n }\n }\n\n // constructors\n public SerializableType()\n {\n type = null;\n }\n public SerializableType(Type t)\n {\n type = t;\n }\n\n // allow SerializableType to implicitly be converted to and from System.Type\n static public implicit operator Type(SerializableType stype)\n {\n return stype.type;\n }\n static public implicit operator SerializableType(Type t)\n {\n return new SerializableType(t);\n }\n\n // overload the == and != operators\n public static bool operator ==(SerializableType a, SerializableType b)\n {\n // If both are null, or both are same instance, return true.\n if (System.Object.ReferenceEquals(a, b))\n {\n return true;\n }\n\n // If one is null, but not both, return false.\n if (((object)a == null) || ((object)b == null))\n {\n return false;\n }\n\n // Return true if the fields match:\n return a.type == b.type;\n }\n public static bool operator !=(SerializableType a, SerializableType b)\n {\n return !(a == b);\n }\n // we don't need to overload operators between SerializableType and System.Type because we already enabled them to implicitly convert\n\n public override int GetHashCode()\n {\n return type.GetHashCode();\n }\n\n // overload the .Equals method\n public override bool Equals(System.Object obj)\n {\n // If parameter is null return false.\n if (obj == null)\n {\n return false;\n }\n\n // If parameter cannot be cast to SerializableType return false.\n SerializableType p = obj as SerializableType;\n if ((System.Object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (type == p.type);\n }\n public bool Equals(SerializableType p)\n {\n // If parameter is null return false:\n if ((object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (type == p.type);\n }\n}\n</code></pre>\n\n<p>and an example of usage:</p>\n\n<pre><code>[DataContract]\npublic class A\n{\n\n ...\n\n [DataMember]\n private Dictionary<SerializableType, B> _bees;\n\n ...\n\n public B GetB(Type type)\n {\n return _bees[type];\n }\n\n ...\n\n}\n</code></pre>\n\n<p>You might also consider using AssemblyQualifiedName instead of Type.FullName - see comment by @GreyCloud</p>\n"
},
{
"answer_id": 21435254,
"author": "Dzyann",
"author_id": 752842,
"author_profile": "https://Stackoverflow.com/users/752842",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/12342/752842\">Brian's</a> answer works well if the type is in the same assembly as the call (like GreyCloud pointed out in one of the comments).\nSo if the type is in another assembly you need to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname%28v=vs.110%29.aspx\" rel=\"noreferrer\">AssemblyQualifiedName</a> as GreyCloud also pointed out.</p>\n\n<p>However as the <a href=\"http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname%28v=vs.110%29.aspx\" rel=\"noreferrer\">AssemblyQualifiedName</a> saves the version, if your assemblies have a different version than the one in the string where you have the type, it won't work.</p>\n\n<p>In my case this was an issue and I solved it like this:</p>\n\n<pre><code>string typeName = typeof (MyClass).FullName;\n\nType type = GetTypeFrom(typeName);\n\nobject myInstance = Activator.CreateInstance(type);\n</code></pre>\n\n<p><strong>GetTypeFrom Method</strong></p>\n\n<pre><code>private Type GetTypeFrom(string valueType)\n {\n var type = Type.GetType(valueType);\n if (type != null)\n return type;\n\n try\n {\n var assemblies = AppDomain.CurrentDomain.GetAssemblies(); \n\n //To speed things up, we check first in the already loaded assemblies.\n foreach (var assembly in assemblies)\n {\n type = assembly.GetType(valueType);\n if (type != null)\n break;\n }\n if (type != null)\n return type;\n\n var loadedAssemblies = assemblies.ToList();\n\n foreach (var loadedAssembly in assemblies)\n {\n foreach (AssemblyName referencedAssemblyName in loadedAssembly.GetReferencedAssemblies())\n {\n var found = loadedAssemblies.All(x => x.GetName() != referencedAssemblyName);\n\n if (!found)\n {\n try\n {\n var referencedAssembly = Assembly.Load(referencedAssemblyName);\n type = referencedAssembly.GetType(valueType);\n if (type != null)\n break;\n loadedAssemblies.Add(referencedAssembly);\n }\n catch\n {\n //We will ignore this, because the Type might still be in one of the other Assemblies.\n }\n }\n }\n } \n }\n catch(Exception exception)\n {\n //throw my custom exception \n }\n\n if (type == null)\n {\n //throw my custom exception.\n }\n\n return type;\n }\n</code></pre>\n\n<p>I am posting this in case anyone needs it.</p>\n"
},
{
"answer_id": 54830442,
"author": "Peter Riesz",
"author_id": 1003150,
"author_profile": "https://Stackoverflow.com/users/1003150",
"pm_score": 2,
"selected": false,
"text": "<p>I came across this issue trying to do binary serialization in .net standard 2.0. I ended up solving the problem using a custom <code>SurrogateSelector</code> and <code>SerializationBinder</code>.</p>\n\n<p>The <code>TypeSerializationBinder</code> was required because the framework was having trouble resolving <code>System.RuntimeType</code> before it got <code>SurrogateSelector</code>. I don't really understand why the type must be resolved before this step though...</p>\n\n<p>Here is the code:</p>\n\n<pre><code>// Serializes and deserializes System.Type\npublic class TypeSerializationSurrogate : ISerializationSurrogate {\n public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) {\n info.AddValue(nameof(Type.FullName), (obj as Type).FullName);\n }\n\n public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) {\n return Type.GetType(info.GetString(nameof(Type.FullName)));\n }\n}\n\n// Just a stub, doesn't need an implementation\npublic class TypeStub : Type { ... }\n\n// Binds \"System.RuntimeType\" to our TypeStub\npublic class TypeSerializationBinder : SerializationBinder {\n public override Type BindToType(string assemblyName, string typeName) {\n if(typeName == \"System.RuntimeType\") {\n return typeof(TypeStub);\n }\n return Type.GetType($\"{typeName}, {assemblyName}\");\n }\n}\n\n// Selected out TypeSerializationSurrogate when [de]serializing Type\npublic class TypeSurrogateSelector : ISurrogateSelector {\n public virtual void ChainSelector(ISurrogateSelector selector) => throw new NotSupportedException();\n\n public virtual ISurrogateSelector GetNextSelector() => throw new NotSupportedException();\n\n public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) {\n if(typeof(Type).IsAssignableFrom(type)) {\n selector = this;\n return new TypeSerializationSurrogate();\n }\n selector = null;\n return null;\n }\n}\n</code></pre>\n\n<p>Usage Example:</p>\n\n<pre><code>byte[] bytes\nvar serializeFormatter = new BinaryFormatter() {\n SurrogateSelector = new TypeSurrogateSelector()\n}\nusing (var stream = new MemoryStream()) {\n serializeFormatter.Serialize(stream, typeof(string));\n bytes = stream.ToArray();\n}\n\nvar deserializeFormatter = new BinaryFormatter() {\n SurrogateSelector = new TypeSurrogateSelector(),\n Binder = new TypeDeserializationBinder()\n}\nusing (var stream = new MemoryStream(bytes)) {\n type = (Type)deserializeFormatter .Deserialize(stream);\n Assert.Equal(typeof(string), type);\n}\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] | I'm trying to serialize a Type object in the following way:
```
Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
```
When I do this, the call to Serialize throws the following exception:
>
> "The type System.Text.StringBuilder was not expected. Use the
> XmlInclude or SoapInclude attribute to specify types that are not
> known statically."
>
>
>
Is there a way for me to serialize the `Type` object? Note that I am not trying to serialize the `StringBuilder` itself, but the `Type` object containing the metadata about the `StringBuilder` class. | I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:
```
string typeName = typeof (StringBuilder).FullName;
```
You can then persist this string however needed, then reconstruct the type like this:
```
Type t = Type.GetType(typeName);
```
If you need to create an instance of the type, you can do this:
```
object o = Activator.CreateInstance(t);
```
If you check the value of o.GetType(), it will be StringBuilder, just as you would expect. |
12,319 | <p>I'm looking to the equivalent of Windows <a href="http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx" rel="noreferrer"><code>_wfopen()</code></a> under Mac OS X. Any idea?</p>
<p>I need this in order to port a Windows library that uses <code>wchar*</code> for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.</p>
| [
{
"answer_id": 12367,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using Cocoa it's fairly easy with NSString. Just load the UTF16 data in using -initWithBytes:length:encoding: (or perhaps -initWithCString:encoding:) and then get a UTF8 version by calling UTF8String on the result. Then, just call fopen with your new UTF8 string as the param.</p>\n\n<p>You can definitely call fopen with a UTF-8 string, regardless of language - can't help with C++ on OSX though - sorry.</p>\n"
},
{
"answer_id": 13562,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>You just want to open a file handle using a path that may contain Unicode characters, right? Just pass the path in <em>filesystem representation</em> to <code>fopen</code>.</p>\n\n<ul>\n<li><p>If the path came from the stock Mac OS X frameworks (for example, an Open panel whether Carbon or Cocoa), you won't need to do any conversion on it and will be able to use it as-is.</p></li>\n<li><p>If you're generating part of the path yourself, you should create a CFStringRef from your path and then get that in filesystem representation to pass to POSIX APIs like <code>open</code> or <code>fopen</code>.</p></li>\n</ul>\n\n<p>Generally speaking, you won't have to do a lot of that for most applications. For example, many applications may have auxiliary data files stored the user's Application Support directory, but as long as the names of those files are ASCII, and you use standard Mac OS X APIs to locate the user's Application Support directory, you don't need to do a bunch of paranoid conversion of a path constructed with those two components.</p>\n\n<p><em>Edited to add:</em> I would strongly caution <strong>against</strong> arbitrarily converting everything to UTF-8 using something like <code>wcstombs</code> because filesystem encoding is not necessarily identical to the generated UTF-8. Mac OS X and Windows both use specific (but different) canonical decomposition rules for the encoding used in filesystem paths.</p>\n\n<p>For example, they need to decide whether \"é\" will be stored as one or two code units (either <code>LATIN SMALL LETTER E WITH ACUTE</code> or <code>LATIN SMALL LETTER E</code> followed by <code>COMBINING ACUTE ACCENT</code>). These will result in two different — and different-length — byte sequences, and both Mac OS X and Windows work to avoid putting multiple files with the same name (as the user perceives them) in the same directory.</p>\n\n<p>The rules for how to perform this canonical decomposition can get pretty hairy, so rather than try to implement it yourself it's best to leave it to the functions the system frameworks have provided for you to do the heavy lifting.</p>\n"
},
{
"answer_id": 161798,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "<p>@JKP:</p>\n\n<p>Not all functions in MacOS X accept UTF8, but filenames and filepaths may be UTF8, thus all POSIX functions dealing with file access (open, fopen, stat, etc.) accept UTF8.</p>\n\n<p>See <a href=\"http://lists.apple.com/archives/applescript-users/2002/Sep/msg00319.html\" rel=\"nofollow noreferrer\">here</a>. Quote:</p>\n\n<blockquote>\n <p>How a file name looks at the API level\n depends on the API. Current Carbon\n APIs handle file names as an array of\n UTF-16 characters; POSIX ones handle\n them as an array of UTF-8, which is\n why UTF-8 works well in Terminal. How\n it's stored on disk depends on the\n disk format; HFS+ uses UTF-16, but\n that's not important in most cases.</p>\n</blockquote>\n\n<p>Some other POSIX functions handle UTF8 as well. E.g. functions dealing with user names, group names or user passwords use UTF8 to store the information (thus a user name can be Japanese and your password can be Chinese, no problem).</p>\n\n<p>But not all handle UTF8. E.g. for all string functions an UTF8 string is just a normal C String and characters above 126 have no special meaning. They don't understand the concept of multiple bytes (chars in C) forming a single Unicode character. How other APIs handle char * pointer being passed to them is different from API to API. However, as a rule as the thumb you can say:</p>\n\n<p>Either the function only accepts C strings with pure ASCII characters (only in the range 0 to 126) or it will accept UTF8. Usually functions don't allow characters above 126 and interpret them in any other encoding than UTF8. If this really was the case, it is documented and then there must be a way to pass the encoding along with the string.</p>\n"
},
{
"answer_id": 265407,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 5,
"selected": true,
"text": "<p>POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X. </p>\n\n<p>Here is a class that will wrap an UTF-8 generated string from a wchar_t string.</p>\n\n<pre><code>class Utf8\n{\npublic:\n Utf8(const wchar_t* wsz): m_utf8(NULL)\n {\n // OS X uses 32-bit wchar\n const int bytes = wcslen(wsz) * sizeof(wchar_t);\n // comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel\n CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE\n : kCFStringEncodingUTF32BE;\n CFStringRef str = CFStringCreateWithBytesNoCopy(NULL, \n (const UInt8*)wsz, bytes, \n encoding, false, \n kCFAllocatorNull\n );\n\n const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);\n m_utf8 = new char[bytesUtf8];\n CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);\n CFRelease(str);\n } \n\n ~Utf8() \n { \n if( m_utf8 )\n {\n delete[] m_utf8;\n }\n }\n\npublic:\n operator const char*() const { return m_utf8; }\n\nprivate:\n char* m_utf8;\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>const wchar_t wsz = L\"Here is some Unicode content: éà€œæ\";\nconst Utf8 utf8 = wsz;\nFILE* file = fopen(utf8, \"r\");\n</code></pre>\n\n<p>This will work for reading or writing files.</p>\n"
},
{
"answer_id": 20800154,
"author": "AVG",
"author_id": 1421589,
"author_profile": "https://Stackoverflow.com/users/1421589",
"pm_score": 0,
"selected": false,
"text": "<p>I have read file name from configuration UTF8 file through <strong>wifstream</strong> (it uses <strong>wchar_t</strong> buffer). </p>\n\n<p>Mac implementation is different from Linux and Windows. \nwifstream reads each byte from file to separate wchar_t cell in the buffer. So we have 3 empty bytes, although <strong>open</strong> requires <strong>char</strong> string. Thus programmer can use <strong>wcstombs</strong> function to convert wide character string to multi-byte string. </p>\n\n<p>The API supports UTF8. For better understanding use memory watcher and hex editor for your file.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] | I'm looking to the equivalent of Windows [`_wfopen()`](http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx) under Mac OS X. Any idea?
I need this in order to port a Windows library that uses `wchar*` for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library. | POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar\_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X.
Here is a class that will wrap an UTF-8 generated string from a wchar\_t string.
```
class Utf8
{
public:
Utf8(const wchar_t* wsz): m_utf8(NULL)
{
// OS X uses 32-bit wchar
const int bytes = wcslen(wsz) * sizeof(wchar_t);
// comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel
CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE
: kCFStringEncodingUTF32BE;
CFStringRef str = CFStringCreateWithBytesNoCopy(NULL,
(const UInt8*)wsz, bytes,
encoding, false,
kCFAllocatorNull
);
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);
m_utf8 = new char[bytesUtf8];
CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);
CFRelease(str);
}
~Utf8()
{
if( m_utf8 )
{
delete[] m_utf8;
}
}
public:
operator const char*() const { return m_utf8; }
private:
char* m_utf8;
};
```
Usage:
```
const wchar_t wsz = L"Here is some Unicode content: éà€œæ";
const Utf8 utf8 = wsz;
FILE* file = fopen(utf8, "r");
```
This will work for reading or writing files. |
12,368 | <p>The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class <code>MyClass</code> to call</p>
<pre><code>MyClass.Dispose()
</code></pre>
<p>and free up all the used space by variables and objects in <code>MyClass</code>?</p>
| [
{
"answer_id": 12376,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c7047/\" rel=\"nofollow noreferrer\" title=\"Forcing Garbage Collection in .Net\">This article</a> has a pretty straightforward walkthrough. However, <em>having</em> to call the GC instead of letting it take its natural course is generally a sign of bad design/memory management, <strong>especially</strong> if no limited resources are being consumed (connections, handles, anything else that typically leads to implementing IDisposable).</p>\n\n<p>What's causing you to need to do this?</p>\n"
},
{
"answer_id": 12377,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public class MyClass : IDisposable\n{\n public void Dispose()\n {\n // cleanup here\n }\n}\n</code></pre>\n\n<p>then you can do something like this</p>\n\n<pre><code>MyClass todispose = new MyClass();\ntodispose.Dispose(); // instance is disposed right here\n</code></pre>\n\n<p>or</p>\n\n<pre><code>using (MyClass instance = new MyClass())\n{\n\n}\n// instance will be disposed right here as it goes out of scope\n</code></pre>\n"
},
{
"answer_id": 12380,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>If MyClass implements IDisposable you can do just that.</p>\n\n<pre><code>MyClass.Dispose();\n</code></pre>\n\n<p>Best practice in C# is:</p>\n\n<pre><code>using( MyClass x = new MyClass() ) {\n //do stuff\n}\n</code></pre>\n\n<p>As that wraps up the dispose in a try-finally and makes sure that it's never missed.</p>\n"
},
{
"answer_id": 12383,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want to (or can't) implement IDisposable on your class, you can force garbage collection like this (but it's slow) -</p>\n\n<pre><code>GC.Collect();\n</code></pre>\n"
},
{
"answer_id": 12394,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 8,
"selected": true,
"text": "<p>IDisposable has nothing to do with freeing memory. IDisposable is a pattern for freeing <em>unmanaged</em> resources -- and memory is quite definitely a managed resource.</p>\n\n<p>The links pointing to GC.Collect() are the correct answer, though use of this function is generally discouraged by the Microsoft .NET documentation.</p>\n\n<p><strong>Edit:</strong> Having earned a substantial amount of karma for this answer, I feel a certain responsibility to elaborate on it, lest a newcomer to .NET resource management get the wrong impression.</p>\n\n<p>Inside a .NET process, there are two kinds of resource -- managed and unmanaged. \"Managed\" means that the runtime is in control of the resource, while \"unmanaged\" means that it's the programmer's responsibility. And there really is only one kind of managed resource that we care about in .NET today -- memory. The programmer tells the runtime to allocate memory and after that it's up to the runtime to figure out when the memory can freed. The mechanism that .NET uses for this purpose is called <a href=\"http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)\" rel=\"noreferrer\">garbage collection</a> and you can find plenty of information about GC on the internet simply by using Google.</p>\n\n<p>For the other kinds of resources, .NET doesn't know anything about cleaning them up so it has to rely on the programmer to do the right thing. To this end, the platform gives the programmer three tools:</p>\n\n<ol>\n<li>The IDisposable interface and the \"using\" statement in VB and C#</li>\n<li>Finalizers</li>\n<li>The IDisposable pattern as implemented by many BCL classes</li>\n</ol>\n\n<p>The first of these allows the programmer to efficiently acquire a resource, use it and then release it all within the same method.</p>\n\n<pre><code>using (DisposableObject tmp = DisposableObject.AcquireResource()) {\n // Do something with tmp\n}\n// At this point, tmp.Dispose() will automatically have been called\n// BUT, tmp may still a perfectly valid object that still takes up memory\n</code></pre>\n\n<p>If \"AcquireResource\" is a factory method that (for instance) opens a file and \"Dispose\" automatically closes the file, then this code cannot leak a file resource. But the memory for the \"tmp\" object itself may well still be allocated. That's because the IDisposable interface has absolutely no connection to the garbage collector. If you <em>did</em> want to ensure that the memory was freed, your only option would be to call <code>GC.Collect()</code> to force a garbage collection.</p>\n\n<p>However, it cannot be stressed enough that this is probably not a good idea. It's generally much better to let the garbage collector do what it was designed to do, which is to manage memory.</p>\n\n<p>What happens if the resource is being used for a longer period of time, such that its lifespan crosses several methods? Clearly, the \"using\" statement is no longer applicable, so the programmer would have to manually call \"Dispose\" when he or she is done with the resource. And what happens if the programmer forgets? If there's no fallback, then the process or computer may eventually run out of whichever resource isn't being properly freed.</p>\n\n<p>That's where finalizers come in. A finalizer is a method on your class that has a special relationship with the garbage collector. The GC promises that -- before freeing the memory for any object of that type -- it will first give the finalizer a chance to do some kind of cleanup.</p>\n\n<p>So in the case of a file, we theoretically don't need to close the file manually at all. We can just wait until the garbage collector gets to it and then let the finalizer do the work. Unfortunately, this doesn't work well in practice because the garbage collector runs non-deterministically. The file may stay open considerably longer than the programmer expects. And if enough files are kept open, the system may fail when trying to open an additional file.</p>\n\n<p>For most resources, we want both of these things. We want a convention to be able to say \"we're done with this resource now\" and we want to make sure that there's at least some chance for the cleanup to happen automatically if we forget to do it manually. That's where the \"IDisposable\" pattern comes into play. This is a convention that allows IDispose and a finalizer to play nicely together. You can see how the pattern works by looking at the <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"noreferrer\">official documentation for IDisposable</a>.</p>\n\n<p><strong>Bottom line:</strong> If what you really want to do is to just make sure that memory is freed, then IDisposable and finalizers will not help you. But the IDisposable interface is part of an extremely important pattern that all .NET programmers should understand.</p>\n"
},
{
"answer_id": 12396,
"author": "Brian Lyttle",
"author_id": 636,
"author_profile": "https://Stackoverflow.com/users/636",
"pm_score": 4,
"selected": false,
"text": "<p>Would it be appropriate to also mention that dispose doesn't always refer to memory? I dispose resources such a references to files more often than memory. GC.Collect() directly relates to the CLR garbage collector and may or may not free memory (in Task Manager). It will likely impact your application in negative ways (eg performance).</p>\n\n<p>At the end of the day why do you want the memory back immediately? If there is memory pressure from elsewhere the OS will get you memory in most cases.</p>\n"
},
{
"answer_id": 12398,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 2,
"selected": false,
"text": "<p>You can't really force a GC to clean up an object when you want, although there are ways to force it to run, nothing says it's clean up the all the object you want/expect. It's best to call dispose in a try catch ex finally dispose end try (VB.NET rulz) way. But Dispose is for cleaning up system resources (memory, handles, db connections, etc. allocated by the object in deterministic way. Dispose doesn't (and can't) clean up the memory used by the object itself, only the the GC can do that. </p>\n"
},
{
"answer_id": 12405,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 5,
"selected": false,
"text": "<p>You can only dispose instances that implement the IDisposable interface. </p>\n\n<p><strong>To force a garbage collect to free up the (unmanaged) memory immediately:</strong></p>\n\n<pre><code>GC.Collect(); \nGC.WaitForPendingFinalizers();\n</code></pre>\n\n<p>This is normally bad practice, but there is for example a bug in the x64-version of the .NET framework that makes the GC behave strange in some scenarios, and then you might want to do this. I don't know if the bug have been resolved yet. Does anyone know?</p>\n\n<p><strong>To dispose a class you do this:</strong></p>\n\n<pre><code>instance.Dispose();\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>using(MyClass instance = new MyClass())\n{\n // Your cool code.\n}\n</code></pre>\n\n<p>that will translate at compile-time to:</p>\n\n<pre><code>MyClass instance = null; \n\ntry\n{\n instance = new MyClass(); \n // Your cool code.\n}\nfinally\n{\n if(instance != null)\n instance.Dispose();\n}\n</code></pre>\n\n<p><strong>You can implement the IDisposable interface like this:</strong></p>\n\n<pre><code>public class MyClass : IDisposable\n{\n private bool disposed;\n\n /// <summary>\n /// Construction\n /// </summary>\n public MyClass()\n {\n }\n\n /// <summary>\n /// Destructor\n /// </summary>\n ~MyClass()\n {\n this.Dispose(false);\n }\n\n /// <summary>\n /// The dispose method that implements IDisposable.\n /// </summary>\n public void Dispose()\n {\n this.Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// The virtual dispose method that allows\n /// classes inherithed from this one to dispose their resources.\n /// </summary>\n /// <param name=\"disposing\"></param>\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n // Dispose managed resources here.\n }\n\n // Dispose unmanaged resources here.\n }\n\n disposed = true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12470,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 0,
"selected": false,
"text": "<p>IDisposable interface is really for classes that contain unmanaged resources. If your class doesn't contain unmanaged resources, why do you <strong>need</strong> to free up resources before the garbage collector does it? Otherwise, just ensure your object is instantiated as late as possible and goes out of scope as soon as possible.</p>\n"
},
{
"answer_id": 13649,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at this <a href=\"http://www.codeproject.com/KB/cs/idisposable.aspx\" rel=\"nofollow noreferrer\">article</a></p>\n\n<p>Implementing the Dispose pattern, IDisposable, and/or a finalizer has absolutely nothing to do with when memory gets reclaimed; instead, it has everything to do with telling the GC <strong><em>how</em></strong> to reclaim that memory. When you call Dispose() you are in no way interacting with the GC.</p>\n\n<p>The GC will only run when it determines the need to (called memory pressure) and then (and only then) will it deallocate memory for unused objects and compact the memory space.</p>\n\n<p>You <em>could</em> call GC.Collect() but you really shouldn't unless there is a <strong>very</strong> good reason to (which is almost always \"Never\"). When you force an out-of-band collection cycle like this you actually cause the GC to do more work and ultimately can end up hurting your applications performance. For the duration of the GC collection cycle your application is actually in a frozen state...the more GC cycles that run, the more time your application spends frozen.</p>\n\n<p>There are also some native Win32 API calls you can make to free your working set, but even those should be avoided unless there is a <strong>very</strong> good reason to do it.</p>\n\n<p>The whole premise behind a gargbage collected runtime is that you don't need to worry (as much) about when the runtime allocates/deallocates actual memory; you only need to worry about making sure the your object knows how to clean up after itself when asked.</p>\n"
},
{
"answer_id": 19463,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 0,
"selected": false,
"text": "<p>You can have deterministic object destruction in c++</p>\n\n<p>You never want to call GC.Collect, it messes with the self tuning of the garbage collector to detect memory pressure and in some cases do nothing other than increase the current generation of every object on the heap. </p>\n\n<p>For those posting IDisposable answers. Calling a Dispose method doesn't destroy an object as the asker describes.</p>\n"
},
{
"answer_id": 26949,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry but the selected answer here is incorrect. As a few people have stated subsequently Dispose and implementing IDisposable has nothing to do with freeing the memory associated with a .NET class. It is mainly and traditionally used to free unmanaged resources such as file handles etc.</p>\n\n<p>While your application can call GC.Collect() to try to force a collection by the garbage collector this will only really have an effect on those items that are at the correct generation level in the freachable queue. So it is possible that if you have cleared all references to the object it might still be a couple of calls to GC.Collect() before the actual memory is freed.</p>\n\n<p>You don't say in your question WHY you feel the need to free up memory immediately. I understand that sometimes there can be unusual circumstances but seriously, in managed code it is almost always best to let the runtime deal with memory management.</p>\n\n<p>Probably the best advice if you think your code is using up memory quicker than the GC is freeing it then you should review your code to ensure that no objects that are no longer needed are referenced in any data structures you have lying around in static members etc. Also try to avoid situations where you have circular object references as it is possible that these may not be freed either. </p>\n"
},
{
"answer_id": 27597,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>@Curt Hagenlocher - that's back to front. I've no idea why so many have voted it up when it's wrong.</p>\n\n<p><code>IDisposable</code> is for <em>managed</em> resources.</p>\n\n<p>Finalisers are for <em>unmanaged</em> resources.</p>\n\n<p>As long as you only use managed resources both @Jon Limjap and myself are entirely correct.</p>\n\n<p>For classes that use unmanaged resources (and bear in mind that the vast majority of .Net classes don't) Patrik's answer is comprehensive and best practice.</p>\n\n<p>Avoid using GC.Collect - it is a slow way to deal with managed resources, and doesn't do anything with unmanaged ones unless you have correctly built your ~Finalizers.</p>\n\n<hr>\n\n<p>I've removed the moderator comment from the original question in line with <a href=\"https://stackoverflow.com/questions/14593/etiquette-for-modifying-posts\">https://stackoverflow.com/questions/14593/etiquette-for-modifying-posts</a></p>\n"
},
{
"answer_id": 27608,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>@Keith:</p>\n<blockquote>\n<p>IDisposable is for managed resources.</p>\n<p>Finalisers are for unmanaged resources.</p>\n</blockquote>\n<p>Sorry but that's just wrong. Normally, the finalizer does nothing at all. However, if the <a href=\"http://blogs.msdn.com/bclteam/archive/2007/10/30/dispose-pattern-and-object-lifetime-brian-grunkemeyer.aspx\" rel=\"nofollow noreferrer\">dispose pattern</a> has been correctly implemented, the finalizer tries to invoke <code>Dispose</code>.</p>\n<p><code>Dispose</code> has two jobs:</p>\n<ul>\n<li>Free unmanaged resources, and</li>\n<li>free nested managed resources.</li>\n</ul>\n<p>And here your statement comes into play because it's true that while finalizing, an object should never try to free nested managed resources as these may have already been freed. It must still free unmanaged resources though.</p>\n<p>Still, finalizers have no job other than to call <code>Dispose</code> and tell it not to touch managed objects. <code>Dispose</code>, when called manually (or via <code>Using</code>), shall free all unmanaged resources and pass the <code>Dispose</code> message on to nested objects (and base class methods) but this will <em>never</em> free any (managed) memory.</p>\n"
},
{
"answer_id": 27630,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>Konrad Rudolph - yup, normally the finaliser does nothing at all. You shouldn't implement it unless you are dealing with unmanaged resources.</p>\n\n<p>Then, when you do implement it, you use <a href=\"http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx\" rel=\"nofollow noreferrer\">Microsoft's dispose pattern</a> (as already described)</p>\n\n<ul>\n<li><p><code>public Dispose()</code> calls <code>protected Dispose(true)</code> - deals with both managed and unmanaged resources. Calling <code>Dispose()</code> should suppress finalisation.</p></li>\n<li><p><code>~Finalize</code> calls <code>protected Dispose(false)</code> - deals with unmanaged resources only. This prevents unmanaged memory leaks if you fail to call the <code>public Dispose()</code></p></li>\n</ul>\n\n<p><code>~Finalize</code> is slow, and shouldn't be used unless you do have unmanaged resources to deal with.</p>\n\n<p>Managed resources can't memory leak, they can only waste resources for the current application and slow its garbage collection. Unmanaged resources can leak, and <code>~Finalize</code> is best practice to ensure that they don't.</p>\n\n<p>In either case <code>using</code> is best practice.</p>\n"
},
{
"answer_id": 27637,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>Complete explanation by Joe Duffy on \"<a href=\"http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae\" rel=\"nofollow noreferrer\">Dispose, Finalization, and Resource Management</a>\":</p>\n\n<blockquote>\n <p>Earlier in the .NET Framework’s\n lifetime, finalizers were consistently\n referred to as destructors by C#\n programmers. As we become smarter over\n time, we are trying to come to terms\n with the fact that the <strong>Dispose method\n is really more equivalent to a C++\n destructor (deterministic)</strong>, while the\n <strong>finalizer is something entirely\n separate (nondeterministic)</strong>. The fact\n that C# borrowed the C++ destructor\n syntax (i.e. ~T()) surely had at least\n a little to do with the development of\n this misnomer.</p>\n</blockquote>\n"
},
{
"answer_id": 36737,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>The responses to this question have got more than a little confused.</p>\n\n<p>The title asks about disposal, but then says that they want memory back immediately.</p>\n\n<p>.Net is <em>managed</em>, which means that when you write .Net apps you don't need to worry about memory directly, the cost is that you don't have direct control over memory either.</p>\n\n<p>.Net decides when it's best to clean up and free memory, not you as the .Net coder.</p>\n\n<p>The <code>Dispose</code> is a way to tell .Net that you're done with something, but it won't actually free up the memory until it's the best time to do so.</p>\n\n<p>Basically .Net will actually collect the memory back when it's easiest for it to do so - it's very good at deciding when. Unless you're writing something very memory intensive you normally don't need to overrule it (this is part of the reason games aren't often written in .Net yet - they need complete control)</p>\n\n<p>In .Net you can use <code>GC.Collect()</code> to force it to immediately, but that is almost always bad practise. If .Net hasn't cleaned it up yet that means it isn't a particularly good time for it to do so.</p>\n\n<p><code>GC.Collect()</code> picks up the objects that .Net identifies as done with. If you haven't disposed an object that needs it .Net may decide to keep that object. This means that <code>GC.Collect()</code> is only effective if you correctly implement your disposable instances.</p>\n\n<p><code>GC.Collect()</code> is <strong>not</strong> a replacement for correctly using IDisposable.</p>\n\n<p>So Dispose and memory are not directly related, but they don't need to be. Correctly disposing will make your .Net apps more efficient and therefore use less memory though.</p>\n\n<hr>\n\n<p>99% of the time in .Net the following is best practice:</p>\n\n<p><strong>Rule 1:</strong> If you don't deal with anything <em>unmanaged</em> or that implements <code>IDisposable</code> then don't worry about Dispose.</p>\n\n<p><strong>Rule 2:</strong> If you have a local variable that implements IDisposable make sure that you get rid of it in the current scope:</p>\n\n<pre><code>//using is best practice\nusing( SqlConnection con = new SqlConnection(\"my con str\" ) )\n{\n //do stuff\n} \n\n//this is what 'using' actually compiles to:\nSqlConnection con = new SqlConnection(\"my con str\" ) ;\ntry\n{\n //do stuff\n}\nfinally\n{\n con.Dispose();\n}\n</code></pre>\n\n<p><strong>Rule 3:</strong> If a class has a property or member variable that implements IDisposable then that class should implement IDisposable too. In that class's Dispose method you can also dispose of your IDisposable properties:</p>\n\n<pre><code>//rather basic example\npublic sealed MyClass :\n IDisposable\n{ \n //this connection is disposable\n public SqlConnection MyConnection { get; set; }\n\n //make sure this gets rid of it too\n public Dispose() \n {\n //if we still have a connection dispose it\n if( MyConnection != null )\n MyConnection.Dispose();\n\n //note that the connection might have already been disposed\n //always write disposals so that they can be called again\n }\n}\n</code></pre>\n\n<p>This isn't really complete, which is why the example is sealed. Inheriting classes may need to observe the next rule...</p>\n\n<p><strong>Rule 4:</strong> If a class uses an <em>unmanaged</em> resource then implement IDispose <em>and</em> add a finaliser.</p>\n\n<p>.Net can't do anything with the <em>unmanaged</em> resource, so now we are talking about memory. If you don't clean it up you can get a memory leak.</p>\n\n<p>The Dispose method needs to deal with both <em>managed</em> and <em>unmanaged</em> resources.</p>\n\n<p>The finaliser is a safety catch - it ensures that if someone else creates and instance of your class and fails to dispose it the 'dangerous' <em>unmanaged</em> resources can still be cleaned up by .Net.</p>\n\n<pre><code>~MyClass()\n{\n //calls a protected method \n //the false tells this method\n //not to bother with managed\n //resources\n this.Dispose(false);\n}\n\npublic void Dispose()\n{\n //calls the same method\n //passed true to tell it to\n //clean up managed and unmanaged \n this.Dispose(true);\n\n //as dispose has been correctly\n //called we don't need the \n\n //'backup' finaliser\n GC.SuppressFinalize(this);\n}\n</code></pre>\n\n<p>Finally this overload of Dispose that takes a boolean flag:</p>\n\n<pre><code>protected virtual void Dispose(bool disposing)\n{\n //check this hasn't been called already\n //remember that Dispose can be called again\n if (!disposed)\n {\n //this is passed true in the regular Dispose\n if (disposing)\n {\n // Dispose managed resources here.\n }\n\n //both regular Dispose and the finaliser\n //will hit this code\n // Dispose unmanaged resources here.\n }\n\n disposed = true;\n}\n</code></pre>\n\n<p>Note that once this is all in place other managed code creating an instance of your class can just treat it like any other IDisposable (Rules 2 and 3).</p>\n"
},
{
"answer_id": 36751,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>@Keith,</p>\n\n<p>I agree with all of your rules except #4. Adding a finalizer should only be done under very specific circumstances. If a class uses unmanaged resources, those should be cleaned up in your Dispose(bool) function. This same function should only cleanup managed resources when bool is true. Adding a finalizer adds a complexity cost to using your object as each time you create a new instance it must also be placed on the finalization queue, which is checked each time the GC runs a collection cycle. Effectively, this means that your object survives one cycle/generation longer than it should so the finalizer can be run. The finalizer should not be thought of as a \"safety net\".</p>\n\n<p>The GC will only run a collection cycle when it determines that there is not enough available memory in the Gen0 heap to perform the next allocation, unless you \"help\" it by calling GC.Collect() to force an out-of-band collection.</p>\n\n<p>The bottom line is that, no matter what, the GC only knows how to release resources by calling the Dispose method (and possibly the finalizer if one is implemented). It is up to that method to \"do the right thing\" and clean up any unmanaged resources used and instruct any other managed resources to call their Dispose method. It is very efficient at what it does and can self-optimize to a large extent as long as it isn't helped by out-of-band collection cycles. That being said, short of calling GC.Collect explicitly you have no control over when and in what order objects will be disposed of and memory released.</p>\n"
},
{
"answer_id": 9832716,
"author": "Jaycephus",
"author_id": 1287133,
"author_profile": "https://Stackoverflow.com/users/1287133",
"pm_score": -1,
"selected": false,
"text": "<p>In answer to the original question, with the information given so far by the original poster, it is 100% certain that he does not know enough about programming in .NET to even be given the answer: use GC.Collect(). I would say it is 99.99% likely that he really doesn't need to use GC.Collect() at all, as most posters have pointed out. </p>\n\n<p>The correct answer boils down to 'Let the GC do its job. Period. You have other stuff to worry about. But you might want to consider whether and when you should dispose of or clean up specific objects, and whether you need to implement IDisposable and possibly Finalize in your class.'</p>\n\n<p>Regarding Keith's post and his Rule #4:</p>\n\n<p>Some posters are confusing rule 3 and rule 4. Keith's rule 4 is absolutely correct, unequivocately. It's the one rule of the four that needs no editing at all. I would slightly rephrase some of his other rules to make them clearer, but they are essentially correct if you parse them correctly, and actually read the whole post to see how he expands on them.</p>\n\n<ol>\n<li><p>If your class doesn't use an unmanaged resource AND it also never instantiates another object of a class that itself uses, directly or ultimately, an unmanaged object (i.e., a class that implements IDisposable), then there would be no need for your class to either implement IDisposable itself, or even call .dispose on anything. (In such a case, it is silly to think you actually NEED to immediately free up memory with a forced GC, anyway.)</p></li>\n<li><p>If your class uses an unmanaged resource, OR instantiates another object that itself implements IDisposable, then your class should either:</p>\n\n<p>a) dispose/release these immediately in a local context in which they were created, OR...</p>\n\n<p>b) implement IDisposable in the pattern recommended within Keith's post, or a few thousand places on the internet, or in literally about 300 books by now.</p>\n\n<p>b.1) Furthermore, if (b), and it is an unmanaged resource that has been opened, both IDisposable AND Finalize SHOULD ALWAYS be implemented, per Keith's Rule #4.<br>\nIn this context, Finalize absolutely IS a safety net in one sense: if someone instantiates YOUR IDisposable object that uses an unmanaged resource, and they fail to call dispose, then Finalize is the last chance for YOUR object to close the unmanaged resource properly.<br>\n(Finalize should do this by calling Dispose in such a way that the Dispose method skips over releasing anything BUT the unmanaged resource. Alternatively, if your object's Dispose method IS called properly by whatever instantiated your object, then it BOTH passes on the Dispose call to all IDisposable objects it has instantiated, AND releases the unmanaged resources properly, ending with a call to suppress the Finalize on your object, which means that the impact of using Finalize is reduced if your object is disposed properly by the caller. All of these points are included in Keith's post, BTW.) </p>\n\n<p>b.2) IF your class is only implementing IDisposable because it needs to essentially pass on a Dispose to an IDisposable object it has instantiated, then don't implement a Finalize method in your class in that case. Finalize is for handling the case that BOTH Dispose was never called by whatever instantiated your object, AND an unmanaged resource was utilized that's still unreleased. </p></li>\n</ol>\n\n<p>In short, regarding Keith's post, he is completely correct, and that post is the most correct and complete answer, in my opinion. He may use some short-hand statements that some find 'wrong' or object to, but his full post expands on the usage of Finalize completely, and he is absolutely correct. Be sure to read his post completely before jumping on one of the rules or preliminary statements in his post.</p>\n"
},
{
"answer_id": 10422450,
"author": "Ashley Frieze",
"author_id": 1355930,
"author_profile": "https://Stackoverflow.com/users/1355930",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a summary of Destructors and Dispose and Garbage collection on <a href=\"http://codingcraftsman.wordpress.com/2012/04/25/to-dispose-or-not-to-dispose/\" rel=\"noreferrer\">http://codingcraftsman.wordpress.com/2012/04/25/to-dispose-or-not-to-dispose/</a></p>\n\n<p>To answer the original question:</p>\n\n<ol>\n<li>Don't try to manage your memory</li>\n<li>Dispose is not about memory management, it's about unmanaged resource management</li>\n<li>Finalizers are an innate part of the Dispose pattern and actually slow down memory freeing of managed objects (as they have to go into the Finalization queue unless already Dispose d)</li>\n<li>GC.Collect is bad as it makes some short-lived objects appear to be required for longer and so slows them down from being collected.</li>\n</ol>\n\n<p>However, GC.Collect could be useful if you had a performance critical section of code and wanted to reduce the likelihood of Garbage Collection slowing it down. You call that before.</p>\n\n<p>On top of that, there is an argument in favour of this pattern:</p>\n\n<pre><code>var myBigObject = new MyBigObject(1);\n// something happens\nmyBigObject = new MyBigObject(2);\n// at the above line, there are temporarily two big objects in memory and neither can be collected\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>myBigObject = null; // so it could now be collected\nmyBigObject = new MyBigObject(2);\n</code></pre>\n\n<p>But the main answer is that Garbage Collection just works unless you mess around with it!</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
] | The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class `MyClass` to call
```
MyClass.Dispose()
```
and free up all the used space by variables and objects in `MyClass`? | IDisposable has nothing to do with freeing memory. IDisposable is a pattern for freeing *unmanaged* resources -- and memory is quite definitely a managed resource.
The links pointing to GC.Collect() are the correct answer, though use of this function is generally discouraged by the Microsoft .NET documentation.
**Edit:** Having earned a substantial amount of karma for this answer, I feel a certain responsibility to elaborate on it, lest a newcomer to .NET resource management get the wrong impression.
Inside a .NET process, there are two kinds of resource -- managed and unmanaged. "Managed" means that the runtime is in control of the resource, while "unmanaged" means that it's the programmer's responsibility. And there really is only one kind of managed resource that we care about in .NET today -- memory. The programmer tells the runtime to allocate memory and after that it's up to the runtime to figure out when the memory can freed. The mechanism that .NET uses for this purpose is called [garbage collection](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) and you can find plenty of information about GC on the internet simply by using Google.
For the other kinds of resources, .NET doesn't know anything about cleaning them up so it has to rely on the programmer to do the right thing. To this end, the platform gives the programmer three tools:
1. The IDisposable interface and the "using" statement in VB and C#
2. Finalizers
3. The IDisposable pattern as implemented by many BCL classes
The first of these allows the programmer to efficiently acquire a resource, use it and then release it all within the same method.
```
using (DisposableObject tmp = DisposableObject.AcquireResource()) {
// Do something with tmp
}
// At this point, tmp.Dispose() will automatically have been called
// BUT, tmp may still a perfectly valid object that still takes up memory
```
If "AcquireResource" is a factory method that (for instance) opens a file and "Dispose" automatically closes the file, then this code cannot leak a file resource. But the memory for the "tmp" object itself may well still be allocated. That's because the IDisposable interface has absolutely no connection to the garbage collector. If you *did* want to ensure that the memory was freed, your only option would be to call `GC.Collect()` to force a garbage collection.
However, it cannot be stressed enough that this is probably not a good idea. It's generally much better to let the garbage collector do what it was designed to do, which is to manage memory.
What happens if the resource is being used for a longer period of time, such that its lifespan crosses several methods? Clearly, the "using" statement is no longer applicable, so the programmer would have to manually call "Dispose" when he or she is done with the resource. And what happens if the programmer forgets? If there's no fallback, then the process or computer may eventually run out of whichever resource isn't being properly freed.
That's where finalizers come in. A finalizer is a method on your class that has a special relationship with the garbage collector. The GC promises that -- before freeing the memory for any object of that type -- it will first give the finalizer a chance to do some kind of cleanup.
So in the case of a file, we theoretically don't need to close the file manually at all. We can just wait until the garbage collector gets to it and then let the finalizer do the work. Unfortunately, this doesn't work well in practice because the garbage collector runs non-deterministically. The file may stay open considerably longer than the programmer expects. And if enough files are kept open, the system may fail when trying to open an additional file.
For most resources, we want both of these things. We want a convention to be able to say "we're done with this resource now" and we want to make sure that there's at least some chance for the cleanup to happen automatically if we forget to do it manually. That's where the "IDisposable" pattern comes into play. This is a convention that allows IDispose and a finalizer to play nicely together. You can see how the pattern works by looking at the [official documentation for IDisposable](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx).
**Bottom line:** If what you really want to do is to just make sure that memory is freed, then IDisposable and finalizers will not help you. But the IDisposable interface is part of an extremely important pattern that all .NET programmers should understand. |
12,374 | <p>We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off.
But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users. </p>
<p>What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.</p>
<p>We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.</p>
<p>So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?</p>
<p>The second part of my questions is whether unit testing would be/is easier with linq? </p>
<p>I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all)</p>
| [
{
"answer_id": 12387,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried <a href=\"http://dbunit.sourceforge.net/\" rel=\"nofollow noreferrer\">DBUnit</a>? It's designed to unit test your database, and just your database, without needing to go through your C# code.</p>\n"
},
{
"answer_id": 12395,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 2,
"selected": false,
"text": "<p>I am assuming that you want unit testing in MSSQL. Looking at DBUnit there are some limitations in it's support for MSSQL. It doesn't support NVarChar for instance. <a href=\"http://dbunit.wikidot.com/mssql\" rel=\"nofollow noreferrer\">Here are some real users and their problems with DBUnit.</a></p>\n"
},
{
"answer_id": 12399,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>LINQ will simplify this only if you remove the logic from your stored procedures and reimplement it as linq queries. Which would be much more robust and easier to test, definitely. However, it sounds like your requirements would preclude this.</p>\n\n<p>TL;DR: Your design has issues. </p>\n"
},
{
"answer_id": 12409,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 3,
"selected": false,
"text": "<p>If you think about the kind of code that unit testing tends to promote: small highly-cohesive and lowly-coupled routines, then you should pretty much be able to see where at least part of the problem might be.</p>\n\n<p>In my cynical world, stored procedures are part of the RDBMS world's long-standing attempt to persuade you to move your business processing into the database, which makes sense when you consider that server license costs tend to be related to things like processor count. The more stuff you run inside your database, the more they make from you.</p>\n\n<p>But I get the impression you're actually more concerned with performance, which isn't really the preserve of unit testing at all. Unit tests are supposed to be fairly atomic and are intended to check behaviour rather than performance. And in that case you're almost certainly going to need production-class loads in order to check query plans.</p>\n\n<p>I think you need a different class of testing environment. I'd suggest a copy of production as the simplest, assuming security isn't an issue. Then for each candidate release, you start with the previous version, migrate using your release procedures (which will give those a good testing as a side-effect) and run your timings.</p>\n\n<p>Something like that.</p>\n"
},
{
"answer_id": 12410,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>We unit test the C# code that calls the SPs.<br>\nWe have build scripts, creating clean test databases.<br>\nAnd bigger ones we attach and detach during test fixture.<br>\nThese tests could take hours, but I think it`s worth it.</p>\n"
},
{
"answer_id": 12457,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>We use <a href=\"http://blogs.ent0.com/files/default.aspx\" rel=\"nofollow noreferrer\">DataFresh</a> to rollback changes between each test, then testing sprocs is relatively easy.</p>\n\n<p>What is still lacking is code coverage tools.</p>\n"
},
{
"answer_id": 12472,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>But I get the impression you're actually more concerned with performance, which isn't really the preserve of unit testing at all. Unit tests are supposed to be fairly atomic and are intended to check behaviour rather than performance. And in that case you're almost certainly going to need production-class loads in order to check query plans.</p>\n</blockquote>\n\n<p>I think there are two quite distinct testing areas here: the performance, and the actual logic of the stored procedures. </p>\n\n<p>I gave the example of testing the db performance in the past and, thankfully, we have reached a point where the performance is good enough. </p>\n\n<p>I completely agree that the situation with all the business logic in the database is a bad one, but it's something that we've inherited from before most of our developers joined the company. </p>\n\n<p>However, we're now adopting the web services model for our new features, and we've been trying to avoid stored procedures as much as possible, keeping the logic in the C# code and firing SQLCommands at the database (although linq would now be the preferred method). There is still some use of the existing SPs which was why I was thinking about retrospectively unit testing them. </p>\n"
},
{
"answer_id": 12483,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>One option to re-factor the code (I'll admit a ugly hack) would be to generate it via CPP (the C preprocessor) M4 (never tried it) or the like. I have a project that is doing just that and it is actually mostly workable.</p>\n\n<p>The only case I think that might be valid for is 1) as an alternative to KLOC+ stored procedures and 2) and this is my cases, when the point of the project is to see how far (into insane) you can push a technology. </p>\n"
},
{
"answer_id": 12508,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": false,
"text": "<p>The key to testing stored procedures is writing a script that populates a blank database with data that is planned out in advance to result in consistent behavior when the stored procedures are called.</p>\n\n<p>I have to put my vote in for heavily favoring stored procedures and placing your business logic where I (and most DBAs) think it belongs, in the database.</p>\n\n<p>I know that we as software engineers want beautifully refactored code, written in our favorite language, to contain all of our important logic, but the realities of performance in high volume systems, and the critical nature of data integrity, require us to make some compromises. Sql code can be ugly, repetitive, and hard to test, but I can't imagine the difficulty of tuning a database without having complete control over the design of the queries.</p>\n\n<p>I am often forced to completely redesign queries, to include changes to the data model, to get things to run in an acceptable amount of time. With stored procedures, I can assure that the changes will be transparent to the caller, since a stored procedure provides such excellent encapsulation.</p>\n"
},
{
"answer_id": 12639,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 0,
"selected": false,
"text": "<p>Oh, boy. sprocs don't lend themselves to (automated) unit testing. I sort-of \"unit test\" my complex sprocs by writing tests in t-sql batch files and hand checking the output of the print statements and the results. </p>\n"
},
{
"answer_id": 14033,
"author": "Bernard Dy",
"author_id": 1577,
"author_profile": "https://Stackoverflow.com/users/1577",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with unit testing any kind of data-related programming is that you have to have a reliable set of test data to start with. A lot also depends on the complexity of the stored proc and what it does. It would be very hard to automate unit testing for a very complex procedure that modified many tables.</p>\n\n<p>Some of the other posters have noted some simple ways to automate manually testing them, and also some tools you can use with SQL Server. On the Oracle side, PL/SQL guru Steven Feuerstein worked on a free unit testing tool for PL/SQL stored procedures called utPLSQL. </p>\n\n<p>However, he dropped that effort and then went commercial with Quest's Code Tester for PL/SQL. Quest offers a free downloadable trial version. I'm on the verge of trying it out; my understanding is that it is good at taking care of the overhead in setting up a testing framework so that you can focus on just the tests themselves, and it keeps the tests so you can reuse them in regression testing, one of the great benefits of test-driven-development. In addition, it is supposed to be good at more than just checking an output variable and does have provision for validating data changes, but I still have to take a closer look myself. I thought this info might be of value for Oracle users.</p>\n"
},
{
"answer_id": 14390,
"author": "Craig",
"author_id": 1073,
"author_profile": "https://Stackoverflow.com/users/1073",
"pm_score": 2,
"selected": false,
"text": "<p>You can also try <a href=\"http://msdn.microsoft.com/en-gb/vsts2008/products/bb933747.aspx\" rel=\"nofollow noreferrer\">Visual Studio for Database Professionals</a>. It's mainly about change management but also has tools for generating test data and unit tests. </p>\n\n<p>It's pretty expensive tho.</p>\n"
},
{
"answer_id": 25204,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 5,
"selected": true,
"text": "<p>I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db. </p>\n\n<p>This felt better than the usual \"run a script to setup my test db, then after the tests run do a cleanup of the junk/test data\". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of \"everything in the db needs to be 'just so' before I run these tests\".</p>\n\n<p><strong>Here is a snippet of the abstract base class used for data access</strong></p>\n\n<pre><code>Public MustInherit Class Repository(Of T As Class)\n Implements IRepository(Of T)\n\n Private mConnectionString As String = ConfigurationManager.ConnectionStrings(\"Northwind.ConnectionString\").ConnectionString\n Private mConnection As IDbConnection\n Private mTransaction As IDbTransaction\n\n Public Sub New()\n mConnection = Nothing\n mTransaction = Nothing\n End Sub\n\n Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)\n mConnection = connection\n mTransaction = transaction\n End Sub\n\n Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)\n\n Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader\n Dim entityList As List(Of T)\n If Not mConnection Is Nothing Then\n Using cmd As SqlCommand = mConnection.CreateCommand()\n cmd.Transaction = mTransaction\n cmd.CommandType = Parameter.Type\n cmd.CommandText = Parameter.Text\n If Not Parameter.Items Is Nothing Then\n For Each param As SqlParameter In Parameter.Items\n cmd.Parameters.Add(param)\n Next\n End If\n entityList = BuildEntity(cmd)\n If Not entityList Is Nothing Then\n Return entityList\n End If\n End Using\n Else\n Using conn As SqlConnection = New SqlConnection(mConnectionString)\n Using cmd As SqlCommand = conn.CreateCommand()\n cmd.CommandType = Parameter.Type\n cmd.CommandText = Parameter.Text\n If Not Parameter.Items Is Nothing Then\n For Each param As SqlParameter In Parameter.Items\n cmd.Parameters.Add(param)\n Next\n End If\n conn.Open()\n entityList = BuildEntity(cmd)\n If Not entityList Is Nothing Then\n Return entityList\n End If\n End Using\n End Using\n End If\n\n Return Nothing\n End Function\nEnd Class\n</code></pre>\n\n<p><strong>next you will see a sample data access class using the above base to get a list of products</strong></p>\n\n<pre><code>Public Class ProductRepository\n Inherits Repository(Of Product)\n Implements IProductRepository\n\n Private mCache As IHttpCache\n\n 'This const is what you will use in your app\n Public Sub New(ByVal cache As IHttpCache)\n MyBase.New()\n mCache = cache\n End Sub\n\n 'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test\n Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)\n MyBase.New(connection, transaction)\n mCache = cache\n End Sub\n\n Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts\n Dim Parameter As New Parameter()\n Parameter.Type = CommandType.StoredProcedure\n Parameter.Text = \"spGetProducts\"\n Dim productList As List(Of Product)\n productList = MyBase.ExecuteReader(Parameter)\n Return productList\n End Function\n\n 'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object\n Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)\n Dim productList As New List(Of Product)\n Using reader As SqlDataReader = cmd.ExecuteReader()\n Dim product As Product\n While reader.Read()\n product = New Product()\n product.ID = reader(\"ProductID\")\n product.SupplierID = reader(\"SupplierID\")\n product.CategoryID = reader(\"CategoryID\")\n product.ProductName = reader(\"ProductName\")\n product.QuantityPerUnit = reader(\"QuantityPerUnit\")\n product.UnitPrice = reader(\"UnitPrice\")\n product.UnitsInStock = reader(\"UnitsInStock\")\n product.UnitsOnOrder = reader(\"UnitsOnOrder\")\n product.ReorderLevel = reader(\"ReorderLevel\")\n productList.Add(product)\n End While\n If productList.Count > 0 Then\n Return productList\n End If\n End Using\n Return Nothing\n End Function\nEnd Class\n</code></pre>\n\n<p><strong>And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis</strong></p>\n\n<p><strong>below is the simple testing base class I used</strong></p>\n\n<pre><code>Imports System.Configuration\nImports System.Data\nImports System.Data.SqlClient\nImports Microsoft.VisualStudio.TestTools.UnitTesting\n\nPublic MustInherit Class TransactionFixture\n Protected mConnection As IDbConnection\n Protected mTransaction As IDbTransaction\n Private mConnectionString As String = ConfigurationManager.ConnectionStrings(\"Northwind.ConnectionString\").ConnectionString\n\n <TestInitialize()> _\n Public Sub CreateConnectionAndBeginTran()\n mConnection = New SqlConnection(mConnectionString)\n mConnection.Open()\n mTransaction = mConnection.BeginTransaction()\n End Sub\n\n <TestCleanup()> _\n Public Sub RollbackTranAndCloseConnection()\n mTransaction.Rollback()\n mTransaction.Dispose()\n mConnection.Close()\n mConnection.Dispose()\n End Sub\nEnd Class\n</code></pre>\n\n<p><strong>and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly</strong></p>\n\n<p><strong>I know this doesn't test the \"spGetProducts\" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs</strong></p>\n\n<pre><code>Imports SampleApplication.Library\nImports System.Collections.Generic\nImports Microsoft.VisualStudio.TestTools.UnitTesting\n\n<TestClass()> _\nPublic Class ProductRepositoryUnitTest\n Inherits TransactionFixture\n\n Private mRepository As ProductRepository\n\n <TestMethod()> _\n Public Sub Should-Insert-Update-And-Delete-Product()\n mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)\n '** Create a test product to manipulate throughout **'\n Dim Product As New Product()\n Product.ProductName = \"TestProduct\"\n Product.SupplierID = 1\n Product.CategoryID = 2\n Product.QuantityPerUnit = \"10 boxes of stuff\"\n Product.UnitPrice = 14.95\n Product.UnitsInStock = 22\n Product.UnitsOnOrder = 19\n Product.ReorderLevel = 12\n '** Insert the new product object into SQL using your insert sproc **'\n mRepository.InsertProduct(Product)\n '** Select the product object that was just inserted and verify it does exist **'\n '** Using your GetProductById sproc **'\n Dim Product2 As Product = mRepository.GetProduct(Product.ID)\n Assert.AreEqual(\"TestProduct\", Product2.ProductName)\n Assert.AreEqual(1, Product2.SupplierID)\n Assert.AreEqual(2, Product2.CategoryID)\n Assert.AreEqual(\"10 boxes of stuff\", Product2.QuantityPerUnit)\n Assert.AreEqual(14.95, Product2.UnitPrice)\n Assert.AreEqual(22, Product2.UnitsInStock)\n Assert.AreEqual(19, Product2.UnitsOnOrder)\n Assert.AreEqual(12, Product2.ReorderLevel)\n '** Update the product object **'\n Product2.ProductName = \"UpdatedTestProduct\"\n Product2.SupplierID = 2\n Product2.CategoryID = 1\n Product2.QuantityPerUnit = \"a box of stuff\"\n Product2.UnitPrice = 16.95\n Product2.UnitsInStock = 10\n Product2.UnitsOnOrder = 20\n Product2.ReorderLevel = 8\n mRepository.UpdateProduct(Product2) '**using your update sproc\n '** Select the product object that was just updated to verify it completed **'\n Dim Product3 As Product = mRepository.GetProduct(Product2.ID)\n Assert.AreEqual(\"UpdatedTestProduct\", Product2.ProductName)\n Assert.AreEqual(2, Product2.SupplierID)\n Assert.AreEqual(1, Product2.CategoryID)\n Assert.AreEqual(\"a box of stuff\", Product2.QuantityPerUnit)\n Assert.AreEqual(16.95, Product2.UnitPrice)\n Assert.AreEqual(10, Product2.UnitsInStock)\n Assert.AreEqual(20, Product2.UnitsOnOrder)\n Assert.AreEqual(8, Product2.ReorderLevel)\n '** Delete the product and verify it does not exist **'\n mRepository.DeleteProduct(Product3.ID)\n '** The above will use your delete product by id sproc **'\n Dim Product4 As Product = mRepository.GetProduct(Product3.ID)\n Assert.AreEqual(Nothing, Product4)\n End Sub\n\nEnd Class\n</code></pre>\n\n<p>I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;)</p>\n"
},
{
"answer_id": 161060,
"author": "thvo",
"author_id": 13041,
"author_profile": "https://Stackoverflow.com/users/13041",
"pm_score": 2,
"selected": false,
"text": "<p>I'm in the exact same situation as the original poster. It comes down to performance versus testability. My bias is towards testability (make it work, make it right, make it fast), which suggests keeping business logic out of the database. Databases not only lack the testing frameworks, code factoring constructs, and code analysis and navigation tools found in languages like Java, but highly factored database code is also slow (where highly factored Java code is not). </p>\n\n<p>However, I do recognize the power of database set processing. When used appropriately, SQL can do some incredibly powerful stuff with very little code. So, I'm ok with some set-based logic living in the database even though I will still do everything I can to unit test it.</p>\n\n<p>On a related note, it seems that very long and procedural database code is often a symptom of something else, and I think such code can be converted to testable code without incurring a performance hit. The theory is that such code often represents batch processes that periodically process large amounts of data. If these batch processes were to be converted into smaller chunks of real-time business logic that runs whenever the input data is changed, this logic could be run on the middle-tier (where it can be tested) without taking a performance hit (since the work is done in small chunks in real-time). As a side-effect, this also eliminates the long feedback-loops of batch process error handling. Of course this approach won't work in all cases, but it may work in some. Also, if there is tons of such untestable batch processing database code in your system, the road to salvation may be long and arduous. YMMV.</p>\n"
},
{
"answer_id": 161851,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<p>Good question. </p>\n\n<p>I have similar problems, and I have taken the path of least resistance (for me, anyway). </p>\n\n<p>There are a bunch of other solutions, which others have mentionned. Many of them are better / more pure / more appropriate for others. </p>\n\n<p>I was already using Testdriven.NET/MbUnit to test my C#, so I simply added tests to each project to call the stored procedures used by that app. </p>\n\n<p>I know, I know. This sounds terrible, but what I need is to get off the ground with <em>some</em> testing, and go from there. This approach means that although my coverage is low I am testing some stored procs at the same time as I am testing the code which will be calling them. There is some logic to this. </p>\n"
},
{
"answer_id": 800759,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 1,
"selected": false,
"text": "<p>I do poor man's unit testing. If I'm lazy, the test is just a couple of valid invocations with potentially problematic parameter values.</p>\n\n<pre><code>/*\n\n--setup\nDeclare @foo int Set @foo = (Select top 1 foo from mytable)\n\n--test\nexecute wish_I_had_more_Tests @foo\n\n--look at rowcounts/look for errors\nIf @@rowcount=1 Print 'Ok!' Else Print 'Nokay!'\n\n--Teardown\nDelete from mytable where foo = @foo\n*/\ncreate procedure wish_I_had_more_Tests\nas\nselect....\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078/"
] | We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off.
But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users.
What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.
We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.
So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?
The second part of my questions is whether unit testing would be/is easier with linq?
I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all) | I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db.
This felt better than the usual "run a script to setup my test db, then after the tests run do a cleanup of the junk/test data". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of "everything in the db needs to be 'just so' before I run these tests".
**Here is a snippet of the abstract base class used for data access**
```
Public MustInherit Class Repository(Of T As Class)
Implements IRepository(Of T)
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
Private mConnection As IDbConnection
Private mTransaction As IDbTransaction
Public Sub New()
mConnection = Nothing
mTransaction = Nothing
End Sub
Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
mConnection = connection
mTransaction = transaction
End Sub
Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)
Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader
Dim entityList As List(Of T)
If Not mConnection Is Nothing Then
Using cmd As SqlCommand = mConnection.CreateCommand()
cmd.Transaction = mTransaction
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
Else
Using conn As SqlConnection = New SqlConnection(mConnectionString)
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
conn.Open()
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
End Using
End If
Return Nothing
End Function
End Class
```
**next you will see a sample data access class using the above base to get a list of products**
```
Public Class ProductRepository
Inherits Repository(Of Product)
Implements IProductRepository
Private mCache As IHttpCache
'This const is what you will use in your app
Public Sub New(ByVal cache As IHttpCache)
MyBase.New()
mCache = cache
End Sub
'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test
Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
MyBase.New(connection, transaction)
mCache = cache
End Sub
Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts
Dim Parameter As New Parameter()
Parameter.Type = CommandType.StoredProcedure
Parameter.Text = "spGetProducts"
Dim productList As List(Of Product)
productList = MyBase.ExecuteReader(Parameter)
Return productList
End Function
'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object
Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)
Dim productList As New List(Of Product)
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = reader("ProductID")
product.SupplierID = reader("SupplierID")
product.CategoryID = reader("CategoryID")
product.ProductName = reader("ProductName")
product.QuantityPerUnit = reader("QuantityPerUnit")
product.UnitPrice = reader("UnitPrice")
product.UnitsInStock = reader("UnitsInStock")
product.UnitsOnOrder = reader("UnitsOnOrder")
product.ReorderLevel = reader("ReorderLevel")
productList.Add(product)
End While
If productList.Count > 0 Then
Return productList
End If
End Using
Return Nothing
End Function
End Class
```
**And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis**
**below is the simple testing base class I used**
```
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Public MustInherit Class TransactionFixture
Protected mConnection As IDbConnection
Protected mTransaction As IDbTransaction
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
<TestInitialize()> _
Public Sub CreateConnectionAndBeginTran()
mConnection = New SqlConnection(mConnectionString)
mConnection.Open()
mTransaction = mConnection.BeginTransaction()
End Sub
<TestCleanup()> _
Public Sub RollbackTranAndCloseConnection()
mTransaction.Rollback()
mTransaction.Dispose()
mConnection.Close()
mConnection.Dispose()
End Sub
End Class
```
**and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly**
**I know this doesn't test the "spGetProducts" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs**
```
Imports SampleApplication.Library
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> _
Public Class ProductRepositoryUnitTest
Inherits TransactionFixture
Private mRepository As ProductRepository
<TestMethod()> _
Public Sub Should-Insert-Update-And-Delete-Product()
mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)
'** Create a test product to manipulate throughout **'
Dim Product As New Product()
Product.ProductName = "TestProduct"
Product.SupplierID = 1
Product.CategoryID = 2
Product.QuantityPerUnit = "10 boxes of stuff"
Product.UnitPrice = 14.95
Product.UnitsInStock = 22
Product.UnitsOnOrder = 19
Product.ReorderLevel = 12
'** Insert the new product object into SQL using your insert sproc **'
mRepository.InsertProduct(Product)
'** Select the product object that was just inserted and verify it does exist **'
'** Using your GetProductById sproc **'
Dim Product2 As Product = mRepository.GetProduct(Product.ID)
Assert.AreEqual("TestProduct", Product2.ProductName)
Assert.AreEqual(1, Product2.SupplierID)
Assert.AreEqual(2, Product2.CategoryID)
Assert.AreEqual("10 boxes of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(14.95, Product2.UnitPrice)
Assert.AreEqual(22, Product2.UnitsInStock)
Assert.AreEqual(19, Product2.UnitsOnOrder)
Assert.AreEqual(12, Product2.ReorderLevel)
'** Update the product object **'
Product2.ProductName = "UpdatedTestProduct"
Product2.SupplierID = 2
Product2.CategoryID = 1
Product2.QuantityPerUnit = "a box of stuff"
Product2.UnitPrice = 16.95
Product2.UnitsInStock = 10
Product2.UnitsOnOrder = 20
Product2.ReorderLevel = 8
mRepository.UpdateProduct(Product2) '**using your update sproc
'** Select the product object that was just updated to verify it completed **'
Dim Product3 As Product = mRepository.GetProduct(Product2.ID)
Assert.AreEqual("UpdatedTestProduct", Product2.ProductName)
Assert.AreEqual(2, Product2.SupplierID)
Assert.AreEqual(1, Product2.CategoryID)
Assert.AreEqual("a box of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(16.95, Product2.UnitPrice)
Assert.AreEqual(10, Product2.UnitsInStock)
Assert.AreEqual(20, Product2.UnitsOnOrder)
Assert.AreEqual(8, Product2.ReorderLevel)
'** Delete the product and verify it does not exist **'
mRepository.DeleteProduct(Product3.ID)
'** The above will use your delete product by id sproc **'
Dim Product4 As Product = mRepository.GetProduct(Product3.ID)
Assert.AreEqual(Nothing, Product4)
End Sub
End Class
```
I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;) |
12,385 | <p>How would you attach a propertychanged callback to a property that is inherited? Like such:</p>
<pre><code>class A {
DependencyProperty prop;
}
class B : A {
//...
prop.AddListener(PropertyChangeCallback);
}
</code></pre>
| [
{
"answer_id": 12436,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": true,
"text": "<p>(edited to remove recommendation to use DependencyPropertyDescriptor, which is not available in Silverlight)</p>\n\n<p><a href=\"http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/\" rel=\"nofollow noreferrer\">PropertyDescriptor AddValueChanged Alternative</a></p>\n"
},
{
"answer_id": 12637,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried a two way data binding between the two dependency properties?</p>\n"
},
{
"answer_id": 258575,
"author": "Daniel Crenna",
"author_id": 18440,
"author_profile": "https://Stackoverflow.com/users/18440",
"pm_score": 0,
"selected": false,
"text": "<p>@MojoFilter,</p>\n\n<p>Jon's last suggestion link will give you what you're looking for: it uses weak references to register listening to changes by wrapping properties in a new object. Scroll to the bottom of \"PropertyDescriptor AddValueChanged Alternative\". You'll have to change the Binding code around a bit since BindingOperations doesn't exist.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | How would you attach a propertychanged callback to a property that is inherited? Like such:
```
class A {
DependencyProperty prop;
}
class B : A {
//...
prop.AddListener(PropertyChangeCallback);
}
``` | (edited to remove recommendation to use DependencyPropertyDescriptor, which is not available in Silverlight)
[PropertyDescriptor AddValueChanged Alternative](http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/) |
12,428 | <p>Once I have my renamed files I need to add them to my project's wiki page. This is a fairly repetitive manual task, so I guess I could script it but I don't know where to start.</p>
<p>The process is:</p>
<pre><code>Got to appropriate page on the wiki
for each team member (DeveloperA, DeveloperB, DeveloperC)
{
for each of two files ('*_current.jpg', '*_lastweek.jpg')
{
Select 'Attach' link on page
Select the 'manage' link next to the file to be updated
Click 'Browse' button
Browse to the relevant file (which has the same name as the previous version)
Click 'Upload file' button
}
}
</code></pre>
<p>Not necessarily looking for the full solution as I'd like to give it a go myself.</p>
<p>Where to begin? What language could I use to do this and how difficult would it be?</p>
| [
{
"answer_id": 12439,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 1,
"selected": false,
"text": "<p>If you're writing in C#, the WebClient classes might be a good place to start. I bet people could give more specific advice if you mentioned which wiki platform you are using, and whether it requires authentication, though.</p>\n\n<p>I'd probably start by downloading fiddler and watching the http requests from doing it manually. Then you could use some simple scripts and regexes to build your http requests for automating the process.</p>\n\n<p>Of course, if your wildly lucky, your wiki would have a backend simple enough that you could just plug them into its db directly. :)</p>\n"
},
{
"answer_id": 12444,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 1,
"selected": false,
"text": "<p>You might find <a href=\"http://services.alphaworks.ibm.com/coscripter\" rel=\"nofollow noreferrer\">CoScripter</a> useful -- it's a Firefox extension that allows you to automate tasks you perform on websites. I'm not certain how you'd integrate this with the list of files you're changing on your local system, but it can certainly handle the file uploading through a web form.</p>\n\n<p>Better bet is probably using <a href=\"http://curl.haxx.se/\" rel=\"nofollow noreferrer\">cURL</a> or a similar HTTP library with your programming language of choice. If you're on *nix, you can use the <a href=\"http://curl.haxx.se/docs/manpage.html\" rel=\"nofollow noreferrer\">cURL commandline program</a> inside your shell script to get this done fairly easily. (Like @jsight said you will need to analyze the actual forms you're using on the webpage, using Fiddler or just looking at the form elements and re-creating the POST through cURL.)</p>\n"
},
{
"answer_id": 12485,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<p>Check if the wiki you mean to talk to supports <a href=\"http://www.jspwiki.org/wiki/WikiRPCInterface2\" rel=\"nofollow noreferrer\">XMLRPC</a>, because if it does it should be a snap. I wrote a tool called <a href=\"http://trac.gargoyle.ath.cx/trac/wiki/WikiUp\" rel=\"nofollow noreferrer\">WikiUp</a> to solve a similar problem (updating a delineated section on a wiki page). </p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849/"
] | Once I have my renamed files I need to add them to my project's wiki page. This is a fairly repetitive manual task, so I guess I could script it but I don't know where to start.
The process is:
```
Got to appropriate page on the wiki
for each team member (DeveloperA, DeveloperB, DeveloperC)
{
for each of two files ('*_current.jpg', '*_lastweek.jpg')
{
Select 'Attach' link on page
Select the 'manage' link next to the file to be updated
Click 'Browse' button
Browse to the relevant file (which has the same name as the previous version)
Click 'Upload file' button
}
}
```
Not necessarily looking for the full solution as I'd like to give it a go myself.
Where to begin? What language could I use to do this and how difficult would it be? | Check if the wiki you mean to talk to supports [XMLRPC](http://www.jspwiki.org/wiki/WikiRPCInterface2), because if it does it should be a snap. I wrote a tool called [WikiUp](http://trac.gargoyle.ath.cx/trac/wiki/WikiUp) to solve a similar problem (updating a delineated section on a wiki page). |
12,482 | <p>I have CruiseControl.NET Version 1.4 set up on my development server. Whenever a developer checks in code, it makes a compile. </p>
<p>Now we're at a place where we can start giving our application to the testers. We'd like to use ClickOnce to distribute the application, with the idea being that when a tester goes to test the application, they have the latest build. </p>
<p>I can't find a way to make that happen with CruiseControl.NET. We're using MSBUILD to perform the builds.</p>
| [
{
"answer_id": 12497,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": -1,
"selected": false,
"text": "<p>You want to use the ClickOnce manifest generation tasks in msbuild. The process is a little long winded, so I am just going to point you to a couple of links. Here is the <a href=\"http://msdn.microsoft.com/en-us/library/6wc2ccdc.aspx\" rel=\"nofollow noreferrer\">reference on msdn</a> and a <a href=\"http://windowsclient.net/articles/ClickOnce_MsBuild.aspx\" rel=\"nofollow noreferrer\">sample article</a> to hopefully get you started.</p>\n"
},
{
"answer_id": 12512,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 5,
"selected": false,
"text": "<p>We've done this and can give you some pointers to start.</p>\n\n<p>2 things you should be aware of:</p>\n\n<ul>\n<li>MSBuild can generate the necessary deployment files for you.</li>\n<li>MSBuild won't deploy the files to the FTP or UNC share. You'll need a separate step for this.</li>\n</ul>\n\n<p>To use MSBuild to generate the ClickOnce manifests, here's the command you'll need to issue:</p>\n\n<pre><code>msbuild /target:publish /p:Configuration=Release /p:Platform=AnyCPU; \"c:\\yourProject.csproj\"\n</code></pre>\n\n<p>That will tell MSBuild to build your project and generate ClickOnce deployment files inside the <em>bin\\Release\\YourProject.publish</em> directory.</p>\n\n<p>All that's left is to copy those files to the FTP/UNC share/wherever, and you're all set.</p>\n\n<p>You can tell CruiseControl.NET to build using those MSBuild parameters.</p>\n\n<p>You'll then need a CruiseControl.NET build task to take the generated deployment files and copy them to the FTP or UNC share. We use a custom little C# console program for this, but you could just as easily use a Powershell script.</p>\n"
},
{
"answer_id": 103741,
"author": "fnCzar",
"author_id": 15053,
"author_profile": "https://Stackoverflow.com/users/15053",
"pm_score": 2,
"selected": false,
"text": "<p>I remember doing this last year for a ClickOnce project I was working on. I remember it taking me forever to figure out but here it is. What I wanted my scripts to do was to generate a different installer that pointed to our dev env and a different one for prod. Not only that but i needed it to inject the right versioning information so the existing clients would 'realize' there is a new version out there which is the whole point of clickOnce. \nIn this script you have to replace with your own server names etc. The trick is to save the publish.htm and project.publish file and inject the new version number based on the version that is provided to you by CC.NET.</p>\n\n<p>Here is what my build script looked like:</p>\n\n<pre><code><target name=\"deployProd\">\n <exec program=\"<framework_dir>\\msbuild.exe\" commandline=\"<project>/<project>.csproj /property:Configuration=PublishProd /property:ApplicationVersion=${build.label}.*;PublishUrl=\\\\<prod_location>\\binups$\\;InstallUrl=\\\\<prod_location>\\binups$\\;UpdateUrl=\\\\<prod_location>\\binups$\\;BootstrapperComponentsUrl=\\\\<prod_location>\\prereqs$\\ /target:publish\"/>\n\n <copy todir=\"<project>\\bin\\PublishProd\\<project>.publish\">\n\n <fileset basedir=\".\">\n <include name=\"publish.htm\"/>\n </fileset>\n\n <filterchain>\n <replacetokens>\n <token key=\"CURRENT_VERSION\" value=\"${build.label}\"/>\n </replacetokens>\n </filterchain>\n </copy>\n\n</target>\n</code></pre>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 462529,
"author": "proudgeekdad",
"author_id": 702,
"author_profile": "https://Stackoverflow.com/users/702",
"pm_score": 5,
"selected": true,
"text": "<p>Thanks for all the help. The final solution we implemented took a bit from every answer.</p>\n\n<p>We found it easier to handle working with multiple environments using simple batch files. I'm not suggesting this is the best way to do this, but for our given scenario and requirements, this worked well. Supplement \"Project\" with your project name and \"Environment\" with your environment name (dev, test, stage, production, whatever).</p>\n\n<p>Here is the tasks area of our \"ccnet.config\" file.</p>\n\n<p></p>\n\n<pre><code><!-- override settings -->\n<exec>\n <executable>F:\\Source\\Project\\Environment\\CruiseControl\\CopySettings.bat</executable>\n</exec>\n\n<!-- compile -->\n<msbuild>\n <executable>C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe</executable>\n <workingDirectory>F:\\Source\\Project\\Environment\\</workingDirectory>\n <projectFile>Project.sln</projectFile>\n <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>\n <targets>Rebuild</targets>\n <timeout>0</timeout>\n <logger>ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll</logger>\n</msbuild>\n\n<!-- clickonce publish -->\n<exec>\n <executable>F:\\Source\\Project\\Environment\\CruiseControl\\Publish.bat</executable>\n</exec>\n</code></pre>\n\n<p></p>\n\n<p>The first thing you will notice is that CopySettings.bat runs. This copies specific settings for the environment, such as database connections.</p>\n\n<p>Next, the standard MSBUILD task runs. Any compile errors are caught here and handled as normal.</p>\n\n<p>The last thing to execute is Publish.bat. This actually performs a MSBUILD \"rebuild\" again from command line, and parameters from CruiseControl are automatically passed in and built. Next, MSBUILD is called for the \"publish\" target. The exact same parameters are given to the publish as the rebuild was issued. This keeps the build numbers in sync. Also, our executables are named differently (i.e. - ProjectDev and ProjectTest). We end up with different version numbers and names, and this allows ClickOnce to do its thing.</p>\n\n<p>The last part of Publish.bat copies the actual files to their new homes. We don't use the publish.htm as all our users are on the network, we just give them a shortcut to the manifest file on their desktop and they can click and always be running the correct executable with a version number that ties out in CruiseControl.</p>\n\n<p>Here is CopySettings.bat</p>\n\n<pre><code>XCOPY \"F:\\Source\\Project\\Environment\\CruiseControl\\Project\\app.config\" \"F:\\Source\\Project\\Environment\\Project\" /Y /I /R\nXCOPY \"F:\\Source\\Project\\Environment\\CruiseControl\\Project\\My Project\\Settings.Designer.vb\" \"F:\\Source\\Project\\Environment\\Project\\My Project\" /Y /I /R\nXCOPY \"F:\\Source\\Project\\Environment\\CruiseControl\\Project\\My Project\\Settings.settings\" \"F:\\Source\\Project\\Environment\\Project\\My Project\" /Y /I /R\n</code></pre>\n\n<p>And lastly, here is Publish.bat</p>\n\n<pre><code>C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe /target:rebuild \"F:\\Source\\Project\\Environment\\Project\\Project.vbproj\" /property:ApplicationRevision=%CCNetLabel% /property:AssemblyName=\"ProjectEnvironment\" /property:PublishUrl=\"\\\\Server\\bin\\Project\\Environment\\\\\"\nC:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe /target:publish \"F:\\Source\\Project\\Environment\\Project\\Project.vbproj\" /property:ApplicationVersion=\"1.0.0.%CCNetLabel%\" /property:AssemblyVersion=\"1.0.0.%CCNetLabel%\" /property:AssemblyName=\"ProjectEnvironment\" \n\nXCOPY \"F:\\Source\\Project\\Environment\\Project\\bin\\Debug\\app.publish\" \"F:\\Binary\\Project\\Environment\" /Y /I\nXCOPY \"F:\\Source\\Project\\Environment\\Project\\bin\\Debug\\app.publish\\Application Files\" \"F:\\Binary\\Project\\Environment\\Application Files\" /Y /I /S\n</code></pre>\n\n<p>Like I said, it's probably not done the way that CruiseControl and MSBUILD developers had intended things to work, but it does work. If you need to get this working yesterday, it might be the solution you're looking for. Good luck!</p>\n"
},
{
"answer_id": 714157,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Just be able passing the ${CCNetLabel} in the CCNET.config msbuild task would be a great improvement.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/702/"
] | I have CruiseControl.NET Version 1.4 set up on my development server. Whenever a developer checks in code, it makes a compile.
Now we're at a place where we can start giving our application to the testers. We'd like to use ClickOnce to distribute the application, with the idea being that when a tester goes to test the application, they have the latest build.
I can't find a way to make that happen with CruiseControl.NET. We're using MSBUILD to perform the builds. | Thanks for all the help. The final solution we implemented took a bit from every answer.
We found it easier to handle working with multiple environments using simple batch files. I'm not suggesting this is the best way to do this, but for our given scenario and requirements, this worked well. Supplement "Project" with your project name and "Environment" with your environment name (dev, test, stage, production, whatever).
Here is the tasks area of our "ccnet.config" file.
```
<!-- override settings -->
<exec>
<executable>F:\Source\Project\Environment\CruiseControl\CopySettings.bat</executable>
</exec>
<!-- compile -->
<msbuild>
<executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
<workingDirectory>F:\Source\Project\Environment\</workingDirectory>
<projectFile>Project.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
<targets>Rebuild</targets>
<timeout>0</timeout>
<logger>ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll</logger>
</msbuild>
<!-- clickonce publish -->
<exec>
<executable>F:\Source\Project\Environment\CruiseControl\Publish.bat</executable>
</exec>
```
The first thing you will notice is that CopySettings.bat runs. This copies specific settings for the environment, such as database connections.
Next, the standard MSBUILD task runs. Any compile errors are caught here and handled as normal.
The last thing to execute is Publish.bat. This actually performs a MSBUILD "rebuild" again from command line, and parameters from CruiseControl are automatically passed in and built. Next, MSBUILD is called for the "publish" target. The exact same parameters are given to the publish as the rebuild was issued. This keeps the build numbers in sync. Also, our executables are named differently (i.e. - ProjectDev and ProjectTest). We end up with different version numbers and names, and this allows ClickOnce to do its thing.
The last part of Publish.bat copies the actual files to their new homes. We don't use the publish.htm as all our users are on the network, we just give them a shortcut to the manifest file on their desktop and they can click and always be running the correct executable with a version number that ties out in CruiseControl.
Here is CopySettings.bat
```
XCOPY "F:\Source\Project\Environment\CruiseControl\Project\app.config" "F:\Source\Project\Environment\Project" /Y /I /R
XCOPY "F:\Source\Project\Environment\CruiseControl\Project\My Project\Settings.Designer.vb" "F:\Source\Project\Environment\Project\My Project" /Y /I /R
XCOPY "F:\Source\Project\Environment\CruiseControl\Project\My Project\Settings.settings" "F:\Source\Project\Environment\Project\My Project" /Y /I /R
```
And lastly, here is Publish.bat
```
C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /target:rebuild "F:\Source\Project\Environment\Project\Project.vbproj" /property:ApplicationRevision=%CCNetLabel% /property:AssemblyName="ProjectEnvironment" /property:PublishUrl="\\Server\bin\Project\Environment\\"
C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /target:publish "F:\Source\Project\Environment\Project\Project.vbproj" /property:ApplicationVersion="1.0.0.%CCNetLabel%" /property:AssemblyVersion="1.0.0.%CCNetLabel%" /property:AssemblyName="ProjectEnvironment"
XCOPY "F:\Source\Project\Environment\Project\bin\Debug\app.publish" "F:\Binary\Project\Environment" /Y /I
XCOPY "F:\Source\Project\Environment\Project\bin\Debug\app.publish\Application Files" "F:\Binary\Project\Environment\Application Files" /Y /I /S
```
Like I said, it's probably not done the way that CruiseControl and MSBUILD developers had intended things to work, but it does work. If you need to get this working yesterday, it might be the solution you're looking for. Good luck! |
12,489 | <p>How do you scan a directory for folders and files in C? It needs to be cross-platform.</p>
| [
{
"answer_id": 12500,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 3,
"selected": false,
"text": "<p>opendir/readdir are POSIX. If POSIX is not enough for the portability you want to achieve, check <a href=\"http://apr.apache.org/docs/apr/1.3/group__apr__dir.html\" rel=\"noreferrer\">Apache Portable Runtime</a></p>\n"
},
{
"answer_id": 12506,
"author": "Clayton",
"author_id": 1449,
"author_profile": "https://Stackoverflow.com/users/1449",
"pm_score": 6,
"selected": false,
"text": "<p>The following POSIX program will print the names of the files in the current directory:</p>\n<pre><code>#define _XOPEN_SOURCE 700\n#include <stdio.h>\n#include <sys/types.h>\n#include <dirent.h>\n\nint main (void)\n{\n DIR *dp;\n struct dirent *ep; \n dp = opendir ("./");\n if (dp != NULL)\n {\n while ((ep = readdir (dp)) != NULL)\n puts (ep->d_name);\n \n (void) closedir (dp);\n return 0;\n }\n else\n {\n perror ("Couldn't open the directory");\n return -1;\n }\n}\n</code></pre>\n<p>Credit: <a href=\"http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html</a></p>\n<p>Tested in Ubuntu 16.04.</p>\n"
},
{
"answer_id": 12507,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": false,
"text": "<p>The strict answer is \"you can't\", as the very concept of a folder is not truly cross-platform.</p>\n\n<p>On MS platforms you can use _findfirst, _findnext and _findclose for a 'c' sort of feel, and FindFirstFile and FindNextFile for the underlying Win32 calls.</p>\n\n<p>Here's the C-FAQ answer: </p>\n\n<p><a href=\"http://c-faq.com/osdep/readdir.html\" rel=\"noreferrer\">http://c-faq.com/osdep/readdir.html</a></p>\n"
},
{
"answer_id": 12513,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 4,
"selected": false,
"text": "<p>There is no standard C (or C++) way to enumerate files in a directory.</p>\n\n<p>Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.</p>\n"
},
{
"answer_id": 12694,
"author": "Pascal",
"author_id": 1311,
"author_profile": "https://Stackoverflow.com/users/1311",
"pm_score": 2,
"selected": false,
"text": "<p>Directory listing varies greatly according to the OS/platform under consideration. This is because, various Operating systems using their own internal system calls to achieve this.</p>\n\n<p>A solution to this problem would be to look for a library which masks this problem and portable. Unfortunately, there is no solution that works on all platforms flawlessly. </p>\n\n<p>On POSIX compatible systems, you could use the library to achieve this using the code posted by Clayton (which is referenced originally from the Advanced Programming under UNIX book by W. Richard Stevens). this solution will work under *NIX systems and would also work on Windows if you have Cygwin installed.</p>\n\n<p>Alternatively, you could write a code to detect the underlying OS and then call the appropriate directory listing function which would hold the 'proper' way of listing the directory structure under that OS.</p>\n"
},
{
"answer_id": 87178,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://library.gnome.org/devel/glib/stable/\" rel=\"noreferrer\">GLib</a> is a portability/utility library for C which forms the basis of the GTK+ graphical toolkit. It can be used as a standalone library.</p>\n\n<p>It contains portable wrappers for managing directories. See <a href=\"http://library.gnome.org/devel/glib/stable/glib-File-Utilities.html\" rel=\"noreferrer\">Glib File Utilities</a> documentation for details.</p>\n\n<p>Personally, I wouldn't even consider writing large amounts of C-code without something like GLib behind me. Portability is one thing, but it's also nice to get data structures, thread helpers, events, mainloops etc. for free </p>\n\n<p>Jikes, I'm almost starting to sound like a sales guy :) (don't worry, glib is open source (LGPL) and I'm not affiliated with it in any way)</p>\n"
},
{
"answer_id": 6805559,
"author": "user541686",
"author_id": 541686,
"author_profile": "https://Stackoverflow.com/users/541686",
"pm_score": 2,
"selected": false,
"text": "<p>The most <em>similar</em> method to <code>readdir</code> is probably using the little-known <a href=\"http://msdn.microsoft.com/en-us/library/kda16keh.aspx\" rel=\"nofollow\"><code>_find</code> family of functions</a>.</p>\n"
},
{
"answer_id": 14679104,
"author": "congusbongus",
"author_id": 2038264,
"author_profile": "https://Stackoverflow.com/users/2038264",
"pm_score": 4,
"selected": false,
"text": "<p>I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:</p>\n\n<p><a href=\"https://github.com/cxong/tinydir\">https://github.com/cxong/tinydir</a></p>\n\n<pre><code>tinydir_dir dir;\ntinydir_open(&dir, \"/path/to/dir\");\n\nwhile (dir.has_next)\n{\n tinydir_file file;\n tinydir_readfile(&dir, &file);\n\n printf(\"%s\", file.name);\n if (file.is_dir)\n {\n printf(\"/\");\n }\n printf(\"\\n\");\n\n tinydir_next(&dir);\n}\n\ntinydir_close(&dir);\n</code></pre>\n"
},
{
"answer_id": 47539331,
"author": "Howard Wu",
"author_id": 833657,
"author_profile": "https://Stackoverflow.com/users/833657",
"pm_score": 0,
"selected": false,
"text": "<p>You can find the sample code on the <a href=\"https://en.wikibooks.org/wiki/C_Programming/dirent.h\" rel=\"nofollow noreferrer\">wikibooks link</a></p>\n\n<pre><code>/**************************************************************\n * A simpler and shorter implementation of ls(1)\n * ls(1) is very similar to the DIR command on DOS and Windows.\n **************************************************************/\n#include <stdio.h>\n#include <dirent.h>\n\nint listdir(const char *path) \n{\n struct dirent *entry;\n DIR *dp;\n\n dp = opendir(path);\n if (dp == NULL) \n {\n perror(\"opendir\");\n return -1;\n }\n\n while((entry = readdir(dp)))\n puts(entry->d_name);\n\n closedir(dp);\n return 0;\n}\n\nint main(int argc, char **argv) {\n int counter = 1;\n\n if (argc == 1)\n listdir(\".\");\n\n while (++counter <= argc) {\n printf(\"\\nListing %s...\\n\", argv[counter-1]);\n listdir(argv[counter-1]);\n }\n\n return 0;\n}\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How do you scan a directory for folders and files in C? It needs to be cross-platform. | The following POSIX program will print the names of the files in the current directory:
```
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while ((ep = readdir (dp)) != NULL)
puts (ep->d_name);
(void) closedir (dp);
return 0;
}
else
{
perror ("Couldn't open the directory");
return -1;
}
}
```
Credit: <http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html>
Tested in Ubuntu 16.04. |
12,516 | <p>This morning, I was reading <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">Steve Yegge's: When Polymorphism Fails</a>, when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.</p>
<blockquote>
<p>As an example of polymorphism in
action, let's look at the classic
"eval" interview question, which (as
far as I know) was brought to Amazon
by Ron Braunstein. The question is
quite a rich one, as it manages to
probe a wide variety of important
skills: OOP design, recursion, binary
trees, polymorphism and runtime
typing, general coding skills, and (if
you want to make it extra hard)
parsing theory.</p>
<p>At some point, the candidate hopefully
realizes that you can represent an
arithmetic expression as a binary
tree, assuming you're only using
binary operators such as "+", "-",
"*", "/". The leaf nodes are all
numbers, and the internal nodes are
all operators. Evaluating the
expression means walking the tree. If
the candidate doesn't realize this,
you can gently lead them to it, or if
necessary, just tell them.</p>
<p>Even if you tell them, it's still an
interesting problem.</p>
<p>The first half of the question, which
some people (whose names I will
protect to my dying breath, but their
initials are Willie Lewis) feel is a
Job Requirement If You Want To Call
Yourself A Developer And Work At
Amazon, is actually kinda hard. The
question is: how do you go from an
arithmetic expression (e.g. in a
string) such as "2 + (2)" to an
expression tree. We may have an ADJ
challenge on this question at some
point.</p>
<p>The second half is: let's say this is
a 2-person project, and your partner,
who we'll call "Willie", is
responsible for transforming the
string expression into a tree. You get
the easy part: you need to decide what
classes Willie is to construct the
tree with. You can do it in any
language, but make sure you pick one,
or Willie will hand you assembly
language. If he's feeling ornery, it
will be for a processor that is no
longer manufactured in production.</p>
<p>You'd be amazed at how many candidates
boff this one.</p>
<p>I won't give away the answer, but a
Standard Bad Solution involves the use
of a switch or case statment (or just
good old-fashioned cascaded-ifs). A
Slightly Better Solution involves
using a table of function pointers,
and the Probably Best Solution
involves using polymorphism. I
encourage you to work through it
sometime. Fun stuff!</p>
</blockquote>
<p>So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism? </p>
<p>Feel free to tackle one, two, or all three.</p>
<p>[update: title modified to better match what most of the answers have been.]</p>
| [
{
"answer_id": 12538,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 2,
"selected": false,
"text": "<p>String Tokenizer + LL(1) Parser will give you an expression tree... the polymorphism way might involve an abstract Arithmetic class with an \"evaluate(a,b)\" function, which is overridden for each of the operators involved (Addition, Subtraction etc) to return the appropriate value, and the tree contains Integers and Arithmetic operators, which can be evaluated by a post(?)-order traversal of the tree.</p>\n"
},
{
"answer_id": 12630,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 0,
"selected": false,
"text": "<p>should use a functional language imo. Trees are harder to represent and manipulate in OO languages.</p>\n"
},
{
"answer_id": 12655,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Or maybe this is the real question:\n how can you represent (2) as a BST?\n That is the part that is tripping me\n up.</p>\n</blockquote>\n\n<p>Recursion.</p>\n"
},
{
"answer_id": 12674,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>The problem, I think, is that we need to parse perentheses, and yet they are not a binary operator? Should we take (2) as a single token, that evaluates to 2?</p>\n</blockquote>\n\n<p>The parens don't need to show up in the expression tree, but they do affect its shape. E.g., the tree for (1+2)+3 is different from 1+(2+3):</p>\n\n<pre><code> +\n / \\\n + 3\n / \\\n1 2\n</code></pre>\n\n<p>versus</p>\n\n<pre><code> +\n / \\\n 1 +\n / \\\n 2 3\n</code></pre>\n\n<p>The parentheses are a \"hint\" to the parser (e.g., per superjoe30, to \"recursively descend\")</p>\n"
},
{
"answer_id": 12688,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 1,
"selected": false,
"text": "<p>Re: Justin</p>\n\n<p>I think the tree would look something like this:</p>\n\n<pre><code> +\n / \\\n2 ( )\n |\n 2\n</code></pre>\n\n<p>Basically, you'd have an \"eval\" node, that just evaluates the tree below it. That would then be optimized out to just being:</p>\n\n<pre><code> +\n / \\\n2 2\n</code></pre>\n\n<p>In this case the parens aren't required and don't add anything. They don't add anything logically, so they'd just go away.</p>\n"
},
{
"answer_id": 12812,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 2,
"selected": false,
"text": "<p>This gets into parsing/compiler theory, which is kind of a rabbit hole... <a href=\"http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools\" rel=\"nofollow noreferrer\">The Dragon Book</a> is the standard text for compiler construction, and takes this to extremes. In this particular case, you want to construct a <a href=\"http://en.wikipedia.org/wiki/Context-free_grammar#Example_3\" rel=\"nofollow noreferrer\">context-free grammar</a> for basic arithmetic, then use that grammar to parse out an <a href=\"http://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"nofollow noreferrer\">abstract syntax tree</a>. You can then iterate over the tree, reducing it from the bottom up (it's at this point you'd apply the polymorphism/function pointers/switch statement to reduce the tree).</p>\n\n<p>I've found <a href=\"http://cg.scs.carleton.ca/~morin/teaching/3002/#notes\" rel=\"nofollow noreferrer\">these notes</a> to be incredibly helpful in compiler and parsing theory.</p>\n"
},
{
"answer_id": 12861,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Polymorphic Tree Walking</strong>, Python version</p>\n\n<pre><code>#!/usr/bin/python\n\nclass Node:\n \"\"\"base class, you should not process one of these\"\"\"\n def process(self):\n raise('you should not be processing a node')\n\nclass BinaryNode(Node):\n \"\"\"base class for binary nodes\"\"\"\n def __init__(self, _left, _right):\n self.left = _left\n self.right = _right\n def process(self):\n raise('you should not be processing a binarynode')\n\nclass Plus(BinaryNode):\n def process(self):\n return self.left.process() + self.right.process()\n\nclass Minus(BinaryNode):\n def process(self):\n return self.left.process() - self.right.process()\n\nclass Mul(BinaryNode):\n def process(self):\n return self.left.process() * self.right.process()\n\nclass Div(BinaryNode):\n def process(self):\n return self.left.process() / self.right.process()\n\nclass Num(Node):\n def __init__(self, _value):\n self.value = _value\n def process(self):\n return self.value\n\ndef demo(n):\n print n.process()\n\ndemo(Num(2)) # 2\ndemo(Plus(Num(2),Num(5))) # 2 + 3\ndemo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2)\n</code></pre>\n\n<p>The tests are just building up the binary trees by using constructors.</p>\n\n<p>program structure:</p>\n\n<p>abstract base class: Node</p>\n\n<ul>\n<li>all Nodes inherit from this class</li>\n</ul>\n\n<p>abstract base class: BinaryNode</p>\n\n<ul>\n<li>all binary operators inherit from this class</li>\n<li>process method does the work of evaluting the expression and returning the result</li>\n</ul>\n\n<p>binary operator classes: Plus,Minus,Mul,Div</p>\n\n<ul>\n<li>two child nodes, one each for left side and right side subexpressions</li>\n</ul>\n\n<p>number class: Num</p>\n\n<ul>\n<li>holds a leaf-node numeric value, e.g. 17 or 42</li>\n</ul>\n"
},
{
"answer_id": 12876,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 0,
"selected": false,
"text": "<p>@Justin:</p>\n\n<p>Look at my note on representing the nodes. If you use that scheme, then</p>\n\n<pre><code>2 + (2)\n</code></pre>\n\n<p>can be represented as</p>\n\n<pre><code> .\n / \\\n 2 ( )\n |\n 2\n</code></pre>\n"
},
{
"answer_id": 12893,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>Representing the Nodes</p>\n\n<p>If we want to include parentheses, we need 5 kinds of nodes:</p>\n\n<ul>\n<li><p>the binary nodes: Add Minus Mul Div<br>these have two children, a left and right side</p>\n\n<pre><code> +\n / \\\nnode node\n</code></pre></li>\n<li><p>a node to hold a value: Val<br>no children nodes, just a numeric value</p></li>\n<li><p>a node to keep track of the parens: Paren<br>a single child node for the subexpression</p>\n\n<pre><code> ( )\n |\n node\n</code></pre></li>\n</ul>\n\n<p>For a polymorphic solution, we need to have this kind of class relationship:</p>\n\n<ul>\n<li>Node</li>\n<li>BinaryNode : inherit from Node</li>\n<li>Plus : inherit from Binary Node</li>\n<li>Minus : inherit from Binary Node</li>\n<li>Mul : inherit from Binary Node</li>\n<li>Div : inherit from Binary Node</li>\n<li>Value : inherit from Node</li>\n<li>Paren : inherit from node</li>\n</ul>\n\n<p>There is a virtual function for all nodes called eval(). If you call that function, it will return the value of that subexpression.</p>\n"
},
{
"answer_id": 13643,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I won't give away the answer, but a\n Standard Bad Solution involves the use\n of a switch or case statment (or just\n good old-fashioned cascaded-ifs). A\n Slightly Better Solution involves\n using a table of function pointers,\n and the Probably Best Solution\n involves using polymorphism. </p>\n</blockquote>\n\n<p>The last twenty years of evolution in interpreters can be seen as going the other way - polymorphism (eg naive Smalltalk metacircular interpreters) to function pointers (naive lisp implementations, threaded code, C++) to switch (naive byte code interpreters), and then onwards to JITs and so on - which either require very big classes, or (in singly polymorphic languages) double-dispatch, which reduces the polymorphism to a type-case, and you're back at stage one. What definition of 'best' is in use here?</p>\n\n<p>For simple stuff a polymorphic solution is OK - <a href=\"http://www.tincancamera.com/examples/java/expressions/ExpressionParser.java.txt\" rel=\"nofollow noreferrer\">here's one I made earlier</a>, but either stack and bytecode/switch or exploiting the runtime's compiler is usually better if you're, say, plotting a function with a few thousand data points.</p>\n"
},
{
"answer_id": 20499,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 1,
"selected": false,
"text": "<p>I think the question is about how to write a parser, not the evaluator. Or rather, how to create the expression tree from a string.</p>\n\n<p>Case statements that return a base class don't exactly count.</p>\n\n<p>The basic structure of a \"polymorphic\" solution (which is another way of saying, I don't care what you build this with, I just want to extend it with rewriting the least amount of code possible) is deserializing an object hierarchy from a stream with a (dynamic) set of known types.</p>\n\n<p>The crux of the implementation of the polymorphic solution is to have a way to create an expression object from a pattern matcher, likely recursive. I.e., map a BNF or similar syntax to an object factory.</p>\n"
},
{
"answer_id": 26225,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 0,
"selected": false,
"text": "<p>As people have been mentioning previously, when you use expression trees parens are not necessary. The order of operations becomes trivial and obvious when you're looking at an expression tree. The parens are hints to the parser.</p>\n\n<p>While the accepted answer is the solution to one half of the problem, the other half - actually parsing the expression - is still unsolved. Typically, these sorts of problems can be solved using a <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"nofollow noreferrer\">recursive descent parser</a>. Writing such a parser is often a fun exercise, but most <a href=\"http://www.antlr.org/\" rel=\"nofollow noreferrer\">modern tools for language parsing</a> will abstract that away for you. </p>\n\n<p>The parser is also <strong>significantly</strong> harder if you allow floating point numbers in your string. I had to create a DFA to accept floating point numbers in C -- it was a very painstaking and detailed task. Remember, valid floating points include: 10, 10., 10.123, 9.876e-5, 1.0f, .025, etc. I assume some dispensation from this (in favor of simplicty and brevity) was made in the interview.</p>\n"
},
{
"answer_id": 277786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Hm... I don't think you can write a top-down parser for this without backtracking, so it has to be some sort of a shift-reduce parser. LR(1) or even LALR will of course work just fine with the following (ad-hoc) language definition:</p>\n\n<p>Start -> E1 <br>\nE1 -> E1+E1 | E1-E1 <br>\nE1 -> E2*E2 | E2/E2 | E2 <br>\nE2 -> <em>number</em> | (E1)</p>\n\n<p>Separating it out into E1 and E2 is necessary to maintain the precedence of * and / over + and -.</p>\n\n<p>But this is how I would do it if I had to write the parser by hand:</p>\n\n<ul>\n<li>Two stacks, one storing nodes of the tree as operands and one storing operators</li>\n<li>Read the input left to right, make leaf nodes of the numbers and push them into the operand stack.</li>\n<li>If you have >= 2 operands on the stack, pop 2, combine them with the topmost operator in the operator stack and push this structure back to the operand tree, <em>unless</em></li>\n<li>The next operator has higher precedence that the one currently on top of the stack.</li>\n</ul>\n\n<p>This leaves us the problem of handling brackets. One elegant (I thought) solution is to store the precedence of each operator as a number in a variable. So initially, </p>\n\n<ul>\n<li>int plus, minus = 1;</li>\n<li>int mul, div = 2;</li>\n</ul>\n\n<p>Now every time you see a a left bracket increment all these variables by 2, and every time you see a right bracket, decrement all the variables by 2.</p>\n\n<p>This will ensure that the + in 3*(4+5) has higher precedence than the *, and 3*4 will not be pushed onto the stack. Instead it will wait for 5, push 4+5, then push 3*(4+5).</p>\n"
},
{
"answer_id": 307536,
"author": "xxxxxxx",
"author_id": 34051,
"author_profile": "https://Stackoverflow.com/users/34051",
"pm_score": 0,
"selected": false,
"text": "<p>I've written such a parser with some basic techniques like \n<a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\" rel=\"nofollow noreferrer\">Infix -> RPN</a> and \n<a href=\"http://en.wikipedia.org/wiki/Shunting_yard_algorithm\" rel=\"nofollow noreferrer\">Shunting Yard</a> and \n<a href=\"http://en.wikipedia.org/wiki/Tree_traversal\" rel=\"nofollow noreferrer\">Tree Traversals</a>.\n<a href=\"http://perlhobby.googlecode.com/svn/trunk/parser_v0.1/\" rel=\"nofollow noreferrer\">Here is the implementation I've came up with</a>.<br>\nIt's written in C++ and compiles on both Linux and Windows.<br>\nAny suggestions/questions are welcomed.</p>\n\n<blockquote>\n <p>So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as \"2 + (2)\" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism? </p>\n</blockquote>\n\n<p>This is interesting,but I don't think this belongs to the realm of object-oriented programming...I think it has more to do with <a href=\"ftp://ftp.cs.vu.nl/pub/dick/PTAPG_1st_Edition/BookBody.pdf\" rel=\"nofollow noreferrer\">parsing techniques</a>.</p>\n"
},
{
"answer_id": 474783,
"author": "Wilfred Knievel",
"author_id": 6124,
"author_profile": "https://Stackoverflow.com/users/6124",
"pm_score": 0,
"selected": false,
"text": "<p>I've kind of chucked this c# console app together as a bit of a proof of concept. Have a feeling it could be a lot better (that switch statement in GetNode is kind of clunky (it's there coz I hit a blank trying to map a class name to an operator)). Any suggestions on how it could be improved very welcome.</p>\n\n<pre><code>using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n string expression = \"(((3.5 * 4.5) / (1 + 2)) + 5)\";\n Console.WriteLine(string.Format(\"{0} = {1}\", expression, new Expression.ExpressionTree(expression).Value));\n Console.WriteLine(\"\\nShow's over folks, press a key to exit\");\n Console.ReadKey(false);\n }\n}\n\nnamespace Expression\n{\n // -------------------------------------------------------\n\n abstract class NodeBase\n {\n public abstract double Value { get; }\n }\n\n // -------------------------------------------------------\n\n class ValueNode : NodeBase\n {\n public ValueNode(double value)\n {\n _double = value;\n }\n\n private double _double;\n public override double Value\n {\n get\n {\n return _double;\n }\n }\n }\n\n // -------------------------------------------------------\n\n abstract class ExpressionNodeBase : NodeBase\n {\n protected NodeBase GetNode(string expression)\n {\n // Remove parenthesis\n expression = RemoveParenthesis(expression);\n\n // Is expression just a number?\n double value = 0;\n if (double.TryParse(expression, out value))\n {\n return new ValueNode(value);\n }\n else\n {\n int pos = ParseExpression(expression);\n if (pos > 0)\n {\n string leftExpression = expression.Substring(0, pos - 1).Trim();\n string rightExpression = expression.Substring(pos).Trim();\n\n switch (expression.Substring(pos - 1, 1))\n {\n case \"+\":\n return new Add(leftExpression, rightExpression);\n case \"-\":\n return new Subtract(leftExpression, rightExpression);\n case \"*\":\n return new Multiply(leftExpression, rightExpression);\n case \"/\":\n return new Divide(leftExpression, rightExpression);\n default:\n throw new Exception(\"Unknown operator\");\n }\n }\n else\n {\n throw new Exception(\"Unable to parse expression\");\n }\n }\n }\n\n private string RemoveParenthesis(string expression)\n {\n if (expression.Contains(\"(\"))\n {\n expression = expression.Trim();\n\n int level = 0;\n int pos = 0;\n\n foreach (char token in expression.ToCharArray())\n {\n pos++;\n switch (token)\n {\n case '(':\n level++;\n break;\n case ')':\n level--;\n break;\n }\n\n if (level == 0)\n {\n break;\n }\n }\n\n if (level == 0 && pos == expression.Length)\n {\n expression = expression.Substring(1, expression.Length - 2);\n expression = RemoveParenthesis(expression);\n }\n }\n return expression;\n }\n\n private int ParseExpression(string expression)\n {\n int winningLevel = 0;\n byte winningTokenWeight = 0;\n int winningPos = 0;\n\n int level = 0;\n int pos = 0;\n\n foreach (char token in expression.ToCharArray())\n {\n pos++;\n\n switch (token)\n {\n case '(':\n level++;\n break;\n case ')':\n level--;\n break;\n }\n\n if (level <= winningLevel)\n {\n if (OperatorWeight(token) > winningTokenWeight)\n {\n winningLevel = level;\n winningTokenWeight = OperatorWeight(token);\n winningPos = pos;\n }\n }\n }\n return winningPos;\n }\n\n private byte OperatorWeight(char value)\n {\n switch (value)\n {\n case '+':\n case '-':\n return 3;\n case '*':\n return 2;\n case '/':\n return 1;\n default:\n return 0;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class ExpressionTree : ExpressionNodeBase\n {\n protected NodeBase _rootNode;\n\n public ExpressionTree(string expression)\n {\n _rootNode = GetNode(expression);\n }\n\n public override double Value\n {\n get\n {\n return _rootNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n abstract class OperatorNodeBase : ExpressionNodeBase\n {\n protected NodeBase _leftNode;\n protected NodeBase _rightNode;\n\n public OperatorNodeBase(string leftExpression, string rightExpression)\n {\n _leftNode = GetNode(leftExpression);\n _rightNode = GetNode(rightExpression);\n\n }\n }\n\n // -------------------------------------------------------\n\n class Add : OperatorNodeBase\n {\n public Add(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value + _rightNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class Subtract : OperatorNodeBase\n {\n public Subtract(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value - _rightNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class Divide : OperatorNodeBase\n {\n public Divide(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value / _rightNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class Multiply : OperatorNodeBase\n {\n public Multiply(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value * _rightNode.Value;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19599052,
"author": "mmierzwa",
"author_id": 2921510,
"author_profile": "https://Stackoverflow.com/users/2921510",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, here is my naive implementation. Sorry, I did not feel to use objects for that one but it is easy to convert. I feel a bit like evil Willy (from Steve's story).</p>\n\n<pre><code>#!/usr/bin/env python\n\n#tree structure [left argument, operator, right argument, priority level]\ntree_root = [None, None, None, None]\n#count of parethesis nesting\nparenthesis_level = 0\n#current node with empty right argument\ncurrent_node = tree_root\n\n#indices in tree_root nodes Left, Operator, Right, PRiority\nL, O, R, PR = 0, 1, 2, 3\n\n#functions that realise operators\ndef sum(a, b):\n return a + b\n\ndef diff(a, b):\n return a - b\n\ndef mul(a, b):\n return a * b\n\ndef div(a, b):\n return a / b\n\n#tree evaluator\ndef process_node(n):\n try:\n len(n)\n except TypeError:\n return n\n left = process_node(n[L])\n right = process_node(n[R])\n return n[O](left, right)\n\n#mapping operators to relevant functions\no2f = {'+': sum, '-': diff, '*': mul, '/': div, '(': None, ')': None}\n\n#converts token to a node in tree\ndef convert_token(t):\n global current_node, tree_root, parenthesis_level\n if t == '(':\n parenthesis_level += 2\n return\n if t == ')':\n parenthesis_level -= 2\n return\n try: #assumption that we have just an integer\n l = int(t)\n except (ValueError, TypeError):\n pass #if not, no problem\n else:\n if tree_root[L] is None: #if it is first number, put it on the left of root node\n tree_root[L] = l\n else: #put on the right of current_node\n current_node[R] = l\n return\n\n priority = (1 if t in '+-' else 2) + parenthesis_level\n\n #if tree_root does not have operator put it there\n if tree_root[O] is None and t in o2f:\n tree_root[O] = o2f[t]\n tree_root[PR] = priority\n return\n\n #if new node has less or equals priority, put it on the top of tree\n if tree_root[PR] >= priority:\n temp = [tree_root, o2f[t], None, priority]\n tree_root = current_node = temp\n return\n\n #starting from root search for a place with higher priority in hierarchy\n current_node = tree_root\n while type(current_node[R]) != type(1) and priority > current_node[R][PR]:\n current_node = current_node[R]\n #insert new node\n temp = [current_node[R], o2f[t], None, priority]\n current_node[R] = temp\n current_node = temp\n\n\n\ndef parse(e):\n token = ''\n for c in e:\n if c <= '9' and c >='0':\n token += c\n continue\n if c == ' ':\n if token != '':\n convert_token(token)\n token = ''\n continue\n if c in o2f:\n if token != '':\n convert_token(token)\n convert_token(c)\n token = ''\n continue\n print \"Unrecognized character:\", c\n if token != '':\n convert_token(token)\n\n\ndef main():\n parse('(((3 * 4) / (1 + 2)) + 5)')\n print tree_root\n print process_node(tree_root)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | This morning, I was reading [Steve Yegge's: When Polymorphism Fails](http://steve.yegge.googlepages.com/when-polymorphism-fails), when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.
>
> As an example of polymorphism in
> action, let's look at the classic
> "eval" interview question, which (as
> far as I know) was brought to Amazon
> by Ron Braunstein. The question is
> quite a rich one, as it manages to
> probe a wide variety of important
> skills: OOP design, recursion, binary
> trees, polymorphism and runtime
> typing, general coding skills, and (if
> you want to make it extra hard)
> parsing theory.
>
>
> At some point, the candidate hopefully
> realizes that you can represent an
> arithmetic expression as a binary
> tree, assuming you're only using
> binary operators such as "+", "-",
> "\*", "/". The leaf nodes are all
> numbers, and the internal nodes are
> all operators. Evaluating the
> expression means walking the tree. If
> the candidate doesn't realize this,
> you can gently lead them to it, or if
> necessary, just tell them.
>
>
> Even if you tell them, it's still an
> interesting problem.
>
>
> The first half of the question, which
> some people (whose names I will
> protect to my dying breath, but their
> initials are Willie Lewis) feel is a
> Job Requirement If You Want To Call
> Yourself A Developer And Work At
> Amazon, is actually kinda hard. The
> question is: how do you go from an
> arithmetic expression (e.g. in a
> string) such as "2 + (2)" to an
> expression tree. We may have an ADJ
> challenge on this question at some
> point.
>
>
> The second half is: let's say this is
> a 2-person project, and your partner,
> who we'll call "Willie", is
> responsible for transforming the
> string expression into a tree. You get
> the easy part: you need to decide what
> classes Willie is to construct the
> tree with. You can do it in any
> language, but make sure you pick one,
> or Willie will hand you assembly
> language. If he's feeling ornery, it
> will be for a processor that is no
> longer manufactured in production.
>
>
> You'd be amazed at how many candidates
> boff this one.
>
>
> I won't give away the answer, but a
> Standard Bad Solution involves the use
> of a switch or case statment (or just
> good old-fashioned cascaded-ifs). A
> Slightly Better Solution involves
> using a table of function pointers,
> and the Probably Best Solution
> involves using polymorphism. I
> encourage you to work through it
> sometime. Fun stuff!
>
>
>
So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism?
Feel free to tackle one, two, or all three.
[update: title modified to better match what most of the answers have been.] | **Polymorphic Tree Walking**, Python version
```
#!/usr/bin/python
class Node:
"""base class, you should not process one of these"""
def process(self):
raise('you should not be processing a node')
class BinaryNode(Node):
"""base class for binary nodes"""
def __init__(self, _left, _right):
self.left = _left
self.right = _right
def process(self):
raise('you should not be processing a binarynode')
class Plus(BinaryNode):
def process(self):
return self.left.process() + self.right.process()
class Minus(BinaryNode):
def process(self):
return self.left.process() - self.right.process()
class Mul(BinaryNode):
def process(self):
return self.left.process() * self.right.process()
class Div(BinaryNode):
def process(self):
return self.left.process() / self.right.process()
class Num(Node):
def __init__(self, _value):
self.value = _value
def process(self):
return self.value
def demo(n):
print n.process()
demo(Num(2)) # 2
demo(Plus(Num(2),Num(5))) # 2 + 3
demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2)
```
The tests are just building up the binary trees by using constructors.
program structure:
abstract base class: Node
* all Nodes inherit from this class
abstract base class: BinaryNode
* all binary operators inherit from this class
* process method does the work of evaluting the expression and returning the result
binary operator classes: Plus,Minus,Mul,Div
* two child nodes, one each for left side and right side subexpressions
number class: Num
* holds a leaf-node numeric value, e.g. 17 or 42 |
12,533 | <p>Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?</p>
<pre><code>select datepart(dw, getdate());
</code></pre>
<p>This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1.</p>
| [
{
"answer_id": 12541,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 0,
"selected": false,
"text": "<p>This is not possible without using the result to select the day yourself. For one thing the textual representation of the day is locale-dependent. For another the returned value depends upon the 'datefirst' setting.</p>\n"
},
{
"answer_id": 12544,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "<p>If you want a localizable solution, just join the result against a table with the names and numbers.</p>\n"
},
{
"answer_id": 12548,
"author": "Erick B",
"author_id": 1373,
"author_profile": "https://Stackoverflow.com/users/1373",
"pm_score": 5,
"selected": true,
"text": "<pre><code>select datename(weekday, getdate());\n</code></pre>\n"
},
{
"answer_id": 12549,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>It actually took me more searching than I thought it would to find this answer. It's funny how you can use a technology for ages and never know about simple functions like this.</p>\n\n<pre><code>select datename(dw, getdate())\n</code></pre>\n\n<p>I'm not sure how localization would work with this function. Getting the name client-side is probably the answer, but it would be nice to do it on the database. Would Sql Server use the collation setting to determine the output for this?</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?
```
select datepart(dw, getdate());
```
This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1. | ```
select datename(weekday, getdate());
``` |
12,565 | <p>In Ruby, what's the difference between <code>{}</code> and <code>[]</code>?</p>
<p><code>{}</code> seems to be used for both code blocks and hashes.</p>
<p>Are <code>[]</code> only for arrays?</p>
<p>The documention isn't very clear.</p>
| [
{
"answer_id": 12575,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 3,
"selected": false,
"text": "<p>Broadly speaking, you're correct. As well as hashes, the general style is that curly braces <code>{}</code> are often used for blocks that can fit all onto one line, instead of using <code>do</code>/<code>end</code> across several lines.</p>\n\n<p>Square brackets <code>[]</code> are used as class methods in lots of Ruby classes, including String, BigNum, Dir and confusingly enough, Hash. So:</p>\n\n<pre><code>Hash[\"key\" => \"value\"]\n</code></pre>\n\n<p>is just as valid as:</p>\n\n<pre><code>{ \"key\" => \"value\" }\n</code></pre>\n"
},
{
"answer_id": 12608,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>a few examples:</p>\n\n<pre><code>[1, 2, 3].class\n# => Array\n\n[1, 2, 3][1]\n# => 2\n\n{ 1 => 2, 3 => 4 }.class\n# => Hash\n\n{ 1 => 2, 3 => 4 }[3]\n# => 4\n\n{ 1 + 2 }.class\n# SyntaxError: compile error, odd number list for Hash\n\nlambda { 1 + 2 }.class\n# => Proc\n\nlambda { 1 + 2 }.call\n# => 3\n</code></pre>\n"
},
{
"answer_id": 13935,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 7,
"selected": true,
"text": "<p>It depends on the context:</p>\n\n<ol>\n<li><p>When on their own, or assigning to a variable, <code>[]</code> creates arrays, and <code>{}</code> creates hashes. e.g.</p>\n\n<pre><code>a = [1,2,3] # an array\nb = {1 => 2} # a hash\n</code></pre></li>\n<li><p><code>[]</code> can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up <code>[]</code> as a method on hashes which is the same as <code>fetch</code>) <br>\nThere is also a convention that it is used as a class method in the same way you might use a <code>static Create</code> method in C# or Java. e.g.</p>\n\n<pre><code>a = {1 => 2} # create a hash for example\nputs a[1] # same as a.fetch(1), will print 2\n\nHash[1,2,3,4] # this is a custom class method which creates a new hash\n</code></pre>\n\n<p>See the Ruby <a href=\"http://www.ruby-doc.org/core-2.0/Hash.html#method-c-5B-5D\" rel=\"noreferrer\">Hash docs</a> for that last example.</p></li>\n<li><p>This is probably the most tricky one -\n<code>{}</code> is also syntax for blocks, but only when passed to a method OUTSIDE the arguments parens.</p>\n\n<p>When you invoke methods without parens, Ruby looks at where you put the commas to figure out where the arguments end (where the parens would have been, had you typed them)</p>\n\n<pre><code>1.upto(2) { puts 'hello' } # it's a block\n1.upto 2 { puts 'hello' } # syntax error, ruby can't figure out where the function args end\n1.upto 2, { puts 'hello' } # the comma means \"argument\", so ruby sees it as a hash - this won't work because puts 'hello' isn't a valid hash\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 80928,
"author": "Evgeny",
"author_id": 11414,
"author_profile": "https://Stackoverflow.com/users/11414",
"pm_score": 2,
"selected": false,
"text": "<p>The square brackets [ ] are used to initialize arrays.\nThe documentation for initializer case of [ ] is in</p>\n\n<pre><code>ri Array::[]\n</code></pre>\n\n<p>The curly brackets { } are used to initialize hashes.\nThe documentation for initializer case of { } is in</p>\n\n<pre><code>ri Hash::[]\n</code></pre>\n\n<p>The square brackets are also commonly used as a method in many core ruby classes, like Array, Hash, String, and others.</p>\n\n<p>You can access a list of all classes that have method \"[ ]\" defined with</p>\n\n<pre><code>ri []\n</code></pre>\n\n<p>most methods also have a \"[ ]=\" method that allows to assign things, for example:</p>\n\n<pre><code>s = \"hello world\"\ns[2] # => 108 is ascii for e\ns[2]=109 # 109 is ascii for m\ns # => \"hemlo world\"\n</code></pre>\n\n<p>Curly brackets can also be used instead of \"do ... end\" on blocks, as \"{ ... }\".</p>\n\n<p>Another case where you can see square brackets or curly brackets used - is in the special initializers where any symbol can be used, like:</p>\n\n<pre><code>%w{ hello world } # => [\"hello\",\"world\"]\n%w[ hello world ] # => [\"hello\",\"world\"]\n%r{ hello world } # => / hello world /\n%r[ hello world ] # => / hello world /\n%q{ hello world } # => \"hello world\"\n%q[ hello world ] # => \"hello world\"\n%q| hello world | # => \"hello world\"\n</code></pre>\n"
},
{
"answer_id": 710327,
"author": "sris",
"author_id": 83996,
"author_profile": "https://Stackoverflow.com/users/83996",
"pm_score": 5,
"selected": false,
"text": "<p>Another, not so obvious, usage of <code>[]</code> is as a synonym for Proc#call and Method#call. This might be a little confusing the first time you encounter it. I guess the rational behind it is that it makes it look more like a normal function call.</p>\n\n<p>E.g.</p>\n\n<pre><code>proc = Proc.new { |what| puts \"Hello, #{what}!\" }\nmeth = method(:print)\n\nproc[\"World\"]\nmeth[\"Hello\",\",\",\" \", \"World!\", \"\\n\"]\n</code></pre>\n"
},
{
"answer_id": 1563105,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 2,
"selected": false,
"text": "<p>Note that you can define the <code>[]</code> method for your own classes:</p>\n\n<pre><code>class A\n def [](position)\n # do something\n end\n\n def @rank.[]= key, val\n # define the instance[a] = b method\n end\n\nend\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470/"
] | In Ruby, what's the difference between `{}` and `[]`?
`{}` seems to be used for both code blocks and hashes.
Are `[]` only for arrays?
The documention isn't very clear. | It depends on the context:
1. When on their own, or assigning to a variable, `[]` creates arrays, and `{}` creates hashes. e.g.
```
a = [1,2,3] # an array
b = {1 => 2} # a hash
```
2. `[]` can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up `[]` as a method on hashes which is the same as `fetch`)
There is also a convention that it is used as a class method in the same way you might use a `static Create` method in C# or Java. e.g.
```
a = {1 => 2} # create a hash for example
puts a[1] # same as a.fetch(1), will print 2
Hash[1,2,3,4] # this is a custom class method which creates a new hash
```
See the Ruby [Hash docs](http://www.ruby-doc.org/core-2.0/Hash.html#method-c-5B-5D) for that last example.
3. This is probably the most tricky one -
`{}` is also syntax for blocks, but only when passed to a method OUTSIDE the arguments parens.
When you invoke methods without parens, Ruby looks at where you put the commas to figure out where the arguments end (where the parens would have been, had you typed them)
```
1.upto(2) { puts 'hello' } # it's a block
1.upto 2 { puts 'hello' } # syntax error, ruby can't figure out where the function args end
1.upto 2, { puts 'hello' } # the comma means "argument", so ruby sees it as a hash - this won't work because puts 'hello' isn't a valid hash
``` |
12,569 | <p>Let's say we have a simple function defined in a pseudo language.</p>
<pre><code>List<Numbers> SortNumbers(List<Numbers> unsorted, bool ascending);
</code></pre>
<p>We pass in an unsorted list of numbers and a boolean specifying ascending or descending sort order. In return, we get a sorted list of numbers.</p>
<p>In my experience, some people are better at capturing boundary conditions than others. The question is, "How do you know when you are 'done' capturing test cases"?</p>
<p>We can start listing cases now and some clever person will undoubtedly think of 'one more' case that isn't covered by any of the previous.</p>
| [
{
"answer_id": 12571,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 4,
"selected": true,
"text": "<p>Don't waste too much time trying to think of <em>every</em> boundry condition. Your tests won't be able to catch <em>every</em> bug first time around. The idea is to have tests that are <em>pretty good</em>, and then each time a bug <em>does</em> surface, write a new test specifically for that bug so that you never hear from it again.</p>\n\n<p>Another note I want to make about code coverage tools. In a language like C# or Java where your have many get/set and similar methods, you should <strong>not</strong> be shooting for 100% coverage. That means you are wasting too much time writing tests for trivial code. You <em>only</em> want 100% coverage on your complex business logic. If your full codebase is closer to 70-80% coverage, you are doing a good job. If your code coverage tool allows multiple coverage metrics, the best one is 'block coverage' which measures coverage of 'basic blocks'. Other types are class and method coverage (which don't give you as much information) and line coverage (which is too fine grain).</p>\n"
},
{
"answer_id": 12573,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>A good code coverage tool really helps.</p>\n\n<p>100% coverage doesn't mean that it definitely is adequately tested, but it's a good indicator.</p>\n\n<p>For .Net NCover's quite good, but is no longer open source.</p>\n\n<hr>\n\n<p>@Mike Stone - \nYeah, perhaps that should have been \"high coverage\" - we aim for 80% minimum, past about 95% it's usually diminishing returns, especially if you have belt 'n' braces code.</p>\n"
},
{
"answer_id": 12583,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>@Keith</p>\n\n<p>I think you nailed it, code coverage is important to look at if you want to see how \"done\" you are, but I think 100% is a bit unrealistic a goal. Striving for 75-90% will give you pretty good coverage without going overboard... don't test for the pure sake of hitting 100%, because at that point you are just wasting your time.</p>\n"
},
{
"answer_id": 13064,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>How do you know when you are 'done' capturing test cases?</p>\n</blockquote>\n<p>You don't.You can't get to 100% except for the most trivial cases. Also 100% coverage (of lines, paths, conditions...) doesn't tell you you've hit all boundary conditions.</p>\n<p>Most importantly, the test cases are not write-and-forget. <strong>Each time you find a bug, write an additional test.</strong> Check it fails with the original program, check it passes with the corrected program and add it to your test set.</p>\n<p>An excerpt from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0471469122\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><em>The Art of Software Testing</em></a> by Glenford J. Myers:</p>\n<ol>\n<li>If an input condition specifies a range of values, write test cases for the ends of the range, and invalid-input test cases for situations just beyond the ends.</li>\n<li>If an input condition specifies a number of values, write test cases for the minimum and maximum number of values and one beneath and beyond these values.</li>\n<li>Use guideline 1 for each output condition.</li>\n<li>Use guideline 2 for each output condition.</li>\n<li>If the input or output of a program is an ordered set focus attention on the first and last elements of the set.</li>\n<li>In addition, use your ingenuity to search for other boundary conditions</li>\n</ol>\n<p>(<em>I've only pasted the bare minimum for copyright reasons.</em>)</p>\n<p>Points 3. and 4. above are very important. People tend to forget boundary conditions for the outputs. 5. is OK. 6. really doesn't help :-)</p>\n<h2>Short exam</h2>\n<p>This is more difficult than it looks. Myers offers this test:</p>\n<blockquote>\n<p>The program reads three integer values from an input dialog. The three values represent the lengths of the sides of a triangle. The program displays a message that states whether the triangle is scalene, isosceles, or equilateral.</p>\n<p>Remember that a scalene triangle is one where no two sides are equal, whereas an isosceles triangle has two equal sides, and an equilateral triangle has three sides of equal length. Moreover, the angles opposite the equal sides in an isosceles triangle also are equal (it also follows that the sides opposite equal angles in a triangle are equal), and all angles in an equilateral triangle are equal.</p>\n</blockquote>\n<p>Write your test cases. How many do you have? Myers asks 14 questions about your test set and reports that highly qualified professional programmes average 7.8 out of a possible 14.</p>\n"
},
{
"answer_id": 137296,
"author": "s_t_e_v_e",
"author_id": 21176,
"author_profile": "https://Stackoverflow.com/users/21176",
"pm_score": 1,
"selected": false,
"text": "<p>From a practical standpoint, I create a list of tests that I believe must pass prior to acceptance. I test these and automate where possible. Based on how much time I've estimated for the task or how much time I've been given, I extend my test coverage to include items that should pass prior to acceptance. Of course, the line between must and should is subjective. After that, I update automated tests as bugs are discovered.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12081/"
] | Let's say we have a simple function defined in a pseudo language.
```
List<Numbers> SortNumbers(List<Numbers> unsorted, bool ascending);
```
We pass in an unsorted list of numbers and a boolean specifying ascending or descending sort order. In return, we get a sorted list of numbers.
In my experience, some people are better at capturing boundary conditions than others. The question is, "How do you know when you are 'done' capturing test cases"?
We can start listing cases now and some clever person will undoubtedly think of 'one more' case that isn't covered by any of the previous. | Don't waste too much time trying to think of *every* boundry condition. Your tests won't be able to catch *every* bug first time around. The idea is to have tests that are *pretty good*, and then each time a bug *does* surface, write a new test specifically for that bug so that you never hear from it again.
Another note I want to make about code coverage tools. In a language like C# or Java where your have many get/set and similar methods, you should **not** be shooting for 100% coverage. That means you are wasting too much time writing tests for trivial code. You *only* want 100% coverage on your complex business logic. If your full codebase is closer to 70-80% coverage, you are doing a good job. If your code coverage tool allows multiple coverage metrics, the best one is 'block coverage' which measures coverage of 'basic blocks'. Other types are class and method coverage (which don't give you as much information) and line coverage (which is too fine grain). |
12,576 | <p>What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?</p>
| [
{
"answer_id": 12579,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 2,
"selected": false,
"text": "<p>There is no magic solution, and attempting to provide generic solutions could well just be a waste of time.</p>\n\n<p>Where are your bottlenecks? For example are your scripts processor/database/memory intensive?</p>\n\n<p>Have you performed any profiling?</p>\n"
},
{
"answer_id": 12580,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Whenever I look at performance problems, I think the best thing to do is time how long your pages take to run, and then look at the slowest ones. When you get these real metrics, you can often improve performance on the slowest ones by orders of magnitude, either by fixing a slow SQL query or perhaps tightening up the code a bit.</p>\n\n<p>This of course requires no new hardware or special software, just a critical eye on the existing code.</p>\n\n<p>That said, this will only work for so long... if you really are getting enough traffic to hit the limits of your hardware, and/or there is some code that is just inherently slow and really required, you will have to look at other possibilities.</p>\n"
},
{
"answer_id": 12584,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": true,
"text": "<p>Profile. Profile. Profile. I'm not sure if there is anything out there for PHP, but it should be simple to write a little tool to insert profiling information in your code. You will want to profile function times and SQL query times.</p>\n\n<p>So where you have a function:</p>\n\n<pre><code>function foo($stuff) {\n ...\n return ...;\n}\n</code></pre>\n\n<p>I would change it to:</p>\n\n<pre><code>function foo($stuff) {\n trace_push_fn('foo');\n ...\n trace_pop_fn('foo');\n return ...;\n}\n</code></pre>\n\n<p>(This is one of those cases where multiple returns in a function become a hinderance.)</p>\n\n<p>And SQL:</p>\n\n<pre><code>function bar($stuff) {\n trace_push_fn('bar');\n\n $query = ...;\n trace_push_sql($query);\n mysql_query($query);\n trace_pop_sql($query);\n\n trace_pop_fn('bar');\n return ...;\n}\n</code></pre>\n\n<p>In the end, you can generate a full trace of the program execution and use all sorts of techniques to identify your bottlenecks.</p>\n"
},
{
"answer_id": 12857,
"author": "Eric Goodwin",
"author_id": 1430,
"author_profile": "https://Stackoverflow.com/users/1430",
"pm_score": 0,
"selected": false,
"text": "<p>I'm responsible for a large reporting system and we track the slowest reports kind of like that. I fire a unique key into the db when the report starts and then when it finishes I can determine how long it took. I'm using the database because that way I can detect when pages timeout (which happens a lot more than I'd like)</p>\n"
},
{
"answer_id": 12859,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 3,
"selected": false,
"text": "<p>One reasonable technique that can easily be pulled off the shelf is caching. A vast amount of time tends to go into generating resources for clients that are common between requests (and even across clients); eliminating this runtime work can lead to dramatic speed increases. You can dump the generated resource (or resource fragment) into a file outside the web tree, and then read it back in when needed. Obviously, some profiling will be needed to ensure this is actually faster than regeneration - forcing the web server back to disk regularly can be detrimental, so the resource really does need to have heavy reuse.</p>\n\n<p>You might also be surprised how much time is spent inside badly written database queries; time common generated queries and see if they can be rewritten. The amount of time spent executing actual PHP code is generally pretty limited, unless you're using some sub-optimal algorithms. </p>\n\n<p>Neither of these are limited to PHP, though some of the PHP \"magicy\" approaches/functions can over-protect one from thinking about these concerns. For example, I recently updated a script that was using array_search to use a binary search over a sorted array, and gained the expected exponential speedup.</p>\n"
},
{
"answer_id": 12868,
"author": "Barrett Conrad",
"author_id": 1227,
"author_profile": "https://Stackoverflow.com/users/1227",
"pm_score": 0,
"selected": false,
"text": "<p>Follow some of the other advice first like profiling and making good resource allocation decisions, e.g. caching. </p>\n\n<p>Also, take into account the performance of outside resources like your database. In MySQL you can check the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/slow-query-log.html\" rel=\"nofollow noreferrer\">slow query log</a> for example. In addition make sure you didn't design your database an forget about it. Optimizing your queries (<a href=\"http://dev.mysql.com/doc/refman/5.0/en/using-explain.html\" rel=\"nofollow noreferrer\">again for MySQL</a>) against real data can pay of big.</p>\n"
},
{
"answer_id": 16348,
"author": "Dave Marshall",
"author_id": 1248,
"author_profile": "https://Stackoverflow.com/users/1248",
"pm_score": 1,
"selected": false,
"text": "<p>The ones I can think of...</p>\n\n<ul>\n<li><p><a href=\"http://hudzilla.org/phpwiki/index.php?title=Get_your_loops_right_first\" rel=\"nofollow noreferrer\">Loop invariants</a> are always a\ngood one to watch.</p></li>\n<li><p>Write E_STRICT and E_NOTICE\ncompliant code, particularly if you\nare logging errors.</p></li>\n<li><p>Avoid the @ operator.</p></li>\n<li><p>Absolute paths for requires and\nincludes.</p></li>\n<li><p>Use strpos, str_replace etc. instead of regular expressions whenever possible.</p></li>\n</ul>\n\n<p>Then there's a bunch of other methods that might work, but probably wont give you much benefit.</p>\n"
},
{
"answer_id": 87954,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 3,
"selected": false,
"text": "<p>Really consider using XDebug profiler: it helps with checking how much a certain function is being executed against what you would have expected.</p>\n\n<p>I try to decrease instructions while improving code readability by replacing logic with array-lookups when appropriate. \nIt's what Jeff Atwood wrote in [The Best Code is No Code At All][1].</p>\n\n<ul>\n<li>Also, avoid loops inside another\nloop, and nested if/else statements.</li>\n<li>Short functions. Sometimes a lot of\ncode does not need to be executed\nwhen the result-value is already\nknown. </li>\n<li><p>Unnecessary testing:</p>\n\n<blockquote>\n <p>if (count($array) === 0) return;</p>\n</blockquote>\n\n<p>can also be written as:</p>\n\n<blockquote>\n <p>if (! $array) return;</p>\n</blockquote>\n\n<p>Another function-call eliminated!</p>\n\n<p>[1]: <a href=\"http://www.codinghorror.com/blog/archives/000878.html\" rel=\"noreferrer\">http://www.codinghorror.com/blog/archives/000878.html</a>\"The Best Code is No Code At All\"</p></li>\n</ul>\n"
},
{
"answer_id": 88051,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>including files is slow, and requiring them is even slower. If you use __autoload for including every class then that will add up. for example.</p>\n\n<p>I'm always a bit wary of trying to be too clever in terms of code optimisation, if it sacrifices code clairty. If you need to make code obscure to make it fast, would it not be cheaper to upgrade hardwear instead of wasting your time trying to tweak code? Processor cycles are cheaper than programmer cycles, after all.</p>\n"
},
{
"answer_id": 88443,
"author": "TobiX",
"author_id": 13258,
"author_profile": "https://Stackoverflow.com/users/13258",
"pm_score": 0,
"selected": false,
"text": "<p>Rasmus Lerdorf gave some good tips in his recent presentation \"<a href=\"http://talks.php.net/show/froscon08\" rel=\"nofollow noreferrer\">Simple is Hard</a>\" at FrOSCon '08. If you are using a bytecode cache (and you really should be using one), include path misses hurt a lot, so optimize your require/require_once.</p>\n"
},
{
"answer_id": 18545783,
"author": "0xBAADF00D",
"author_id": 436766,
"author_profile": "https://Stackoverflow.com/users/436766",
"pm_score": 0,
"selected": false,
"text": "<p>You can use profiling tool like xhprof to view what part of your code can by optimized !</p>\n"
},
{
"answer_id": 24074405,
"author": "Dinesh Saini",
"author_id": 1547664,
"author_profile": "https://Stackoverflow.com/users/1547664",
"pm_score": 3,
"selected": false,
"text": "<p>You can optimized the code with two basic things:</p>\n\n<h2>Optimizing PHP associated library and server</h2>\n\n<p>Go through <a href=\"https://www.digitalocean.com/community/articles/how-to-optimize-apache-web-server-performance\">https://www.digitalocean.com/community/articles/how-to-optimize-apache-web-server-performance</a> Or</p>\n\n<p>You can use profiling tool like xhprof to view what part of your code can by optimized and here is the link to follow: <a href=\"http://michaelsanford.com/compiling-xhprof-for-php-5-4/\">http://michaelsanford.com/compiling-xhprof-for-php-5-4/</a></p>\n\n<h2>Optimizing your code using code profiler and code analyzer</h2>\n\n<p>You need to install Netbeans in order to use this plugin. \nHere are the steps you need to follow:</p>\n\n<p>1) Open NetBeans then select option from menu bar Tools > Plugin. Then search plug-in name \"phpcsmd\" in the available plug-in tab and install it from there.</p>\n\n<p>2) Now open the terminal and be there as the super user by typing command \"sudo su\".</p>\n\n<p>3) Install PEAR library (if it is not installed) into your system by running following commands into your terminal</p>\n\n<pre><code>a) wget http://pear.php.net/go-pear.phar\nb) php go-pear.phar\n</code></pre>\n\n<p>As we need this for the installation of further addons.</p>\n\n<p>4) Then run the command</p>\n\n<pre><code>\"pear config-set auto_discover 1\"\n</code></pre>\n\n<p>This will be used to set auto discover the path \"true\" for the required plug-ins. So they get install to the desired location automatically.</p>\n\n<p>5) Then run below command to install PHP code sniffer.</p>\n\n<pre><code>\"pear install --alldeps pear/PHP_CodeSniffer\"\n</code></pre>\n\n<p>6) Now to install the PHP Mess Detector by running following command</p>\n\n<pre><code>\"pear install --alldeps phpmd/PHP_PMD\"\n</code></pre>\n\n<p>If you get the error like \"invalid package name/package file \"phpmd/PHP_PMD\"\" while installing this module. You need to use this \"pear channel-discover pear.phpmd.org\" command to get rid of this error. After this command you can run the above command again to install Mess detector.</p>\n\n<p>7) Now to install the PHP Depend by running following command</p>\n\n<pre><code>\"pear install --alldeps pdepend/PHP_Depend\"\n</code></pre>\n\n<p>8) Now install the PHP Copy Paste Detector by running following command</p>\n\n<pre><code>\"pear install --alldeps phpunit/phpcpd\"\n</code></pre>\n\n<p>9) Then run the command</p>\n\n<pre><code>\"pear config-set auto_discover 0\"\n</code></pre>\n\n<p>This will be used to set auto discover path \"false\".</p>\n\n<p>10) Then open net beans and follow the path Tools>Options>PHP>PHPCSMD</p>\n"
},
{
"answer_id": 47991499,
"author": "Stephan Muggli",
"author_id": 7459505,
"author_profile": "https://Stackoverflow.com/users/7459505",
"pm_score": 0,
"selected": false,
"text": "<p>1) Use latest version of PHP</p>\n\n<p>The core team is working hard on improving the performance of PHP in every version.</p>\n\n<p>2) Use a bytecode cache</p>\n\n<p>Since PHP 5.5 a bytecode cache has been added to PHP named <code>OPcache</code>. Using <code>OPcache</code> can make a huge difference especially since PHP 7. It receives improvements in every PHP version and might even get a <a href=\"https://externals.io/message/95531\" rel=\"nofollow noreferrer\">JIT implementation in the future</a>.</p>\n\n<p>3) Profiling</p>\n\n<p>While developing profiling gives you great insight what exactly is happening. This helps a lot finding bottlenecks in your code.</p>\n\n<p>One of the most used tools is <code>XHProf</code> but is not officially supported anymore and has issues with PHP >= 7. An alternative when you want to profile PHP >= 7 is <a href=\"https://tideways.io/profiler/xhprof-for-php7-php5.6\" rel=\"nofollow noreferrer\"><code>Tideways</code> which is a fork of <code>XHProf</code></a>.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | What can I do to increase the performance/speed of my PHP scripts without installing software on my servers? | Profile. Profile. Profile. I'm not sure if there is anything out there for PHP, but it should be simple to write a little tool to insert profiling information in your code. You will want to profile function times and SQL query times.
So where you have a function:
```
function foo($stuff) {
...
return ...;
}
```
I would change it to:
```
function foo($stuff) {
trace_push_fn('foo');
...
trace_pop_fn('foo');
return ...;
}
```
(This is one of those cases where multiple returns in a function become a hinderance.)
And SQL:
```
function bar($stuff) {
trace_push_fn('bar');
$query = ...;
trace_push_sql($query);
mysql_query($query);
trace_pop_sql($query);
trace_pop_fn('bar');
return ...;
}
```
In the end, you can generate a full trace of the program execution and use all sorts of techniques to identify your bottlenecks. |
12,591 | <p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
| [
{
"answer_id": 13040,
"author": "Michael Twomey",
"author_id": 995,
"author_profile": "https://Stackoverflow.com/users/995",
"pm_score": 1,
"selected": false,
"text": "<p>Can you give an example? According to the <a href=\"http://codespeak.net/lxml/validation.html\" rel=\"nofollow noreferrer\">lxml validation docs</a>, lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs, which covers most cases I can think of.</p>\n\n<pre><code>f = StringIO(\"<!ELEMENT b EMPTY>\")\ndtd = etree.DTD(f)\ndtd = etree.DTD(external_id = \"-//OASIS//DTD DocBook XML V4.2//EN\")\n</code></pre>\n"
},
{
"answer_id": 36219,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 0,
"selected": false,
"text": "<p>It seems that lxml does not expose this libxml2 feature, grepping the source only turns up some #defines for the error handling:</p>\n\n<pre><code>C:\\Dev>grep -ir --include=*.px[id] catalog lxml-2.1.1/src | sed -r \"s/\\s+/ /g\"\nlxml-2.1.1/src/lxml/dtd.pxi: catalog.\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_FROM_CATALOG = 20 # The Catalog module\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_WAR_CATALOG_PI = 93 # 93\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_MISSING_ATTR = 1650\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_ENTRY_BROKEN = 1651 # 1651\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_PREFER_VALUE = 1652 # 1652\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_NOT_CATALOG = 1653 # 1653\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_RECURSION = 1654 # 1654\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG=20\nlxml-2.1.1/src/lxml/xmlerror.pxi:WAR_CATALOG_PI=93\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_MISSING_ATTR=1650\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_ENTRY_BROKEN=1651\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_PREFER_VALUE=1652\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_NOT_CATALOG=1653\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_RECURSION=1654\n</code></pre>\n\n<p>From the <a href=\"http://xmlsoft.org/catalog.html\" rel=\"nofollow noreferrer\">catalog implementation in libxml2 page</a> it seems possible that the 'transparent' handling through installation in /etc/xml/catalog may still work in lxml, but if you need more than that you can always abandon lxml and use the default python bindings, which do expose the catalog functions.</p>\n"
},
{
"answer_id": 8391738,
"author": "Brecht Machiels",
"author_id": 438249,
"author_profile": "https://Stackoverflow.com/users/438249",
"pm_score": 3,
"selected": false,
"text": "<p>You can add the catalog to the <code>XML_CATALOG_FILES</code> environment variable:</p>\n\n<pre><code>os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml'\n</code></pre>\n\n<p>See <a href=\"http://thread.gmane.org/gmane.comp.python.lxml.devel/5907\" rel=\"noreferrer\">this thread</a>. Note that entries in <code>XML_CATALOG_FILES</code> are space-separated URLs. You can use Python's <code>pathname2url</code> and <code>urljoin</code> (with <code>file:</code>) to generate the URL from a pathname.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207/"
] | Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD. | You can add the catalog to the `XML_CATALOG_FILES` environment variable:
```
os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml'
```
See [this thread](http://thread.gmane.org/gmane.comp.python.lxml.devel/5907). Note that entries in `XML_CATALOG_FILES` are space-separated URLs. You can use Python's `pathname2url` and `urljoin` (with `file:`) to generate the URL from a pathname. |
12,592 | <p>Is it possible to write a <code>doctest</code> unit test that will check that an exception is raised?<br />
For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x < 0</code>, how would I write the <code>doctest</code> for that?</p>
| [
{
"answer_id": 12609,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 8,
"selected": true,
"text": "<p>Yes. You can do it. The <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctest module documentation</a> and Wikipedia has an <a href=\"http://en.wikipedia.org/wiki/Doctest#Example_2:_doctests_embedded_in_a_README.txt_file\" rel=\"noreferrer\">example</a> of it.</p>\n\n<pre><code> >>> x\n Traceback (most recent call last):\n ...\n NameError: name 'x' is not defined\n</code></pre>\n"
},
{
"answer_id": 33787471,
"author": "glickind",
"author_id": 5577962,
"author_profile": "https://Stackoverflow.com/users/5577962",
"pm_score": 3,
"selected": false,
"text": "<pre><code>>>> import math\n>>> math.log(-2)\nTraceback (most recent call last):\n ...\nValueError: math domain error\n</code></pre>\n\n<p>ellipsis flag <em># doctest: +ELLIPSIS</em> is not required to use ... in Traceback doctest </p>\n"
},
{
"answer_id": 63539385,
"author": "runsun",
"author_id": 2565778,
"author_profile": "https://Stackoverflow.com/users/2565778",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> scope # doctest: +IGNORE_EXCEPTION_DETAIL\nTraceback (most recent call last):\nNameError: name 'scope' is not defined\n</code></pre>\n<p>Don't know why the previous answers don't have the IGNORE_EXCEPTION_DETAIL. I need this for it to work. Py versioin: 3.7.3.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | Is it possible to write a `doctest` unit test that will check that an exception is raised?
For example, if I have a function `foo(x)` that is supposed to raise an exception if `x < 0`, how would I write the `doctest` for that? | Yes. You can do it. The [doctest module documentation](https://docs.python.org/3/library/doctest.html) and Wikipedia has an [example](http://en.wikipedia.org/wiki/Doctest#Example_2:_doctests_embedded_in_a_README.txt_file) of it.
```
>>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined
``` |
12,613 | <p>I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.</p>
<p>How do I specify a port number when I'm trying to connect to a database?</p>
<p>It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that?</p>
| [
{
"answer_id": 12628,
"author": "Marcel Levy",
"author_id": 676,
"author_profile": "https://Stackoverflow.com/users/676",
"pm_score": 3,
"selected": false,
"text": "<pre><code>(setq sql-mysql-options (list \"-P <port number>\"))\n</code></pre>\n"
},
{
"answer_id": 12658,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": false,
"text": "<p>I found the option using:</p>\n\n<pre><code>M-x customize-group\nSQL\n</code></pre>\n\n<p>That included a setting labeled:</p>\n\n<pre><code>Mysql Options:\n</code></pre>\n\n<p>If you set the option and save it, there will be a new line added to your .emacs:</p>\n\n<pre><code>(custom-set-variables\n '(sql-mysql-options (quote (\"-P ???\"))))\n</code></pre>\n\n<p>(Obviously, you ought to use the actual port number.)</p>\n\n<p>I use XEmacs, so your mileage may vary.</p>\n"
},
{
"answer_id": 12538719,
"author": "Cristian",
"author_id": 680,
"author_profile": "https://Stackoverflow.com/users/680",
"pm_score": 5,
"selected": true,
"text": "<p>After digging through the sql.el file, I found a variable that allows me to specify a port when I try to create a connection.</p>\n<p>This option was added GNU Emacs 24.1.</p>\n<blockquote>\n<p><strong>sql-mysql-login-params</strong></p>\n<p>List of login parameters needed to connect to MySQL.</p>\n</blockquote>\n<p>I added this to my Emacs init file:</p>\n<pre><code>(setq sql-mysql-login-params (append sql-mysql-login-params '(port)))\n</code></pre>\n<p>The default port is 0. If you'd like to set that to the default MySQL port you can customize <code>sql-port</code></p>\n<pre><code>(setq sql-port 3306) ;; default MySQL port\n</code></pre>\n<p>There is a <code>sql-*-login-params</code> variable for all the popular RDMS systems in GNU Emacs 24.1. <code>sql-port</code> is used for both MySQL and PostreSQL</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.
How do I specify a port number when I'm trying to connect to a database?
It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that? | After digging through the sql.el file, I found a variable that allows me to specify a port when I try to create a connection.
This option was added GNU Emacs 24.1.
>
> **sql-mysql-login-params**
>
>
> List of login parameters needed to connect to MySQL.
>
>
>
I added this to my Emacs init file:
```
(setq sql-mysql-login-params (append sql-mysql-login-params '(port)))
```
The default port is 0. If you'd like to set that to the default MySQL port you can customize `sql-port`
```
(setq sql-port 3306) ;; default MySQL port
```
There is a `sql-*-login-params` variable for all the popular RDMS systems in GNU Emacs 24.1. `sql-port` is used for both MySQL and PostreSQL |
12,638 | <p>So basically I'm building an app for my company and it NEEDS to be built using MS Access and it needs to be built on SQL Server.</p>
<p>I've drawn up most of the plans but am having a hard time figuring out a way to handle the auditing system.</p>
<p>Since it is being used internally only and you won't even be able to touch the db from outside the building we are not using a login system as the program will only be used once a user has already logged in to our internal network via Active Directory. Knowing this, we're using <a href="https://stackoverflow.com/questions/9052/is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user">a system to detect automatically the name of the Active Directory user</a> and with their permissions in one of the DB tables, deciding what they can or cannot do.</p>
<p>So the actual audit table will have 3 columns (this design may change but for this question it doesn't matter); who (Active Directory User), when (time of addition/deletion/edit), what (what was changed)</p>
<p>My question is how should I be handling this. Ideally I know I should be using a trigger so that it is impossible for the database to be updated without an audit being logged, however I don't know how I could grab the Active Directory User that way. An alternate would be to code it directly into the Access source so that whenever something changes I run an INSERT statement. Obviously that is flawed because if something happens to Access or the database is touched by something else then it will not log the audit.</p>
<p>Any advice, examples or articles that may help me would be greatly appreciated!</p>
| [
{
"answer_id": 12644,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>How many users of the app will there be? Is there possibility of using windows integrated authentication for SQL authentication?</p>\n\n<p><strong>Updated</strong>: If you can give each user a SQL login (windows integrated) then you can pickup the logged on user using the SYSTEM_USER function. </p>\n"
},
{
"answer_id": 12650,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 2,
"selected": false,
"text": "<p>Does this work for you?</p>\n\n<pre><code>\nselect user_name(),suser_sname()\n</code></pre>\n\n<hr>\n\n<p>Doh! I forgot to escape my code.</p>\n"
},
{
"answer_id": 12653,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>It should be</p>\n\n<pre><code>select user name(),suser sname()\n</code></pre>\n\n<p>replace spaces with underscores</p>\n"
},
{
"answer_id": 12660,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 1,
"selected": false,
"text": "<p>If you specify SSPI in your connection string to Sql, I think your Windows credentials are provided.</p>\n"
},
{
"answer_id": 12672,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>you need to connect with integrated security aka trusted connection see (<a href=\"http://www.connectionstrings.com/?carrier=sqlserver\" rel=\"nofollow noreferrer\">http://www.connectionstrings.com/?carrier=sqlserver</a>)</p>\n"
},
{
"answer_id": 12679,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 1,
"selected": false,
"text": "<p>I tried playing with Access a bit to see if I could find a way for you. I think you can specify a new datasource to your SQL table, and select Windows NT Authentication as your connection type. </p>\n"
},
{
"answer_id": 12687,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 1,
"selected": false,
"text": "<p>Sure :)</p>\n\n<p>There should be a section in Access called \"External Data\" (I'm running a new version of Access, so the menu choice might be different).</p>\n\n<p>Form this there should be an option to specify an ODBC connection.</p>\n\n<p>I get an option to Link to the datasource by creating a linked table.</p>\n\n<p>I then created a Machine datasource. I selected SqlServer from the drop down list. Then when I click Next, I'm prompted for how I want to authenticate.</p>\n"
},
{
"answer_id": 12724,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 1,
"selected": false,
"text": "<pre><code>CREATE TRIGGER testtrigger1\nON testdatatable\nAFTER update\nAS \nBEGIN\n INSERT INTO testtable (datecol,usercol1,usercol2) VALUES (getdate(),user_name(),suser_sname());\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 12731,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, it's working here. I'm seeing my windows credentials when I update my tables. So, I bet we missed a step. Let me put together a 1,2,3 sequence of what I did and maybe we can track down where this is breaking for you.</p>\n\n<hr>\n\n<ol>\n<li>Create a new MSAccess database (empty)</li>\n<li>Click on the tables section</li>\n<li>Select external data</li>\n<li>Pick ODBC database</li>\n<li>Pick Link to the datasource by creating a linked table</li>\n<li>Select Machine datasource</li>\n<li>Pick New...</li>\n<li>System Datasource</li>\n<li>Pick SQL Server from the list and click Next, Finish.</li>\n<li>Give the new datasource a name and description, and select (local) for the server. Click Next.</li>\n<li>Pick \"With Windows NT authentication using the network login ID\". Click Next.</li>\n<li>Check Change the default database to, and pick the DB. Click Next. Click Finish.</li>\n<li>Test the datasource.</li>\n<li>Pick the table that the Trigger is associated with and click OK.</li>\n<li>Open the table in Access and modify one of the entries (the trigger doesn't fire on Insert, just Update)</li>\n<li>Select * from your audit table</li>\n</ol>\n"
},
{
"answer_id": 67920,
"author": "Mark Plumpton",
"author_id": 10422,
"author_profile": "https://Stackoverflow.com/users/10422",
"pm_score": 1,
"selected": false,
"text": "<p>We also have a database system that is used exclusively within the organisation and use Window NT logins. This function returns the current users login name:</p>\n\n<pre><code>CREATE FUNCTION dbo.UserName() RETURNS varchar(50)\nAS\n BEGIN\n RETURN (SELECT nt_username FROM master.dbo.sysprocesses WHERE spid = @@SPID)\n END\n</code></pre>\n\n<p>You can use this function in your triggers.</p>\n"
},
{
"answer_id": 69057,
"author": "Ricardo C",
"author_id": 232589,
"author_profile": "https://Stackoverflow.com/users/232589",
"pm_score": 0,
"selected": false,
"text": "<p>My solution would be not to let Access modify the data with linked tables. </p>\n\n<p>I would only create the UI in Access and create an ADO connection to the server using windows authenticated in the connection string. Compile you Access application as dbe to protect the VB code. </p>\n\n<p>I would not issue SQL statement, but I would call stored procedures to perform the changes in the database, and create the audit log entry in an atomic transaction.</p>\n\n<p>The UI (Access) does not need to know the inner works on the server. All it needs to do is request and update/insert/delete using the stored procedures you would create for this purpose. The server should handle the work.</p>\n\n<p>Retrieve a record set with ADO using a view with the hint NOLOCK implemented in the server and cache this data in Access for local display. Or retrieve a single record and lock only that row for editing. </p>\n\n<p>Using linked tables your users will be locking each other.</p>\n\n<p>With ADO connections you will not have the trouble to set ODBCs on every single client. </p>\n\n<p>Create a table to set the server status. You application will check it before any action. you can use it to close the server to the application in case that you need to perform changes or maintenance.</p>\n\n<p>Access is a great tool. But it should only handle its local data and not be allowed to mess with the precious server.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | So basically I'm building an app for my company and it NEEDS to be built using MS Access and it needs to be built on SQL Server.
I've drawn up most of the plans but am having a hard time figuring out a way to handle the auditing system.
Since it is being used internally only and you won't even be able to touch the db from outside the building we are not using a login system as the program will only be used once a user has already logged in to our internal network via Active Directory. Knowing this, we're using [a system to detect automatically the name of the Active Directory user](https://stackoverflow.com/questions/9052/is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user) and with their permissions in one of the DB tables, deciding what they can or cannot do.
So the actual audit table will have 3 columns (this design may change but for this question it doesn't matter); who (Active Directory User), when (time of addition/deletion/edit), what (what was changed)
My question is how should I be handling this. Ideally I know I should be using a trigger so that it is impossible for the database to be updated without an audit being logged, however I don't know how I could grab the Active Directory User that way. An alternate would be to code it directly into the Access source so that whenever something changes I run an INSERT statement. Obviously that is flawed because if something happens to Access or the database is touched by something else then it will not log the audit.
Any advice, examples or articles that may help me would be greatly appreciated! | Does this work for you?
```
select user_name(),suser_sname()
```
---
Doh! I forgot to escape my code. |
12,642 | <p>I am trying to upload a file or stream of data to our web server and I cant find a decent way of doing this. I have tried both <code>WebClient</code> and <code>WebRequest</code> both have their problems. </p>
<p><strong>WebClient</strong><br>
Nice and easy but you do not get any notification that the asynchronous upload has completed, and the <code>UploadProgressChanged</code> event doesnt get called back with anything useful. The alternative is to convert your binary data to a string and use <code>UploadStringASync</code> because then at least you get a <code>UploadStringCompleted</code>, problem is you need a lot of ram for big files as its encoding all the data and uploading it in one go.</p>
<p><strong>HttpWebRequest</strong><br>
Bit more complicated but still does what is needed, problem I am getting is that even though it is called on a background thread (supposedly), it still seems to be blocking my UI and the whole browser until the upload has completed which doesnt seem quite right.</p>
<p>Normal .net does have some appropriate <code>WebClient</code> methods for <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.onuploaddatacompleted.aspx" rel="nofollow noreferrer">OnUploadDataCompleted</a> and progress but these arent available in Silverlight .net ... big omission I think!</p>
<p>Does anyone have any solutions, I need to upload multiple binary files preferrably with a progress but I need to perform some actions when the files have completed their upload.</p>
<p>Look forward to some help with this.</p>
| [
{
"answer_id": 12649,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>Matt Berseth had some thoughts in this, might help:</p>\n\n<p><a href=\"http://mattberseth.com/blog/2008/07/aspnet_file_upload_with_realti_1.html\" rel=\"nofollow noreferrer\">http://mattberseth.com/blog/2008/07/aspnet_file_upload_with_realti_1.html</a></p>\n\n<p><strong>@Dan</strong> - Apologies mate, I coulda sworn Matt's article was about Silverlight, but it's quite clearly not. Blame it on those two big glasses of Chilean red I just downed. :-) </p>\n"
},
{
"answer_id": 12662,
"author": "Dan",
"author_id": 1478,
"author_profile": "https://Stackoverflow.com/users/1478",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks, problem I can see with the article is that its not talking about Silverlight, and Silverlight has limited functions, for some reason they have removed some necessary events and methods for binary transfers for no reason. </p>\n\n<p>I need to use Silverlight as I need/want to upload multiple files and HTML does not allow for a multiple file upload.</p>\n"
},
{
"answer_id": 12691,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": true,
"text": "<p>The way i get around it is through INotifyPropertyChanged and event notification.</p>\n\n<p>The essentials:</p>\n\n<pre><code> public void DoIt(){\nthis.IsUploading = True; \n\n WebRequest postRequest = WebRequest.Create(new Uri(ServiceURL));\n\n postRequest.BeginGetRequestStream(new AsyncCallback(RequestOpened), postRequest);\n }\n\nprivate void RequestOpened(IAsyncResult result){\n WebRequest req = result.AsyncState as WebRequest;\n req.BeginGetResponse(new AsyncCallback(GetResponse), req);\n }\n\n private void GetResponse(IAsyncResult result)\n {\n WebRequest req = result.AsyncState as WebRequest;\n string serverresult = string.Empty;\n WebResponse postResponse = req.EndGetResponse(result);\n\n StreamReader responseReader = new StreamReader(postResponse.GetResponseStream());\n\nthis.IsUploading= False;\n}\n\n private Bool_IsUploading;\n public Bool IsUploading\n {\n get { return _IsUploading; }\n private set\n {\n\n _IsUploading = value;\n\n OnPropertyChanged(\"IsUploading\");\n }\n }\n</code></pre>\n\n<p>Right now silverlight is a PiTA because of the double and triple Async calls. </p>\n"
},
{
"answer_id": 12864,
"author": "Dan",
"author_id": 1478,
"author_profile": "https://Stackoverflow.com/users/1478",
"pm_score": 0,
"selected": false,
"text": "<p>This was pretty much what I was doing, the problem I was getting was that my UI was getting locked up.</p>\n\n<p>As you suggested what I was doing already, I presumed the problem was somewhere else so I used the old divide and conquer to narrow down the problem and it wasnt the actual update code, it was my attempt to <strong>Dispatch</strong> a request to update my progress bar during the upload stream code.</p>\n\n<p>Thanks for the advice.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1478/"
] | I am trying to upload a file or stream of data to our web server and I cant find a decent way of doing this. I have tried both `WebClient` and `WebRequest` both have their problems.
**WebClient**
Nice and easy but you do not get any notification that the asynchronous upload has completed, and the `UploadProgressChanged` event doesnt get called back with anything useful. The alternative is to convert your binary data to a string and use `UploadStringASync` because then at least you get a `UploadStringCompleted`, problem is you need a lot of ram for big files as its encoding all the data and uploading it in one go.
**HttpWebRequest**
Bit more complicated but still does what is needed, problem I am getting is that even though it is called on a background thread (supposedly), it still seems to be blocking my UI and the whole browser until the upload has completed which doesnt seem quite right.
Normal .net does have some appropriate `WebClient` methods for [OnUploadDataCompleted](http://msdn.microsoft.com/en-us/library/system.net.webclient.onuploaddatacompleted.aspx) and progress but these arent available in Silverlight .net ... big omission I think!
Does anyone have any solutions, I need to upload multiple binary files preferrably with a progress but I need to perform some actions when the files have completed their upload.
Look forward to some help with this. | The way i get around it is through INotifyPropertyChanged and event notification.
The essentials:
```
public void DoIt(){
this.IsUploading = True;
WebRequest postRequest = WebRequest.Create(new Uri(ServiceURL));
postRequest.BeginGetRequestStream(new AsyncCallback(RequestOpened), postRequest);
}
private void RequestOpened(IAsyncResult result){
WebRequest req = result.AsyncState as WebRequest;
req.BeginGetResponse(new AsyncCallback(GetResponse), req);
}
private void GetResponse(IAsyncResult result)
{
WebRequest req = result.AsyncState as WebRequest;
string serverresult = string.Empty;
WebResponse postResponse = req.EndGetResponse(result);
StreamReader responseReader = new StreamReader(postResponse.GetResponseStream());
this.IsUploading= False;
}
private Bool_IsUploading;
public Bool IsUploading
{
get { return _IsUploading; }
private set
{
_IsUploading = value;
OnPropertyChanged("IsUploading");
}
}
```
Right now silverlight is a PiTA because of the double and triple Async calls. |
12,647 | <p>Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:</p>
<pre><code>if (is_number($x))
{ ... }
</code></pre>
<p>would be ideal. A technique that won't throw warnings when the <code>-w</code> switch is being used is certainly preferred.</p>
| [
{
"answer_id": 12654,
"author": "farmerchris",
"author_id": 1317,
"author_profile": "https://Stackoverflow.com/users/1317",
"pm_score": 2,
"selected": false,
"text": "<p>Not perfect, but you can use a regex:</p>\n\n<pre><code>sub isnumber \n{\n shift =~ /^-?\\d+\\.?\\d*$/;\n}\n</code></pre>\n"
},
{
"answer_id": 12667,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 4,
"selected": false,
"text": "<p>Usually number validation is done with regular expressions. This code will determine if something is numeric as well as check for undefined variables as to not throw warnings:</p>\n\n<pre><code>sub is_integer {\n defined $_[0] && $_[0] =~ /^[+-]?\\d+$/;\n}\n\nsub is_float {\n defined $_[0] && $_[0] =~ /^[+-]?\\d+(\\.\\d+)?$/;\n}\n</code></pre>\n\n<p>Here's some <a href=\"http://www.perl.com/doc/FMTEYEWTK/is_numeric.html\" rel=\"noreferrer\">reading material</a> you should look at.</p>\n"
},
{
"answer_id": 12736,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>A slightly more robust regex can be found in <a href=\"http://search.cpan.org/dist/Regexp-Common\" rel=\"nofollow noreferrer\">Regexp::Common</a>.</p>\n\n<p>It sounds like you want to know if Perl thinks a variable is numeric. Here's a function that traps that warning:</p>\n\n<pre><code>sub is_number{\n my $n = shift;\n my $ret = 1;\n $SIG{\"__WARN__\"} = sub {$ret = 0};\n eval { my $x = $n + 1 };\n return $ret\n}\n</code></pre>\n\n<p>Another option is to turn off the warning locally:</p>\n\n<pre><code>{\n no warnings \"numeric\"; # Ignore \"isn't numeric\" warning\n ... # Use a variable that might not be numeric\n}\n</code></pre>\n\n<p>Note that non-numeric variables will be silently converted to 0, which is probably what you wanted anyway.</p>\n"
},
{
"answer_id": 12742,
"author": "naumcho",
"author_id": 779,
"author_profile": "https://Stackoverflow.com/users/779",
"pm_score": 5,
"selected": false,
"text": "<p>Check out the CPAN module <a href=\"http://search.cpan.org/dist/Regexp-Common\" rel=\"noreferrer\">Regexp::Common</a>. I think it does exactly what you need and handles all the edge cases (e.g. real numbers, scientific notation, etc). e.g.</p>\n\n<pre><code>use Regexp::Common;\nif ($var =~ /$RE{num}{real}/) { print q{a number}; }\n</code></pre>\n"
},
{
"answer_id": 28589,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 8,
"selected": true,
"text": "<p>Use <code>Scalar::Util::looks_like_number()</code> which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this.\nNote that the strings \"inf\" and \"infinity\" are treated as numbers.</p>\n\n<h2>Example:</h2>\n\n<pre><code>#!/usr/bin/perl\n\nuse warnings;\nuse strict;\n\nuse Scalar::Util qw(looks_like_number);\n\nmy @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);\n\nforeach my $expr (@exprs) {\n print \"$expr is\", looks_like_number($expr) ? '' : ' not', \" a number\\n\";\n}\n</code></pre>\n\n<p>Gives this output:</p>\n\n<pre><code>1 is a number\n5.25 is a number\n0.001 is a number\n1.3e8 is a number\nfoo is not a number\nbar is not a number\n1dd is not a number\ninf is a number\ninfinity is a number\n</code></pre>\n\n<h2>See also:</h2>\n\n<ul>\n<li><a href=\"http://perldoc.perl.org/Scalar/Util.html\" rel=\"noreferrer\">perldoc Scalar::Util</a></li>\n<li><a href=\"http://perldoc.perl.org/perlapi.html#SV-Body-Allocation\" rel=\"noreferrer\">perldoc perlapi</a> for <code>looks_like_number</code></li>\n</ul>\n"
},
{
"answer_id": 3806159,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 5,
"selected": false,
"text": "<p>The original question was how to tell if a variable was numeric, not if it \"has a numeric value\".</p>\n\n<p>There are a few operators that have separate modes of operation for numeric and string operands, where \"numeric\" means anything that was originally a number or was ever used in a numeric context (e.g. in <code>$x = \"123\"; 0+$x</code>, before the addition, <code>$x</code> is a string, afterwards it is considered numeric).</p>\n\n<p>One way to tell is this:</p>\n\n<pre><code>if ( length( do { no warnings \"numeric\"; $x & \"\" } ) ) {\n print \"$x is numeric\\n\";\n}\n</code></pre>\n\n<p>If the bitwise feature is enabled, that makes <code>&</code> only a numeric operator and adds a separate string <code>&.</code> operator, you must disable it:</p>\n\n<pre><code>if ( length( do { no if $] >= 5.022, \"feature\", \"bitwise\"; no warnings \"numeric\"; $x & \"\" } ) ) {\n print \"$x is numeric\\n\";\n}\n</code></pre>\n\n<p>(bitwise is available in perl 5.022 and above, and enabled by default if you <code>use 5.028;</code> or above.)</p>\n"
},
{
"answer_id": 4412308,
"author": "fringd",
"author_id": 284511,
"author_profile": "https://Stackoverflow.com/users/284511",
"pm_score": 2,
"selected": false,
"text": "<p>rexep not perfect... this is:</p>\n\n<pre><code>use Try::Tiny;\n\nsub is_numeric {\n my ($x) = @_;\n my $numeric = 1;\n try {\n use warnings FATAL => qw/numeric/;\n 0 + $x;\n }\n catch {\n $numeric = 0;\n };\n return $numeric;\n}\n</code></pre>\n"
},
{
"answer_id": 12937508,
"author": "Peter Vanroose",
"author_id": 1753621,
"author_profile": "https://Stackoverflow.com/users/1753621",
"pm_score": 3,
"selected": false,
"text": "<p>A simple (and maybe simplistic) answer to the question <em>is the content of <code>$x</code> numeric</em> is the following:</p>\n\n<pre><code>if ($x eq $x+0) { .... }\n</code></pre>\n\n<p>It does a textual comparison of the original <code>$x</code> with the <code>$x</code> converted to a numeric value.</p>\n"
},
{
"answer_id": 16861447,
"author": "CDC",
"author_id": 2441129,
"author_profile": "https://Stackoverflow.com/users/2441129",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>If (($x !~ /\\D/) && ($x ne \"\")) { ... }\n</code></pre>\n"
},
{
"answer_id": 18934806,
"author": "Jason Van Patten",
"author_id": 2802457,
"author_profile": "https://Stackoverflow.com/users/2802457",
"pm_score": -1,
"selected": false,
"text": "<p>if ( defined $x && $x !~ m/\\D/ ) {}\nor\n$x = 0 if ! $x;\nif ( $x !~ m/\\D/) {}</p>\n\n<p>This is a slight variation on Veekay's answer but let me explain my reasoning for the change.</p>\n\n<p>Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.</p>\n"
},
{
"answer_id": 32889849,
"author": "Swadhikar",
"author_id": 5397845,
"author_profile": "https://Stackoverflow.com/users/5397845",
"pm_score": 1,
"selected": false,
"text": "<p>I found this interesting though</p>\n\n<pre><code>if ( $value + 0 eq $value) {\n # A number\n push @args, $value;\n} else {\n # A string\n push @args, \"'$value'\";\n}\n</code></pre>\n"
},
{
"answer_id": 34547363,
"author": "zagrimsan",
"author_id": 2745865,
"author_profile": "https://Stackoverflow.com/users/2745865",
"pm_score": 0,
"selected": false,
"text": "<p>Personally I think that the way to go is to rely on Perl's internal context to make the solution bullet-proof. A good regexp could match all the valid numeric values and none of the non-numeric ones (or vice versa), but as there is a way of employing the same logic the interpreter is using it should be safer to rely on that directly.</p>\n\n<p>As I tend to run my scripts with <code>-w</code>, I had to combine the idea of comparing the result of \"value plus zero\" to the original value with the <code>no warnings</code> based approach of @ysth:</p>\n\n<pre><code>do { \n no warnings \"numeric\";\n if ($x + 0 ne $x) { return \"not numeric\"; } else { return \"numeric\"; }\n}\n</code></pre>\n"
},
{
"answer_id": 35657449,
"author": "bLIGU",
"author_id": 4615814,
"author_profile": "https://Stackoverflow.com/users/4615814",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Regular Expressions to determine if $foo is a number (or not).</p>\n\n<p>Take a look here:\n<a href=\"http://perldoc.perl.org/perlfaq4.html#How-do-I-determine-whether-a-scalar-is-a-number%2fwhole%2finteger%2ffloat%3f\" rel=\"nofollow\">How do I determine whether a scalar is a number</a></p>\n"
},
{
"answer_id": 72480461,
"author": "Kevin",
"author_id": 824897,
"author_profile": "https://Stackoverflow.com/users/824897",
"pm_score": 0,
"selected": false,
"text": "<p>There is a highly upvoted accepted answer around using a library function, but it includes the caveat that "inf" and "infinity" are accepted as numbers. I see some regex stuff for answers too, but they seem to have issues. I tried my hand at writing some regex that would work better (I'm sorry it's long)...</p>\n<pre><code>/^0$|^[+-]?[1-9][0-9]*$|^[+-]?[1-9][0-9]*(\\.[0-9]+)?([eE]-?[1-9][0-9]*)?$|^[+-]?[0-9]?\\.[0-9]+$|^[+-]?[1-9][0-9]*\\.[0-9]+$/\n</code></pre>\n<p>That's really 5 patterns separated by "or"...</p>\n<p><strong>Zero:</strong> <code>^0$</code><br>\nIt's a kind of special case. It's the only integer that can start with 0.</p>\n<p><strong>Integers:</strong> <code>^[+-]?[1-9][0-9]*$</code><br>\nThat makes sure the first digit is 1 to 9 and allows 0 to 9 for any of the following digits.</p>\n<p><strong>Scientific Numbers:</strong> <code>^[+-]?[1-9][0-9]*(\\.[0-9]+)?([eE]-?[1-9][0-9]*)?$</code><br>\nUses the same idea that the base number can't start with zero since in proper scientific notation you start with the highest significant bit (meaning the first number won't be zero). However, my pattern allows for multiple digits left of the decimal point. That's incorrect, but I've already spent too much time on this... you could replace the <code>[1-9][0-9]*</code> with just <code>[0-9]</code> to force a single digit before the decimal point and allow for zeroes.</p>\n<p><strong>Short Float Numbers:</strong> <code>^[+-]?[0-9]?\\.[0-9]+$</code><br>\nThis is like a zero integer. It's special in that it can start with 0 if there is only one digit left of the decimal point. It does overlap the next pattern though...</p>\n<p><strong>Long Float Numbers:</strong> <code>^[+-]?[1-9][0-9]*\\.[0-9]+$</code><br>\nThis handles most float numbers and allows more than one digit left of the decimal point while still enforcing that the higher number of digits can't start with 0.</p>\n<p><strong>The simple function...</strong><br></p>\n<pre><code>sub is_number {\n my $testVal = shift;\n return $testVal =~ /^0$|^[+-]?[1-9][0-9]*$|^[+-]?[1-9][0-9]*(\\.[0-9]+)?([eE]-?[1-9][0-9]*)?$|^[+-]?[0-9]?\\.[0-9]+$|^[+-]?[1-9][0-9]*\\.[0-9]+$/;\n}\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872/"
] | Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:
```
if (is_number($x))
{ ... }
```
would be ideal. A technique that won't throw warnings when the `-w` switch is being used is certainly preferred. | Use `Scalar::Util::looks_like_number()` which uses the internal Perl C API's looks\_like\_number() function, which is probably the most efficient way to do this.
Note that the strings "inf" and "infinity" are treated as numbers.
Example:
--------
```
#!/usr/bin/perl
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);
foreach my $expr (@exprs) {
print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n";
}
```
Gives this output:
```
1 is a number
5.25 is a number
0.001 is a number
1.3e8 is a number
foo is not a number
bar is not a number
1dd is not a number
inf is a number
infinity is a number
```
See also:
---------
* [perldoc Scalar::Util](http://perldoc.perl.org/Scalar/Util.html)
* [perldoc perlapi](http://perldoc.perl.org/perlapi.html#SV-Body-Allocation) for `looks_like_number` |
12,656 | <p>In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.</p>
<p>Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the <code>bind_params()</code> or <code>bind_result()</code> methods. </p>
<p>Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.</p>
<p>Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.</p>
<p>Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).</p>
| [
{
"answer_id": 13092,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 5,
"selected": true,
"text": "<p>In PHP you can pass a variable number of arguments to a function or method by using <a href=\"http://www.php.net/call_user_func_array\" rel=\"noreferrer\"><code>call_user_func_array</code></a>. An example for a method would be:</p>\n\n<pre><code>call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);\n</code></pre>\n\n<p>The function will be called with each member in the array passed as its own argument.</p>\n"
},
{
"answer_id": 80352,
"author": "Steven Oxley",
"author_id": 3831,
"author_profile": "https://Stackoverflow.com/users/3831",
"pm_score": 0,
"selected": false,
"text": "<p>I am not allowed to edit, but I believe in the code</p>\n\n<pre><code>call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);\n</code></pre>\n\n<p>The reference in front of $stmt is not necessary. Since <code>$stmt</code> is the object and <code>bindparams</code> is the method in that object, the reference is not necessary. It should be:</p>\n\n<pre><code>call_user_func_array(array($stmt, 'bindparams'), $array_of_params);\n</code></pre>\n\n<p>For more information, see the PHP manual on <a href=\"http://au2.php.net/manual/en/language.pseudo-types.php#language.types.callback\" rel=\"nofollow noreferrer\">Callback Functions</a>.\" </p>\n"
},
{
"answer_id": 2575732,
"author": "jsleuth",
"author_id": 275700,
"author_profile": "https://Stackoverflow.com/users/275700",
"pm_score": 0,
"selected": false,
"text": "<pre><code>call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);\n</code></pre>\n\n<p>Didn't work for me in my environment but this answer set me on the right track. What actually worked was:</p>\n\n<pre><code>$sitesql = '';\n$array_of_params = array();\nforeach($_POST['multiselect'] as $value){\n if($sitesql!=''){\n $sitesql .= \"OR siteID=? \";\n $array_of_params[0] .= 'i';\n $array_of_params[] = $value;\n }else{\n $sitesql = \" siteID=? \";\n $array_of_params[0] .= 'i';\n $array_of_params[] = $value;\n }\n}\n\n$stmt = $linki->prepare(\"SELECT IFNULL(SUM(hours),0) FROM table WHERE \".$sitesql.\" AND week!='0000-00-00'\");\ncall_user_func_array(array(&$stmt, 'bind_param'), $array_of_params);\n$stmt->execute();\n</code></pre>\n"
},
{
"answer_id": 7240875,
"author": "zhikharev",
"author_id": 919105,
"author_profile": "https://Stackoverflow.com/users/919105",
"pm_score": 1,
"selected": false,
"text": "<p>You've got to make sure that $array_of_params is array of <strong>links to variables</strong>, not values themselves. Should be:</p>\n\n<pre><code>$array_of_params[0] = &$param_string; //link to variable that stores types\n</code></pre>\n\n<p>And then...</p>\n\n<pre><code>$param_string .= \"i\";\n$user_id_var = $_GET['user_id'];//\n$array_of_params[] = &$user_id_var; //link to variable that stores value\n</code></pre>\n\n<p>Otherwise (if it is array of values) you'll get:</p>\n\n<blockquote>\n <p>PHP Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference</p>\n</blockquote>\n\n<hr>\n\n<p>One more example:</p>\n\n<pre><code>$bind_names[] = implode($types); //putting types of parameters in a string\nfor ($i = 0; $i < count($params); $i++)\n{\n $bind_name = 'bind'.$i; //generate a name for variable bind1, bind2, bind3...\n $$bind_name = $params[$i]; //create a variable with this name and put value in it\n $bind_names[] = & $$bind_name; //put a link to this variable in array\n}\n</code></pre>\n\n<p>and BOOOOOM:</p>\n\n<pre><code>call_user_func_array( array ($stmt, 'bind_param'), $bind_names); \n</code></pre>\n"
},
{
"answer_id": 58364199,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 2,
"selected": false,
"text": "<p>The more modern way to bind parameters dynamically is via the splat/spread operator (<code>...</code>).</p>\n<p>Assuming:</p>\n<ul>\n<li>you have a non-empty array of values to bind to your query and</li>\n<li>your array values are suitably processed as string type values in the context of the query and</li>\n<li>your input array is called <code>$values</code></li>\n</ul>\n<p>Code for PHP5.6 and higher:</p>\n<pre><code>$stmt->bind_param(str_repeat('s', count($values)), ...$values);\n</code></pre>\n<p>In fact, all of the arguments fed to <code>bind_param()</code> can be unpacked with the splat/spread operator if you wish -- the data types string just needs to be the first element of the array.</p>\n<pre><code>array_unshift($values, str_repeat('s', count($values)));\n$stmt->bind_param(...$values);\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
] | In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.
Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the `bind_params()` or `bind_result()` methods.
Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.
Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.
Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure). | In PHP you can pass a variable number of arguments to a function or method by using [`call_user_func_array`](http://www.php.net/call_user_func_array). An example for a method would be:
```
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
```
The function will be called with each member in the array passed as its own argument. |
12,657 | <p>I'm using the new ASP.Net ListView control to list database items that will be grouped together in sections based on one of their columns like so:</p>
<pre><code>region1
store1
store2
store3
region2
store4
region3
store5
store6
</code></pre>
<p>Is this possible to do with the ListView's GroupItemTemplate? Every example I have seen uses a static number of items per group, which won't work for me. Am I misunderstanding the purpose of the GroupItem?</p>
| [
{
"answer_id": 12735,
"author": "Otto",
"author_id": 519,
"author_profile": "https://Stackoverflow.com/users/519",
"pm_score": 3,
"selected": true,
"text": "<p>I haven't used GroupItemCount, but I have taken this example written up by <a href=\"http://mattberseth.com/\" rel=\"nofollow noreferrer\">Matt Berseth</a> titled <a href=\"http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html\" rel=\"nofollow noreferrer\">Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls</a> and have grouped items by a key just like you want.</p>\n\n<p>It involves using an outer and inner ListView control. Works great, give it a try.</p>\n"
},
{
"answer_id": 1631731,
"author": "mathijsuitmegen",
"author_id": 78939,
"author_profile": "https://Stackoverflow.com/users/78939",
"pm_score": 0,
"selected": false,
"text": "<p>I tried using GroupItemCount programmatically but it didn't give me the expected results. </p>\n\n<p>I followed Otto's suggestion and implemented an outer and inner ListView control. This seems to be the best available solution.</p>\n"
},
{
"answer_id": 21299212,
"author": "c0d3m0nk3y",
"author_id": 3226224,
"author_profile": "https://Stackoverflow.com/users/3226224",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure you're doing a DataBind <strong>AFTER</strong> setting the GroupItemCount property. I had the same problem and that's what I did to resolve it.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1249/"
] | I'm using the new ASP.Net ListView control to list database items that will be grouped together in sections based on one of their columns like so:
```
region1
store1
store2
store3
region2
store4
region3
store5
store6
```
Is this possible to do with the ListView's GroupItemTemplate? Every example I have seen uses a static number of items per group, which won't work for me. Am I misunderstanding the purpose of the GroupItem? | I haven't used GroupItemCount, but I have taken this example written up by [Matt Berseth](http://mattberseth.com/) titled [Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls](http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html) and have grouped items by a key just like you want.
It involves using an outer and inner ListView control. Works great, give it a try. |
12,661 | <p>What's the most efficient way to resize large images in PHP?</p>
<p>I'm currently using the <a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="noreferrer">GD</a> function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).</p>
<p>This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).</p>
<p>Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as <a href="http://en.wikipedia.org/wiki/ImageMagick" rel="noreferrer">ImageMagick</a>?</p>
<p>Right now, the resize code looks something like this</p>
<pre><code>function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
$img = imagecreatefromjpeg($sourcefile);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
imagejpeg( $tmpimg, $endfile, $quality);
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
</code></pre>
| [
{
"answer_id": 12732,
"author": "phenry",
"author_id": 1482,
"author_profile": "https://Stackoverflow.com/users/1482",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://phpthumb.sourceforge.net/\" rel=\"noreferrer\">phpThumb</a> uses ImageMagick whenever possible for speed (falling back to GD if necessary) and seems to cache pretty well to reduce the load on the server. It's pretty lightweight to try out (to resize an image, just call phpThumb.php with a GET query that includes the graphic filename and output dimensions), so you might give it a shot to see if it meets your needs.</p>\n"
},
{
"answer_id": 12805,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 5,
"selected": false,
"text": "<p>Here's a snippet from the php.net docs that I've used in a project and works fine:</p>\n\n<pre><code><?\nfunction fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {\n // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.\n // Just include this function and change all \"imagecopyresampled\" references to \"fastimagecopyresampled\".\n // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.\n // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.\n //\n // Optional \"quality\" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.\n // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.\n // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.\n // 2 = Up to 95 times faster. Images appear a little sharp, some prefer this over a quality of 3.\n // 3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled, just faster.\n // 4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images.\n // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.\n\n if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }\n if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {\n $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);\n imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);\n imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);\n imagedestroy ($temp);\n } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);\n return true;\n}\n?>\n</code></pre>\n\n<p><a href=\"http://us.php.net/manual/en/function.imagecopyresampled.php#77679\" rel=\"nofollow noreferrer\">http://us.php.net/manual/en/function.imagecopyresampled.php#77679</a></p>\n"
},
{
"answer_id": 12822,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 7,
"selected": true,
"text": "<p>People say that ImageMagick is much faster. At best just compare both libraries and measure that.</p>\n\n<ol>\n<li>Prepare 1000 typical images.</li>\n<li>Write two scripts -- one for GD, one\nfor ImageMagick.</li>\n<li>Run both of them a few times.</li>\n<li>Compare results (total execution\ntime, CPU and I/O usage, result\nimage quality).</li>\n</ol>\n\n<p>Something which the best everyone else, could not be the best for you.</p>\n\n<p>Also, in my opinion, ImageMagick has much better API interface.</p>\n"
},
{
"answer_id": 716766,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest that you work something along these lines:</p>\n\n<ol>\n<li>Perform a getimagesize( ) on the uploaded file to check image type and size</li>\n<li>Save any uploaded JPEG image smaller than 700x700px in to the destination folder \"as-is\"</li>\n<li>Use GD library for medium size images (see this article for code sample: <a href=\"http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html\" rel=\"nofollow noreferrer\">Resize Images Using PHP and GD Library</a>)</li>\n<li>Use ImageMagick for large images. You can use ImageMagick in background if you prefer.</li>\n</ol>\n\n<p>To use ImageMagick in background, move the uploaded files to a temporary folder and schedule a CRON job that \"convert\"s all files to jpeg and resizes them accordingly. See command syntax at: <a href=\"http://www.imagemagick.org/script/command-line-processing.php\" rel=\"nofollow noreferrer\">imagemagick-command line processing</a></p>\n\n<p>You can prompt the user that file is uploaded and scheduled to be processed. The CRON job could be scheduled to run daily at a specific interval. The source image could be deleted after processing to assure that an image is not processed twice.</p>\n"
},
{
"answer_id": 957421,
"author": "Adnan",
"author_id": 88907,
"author_profile": "https://Stackoverflow.com/users/88907",
"pm_score": 2,
"selected": false,
"text": "<p>For larger images use <a href=\"http://phpthumb.sourceforge.net/\" rel=\"nofollow noreferrer\">phpThumb()</a>. Here is how to use it: <a href=\"http://abcoder.com/php/problem-with-resizing-corrupted-images-using-php-image-functions/\" rel=\"nofollow noreferrer\">http://abcoder.com/php/problem-with-resizing-corrupted-images-using-php-image-functions/</a>. It also works for large corrupted images.</p>\n"
},
{
"answer_id": 4613341,
"author": "Steve-o",
"author_id": 175849,
"author_profile": "https://Stackoverflow.com/users/175849",
"pm_score": 3,
"selected": false,
"text": "<p>For larger images use libjpeg to resize on image load in ImageMagick and thereby significantly reducing memory usage and improving performance, it is not possible with GD.</p>\n\n<pre><code>$im = new Imagick();\ntry {\n $im->pingImage($file_name);\n} catch (ImagickException $e) {\n throw new Exception(_('Invalid or corrupted image file, please try uploading another image.'));\n}\n\n$width = $im->getImageWidth();\n$height = $im->getImageHeight();\nif ($width > $config['width_threshold'] || $height > $config['height_threshold'])\n{\n try {\n/* send thumbnail parameters to Imagick so that libjpeg can resize images\n * as they are loaded instead of consuming additional resources to pass back\n * to PHP.\n */\n $fitbyWidth = ($config['width_threshold'] / $width) > ($config['height_threshold'] / $height);\n $aspectRatio = $height / $width;\n if ($fitbyWidth) {\n $im->setSize($config['width_threshold'], abs($width * $aspectRatio));\n } else {\n $im->setSize(abs($height / $aspectRatio), $config['height_threshold']);\n }\n $im->readImage($file_name);\n\n/* Imagick::thumbnailImage(fit = true) has a bug that it does fit both dimensions\n */\n// $im->thumbnailImage($config['width_threshold'], $config['height_threshold'], true);\n\n// workaround:\n if ($fitbyWidth) {\n $im->thumbnailImage($config['width_threshold'], 0, false);\n } else {\n $im->thumbnailImage(0, $config['height_threshold'], false);\n }\n\n $im->setImageFileName($thumbnail_name);\n $im->writeImage();\n }\n catch (ImagickException $e)\n {\n header('HTTP/1.1 500 Internal Server Error');\n throw new Exception(_('An error occured reszing the image.'));\n }\n}\n\n/* cleanup Imagick\n */\n$im->destroy();\n</code></pre>\n"
},
{
"answer_id": 5004150,
"author": "alessioalex",
"author_id": 617839,
"author_profile": "https://Stackoverflow.com/users/617839",
"pm_score": 2,
"selected": false,
"text": "<p>I've heard big things about the Imagick library, unfortunately I couldn't install it at my work computer and neither at home (and trust me, I spent hours and hours on all kinds of forums).</p>\n\n<p>Afterwords, I've decided to try this PHP class:</p>\n\n<p><a href=\"http://www.verot.net/php_class_upload.htm\" rel=\"nofollow\">http://www.verot.net/php_class_upload.htm</a></p>\n\n<p>It's pretty cool and I can resize all kinds of images (I can convert them to JPG also).</p>\n"
},
{
"answer_id": 8321603,
"author": "Alasdair",
"author_id": 1018582,
"author_profile": "https://Stackoverflow.com/users/1018582",
"pm_score": 2,
"selected": false,
"text": "<p>ImageMagick is multithreaded, so it appears to be faster, but actually uses a lot more resources than GD. If you ran several PHP scripts in parallel all using GD then they'd beat ImageMagick in speed for simple operations. ExactImage is less powerful than ImageMagick but a lot faster, though not available through PHP, you'll have to install it on the server and run it through <code>exec</code>.</p>\n"
},
{
"answer_id": 19675318,
"author": "Eathen Nutt",
"author_id": 1970939,
"author_profile": "https://Stackoverflow.com/users/1970939",
"pm_score": 3,
"selected": false,
"text": "<p>From you quesion, it seems you are kinda new to GD, I will share some experence of mine, \nmaybe this is a bit off topic, but I think it will be helpful to someone new to GD like you:</p>\n\n<p><strong>Step 1, validate file.</strong> Use the following function to check if the <code>$_FILES['image']['tmp_name']</code> file is valid file:</p>\n\n<pre><code> function getContentsFromImage($image) {\n if (@is_file($image) == true) {\n return file_get_contents($image);\n } else {\n throw new \\Exception('Invalid image');\n }\n }\n $contents = getContentsFromImage($_FILES['image']['tmp_name']);\n</code></pre>\n\n<p><strong>Step 2, get file format</strong> Try the following function with finfo extension to check file format of the file(contents). You would say why don't you just use <code>$_FILES[\"image\"][\"type\"]</code> to check file format? Because it <strong>ONLY</strong> check file extension not file contents, if someone rename a file originally called <em>world.png</em> to <em>world.jpg</em>, <code>$_FILES[\"image\"][\"type\"]</code> will return jpeg not png, so <code>$_FILES[\"image\"][\"type\"]</code> may return wrong result.</p>\n\n<pre><code> function getFormatFromContents($contents) {\n $finfo = new \\finfo();\n $mimetype = $finfo->buffer($contents, FILEINFO_MIME_TYPE);\n switch ($mimetype) {\n case 'image/jpeg':\n return 'jpeg';\n break;\n case 'image/png':\n return 'png';\n break;\n case 'image/gif':\n return 'gif';\n break;\n default:\n throw new \\Exception('Unknown or unsupported image format');\n }\n }\n $format = getFormatFromContents($contents);\n</code></pre>\n\n<p><strong>Step.3, Get GD resource</strong> Get GD resource from contents we have before:</p>\n\n<pre><code> function getGDResourceFromContents($contents) {\n $resource = @imagecreatefromstring($contents);\n if ($resource == false) {\n throw new \\Exception('Cannot process image');\n }\n return $resource;\n }\n $resource = getGDResourceFromContents($contents);\n</code></pre>\n\n<p><strong>Step 4, get image dimension</strong> Now you can get image dimension with the following simple code:</p>\n\n<pre><code> $width = imagesx($resource);\n $height = imagesy($resource);\n</code></pre>\n\n<p><strong>Now,</strong> Let's see what variable we got from the original image then:</p>\n\n<pre><code> $contents, $format, $resource, $width, $height\n OK, lets move on\n</code></pre>\n\n<p><strong>Step 5, calculate resized image arguments</strong> This step is related to your question, the purpose of the following function is to get resize arguments for GD function <code>imagecopyresampled()</code>, the code is kinda long, but it works great, it even has three options: stretch, shrink, and fill.</p>\n\n<p><strong><em>stretch</em></strong>: output image's dimension is the same as the new dimension you set. Won't keep height/width ratio.</p>\n\n<p><strong><em>shrink</em></strong>: output image's dimension won't exceed the new dimension you give, and keep image height/width ratio.</p>\n\n<p><strong><em>fill</em></strong>: output image's dimension will be the same as new dimension you give, it will <strong><em>crop & resize</em></strong> image if needed, and keep image height/width ratio. <strong>This option is what you need in your question.</strong></p>\n\n<pre><code> function getResizeArgs($width, $height, $newwidth, $newheight, $option) {\n if ($option === 'stretch') {\n if ($width === $newwidth && $height === $newheight) {\n return false;\n }\n $dst_w = $newwidth;\n $dst_h = $newheight;\n $src_w = $width;\n $src_h = $height;\n $src_x = 0;\n $src_y = 0;\n } else if ($option === 'shrink') {\n if ($width <= $newwidth && $height <= $newheight) {\n return false;\n } else if ($width / $height >= $newwidth / $newheight) {\n $dst_w = $newwidth;\n $dst_h = (int) round(($newwidth * $height) / $width);\n } else {\n $dst_w = (int) round(($newheight * $width) / $height);\n $dst_h = $newheight;\n }\n $src_x = 0;\n $src_y = 0;\n $src_w = $width;\n $src_h = $height;\n } else if ($option === 'fill') {\n if ($width === $newwidth && $height === $newheight) {\n return false;\n }\n if ($width / $height >= $newwidth / $newheight) {\n $src_w = (int) round(($newwidth * $height) / $newheight);\n $src_h = $height;\n $src_x = (int) round(($width - $src_w) / 2);\n $src_y = 0;\n } else {\n $src_w = $width;\n $src_h = (int) round(($width * $newheight) / $newwidth);\n $src_x = 0;\n $src_y = (int) round(($height - $src_h) / 2);\n }\n $dst_w = $newwidth;\n $dst_h = $newheight;\n }\n if ($src_w < 1 || $src_h < 1) {\n throw new \\Exception('Image width or height is too small');\n }\n return array(\n 'dst_x' => 0,\n 'dst_y' => 0,\n 'src_x' => $src_x,\n 'src_y' => $src_y,\n 'dst_w' => $dst_w,\n 'dst_h' => $dst_h,\n 'src_w' => $src_w,\n 'src_h' => $src_h\n );\n }\n $args = getResizeArgs($width, $height, 150, 170, 'fill');\n</code></pre>\n\n<p><strong>Step 6, resize image</strong> Use <code>$args</code>, <code>$width</code>, <code>$height</code>, <code>$format</code> and $resource we got from above into the following function and get the new resource of the resized image:</p>\n\n<pre><code> function runResize($width, $height, $format, $resource, $args) {\n if ($args === false) {\n return; //if $args equal to false, this means no resize occurs;\n }\n $newimage = imagecreatetruecolor($args['dst_w'], $args['dst_h']);\n if ($format === 'png') {\n imagealphablending($newimage, false);\n imagesavealpha($newimage, true);\n $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);\n imagefill($newimage, 0, 0, $transparentindex);\n } else if ($format === 'gif') {\n $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);\n imagefill($newimage, 0, 0, $transparentindex);\n imagecolortransparent($newimage, $transparentindex);\n }\n imagecopyresampled($newimage, $resource, $args['dst_x'], $args['dst_y'], $args['src_x'], $args['src_y'], $args['dst_w'], $args['dst_h'], $args['src_w'], $args['src_h']);\n imagedestroy($resource);\n return $newimage;\n }\n $newresource = runResize($width, $height, $format, $resource, $args);\n</code></pre>\n\n<p><strong>Step 7, get new contents</strong>, Use the following function to get contents from the new GD resource:</p>\n\n<pre><code> function getContentsFromGDResource($resource, $format) {\n ob_start();\n switch ($format) {\n case 'gif':\n imagegif($resource);\n break;\n case 'jpeg':\n imagejpeg($resource, NULL, 100);\n break;\n case 'png':\n imagepng($resource, NULL, 9);\n }\n $contents = ob_get_contents();\n ob_end_clean();\n return $contents;\n }\n $newcontents = getContentsFromGDResource($newresource, $format);\n</code></pre>\n\n<p><strong>Step 8 get extension</strong>, Use the following function to get extension of from image format(note, image format is not equal to image extension):</p>\n\n<pre><code> function getExtensionFromFormat($format) {\n switch ($format) {\n case 'gif':\n return 'gif';\n break;\n case 'jpeg':\n return 'jpg';\n break;\n case 'png':\n return 'png';\n }\n }\n $extension = getExtensionFromFormat($format);\n</code></pre>\n\n<p><strong>Step 9 save image</strong> If we have a user named mike, you can do the following, it will save to the same folder as this php script:</p>\n\n<pre><code>$user_name = 'mike';\n$filename = $user_name . '.' . $extension;\nfile_put_contents($filename, $newcontents);\n</code></pre>\n\n<p><strong>Step 10 destroy resource</strong> Don't forget destroy GD resource!</p>\n\n<pre><code>imagedestroy($newresource);\n</code></pre>\n\n<p>or you can write all your code into a class, and simply use the following:</p>\n\n<pre><code> public function __destruct() {\n @imagedestroy($this->resource);\n }\n</code></pre>\n\n<p><strong>TIPS</strong></p>\n\n<p><strong>I recommend not to convert file format that user upload, you will meet many problems.</strong></p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477/"
] | What's the most efficient way to resize large images in PHP?
I'm currently using the [GD](http://en.wikipedia.org/wiki/GD_Graphics_Library) function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).
This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).
Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as [ImageMagick](http://en.wikipedia.org/wiki/ImageMagick)?
Right now, the resize code looks something like this
```
function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
$img = imagecreatefromjpeg($sourcefile);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
imagejpeg( $tmpimg, $endfile, $quality);
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
``` | People say that ImageMagick is much faster. At best just compare both libraries and measure that.
1. Prepare 1000 typical images.
2. Write two scripts -- one for GD, one
for ImageMagick.
3. Run both of them a few times.
4. Compare results (total execution
time, CPU and I/O usage, result
image quality).
Something which the best everyone else, could not be the best for you.
Also, in my opinion, ImageMagick has much better API interface. |
12,702 | <p>I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.</p>
<p>When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:</p>
<pre><code>[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
for(int i=0;i<100;i++)
{
tbl.Columns.Add(i);
tbl.Rows.Add(new string[]{"testValue"});
}
return tbl;
}
</code></pre>
<p>However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."</p>
<pre><code>[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
//Populate table with SQL query
return tbl;
}
</code></pre>
<p>The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.</p>
<p>Why would the way that the table is being populated have any bearing on the table returning successfully?</p>
| [
{
"answer_id": 12712,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>The attribute you want is OperationContract (on interface) / Operation Behavior (on method):</p>\n\n<pre><code>[ServiceContract]\npublic interface ITableProvider\n{\n [OperationContract]\n DataTable GetTbl();\n}\n\n\n[OperationBehavior]\npublic DataTable GetTbl(){\n DataTable tbl = new DataTable(\"testTbl\");\n //Populate table with SQL query\n\n return tbl;\n}\n</code></pre>\n\n<p>Also, in the... I think service configuration... you want to specify that errors can be sent. You might be hitting an error that is something like the message size is to big, etc. You can fix that by fudging with the reader quotas and such.</p>\n\n<p>By default wsHttpBinding has a receive size quota of like 65 KB, so if the serialized data table's XML is more than that, it would throw an error (and I'm 95% sure the data table is more than 65 KB with data in it).</p>\n\n<p>You can change the settings for the reader quotas and such in the <code>web.config</code> / <code>app.config</code> or you can set it on a binding instance in code. But yeah, that's probably what your problem is, if you haven't changed it by default.</p>\n\n<p><em><a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.wshttpbindingbase_members.aspx\" rel=\"nofollow noreferrer\">WSHttpBindingBase Members</a></em> - Look at ReaderQuotas property as well as the MaxReceivedMessageSize property.</p>\n"
},
{
"answer_id": 24492,
"author": "Chris Gillum",
"author_id": 2069,
"author_profile": "https://Stackoverflow.com/users/2069",
"pm_score": 4,
"selected": false,
"text": "<p>The best way to diagnose these kinds of WCF errors (the ones that really don't tell you much) is to enable tracing. In your web.config file, add the following:</p>\n\n<pre><code> <system.diagnostics>\n <sources>\n <source name=\"System.ServiceModel\" \n switchValue=\"Information\" \n propagateActivity=\"true\">\n <listeners>\n <add name=\"ServiceModelTraceListener\" \n type=\"System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" \n initializeData=\"wcf-traces.svclog\"/>\n </listeners>\n </source>\n </sources>\n </system.diagnostics>\n</code></pre>\n\n<p>You can then open the resulting file in the SvcTraceViewer.exe utility which comes in the .NET Framework SDK (or with Visual Studio). On my machine, it can be found at %PROGRAMFILES%\\Microsoft SDKs\\Windows\\v6.0A\\Bin\\SvcTraceViewer.exe.</p>\n\n<p>Just look for an error message (in bold red) and that will tell you specifically what your problem is.</p>\n"
},
{
"answer_id": 39638,
"author": "Paul Mrozowski",
"author_id": 3656,
"author_profile": "https://Stackoverflow.com/users/3656",
"pm_score": 0,
"selected": false,
"text": "<p>I think Darren is most likely correct - the default values provided for WCF are laughably small and if you bump into them you end up with errors that can be difficult to track down. They seem to appear as soon as you attempt to do anything beyond a simple test case. I wasted more time than I'd like to admit debugging problems that turned out to be related to the various configuration (size) settings on both the client and server. I think I ended up modifying almost all of them, ex. MaxBufferPoolSize, MaxBufferSize, MaxConnections, MaxReceivedMessageSize, etc. </p>\n\n<p>Having said that, the SvcTraceViewer utility also mentioned is great. I did run into a few cases where it wasn't as helpful as I would have liked, but overall it's a nice tool for analyzing the communications flow and errors.</p>\n"
},
{
"answer_id": 42332,
"author": "goric",
"author_id": 940,
"author_profile": "https://Stackoverflow.com/users/940",
"pm_score": 7,
"selected": true,
"text": "<p>For anyone having similar problems, I have solved my issue. It was several-fold.</p>\n\n<ul>\n<li>As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages. </li>\n<li>It also appears that when the Service Reference is updated on the client side, the configuration will sometimes not update properly (e.g. Changing config values on the server will not always properly update on the client. I had to go in and change the Max..Size properties multiple times on both the client and server sides in the course of my debugging)</li>\n<li><p>For a DataTable to be serializable, it needs to be given a name. The default constructor does not give the table a name, so:</p>\n\n<pre><code>return new DataTable();\n</code></pre>\n\n<p>will not be serializable, while:</p>\n\n<pre><code>return new DataTable(\"someName\");\n</code></pre>\n\n<p>will name the table whatever is passed as the parameter. </p>\n\n<p>Note that a table can be given a name at any time by assigning a string to the <code>TableName</code> property of the DataTable.</p>\n\n<pre><code>var table = new DataTable();\ntable.TableName = \"someName\";\n</code></pre></li>\n</ul>\n\n<p>Hopefully that will help someone.</p>\n"
},
{
"answer_id": 233550,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 2,
"selected": false,
"text": "<p>You probably blew your quota - the datatable is larger than the allowed maximum packet size for your connection.</p>\n\n<p>You probably need to set <strong>MaxReceivedMessageSize</strong> and <strong>MaxBufferSize</strong> to higher values on your connection.</p>\n"
},
{
"answer_id": 4499790,
"author": "aditya pathak",
"author_id": 549975,
"author_profile": "https://Stackoverflow.com/users/549975",
"pm_score": 3,
"selected": false,
"text": "<p>Other than setting maximum values for all binding attributes.</p>\n\n<p>Make sure each table you are passing/returning from webservice must have a table name, meaning the <code>table.tablename</code> property should not be blank.</p>\n"
},
{
"answer_id": 7872975,
"author": "Jani5e",
"author_id": 1008160,
"author_profile": "https://Stackoverflow.com/users/1008160",
"pm_score": 3,
"selected": false,
"text": "<p>I added the Datable to a data set and returned the table like so...</p>\n\n<pre><code>DataTable result = new DataTable(\"result\");\n\n//linq to populate the table\n\nDataset ds = new DataSet();\nds.Tables.Add(result);\nreturn ds.Tables[0];\n</code></pre>\n\n<p>Hope it helps\n:)</p>\n"
},
{
"answer_id": 40925254,
"author": "Mukesh Methaniya",
"author_id": 1410033,
"author_profile": "https://Stackoverflow.com/users/1410033",
"pm_score": 1,
"selected": false,
"text": "<p>There are 3 reason for failed return type as <code>datatable</code> in WCF services</p>\n\n<ul>\n<li><p>You have to specify data table name like: </p>\n\n<pre><code>MyTable=new DataTable(\"tableName\");\n</code></pre></li>\n<li><p>When you are adding reference on client side of WCF service select reusable dll <code>system.data</code></p></li>\n<li><p>Specify attribute on <code>datatable</code> member variable like</p>\n\n<pre><code>[DataMember]\npublic DataTable MyTable{ get; set; }\n</code></pre></li>\n</ul>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] | I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.
When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:
```
[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
for(int i=0;i<100;i++)
{
tbl.Columns.Add(i);
tbl.Rows.Add(new string[]{"testValue"});
}
return tbl;
}
```
However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."
```
[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
//Populate table with SQL query
return tbl;
}
```
The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.
Why would the way that the table is being populated have any bearing on the table returning successfully? | For anyone having similar problems, I have solved my issue. It was several-fold.
* As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages.
* It also appears that when the Service Reference is updated on the client side, the configuration will sometimes not update properly (e.g. Changing config values on the server will not always properly update on the client. I had to go in and change the Max..Size properties multiple times on both the client and server sides in the course of my debugging)
* For a DataTable to be serializable, it needs to be given a name. The default constructor does not give the table a name, so:
```
return new DataTable();
```
will not be serializable, while:
```
return new DataTable("someName");
```
will name the table whatever is passed as the parameter.
Note that a table can be given a name at any time by assigning a string to the `TableName` property of the DataTable.
```
var table = new DataTable();
table.TableName = "someName";
```
Hopefully that will help someone. |
12,716 | <p>In C++ program, I am trying to #import TLB of .NET out-of-proc server.</p>
<p>I get errors like:</p>
<blockquote>
<p>z:\server.tlh(111) : error C2146: syntax error : missing ';' before identifier 'GetType'</p>
<p>z:\server.tlh(111) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p>
<p>z:\server.tli(74) : error C2143: syntax error : missing ';' before 'tag::id'</p>
<p>z:\server.tli(74) : error C2433: '_TypePtr' : 'inline' not permitted on data declarations</p>
<p>z:\server.tli(74) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p>
<p>z:\server.tli(74) : fatal error C1004: unexpected end of file found</p>
</blockquote>
<p>The TLH looks like:</p>
<pre><code>_bstr_t GetToString();
VARIANT_BOOL Equals (const _variant_t & obj);
long GetHashCode();
_TypePtr GetType();
long Open();
</code></pre>
<p>I am not really interested in the having the base object .NET object methods like GetType(), Equals(), etc. But GetType() seems to be causing problems.</p>
<p>Some google research indicates I could <code>#import mscorlib.tlb</code> (or put it in path), but I can't get that to compile either.</p>
<p>Any tips?</p>
| [
{
"answer_id": 12751,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 2,
"selected": true,
"text": "<p>Added no_namespace and raw_interfaces_only to my #import:</p>\n\n<pre><code>#import \"server.tlb\" no_namespace named_guids\n</code></pre>\n\n<p>Also using TLBEXP.EXE instead of REGASM.EXE seems to help this issue.</p>\n"
},
{
"answer_id": 18376,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 0,
"selected": false,
"text": "<p>Also, make sure your C# class doesn't have this attribute:</p>\n\n<p>[ClassInterface(ClassInterfaceType.AutoDual)] <-- Seems to cause errors in C++ with _TypePtr</p>\n"
},
{
"answer_id": 758927,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Often, when MSVC compile COM source to a <code>TLB</code>, there'll be hints left behind like:</p>\n\n<pre><code>#import \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\mscorlib.tlb\"\n</code></pre>\n\n<p>You should add that to <code>stdafx.h</code> before the line</p>\n\n<pre><code>#import \"your_own.tlb\"\n</code></pre>\n\n<p>After that, basic types like <code>_Type</code>, <code>_ObjRef</code> will be added to your project for the prototypes generated.</p>\n\n<p>I hope that solves your problem.</p>\n\n<p>but the bigger problem is that after everything is done, there might be runtime errors when you call a Ptr in you program</p>\n\n<p>anyone can help?</p>\n"
},
{
"answer_id": 2071836,
"author": "OndrejP_SK",
"author_id": 251550,
"author_profile": "https://Stackoverflow.com/users/251550",
"pm_score": 1,
"selected": false,
"text": "<p>It seems that you need to use </p>\n\n<pre><code>[ClassInterface(ClassInterfaceType.None)]\n</code></pre>\n\n<p>Here is <a href=\"http://osdir.com/ml/windows.devel.dotnet.cx/2004-05/msg00016.html\" rel=\"nofollow noreferrer\">another discussion</a> about the similar problem.</p>\n"
},
{
"answer_id": 2731679,
"author": "ggo",
"author_id": 328135,
"author_profile": "https://Stackoverflow.com/users/328135",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#import \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\mscorlib.tlb\"\n</code></pre>\n\n<p>Was the solution for me.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | In C++ program, I am trying to #import TLB of .NET out-of-proc server.
I get errors like:
>
> z:\server.tlh(111) : error C2146: syntax error : missing ';' before identifier 'GetType'
>
>
> z:\server.tlh(111) : error C2501: '\_TypePtr' : missing storage-class or type specifiers
>
>
> z:\server.tli(74) : error C2143: syntax error : missing ';' before 'tag::id'
>
>
> z:\server.tli(74) : error C2433: '\_TypePtr' : 'inline' not permitted on data declarations
>
>
> z:\server.tli(74) : error C2501: '\_TypePtr' : missing storage-class or type specifiers
>
>
> z:\server.tli(74) : fatal error C1004: unexpected end of file found
>
>
>
The TLH looks like:
```
_bstr_t GetToString();
VARIANT_BOOL Equals (const _variant_t & obj);
long GetHashCode();
_TypePtr GetType();
long Open();
```
I am not really interested in the having the base object .NET object methods like GetType(), Equals(), etc. But GetType() seems to be causing problems.
Some google research indicates I could `#import mscorlib.tlb` (or put it in path), but I can't get that to compile either.
Any tips? | Added no\_namespace and raw\_interfaces\_only to my #import:
```
#import "server.tlb" no_namespace named_guids
```
Also using TLBEXP.EXE instead of REGASM.EXE seems to help this issue. |
12,718 | <p>When installing subversion as a service, I used this command:</p>
<pre><code>c:\>svnservice -install --daemon --root "c:\documents and settings\my_repository"
</code></pre>
<p>And then I got this error:</p>
<pre><code>Could not create service in service control manager.
</code></pre>
<p>After looking at some MSDN docs on the service control manager, I tried granting full control to everyone in the permissions on the registry key at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services, but that hasn't had any effect.</p>
<p>Anybody know what I did wrong, or how to overcome this?</p>
<p><em>Note #1: I am running as an administrator on this box</em></p>
<p>*Note #2: I was following the instructions given <a href="http://blogs.vertigosoftware.com/teamsystem/archive/2006/01/16/Setting_up_a_Subversion_Server_under_Windows.aspx" rel="nofollow noreferrer">here</a>, so maybe my choice of directory is misguided. And my repository is not actually called "my_repository". I used the name of an actual project which is currently under source control in <em>gasp</em> VSS.*</p>
| [
{
"answer_id": 12727,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>I've never used the command line installer for this. I assume you are downloading the latest from:</p>\n\n<p><a href=\"http://svnservice.tigris.org/\" rel=\"nofollow noreferrer\">http://svnservice.tigris.org/</a></p>\n\n<p>I run the installer, and then use the configuration tool (in the Start Menu, SVN Service, SVN Service Administration) to set it up.</p>\n"
},
{
"answer_id": 12730,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 0,
"selected": false,
"text": "<p>The only thing I can currently think of, is the following: make sure you're running under an administrator account. That's absolutely necessary to install a service, AFAIK.</p>\n\n<p>Have fun with Subversion, btw :)</p>\n"
},
{
"answer_id": 12738,
"author": "BrianH",
"author_id": 1484,
"author_profile": "https://Stackoverflow.com/users/1484",
"pm_score": 0,
"selected": false,
"text": "<p>I'd suggest you move your repository to somewhere a little safer, maybe \"c:\\SVNRepo\". </p>\n\n<p>I'd hesitate to put the Repository in \"Documents and Settings\". Is your repository actually called \"my_repository\"?</p>\n"
},
{
"answer_id": 12744,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.visualsvn.com/server\" rel=\"nofollow noreferrer\">VisualSVN Server</a> installs as a Windows service. It is free, includes Apache, OpenSSL, and a repository / permission management tool. It can also integrate with Active Directory for user authentication. I highly recommend it for hosting SVN on Windows.</p>\n"
},
{
"answer_id": 12746,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend you tu use <a href=\"http://www.visualsvn.com/server/\" rel=\"nofollow noreferrer\">Visual SVN Server</a>. Very easy to install</p>\n"
},
{
"answer_id": 12756,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 1,
"selected": false,
"text": "<p>I've followed the instructions given at the Collabnet site:</p>\n\n<p><a href=\"http://svn.apache.org/repos/asf/subversion/trunk/notes/windows-service.txt\" rel=\"nofollow noreferrer\">http://svn.apache.org/repos/asf/subversion/trunk/notes/windows-service.txt</a></p>\n\n<p>They use the windows SC to create the service (which runs svnserve). This has worked for me without any problems (using svn 1.4 and 1.5)</p>\n"
},
{
"answer_id": 12762,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "<p>I think svnservice is obsolete, because since 1.4, svnserve itself has been able to run as a Windows service. (svnserve comes as a part of the normal SVN binary distribution)</p>\n\n<p><a href=\"http://svn.apache.org/repos/asf/subversion/trunk/notes/windows-service.txt\" rel=\"nofollow noreferrer\">http://svn.apache.org/repos/asf/subversion/trunk/notes/windows-service.txt</a> contains the details of how to set it up.</p>\n\n<p>And the binaries you want are here: <a href=\"http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91\" rel=\"nofollow noreferrer\">http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91</a></p>\n\n<p>But as others have said, there are now more friendly packages containing the svn stuff - VisualSVN Server (so badly named it makes me weep) and the Collabnet distribution - the later is Apache only, and is hand rolled on the thighs of virgins, which means that it always seems to appear about three weeks later than everyone else.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | When installing subversion as a service, I used this command:
```
c:\>svnservice -install --daemon --root "c:\documents and settings\my_repository"
```
And then I got this error:
```
Could not create service in service control manager.
```
After looking at some MSDN docs on the service control manager, I tried granting full control to everyone in the permissions on the registry key at HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services, but that hasn't had any effect.
Anybody know what I did wrong, or how to overcome this?
*Note #1: I am running as an administrator on this box*
\*Note #2: I was following the instructions given [here](http://blogs.vertigosoftware.com/teamsystem/archive/2006/01/16/Setting_up_a_Subversion_Server_under_Windows.aspx), so maybe my choice of directory is misguided. And my repository is not actually called "my\_repository". I used the name of an actual project which is currently under source control in *gasp* VSS.\* | [VisualSVN Server](http://www.visualsvn.com/server) installs as a Windows service. It is free, includes Apache, OpenSSL, and a repository / permission management tool. It can also integrate with Active Directory for user authentication. I highly recommend it for hosting SVN on Windows. |
12,765 | <p>This is driving me crazy.</p>
<p>I have this one php file on a test server at work which does not work.. I kept deleting stuff from it till it became </p>
<pre>
<?
print 'Hello';
?>
</pre>
<p>it outputs </p>
<blockquote>
<p>Hello</p>
</blockquote>
<p>if I create a new file and copy / paste the same script to it it works!
Why does this one file give me the strange characters all the time?</p>
| [
{
"answer_id": 12769,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 5,
"selected": true,
"text": "<p>That's the <a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"noreferrer\">BOM (Byte Order Mark)</a> you are seeing.</p>\n\n<p>In your editor, there should be a way to force saving without BOM which will remove the problem.</p>\n"
},
{
"answer_id": 12786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Found it, file -> encoding -> UTF8 with BOM , changed to to UTF :-)</p>\n\n<p>I should ahve asked before wasing time trying to figure it out :-)</p>\n"
},
{
"answer_id": 86059,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Just in case, here is a list of bytes for BOM </p>\n\n<pre>\nEncoding Representation (hexadecimal)\nUTF-8 EF BB BF\nUTF-16 (BE) FE FF\nUTF-16 (LE) FF FE\nUTF-32 (BE) 00 00 FE FF\nUTF-32 (LE) FF FE 00 00\nUTF-7 2B 2F 76, and one of the following bytes: [ 38 | 39 | 2B | 2F ]†\nUTF-1 F7 64 4C\nUTF-EBCDIC DD 73 66 73\nSCSU 0E FE FF\nBOCU-1 FB EE 28 optionally followed by FF†\n</pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is driving me crazy.
I have this one php file on a test server at work which does not work.. I kept deleting stuff from it till it became
```
<?
print 'Hello';
?>
```
it outputs
>
> Hello
>
>
>
if I create a new file and copy / paste the same script to it it works!
Why does this one file give me the strange characters all the time? | That's the [BOM (Byte Order Mark)](http://en.wikipedia.org/wiki/Byte_Order_Mark) you are seeing.
In your editor, there should be a way to force saving without BOM which will remove the problem. |
12,794 | <p>I'm trying to use <code>jQuery</code> to format code blocks, specifically to add a <code><pre></code> tag inside the <code><code></code> tag:</p>
<pre><code>$(document).ready(function() {
$("code").wrapInner("<pre></pre>");
});
</code></pre>
<p>Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert </p>
<pre><code>alert($("code").html());
</code></pre>
<p>I see that IE has inserted some additional text into the pre tag:</p>
<pre><code><PRE jQuery1218834632572="null">
</code></pre>
<p>If I reload the page, the number following jQuery changes.</p>
<p>If I use <code>wrap()</code> instead of <code>wrapInner()</code>, to wrap the <code><pre></code> outside the <code><code></code> tag, both IE and Firefox handle it correctly. But shouldn't <code><pre></code> work <em>inside</em> <code><code></code> as well?</p>
<p>I'd prefer to use <code>wrapInner()</code> because I can then add a CSS class to the <code><pre></code> tag to handle all formatting, but if I use <code>wrap()</code>, I have to put page formatting CSS in the <code><pre></code> tag and text/font formatting in the <code><code></code> tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.</p>
<p>Has anyone else encountered this? Am I missing something?</p>
| [
{
"answer_id": 12804,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using the latest jQuery ?\nWhat if you try </p>\n\n<pre><code>$(\"code\").wrapInner(document.createElement(\"pre\"));\n</code></pre>\n\n<p>Is it any better or do you get the same result ?</p>\n"
},
{
"answer_id": 12810,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>Btw I don't know if it is related but pre tags inside code tags will not validate in strict mode.</p>\n"
},
{
"answer_id": 12983,
"author": "markpasc",
"author_id": 1472,
"author_profile": "https://Stackoverflow.com/users/1472",
"pm_score": 5,
"selected": true,
"text": "<p>That's the difference between <a href=\"http://www.w3.org/TR/html4/struct/global.html#h-7.5.3\" rel=\"noreferrer\">block and inline</a> elements. <a href=\"http://www.w3.org/TR/html4/sgml/dtd.html#block\" rel=\"noreferrer\"><code>pre</code> is a block level element</a>. It's not legal to put it inside a <code>code</code> tag, which <a href=\"http://www.w3.org/TR/html4/struct/text.html#h-9.2.1\" rel=\"noreferrer\">can only contain inline content</a>.</p>\n<p>Because browsers have to support whatever godawful tag soup they might find on the real web, Firefox tries to do what you mean. IE happens to handle it differently, which is fine by the spec; behavior in that case is unspecified, because it should never happen.</p>\n<ul>\n<li>Could you instead <em>replace</em> the <code>code</code> element with the <code>pre</code>? (Because of the block/inline issue, technically that should only work if the elements are inside <a href=\"http://www.w3.org/TR/html4/sgml/dtd.html#flow\" rel=\"noreferrer\">an element with "flow" content</a>, but the browsers might do what you want anyway.)</li>\n<li>Why is it a <code>code</code> element in the first place, if you want <code>pre</code>'s behavior?</li>\n<li>You could also give the <code>code</code> element <code>pre</code>'s whitespace preserving power with the CSS <a href=\"http://www.blooberry.com/indexdot/css/properties/text/whitespace.htm\" rel=\"noreferrer\"><code>white-space: pre</code></a>, but apparently <a href=\"http://www.quirksmode.org/css/whitespace.html\" rel=\"noreferrer\">IE 6 only honors that in Strict Mode</a>.</li>\n</ul>\n"
},
{
"answer_id": 14501,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 1,
"selected": false,
"text": "<p>As markpasc stated, a PRE element inside CODE element is not allowed in HTML. The best solution is to change your HTML code to use <pre><code> (which means a preformatted block that contains code) directly in your HTML for code blocks.</p>\n"
},
{
"answer_id": 7108933,
"author": "Harry B",
"author_id": 897266,
"author_profile": "https://Stackoverflow.com/users/897266",
"pm_score": 1,
"selected": false,
"text": "<p>You could use html() to wrap it:</p>\n\n<pre><code>$('code').each(function(i,e)\n{\n var self = $(e);\n self.html('<pre>' + self.html() + '</pre>');\n});\n</code></pre>\n\n<p>As mentioned above, you'd be better off changing your html. But this solution should work.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311/"
] | I'm trying to use `jQuery` to format code blocks, specifically to add a `<pre>` tag inside the `<code>` tag:
```
$(document).ready(function() {
$("code").wrapInner("<pre></pre>");
});
```
Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert
```
alert($("code").html());
```
I see that IE has inserted some additional text into the pre tag:
```
<PRE jQuery1218834632572="null">
```
If I reload the page, the number following jQuery changes.
If I use `wrap()` instead of `wrapInner()`, to wrap the `<pre>` outside the `<code>` tag, both IE and Firefox handle it correctly. But shouldn't `<pre>` work *inside* `<code>` as well?
I'd prefer to use `wrapInner()` because I can then add a CSS class to the `<pre>` tag to handle all formatting, but if I use `wrap()`, I have to put page formatting CSS in the `<pre>` tag and text/font formatting in the `<code>` tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.
Has anyone else encountered this? Am I missing something? | That's the difference between [block and inline](http://www.w3.org/TR/html4/struct/global.html#h-7.5.3) elements. [`pre` is a block level element](http://www.w3.org/TR/html4/sgml/dtd.html#block). It's not legal to put it inside a `code` tag, which [can only contain inline content](http://www.w3.org/TR/html4/struct/text.html#h-9.2.1).
Because browsers have to support whatever godawful tag soup they might find on the real web, Firefox tries to do what you mean. IE happens to handle it differently, which is fine by the spec; behavior in that case is unspecified, because it should never happen.
* Could you instead *replace* the `code` element with the `pre`? (Because of the block/inline issue, technically that should only work if the elements are inside [an element with "flow" content](http://www.w3.org/TR/html4/sgml/dtd.html#flow), but the browsers might do what you want anyway.)
* Why is it a `code` element in the first place, if you want `pre`'s behavior?
* You could also give the `code` element `pre`'s whitespace preserving power with the CSS [`white-space: pre`](http://www.blooberry.com/indexdot/css/properties/text/whitespace.htm), but apparently [IE 6 only honors that in Strict Mode](http://www.quirksmode.org/css/whitespace.html). |
12,855 | <p>I have a query where I am searching against a string:</p>
<pre><code>SELECT county FROM city WHERE UPPER(name) = 'SAN FRANCISCO';
</code></pre>
<p>Now, this works fine, but it doesn't scale well, and I need to optimize it. I have <a href="http://www.ibm.com/developerworks/db2/library/techarticle/0203adamache/0203adamache.html" rel="nofollow noreferrer">found an option</a> along the lines of creating a generated view, or something like that, but I was hoping for a simpler solution using an index.</p>
<p>We are using DB2, and I really want to use an <a href="http://ibmsystemsmag.blogs.com/db2utor/2007/11/db2-9-index-wit.html" rel="nofollow noreferrer">expression in an index</a>, but this option seems to only be available on z/OS, however we are running Linux. I tried the expression index anyways:</p>
<pre><code>CREATE INDEX city_upper_name_idx
ON city UPPER(name) ALLOW REVERSE SCANS;
</code></pre>
<p>But of course, it chokes on the UPPER(name).</p>
<p>Is there another way I can create an index or something similar in this manner such that I don't have to restructure my existing queries to use a new generated view, or alter my existing columns, or any other such intrusive change?</p>
<p>EDIT: I'm open to hearing solutions for other databases... it might carry over to DB2...</p>
| [
{
"answer_id": 12886,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 3,
"selected": false,
"text": "<p>You could add an indexed column holding a numerical hash key of the city name. (With duplicates allowed).</p>\n\n<p>Then you could do a multi-clause where :</p>\n\n<pre><code>hash = [compute hash key for 'SAN FRANCISCO']\n\nSELECT county \nFROM city \nWHERE cityHash = hash \n AND UPPER(name) = 'SAN FRANCISCO' ;\n</code></pre>\n\n<p>Alternatively, go through your db manual and look at the options for creating table indexes. There might be something helpful.</p>\n"
},
{
"answer_id": 12962,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 1,
"selected": false,
"text": "<p>Oracle supports function-based indexes. Their canonical example:</p>\n\n<pre><code> create index emp_upper_idx on emp(upper(ename)); \n</code></pre>\n"
},
{
"answer_id": 13108,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 1,
"selected": false,
"text": "<p>PostgreSQL also supports indexing the results of a function:</p>\n\n<pre><code>CREATE INDEX mytable_lower_col1_idx ON mytable (lower(col1));\n</code></pre>\n\n<p>The only other option I can think of is to de-normalize your data a bit by creating another column to hold the upper-case version (updated by triggers) and index that. Blech!</p>\n"
},
{
"answer_id": 16544,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know whether this would work in DB2, but I'll tell you how I'd do this in SQL Server. I <em>think</em> the way MSSQL does this is ANSI standard, though the specific collation strings may differ. Anyway, if you can do this without trashing the rest of your application -- are there other places where the \"name\" column needs to be case-sensitive? -- try making that whole column case-insensitive by changing the collation, then index the column.</p>\n\n<pre><code>ALTER TABLE city ALTER COLUMN name nvarchar(200) \n COLLATE SQL_Latin1_General_CP1_CI_AS\n</code></pre>\n\n<p>...where \"nvarchar(200)\" stands in for whatever's your current column data type. The \"CI\" part of the collation string is what marks it as case-insensitive in MSSQL.</p>\n\n<p>To explain... my understanding is that the index will store values in the order of the indexed column's collation. Making the column's collation be case-insensitive would make the index store 'San Francisco', 'SAN FRANCISCO', and 'san francisco' all together. Then you should just have to remove the \"UPPER()\" from your query, and DB2 should know that it can use your index.</p>\n\n<p>Again, this is based solely on what I know about SQL Server, plus a couple minutes looking at the SQL-92 spec; it may or may not work for DB2.</p>\n"
},
{
"answer_id": 42789,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 1,
"selected": false,
"text": "<p>DB2 isn't strong regarding collation. And it doesn't have function-based indexes.</p>\n\n<p>Niek Sanders's suggestion would work, if you can accept that the hashing has to happen in your application (as DB2 doesn't have SHA or MD5 functions, as far as I know).</p>\n\n<p>However, if I were you, I'd create a materialized view (MQT == Materialized Query Table, in db2 parlance) using <a href=\"http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0000927.html\" rel=\"nofollow noreferrer\">CREATE TABLE AS</a>, adding a column with a pre-computed upper-case variant of the name. Note: You may add indexes to materialized views in DB2.</p>\n"
},
{
"answer_id": 419382,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>Short answer, no.</p>\n\n<p>Long answer, yes if you're running on the mainframe, but you're not, so you have to use other trickery.</p>\n\n<p>DB2 (as of DB2/LUW v8) now has generated columns so you can:</p>\n\n<pre><code>CREATE TABLE tbl (\n lname VARCHAR(20),\n fname VARCHAR(20),\n ulname VARCHAR(20) GENERATED ALWAYS AS UPPER(lname)\n);\n</code></pre>\n\n<p>and then create an index on ulname. I'm not sure you're going to get it simpler than that.</p>\n\n<p>Before that, you used to have to use a combination of insert and update triggers to ensure the ulname column was kept in sync, and this was a nightmare to maintain. Also, now that this functionality is part of the core DBMS, it's been highly optimized (it's much faster than the trigger-based solution) and doesn't get in the way of real user triggers, so no extra DB objects to maintain.</p>\n\n<p>See <a href=\"http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/c0007004.htm\" rel=\"noreferrer\">here</a> for details.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I have a query where I am searching against a string:
```
SELECT county FROM city WHERE UPPER(name) = 'SAN FRANCISCO';
```
Now, this works fine, but it doesn't scale well, and I need to optimize it. I have [found an option](http://www.ibm.com/developerworks/db2/library/techarticle/0203adamache/0203adamache.html) along the lines of creating a generated view, or something like that, but I was hoping for a simpler solution using an index.
We are using DB2, and I really want to use an [expression in an index](http://ibmsystemsmag.blogs.com/db2utor/2007/11/db2-9-index-wit.html), but this option seems to only be available on z/OS, however we are running Linux. I tried the expression index anyways:
```
CREATE INDEX city_upper_name_idx
ON city UPPER(name) ALLOW REVERSE SCANS;
```
But of course, it chokes on the UPPER(name).
Is there another way I can create an index or something similar in this manner such that I don't have to restructure my existing queries to use a new generated view, or alter my existing columns, or any other such intrusive change?
EDIT: I'm open to hearing solutions for other databases... it might carry over to DB2... | You could add an indexed column holding a numerical hash key of the city name. (With duplicates allowed).
Then you could do a multi-clause where :
```
hash = [compute hash key for 'SAN FRANCISCO']
SELECT county
FROM city
WHERE cityHash = hash
AND UPPER(name) = 'SAN FRANCISCO' ;
```
Alternatively, go through your db manual and look at the options for creating table indexes. There might be something helpful. |
12,865 | <p>Got a bluescreen in windows while cloning a mercurial repository.</p>
<p>After reboot, I now get this message for almost all hg commands:</p>
<pre>
c:\src\>hg commit
waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\
x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
interrupted!
</pre>
<p>Google is no help.</p>
<p>Any tips?</p>
| [
{
"answer_id": 12879,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 10,
"selected": true,
"text": "<p>When \"waiting for lock on repository\", delete the repository file: <code>.hg/wlock</code> (or it may be in <code><code>.hg/store/lock</code></code>)</p>\n\n<p>When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true).</p>\n"
},
{
"answer_id": 13357,
"author": "markpasc",
"author_id": 1472,
"author_profile": "https://Stackoverflow.com/users/1472",
"pm_score": 2,
"selected": false,
"text": "<p>If the locked repo was the original, I can't imagine it was <em>modifying</em> it to clone it, so it was only preventing you from changing it in the middle and messing up the clone. It should be fine after removing the lock.</p>\n\n<p>The new cloned copy (if it was a local clone) could be in any sort of malformed state, though, so you should throw it out and start it over. (If it was a remote clone, I would hope it failed and already threw out the incomplete copy.)</p>\n"
},
{
"answer_id": 2960524,
"author": "Tiago Matos",
"author_id": 356772,
"author_profile": "https://Stackoverflow.com/users/356772",
"pm_score": 8,
"selected": false,
"text": "<p>When <code>waiting for lock on working directory</code>, delete <code>.hg/wlock</code>.</p>\n"
},
{
"answer_id": 7981259,
"author": "Brad O",
"author_id": 1025721,
"author_profile": "https://Stackoverflow.com/users/1025721",
"pm_score": 4,
"selected": false,
"text": "<p>I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:</p>\n\n<ol>\n<li>I've seen this in the wild, but rarely, and only on Windows machines.</li>\n<li>Deleting lock files is the easiest fix, BUT you have to make sure nothing else is accessing the repository. (If the lock is a string of zeros, this is almost certainly true).</li>\n</ol>\n\n<p>(For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)</p>\n"
},
{
"answer_id": 11445420,
"author": "matt wilkie",
"author_id": 14420,
"author_profile": "https://Stackoverflow.com/users/14420",
"pm_score": 1,
"selected": false,
"text": "<p>If it only happens on mapped drives it might be bug <a href=\"https://bitbucket.org/tortoisehg/thg/issue/889/cant-commit-file-over-network-share\" rel=\"nofollow\">https://bitbucket.org/tortoisehg/thg/issue/889/cant-commit-file-over-network-share</a>. Using UNC path instead of drive letter seems to sidestep the issue.</p>\n"
},
{
"answer_id": 16423091,
"author": "Ian Kemp",
"author_id": 70345,
"author_profile": "https://Stackoverflow.com/users/70345",
"pm_score": 4,
"selected": false,
"text": "<p>Coworker had this exact problem today, after a BSoD while trying to push. He had to:</p>\n\n<ul>\n<li>delete the file <code>.hg/store/lock</code> (as per <a href=\"https://stackoverflow.com/a/12879/70345\">the accepted answer</a>)</li>\n<li>delete the file <code>.hg/store/phaseroots</code> (as per <a href=\"https://bitbucket.org/tortoisehg/thg/issue/2366/valueerror-need-more-than-1-value-to#comment-2867642\" rel=\"noreferrer\">this TortoiseHG bug report</a>)</li>\n</ul>\n\n<p>Then his repo worked again.</p>\n\n<p><strong>EDIT:</strong> As per @Marmoute's comment - when dealing with lock-related issues, using <code>hg debuglock</code> is a safer alternative to blindly deleting the <code>.hg/store/lock</code> file.</p>\n"
},
{
"answer_id": 25089553,
"author": "Krazy Glew",
"author_id": 1051115,
"author_profile": "https://Stackoverflow.com/users/1051115",
"pm_score": 3,
"selected": false,
"text": "<p>I do not expect this to be a winning answer, but it is a fairly unusual situation.\nMentioning in case someone other than me runs into it.</p>\n\n<p>Today I got the \"waiting for lock on repository\" on an hg push command.</p>\n\n<p>When I killed the hung hg command I could see no .hg/store/lock</p>\n\n<p>When I looked for .hg/store/lock while the command was hung, it existed. But the lockfile was deleted when the hg command was killed.</p>\n\n<p>When I went to the target of the push, and executed hg pull, no problem.</p>\n\n<p>Eventually I realized that the process ID on the hg push was lock waiting message was changing each time. It turns out that the \"hg push\" was hanging waiting for a lock held by itself (or possibly a subprocess, I did not investigate further).</p>\n\n<p>It turns out that the two workspaces, let's call them A and B, had .hg trees shared by symlink:</p>\n\n<pre><code>A/.hg --symlinked-to--> B/.hg\n</code></pre>\n\n<p>This is NOT a good thing to do with Mercurial. Mercurial does not understand the concept of two workspaces sharing the same repository. I do understand, however, how somebody coming to Mercurial from another VCS might want this (Perforce does, although not a DVCS; the Bazaar DVCS reportedly can do so). I am surprised that a symlinked REP-ROOT/.hg works at all, although it seems to except for this push.</p>\n"
},
{
"answer_id": 27111373,
"author": "JWWalker",
"author_id": 309425,
"author_profile": "https://Stackoverflow.com/users/309425",
"pm_score": 2,
"selected": false,
"text": "<p>I encountered this problem on Mac OS X 10.7.5 and Mercurial 2.6.2 when trying to push. After upgrading to Mercurial 3.2.1, I got \"no changes found\" instead of \"waiting for lock on repository\". I found out that somehow the default path had gotten set to point to the same repository, so it's not too surprising that Mercurial would get confused.</p>\n"
},
{
"answer_id": 29005897,
"author": "Ivan Dulov",
"author_id": 3543982,
"author_profile": "https://Stackoverflow.com/users/3543982",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same problem on Win 7. \nThe solution was to remove following files: </p>\n\n<ol>\n<li>.hg/store/phaseroots</li>\n<li>.hg/wlock</li>\n</ol>\n\n<p>As for .hg/store/lock - there was no such file.</p>\n"
},
{
"answer_id": 41527661,
"author": "Thomas Sharpless",
"author_id": 1789624,
"author_profile": "https://Stackoverflow.com/users/1789624",
"pm_score": 6,
"selected": false,
"text": "<p>I had this problem with no detectable lock files. I found the solution here: <a href=\"http://schooner.uwaterloo.ca/twiki/bin/view/MAG/HgLockError\" rel=\"noreferrer\">http://schooner.uwaterloo.ca/twiki/bin/view/MAG/HgLockError</a></p>\n\n<p>Here is a transcript from Tortoise Hg Workbench console</p>\n\n<pre><code>% hg debuglocks\nlock: user None, process 7168, host HPv32 (114213199s)\nwlock: free\n[command returned code 1 Sat Jan 07 18:00:18 2017]\n% hg debuglocks --force-lock\n[command completed successfully Sat Jan 07 18:03:15 2017]\ncmdserver: Process crashed\nPaniniDev% hg debuglocks\n% hg debuglocks\nlock: free\nwlock: free\n[command completed successfully Sat Jan 07 18:03:30 2017]\n</code></pre>\n\n<p>After this the aborted pull ran sucessfully.</p>\n\n<p>The lock had been set more than 2 years ago, by a process on a machine that is no longer on the LAN. Shame on the hg developers for a) not documenting locks adequately; b) not timestamping them for automatic removal when they get stale.</p>\n"
},
{
"answer_id": 51491278,
"author": "user10125940",
"author_id": 10125940,
"author_profile": "https://Stackoverflow.com/users/10125940",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same problem. Got the following message when I tried to commit:</p>\n\n<pre><code>waiting for lock on working directory of <MyProject> held by '...'\n</code></pre>\n\n<p><code>hg debuglock</code> showed this:</p>\n\n<pre><code>lock: free\nwlock: (66722s)\n</code></pre>\n\n<p>So I did the following command, and that fixed the problem for me:</p>\n\n<pre><code>hg debuglocks -W\n</code></pre>\n\n<p>Using Win7 and TortoiseHg 4.8.7.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | Got a bluescreen in windows while cloning a mercurial repository.
After reboot, I now get this message for almost all hg commands:
```
c:\src\>hg commit
waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\
x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
interrupted!
```
Google is no help.
Any tips? | When "waiting for lock on repository", delete the repository file: `.hg/wlock` (or it may be in ``.hg/store/lock``)
When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true). |
12,870 | <p>This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. </p>
<p>I'd prefer to do it right. Here is the situation:</p>
<p>I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this:
Summer (5-1 to 8-31)
Spring (3-1 to 4-30)
Fall (9-1 to 10-31)
Winter (11-1 to 2-28) </p>
<p>An example might be:</p>
<p>If I'm in group A, here would be my allowed times:
Winter: Mondays only
Spring: Tues, Thurs, Sat
Summer: Any Day
Fall: Tues, Thurs, Sat</p>
<p>If I was writing this in PHP I would use arrays like this:</p>
<pre><code>//M=Monday,t=Tuesday,T=Thursday.... etc
$schedule["A"]["Winter"]='M';
$schedule["A"]["Spring"]='tTS';
$schedule["A"]["Summer"]='Any';
$schedule["A"]["Fall"]='tTS';
$schedule["B"]["Winter"]='t';
</code></pre>
<p>I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish.</p>
<p>I will also need to setup arrays to determine what season I'm in:</p>
<pre><code>$seasons["Summer"]["start"]=0501;
$seasons["Summer"]["end"]=0801;
</code></pre>
<p>Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any).</p>
| [
{
"answer_id": 12878,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": true,
"text": "<p>You could do essentially the same code with Hashtables (or some other Map):</p>\n\n<pre><code>Hashtable<String, Hashtable<String, String>> schedule\n = new Hashtable<String, Hashtable<String, String>>();\nschedule.put(\"A\", new Hashtable<String, String>());\nschedule.put(\"B\", new Hashtable<String, String>());\nschedule.put(\"C\", new Hashtable<String, String>());\nschedule.put(\"D\", new Hashtable<String, String>());\nschedule.put(\"E\", new Hashtable<String, String>());\n\nschedule.get(\"A\").put(\"Winter\", \"M\");\nschedule.get(\"A\").put(\"Spring\", \"tTS\");\n// Etc...\n</code></pre>\n\n<p>Not as elegant, but then again, Java isn't a dynamic language, and it doesn't have hashes on the language level.</p>\n\n<p>Note: You might be able to do a better solution, this just popped in my head as I read your question.</p>\n"
},
{
"answer_id": 12885,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>There is no pretty solution. Java just doesn't do things like this well. Mike's solution is pretty much the way to do it if you want strings as the indices (keys). Another option if the hash-of-hashes setup is too ugly is to append the strings together (shamelessly stolen from Mike and modified):</p>\n\n<pre><code>Hashtable<String, String> schedule = new Hashtable<String, String>();\nschedule.put(\"A-Winter\", \"M\");\nschedule.put(\"A-Spring\", \"tTS\");\n</code></pre>\n\n<p>and then lookup:</p>\n\n<pre><code>String val = schedule.get(group + \"-\" + season);\n</code></pre>\n\n<p>If you're unhappy with the general ugliness (and I don't blame you), put it all behind a method call:</p>\n\n<pre><code>String whenCanIWater(String group, Date date) { /* ugliness here */ }\n</code></pre>\n"
},
{
"answer_id": 12899,
"author": "Wing",
"author_id": 958,
"author_profile": "https://Stackoverflow.com/users/958",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not a Java programmer, but getting away from Java and just thinking in terms that are more language agnostic - a cleaner way to do it might be to use either constants or enumerated types. This should work in any langauge that supports multi-dimensional arrays.</p>\n\n<p>If using named constants, where, for example: </p>\n\n<pre><code>int A = 0;\nint B = 1;\nint C = 2;\nint D = 3;\n\nint Spring = 0; \nint Summer = 1;\nint Winter = 2; \nint Fall = 3;\n...\n</code></pre>\n\n<p>Then the constants serve as more readable array subscripts:</p>\n\n<pre><code>schedule[A][Winter]=\"M\";\nschedule[A][Spring]=\"tTS\";\nschedule[A][Summer]=\"Any\";\nschedule[A][Fall]=\"tTS\";\nschedule[B][Winter]=\"t\";\n</code></pre>\n\n<p>Using enumerated types:</p>\n\n<pre><code>enum groups\n{\n A = 0,\n B = 1,\n C = 2,\n D = 3\n}\n\nenum seasons\n{\n Spring = 0,\n Summer = 1,\n Fall = 2,\n Winter = 3\n}\n...\nschedule[groups.A][seasons.Winter]=\"M\";\nschedule[groups.A][seasons.Spring]=\"tTS\";\nschedule[groups.A][seasons.Summer]=\"Any\";\nschedule[groups.A][seasons.Fall]=\"tTS\";\nschedule[groups.B][seasons.Winter]=\"t\";\n</code></pre>\n"
},
{
"answer_id": 12918,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "<p>Don't try to be as dynamic as PHP is. You could try to first <strong>define</strong> what you need.</p>\n\n<pre><code>interface Season\n{\n public string getDays();\n}\n\ninterface User\n{\n public Season getWinter();\n public Season getSpring();\n public Season getSummer();\n public Season getFall();\n}\n\ninterface UserMap\n{\n public User getUser(string name);\n}\n</code></pre>\n\n<p>And please, read the documentation of <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html\" rel=\"noreferrer\">Hashtable</a> before using it. This class is synchronized which means that each call is protected against multithreading which really slows the access when you don't need the extra protection. Please use any <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Map.html\" rel=\"noreferrer\">Map</a> implementation instead like <a href=\"http://java.sun.com/javase/6/docs/api/java/util/HashMap.html\" rel=\"noreferrer\">HashMap</a> or <a href=\"http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html\" rel=\"noreferrer\">TreeMap</a>.</p>\n"
},
{
"answer_id": 12923,
"author": "Ian Good",
"author_id": 1195,
"author_profile": "https://Stackoverflow.com/users/1195",
"pm_score": 3,
"selected": false,
"text": "<p>It seems like everyone is trying to find the Java way to do it like you're doing it in PHP, instead of the way it ought to be done in Java. Just consider each piece of your array an object, or, at the very least, the first level of the array as an object and each sub level as variables inside the object. The build a data structure that you populate with said objects and access the objects through the data structure's given accessors.</p>\n\n<p>Something like:</p>\n\n<pre><code>class Schedule\n{\n private String group;\n private String season;\n private String rundays;\n public Schedule() { this.group = null; this.season = null; this.rundays= null; }\n public void setGroup(String g) { this.group = g; }\n public String getGroup() { return this.group; }\n ...\n}\n\npublic ArrayList<Schedule> schedules = new ArrayList<Schedule>();\nSchedule s = new Schedule();\ns.setGroup(...);\n...\nschedules.add(s);\n...\n</code></pre>\n\n<p>Of course that probably isn't right either. I'd make each season an object, and maybe each weekday list as an object too. Anyway, its more easily reused, understood, and extensible than a hobbled-together Hashtable that tries to imitate your PHP code. Of course, PHP has objects too, and you should use them in a similar fashion instead of your uber-arrays, wherever possible. I do understand the temptation to cheat, though. PHP makes it so easy, and so fun!</p>\n"
},
{
"answer_id": 12932,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 1,
"selected": false,
"text": "<p>I agree that you should definitely put this logic behind the clean interface of:</p>\n\n<pre><code>public String lookupDays(String group, String date);\n</code></pre>\n\n<p>but maybe you should stick the data in a properties file. I'm not against hardcoding this data in your source files but, as you noticed, Java can be pretty wordy when it comes to nested Collections. Your file might looks like:</p>\n\n<blockquote>\n <p>A.Summer=M<br>\n A.Spring=tTS<br>\n B.Summer=T</p>\n</blockquote>\n\n<p>Usually I don't like to move static data like this to an external file because it increases the \"distance\" between the data and the code that uses it. However, whenever you're dealing with nested Collections, especially maps, things can get real ugly, real fast.</p>\n\n<p>If you don't like this idea, maybe you can do something like this:</p>\n\n<pre><code>public class WaterScheduler\n{\n private static final Map<String, String> GROUP2SEASON = new HashMap<String, String>();\n static\n {\n addEntry(\"A\", \"Summer\", \"M\");\n addEntry(\"A\", \"Spring\", \"tTS\");\n addEntry(\"B\", \"Summer\", \"T\");\n }\n\n private static void addEntry(String group, String season, String value)\n {\n GROUP2SEASON.put(group + \".\" + season, value);\n }\n\n}\n</code></pre>\n\n<p>You lose some readability but at least the data is closer to where it's going to be used.</p>\n"
},
{
"answer_id": 12941,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>I'm totally at a loss as to why some of you seem to think that throwing gobs of objects at the code is the way to go. For example, there are exactly four seasons, and they don't <em>do</em> or <em>store</em> anything. How does it simplify anything to make them objects? Wing is quite right that these should probably be <strong><em>constants</em></strong> (or maybe enums).</p>\n\n<p>What Bruce needs, at it's heart, is simply a lookup table. He doesn't need a hierarchy of objects and interfaces; he needs a way to look up a schedule based on a season and a group identifier. Turning things into objects only makes sense if they have responsibilities or state. If they have neither, then they are simply identifiers, and building special objects for them just makes the codebase larger.</p>\n\n<p>You <em>could</em> build, e.g., <code>Group</code> objects that each contain a set of schedule strings (one for each season), but if all the <code>Group</code> object does is provide lookup functionality, then you've reinvented the lookup table in a much less intuitive fashion. If he has to look up the group, and then lookup the schedule, all he has is a two-step lookup table that took longer to code, is more likely to be buggy, and will be harder to maintain.</p>\n"
},
{
"answer_id": 12953,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 1,
"selected": false,
"text": "<p>A better solution would perhaps be to put all that data into a database, instead of hard-coding it in your sources or using properties files.</p>\n\n<p>Using a database will be much easier to maintain, and there are a <a href=\"http://www.mysql.com/\" rel=\"nofollow noreferrer\">variety</a> <a href=\"http://www.postgresql.org/\" rel=\"nofollow noreferrer\">of</a> <a href=\"http://hsqldb.sourceforge.net/\" rel=\"nofollow noreferrer\">free</a> <a href=\"http://db.apache.org/derby/\" rel=\"nofollow noreferrer\">database</a> engines to choose from.</p>\n\n<p>Two of these database engines are implemented entirely in Java and can be embedded in an application just by including a jar file. It's a little heavyweight, sure, but it's a lot more scalable and easier to maintain. Just because there are 20 records today doesn't mean there won't be more later due to changing requirements or feature creep.</p>\n\n<p>If, in a few weeks or months, you decide you want to add, say, time of day watering restrictions, it will be much easier to add that functionality if you're already using a database. Even if that never happens, then you've spent a few hours learning how to embed a database in an application.</p>\n"
},
{
"answer_id": 12992,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 1,
"selected": false,
"text": "<p>Does the \"date\" have to be a parameter? If you're just showing the current watering schedule the WateringSchedule class itself can figure out what day it is, and therefore what season it is. Then just have a method which returns a map where the Key is the group letter. Something like:</p>\n\n<pre><code>public Map<String,List<String>> getGroupToScheduledDaysMap() {\n // instantiate a date or whatever to decide what Map to return\n}\n</code></pre>\n\n<p>Then in the JSP page</p>\n\n<pre><code><c:forEach var=\"day\" items=\"${scheduler.groupToScheduledDaysMap[\"A\"]}\">\n ${day}\n</c:forEach>\n</code></pre>\n\n<p>If you need to show the schedules for more than one season, you should have a method in the WateringSchedule class that returns a map where Seasons are the keys, and then Maps of groupToScheduledDays are the values.</p>\n"
},
{
"answer_id": 13037,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 2,
"selected": false,
"text": "<p>Here's one way it <em>could</em> look like, you can figure the rest out:</p>\n\n<pre><code>A = new Group();\nA.getSeason(Seasons.WINTER).addDay(Days.MONDAY);\nA.getSeason(Seasons.SPRING).addDay(Days.TUESDAY).addDay(Days.THURSDAY);\nA.getSeason(Seasons.SPRING).addDays(Days.MONDAY, Days.TUESDAY, ...);\n\nschedule = new Schedule();\nschedule.addWateringGroup( A );\n</code></pre>\n"
},
{
"answer_id": 13099,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "<p>I'm with those that suggest encapsulating function in objects.</p>\n\n<pre><code>import java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Group {\n\n private String groupName;\n\n private Map<Season, Set<Day>> schedule;\n\n public String getGroupName() {\n return groupName;\n }\n\n public void setGroupName(String groupName) {\n this.groupName = groupName;\n }\n\n public Map<Season, Set<Day>> getSchedule() {\n return schedule;\n }\n\n public void setSchedule(Map<Season, Set<Day>> schedule) {\n this.schedule = schedule;\n }\n\n public String getScheduleFor(Date date) {\n Season now = Season.getSeason(date);\n Set<Day> days = schedule.get(now);\n return Day.getDaysForDisplay(days);\n }\n\n}\n</code></pre>\n\n<p>EDIT: Also, your date ranges don't take leap years into account:</p>\n\n<blockquote>\n <p>Our seasons look like this: Summer\n (5-1 to 8-31) Spring (3-1 to 4-30)\n Fall (9-1 to 10-31) Winter (11-1 to\n 2-28)</p>\n</blockquote>\n"
},
{
"answer_id": 48512739,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 0,
"selected": false,
"text": "<h1>tl;dr</h1>\n\n<p>Using modern Java language features and classes, define your own enums to represent the seasons and groups.</p>\n\n<pre><code>Schedule.daysForGroupOnDate( \n Group.D , \n LocalDate.now()\n) \n</code></pre>\n\n<p>That method yields a <code>Set</code> of <code>DayOfWeek</code> enum objects (not mere text!), such as <code>DayOfWeek.TUESDAY</code> & <code>DayOfWeek.THURSDAY</code>.</p>\n\n<h1>Modern Java</h1>\n\n<blockquote>\n <p>Can anyone suggest a really cool way to do this?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>Modern Java has built-in classes, collections, and enums to help you with this problem.</p>\n\n<p>The <em>java.time</em> framework built into Java offers the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/Month.html\" rel=\"nofollow noreferrer\"><code>Month</code></a> enum and <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/DayOfWeek.html\" rel=\"nofollow noreferrer\"><code>DayOfWeek</code></a> enum. </p>\n\n<p>The <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/EnumSet.html\" rel=\"nofollow noreferrer\"><code>EnumSet</code></a> and <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/EnumMap.html\" rel=\"nofollow noreferrer\"><code>EnumMap</code></a> provide implementations of <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Set.html\" rel=\"nofollow noreferrer\"><code>Set</code></a> and <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\"><code>Map</code></a> that are optimized for use with enums for fast execution in very little memory.</p>\n\n<p>You can define your own <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/Enum.html\" rel=\"nofollow noreferrer\">enums</a> to represent your season and your groups (A, B, and so on). The enum facility in Java is far more useful and powerful than seen in other languages. If not familiar, see the <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow noreferrer\"><em>Oracle Tutorial</em></a>. </p>\n\n<p>The simple syntax of defining your own enums actually provides much of the functionality needed to solve this Question, eliminating some complicated coding. New <a href=\"http://iteratrlearning.com/java9/2016/11/09/java9-collection-factory-methods.html\" rel=\"nofollow noreferrer\">literals syntax</a> for sets and maps in the <a href=\"https://stackoverflow.com/q/43533835/642706\">collections factory methods</a> in Java 9 (<a href=\"http://openjdk.java.net/jeps/269\" rel=\"nofollow noreferrer\">JEP 269</a>) makes the code even simpler now.</p>\n\n<p>Here is a complete working app. <strong>Note how little code</strong> there is for algorithms. Defining your own custom enums does most of the heavy-lifting. </p>\n\n<p>One caveat with this app code: It assumes nothing changes in your business definitions, or at least if there is a change you only care about the current rules, “latest is greatest”. If your rules change over time and you need to represent all the past, present, and future versions, I would build a very different app, probably with a database to store the rules. But this app here solves the Question as asked. </p>\n\n<h2><code>Season</code></h2>\n\n<p>Represent your season as an enum <code>Season</code>. Each season object holds a <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/List.html\" rel=\"nofollow noreferrer\"><code>List</code></a> of <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/Month.html\" rel=\"nofollow noreferrer\"><code>Month</code></a> enum objects that define the length of that particular season. The new <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/List.html#of-E-\" rel=\"nofollow noreferrer\"><code>List.of</code></a> syntax added to Java 9 defines an immutable list in a literals syntax via static factory methods.</p>\n\n<pre><code>package com.basilbourque.watering;\n\nimport java.time.LocalDate;\nimport java.time.Month;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic enum Season\n{\n SPRING( List.of( Month.MARCH , Month.APRIL ) ),\n SUMMER( List.of( Month.MAY , Month.JUNE, Month.JULY , Month.AUGUST ) ),\n FALL( List.of( Month.SEPTEMBER , Month.OCTOBER ) ),\n WINTER( List.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY ) );\n\n private List< Month > months;\n\n // Constructor\n Season ( List < Month > monthsArg )\n {\n this.months = monthsArg;\n }\n\n public List < Month > getMonths ( )\n {\n return this.months;\n }\n\n // For any given month, determine the season.\n static public Season ofLocalMonth ( Month monthArg )\n {\n Season s = null;\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n if ( season.getMonths().contains( monthArg ) )\n {\n s = season;\n break; // Bail out of this FOR loop.\n }\n }\n return s;\n }\n\n // For any given date, determine the season.\n static public Season ofLocalDate ( LocalDate localDateArg )\n {\n Month month = localDateArg.getMonth();\n Season s = Season.ofLocalMonth( month );\n return s;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n System.out.println( \"Season: \" + season.toString() + \" = \" + season.getMonths() );\n }\n }\n}\n</code></pre>\n\n<h2><code>Group</code></h2>\n\n<p>Represent each grouping of customers’ lawns/yards, (A, B, C, D, E) as an enum named <code>Group</code>. Each of these enum objects holds a <code>Map</code>, mapping a <code>Season</code> enum object to a <code>Set</code> of <code>DayOfWeek</code> enum objects. For example, <code>Group.A</code> in <code>Season.SPRING</code> allows watering on two days, <code>DayOfWeek.TUESDAY</code> & <code>DayOfWeek.THURSDAY</code>.</p>\n\n<pre><code>package com.basilbourque.watering;\n\nimport java.time.DayOfWeek;\nimport java.util.EnumMap;\nimport java.util.EnumSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic enum Group\n{\n A(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.TUESDAY )\n )\n ),\n B(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.FRIDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.FRIDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.FRIDAY )\n )\n ),\n C(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.MONDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.MONDAY , DayOfWeek.TUESDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.MONDAY )\n )\n ),\n D(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.WEDNESDAY , DayOfWeek.FRIDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.FRIDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.WEDNESDAY )\n )\n ),\n E(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.TUESDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.WEDNESDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.WEDNESDAY )\n )\n );\n\n private Map < Season, Set < DayOfWeek > > map;\n\n // Constructor\n Group ( Map < Season, Set < DayOfWeek > > mapArg )\n {\n this.map = mapArg;\n }\n\n // Getter\n private Map < Season, Set < DayOfWeek > > getMapOfSeasonToDaysOfWeek() {\n return this.map ;\n }\n\n // Retrieve the DayOfWeek set for this particular Group.\n public Set<DayOfWeek> daysForSeason (Season season ) {\n Set<DayOfWeek> days = this.map.get( season ) ; // Retrieve the value (set of days) for this key (a season) for this particular grouping of lawns/yards.\n return days;\n }\n\n\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Group group : EnumSet.allOf( Group.class ) )\n {\n System.out.println( \"Group: \" + group.toString() + \" = \" + group.getMapOfSeasonToDaysOfWeek() );\n }\n }\n\n}\n</code></pre>\n\n<h2><code>Schedule</code></h2>\n\n<p>Pull it all together in this <code>Schedule</code> class. </p>\n\n<p>This class makes use of the two enums defined above to get useful work done. The only method implemented so far tells you which days of the week are allowed for a particular group on a particular date. The method determines which <code>Season</code> applies for that date. </p>\n\n<p>Run the <code>main</code> method here to dump the contents of our two enums, and report on the days of the week allowing for watering in each group for a particular hard-coded date.</p>\n\n<pre><code>package com.basilbourque.watering;\n\nimport java.time.DayOfWeek;\nimport java.time.LocalDate;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.time.temporal.ChronoField;\nimport java.time.temporal.IsoFields;\nimport java.util.EnumSet;\nimport java.util.Set;\n\npublic class Schedule\n{\n static private DateTimeFormatter isoWeekFormatter = DateTimeFormatter.ofPattern( \"uuuu-'W'ww\" ) ;\n\n static public Set < DayOfWeek > daysForGroupOnDate ( Group group , LocalDate localDate )\n {\n Season season = Season.ofLocalDate( localDate );\n Set < DayOfWeek > days = group.daysForSeason( season );\n return days;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n Season.main( null );\n Group.main( null );\n // Dump all these enum objects to console.\n for ( Group group : EnumSet.allOf( Group.class ) )\n {\n LocalDate localDate = LocalDate.now( ZoneId.of( \"Africa/Tunis\" ) );\n Set < DayOfWeek > days = Schedule.daysForGroupOnDate( group , localDate );\n String week = localDate.format( Schedule.isoWeekFormatter ) ; // Standard ISO 8601 week, where week number one has the first Thursday of the calendar year, and week starts on Monday, so year is either 52 or 53 weeks long.\n String message = \"Group \" + group + \" – Watering days on \" + localDate + \" week # \" + week + \" is: \" + days;\n System.out.println( message );\n }\n }\n}\n</code></pre>\n\n<h2>Console</h2>\n\n<p>When running <code>Schedule.main</code>, we see this dumped to the console.</p>\n\n<blockquote>\n <p>Season: SPRING = [MARCH, APRIL]</p>\n \n <p>Season: SUMMER = [MAY, JUNE, JULY, AUGUST]</p>\n \n <p>Season: FALL = [SEPTEMBER, OCTOBER]</p>\n \n <p>Season: WINTER = [NOVEMBER, DECEMBER, JANUARY, FEBRUARY]</p>\n \n <p>Group: A = {SPRING=[TUESDAY, THURSDAY], FALL=[TUESDAY, THURSDAY], SUMMER=[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY], WINTER=[TUESDAY]}</p>\n \n <p>Group: B = {SPRING=[FRIDAY], FALL=[TUESDAY, FRIDAY], SUMMER=[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY], WINTER=[FRIDAY]}</p>\n \n <p>Group: C = {SPRING=[MONDAY], FALL=[MONDAY, TUESDAY], SUMMER=[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY], WINTER=[MONDAY]}</p>\n \n <p>Group: D = {SPRING=[WEDNESDAY, FRIDAY], FALL=[FRIDAY], SUMMER=[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY], WINTER=[WEDNESDAY]}</p>\n \n <p>Group: E = {SPRING=[TUESDAY], FALL=[TUESDAY, WEDNESDAY], SUMMER=[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY], WINTER=[WEDNESDAY]}</p>\n \n <p>Group A – Watering days on 2018-01-30 week # 2018-W05 is: [TUESDAY]</p>\n \n <p>Group B – Watering days on 2018-01-30 week # 2018-W05 is: [FRIDAY]</p>\n \n <p>Group C – Watering days on 2018-01-30 week # 2018-W05 is: [MONDAY]</p>\n \n <p>Group D – Watering days on 2018-01-30 week # 2018-W05 is: [WEDNESDAY]</p>\n \n <p>Group E – Watering days on 2018-01-30 week # 2018-W05 is: [WEDNESDAY]</p>\n</blockquote>\n\n<h1>ISO 8601 week</h1>\n\n<p>You may find it helpful to learn about the <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a> standard for a <a href=\"https://en.wikipedia.org/wiki/ISO_week_date\" rel=\"nofollow noreferrer\">definition of week</a>. The standard gives a specific meaning to “week” and defines a textual format for representing a particular week or a particular day within that week.</p>\n\n<p>For working with such weeks within Java, consider adding the <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\"><em>ThreeTen-Extra</em></a> library to your project to make use of the <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a> class.</p>\n\n<h1><code>LocalDate</code></h1>\n\n<p>The <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/LocalDate.html\" rel=\"nofollow noreferrer\"><code>LocalDate</code></a> class represents a date-only value without time-of-day and without time zone.</p>\n\n<p>A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in <a href=\"https://en.wikipedia.org/wiki/Europe/Paris\" rel=\"nofollow noreferrer\">Paris France</a> is a new day while still “yesterday” in <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\">Montréal Québec</a>.</p>\n\n<p>If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.</p>\n\n<p>Specify a <a href=\"https://en.wikipedia.org/wiki/List_of_tz_zones_by_name\" rel=\"nofollow noreferrer\">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\"><code>America/Montreal</code></a>, <a href=\"https://en.wikipedia.org/wiki/Africa/Casablanca\" rel=\"nofollow noreferrer\"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter abbreviation such as <code>EST</code> or <code>IST</code> as they are <em>not</em> true time zones, not standardized, and not even unique(!). </p>\n\n<pre><code>ZoneId z = ZoneId.of( \"America/Montreal\" ) ; \nLocalDate today = LocalDate.now( z ) ;\n</code></pre>\n\n<p>If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit.</p>\n\n<pre><code>ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.\n</code></pre>\n\n<p>Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December. </p>\n\n<pre><code>LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.\n</code></pre>\n\n<p>Or, better, use the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/Month.html\" rel=\"nofollow noreferrer\"><code>Month</code></a> enum objects pre-defined, one for each month of the year. Tip: Use these <code>Month</code> objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide <a href=\"https://en.wikipedia.org/wiki/Type_safety\" rel=\"nofollow noreferrer\">type-safety</a>.</p>\n\n<pre><code>LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;\n</code></pre>\n\n<h1>Immutable collections</h1>\n\n<p>The lists, sets, and maps seen above should ideally be immutable collections, as changing the membership of those collections is likely to be confounding and erroneous.</p>\n\n<p>The new Java 9 syntax <code>List.of</code> and <code>Map.of</code> are already promised to be immutable. However, in our case the <code>Map</code> should ideally be an <code>EnumMap</code> for efficiency of performance and memory. The current implementation of <code>Map.of</code> and <code>Set.of</code> apparently do not detect the use of enums as members and automatically optimize with an internal use of <code>EnumMap</code> and <code>EnumSet</code>. There is a OpenJDK issue opened to consider such issues: <a href=\"https://bugs.openjdk.java.net/browse/JDK-8145048\" rel=\"nofollow noreferrer\"><em>consider enhancements to EnumMap and EnumSet</em></a>.</p>\n\n<p>One way to obtain an immutable EnumSet and immutable EnumMap is through the <a href=\"https://en.wikipedia.org/wiki/Google_Guava\" rel=\"nofollow noreferrer\">Google Guava</a> library:</p>\n\n<ul>\n<li><a href=\"http://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html#immutableEnumSet-E-E...-\" rel=\"nofollow noreferrer\"><code>Sets.immutableEnumSet( … )</code></a></li>\n<li><a href=\"http://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Maps.html#immutableEnumMap-java.util.Map-\" rel=\"nofollow noreferrer\"><code>Maps.immutableEnumMap( … )</code></a></li>\n</ul>\n\n<p>The results of each use an underlying <code>EnumSet</code>/<code>EnumMap</code>. Operations such as <code>get</code> and <code>put</code> throw an exception. So you get the enum-related optimizations along with immutability.</p>\n\n<p>Here are the <code>Season</code> and <code>Group</code> classes seen above modified to use the Google Guava 23.6 library.</p>\n\n<h2><code>Season</code> with immutability</h2>\n\n<pre><code>package com.basilbourque.watering;\n\nimport java.time.LocalDate;\nimport java.time.Month;\nimport java.util.EnumSet;\nimport java.util.List;\n\npublic enum Season\n{\n SPRING( List.of( Month.MARCH , Month.APRIL ) ), // `List.of` provides literals-style syntax, and returns an immutable `List`. New in Java 9.\n SUMMER( List.of( Month.MAY , Month.JUNE, Month.JULY , Month.AUGUST ) ),\n FALL( List.of( Month.SEPTEMBER , Month.OCTOBER ) ),\n WINTER( List.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY ) );\n\n private List< Month > months;\n\n // Constructor\n Season ( List < Month > monthsArg )\n {\n this.months = monthsArg;\n }\n\n public List < Month > getMonths ( )\n {\n return this.months;\n }\n\n // For any given month, determine the season.\n static public Season ofLocalMonth ( Month monthArg )\n {\n Season s = null;\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n if ( season.getMonths().contains( monthArg ) )\n {\n s = season;\n break; // Bail out of this FOR loop.\n }\n }\n return s;\n }\n\n // For any given date, determine the season.\n static public Season ofLocalDate ( LocalDate localDateArg )\n {\n Month month = localDateArg.getMonth();\n Season s = Season.ofLocalMonth( month );\n return s;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n System.out.println( \"Season: \" + season.toString() + \" = \" + season.getMonths() );\n }\n }\n}\n</code></pre>\n\n<h2><code>Group</code> with immutability</h2>\n\n<pre><code>package com.basilbourque.watering;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\nimport java.time.DayOfWeek;\nimport java.util.EnumSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic enum Group\n{\n A(\n Maps.immutableEnumMap(\n Map.of( // `Map.of` provides literals-style syntax, and returns an immutable `Map`. New in Java 9.\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.TUESDAY )\n )\n )\n ),\n\n B(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.FRIDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.TUESDAY , DayOfWeek.FRIDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.FRIDAY )\n )\n )\n ),\n\n C(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.MONDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.MONDAY , DayOfWeek.TUESDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.MONDAY )\n )\n )\n ),\n\n D(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.WEDNESDAY , DayOfWeek.FRIDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.FRIDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.WEDNESDAY )\n )\n )\n ),\n\n E(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.TUESDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.WEDNESDAY ) ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.WEDNESDAY )\n )\n )\n );\n\n private Map < Season, Set < DayOfWeek > > map;\n\n // Constructor\n Group ( Map < Season, Set < DayOfWeek > > mapArg )\n {\n this.map = mapArg;\n }\n\n // Getter\n private Map < Season, Set < DayOfWeek > > getMapOfSeasonToDaysOfWeek ( )\n {\n return this.map;\n }\n\n // Retrieve the DayOfWeek set for this particular Group.\n public Set < DayOfWeek > daysForSeason ( Season season )\n {\n Set < DayOfWeek > days = this.map.get( season ); // Retrieve the value (set of days) for this key (a season) for this particular grouping of lawns/yards.\n return days;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Group group : EnumSet.allOf( Group.class ) )\n {\n System.out.println( \"Group: \" + group.toString() + \" = \" + group.getMapOfSeasonToDaysOfWeek() );\n }\n }\n\n}\n</code></pre>\n\n<hr>\n\n<h1>About java.time</h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, & <a href=\"http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\">Joda-Time</a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to the <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\">Oracle Tutorial</a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>Java SE 9</strong></a>, and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the java.time classes.</li>\n<li>For earlier Android, the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <em>ThreeTen-Backport</em> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"nofollow noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"nofollow noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"nofollow noreferrer\">more</a>.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172/"
] | This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse.
I'd prefer to do it right. Here is the situation:
I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this:
Summer (5-1 to 8-31)
Spring (3-1 to 4-30)
Fall (9-1 to 10-31)
Winter (11-1 to 2-28)
An example might be:
If I'm in group A, here would be my allowed times:
Winter: Mondays only
Spring: Tues, Thurs, Sat
Summer: Any Day
Fall: Tues, Thurs, Sat
If I was writing this in PHP I would use arrays like this:
```
//M=Monday,t=Tuesday,T=Thursday.... etc
$schedule["A"]["Winter"]='M';
$schedule["A"]["Spring"]='tTS';
$schedule["A"]["Summer"]='Any';
$schedule["A"]["Fall"]='tTS';
$schedule["B"]["Winter"]='t';
```
I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish.
I will also need to setup arrays to determine what season I'm in:
```
$seasons["Summer"]["start"]=0501;
$seasons["Summer"]["end"]=0801;
```
Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any). | You could do essentially the same code with Hashtables (or some other Map):
```
Hashtable<String, Hashtable<String, String>> schedule
= new Hashtable<String, Hashtable<String, String>>();
schedule.put("A", new Hashtable<String, String>());
schedule.put("B", new Hashtable<String, String>());
schedule.put("C", new Hashtable<String, String>());
schedule.put("D", new Hashtable<String, String>());
schedule.put("E", new Hashtable<String, String>());
schedule.get("A").put("Winter", "M");
schedule.get("A").put("Spring", "tTS");
// Etc...
```
Not as elegant, but then again, Java isn't a dynamic language, and it doesn't have hashes on the language level.
Note: You might be able to do a better solution, this just popped in my head as I read your question. |
12,877 | <p>I just get the beach ball all day long (it's been doing nothing for hours). It's not taking CPU, not reading from disk, not using the network.</p>
<p>I'm using <strong>Java 1.6</strong> on <strong>Mac OS X 10.5.4</strong>. It worked once, now even restarts of the computer won't help. Activity Monitor says it's "(Not Responding)". Only thing that I can do is kill -9 that sucker.</p>
<p>When I sample the process I see this:</p>
<pre><code> mach_msg_trap 16620
read 831
semaphore_wait_trap 831
</code></pre>
<p>An acceptable answer that doesn't fix this would include a url for a decent free Oracle client for the Mac.</p>
<p>Edit:
@Mark Harrison sadly this happens every time I start it up, it's not an old connection. I'll like to avoid running Windows on my laptop. I'm giving some plugins for my IDE a whirl, but still no solution for me.
@Matthew Schinckel Navicat seems to only have a non-commercial Oracle product...I need a commercial friendly one (even if it costs money).</p>
| [
{
"answer_id": 12943,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "<p>The company <a href=\"http://www.navicat.com/\" rel=\"nofollow noreferrer\">Navicat</a> has released an Oracle client for Mac (and they do a Windows version too).</p>\n\n<p>It's not free, but I think you can get a 30 day demo.</p>\n"
},
{
"answer_id": 12959,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 3,
"selected": true,
"text": "<p>I get the same problem after there's been an active connection sitting idle for a while. I solve it by restarting sql developer every once in a while.</p>\n\n<p>I also have Toad for Oracle running on a vmware XP session, and it works great. If you don't mind the money, try that.</p>\n"
},
{
"answer_id": 17714,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.squirrelsql.org/\" rel=\"nofollow noreferrer\">Squirrel</a> is a nice database agonstic application development client. No Oracle specific features, but runs well on the mac</p>\n"
},
{
"answer_id": 27692,
"author": "stevechol",
"author_id": 2981,
"author_profile": "https://Stackoverflow.com/users/2981",
"pm_score": -1,
"selected": false,
"text": "<p>The latest version of SQL Developer is very good and I have experienced no problems with it on my Mac Pro. DB Solo 3 is also quite good.</p>\n"
},
{
"answer_id": 215760,
"author": "terson",
"author_id": 22974,
"author_profile": "https://Stackoverflow.com/users/22974",
"pm_score": 0,
"selected": false,
"text": "<p>I use SQLDeveloper on the Mac and have had problems where it becomes unresponsive. Usually, I can fix this by going into the Activity Monitor and killing the process. However, this doesn't always work to end the process. When that happens, I go to the Terminal and find the process id and send it a SIGKILL and then the next time it will work correctly.</p>\n\n<p>However, more importantly I evaluated <a href=\"http://www.sqlgrinder.com/\" rel=\"nofollow noreferrer\">SQLGrinder</a> at one point. I didn't end up buying the software, largely because I have a Mac laptop and a windows desktop. Therefore, I more often use Toad on the windows desktop and it wasn't worth purchasing SQLGrinder for me.</p>\n"
},
{
"answer_id": 1395000,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Have you looked at <a href=\"http://www.aquafold.com/\" rel=\"nofollow noreferrer\">http://www.aquafold.com/</a>? They have a very JDBC/java Mac-friendly utility, Aqua Data Studio (ADS) that you can try for I think 30 days. It's not free, but... </p>\n\n<p>Excellent support via Yahoo groups. VERY responsive re bugs or enhancement requests.</p>\n\n<p>No affiliation with them - just a fan.</p>\n"
},
{
"answer_id": 1885890,
"author": "Steve Bower",
"author_id": 229373,
"author_profile": "https://Stackoverflow.com/users/229373",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://www.razorsql.com/\" rel=\"nofollow noreferrer\">RazorSQL</a>. Do yourself a favor and spend the 60 bucks. It will pay for itself in the first hour or two of use. You may even be able to get 60 days for free out of it.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484/"
] | I just get the beach ball all day long (it's been doing nothing for hours). It's not taking CPU, not reading from disk, not using the network.
I'm using **Java 1.6** on **Mac OS X 10.5.4**. It worked once, now even restarts of the computer won't help. Activity Monitor says it's "(Not Responding)". Only thing that I can do is kill -9 that sucker.
When I sample the process I see this:
```
mach_msg_trap 16620
read 831
semaphore_wait_trap 831
```
An acceptable answer that doesn't fix this would include a url for a decent free Oracle client for the Mac.
Edit:
@Mark Harrison sadly this happens every time I start it up, it's not an old connection. I'll like to avoid running Windows on my laptop. I'm giving some plugins for my IDE a whirl, but still no solution for me.
@Matthew Schinckel Navicat seems to only have a non-commercial Oracle product...I need a commercial friendly one (even if it costs money). | I get the same problem after there's been an active connection sitting idle for a while. I solve it by restarting sql developer every once in a while.
I also have Toad for Oracle running on a vmware XP session, and it works great. If you don't mind the money, try that. |
12,890 | <p>I have a large database of normalized order data that is becoming very slow to query for reporting. Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.</p>
<p>There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed. I think it's time to start keeping a copy of the data in a denormalized format.</p>
<p>Any ideas on an approach? Should I start with a couple of my worst queries and go from there?</p>
| [
{
"answer_id": 12900,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is a bit tangential, but have you tried seeing if there are more indexes you can add?</p>\n\n<p>I don't have a lot of DB background, but I am working with databases a lot recently, and I've been finding that a lot of the queries can be improved just by adding indexes.</p>\n\n<p>We are using DB2, and there is a command called db2expln and db2advis, the first will indicate whether table scans vs index scans are being used, and the second will recommend indexes you can add to improve performance. I'm sure MySQL has similar tools...</p>\n\n<p>Anyways, if this is something you haven't considered yet, it has been helping a lot with me... but if you've already gone this route, then I guess it's not what you are looking for.</p>\n\n<p>Another possibility is a \"materialized view\" (or as they call it in DB2), which lets you specify a table that is essentially built of parts from multiple tables. Thus, rather than normalizing the actual columns, you could provide this view to access the data... but I don't know if this has severe performance impacts on inserts/updates/deletes (but if it is \"materialized\", then it should help with selects since the values are physically stored separately).</p>\n"
},
{
"answer_id": 12902,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 2,
"selected": false,
"text": "<p>MySQL 5 does support <a href=\"http://dev.mysql.com/doc/refman/5.0/en/create-view.html\" rel=\"nofollow noreferrer\">views</a>, which may be helpful in this scenario. It sounds like you've already done a lot of optimizing, but if not you can use MySQL's <a href=\"http://dev.mysql.com/doc/refman/5.0/en/explain.html\" rel=\"nofollow noreferrer\">EXPLAIN</a> syntax to see what indexes are actually being used and what is slowing down your queries.</p>\n\n<p>As far as going about normalizing data (whether you're using views or just duplicating data in a more efficient manner), I think starting with the slowest queries and working your way through is a good approach to take.</p>\n"
},
{
"answer_id": 12917,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>You might also want to consider selecting into a temporary table and then performing queries on that temporary table. This would avoid the need to rejoin your tables for every single query you issue (assuming that you can use the temporary table for numerous queries, of course). This basically gives you denormalized data, but if you are only doing select calls, there's no concern about data consistency.</p>\n"
},
{
"answer_id": 12950,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 5,
"selected": true,
"text": "<p>I know more about mssql that mysql, but I don't think the number of joins or number of rows you are talking about should cause you too many problems with the correct indexes in place. Have you analyzed the query plan to see if you are missing any?</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/explain.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/explain.html</a></p>\n\n<p>That being said, once you are satisifed with your indexes and have exhausted all other avenues, de-normalization might be the right answer. If you just have one or two queries that are problems, a manual approach is probably appropriate, whereas some sort of data warehousing tool might be better for creating a platform to develop data cubes.</p>\n\n<p>Here's a site I found that touches on the subject:</p>\n\n<p><a href=\"http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D\" rel=\"noreferrer\">http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D</a></p>\n\n<p>Here's a simple technique that you can use to keep denormalizing queries simple, if you're just doing a few at a time (and I'm not replacing your OLTP tables, just creating a new one for reporting purposes). Let's say you have this query in your application:</p>\n\n<pre><code>select a.name, b.address from tbla a \njoin tblb b on b.fk_a_id = a.id where a.id=1\n</code></pre>\n\n<p>You could create a denormalized table and populate with almost the same query:</p>\n\n<pre><code>create table tbl_ab (a_id, a_name, b_address); \n-- (types elided)\n</code></pre>\n\n<p>Notice the underscores match the table aliases you use</p>\n\n<pre><code>insert tbl_ab select a.id, a.name, b.address from tbla a\njoin tblb b on b.fk_a_id = a.id \n-- no where clause because you want everything\n</code></pre>\n\n<p>Then to fix your app to use the new denormalized table, switch the dots for underscores. </p>\n\n<pre><code>select a_name as name, b_address as address \nfrom tbl_ab where a_id = 1;\n</code></pre>\n\n<p>For huge queries this can save a lot of time and makes it clear where the data came from, and you can re-use the queries you already have.</p>\n\n<p>Remember, I'm only advocating this as the last resort. I bet there's a few indexes that would help you. And when you de-normalize, don't forget to account for the extra space on your disks, and figure out when you will run the query to populate the new tables. This should probably be at night, or whenever activity is low. And the data in that table, of course, will never exactly be up to date.</p>\n\n<p>[Yet another edit] Don't forget that the new tables you create need to be indexed too! The good part is that you can index to your heart's content and not worry about update lock contention, since aside from your bulk insert the table will only see selects.</p>\n"
},
{
"answer_id": 12966,
"author": "Jarod Elliott",
"author_id": 1061,
"author_profile": "https://Stackoverflow.com/users/1061",
"pm_score": 1,
"selected": false,
"text": "<p>In line with some of the other comments, i would definately have a look at your indexing.</p>\n\n<p>One thing i discovered earlier this year on our MySQL databases was the power of composite indexes. For example, if you are reporting on order numbers over date ranges, a composite index on the order number and order date columns could help. I believe MySQL can only use one index for the query so if you just had separate indexes on the order number and order date it would have to decide on just one of them to use. Using the EXPLAIN command can help determine this.</p>\n\n<p>To give an indication of the performance with good indexes (including numerous composite indexes), i can run queries joining 3 tables in our database and get almost instant results in most cases. For more complex reporting most of the queries run in under 10 seconds. These 3 tables have 33 million, 110 million and 140 millions rows respectively. Note that we had also already normalised these slightly to speed up our most common query on the database.</p>\n\n<p>More information regarding your tables and the types of reporting queries may allow further suggestions.</p>\n"
},
{
"answer_id": 12972,
"author": "Jarod Elliott",
"author_id": 1061,
"author_profile": "https://Stackoverflow.com/users/1061",
"pm_score": 0,
"selected": false,
"text": "<p>Further to my previous answer, another approach we have taken in some situations is to store key reporting data in separate summary tables. There are certain reporting queries which are just going to be slow even after denormalising and optimisations and we found that creating a table and storing running totals or summary information throughout the month as it came in made the end of month reporting much quicker as well.</p>\n\n<p>We found this approach easy to implement as it didn't break anything that was already working - it's just additional database inserts at certain points.</p>\n"
},
{
"answer_id": 13716,
"author": "Eric Goodwin",
"author_id": 1430,
"author_profile": "https://Stackoverflow.com/users/1430",
"pm_score": 0,
"selected": false,
"text": "<p>I've been toying with composite indexes and have seen some real benefits...maybe I'll setup some tests to see if that can save me here..at least for a little longer.</p>\n"
},
{
"answer_id": 14759,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 1,
"selected": false,
"text": "<p>For MySQL I like this talk: <a href=\"http://develooper.com/talks/rww-mysql-2008.pdf\" rel=\"nofollow noreferrer\">Real World Web: Performance & Scalability, MySQL Edition</a>. This contains a lot of different pieces of advice for getting more speed out of MySQL.</p>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430/"
] | I have a large database of normalized order data that is becoming very slow to query for reporting. Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.
There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed. I think it's time to start keeping a copy of the data in a denormalized format.
Any ideas on an approach? Should I start with a couple of my worst queries and go from there? | I know more about mssql that mysql, but I don't think the number of joins or number of rows you are talking about should cause you too many problems with the correct indexes in place. Have you analyzed the query plan to see if you are missing any?
<http://dev.mysql.com/doc/refman/5.0/en/explain.html>
That being said, once you are satisifed with your indexes and have exhausted all other avenues, de-normalization might be the right answer. If you just have one or two queries that are problems, a manual approach is probably appropriate, whereas some sort of data warehousing tool might be better for creating a platform to develop data cubes.
Here's a site I found that touches on the subject:
<http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D>
Here's a simple technique that you can use to keep denormalizing queries simple, if you're just doing a few at a time (and I'm not replacing your OLTP tables, just creating a new one for reporting purposes). Let's say you have this query in your application:
```
select a.name, b.address from tbla a
join tblb b on b.fk_a_id = a.id where a.id=1
```
You could create a denormalized table and populate with almost the same query:
```
create table tbl_ab (a_id, a_name, b_address);
-- (types elided)
```
Notice the underscores match the table aliases you use
```
insert tbl_ab select a.id, a.name, b.address from tbla a
join tblb b on b.fk_a_id = a.id
-- no where clause because you want everything
```
Then to fix your app to use the new denormalized table, switch the dots for underscores.
```
select a_name as name, b_address as address
from tbl_ab where a_id = 1;
```
For huge queries this can save a lot of time and makes it clear where the data came from, and you can re-use the queries you already have.
Remember, I'm only advocating this as the last resort. I bet there's a few indexes that would help you. And when you de-normalize, don't forget to account for the extra space on your disks, and figure out when you will run the query to populate the new tables. This should probably be at night, or whenever activity is low. And the data in that table, of course, will never exactly be up to date.
[Yet another edit] Don't forget that the new tables you create need to be indexed too! The good part is that you can index to your heart's content and not worry about update lock contention, since aside from your bulk insert the table will only see selects. |
12,896 | <p>I'm looking for good/working/simple to use PHP code for parsing raw email into parts.</p>
<p>I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.</p>
<p>And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).</p>
<p>Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.</p>
<p>I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it "right". This is one of those "wheel" problems that I know has already been solved.</p>
| [
{
"answer_id": 12965,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 6,
"selected": true,
"text": "<p>What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with <a href=\"http://www.faqs.org/rfcs/rfc2822.html\" rel=\"noreferrer\">RFC2822</a> to understand the format of the mail, but here's the simplest rules for well formed email:</p>\n\n<pre><code>HEADERS\\n\n\\n\nBODY\n</code></pre>\n\n<p>That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:</p>\n\n<pre><code>HSTRING:HTEXT\n</code></pre>\n\n<p>HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.</p>\n\n<p>The \"BODY\" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).</p>\n\n<p>So, in really simple, circa-1982 <a href=\"http://www.faqs.org/rfcs/rfc822.html\" rel=\"noreferrer\">RFC822</a> terms, an email looks like this:</p>\n\n<pre><code>HEADER: HEADER TEXT\nHEADER: MORE HEADER TEXT\n INCLUDING A LINE CONTINUATION\nHEADER: LAST HEADER\n\nTHIS IS ANY\nARBITRARY DATA\n(FOR THE MOST PART)\n</code></pre>\n\n<p>Most modern email is more complex than that though. Headers can be encoded for charsets or <a href=\"http://www.faqs.org/rfcs/rfc2047.html\" rel=\"noreferrer\">RFC2047</a> mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be <a href=\"http://www.faqs.org/rfcs/rfc2045.html\" rel=\"noreferrer\">MIME</a> encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.</p>\n\n<p>I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction.</p>\n"
},
{
"answer_id": 13001,
"author": "Uberfuzzy",
"author_id": 314,
"author_profile": "https://Stackoverflow.com/users/314",
"pm_score": 0,
"selected": false,
"text": "<p>yeah, ive been able to write a basic parser, based off that rfc and some other basic tutorials. but its the multipart mime nested boundaries that keep messing me up.</p>\n\n<p>i found out that MMS (not SMS) messages sent from my phone are just standard emails, so i have a system that reads the incoming email, checks the from (to only allow from my phone), and uses the body part to run different commands on my server. its sort of like a remote control by email.</p>\n\n<p>because the system is designed to send pictures, its got a bunch of differently encoded parts. a mms.smil.txt part, a text/plain (which is useless, just says 'this is a html message'), a application/smil part (which the part that phones would pic up on), a text/html part with a advertisement for my carrier, then my message, but all wrapped in html, then finally a textfile attachment with my plain message (which is the part i use) (if i shove an image as an attachment in the message, its put at attachment 1, base64 encoded, then my text portion is attached as attachment 2)</p>\n\n<p>i had it working with the exact mail format from my carrier, but when i ran a message from someone elses phone through it, it failed in a whole bunch of miserable ways.</p>\n\n<p>i have other projects i'd like to extend this phone->mail->parse->command system to, but i need to have a stable/solid/generic parser to get the different parts out of the mail to use it.</p>\n\n<p>my end goal would be to have a function that i could feed the raw piped mail into, and get back a big array with associative sub-arrays of headers var:val pairs, and one for the body text as a whole string</p>\n\n<p>the more and more i search on this, the more i find the same thing: giant overdeveloped mail handling packages that do everything under the sun thats related to mails, or useless (to me, in this project) tutorials.</p>\n\n<p>i think i'm going to have to bite the bullet and just carefully write something my self.</p>\n"
},
{
"answer_id": 13195,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "<p>You're probably not going to have much fun writing your own MIME parser. The reason you are finding \"overdeveloped mail handling packages\" is because MIME is a really complex set of rules/formats/encodings. MIME parts can be recursive, which is part of the fun. I think your best bet is to write the best MIME handler you can, parse a message, throw away everything that's not text/plain or text/html, and then force the command in the incoming string to be prefixed with COMMAND: or something similar so that you can find it in the muck. If you start with rules like that you have a decent chance of handling new providers, but you should be ready to tweak if a new provider comes along (or heck, if your current provider chooses to change their messaging architecture).</p>\n"
},
{
"answer_id": 13270,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure if this will be of help to you - hope so - but it will surely help others interested in finding out more about email. <a href=\"http://marcus.bointon.com/\" rel=\"nofollow noreferrer\">Marcus Bointon</a> did one of the best presentations entitled \"Mail() and life after Mail()\" at the PHP London conference in March this year and the <a href=\"http://www.phpconference.co.uk/media/docs/marcus_bointon_mail_presentation.pdf\" rel=\"nofollow noreferrer\">slides</a> and <a href=\"http://www.phpconference.co.uk/media/audio/mail_and_life_beyond_mail_marcus_bointon.mp3\" rel=\"nofollow noreferrer\">MP3</a> are online. He speaks with some authority, having worked extensively with email and PHP at a deep level.</p>\n\n<p>My perception is that you are in for a world of pain trying to write a truly generic parser.</p>\n\n<p>EDIT - The files seem to have been removed on the PHP London site; found the slides on Marcus' <a href=\"http://marcus.bointon.com/archives/53-PHPLondon.html\" rel=\"nofollow noreferrer\">own site</a>: <a href=\"http://marcus.bointon.com/uploads/MarcusBointonMailpresentation.pdf\" rel=\"nofollow noreferrer\">Part 1</a> <a href=\"http://marcus.bointon.com/uploads/MarcusBointonLifeaftermailpresentation.pdf\" rel=\"nofollow noreferrer\">Part 2</a> Couldn't see the MP3 anywhere though</p>\n"
},
{
"answer_id": 4106876,
"author": "zuups",
"author_id": 338756,
"author_profile": "https://Stackoverflow.com/users/338756",
"pm_score": 2,
"selected": false,
"text": "<p>There are Mailparse Functions you could try: <a href=\"http://php.net/manual/en/book.mailparse.php\" rel=\"nofollow\">http://php.net/manual/en/book.mailparse.php</a>, not in default php conf, however.</p>\n"
},
{
"answer_id": 4234946,
"author": "astateful",
"author_id": 514705,
"author_profile": "https://Stackoverflow.com/users/514705",
"pm_score": 1,
"selected": false,
"text": "<p>Parsing email in PHP isn't an impossible task. What I mean is, you don't need a team of engineers to do it; it is attainable as an individual. Really the hardest part I found was creating the FSM for parsing an IMAP BODYSTRUCTURE result. Nowhere on the Internet had I seen this so I wrote my own. My routine basically creates an array of nested arrays from the command output, and the depth one is at in the array roughly corresponds to the part number(s) needed to perform the lookups. So it handles the nested MIME structures quite gracefully.</p>\n\n<p>The problem is that PHP's default imap_* functions don't provide much granularity...so I had to open a socket to the IMAP port and write the functions to send and retrieve the necessary information (IMAP FETCH 1 BODY.PEEK[1.2] for example), and that involves looking at the RFC documentation.</p>\n\n<p>The encoding of the data (quoted-printable, base64, 7bit, 8bit, etc.), length of the message, content-type, etc. is all provided to you; for attachments, text, html, etc. You may have to figure out the nuances of your mail server as well since not all fields are always implemented 100%.</p>\n\n<p>The gem is the FSM...if you have a background in Comp Sci it can be really really fun to make this (they key is that brackets are not a regular grammar ;)); otherwise it will be a struggle and/or result in ugly code, using traditional methods. Also you need some time!</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 5954640,
"author": "Carter Cole",
"author_id": 180434,
"author_profile": "https://Stackoverflow.com/users/180434",
"pm_score": 3,
"selected": false,
"text": "<p>I cobbled this together, some code isn't mine but I don't know where it came from... I later adopted the more robust \"MimeMailParser\" but this works fine, I pipe my default email to it using cPanel and it works great.</p>\n\n<pre><code>#!/usr/bin/php -q\n<?php\n// Config\n$dbuser = 'emlusr';\n$dbpass = 'pass';\n$dbname = 'email';\n$dbhost = 'localhost';\n$notify= '[email protected]'; // an email address required in case of errors\nfunction mailRead($iKlimit = \"\") \n { \n // Purpose: \n // Reads piped mail from STDIN \n // \n // Arguements: \n // $iKlimit (integer, optional): specifies after how many kilobytes reading of mail should stop \n // Defaults to 1024k if no value is specified \n // A value of -1 will cause reading to continue until the entire message has been read \n // \n // Return value: \n // A string containing the entire email, headers, body and all. \n\n // Variable perparation \n // Set default limit of 1024k if no limit has been specified \n if ($iKlimit == \"\") { \n $iKlimit = 1024; \n } \n\n // Error strings \n $sErrorSTDINFail = \"Error - failed to read mail from STDIN!\"; \n\n // Attempt to connect to STDIN \n $fp = fopen(\"php://stdin\", \"r\"); \n\n // Failed to connect to STDIN? (shouldn't really happen) \n if (!$fp) { \n echo $sErrorSTDINFail; \n exit(); \n } \n\n // Create empty string for storing message \n $sEmail = \"\"; \n\n // Read message up until limit (if any) \n if ($iKlimit == -1) { \n while (!feof($fp)) { \n $sEmail .= fread($fp, 1024); \n } \n } else { \n while (!feof($fp) && $i_limit < $iKlimit) { \n $sEmail .= fread($fp, 1024); \n $i_limit++; \n } \n } \n\n // Close connection to STDIN \n fclose($fp); \n\n // Return message \n return $sEmail; \n } \n$email = mailRead();\n\n// handle email\n$lines = explode(\"\\n\", $email);\n\n// empty vars\n$from = \"\";\n$subject = \"\";\n$headers = \"\";\n$message = \"\";\n$splittingheaders = true;\nfor ($i=0; $i < count($lines); $i++) {\n if ($splittingheaders) {\n // this is a header\n $headers .= $lines[$i].\"\\n\";\n\n // look out for special headers\n if (preg_match(\"/^Subject: (.*)/\", $lines[$i], $matches)) {\n $subject = $matches[1];\n }\n if (preg_match(\"/^From: (.*)/\", $lines[$i], $matches)) {\n $from = $matches[1];\n }\n if (preg_match(\"/^To: (.*)/\", $lines[$i], $matches)) {\n $to = $matches[1];\n }\n } else {\n // not a header, but message\n $message .= $lines[$i].\"\\n\";\n }\n\n if (trim($lines[$i])==\"\") {\n // empty line, header section has ended\n $splittingheaders = false;\n }\n}\n\nif ($conn = @mysql_connect($dbhost,$dbuser,$dbpass)) {\n if(!@mysql_select_db($dbname,$conn))\n mail($email,'Email Logger Error',\"There was an error selecting the email logger database.\\n\\n\".mysql_error());\n $from = mysql_real_escape_string($from);\n $to = mysql_real_escape_string($to);\n $subject = mysql_real_escape_string($subject);\n $headers = mysql_real_escape_string($headers);\n $message = mysql_real_escape_string($message);\n $email = mysql_real_escape_string($email);\n $result = @mysql_query(\"INSERT INTO email_log (`to`,`from`,`subject`,`headers`,`message`,`source`) VALUES('$to','$from','$subject','$headers','$message','$email')\");\n if (mysql_affected_rows() == 0)\n mail($notify,'Email Logger Error',\"There was an error inserting into the email logger database.\\n\\n\".mysql_error());\n} else {\n mail($notify,'Email Logger Error',\"There was an error connecting the email logger database.\\n\\n\".mysql_error());\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 6011540,
"author": "Dan",
"author_id": 354742,
"author_profile": "https://Stackoverflow.com/users/354742",
"pm_score": 4,
"selected": false,
"text": "<p>Try the Plancake PHP Email parser:\n<a href=\"https://github.com/plancake/official-library-php-email-parser\" rel=\"noreferrer\">https://github.com/plancake/official-library-php-email-parser</a></p>\n\n<p>I have used it for my projects. It works great, it is just one class and it is open source.</p>\n"
},
{
"answer_id": 8042425,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 2,
"selected": false,
"text": "<p>The Pear lib Mail_mimeDecode is written in plain PHP that you can see here: <a href=\"http://svn.php.net/viewvc/pear/packages/Mail_mimeDecode/trunk/Mail/mimeDecode.php?revision=337165&view=markup\" rel=\"nofollow noreferrer\">Mail_mimeDecode source</a></p>\n"
},
{
"answer_id": 8057264,
"author": "Petah",
"author_id": 268074,
"author_profile": "https://Stackoverflow.com/users/268074",
"pm_score": 0,
"selected": false,
"text": "<p>This library work very well:</p>\n\n<p><a href=\"http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html\" rel=\"nofollow\">http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html</a></p>\n"
},
{
"answer_id": 31186504,
"author": "Yaroslav",
"author_id": 3238670,
"author_profile": "https://Stackoverflow.com/users/3238670",
"pm_score": 2,
"selected": false,
"text": "<p>There is a library for parsing raw email message into php array - <a href=\"http://flourishlib.com/api/fMailbox#parseMessage\" rel=\"nofollow\">http://flourishlib.com/api/fMailbox#parseMessage</a>. </p>\n\n<blockquote>\n <p>The static method parseMessage() can be used to parse a full MIME\n email message into the same format that fetchMessage() returns, minus\n the uid key.</p>\n \n <p>$parsed_message =\n fMailbox::parseMessage(file_get_contents('/path/to/email'));</p>\n \n <p>Here is an example of a parsed message:</p>\n</blockquote>\n\n<pre><code>array(\n 'received' => '28 Apr 2010 22:00:38 -0400',\n 'headers' => array(\n 'received' => array(\n 0 => '(qmail 25838 invoked from network); 28 Apr 2010 22:00:38 -0400',\n 1 => 'from example.com (HELO ?192.168.10.2?) (example) by example.com with (DHE-RSA-AES256-SHA encrypted) SMTP; 28 Apr 2010 22:00:38 -0400'\n ),\n 'message-id' => '<[email protected]>',\n 'date' => 'Wed, 28 Apr 2010 21:59:49 -0400',\n 'from' => array(\n 'personal' => 'Will Bond',\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n ),\n 'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100317 Thunderbird/3.0.4',\n 'mime-version' => '1.0',\n 'to' => array(\n 0 => array(\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n )\n ),\n 'subject' => 'This message is encrypted'\n ),\n 'text' => 'This message is encrypted',\n 'decrypted' => TRUE,\n 'uid' => 15\n);\n</code></pre>\n"
},
{
"answer_id": 33311882,
"author": "Jonathan Roy",
"author_id": 577950,
"author_profile": "https://Stackoverflow.com/users/577950",
"pm_score": 0,
"selected": false,
"text": "<p>I met the same problem so I wrote the following class: Email_Parser. It takes in a raw email and turns it into a nice object.</p>\n\n<p>It requires PEAR Mail_mimeDecode but that should be easy to install via WHM or straight from command line.</p>\n\n<p>Get it here : <a href=\"https://github.com/optimumweb/php-email-reader-parser\" rel=\"nofollow\">https://github.com/optimumweb/php-email-reader-parser</a></p>\n"
},
{
"answer_id": 40764732,
"author": "TomaszKane",
"author_id": 1829368,
"author_profile": "https://Stackoverflow.com/users/1829368",
"pm_score": 2,
"selected": false,
"text": "<p>This <a href=\"https://github.com/zbateson/MailMimeParser\" rel=\"nofollow noreferrer\">https://github.com/zbateson/MailMimeParser</a> works for me, and don't need mailparse extension.</p>\n\n<pre><code><?php\necho $message->getHeaderValue('from'); // [email protected]\necho $message\n ->getHeader('from')\n ->getPersonName(); // Person Name\necho $message->getHeaderValue('subject'); // The email's subject\n\necho $message->getTextContent(); // or getHtmlContent\n</code></pre>\n"
},
{
"answer_id": 47110625,
"author": "Kazik",
"author_id": 8885286,
"author_profile": "https://Stackoverflow.com/users/8885286",
"pm_score": 0,
"selected": false,
"text": "<p>Simple PhpMimeParser <a href=\"https://github.com/breakermind/PhpMimeParser\" rel=\"nofollow noreferrer\">https://github.com/breakermind/PhpMimeParser</a> Yuo can cut mime messages from files, string. Get files, html and inline images.</p>\n\n<pre><code>$str = file_get_contents('mime-mixed-related-alternative.eml');\n\n// MimeParser\n$m = new PhpMimeParser($str);\n\n// Emails\nprint_r($m->mTo);\nprint_r($m->mFrom);\n\n// Message\necho $m->mSubject;\necho $m->mHtml;\necho $m->mText;\n\n// Attachments and inline images\nprint_r($m->mFiles);\nprint_r($m->mInlineList);\n</code></pre>\n"
},
{
"answer_id": 67923886,
"author": "Adam Winter",
"author_id": 10664600,
"author_profile": "https://Stackoverflow.com/users/10664600",
"pm_score": 0,
"selected": false,
"text": "<p>If you're trying to do this from a Docker container, use PEAR to install Mail and Mail_mimeDecode at build.</p>\n<pre><code>FROM php:7.4-apache\nWORKDIR /var/www/html\nEXPOSE 80\nWORKDIR /var/www\nRUN chown -R www-data html\nRUN docker-php-ext-install mysqli\nRUN pear install --alldeps mail\nRUN pear install Mail_mimeDecode\n</code></pre>\n<p>Then in your PHP code, something like this:</p>\n<pre><code><?php\n\nrequire_once "/usr/local/lib/php/Mail.php";\nrequire_once "/usr/local/lib/php/Mail/mimeDecode.php";\n\n$mailfiles = ['/var/www/mail/mailFile1','/var/www/mail/mailFile2'];\n\nforeach($mailfiles as $filename){\n $theFile = fopen($filename, "r") or die("Unable to open file!");\n $rawEmail = fread($theFile, filesize($filename));\n fclose($theFile);\n\n $args = [];\n $args['include_bodies'] = true;\n $args['decode_bodies'] = FALSE;\n $args['decode_headers'] = FALSE;\n $objMail = new Mail_mimeDecode($rawEmail);\n $return = $objMail->decode($args);\n\n if (PEAR::isError($return)) {\n echo("<p>" . $return->getMessage() . "</p>");\n var_dump($return);\n } else {\n //echo("No error in PEAR::isError(return)");\n }\n\n if($return->body){\n $decoded = base64_decode($return->body, true);\n var_dump($decoded);\n }//end if(body)\n\n}//end foreach(mailfiles as file)\n\n\n?>\n</code></pre>\n"
}
] | 2008/08/15 | [
"https://Stackoverflow.com/questions/12896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314/"
] | I'm looking for good/working/simple to use PHP code for parsing raw email into parts.
I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.
And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).
Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.
I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it "right". This is one of those "wheel" problems that I know has already been solved. | What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with [RFC2822](http://www.faqs.org/rfcs/rfc2822.html) to understand the format of the mail, but here's the simplest rules for well formed email:
```
HEADERS\n
\n
BODY
```
That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:
```
HSTRING:HTEXT
```
HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.
The "BODY" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).
So, in really simple, circa-1982 [RFC822](http://www.faqs.org/rfcs/rfc822.html) terms, an email looks like this:
```
HEADER: HEADER TEXT
HEADER: MORE HEADER TEXT
INCLUDING A LINE CONTINUATION
HEADER: LAST HEADER
THIS IS ANY
ARBITRARY DATA
(FOR THE MOST PART)
```
Most modern email is more complex than that though. Headers can be encoded for charsets or [RFC2047](http://www.faqs.org/rfcs/rfc2047.html) mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be [MIME](http://www.faqs.org/rfcs/rfc2045.html) encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.
I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction. |
12,905 | <p>I'm experimenting with creating an add-in for Infopath 2007. The documentation is very skimpy. What I'm trying to determine is what kind of actions an add-in can take while designing a form. Most of the discussion and samples are for when the user is filling out the form. Can I, for example, add a new field to the form in the designer? Add a new item to the schema? Move a form field on the design surface? It doesn't appear so, but I can't find anything definitive.</p>
| [
{
"answer_id": 12965,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 6,
"selected": true,
"text": "<p>What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with <a href=\"http://www.faqs.org/rfcs/rfc2822.html\" rel=\"noreferrer\">RFC2822</a> to understand the format of the mail, but here's the simplest rules for well formed email:</p>\n\n<pre><code>HEADERS\\n\n\\n\nBODY\n</code></pre>\n\n<p>That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:</p>\n\n<pre><code>HSTRING:HTEXT\n</code></pre>\n\n<p>HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.</p>\n\n<p>The \"BODY\" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).</p>\n\n<p>So, in really simple, circa-1982 <a href=\"http://www.faqs.org/rfcs/rfc822.html\" rel=\"noreferrer\">RFC822</a> terms, an email looks like this:</p>\n\n<pre><code>HEADER: HEADER TEXT\nHEADER: MORE HEADER TEXT\n INCLUDING A LINE CONTINUATION\nHEADER: LAST HEADER\n\nTHIS IS ANY\nARBITRARY DATA\n(FOR THE MOST PART)\n</code></pre>\n\n<p>Most modern email is more complex than that though. Headers can be encoded for charsets or <a href=\"http://www.faqs.org/rfcs/rfc2047.html\" rel=\"noreferrer\">RFC2047</a> mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be <a href=\"http://www.faqs.org/rfcs/rfc2045.html\" rel=\"noreferrer\">MIME</a> encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.</p>\n\n<p>I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction.</p>\n"
},
{
"answer_id": 13001,
"author": "Uberfuzzy",
"author_id": 314,
"author_profile": "https://Stackoverflow.com/users/314",
"pm_score": 0,
"selected": false,
"text": "<p>yeah, ive been able to write a basic parser, based off that rfc and some other basic tutorials. but its the multipart mime nested boundaries that keep messing me up.</p>\n\n<p>i found out that MMS (not SMS) messages sent from my phone are just standard emails, so i have a system that reads the incoming email, checks the from (to only allow from my phone), and uses the body part to run different commands on my server. its sort of like a remote control by email.</p>\n\n<p>because the system is designed to send pictures, its got a bunch of differently encoded parts. a mms.smil.txt part, a text/plain (which is useless, just says 'this is a html message'), a application/smil part (which the part that phones would pic up on), a text/html part with a advertisement for my carrier, then my message, but all wrapped in html, then finally a textfile attachment with my plain message (which is the part i use) (if i shove an image as an attachment in the message, its put at attachment 1, base64 encoded, then my text portion is attached as attachment 2)</p>\n\n<p>i had it working with the exact mail format from my carrier, but when i ran a message from someone elses phone through it, it failed in a whole bunch of miserable ways.</p>\n\n<p>i have other projects i'd like to extend this phone->mail->parse->command system to, but i need to have a stable/solid/generic parser to get the different parts out of the mail to use it.</p>\n\n<p>my end goal would be to have a function that i could feed the raw piped mail into, and get back a big array with associative sub-arrays of headers var:val pairs, and one for the body text as a whole string</p>\n\n<p>the more and more i search on this, the more i find the same thing: giant overdeveloped mail handling packages that do everything under the sun thats related to mails, or useless (to me, in this project) tutorials.</p>\n\n<p>i think i'm going to have to bite the bullet and just carefully write something my self.</p>\n"
},
{
"answer_id": 13195,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "<p>You're probably not going to have much fun writing your own MIME parser. The reason you are finding \"overdeveloped mail handling packages\" is because MIME is a really complex set of rules/formats/encodings. MIME parts can be recursive, which is part of the fun. I think your best bet is to write the best MIME handler you can, parse a message, throw away everything that's not text/plain or text/html, and then force the command in the incoming string to be prefixed with COMMAND: or something similar so that you can find it in the muck. If you start with rules like that you have a decent chance of handling new providers, but you should be ready to tweak if a new provider comes along (or heck, if your current provider chooses to change their messaging architecture).</p>\n"
},
{
"answer_id": 13270,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure if this will be of help to you - hope so - but it will surely help others interested in finding out more about email. <a href=\"http://marcus.bointon.com/\" rel=\"nofollow noreferrer\">Marcus Bointon</a> did one of the best presentations entitled \"Mail() and life after Mail()\" at the PHP London conference in March this year and the <a href=\"http://www.phpconference.co.uk/media/docs/marcus_bointon_mail_presentation.pdf\" rel=\"nofollow noreferrer\">slides</a> and <a href=\"http://www.phpconference.co.uk/media/audio/mail_and_life_beyond_mail_marcus_bointon.mp3\" rel=\"nofollow noreferrer\">MP3</a> are online. He speaks with some authority, having worked extensively with email and PHP at a deep level.</p>\n\n<p>My perception is that you are in for a world of pain trying to write a truly generic parser.</p>\n\n<p>EDIT - The files seem to have been removed on the PHP London site; found the slides on Marcus' <a href=\"http://marcus.bointon.com/archives/53-PHPLondon.html\" rel=\"nofollow noreferrer\">own site</a>: <a href=\"http://marcus.bointon.com/uploads/MarcusBointonMailpresentation.pdf\" rel=\"nofollow noreferrer\">Part 1</a> <a href=\"http://marcus.bointon.com/uploads/MarcusBointonLifeaftermailpresentation.pdf\" rel=\"nofollow noreferrer\">Part 2</a> Couldn't see the MP3 anywhere though</p>\n"
},
{
"answer_id": 4106876,
"author": "zuups",
"author_id": 338756,
"author_profile": "https://Stackoverflow.com/users/338756",
"pm_score": 2,
"selected": false,
"text": "<p>There are Mailparse Functions you could try: <a href=\"http://php.net/manual/en/book.mailparse.php\" rel=\"nofollow\">http://php.net/manual/en/book.mailparse.php</a>, not in default php conf, however.</p>\n"
},
{
"answer_id": 4234946,
"author": "astateful",
"author_id": 514705,
"author_profile": "https://Stackoverflow.com/users/514705",
"pm_score": 1,
"selected": false,
"text": "<p>Parsing email in PHP isn't an impossible task. What I mean is, you don't need a team of engineers to do it; it is attainable as an individual. Really the hardest part I found was creating the FSM for parsing an IMAP BODYSTRUCTURE result. Nowhere on the Internet had I seen this so I wrote my own. My routine basically creates an array of nested arrays from the command output, and the depth one is at in the array roughly corresponds to the part number(s) needed to perform the lookups. So it handles the nested MIME structures quite gracefully.</p>\n\n<p>The problem is that PHP's default imap_* functions don't provide much granularity...so I had to open a socket to the IMAP port and write the functions to send and retrieve the necessary information (IMAP FETCH 1 BODY.PEEK[1.2] for example), and that involves looking at the RFC documentation.</p>\n\n<p>The encoding of the data (quoted-printable, base64, 7bit, 8bit, etc.), length of the message, content-type, etc. is all provided to you; for attachments, text, html, etc. You may have to figure out the nuances of your mail server as well since not all fields are always implemented 100%.</p>\n\n<p>The gem is the FSM...if you have a background in Comp Sci it can be really really fun to make this (they key is that brackets are not a regular grammar ;)); otherwise it will be a struggle and/or result in ugly code, using traditional methods. Also you need some time!</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 5954640,
"author": "Carter Cole",
"author_id": 180434,
"author_profile": "https://Stackoverflow.com/users/180434",
"pm_score": 3,
"selected": false,
"text": "<p>I cobbled this together, some code isn't mine but I don't know where it came from... I later adopted the more robust \"MimeMailParser\" but this works fine, I pipe my default email to it using cPanel and it works great.</p>\n\n<pre><code>#!/usr/bin/php -q\n<?php\n// Config\n$dbuser = 'emlusr';\n$dbpass = 'pass';\n$dbname = 'email';\n$dbhost = 'localhost';\n$notify= '[email protected]'; // an email address required in case of errors\nfunction mailRead($iKlimit = \"\") \n { \n // Purpose: \n // Reads piped mail from STDIN \n // \n // Arguements: \n // $iKlimit (integer, optional): specifies after how many kilobytes reading of mail should stop \n // Defaults to 1024k if no value is specified \n // A value of -1 will cause reading to continue until the entire message has been read \n // \n // Return value: \n // A string containing the entire email, headers, body and all. \n\n // Variable perparation \n // Set default limit of 1024k if no limit has been specified \n if ($iKlimit == \"\") { \n $iKlimit = 1024; \n } \n\n // Error strings \n $sErrorSTDINFail = \"Error - failed to read mail from STDIN!\"; \n\n // Attempt to connect to STDIN \n $fp = fopen(\"php://stdin\", \"r\"); \n\n // Failed to connect to STDIN? (shouldn't really happen) \n if (!$fp) { \n echo $sErrorSTDINFail; \n exit(); \n } \n\n // Create empty string for storing message \n $sEmail = \"\"; \n\n // Read message up until limit (if any) \n if ($iKlimit == -1) { \n while (!feof($fp)) { \n $sEmail .= fread($fp, 1024); \n } \n } else { \n while (!feof($fp) && $i_limit < $iKlimit) { \n $sEmail .= fread($fp, 1024); \n $i_limit++; \n } \n } \n\n // Close connection to STDIN \n fclose($fp); \n\n // Return message \n return $sEmail; \n } \n$email = mailRead();\n\n// handle email\n$lines = explode(\"\\n\", $email);\n\n// empty vars\n$from = \"\";\n$subject = \"\";\n$headers = \"\";\n$message = \"\";\n$splittingheaders = true;\nfor ($i=0; $i < count($lines); $i++) {\n if ($splittingheaders) {\n // this is a header\n $headers .= $lines[$i].\"\\n\";\n\n // look out for special headers\n if (preg_match(\"/^Subject: (.*)/\", $lines[$i], $matches)) {\n $subject = $matches[1];\n }\n if (preg_match(\"/^From: (.*)/\", $lines[$i], $matches)) {\n $from = $matches[1];\n }\n if (preg_match(\"/^To: (.*)/\", $lines[$i], $matches)) {\n $to = $matches[1];\n }\n } else {\n // not a header, but message\n $message .= $lines[$i].\"\\n\";\n }\n\n if (trim($lines[$i])==\"\") {\n // empty line, header section has ended\n $splittingheaders = false;\n }\n}\n\nif ($conn = @mysql_connect($dbhost,$dbuser,$dbpass)) {\n if(!@mysql_select_db($dbname,$conn))\n mail($email,'Email Logger Error',\"There was an error selecting the email logger database.\\n\\n\".mysql_error());\n $from = mysql_real_escape_string($from);\n $to = mysql_real_escape_string($to);\n $subject = mysql_real_escape_string($subject);\n $headers = mysql_real_escape_string($headers);\n $message = mysql_real_escape_string($message);\n $email = mysql_real_escape_string($email);\n $result = @mysql_query(\"INSERT INTO email_log (`to`,`from`,`subject`,`headers`,`message`,`source`) VALUES('$to','$from','$subject','$headers','$message','$email')\");\n if (mysql_affected_rows() == 0)\n mail($notify,'Email Logger Error',\"There was an error inserting into the email logger database.\\n\\n\".mysql_error());\n} else {\n mail($notify,'Email Logger Error',\"There was an error connecting the email logger database.\\n\\n\".mysql_error());\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 6011540,
"author": "Dan",
"author_id": 354742,
"author_profile": "https://Stackoverflow.com/users/354742",
"pm_score": 4,
"selected": false,
"text": "<p>Try the Plancake PHP Email parser:\n<a href=\"https://github.com/plancake/official-library-php-email-parser\" rel=\"noreferrer\">https://github.com/plancake/official-library-php-email-parser</a></p>\n\n<p>I have used it for my projects. It works great, it is just one class and it is open source.</p>\n"
},
{
"answer_id": 8042425,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 2,
"selected": false,
"text": "<p>The Pear lib Mail_mimeDecode is written in plain PHP that you can see here: <a href=\"http://svn.php.net/viewvc/pear/packages/Mail_mimeDecode/trunk/Mail/mimeDecode.php?revision=337165&view=markup\" rel=\"nofollow noreferrer\">Mail_mimeDecode source</a></p>\n"
},
{
"answer_id": 8057264,
"author": "Petah",
"author_id": 268074,
"author_profile": "https://Stackoverflow.com/users/268074",
"pm_score": 0,
"selected": false,
"text": "<p>This library work very well:</p>\n\n<p><a href=\"http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html\" rel=\"nofollow\">http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html</a></p>\n"
},
{
"answer_id": 31186504,
"author": "Yaroslav",
"author_id": 3238670,
"author_profile": "https://Stackoverflow.com/users/3238670",
"pm_score": 2,
"selected": false,
"text": "<p>There is a library for parsing raw email message into php array - <a href=\"http://flourishlib.com/api/fMailbox#parseMessage\" rel=\"nofollow\">http://flourishlib.com/api/fMailbox#parseMessage</a>. </p>\n\n<blockquote>\n <p>The static method parseMessage() can be used to parse a full MIME\n email message into the same format that fetchMessage() returns, minus\n the uid key.</p>\n \n <p>$parsed_message =\n fMailbox::parseMessage(file_get_contents('/path/to/email'));</p>\n \n <p>Here is an example of a parsed message:</p>\n</blockquote>\n\n<pre><code>array(\n 'received' => '28 Apr 2010 22:00:38 -0400',\n 'headers' => array(\n 'received' => array(\n 0 => '(qmail 25838 invoked from network); 28 Apr 2010 22:00:38 -0400',\n 1 => 'from example.com (HELO ?192.168.10.2?) (example) by example.com with (DHE-RSA-AES256-SHA encrypted) SMTP; 28 Apr 2010 22:00:38 -0400'\n ),\n 'message-id' => '<[email protected]>',\n 'date' => 'Wed, 28 Apr 2010 21:59:49 -0400',\n 'from' => array(\n 'personal' => 'Will Bond',\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n ),\n 'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100317 Thunderbird/3.0.4',\n 'mime-version' => '1.0',\n 'to' => array(\n 0 => array(\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n )\n ),\n 'subject' => 'This message is encrypted'\n ),\n 'text' => 'This message is encrypted',\n 'decrypted' => TRUE,\n 'uid' => 15\n);\n</code></pre>\n"
},
{
"answer_id": 33311882,
"author": "Jonathan Roy",
"author_id": 577950,
"author_profile": "https://Stackoverflow.com/users/577950",
"pm_score": 0,
"selected": false,
"text": "<p>I met the same problem so I wrote the following class: Email_Parser. It takes in a raw email and turns it into a nice object.</p>\n\n<p>It requires PEAR Mail_mimeDecode but that should be easy to install via WHM or straight from command line.</p>\n\n<p>Get it here : <a href=\"https://github.com/optimumweb/php-email-reader-parser\" rel=\"nofollow\">https://github.com/optimumweb/php-email-reader-parser</a></p>\n"
},
{
"answer_id": 40764732,
"author": "TomaszKane",
"author_id": 1829368,
"author_profile": "https://Stackoverflow.com/users/1829368",
"pm_score": 2,
"selected": false,
"text": "<p>This <a href=\"https://github.com/zbateson/MailMimeParser\" rel=\"nofollow noreferrer\">https://github.com/zbateson/MailMimeParser</a> works for me, and don't need mailparse extension.</p>\n\n<pre><code><?php\necho $message->getHeaderValue('from'); // [email protected]\necho $message\n ->getHeader('from')\n ->getPersonName(); // Person Name\necho $message->getHeaderValue('subject'); // The email's subject\n\necho $message->getTextContent(); // or getHtmlContent\n</code></pre>\n"
},
{
"answer_id": 47110625,
"author": "Kazik",
"author_id": 8885286,
"author_profile": "https://Stackoverflow.com/users/8885286",
"pm_score": 0,
"selected": false,
"text": "<p>Simple PhpMimeParser <a href=\"https://github.com/breakermind/PhpMimeParser\" rel=\"nofollow noreferrer\">https://github.com/breakermind/PhpMimeParser</a> Yuo can cut mime messages from files, string. Get files, html and inline images.</p>\n\n<pre><code>$str = file_get_contents('mime-mixed-related-alternative.eml');\n\n// MimeParser\n$m = new PhpMimeParser($str);\n\n// Emails\nprint_r($m->mTo);\nprint_r($m->mFrom);\n\n// Message\necho $m->mSubject;\necho $m->mHtml;\necho $m->mText;\n\n// Attachments and inline images\nprint_r($m->mFiles);\nprint_r($m->mInlineList);\n</code></pre>\n"
},
{
"answer_id": 67923886,
"author": "Adam Winter",
"author_id": 10664600,
"author_profile": "https://Stackoverflow.com/users/10664600",
"pm_score": 0,
"selected": false,
"text": "<p>If you're trying to do this from a Docker container, use PEAR to install Mail and Mail_mimeDecode at build.</p>\n<pre><code>FROM php:7.4-apache\nWORKDIR /var/www/html\nEXPOSE 80\nWORKDIR /var/www\nRUN chown -R www-data html\nRUN docker-php-ext-install mysqli\nRUN pear install --alldeps mail\nRUN pear install Mail_mimeDecode\n</code></pre>\n<p>Then in your PHP code, something like this:</p>\n<pre><code><?php\n\nrequire_once "/usr/local/lib/php/Mail.php";\nrequire_once "/usr/local/lib/php/Mail/mimeDecode.php";\n\n$mailfiles = ['/var/www/mail/mailFile1','/var/www/mail/mailFile2'];\n\nforeach($mailfiles as $filename){\n $theFile = fopen($filename, "r") or die("Unable to open file!");\n $rawEmail = fread($theFile, filesize($filename));\n fclose($theFile);\n\n $args = [];\n $args['include_bodies'] = true;\n $args['decode_bodies'] = FALSE;\n $args['decode_headers'] = FALSE;\n $objMail = new Mail_mimeDecode($rawEmail);\n $return = $objMail->decode($args);\n\n if (PEAR::isError($return)) {\n echo("<p>" . $return->getMessage() . "</p>");\n var_dump($return);\n } else {\n //echo("No error in PEAR::isError(return)");\n }\n\n if($return->body){\n $decoded = base64_decode($return->body, true);\n var_dump($decoded);\n }//end if(body)\n\n}//end foreach(mailfiles as file)\n\n\n?>\n</code></pre>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/12905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9/"
] | I'm experimenting with creating an add-in for Infopath 2007. The documentation is very skimpy. What I'm trying to determine is what kind of actions an add-in can take while designing a form. Most of the discussion and samples are for when the user is filling out the form. Can I, for example, add a new field to the form in the designer? Add a new item to the schema? Move a form field on the design surface? It doesn't appear so, but I can't find anything definitive. | What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with [RFC2822](http://www.faqs.org/rfcs/rfc2822.html) to understand the format of the mail, but here's the simplest rules for well formed email:
```
HEADERS\n
\n
BODY
```
That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:
```
HSTRING:HTEXT
```
HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.
The "BODY" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).
So, in really simple, circa-1982 [RFC822](http://www.faqs.org/rfcs/rfc822.html) terms, an email looks like this:
```
HEADER: HEADER TEXT
HEADER: MORE HEADER TEXT
INCLUDING A LINE CONTINUATION
HEADER: LAST HEADER
THIS IS ANY
ARBITRARY DATA
(FOR THE MOST PART)
```
Most modern email is more complex than that though. Headers can be encoded for charsets or [RFC2047](http://www.faqs.org/rfcs/rfc2047.html) mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be [MIME](http://www.faqs.org/rfcs/rfc2045.html) encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.
I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction. |
12,906 | <p>I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out.</p>
| [
{
"answer_id": 12911,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>I know this might sound a little arcanine but why not just stat the directory that contains the database.</p>\n"
},
{
"answer_id": 12915,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": true,
"text": "<p>Source: <a href=\"http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1313431,00.html\" rel=\"noreferrer\">http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1313431,00.html</a>\nWorks with SQL2000,2005,2008</p>\n\n<pre><code>USE master;\nGO\n\nIF OBJECT_ID('dbo.sp_SDS', 'P') IS NOT NULL\n DROP PROCEDURE dbo.sp_SDS;\nGO\n\nCREATE PROCEDURE dbo.sp_SDS \n @TargetDatabase sysname = NULL, -- NULL: all dbs\n @Level varchar(10) = 'Database', -- or \"File\"\n @UpdateUsage bit = 0, -- default no update\n @Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes\nAS\n\n/**************************************************************************************************\n**\n** author: Richard Ding\n** date: 4/8/2008\n** usage: list db size AND path w/o SUMmary\n** test code: sp_SDS -- default behavior\n** sp_SDS 'maAster'\n** sp_SDS NULL, NULL, 0\n** sp_SDS NULL, 'file', 1, 'GB'\n** sp_SDS 'Test_snapshot', 'Database', 1\n** sp_SDS 'Test', 'File', 0, 'kb'\n** sp_SDS 'pfaids', 'Database', 0, 'gb'\n** sp_SDS 'tempdb', NULL, 1, 'kb'\n** \n**************************************************************************************************/\n\nSET NOCOUNT ON;\n\nIF @TargetDatabase IS NOT NULL AND DB_ID(@TargetDatabase) IS NULL\n BEGIN\n RAISERROR(15010, -1, -1, @TargetDatabase);\n RETURN (-1)\n END\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_CombinedInfo;\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_DbFileStats;\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_ValidDbs;\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_Logs;\n\nCREATE TABLE dbo.##Tbl_CombinedInfo (\n DatabaseName sysname NULL, \n [type] VARCHAR(10) NULL, \n LogicalName sysname NULL,\n T dec(10, 2) NULL,\n U dec(10, 2) NULL,\n [U(%)] dec(5, 2) NULL,\n F dec(10, 2) NULL,\n [F(%)] dec(5, 2) NULL,\n PhysicalName sysname NULL );\n\nCREATE TABLE dbo.##Tbl_DbFileStats (\n Id int identity, \n DatabaseName sysname NULL, \n FileId int NULL, \n FileGroup int NULL, \n TotalExtents bigint NULL, \n UsedExtents bigint NULL, \n Name sysname NULL, \n FileName varchar(255) NULL );\n\nCREATE TABLE dbo.##Tbl_ValidDbs (\n Id int identity, \n Dbname sysname NULL );\n\nCREATE TABLE dbo.##Tbl_Logs (\n DatabaseName sysname NULL, \n LogSize dec (10, 2) NULL, \n LogSpaceUsedPercent dec (5, 2) NULL,\n Status int NULL );\n\nDECLARE @Ver varchar(10), \n @DatabaseName sysname, \n @Ident_last int, \n @String varchar(2000),\n @BaseString varchar(2000);\n\nSELECT @DatabaseName = '', \n @Ident_last = 0, \n @String = '', \n @Ver = CASE WHEN @@VERSION LIKE '%9.0%' THEN 'SQL 2005' \n WHEN @@VERSION LIKE '%8.0%' THEN 'SQL 2000' \n WHEN @@VERSION LIKE '%10.0%' THEN 'SQL 2008' \n END;\n\nSELECT @BaseString = \n' SELECT DB_NAME(), ' + \nCASE WHEN @Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE ''Data'' END' \n ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-text'' ELSE ''reserved'' END' END + \n', name, ' + \nCASE WHEN @Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END + \n', size*8.0/1024.0 FROM ' + \nCASE WHEN @Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END + \n' WHERE '\n+ CASE WHEN @Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc = ''ONLINE''' END + '';\n\nSELECT @String = 'INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM ' + \n CASE WHEN @Ver = 'SQL 2000' THEN 'master.dbo.sysdatabases' \n WHEN @Ver IN ('SQL 2005', 'SQL 2008') THEN 'master.sys.databases' \n END + ' WHERE HAS_DBACCESS(name) = 1 ORDER BY name ASC';\nEXEC (@String);\n\nINSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');\n\n-- For data part\nIF @TargetDatabase IS NOT NULL\n BEGIN\n SELECT @DatabaseName = @TargetDatabase;\n IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName,'Status') = 'ONLINE' \n AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'\n BEGIN\n SELECT @String = 'USE [' + @DatabaseName + '] DBCC UPDATEUSAGE (0)';\n PRINT '*** ' + @String + ' *** ';\n EXEC (@String);\n PRINT '';\n END\n\n SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString; \n\n INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)\n EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');\n EXEC ('USE [' + @DatabaseName + '] ' + @String);\n\n UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName; \n END\nELSE\n BEGIN\n WHILE 1 = 1\n BEGIN\n SELECT TOP 1 @DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname > @DatabaseName ORDER BY Dbname ASC;\n IF @@ROWCOUNT = 0\n BREAK;\n IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName, 'Status') = 'ONLINE' \n AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'\n BEGIN\n SELECT @String = 'DBCC UPDATEUSAGE (''' + @DatabaseName + ''') ';\n PRINT '*** ' + @String + '*** ';\n EXEC (@String);\n PRINT '';\n END\n\n SELECT @Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;\n\n SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString; \n\n EXEC ('USE [' + @DatabaseName + '] ' + @String);\n\n INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)\n EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');\n\n UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName WHERE Id BETWEEN @Ident_last + 1 AND @@IDENTITY;\n END\n END\n\n-- set used size for data files, do not change total obtained from sys.database_files as it has for log files\nUPDATE dbo.##Tbl_CombinedInfo \nSET U = s.UsedExtents*8*8/1024.0 \nFROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s \nON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;\n\n-- set used size and % values for log files:\nUPDATE dbo.##Tbl_CombinedInfo \nSET [U(%)] = LogSpaceUsedPercent, \nU = T * LogSpaceUsedPercent/100.0\nFROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l \nON l.DatabaseName = t.DatabaseName \nWHERE t.type = 'Log';\n\nUPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;\n\nUPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;\n\nIF UPPER(ISNULL(@Level, 'DATABASE')) = 'FILE'\n BEGIN\n IF @Unit = 'KB'\n UPDATE dbo.##Tbl_CombinedInfo\n SET T = T * 1024, U = U * 1024, F = F * 1024;\n\n IF @Unit = 'GB'\n UPDATE dbo.##Tbl_CombinedInfo\n SET T = T / 1024, U = U / 1024, F = F / 1024;\n\n SELECT DatabaseName AS 'Database',\n type AS 'Type',\n LogicalName,\n T AS 'Total',\n U AS 'Used',\n [U(%)] AS 'Used (%)',\n F AS 'Free',\n [F(%)] AS 'Free (%)',\n PhysicalName\n FROM dbo.##Tbl_CombinedInfo \n WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%') \n ORDER BY DatabaseName ASC, type ASC;\n\n SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',\n SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM dbo.##Tbl_CombinedInfo;\n END\n\nIF UPPER(ISNULL(@Level, 'DATABASE')) = 'DATABASE'\n BEGIN\n DECLARE @Tbl_Final TABLE (\n DatabaseName sysname NULL,\n TOTAL dec (10, 2),\n [=] char(1),\n used dec (10, 2),\n [used (%)] dec (5, 2),\n [+] char(1),\n free dec (10, 2),\n [free (%)] dec (5, 2),\n [==] char(2),\n Data dec (10, 2),\n Data_Used dec (10, 2),\n [Data_Used (%)] dec (5, 2),\n Data_Free dec (10, 2),\n [Data_Free (%)] dec (5, 2),\n [++] char(2),\n Log dec (10, 2),\n Log_Used dec (10, 2),\n [Log_Used (%)] dec (5, 2),\n Log_Free dec (10, 2),\n [Log_Free (%)] dec (5, 2) );\n\n INSERT INTO @Tbl_Final\n SELECT x.DatabaseName, \n x.Data + y.Log AS 'TOTAL', \n '=' AS '=', \n x.Data_Used + y.Log_Used AS 'U',\n (x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',\n '+' AS '+',\n x.Data_Free + y.Log_Free AS 'F',\n (x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',\n '==' AS '==',\n x.Data, \n x.Data_Used, \n x.Data_Used*100/x.Data AS 'D_U(%)',\n x.Data_Free, \n x.Data_Free*100/x.Data AS 'D_F(%)',\n '++' AS '++', \n y.Log, \n y.Log_Used, \n y.Log_Used*100/y.Log AS 'L_U(%)',\n y.Log_Free, \n y.Log_Free*100/y.Log AS 'L_F(%)'\n FROM \n ( SELECT d.DatabaseName, \n SUM(d.T) AS 'Data', \n SUM(d.U) AS 'Data_Used', \n SUM(d.F) AS 'Data_Free' \n FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY d.DatabaseName ) AS x\n JOIN \n ( SELECT l.DatabaseName, \n SUM(l.T) AS 'Log', \n SUM(l.U) AS 'Log_Used', \n SUM(l.F) AS 'Log_Free' \n FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY l.DatabaseName ) AS y\n ON x.DatabaseName = y.DatabaseName;\n\n IF @Unit = 'KB'\n UPDATE @Tbl_Final SET TOTAL = TOTAL * 1024,\n used = used * 1024,\n free = free * 1024,\n Data = Data * 1024,\n Data_Used = Data_Used * 1024,\n Data_Free = Data_Free * 1024,\n Log = Log * 1024,\n Log_Used = Log_Used * 1024,\n Log_Free = Log_Free * 1024;\n\n IF @Unit = 'GB'\n UPDATE @Tbl_Final SET TOTAL = TOTAL / 1024,\n used = used / 1024,\n free = free / 1024,\n Data = Data / 1024,\n Data_Used = Data_Used / 1024,\n Data_Free = Data_Free / 1024,\n Log = Log / 1024,\n Log_Used = Log_Used / 1024,\n Log_Free = Log_Free / 1024;\n\n DECLARE @GrantTotal dec(11, 2);\n SELECT @GrantTotal = SUM(TOTAL) FROM @Tbl_Final;\n\n SELECT \n CONVERT(dec(10, 2), TOTAL*100.0/@GrantTotal) AS 'WEIGHT (%)', \n DatabaseName AS 'DATABASE',\n CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)' AS 'USED (%)',\n [+],\n CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)' AS 'FREE (%)',\n [=],\n TOTAL, \n [=],\n CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', ' + \n CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',\n [+],\n CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' + \n CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'\n FROM @Tbl_Final \n WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')\n ORDER BY DatabaseName ASC;\n\n IF @TargetDatabase IS NULL\n SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM', \n SUM (used) AS 'USED', \n SUM (free) AS 'FREE', \n SUM (TOTAL) AS 'TOTAL', \n SUM (Data) AS 'DATA', \n SUM (Log) AS 'LOG' \n FROM @Tbl_Final;\n END\n\nRETURN (0)\n\nGO\n</code></pre>\n"
},
{
"answer_id": 4676585,
"author": "Aaron Kempf",
"author_id": 565882,
"author_profile": "https://Stackoverflow.com/users/565882",
"pm_score": 0,
"selected": false,
"text": "<p>if you use SQL Server Management Studio (from SQL 2005 or newer) you can just right-click properties on the database itself, and then click on the storage tab.</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/12906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] | I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out. | Source: <http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1313431,00.html>
Works with SQL2000,2005,2008
```
USE master;
GO
IF OBJECT_ID('dbo.sp_SDS', 'P') IS NOT NULL
DROP PROCEDURE dbo.sp_SDS;
GO
CREATE PROCEDURE dbo.sp_SDS
@TargetDatabase sysname = NULL, -- NULL: all dbs
@Level varchar(10) = 'Database', -- or "File"
@UpdateUsage bit = 0, -- default no update
@Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes
AS
/**************************************************************************************************
**
** author: Richard Ding
** date: 4/8/2008
** usage: list db size AND path w/o SUMmary
** test code: sp_SDS -- default behavior
** sp_SDS 'maAster'
** sp_SDS NULL, NULL, 0
** sp_SDS NULL, 'file', 1, 'GB'
** sp_SDS 'Test_snapshot', 'Database', 1
** sp_SDS 'Test', 'File', 0, 'kb'
** sp_SDS 'pfaids', 'Database', 0, 'gb'
** sp_SDS 'tempdb', NULL, 1, 'kb'
**
**************************************************************************************************/
SET NOCOUNT ON;
IF @TargetDatabase IS NOT NULL AND DB_ID(@TargetDatabase) IS NULL
BEGIN
RAISERROR(15010, -1, -1, @TargetDatabase);
RETURN (-1)
END
IF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_CombinedInfo;
IF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_DbFileStats;
IF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_ValidDbs;
IF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_Logs;
CREATE TABLE dbo.##Tbl_CombinedInfo (
DatabaseName sysname NULL,
[type] VARCHAR(10) NULL,
LogicalName sysname NULL,
T dec(10, 2) NULL,
U dec(10, 2) NULL,
[U(%)] dec(5, 2) NULL,
F dec(10, 2) NULL,
[F(%)] dec(5, 2) NULL,
PhysicalName sysname NULL );
CREATE TABLE dbo.##Tbl_DbFileStats (
Id int identity,
DatabaseName sysname NULL,
FileId int NULL,
FileGroup int NULL,
TotalExtents bigint NULL,
UsedExtents bigint NULL,
Name sysname NULL,
FileName varchar(255) NULL );
CREATE TABLE dbo.##Tbl_ValidDbs (
Id int identity,
Dbname sysname NULL );
CREATE TABLE dbo.##Tbl_Logs (
DatabaseName sysname NULL,
LogSize dec (10, 2) NULL,
LogSpaceUsedPercent dec (5, 2) NULL,
Status int NULL );
DECLARE @Ver varchar(10),
@DatabaseName sysname,
@Ident_last int,
@String varchar(2000),
@BaseString varchar(2000);
SELECT @DatabaseName = '',
@Ident_last = 0,
@String = '',
@Ver = CASE WHEN @@VERSION LIKE '%9.0%' THEN 'SQL 2005'
WHEN @@VERSION LIKE '%8.0%' THEN 'SQL 2000'
WHEN @@VERSION LIKE '%10.0%' THEN 'SQL 2008'
END;
SELECT @BaseString =
' SELECT DB_NAME(), ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE ''Data'' END'
ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-text'' ELSE ''reserved'' END' END +
', name, ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END +
', size*8.0/1024.0 FROM ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END +
' WHERE '
+ CASE WHEN @Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc = ''ONLINE''' END + '';
SELECT @String = 'INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'master.dbo.sysdatabases'
WHEN @Ver IN ('SQL 2005', 'SQL 2008') THEN 'master.sys.databases'
END + ' WHERE HAS_DBACCESS(name) = 1 ORDER BY name ASC';
EXEC (@String);
INSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');
-- For data part
IF @TargetDatabase IS NOT NULL
BEGIN
SELECT @DatabaseName = @TargetDatabase;
IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName,'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT @String = 'USE [' + @DatabaseName + '] DBCC UPDATEUSAGE (0)';
PRINT '*** ' + @String + ' *** ';
EXEC (@String);
PRINT '';
END
SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString;
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
EXEC ('USE [' + @DatabaseName + '] ' + @String);
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName;
END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
SELECT TOP 1 @DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname > @DatabaseName ORDER BY Dbname ASC;
IF @@ROWCOUNT = 0
BREAK;
IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName, 'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT @String = 'DBCC UPDATEUSAGE (''' + @DatabaseName + ''') ';
PRINT '*** ' + @String + '*** ';
EXEC (@String);
PRINT '';
END
SELECT @Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;
SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString;
EXEC ('USE [' + @DatabaseName + '] ' + @String);
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName WHERE Id BETWEEN @Ident_last + 1 AND @@IDENTITY;
END
END
-- set used size for data files, do not change total obtained from sys.database_files as it has for log files
UPDATE dbo.##Tbl_CombinedInfo
SET U = s.UsedExtents*8*8/1024.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s
ON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;
-- set used size and % values for log files:
UPDATE dbo.##Tbl_CombinedInfo
SET [U(%)] = LogSpaceUsedPercent,
U = T * LogSpaceUsedPercent/100.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l
ON l.DatabaseName = t.DatabaseName
WHERE t.type = 'Log';
UPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;
UPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;
IF UPPER(ISNULL(@Level, 'DATABASE')) = 'FILE'
BEGIN
IF @Unit = 'KB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T * 1024, U = U * 1024, F = F * 1024;
IF @Unit = 'GB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T / 1024, U = U / 1024, F = F / 1024;
SELECT DatabaseName AS 'Database',
type AS 'Type',
LogicalName,
T AS 'Total',
U AS 'Used',
[U(%)] AS 'Used (%)',
F AS 'Free',
[F(%)] AS 'Free (%)',
PhysicalName
FROM dbo.##Tbl_CombinedInfo
WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')
ORDER BY DatabaseName ASC, type ASC;
SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM dbo.##Tbl_CombinedInfo;
END
IF UPPER(ISNULL(@Level, 'DATABASE')) = 'DATABASE'
BEGIN
DECLARE @Tbl_Final TABLE (
DatabaseName sysname NULL,
TOTAL dec (10, 2),
[=] char(1),
used dec (10, 2),
[used (%)] dec (5, 2),
[+] char(1),
free dec (10, 2),
[free (%)] dec (5, 2),
[==] char(2),
Data dec (10, 2),
Data_Used dec (10, 2),
[Data_Used (%)] dec (5, 2),
Data_Free dec (10, 2),
[Data_Free (%)] dec (5, 2),
[++] char(2),
Log dec (10, 2),
Log_Used dec (10, 2),
[Log_Used (%)] dec (5, 2),
Log_Free dec (10, 2),
[Log_Free (%)] dec (5, 2) );
INSERT INTO @Tbl_Final
SELECT x.DatabaseName,
x.Data + y.Log AS 'TOTAL',
'=' AS '=',
x.Data_Used + y.Log_Used AS 'U',
(x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',
'+' AS '+',
x.Data_Free + y.Log_Free AS 'F',
(x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',
'==' AS '==',
x.Data,
x.Data_Used,
x.Data_Used*100/x.Data AS 'D_U(%)',
x.Data_Free,
x.Data_Free*100/x.Data AS 'D_F(%)',
'++' AS '++',
y.Log,
y.Log_Used,
y.Log_Used*100/y.Log AS 'L_U(%)',
y.Log_Free,
y.Log_Free*100/y.Log AS 'L_F(%)'
FROM
( SELECT d.DatabaseName,
SUM(d.T) AS 'Data',
SUM(d.U) AS 'Data_Used',
SUM(d.F) AS 'Data_Free'
FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY d.DatabaseName ) AS x
JOIN
( SELECT l.DatabaseName,
SUM(l.T) AS 'Log',
SUM(l.U) AS 'Log_Used',
SUM(l.F) AS 'Log_Free'
FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY l.DatabaseName ) AS y
ON x.DatabaseName = y.DatabaseName;
IF @Unit = 'KB'
UPDATE @Tbl_Final SET TOTAL = TOTAL * 1024,
used = used * 1024,
free = free * 1024,
Data = Data * 1024,
Data_Used = Data_Used * 1024,
Data_Free = Data_Free * 1024,
Log = Log * 1024,
Log_Used = Log_Used * 1024,
Log_Free = Log_Free * 1024;
IF @Unit = 'GB'
UPDATE @Tbl_Final SET TOTAL = TOTAL / 1024,
used = used / 1024,
free = free / 1024,
Data = Data / 1024,
Data_Used = Data_Used / 1024,
Data_Free = Data_Free / 1024,
Log = Log / 1024,
Log_Used = Log_Used / 1024,
Log_Free = Log_Free / 1024;
DECLARE @GrantTotal dec(11, 2);
SELECT @GrantTotal = SUM(TOTAL) FROM @Tbl_Final;
SELECT
CONVERT(dec(10, 2), TOTAL*100.0/@GrantTotal) AS 'WEIGHT (%)',
DatabaseName AS 'DATABASE',
CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)' AS 'USED (%)',
[+],
CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)' AS 'FREE (%)',
[=],
TOTAL,
[=],
CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', ' +
CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',
[+],
CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' +
CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'
FROM @Tbl_Final
WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')
ORDER BY DatabaseName ASC;
IF @TargetDatabase IS NULL
SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (used) AS 'USED',
SUM (free) AS 'FREE',
SUM (TOTAL) AS 'TOTAL',
SUM (Data) AS 'DATA',
SUM (Log) AS 'LOG'
FROM @Tbl_Final;
END
RETURN (0)
GO
``` |
13,000 | <p>I want to define something like this in <em>php</em>:</p>
<pre><code>$EL = "\n<br />\n";
</code></pre>
<p>and then use that variable as an "endline" marker all over my site, like this:</p>
<pre><code>echo "Blah blah blah{$EL}";
</code></pre>
<p>How do I define $EL once (in only 1 file), include it on every page on my site, and <em>not</em> have to reference it using the (strangely backwards) <code>global $EL;</code> statement in every page function?</p>
| [
{
"answer_id": 13003,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": true,
"text": "<p>Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:</p>\n\n<pre><code> include 'header.php';\n</code></pre>\n\n<p>you won't have to use the global keyword or anything, the second line of code you wrote should work.</p>\n\n<p>Edit: Oh sorry, that won't work inside functions... now I see your problem.</p>\n\n<p>Edit #2: Ok, take my original advice with the header, but use a <a href=\"http://php.net/define\" rel=\"noreferrer\">define()</a> rather than a variable. Those work inside functions after being included.</p>\n"
},
{
"answer_id": 13005,
"author": "cringe",
"author_id": 834,
"author_profile": "https://Stackoverflow.com/users/834",
"pm_score": -1,
"selected": false,
"text": "<p>IIRC a common solution is a plain file that contains your declarations, that you include in every source file, something like '<em>constants.inc.php</em>'. There you can define a bunch of application-wide variables that are then imported in every file.</p>\n\n<p>Still, you have to provide the include directive in <strong>every</strong> single source file you use. I even saw some projects using this technique to provide localizations for several languages. I'd prefer the gettext way, but maybe this variant is easier to work with for the average user.</p>\n\n<p><strong>edit</strong> For your problem I recomment the use of <strong>$GLOBALS[]</strong>, see <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">Example #2</a> for details.</p>\n\n<p>If that's still not applicable, I'd try to digg down PHP5 objects and create a static Singleton that provides needed static constants (<a href=\"http://www.developer.com/lang/php/article.php/3345121\" rel=\"nofollow noreferrer\">http://www.developer.com/lang/php/article.php/3345121</a>)</p>\n"
},
{
"answer_id": 13008,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": -1,
"selected": false,
"text": "<p>Sessions are going to be your best bet, if the data is user specific, else just use a conifg file.\nconfig.php:</p>\n\n<pre><code><?php\n$EL = \"\\n<br />\\n\";\n?>\n</code></pre>\n\n<p>Then on each page add</p>\n\n<pre><code>require 'config.php'\n</code></pre>\n\n<p>the you will be able to access $EL on that page.</p>\n"
},
{
"answer_id": 13058,
"author": "TT.",
"author_id": 868,
"author_profile": "https://Stackoverflow.com/users/868",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like the job of a constant. See the function <a href=\"http://us2.php.net/define\" rel=\"nofollow noreferrer\">define()</a>.</p>\n"
},
{
"answer_id": 13075,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>@svec yes this will, you just have to include the file inside the function also. This is how most of my software works.</p>\n\n<pre><code>function myFunc()\n {\nrequire 'config.php';\n//Variables from config are available now.\n }\n</code></pre>\n"
},
{
"answer_id": 13094,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using PHP5? If you define the __autoload() function and use a class with some constants, you can call them where you need them. The only aggravating thing about this is that you have to type something a little longer, like </p>\n\n<pre><code>MyClass::MY_CONST\n</code></pre>\n\n<p>The benefit is that if you ever decide to change the way that you handle new lines, you only have to change it in one place.</p>\n\n<p>Of course, a possible negative is that you're calling including an extra function (__autoload()), running that function (when you reference the class), which then loads another file (your class file). That might be more overhead than it's worth.</p>\n\n<p>If I may offer a suggestion, it would be avoiding this sort of echoing that requires echoing tags (like <code><br /></code>). If you could set up something a little more template-esque, you could handle the nl's without having to explicitly type them. So instead of</p>\n\n<pre><code>echo \"Blah Blah Blah\\n<br />\\n\";\n</code></pre>\n\n<p>try:</p>\n\n<pre><code><?php\nif($condition) {\n?>\n<p>Blah blah blah\n<br />\n</p>\n<?php\n}\n?>\n</code></pre>\n\n<p>It just seems to me like calling up classes or including variables within functions as well as out is a lot of work that doesn't need to be done, and, if at all possible, those sorts of situations are best avoided.</p>\n"
},
{
"answer_id": 53094,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to use an object with public static properties. I used to use $GLOBALS but most editors don't auto complete $GLOBALS. Also, un-instantiated classes are available everywhere (because you can instatiate everywhere without telling PHP you are going to use the class). Example:</p>\n\n<pre><code><?php\n\nclass SITE {\n public static $el;\n}\n\nSITE::$el = \"\\n<br />\\n\";\n\nfunction Test() {\n echo SITE::$el;\n}\n\nTest();\n\n?>\n</code></pre>\n\n<p>This will output <code><br /></code></p>\n\n<p>This is also easier to deal with than costants as you can put any type of value within the property (array, string, int, etc) whereas constants cannot contain arrays.</p>\n\n<p>This was suggested to my by a user on the <a href=\"http://forum.nusphere.com\" rel=\"nofollow noreferrer\">PhpEd forums</a>.</p>\n"
},
{
"answer_id": 53672,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 0,
"selected": false,
"text": "<p>svec, use a PHP framework. Just any - there's plenty of them out there.\nThis is the right way to do it. With framework you have single entry\npoint for your application, so defining site-wide variables is easy and\nnatural. Also you don't need to care about including header files nor\nchecking if user is logged in on every page - decent framework will do\nit for you.</p>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://framework.zend.com/\" rel=\"nofollow noreferrer\">Zend framework</a></li>\n<li><a href=\"http://cakephp.org/\" rel=\"nofollow noreferrer\">CakePHP</a></li>\n<li><a href=\"http://www.symfony-project.org/\" rel=\"nofollow noreferrer\">Symfony</a></li>\n<li><a href=\"http://kohanaphp.com/\" rel=\"nofollow noreferrer\">Kohana</a></li>\n</ul>\n\n<p>Invest some time in learning one of them and it will pay back very soon.</p>\n"
},
{
"answer_id": 4432971,
"author": "dbwebtek",
"author_id": 538362,
"author_profile": "https://Stackoverflow.com/users/538362",
"pm_score": 2,
"selected": false,
"text": "<p>Do this\n<code>\ndefine ('el','\\n\\<\\br/>\\n');\n</code>\nsave it as el.php</p>\n\n<p>then you can include any files you want to use, i.e</p>\n\n<p>echo 'something'.el; // note I just add el at end of line or in front</p>\n\n<p>Hope this help</p>\n\n<p>NOTE please remove the '\\' after < br since I had to put it in or it wont show br tag on the answer...</p>\n"
},
{
"answer_id": 59923336,
"author": "Progrock",
"author_id": 3392762,
"author_profile": "https://Stackoverflow.com/users/3392762",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <a href=\"https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file\" rel=\"nofollow noreferrer\">auto_prepend_file directive</a> to pre parse a file. Add the directive to your configuration, and point it to a file in your include path. In that file add your constants, global variables, functions or whatever you like.</p>\n\n<p>So if your prepend file contains:</p>\n\n<pre><code><?php\ndefine('FOO', 'badger');\n</code></pre>\n\n<p>In another Php file you could access the constant:</p>\n\n<pre><code>echo 'this is my '. FOO;\n</code></pre>\n"
},
{
"answer_id": 63679111,
"author": "Ezekiel Arin",
"author_id": 14135718,
"author_profile": "https://Stackoverflow.com/users/14135718",
"pm_score": 0,
"selected": false,
"text": "<p>You might consider using a framework to achieve this. Better still you can use</p>\n<pre><code>Include 'functions.php';\nrequire('functions');\n</code></pre>\n<p>Doing OOP is another alternative</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103/"
] | I want to define something like this in *php*:
```
$EL = "\n<br />\n";
```
and then use that variable as an "endline" marker all over my site, like this:
```
echo "Blah blah blah{$EL}";
```
How do I define $EL once (in only 1 file), include it on every page on my site, and *not* have to reference it using the (strangely backwards) `global $EL;` statement in every page function? | Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
```
include 'header.php';
```
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a [define()](http://php.net/define) rather than a variable. Those work inside functions after being included. |
13,021 | <p>I've frequently encountered sites that put all of their JavaScript inside a <code>namespace</code> structure along the lines of:</p>
<pre><code>namespaces = { com : { example: { example.com's data} }
</code></pre>
<p>However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the <code>com</code> namespace directly attached to the global object, or is it attached through a namespace object?</p>
<p>[Edit: whoops, obviously <code>{com = { ... } }</code> wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.] </p>
| [
{
"answer_id": 13193,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope. </p>\n\n<p>Here's your example, corrected:</p>\n\n<pre><code>var namespaces = { com: { example: { /* example.com's data */ } } }\n</code></pre>\n\n<p>This is a variable <code>namespaces</code> being assigned an object literal. The object contains one property: <code>com</code>, an object with one property: <code>example</code>, an object which presumably would contain something interesting.</p>\n\n<p>So, you can type something like <strong>namespaces.com.example.<em>somePropertyOrFunctionOnExample</em></strong> and it'll all work. Of course, it's also ridiculous. You don't have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.</p>\n\n<pre><code>var com_example_data = { /* example.com's data */ };\n</code></pre>\n\n<p>That works just as well, without the pointless hierarchy. </p>\n\n<p><strong>Now</strong>, if you actually <em>want</em> to build a hierarchy, you can try something like this:</p>\n\n<pre><code>com_example = com_example || {};\ncom_example.flags = com_example.flags || { active: false, restricted: true};\n\ncom_example.ops = com_example.ops || (function()\n {\n var launchCodes = \"38925491753824\"; // hidden / private\n return {\n activate: function() { /* ... */ },\n destroyTheWorld: function() { /* ... */ }\n };\n })();\n</code></pre>\n\n<p>...which is, IMHO, reasonably concise.</p>\n"
},
{
"answer_id": 13194,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://developer.yahoo.com/yui/yahoo/\" rel=\"nofollow noreferrer\">YUI library</a> library has code which handles namespacing using a function which you may find preferable. Other libraries may do this also.</p>\n"
},
{
"answer_id": 13522,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 4,
"selected": false,
"text": "<p>Here was an interesting article by Peter Michaux on <a href=\"http://peter.michaux.ca/article/7944\" rel=\"noreferrer\">Javascript Namespacing</a>. He discusses 3 different types of Javascript namespacing:</p>\n\n<ol>\n<li>Prefix Namespacing</li>\n<li>Single Object Namespacing</li>\n<li>Nested Object Namespacing</li>\n</ol>\n\n<p>I won't plagiarize what he said here but I think his article is very informative.</p>\n\n<p>Peter even went so far as to point out that there are performance considerations with some of them. I think this topic would be interesting to talk about considering that the new ECMAScript Harmony plans have dropped the 4.0 plans for namespacing and packaging.</p>\n"
},
{
"answer_id": 13583,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 3,
"selected": false,
"text": "<p>I try to follow the Yahoo convention of making a single parent object out in the global scope to contain everything;</p>\n\n<pre><code>var FP = {};\nFP.module = {};\nFP.module.property = 'foo';\n</code></pre>\n"
},
{
"answer_id": 14085,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>As an alternative to a dot or an underscore, you could use the dollar sign character:</p>\n\n<pre><code>var namespaces$com$example = \"data\"; \n</code></pre>\n"
},
{
"answer_id": 14748,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 3,
"selected": false,
"text": "<p>To make sure you don't overwrite an existing object, you should so something like:</p>\n\n<pre><code>if(!window.NameSpace) {\n NameSpace = {};\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var NameSpace = window.NameSpace || {};\n</code></pre>\n\n<p>This way you can put this at the top of every file in your application/website without worrying about the overwriting the namespace object. Also, this would enable you to write unit tests for each file individually.</p>\n"
},
{
"answer_id": 1015213,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 1,
"selected": false,
"text": "<p>I like also this (<a href=\"http://code.google.com/apis/ajax/playground/#anonymous_function_for_clean_namespace\" rel=\"nofollow noreferrer\">source</a>):</p>\n\n<pre><code>(function() {\n var a = 'Invisible outside of anonymous function';\n function invisibleOutside() {\n }\n\n function visibleOutside() {\n }\n window.visibleOutside = visibleOutside;\n\n var html = '--INSIDE Anonymous--';\n html += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;\n html += '<br/> typeof visibleOutside: ' + typeof visibleOutside;\n contentDiv.innerHTML = html + '<br/><br/>';\n})();\n\nvar html = '--OUTSIDE Anonymous--';\nhtml += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;\nhtml += '<br/> typeof visibleOutside: ' + typeof visibleOutside;\ncontentDiv.innerHTML += html + '<br/>';\n</code></pre>\n"
},
{
"answer_id": 9847719,
"author": "Paul Sweatte",
"author_id": 1113772,
"author_profile": "https://Stackoverflow.com/users/1113772",
"pm_score": 0,
"selected": false,
"text": "<p>Use an object literal and either the <code>this</code> object or the explicit name to do namespacing based on the sibling properties of the local variable which contains the function. For example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var foo = { bar: function(){return this.name; }, name: \"rodimus\" }\r\nvar baz = { bar: function(){return this.name; }, name: \"optimus\" }\r\n\r\nconsole.log(foo.bar());\r\nconsole.log(baz.bar());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or without the explicit <code>name</code> property:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var foo = { bar: function rodimus(){return this; } }\r\nvar baz = { bar: function optimus(){return this; } }\r\n\r\nconsole.log(foo.bar.name);\r\nconsole.log(baz.bar.name);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or without using <code>this</code>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var foo = { bar: function rodimus(){return rodimus; } }\r\nvar baz = { bar: function optimus(){return optimus; } }\r\n\r\nconsole.log(foo.bar.name);\r\nconsole.log(baz.bar.name);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Use the <code>RegExp</code> or <code>Object</code> constructor functions to add name properties to counter variables and other common names, then use a <code>hasOwnProperty</code> test to do checking:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> var foo = RegExp(/bar/);\r\n \r\n/* Add property */\r\nfoo.name = \"alpha\";\r\n\r\ndocument.body.innerHTML = String(\"<pre>\" + [\"name\", \"value\", \"namespace\"] + \"</pre>\").replace(/,/g, \"&#09;\");\r\n\r\n/* Check type */\r\nif (foo.hasOwnProperty(\"name\")) \r\n {\r\n document.body.innerHTML += String(\"<pre>\" + [\"foo\", String(foo.exec(foo)), foo.name] + \"</pre>\").replace(/,/g, \"&#09;\");\r\n }\r\n\r\n/* Fallback to atomic value */\r\nelse \r\n {\r\n foo = \"baz\";\r\n }\r\n\r\nvar counter = Object(1);\r\n\r\n/* Add property */\r\ncounter.name = \"beta\";\r\n\r\nif (counter.hasOwnProperty(\"name\")) \r\n {\r\n document.body.innerHTML += String(\"<pre>\" + [\"counter\", Number(counter), counter.name] + \"</pre>\").replace(/,/g, \"&#09;\");\r\n } \r\nelse \r\n {\r\n /* Fallback to atomic value */\r\n counter = 0;\r\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The DOM uses the following convention to namespace HTML and SVG Element interface definitions:</p>\n\n<ul>\n<li>HTMLTitleElement</li>\n<li>SVGTitleElement</li>\n<li>SVGScriptElement</li>\n<li>HTMLScriptElement</li>\n</ul>\n\n<p>JavaScript core uses prototypes to namespace the <code>toString</code> method as a simple form of polymorphism.</p>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/17216847/1113772\">Does javascript autobox?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/17216496/1113772\">Getting sibling value of key in a JavaScript object literal</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method\" rel=\"nofollow noreferrer\">MDN: JavaScript Operators - this as an object method</a></li>\n<li><a href=\"https://www.lua.org/notes/ltn007.html\" rel=\"nofollow noreferrer\">Lua: technical note 7 - Modules and Packages</a></li>\n<li><a href=\"https://github.com/mozilla/gecko-dev/blob/master/dom/webidl/HTMLTitleElement.webidl\" rel=\"nofollow noreferrer\">HTMLTitleElement.webidl</a></li>\n<li><a href=\"https://github.com/mozilla/gecko-dev/blob/master/dom/webidl/SVGTitleElement.webidl\" rel=\"nofollow noreferrer\">SVGTitleElement.webidl</a></li>\n<li><a href=\"https://github.com/mozilla/gecko-dev/blob/master/dom/webidl/SVGScriptElement.webidl\" rel=\"nofollow noreferrer\">SVGScriptElement.webidl</a></li>\n<li><a href=\"https://github.com/mozilla/gecko-dev/blob/master/dom/webidl/HTMLScriptElement.webidl\" rel=\"nofollow noreferrer\">HTMLScriptElement.webidl</a></li>\n<li><a href=\"http://www.2ality.com/2015/09/function-names-es6.html\" rel=\"nofollow noreferrer\">The names of functions in ES6</a></li>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances-name\" rel=\"nofollow noreferrer\">ECMAScript 2015 Language Specification - 19.2.4.2 Function Instances: name | ECMA-262 6th Edition</a></li>\n</ul>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784/"
] | I've frequently encountered sites that put all of their JavaScript inside a `namespace` structure along the lines of:
```
namespaces = { com : { example: { example.com's data} }
```
However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the `com` namespace directly attached to the global object, or is it attached through a namespace object?
[Edit: whoops, obviously `{com = { ... } }` wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.] | Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope.
Here's your example, corrected:
```
var namespaces = { com: { example: { /* example.com's data */ } } }
```
This is a variable `namespaces` being assigned an object literal. The object contains one property: `com`, an object with one property: `example`, an object which presumably would contain something interesting.
So, you can type something like **namespaces.com.example.*somePropertyOrFunctionOnExample*** and it'll all work. Of course, it's also ridiculous. You don't have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.
```
var com_example_data = { /* example.com's data */ };
```
That works just as well, without the pointless hierarchy.
**Now**, if you actually *want* to build a hierarchy, you can try something like this:
```
com_example = com_example || {};
com_example.flags = com_example.flags || { active: false, restricted: true};
com_example.ops = com_example.ops || (function()
{
var launchCodes = "38925491753824"; // hidden / private
return {
activate: function() { /* ... */ },
destroyTheWorld: function() { /* ... */ }
};
})();
```
...which is, IMHO, reasonably concise. |
13,060 | <p>I'm looking for a clear, concise and accurate answer. </p>
<p>Ideally as the actual answer, although links to good explanations welcome.</p>
<p>This also applies to VB.Net, but the keywords are different - <code>ByRef</code> and <code>ByVal</code>.</p>
| [
{
"answer_id": 13061,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p><code>out</code> means that the parameter will be initialised by the method:</p>\n\n<pre><code>int result; //not initialised\n\nif( int.TryParse( \"123\", out result ) )\n //result is now 123\nelse\n //if TryParse failed result has still be \n // initialised to its default value (0)\n</code></pre>\n\n<p><code>ref</code> will force the underlying reference to be passed:</p>\n\n<pre><code>void ChangeMyClass1( MyClass input ) {\n input.MyProperty = \"changed by 1\";\n input = null;\n //can't see input anymore ... \n // I've only nulled my local scope's reference\n}\n\nvoid ChangeMyClass2( ref MyClass input ) {\n input.MyProperty = \"changed by 2\";\n input = null;\n //the passed reference is now null too.\n}\n\nMyClass tester = new MyClass { MyProperty = \"initial value\" };\n\nChangeMyClass1( tester );\n// now tester.MyProperty is \"changed by 1\"\n\nChangeMyClass2( ref tester );\n// now tester is null\n</code></pre>\n"
},
{
"answer_id": 13070,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 2,
"selected": false,
"text": "<p>One of my own questions at stackoverflow handles this topic too.<br>\nIt handles about <a href=\"https://stackoverflow.com/questions/2027/pass-by-reference-or-pass-by-value\">\"pass by reference\" and \"pass by value\"</a> in different types of languages, <a href=\"https://stackoverflow.com/questions/2027/pass-by-reference-or-pass-by-value#2554\">c# is included</a> so maybe you can find some extra information there as well.</p>\n\n<p>Basically it comes down to:</p>\n\n<ul>\n<li>ref: the parameter with the ref keyword will be passed <em>by reference</em></li>\n<li>out: the parameter with the out keyword will be treated as an <em>output parameter</em></li>\n</ul>\n\n<p>but that's really the most basic answer you can give, as it is a little more complex than it is stated here</p>\n"
},
{
"answer_id": 13100,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 6,
"selected": true,
"text": "<p>By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.</p>\n\n<pre><code>void Test1(string param)\n{\n param = \"new value\";\n}\n\nstring s1 = \"initial value\";\nTest1(s1);\n// s1 == \"initial value\"\n</code></pre>\n\n<p>Using <code>out</code> or <code>ref</code> passes a reference to the variable specified in the call to the function. Any changes to the value of an <code>out</code> or <code>ref</code> parameter will be passed back to the caller.</p>\n\n<p>Both <code>out</code> and <code>ref</code> behave identically except for one slight difference: <code>ref</code> parameters are required to be initialised before calling, while <code>out</code> parameters can be uninitialised. By extension, <code>ref</code> parameters are guaranteed to be initialised at the start of the method, while <code>out</code> parameters are treated as uninitialised.</p>\n\n<pre><code>void Test2(ref string param)\n{\n param = \"new value\";\n}\n\nvoid Test3(out string param)\n{\n // Use of param here will not compile\n param = \"another value\";\n}\n\nstring s2 = \"initial value\";\nstring s3;\nTest2(ref s2);\n// s2 == \"new value\"\n// Test2(ref s3); // Passing ref s3 will not compile\nTest3(out s2);\n// s2 == \"another value\"\nTest3(out s3);\n// s3 == \"another value\"\n</code></pre>\n\n<p><strong>Edit</strong>: As <a href=\"https://stackoverflow.com/questions/13060/what-do-ref-val-and-out-mean-on-method-parameters#13105\" title=\"dp\">dp</a> points out, the difference between <code>out</code> and <code>ref</code> is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for <code>out</code> and implements <code>ref</code> (as <code>ByRef</code>) only, matching the support of the CLR.</p>\n"
},
{
"answer_id": 13105,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 3,
"selected": false,
"text": "<p>One additional note about ref vs. out: The distinction between the two is enforced by the C# compiler. The CLR does not distinguish between between out and ref. This means that you cannot have two methods whose signatures differ only by an out or ref</p>\n\n<pre><code>void foo(int value) {}\n\n// Only one of the following would be allowed\n\n// valid to overload with ref\nvoid foo(ref int value) {}\n\n// OR with out\nvoid foo(out int value) {}\n</code></pre>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | I'm looking for a clear, concise and accurate answer.
Ideally as the actual answer, although links to good explanations welcome.
This also applies to VB.Net, but the keywords are different - `ByRef` and `ByVal`. | By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.
```
void Test1(string param)
{
param = "new value";
}
string s1 = "initial value";
Test1(s1);
// s1 == "initial value"
```
Using `out` or `ref` passes a reference to the variable specified in the call to the function. Any changes to the value of an `out` or `ref` parameter will be passed back to the caller.
Both `out` and `ref` behave identically except for one slight difference: `ref` parameters are required to be initialised before calling, while `out` parameters can be uninitialised. By extension, `ref` parameters are guaranteed to be initialised at the start of the method, while `out` parameters are treated as uninitialised.
```
void Test2(ref string param)
{
param = "new value";
}
void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}
string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"
```
**Edit**: As [dp](https://stackoverflow.com/questions/13060/what-do-ref-val-and-out-mean-on-method-parameters#13105 "dp") points out, the difference between `out` and `ref` is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for `out` and implements `ref` (as `ByRef`) only, matching the support of the CLR. |
13,109 | <p>In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:</p>
<pre><code>// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
</code></pre>
<p>This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)</p>
| [
{
"answer_id": 13113,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 5,
"selected": true,
"text": "<p>I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:</p>\n\n<pre><code>$variable = array('a','b','c');\necho $variable[$key];\nunset($variable);\n</code></pre>\n\n<p>Or, you could write a small function:</p>\n\n<pre><code>function indexonce(&$ar, $index) {\n return $ar[$index];\n}\n</code></pre>\n\n<p>and call this with:</p>\n\n<pre><code>$something = indexonce(array('a', 'b', 'c'), 2);\n</code></pre>\n\n<p>The array should be destroyed automatically now.</p>\n"
},
{
"answer_id": 31942,
"author": "John Douthat",
"author_id": 2774,
"author_profile": "https://Stackoverflow.com/users/2774",
"pm_score": 5,
"selected": false,
"text": "<p>The technical answer is that the <strong><em>Grammar</em></strong> of the PHP language only allows subscript notation on the end of <strong>variable expressions</strong> and not <strong>expressions</strong> in general, which is how it works in most other languages. I've always viewed it as a deficiency in the language, because it is possible to have a grammar that resolves subscripts against any expression unambiguously. It could be the case, however, that they're using an inflexible parser generator or they simply don't want to break some sort of backwards compatibility.</p>\n\n<p>Here are a couple more examples of invalid subscripts on valid expressions:</p>\n\n<pre><code>$x = array(1,2,3);\nprint ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.\n\nfunction ret($foo) { return $foo; }\necho ret($x)[1]; // illegal, on a call expression, not a variable exp.\n</code></pre>\n"
},
{
"answer_id": 1270349,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Or something like this, if you need the array value in a variable</p>\n\n<pre><code>$variable = array('a','b','c');\n$variable = $variable[$key];\n</code></pre>\n"
},
{
"answer_id": 2912626,
"author": "John Smith",
"author_id": 350866,
"author_profile": "https://Stackoverflow.com/users/350866",
"pm_score": 1,
"selected": false,
"text": "<p>actually, there is an elegant solution:) The following will assign the 3rd element of the array returned by myfunc to $myvar:</p>\n\n<pre><code>$myvar = array_shift(array_splice(myfunc(),2));\n</code></pre>\n"
},
{
"answer_id": 5040293,
"author": "tjma2001",
"author_id": 622961,
"author_profile": "https://Stackoverflow.com/users/622961",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function doSomething()\n{\n return $somearray;\n}\n\necho doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();\n</code></pre>\n"
},
{
"answer_id": 7888561,
"author": "Mbrevda",
"author_id": 747749,
"author_profile": "https://Stackoverflow.com/users/747749",
"pm_score": 5,
"selected": false,
"text": "<p>This is called array dereferencing. It has been added in php 5.4.\n<a href=\"http://www.php.net/releases/NEWS_5_4_0_alpha1.txt\">http://www.php.net/releases/NEWS_5_4_0_alpha1.txt</a></p>\n\n<p><em>update[2012-11-25]:</em> as of PHP 5.5, dereferencing has been added to contants/strings as well as arrays</p>\n"
},
{
"answer_id": 8613413,
"author": "Uneebe",
"author_id": 283534,
"author_profile": "https://Stackoverflow.com/users/283534",
"pm_score": 3,
"selected": false,
"text": "<p>This might not be directly related.. But I came to this post finding solution to this specific problem.</p>\n\n<p>I got a result from a function in the following form.</p>\n\n<pre><code>Array\n(\n [School] => Array\n (\n [parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a\n )\n)\n</code></pre>\n\n<p>what i wanted was the parent_id value \"9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a\".\nI used the function like this and got it. </p>\n\n<pre><code>array_pop( array_pop( the_function_which_returned_the_above_array() ) )\n</code></pre>\n\n<p>So, It was done in one line :)\nHope It would be helpful to somebody.</p>\n"
},
{
"answer_id": 35601314,
"author": "Dan Jay",
"author_id": 2035600,
"author_profile": "https://Stackoverflow.com/users/2035600",
"pm_score": 0,
"selected": false,
"text": "<p>There are several <em>oneliners</em> you could come up with, using php <strong>array_*</strong> functions. But I assure you that doing so it is total redundant comparing what you want to achieve. </p>\n\n<p>Example you can use something like following, but it is not an elegant solution and I'm not sure about the performance of this;</p>\n\n<pre><code> array_pop ( array_filter( array_returning_func(), function($key){ return $key==\"array_index_you_want\"? TRUE:FALSE; },ARRAY_FILTER_USE_KEY ) );\n</code></pre>\n\n<p>if you are using a php framework and you are stuck with an older version of php, most frameworks has helping libraries.</p>\n\n<p>example: Codeigniter array helpers</p>\n"
},
{
"answer_id": 51780191,
"author": "Elementary",
"author_id": 10127060,
"author_profile": "https://Stackoverflow.com/users/10127060",
"pm_score": 0,
"selected": false,
"text": "<p>though the fact that dereferencing has been added in PHP >=5.4 you could have done it in one line using ternary operator:</p>\n\n<pre><code>echo $var=($var=array(0,1,2,3))?$var[3]:false;\n</code></pre>\n\n<p>this way you don't keep the array only the variable. and you don't need extra functions to do it...If this line is used in a function it will automatically be destroyed at the end but you can also destroyed it yourself as said with <code>unset</code> later in the code if it is not used in a function.</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] | In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:
```
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
```
This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;) | I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:
```
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
```
Or, you could write a small function:
```
function indexonce(&$ar, $index) {
return $ar[$index];
}
```
and call this with:
```
$something = indexonce(array('a', 'b', 'c'), 2);
```
The array should be destroyed automatically now. |
13,160 | <p>I've created a webservice and when I want to use its methods I instantiate it in the a procedure, call the method, and I finally I dispose it, however I think also it could be okay to instantiate the webservice in the "private void Main_Load(object sender, EventArgs e)" event.</p>
<p>The thing is that if I do it the first way I have to instantiate the webservice every time I need one of its methods but in the other way I have to keep a webservice connected all the time when I use it in a form for example. </p>
<p>I would like to know which of these practices are better or if there's a much better way to do it</p>
<p><strong>Strategy 1</strong></p>
<pre><code>private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
if (svc != null)
svc.Dispose();
}
}
</code></pre>
<p><strong>Strategy 2</strong></p>
<pre><code>private myWebservice svc;
private void Main_Load(object sender, EventArgs e)
{
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
}
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void Main_Closing(object sender, CancelEventArgs e)
{
svc.Dispose();
}
</code></pre>
| [
{
"answer_id": 13164,
"author": "Brandon Wood",
"author_id": 423,
"author_profile": "https://Stackoverflow.com/users/423",
"pm_score": 3,
"selected": true,
"text": "<p>It depends on how often you are going to be calling the web service. If you're going to be calling it almost constantly, it would probably be better to use method #2. However, if it's not going to be getting called quite so often, you are better off using method #1, and only instantiating it when you need it.</p>\n"
},
{
"answer_id": 13171,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 0,
"selected": false,
"text": "<p>Right now I made a solution for a mobile device and it turns to be used on irregular times, it could be used in 10 minutes, 1 hour, 4 hours its very variable, it seems that the better aproach is the first strategy.</p>\n\n<p>Last year we went on a project where we used webservices, the fact is that we instantiated our webservices at the Sub New() procedure and it run it very well, however, sometimes some users claimed at us that they woke up from their chairs and when they returned and tried to continue on the application they received a timeout error message and they had to re-login again.</p>\n\n<p>We thougth that maybe that was Ok because maybe the users went out for a very long time out of their seats, but once in a presentation of the application with the CEOs it happened exactly the same scenario and personally I didn't like that behaviour and that's why the question.</p>\n\n<p>Thanks for the answer.</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130097/"
] | I've created a webservice and when I want to use its methods I instantiate it in the a procedure, call the method, and I finally I dispose it, however I think also it could be okay to instantiate the webservice in the "private void Main\_Load(object sender, EventArgs e)" event.
The thing is that if I do it the first way I have to instantiate the webservice every time I need one of its methods but in the other way I have to keep a webservice connected all the time when I use it in a form for example.
I would like to know which of these practices are better or if there's a much better way to do it
**Strategy 1**
```
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
if (svc != null)
svc.Dispose();
}
}
```
**Strategy 2**
```
private myWebservice svc;
private void Main_Load(object sender, EventArgs e)
{
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
}
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void Main_Closing(object sender, CancelEventArgs e)
{
svc.Dispose();
}
``` | It depends on how often you are going to be calling the web service. If you're going to be calling it almost constantly, it would probably be better to use method #2. However, if it's not going to be getting called quite so often, you are better off using method #1, and only instantiating it when you need it. |
13,170 | <p>From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:</p>
<pre><code>// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
this.mThread.Start(60000);
}
else
{
this.mThread.Start(0);
}
</code></pre>
<p>So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring?</p>
| [
{
"answer_id": 13207,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>A ThreadStateException is thrown because you're trying to start a thread that's not in a startable state. The most likely situations would be that it's already running, or that it has fully exited.</p>\n\n<p>There are potentially a couple things that might be happening. First is, the thread might have transitioned from Running to StopRequested, which isn't fully stopped yet, so your logic doesn't create a new thread, and you're trying to start a thread which has just finished running or is about to finish running (neither of which is a valid state for restarting).</p>\n\n<p>The other possibility is that the thread was aborted. Threads which are aborted go to the Aborted state, not the Stopped state, and of course are also not valid for restarting.</p>\n\n<p>Really, the only kind of thread that is still alive that can be \"restarted\" is one that's suspended. You might want to use this conditional instead:</p>\n\n<p><code>if (this.mThread == null || this.mThread.ThreadState != ThreadState.Suspended)</code></p>\n"
},
{
"answer_id": 13214,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 3,
"selected": false,
"text": "<p>It's possible for a thread to be in more than one state at once therefore the ThreadState property is actually a bitmap of possible states. So testing for equality with just one state will not give you the right result. You would need to do something like:</p>\n\n<pre><code>if((mThread.ThreadState & ThreadState.Running) != 0)\n</code></pre>\n\n<p>However, checking thread state is the wrong to do anything. I'm not entirely clear what you're trying to achieve but I will guess that you're waiting for a thread to terminate before restarting it. In that case you should do:</p>\n\n<pre><code>mThread.Join();\nmThread = new Thread(new ParameterizedThreadStart(Monitor));\nif(check)\n mThread.Start(60000);\nelse\n mThread.Start(0);\n</code></pre>\n\n<p>Although if you describe the problem you're trying to solve in more detail I'm almost certain there will be a better solution. Waiting around for a thread to end just to restart it again doesn't seem that efficient to me. Perhaps you just need some kind of inter-thread communication?</p>\n\n<p>John.</p>\n"
},
{
"answer_id": 13255,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that you have code that first checks if it should create a new thread object, and another piece of code that determines wether to start the thread object. Due to race conditions and similar things, your code might end up trying to call .Start on an existing thread object. Considering you don't post the details behind the <em>check</em> variable, it's impossible to know what might trigger this behavior.</p>\n\n<p>You should reorganize your code so that .Start is guaranteed to only be called on new objects. In short, you should put the Start method into the same if-statement as the one that creates a new thread object.</p>\n\n<p>Personally, I would try to reorganize the entire code so that I didn't need to create another thread, but wrap the code inside the thread object inside a loop so that the thread just keeps on going.</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:
```
// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
this.mThread.Start(60000);
}
else
{
this.mThread.Start(0);
}
```
So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring? | The problem is that you have code that first checks if it should create a new thread object, and another piece of code that determines wether to start the thread object. Due to race conditions and similar things, your code might end up trying to call .Start on an existing thread object. Considering you don't post the details behind the *check* variable, it's impossible to know what might trigger this behavior.
You should reorganize your code so that .Start is guaranteed to only be called on new objects. In short, you should put the Start method into the same if-statement as the one that creates a new thread object.
Personally, I would try to reorganize the entire code so that I didn't need to create another thread, but wrap the code inside the thread object inside a loop so that the thread just keeps on going. |
13,204 | <p>I have a cron job on an Ubuntu Hardy VPS that only half works and I can't work out why. The job is a Ruby script that uses mysqldump to back up a MySQL database used by a Rails application, which is then gzipped and uploaded to a remote server using SFTP.</p>
<p>The gzip file is created and copied successfully but it's always zero bytes. Yet if I run the cron command directly from the command line it works perfectly.</p>
<p>This is the cron job:</p>
<pre><code>PATH=/usr/bin
10 3 * * * ruby /home/deploy/bin/datadump.rb
</code></pre>
<p>This is datadump.rb:</p>
<pre><code>#!/usr/bin/ruby
require 'yaml'
require 'logger'
require 'rubygems'
require 'net/ssh'
require 'net/sftp'
APP = '/home/deploy/apps/myapp/current'
LOGFILE = '/home/deploy/log/data.log'
TIMESTAMP = '%Y%m%d-%H%M'
TABLES = 'table1 table2'
log = Logger.new(LOGFILE, 5, 10 * 1024)
dump = "myapp-#{Time.now.strftime(TIMESTAMP)}.sql.gz"
ftpconfig = YAML::load(open('/home/deploy/apps/myapp/shared/config/sftp.yml'))
config = YAML::load(open(APP + '/config/database.yml'))['production']
cmd = "mysqldump -u #{config['username']} -p#{config['password']} -h #{config['host']} --add-drop-table --add-locks --extended-insert --lock-tables #{config['database']} #{TABLES} | gzip -cf9 > #{dump}"
log.info 'Getting ready to create a backup'
`#{cmd}`
# Strongspace
log.info 'Backup created, starting the transfer to Strongspace'
Net::SSH.start(ftpconfig['strongspace']['host'], ftpconfig['strongspace']['username'], ftpconfig['strongspace']['password']) do |ssh|
ssh.sftp.connect do |sftp|
sftp.open_handle("#{ftpconfig['strongspace']['dir']}/#{dump}", 'w') do |handle|
sftp.write(handle, open("#{dump}").read)
end
end
end
log.info 'Finished transferring backup to Strongspace'
log.info 'Removing local file'
cmd = "rm -f #{dump}"
log.debug "Executing: #{cmd}"
`#{cmd}`
log.info 'Local file removed'
</code></pre>
<p>I've checked and double-checked all the paths and they're correct. Both <strong>sftp.yml</strong> (SFTP credentials) and <strong>database.yml</strong> (MySQL credentials) are owned by the executing user (deploy) with read-only permissions for that user (chmod 400). I'm using the 1.1.x versions of net-ssh and net-sftp. I know they're not the latest, but they're what I'm familiar with at the moment.</p>
<p>What could be causing the cron job to fail?</p>
| [
{
"answer_id": 13220,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 3,
"selected": true,
"text": "<p>Are you sure the temporary file is being created correctly when running as a cron job? The working directory for your script will either be specified in the HOME environment variable, or the /etc/passwd entry for the user that installed the cron job. If deploy does not have write permissions for the directory in which it is executing, then you could specify an absolute path for the dump file to fix the problem.</p>\n"
},
{
"answer_id": 13232,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like your <code>PATH</code> is missing a few directories, most importantly <code>/bin</code> (for <code>/bin/rm</code>). Here's what my system's <code>/etc/crontab</code> uses:</p>\n\n<pre><code>PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n</code></pre>\n"
},
{
"answer_id": 16540,
"author": "engtech",
"author_id": 175,
"author_profile": "https://Stackoverflow.com/users/175",
"pm_score": 0,
"selected": false,
"text": "<p>Is cron sending emails with logs?</p>\n\n<p>If not, pipe the output of cron to a log file.</p>\n\n<p>Make sure to redirect STDERR to the log.</p>\n"
},
{
"answer_id": 214503,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 3,
"selected": false,
"text": "<p>When scripts run correctly interactively but not when run by cron, the problem is usually because of the environment environment settings in place ... for example the PATH as alrady mentioned by @Ted Percival, but may be other environment variables.</p>\n\n<p>This is because cron will not invoke .bash_profile, .bashrc or /etc/profile before executing.</p>\n\n<p>The best way to avoid this is to ensure any scripts invoked by cron do not make any assumptions about the environment when executing. Over-coming this can be as simple as including a few lines in your script to make sure the environment is setup properly. For example, in my case I have all the significant settings in /etc/profile (for RHEL), so I will include the following line in any scripts to be run under cron:</p>\n\n<pre><code>source /etc/profile\n</code></pre>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450/"
] | I have a cron job on an Ubuntu Hardy VPS that only half works and I can't work out why. The job is a Ruby script that uses mysqldump to back up a MySQL database used by a Rails application, which is then gzipped and uploaded to a remote server using SFTP.
The gzip file is created and copied successfully but it's always zero bytes. Yet if I run the cron command directly from the command line it works perfectly.
This is the cron job:
```
PATH=/usr/bin
10 3 * * * ruby /home/deploy/bin/datadump.rb
```
This is datadump.rb:
```
#!/usr/bin/ruby
require 'yaml'
require 'logger'
require 'rubygems'
require 'net/ssh'
require 'net/sftp'
APP = '/home/deploy/apps/myapp/current'
LOGFILE = '/home/deploy/log/data.log'
TIMESTAMP = '%Y%m%d-%H%M'
TABLES = 'table1 table2'
log = Logger.new(LOGFILE, 5, 10 * 1024)
dump = "myapp-#{Time.now.strftime(TIMESTAMP)}.sql.gz"
ftpconfig = YAML::load(open('/home/deploy/apps/myapp/shared/config/sftp.yml'))
config = YAML::load(open(APP + '/config/database.yml'))['production']
cmd = "mysqldump -u #{config['username']} -p#{config['password']} -h #{config['host']} --add-drop-table --add-locks --extended-insert --lock-tables #{config['database']} #{TABLES} | gzip -cf9 > #{dump}"
log.info 'Getting ready to create a backup'
`#{cmd}`
# Strongspace
log.info 'Backup created, starting the transfer to Strongspace'
Net::SSH.start(ftpconfig['strongspace']['host'], ftpconfig['strongspace']['username'], ftpconfig['strongspace']['password']) do |ssh|
ssh.sftp.connect do |sftp|
sftp.open_handle("#{ftpconfig['strongspace']['dir']}/#{dump}", 'w') do |handle|
sftp.write(handle, open("#{dump}").read)
end
end
end
log.info 'Finished transferring backup to Strongspace'
log.info 'Removing local file'
cmd = "rm -f #{dump}"
log.debug "Executing: #{cmd}"
`#{cmd}`
log.info 'Local file removed'
```
I've checked and double-checked all the paths and they're correct. Both **sftp.yml** (SFTP credentials) and **database.yml** (MySQL credentials) are owned by the executing user (deploy) with read-only permissions for that user (chmod 400). I'm using the 1.1.x versions of net-ssh and net-sftp. I know they're not the latest, but they're what I'm familiar with at the moment.
What could be causing the cron job to fail? | Are you sure the temporary file is being created correctly when running as a cron job? The working directory for your script will either be specified in the HOME environment variable, or the /etc/passwd entry for the user that installed the cron job. If deploy does not have write permissions for the directory in which it is executing, then you could specify an absolute path for the dump file to fix the problem. |
13,217 | <p>I am uploading multiple files using the BeginGetRequestStream of HttpWebRequest but I want to update the progress control I have written whilst I post up the data stream. </p>
<p>How should this be done, I have tried calling Dispatch.BeginInvoke (as below) from within the loop that pushes the data into the stream but it locks the browser until its finished so it seems to be in some sort of worker/ui thread deadlock. </p>
<p>This is a code snippet of pretty much what I am doing:</p>
<pre><code>class RequestState
{
public HttpWebRequest request; // holds the request
public FileDialogFileInfo file; // store our file stream data
public RequestState( HttpWebRequest request, FileDialogFileInfo file )
{
this.request = request;
this.file = file;
}
}
private void UploadFile( FileDialogFileInfo file )
{
UriBuilder ub = new UriBuilder( app.receiverURL );
ub.Query = string.Format( "filename={0}", file.Name );
// Open the selected file to read.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( ub.Uri );
request.Method = "POST";
RequestState state = new RequestState( request, file );
request.BeginGetRequestStream( new AsyncCallback( OnUploadReadCallback ), state );
}
private void OnUploadReadCallback( IAsyncResult asynchronousResult )
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)state.request;
Stream postStream = request.EndGetRequestStream( asynchronousResult );
PushData( state.file, postStream );
postStream.Close();
state.request.BeginGetResponse( new AsyncCallback( OnUploadResponseCallback ), state.request );
}
private void PushData( FileDialogFileInfo file, Stream output )
{
byte[] buffer = new byte[ 4096 ];
int bytesRead = 0;
Stream input = file.OpenRead();
while( ( bytesRead = input.Read( buffer, 0, buffer.Length ) ) != 0 )
{
output.Write( buffer, 0, bytesRead );
bytesReadTotal += bytesRead;
App app = App.Current as App;
int totalPercentage = Convert.ToInt32( ( bytesReadTotal / app.totalBytesToUpload ) * 100 );
// enabling the following locks up my UI and browser
Dispatcher.BeginInvoke( () =>
{
this.ProgressBarWithPercentage.Percentage = totalPercentage;
} );
}
}
</code></pre>
| [
{
"answer_id": 16648,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": true,
"text": "<p>I was going to say that, I didn't think that Silverlight 2's HttpWebRequest supported streaming, because the request data gets buffered into memory entirely. It had been a while since the last time I looked at it though, therefore I went back to see if Beta 2 supported it. Well turns out it does. I am glad I went back and read before stating that. You can enable it by setting AllowReadStreamBuffering to false. Did you set this property on your HttpWebRequest? That could be causing your block.</p>\n\n<ul>\n<li><a href=\"http://shrinkster.com/11cn\" rel=\"nofollow noreferrer\">MSDN Reference</a></li>\n<li><a href=\"http://www.wilcob.com/Wilco/View.aspx?NewsID=212\" rel=\"nofollow noreferrer\">File upload component for Silverlight and ASP.NET</a></li>\n</ul>\n\n<p>Edit, found another reference for you. You may want to follow this approach by breaking the file into chunks. This was written last March, therefore I am not sure if it will work in Beta 2 or not.</p>\n"
},
{
"answer_id": 18445,
"author": "Dan",
"author_id": 1478,
"author_profile": "https://Stackoverflow.com/users/1478",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for that, I will take a look at those links, I was considering chunking my data anyway, seems to be the only way I can get any reasonable progress reports out of it.</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1478/"
] | I am uploading multiple files using the BeginGetRequestStream of HttpWebRequest but I want to update the progress control I have written whilst I post up the data stream.
How should this be done, I have tried calling Dispatch.BeginInvoke (as below) from within the loop that pushes the data into the stream but it locks the browser until its finished so it seems to be in some sort of worker/ui thread deadlock.
This is a code snippet of pretty much what I am doing:
```
class RequestState
{
public HttpWebRequest request; // holds the request
public FileDialogFileInfo file; // store our file stream data
public RequestState( HttpWebRequest request, FileDialogFileInfo file )
{
this.request = request;
this.file = file;
}
}
private void UploadFile( FileDialogFileInfo file )
{
UriBuilder ub = new UriBuilder( app.receiverURL );
ub.Query = string.Format( "filename={0}", file.Name );
// Open the selected file to read.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( ub.Uri );
request.Method = "POST";
RequestState state = new RequestState( request, file );
request.BeginGetRequestStream( new AsyncCallback( OnUploadReadCallback ), state );
}
private void OnUploadReadCallback( IAsyncResult asynchronousResult )
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)state.request;
Stream postStream = request.EndGetRequestStream( asynchronousResult );
PushData( state.file, postStream );
postStream.Close();
state.request.BeginGetResponse( new AsyncCallback( OnUploadResponseCallback ), state.request );
}
private void PushData( FileDialogFileInfo file, Stream output )
{
byte[] buffer = new byte[ 4096 ];
int bytesRead = 0;
Stream input = file.OpenRead();
while( ( bytesRead = input.Read( buffer, 0, buffer.Length ) ) != 0 )
{
output.Write( buffer, 0, bytesRead );
bytesReadTotal += bytesRead;
App app = App.Current as App;
int totalPercentage = Convert.ToInt32( ( bytesReadTotal / app.totalBytesToUpload ) * 100 );
// enabling the following locks up my UI and browser
Dispatcher.BeginInvoke( () =>
{
this.ProgressBarWithPercentage.Percentage = totalPercentage;
} );
}
}
``` | I was going to say that, I didn't think that Silverlight 2's HttpWebRequest supported streaming, because the request data gets buffered into memory entirely. It had been a while since the last time I looked at it though, therefore I went back to see if Beta 2 supported it. Well turns out it does. I am glad I went back and read before stating that. You can enable it by setting AllowReadStreamBuffering to false. Did you set this property on your HttpWebRequest? That could be causing your block.
* [MSDN Reference](http://shrinkster.com/11cn)
* [File upload component for Silverlight and ASP.NET](http://www.wilcob.com/Wilco/View.aspx?NewsID=212)
Edit, found another reference for you. You may want to follow this approach by breaking the file into chunks. This was written last March, therefore I am not sure if it will work in Beta 2 or not. |
13,225 | <p>I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:</p>
<pre class="lang-jsp prettyprint-override"><code><p>
<bean:message key="alert" />
</p>
</code></pre>
<p>and the properties files look like:</p>
<pre><code>messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">contact information</a>.
</code></pre>
<p>with the appropriate translations in N other languages (messages_fr.properties, etc).</p>
<p>Problems:</p>
<ol>
<li><em><strong>DRY violation</strong></em> - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.</li>
<li><em><strong>Mixed concerns</strong></em> - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).</li>
<li><em><strong>Post-translation markup</strong></em> - Anytime I receive newly-translated text, I must decide what to surround with the <code><a>...</a></code> markup. Easy for English but less so for unfamiliar languages.</li>
</ol>
<p>I've considered adding placeholders in the messages file, like:</p>
<pre><code>alert=Please update your {0} and {1}.
</code></pre>
<p>but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.</p>
<p>What can I do to improve this?</p>
| [
{
"answer_id": 13239,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps:</p>\n\n<pre><code>#\nalert=Please update your {0}address{1} and {2}contact information{3}.\n</code></pre>\n"
},
{
"answer_id": 13250,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>One approach that comes to mind is that you could store the translated replacement parameters i.e. \"address\" and \"contact information\" in a separate properties file, one per locale. Then have your Action class (or probably some helper class) look up the values from the correct ResourceBundle for the current locale and pass them to the message tag.</p>\n"
},
{
"answer_id": 13359,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>The message message tag API allows\n only 5 parametric arguments</p>\n</blockquote>\n\n<p>Ah! I blame my complete ignorance of the Struts API.</p>\n\n<p>To quote the <a href=\"http://struts.apache.org/1.2.7/userGuide/dev_bean.html\" rel=\"nofollow noreferrer\">manual</a>: </p>\n\n<blockquote>\n <p>Some of the features in this taglib\n are also available in the JavaServer\n Pages Standard Tag Library (JSTL). The\n Struts team encourages the use of the\n standard tags over the Struts specific\n tags when possible.</p>\n</blockquote>\n\n<p>You could probably do this with the <strong><a href=\"http://java.sun.com/jsp/jstl/fmt\" rel=\"nofollow noreferrer\">http://java.sun.com/jsp/jstl/fmt</a></strong> taglib.</p>\n\n<pre class=\"lang-jsp prettyprint-override\"><code><fmt:bundle basename=\"messages\">\n <fmt:message key=\"alert\">\n <fmt:param value='<a href=\"/\">' />\n <fmt:param value=\"</a>\" />\n <fmt:param value='<a href=\"/\">' />\n <fmt:param value=\"</a>\" />\n </fmt:message>\n</fmt:bundle>\n</code></pre>\n\n<p>The downside is that this isn't valid XML and yanking the values to variables involves more indirection, lookups and verbosity. This is not a good solution.</p>\n\n<p>I don't know Struts, but if it is anything like JavaServer Faces (same architect), then there is probably support for configuring a replacement control. I would either replace the existing control with a more flexible one or add a new one.</p>\n\n<blockquote>\n <p>Anytime I receive newly-translated\n text, I must decide what to surround\n with the <code><a>...</a></code> markup.</p>\n</blockquote>\n\n<p>There is no way you should be doing this and I see this as a fault in your translation process (I am an ex-localization engineer and ex-developer of localization tools). The <code>{0}</code> characters should be included in the files that are sent to the translators. The localization guidelines should explain the string's context and the meaning of any variables.</p>\n\n<p>You can programmatically validate the property bundles on return. String-specific regex's might do the trick. It isn't outside the realms of possibility that \"address\" and \"contact information\" would swap order during translation.</p>\n\n<p>The simplest solution is to redesign the messages to render:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><a href=\"/address.do\">Please update your address.</a>\n<a href=\"/contact.do\">Please update your contact information.</a>\n</code></pre>\n\n<p>I accept that this might not be a solution in all cases and may have your UI designer spitting teeth.</p>\n"
},
{
"answer_id": 13381,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Avoid creating links within long\n blocks of text. Prefer shorter text\n that can act as a logically complete\n and independent link.</p>\n</blockquote>\n\n<p>Generally, it will lead to fewer problems. Sometimes you have to compromise your UI design to accommodate localization; sometimes you need to compromise your localization process to accommodate the UI.</p>\n\n<p>Any time a developer manually manipulates post-translation strings is a source of potentially expensive bugs. Cutting/pasting or string editing can result in character corruption, misplaced strings, etc. A translation defect needs the participation of outside parties to fix which involves cost and takes time.</p>\n\n<p>Thinking on it, something like this might be less ugly:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p>Please update your address and contact information.\n<br />\n<a href=\"/address.do\">update address</a>\n<br />\n<a href=\"/contact.do\">update contact information</a></p>\n</code></pre>\n\n<p>...but I'm no UI designer.</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1557/"
] | I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:
```jsp
<p>
<bean:message key="alert" />
</p>
```
and the properties files look like:
```
messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">contact information</a>.
```
with the appropriate translations in N other languages (messages\_fr.properties, etc).
Problems:
1. ***DRY violation*** - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.
2. ***Mixed concerns*** - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).
3. ***Post-translation markup*** - Anytime I receive newly-translated text, I must decide what to surround with the `<a>...</a>` markup. Easy for English but less so for unfamiliar languages.
I've considered adding placeholders in the messages file, like:
```
alert=Please update your {0} and {1}.
```
but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.
What can I do to improve this? | >
> Avoid creating links within long
> blocks of text. Prefer shorter text
> that can act as a logically complete
> and independent link.
>
>
>
Generally, it will lead to fewer problems. Sometimes you have to compromise your UI design to accommodate localization; sometimes you need to compromise your localization process to accommodate the UI.
Any time a developer manually manipulates post-translation strings is a source of potentially expensive bugs. Cutting/pasting or string editing can result in character corruption, misplaced strings, etc. A translation defect needs the participation of outside parties to fix which involves cost and takes time.
Thinking on it, something like this might be less ugly:
```html
<p>Please update your address and contact information.
<br />
<a href="/address.do">update address</a>
<br />
<a href="/contact.do">update contact information</a></p>
```
...but I'm no UI designer. |
13,362 | <p>I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.</p>
<p>So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):</p>
<pre><code>$("#thediv").scrollTop = $("#thediv").scrollHeight;
</code></pre>
<p>However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.</p>
<p>The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.</p>
<p>Any ideas guys? This one's got me stumped. Thanks!</p>
| [
{
"answer_id": 13365,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 7,
"selected": true,
"text": "<p><code>scrollHeight</code> should be the total height of content. <code>scrollTop</code> specifies the pixel offset into that content to be displayed at the top of the element's client area.</p>\n\n<p>So you really want (still using jQuery):</p>\n\n<pre><code>$(\"#thediv\").each( function() \n{\n // certain browsers have a bug such that scrollHeight is too small\n // when content does not fill the client area of the element\n var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);\n this.scrollTop = scrollHeight - this.clientHeight;\n});\n</code></pre>\n\n<p>...which will set the scroll offset to the last <code>clientHeight</code> worth of content.</p>\n"
},
{
"answer_id": 14494,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "<p>Using a loop to iterate over a jQuery of one element is quite inefficient. When selecting an ID, you can just retrieve the first and unique element of the jQuery using get() or the [] notation.</p>\n\n<pre><code>var div = $(\"#thediv\")[0];\n\n// certain browsers have a bug such that scrollHeight is too small\n// when content does not fill the client area of the element\nvar scrollHeight = Math.max(div.scrollHeight, div.clientHeight);\ndiv.scrollTop = scrollHeight - div.clientHeight;\n</code></pre>\n"
},
{
"answer_id": 741982,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://developer.mozilla.org/en/DOM/element.scrollIntoView\" rel=\"noreferrer\"><code>scrollIntoView</code></a></p>\n\n<blockquote>\n <p>The <strong>scrollIntoView</strong> method scrolls the element into view. </p>\n</blockquote>\n"
},
{
"answer_id": 7605343,
"author": "peterbrown",
"author_id": 972295,
"author_profile": "https://Stackoverflow.com/users/972295",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$(\"#thediv\").scrollTop($(\"#thediv\")[0].scrollHeight);\n</code></pre>\n"
},
{
"answer_id": 19598983,
"author": "ObjectiveTC",
"author_id": 802196,
"author_profile": "https://Stackoverflow.com/users/802196",
"pm_score": -1,
"selected": false,
"text": "<p>I had a div wrapping 3 divs that were floating left, and whose contents were being resized. It helps to turn funky-colored borders/background on for the div-wrapper when you try to resolve this. The problem was that the resized div-content was overflowing outside the div-wrapper (and bled to underneath the area of content below the wrapper). </p>\n\n<p>Resolved by using @Shog9's answer above. As applied to my situation, this was the HTML layout:</p>\n\n<pre><code><div id=\"div-wrapper\">\n <div class=\"left-div\"></div>\n <div id=\"div-content\" class=\"middle-div\">\n Some short/sweet content that will be elongated by Jquery.\n </div>\n <div class=\"right-div\"></div>\n</div>\n</code></pre>\n\n<p>This was the my jQuery to resize the div-wrapper:</p>\n\n<pre><code><script>\n$(\"#div-content\").text(\"a very long string of text that will overflow beyond the width/height of the div-content\");\n//now I need to resize the div...\nvar contentHeight = $('#div-content').prop('scrollHeight')\n$(\"#div-wrapper\").height(contentHeight);\n</script>\n</code></pre>\n\n<p>To note, $('#div-content').prop('scrollHeight') produces the height that the wrapper needs to resize to. Also I am unaware of any other way to obtain the scrollHeight an actual jQuery function; Neither of $('#div-content').scrollTop() and $('#div-content').height would produce the real content-height values. Hope this helps someone out there!</p>\n"
},
{
"answer_id": 55489459,
"author": "daniels",
"author_id": 2270233,
"author_profile": "https://Stackoverflow.com/users/2270233",
"pm_score": 1,
"selected": false,
"text": "<p>It can be done in plain JS. The trick is to set scrollTop to a value equal or greater than the total height of the element (<code>scrollHeight</code>):</p>\n\n<pre><code>const theDiv = document.querySelector('#thediv');\ntheDiv.scrollTop = Math.pow(10, 10);\n</code></pre>\n\n<p>From <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop#Syntax\" rel=\"nofollow noreferrer\">MDN</a>:</p>\n\n<blockquote>\n <p>If set to a value greater than the maximum available for the element,\n scrollTop settles itself to the maximum value.</p>\n</blockquote>\n\n<p>While the value of <code>Math.pow(10, 10)</code> did the trick using a too high value like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity\" rel=\"nofollow noreferrer\"><code>Infintiy</code></a> or <code>Number.MAX_VALUE</code> will reset scrollTop to <code>0</code> (Firefox 66).</p>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384/"
] | I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.
So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):
```
$("#thediv").scrollTop = $("#thediv").scrollHeight;
```
However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.
The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.
Any ideas guys? This one's got me stumped. Thanks! | `scrollHeight` should be the total height of content. `scrollTop` specifies the pixel offset into that content to be displayed at the top of the element's client area.
So you really want (still using jQuery):
```
$("#thediv").each( function()
{
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
```
...which will set the scroll offset to the last `clientHeight` worth of content. |
13,396 | <p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p>
<p>However, in other languages, I frequently find myself writing something along the lines of:</p>
<pre><code>foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
</code></pre>
<p>This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering?</p>
| [
{
"answer_id": 13399,
"author": "jdd",
"author_id": 242853,
"author_profile": "https://Stackoverflow.com/users/242853",
"pm_score": -1,
"selected": false,
"text": "<p>Depends on the language and what you need to do, a \"map\" as it's called in many languages could be what you're looking for. I don't know C#, but according to <a href=\"http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx\" rel=\"nofollow noreferrer\">this</a> page, .NET 2.0 calls map \"ConvertAll\".</p>\n\n<p>The meaning of \"map\" is pretty simple - take a list, and apply a function to each element of it, returning a new list. You may also be looking for \"filter\", which would give you a list of items that satisfy a predicate in another list.</p>\n"
},
{
"answer_id": 13403,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "<p>in Ruby:</p>\n\n<pre><code>intArray.select { |x| x > 3 }.each do |x|\n # do other processing\nend\n</code></pre>\n\n<p>or if \"other processing\" is a short one-liner:</p>\n\n<pre><code>intArray.select { |x| x > 3 }.each { |x| something_that_uses x }\n</code></pre>\n\n<p>lastly, if you want to return a new array containing the results of the processing of those elements greater than 3:</p>\n\n<pre><code>intArray.select { |x| x > 3 }.map { |x| do_something_to x }\n</code></pre>\n"
},
{
"answer_id": 13405,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<p>In Python, you have <a href=\"http://docs.python.org/tut/node7.html#SECTION007130000000000000000\" rel=\"nofollow noreferrer\">filter and map</a>, which can so what you want:</p>\n\n<pre><code>map(lambda x: foo(x + 1) filter(lambda x: x > 3, intArray))\n</code></pre>\n\n<p>There's also <a href=\"http://docs.python.org/tut/node7.html#SECTION007140000000000000000\" rel=\"nofollow noreferrer\">list comprehensions</a> which can do both in one easy statement:</p>\n\n<pre><code>[f(x + 1) for x in intArray if x > 3]\n</code></pre>\n"
},
{
"answer_id": 13406,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 2,
"selected": false,
"text": "<p>In C# you can apply selective processing on anything that lives inside an IEnumerable like this: </p>\n\n<pre><code>intArray.Where(i => i > 3).ConvertAll();\nDoStuff(intArray.Where(i => i 3));\n</code></pre>\n\n<p>Etc..</p>\n"
},
{
"answer_id": 13435,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 4,
"selected": true,
"text": "<p>The increment in the original <code>foreach</code> loop will not affect the contents of the array, the only way to do this remains a <code>for</code> loop:</p>\n\n<pre><code>for(int i = 0; i < intArray.Length; ++i)\n{\n if(intArray[i] > 3) ++intArray[i];\n}\n</code></pre>\n\n<p>Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:</p>\n\n<pre><code>var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));\nvar newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));\n</code></pre>\n\n<p>Using <code>where</code> (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.</p>\n\n<pre><code>var intArray = new int[] { 10, 1, 20, 2 };\nvar newArray = from i in intArray where i > 3 select i + 1;\n// newArray == { 11, 21 }\n</code></pre>\n\n<p>There is a <code>ForEach</code> method on arrays that will allow you to use a lambda function instead of a <code>foreach</code> block, though for anything more than a method call I would stick with <code>foreach</code>.</p>\n\n<pre><code>intArray.ForEach(i => DoSomething(i));\n</code></pre>\n"
},
{
"answer_id": 6477444,
"author": "sam",
"author_id": 778942,
"author_profile": "https://Stackoverflow.com/users/778942",
"pm_score": 0,
"selected": false,
"text": "<pre><code>map(lambda x: test(x + 1) filter(lambda x: x > 3, arr))\n</code></pre>\n"
}
] | 2008/08/16 | [
"https://Stackoverflow.com/questions/13396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
] | I love list comprehensions in Python, because they concisely represent a transformation of a list.
However, in other languages, I frequently find myself writing something along the lines of:
```
foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
```
This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering? | The increment in the original `foreach` loop will not affect the contents of the array, the only way to do this remains a `for` loop:
```
for(int i = 0; i < intArray.Length; ++i)
{
if(intArray[i] > 3) ++intArray[i];
}
```
Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:
```
var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));
var newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));
```
Using `where` (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.
```
var intArray = new int[] { 10, 1, 20, 2 };
var newArray = from i in intArray where i > 3 select i + 1;
// newArray == { 11, 21 }
```
There is a `ForEach` method on arrays that will allow you to use a lambda function instead of a `foreach` block, though for anything more than a method call I would stick with `foreach`.
```
intArray.ForEach(i => DoSomething(i));
``` |
13,454 | <p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p>
<pre><code>cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
</code></pre>
<p>How can I condense it? </p>
| [
{
"answer_id": 13456,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 0,
"selected": false,
"text": "<p>You can obviously concatenate everything together:</p>\n\n<pre><code>cleaned = stringwithslashes.replace(\"\\\\n\",\"\\n\").replace(\"\\\\r\",\"\\n\").replace(\"\\\\\",\"\")\n</code></pre>\n\n<p>Is that what you were after? Or were you hoping for something more terse?</p>\n"
},
{
"answer_id": 13579,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": -1,
"selected": false,
"text": "<p>Python has a built-in escape() function analogous to PHP's addslashes, but no unescape() function (stripslashes), which in my mind is kind of ridiculous.</p>\n\n<p>Regular expressions to the rescue (code not tested):</p>\n\n<pre><code>p = re.compile( '\\\\(\\\\\\S)')\np.sub('\\1',escapedstring)\n</code></pre>\n\n<p>In theory that takes anything of the form \\\\(not whitespace) and returns \\(same char)</p>\n\n<p>edit: Upon further inspection, Python regular expressions are broken as all hell;</p>\n\n<pre><code>>>> escapedstring\n'This is a \\\\n\\\\n\\\\n test'\n>>> p = re.compile( r'\\\\(\\S)' )\n>>> p.sub(r\"\\1\",escapedstring)\n'This is a nnn test'\n>>> p.sub(r\"\\\\1\",escapedstring)\n'This is a \\\\1\\\\1\\\\1 test'\n>>> p.sub(r\"\\\\\\1\",escapedstring)\n'This is a \\\\n\\\\n\\\\n test'\n>>> p.sub(r\"\\(\\1)\",escapedstring)\n'This is a \\\\(n)\\\\(n)\\\\(n) test'\n</code></pre>\n\n<p>In conclusion, what the hell, Python.</p>\n"
},
{
"answer_id": 13598,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": false,
"text": "<p>Not totally sure this is what you want, but..</p>\n\n<pre><code>cleaned = stringwithslashes.decode('string_escape')\n</code></pre>\n"
},
{
"answer_id": 13608,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like what you want could be reasonably efficiently handled through regular expressions:</p>\n\n<pre><code>import re\ndef stripslashes(s):\n r = re.sub(r\"\\\\(n|r)\", \"\\n\", s)\n r = re.sub(r\"\\\\\", \"\", r)\n return r\ncleaned = stripslashes(stringwithslashes)\n</code></pre>\n"
},
{
"answer_id": 21862975,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 1,
"selected": false,
"text": "<p>use <code>decode('string_escape')</code></p>\n\n<pre><code>cleaned = stringwithslashes.decode('string_escape')\n</code></pre>\n\n<p>Using </p>\n\n<blockquote>\n <p><strong>string_escape</strong> : Produce a string that is suitable as string literal in Python source code</p>\n</blockquote>\n\n<p>or concatenate the replace() like Wilson´s answer.</p>\n\n<pre><code>cleaned = stringwithslashes.replace(\"\\\\\",\"\").replace(\"\\\\n\",\"\\n\").replace(\"\\\\r\",\"\\n\")\n</code></pre>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:
```
cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
```
How can I condense it? | Not totally sure this is what you want, but..
```
cleaned = stringwithslashes.decode('string_escape')
``` |
13,470 | <p>I was reading <a href="https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage">this question</a> about how to parse URLs out of web pages and had a question about the <a href="https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#6183">accepted answer</a> which offered this solution:</p>
<pre class="lang-none prettyprint-override"><code>((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
</code></pre>
<p>The solution was offered by <a href="https://stackoverflow.com/users/350/csmba">csmba</a> and he credited it to <a href="http://regexlib.com/Search.aspx?k=URL" rel="nofollow noreferrer">regexlib.com</a>. Whew. Credits done.</p>
<p>I think this is a fairly naive regular expression but it's a fine starting point for building something better. But, my question is this:</p>
<p>What is the point of <code>{1}</code>? It means "exactly one of the previous grouping", right? Isn't that the default behavior of a grouping in a regular expression? Would the expression be changed in any way if the <code>{1}</code> were removed?</p>
<p>If I saw this from a coworker I would point out his or her error but as I write this the response is rated at a 6 and the expression on regexlib.com is rated a 4 of 5. So maybe I'm missing something?</p>
| [
{
"answer_id": 13475,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it has any purpose. But because RegEx is almost impossible to understand/decompose, people rarely point out errors. That is probably why no one else pointed it out. </p>\n"
},
{
"answer_id": 13483,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/13470/question-about-specific-regular-expression#13479\">Rob</a>: I disagree. To enforce what you are asking for I think you would need to use negative-look-behind, which is possible but is certainly not related to use {1}. Neither version of the regexp address that particular issue.</p>\n\n<p>To let the code speak:</p>\n\n<pre><code>tibook 0 /home/jj33/swap > cat text\nText this is http://example.com text this is\nText this is http://http://example.com text this is\ntibook 0 /home/jj33/swap > cat p\n#!/usr/bin/perl\n\nmy $re1 = '((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)';\nmy $re2 = '((mailto\\:|(news|(ht|f)tp(s?))\\://)\\S+)';\n\nwhile (<>) {\n print \"Evaluating: $_\";\n print \"re1 saw \\$1 = $1\\n\" if (/$re1/);\n print \"re2 saw \\$1 = $1\\n\" if (/$re2/);\n}\ntibook 0 /home/jj33/swap > cat text | perl p\nEvaluating: Text this is http://example.com text this is\nre1 saw $1 = http://example.com\nre2 saw $1 = http://example.com\nEvaluating: Text this is http://http://example.com text this is\nre1 saw $1 = http://http://example.com\nre2 saw $1 = http://http://example.com\ntibook 0 /home/jj33/swap >\n</code></pre>\n\n<p>So, if there is a difference between the two versions, it's doesn't seem to be the one you suggest.</p>\n"
},
{
"answer_id": 13484,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": true,
"text": "<p>@Jeff Atwood, your interpretation is a little off - the {1} means match exactly once, but has no effect on the \"capturing\" - the capturing occurs because of the parens - the braces only specify the number of times the pattern must match the source - once, as you say.</p>\n\n<p>I agree with @Marius, even if his answer is a little terse and may come off as being flippant. Regular expressions are tough, if one's not used to using them, and the {1} in the question isn't quite error - in systems that support it, it does mean \"exactly one match\". In this sense, it doesn't really do anything.</p>\n\n<p>Unfortunately, contrary to a now-deleted post, it doesn't keep the regexp from matching <code>http://http://example.org</code>, since the \\S+ at the end will match one or more non-whitespace characters, including the <code>http://example.org</code> in <code>http://http://example.org</code> (verified using Python 2.5, just in case my regexp reading was off). So, the regexp given isn't really the best. I'm not a URL expert, but probably something limiting the appearance of \":\"s and \"//\"s after the first one would be necessary (but hardly sufficient) to ensure good URLs.</p>\n"
},
{
"answer_id": 13486,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think the {1} has any valid function in that regex. </p>\n\n<blockquote>\n <p><strong>(**mailto:|(news|(ht|f)tp(s?))://</strong>){1}**</p>\n</blockquote>\n\n<p>You should read this as: \"capture the stuff in the parens exactly one time\". But we don't really care about capturing this for use later, eg $1 in the replacement. So it's pointless.</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/430/"
] | I was reading [this question](https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage) about how to parse URLs out of web pages and had a question about the [accepted answer](https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#6183) which offered this solution:
```none
((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
```
The solution was offered by [csmba](https://stackoverflow.com/users/350/csmba) and he credited it to [regexlib.com](http://regexlib.com/Search.aspx?k=URL). Whew. Credits done.
I think this is a fairly naive regular expression but it's a fine starting point for building something better. But, my question is this:
What is the point of `{1}`? It means "exactly one of the previous grouping", right? Isn't that the default behavior of a grouping in a regular expression? Would the expression be changed in any way if the `{1}` were removed?
If I saw this from a coworker I would point out his or her error but as I write this the response is rated at a 6 and the expression on regexlib.com is rated a 4 of 5. So maybe I'm missing something? | @Jeff Atwood, your interpretation is a little off - the {1} means match exactly once, but has no effect on the "capturing" - the capturing occurs because of the parens - the braces only specify the number of times the pattern must match the source - once, as you say.
I agree with @Marius, even if his answer is a little terse and may come off as being flippant. Regular expressions are tough, if one's not used to using them, and the {1} in the question isn't quite error - in systems that support it, it does mean "exactly one match". In this sense, it doesn't really do anything.
Unfortunately, contrary to a now-deleted post, it doesn't keep the regexp from matching `http://http://example.org`, since the \S+ at the end will match one or more non-whitespace characters, including the `http://example.org` in `http://http://example.org` (verified using Python 2.5, just in case my regexp reading was off). So, the regexp given isn't really the best. I'm not a URL expert, but probably something limiting the appearance of ":"s and "//"s after the first one would be necessary (but hardly sufficient) to ensure good URLs. |
13,473 | <p>I would like to sort an array in ascending order using <code>C/C++</code>. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.</p>
<p><strong>Example</strong></p>
<pre><code>Input: 1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
</code></pre>
<p><strong>Edit:</strong> I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.</p>
<h3>Update:</h3>
<p>Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.</p>
<p>Could someone please tell me what's wrong?</p>
<p>I'd very much appreciate some help!</p>
<pre><code>void SortArray(int ** pArray, int ArrayLength)
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for (i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength - 1); j++)
{
if (*pArray[j + 1] > *pArray[j]) // ascending order simply changes to <
{
&temp = &pArray[j]; // swap elements
&pArray[j] = &pArray[j + 1]; //the problem lies somewhere in here
&pArray[j + 1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
};
</code></pre>
| [
{
"answer_id": 13477,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there's a trival n^2 solution.</p>\n\n<p>In python:</p>\n\n<pre><code>newArray = sorted(oldArray)\nblankArray = [0] * len(oldArray)\nfor i in xrange(len(newArray)):\n dex = oldArray.index(newArray[i])\n blankArray[dex] = i\n</code></pre>\n\n<p>Depending on how large your list is, this may work. If your list is very long, you'll need to do some strange parallel array sorting, which doesn't look like much fun and is a quick way to introduce extra bugs in your code.</p>\n\n<p>Also note that the above code assumes unique values in oldArray. If that's not the case, you'll need to do some post processing to solve tied values.</p>\n"
},
{
"answer_id": 13481,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 4,
"selected": true,
"text": "<p>Since you're using C++, I would do it something like this. The <code>SortIntPointers</code> function can be any sort algorithm, the important part is that it sorts the array of pointers based on the <code>int</code> that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which will end up in the original position in the original array.</p>\n\n<pre><code>int* intArray; // set somewhere else\nint arrayLen; // set somewhere else \n\nint** pintArray = new int*[arrayLen];\nfor(int i = 0; i < arrayLen; ++i)\n{\n pintArray[i] = &intArray[i];\n}\n\n// This function sorts the pointers according to the values they\n// point to. In effect, it sorts intArray without losing the positional\n// information.\nSortIntPointers(pintArray, arrayLen);\n\n// Dereference the pointers and assign their sorted position.\nfor(int i = 0; i < arrayLen; ++i)\n{\n *pintArray[i] = i;\n}\n</code></pre>\n\n<p>Hopefully that's clear enough.</p>\n"
},
{
"answer_id": 13482,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 2,
"selected": false,
"text": "<p>create a new array with increasing values from 0 to n-1 (where n is the length of the array you want to sort). Then sort the new array based on the values in the old array indexed by the values in the new array. </p>\n\n<p>For example, if you use bubble sort (easy to explain), then instead of comparing the values in the new array, you compare the values in the old array at the position indexed by a value in the new array:</p>\n\n<pre><code>function bubbleRank(A){\n var B = new Array();\n for(var i=0; i<A.length; i++){\n B[i] = i;\n }\n do{\n swapped = false;\n for(var i=0; i<A.length; i++){\n if(A[B[i]] > A[B[i+1]]){\n var temp = B[i];\n B[i] = B[i+1];\n B[i+1] = temp;\n swapped = true;\n }\n }\n }while(swapped);\n return B;\n}\n</code></pre>\n"
},
{
"answer_id": 119587,
"author": "Maciej Hehl",
"author_id": 19939,
"author_profile": "https://Stackoverflow.com/users/19939",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, here is my atempt in C++ </p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n\nstruct mycomparison\n{\n bool operator() (int* lhs, int* rhs) {return (*lhs) < (*rhs);}\n};\n\nint main(int argc, char* argv[])\n{\n int myarray[] = {1, 3, 6, 2, 4, 9, 5, 12, 10};\n const size_t size = sizeof(myarray) / sizeof(myarray[0]);\n int *arrayofpointers[size];\n for(int i = 0; i < size; ++i)\n {\n arrayofpointers[i] = myarray + i;\n }\n std::sort(arrayofpointers, arrayofpointers + size, mycomparison());\n for(int i = 0; i < size; ++i)\n {\n *arrayofpointers[i] = i + 1;\n }\n for(int i = 0; i < size; ++i)\n {\n std::cout << myarray[i] << \" \";\n }\n std::cout << std::endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 122083,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 0,
"selected": false,
"text": "<p>Parallel sorting of vector using boost::lambda...</p>\n\n<pre><code> std::vector<int> intVector;\n std::vector<int> rank;\n\n // set up values according to your example...\n intVector.push_back( 1 );\n intVector.push_back( 3 );\n intVector.push_back( 4 );\n intVector.push_back( 9 );\n intVector.push_back( 6 );\n\n\n for( int i = 0; i < intVector.size(); ++i )\n {\n rank.push_back( i );\n }\n\n using namespace boost::lambda;\n std::sort( \n rank.begin(), rank.end(),\n var( intVector )[ _1 ] < var( intVector )[ _2 ] \n );\n\n //... and because you wanted to replace the values of the original with \n // their rank\n intVector = rank;\n</code></pre>\n\n<p>Note: I used vectorS instead of arrays because it is clearer/easier, also, I used C-style indexing which starts counting from 0, not 1.</p>\n"
},
{
"answer_id": 33194962,
"author": "aravinth",
"author_id": 3553385,
"author_profile": "https://Stackoverflow.com/users/3553385",
"pm_score": 1,
"selected": false,
"text": "<p>create a new Array and use bubble sort to rank the elements</p>\n\n<pre><code>int arr[n];\nint rank[n];\n for(int i=0;i<n;i++)\n for(int j=0;j<n;j++)\n if(arr[i]>arr[j])\n rank[i]++;\n</code></pre>\n\n<p>The rank of each element will be rank[i]+1 to be in the order of 1,2,....n</p>\n"
},
{
"answer_id": 44255995,
"author": "Phillip Kigenyi",
"author_id": 4991437,
"author_profile": "https://Stackoverflow.com/users/4991437",
"pm_score": 0,
"selected": false,
"text": "<p>This is a solution in c language</p>\n\n<pre><code>#include <stdio.h>\n\nvoid swap(int *xp, int *yp) {\n int temp = *xp;\n *xp = *yp;\n *yp = temp;\n}\n\n// A function to implement bubble sort\nvoid bubbleSort(int arr[], int n) {\n int i, j;\n for (i = 0; i < n - 1; i++)\n\n // Last i elements are already in place\n for (j = 0; j < n - i - 1; j++)\n if (arr[j] > arr[j + 1])\n swap(&arr[j], &arr[j + 1]);\n}\n\n/* Function to print an array */\nvoid printArray(int arr[], int size) {\n for (int i = 0; i < size; i++)\n printf(\"%d \", arr[i]);\n printf(\"\\n\");\n}\n\nint main() {\n int arr[] = {64, 34, 25, 12, 22, 11, 98};\n int arr_original[] = {64, 34, 25, 12, 22, 11, 98};\n int rank[7];\n\n int n = sizeof(arr) / sizeof(arr[0]);\n bubbleSort(arr, n);\n\n printf(\"Sorted array: \\n\");\n printArray(arr, n);\n\n //PLACE RANK\n //look for location of number in original array\n //place the location in rank array\n int counter = 1;\n for (int k = 0; k < n; k++){\n for (int i = 0; i < n; i++){\n printf(\"Checking..%d\\n\", i);\n if (arr_original[i] == arr[k]){\n rank[i] = counter;\n counter++;\n printf(\"Found..%d\\n\", i);\n }\n }\n }\n\n printf(\"Original array: \\n\");\n printArray(arr_original, n);\n\n printf(\"Rank array: \\n\");\n printArray(rank, n);\n return 0;\n}\n</code></pre>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522/"
] | I would like to sort an array in ascending order using `C/C++`. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.
**Example**
```
Input: 1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
```
**Edit:** I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.
### Update:
Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.
Could someone please tell me what's wrong?
I'd very much appreciate some help!
```
void SortArray(int ** pArray, int ArrayLength)
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for (i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength - 1); j++)
{
if (*pArray[j + 1] > *pArray[j]) // ascending order simply changes to <
{
&temp = &pArray[j]; // swap elements
&pArray[j] = &pArray[j + 1]; //the problem lies somewhere in here
&pArray[j + 1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
};
``` | Since you're using C++, I would do it something like this. The `SortIntPointers` function can be any sort algorithm, the important part is that it sorts the array of pointers based on the `int` that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which will end up in the original position in the original array.
```
int* intArray; // set somewhere else
int arrayLen; // set somewhere else
int** pintArray = new int*[arrayLen];
for(int i = 0; i < arrayLen; ++i)
{
pintArray[i] = &intArray[i];
}
// This function sorts the pointers according to the values they
// point to. In effect, it sorts intArray without losing the positional
// information.
SortIntPointers(pintArray, arrayLen);
// Dereference the pointers and assign their sorted position.
for(int i = 0; i < arrayLen; ++i)
{
*pintArray[i] = i;
}
```
Hopefully that's clear enough. |
13,540 | <p>I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:</p>
<pre><code>update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)
</code></pre>
<p>My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.</p>
<p>The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.</p>
<p>Is my logic sound here?
Is this how you would combine an insert and update into a stored proc?</p>
| [
{
"answer_id": 13554,
"author": "binOr",
"author_id": 990,
"author_profile": "https://Stackoverflow.com/users/990",
"pm_score": 7,
"selected": true,
"text": "<p>Your assumption is right, this is the optimal way to do it and it's called <a href=\"http://en.wikipedia.org/wiki/Upsert\" rel=\"noreferrer\">upsert/merge</a>.</p>\n\n<p><a href=\"http://www.sqlservercentral.com/articles/T-SQL/61773/\" rel=\"noreferrer\">Importance of UPSERT - from sqlservercentral.com</a>: </p>\n\n<blockquote>\n <p>For every update in the case mentioned above we are removing one\n additional read from the table if we\n use the UPSERT instead of EXISTS.\n Unfortunately for an Insert, both the\n UPSERT and IF EXISTS methods use the\n same number of reads on the table.\n Therefore the check for existence\n should only be done when there is a\n very valid reason to justify the\n additional I/O. The optimized way to\n do things is to make sure that you\n have little reads as possible on the\n DB.</p>\n \n <p>The best strategy is to attempt the\n update. If no rows are affected by the\n update then insert. In most\n circumstances, the row will already\n exist and only one I/O will be\n required.</p>\n</blockquote>\n\n<p><strong>Edit</strong>: \nPlease check out <a href=\"https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server/193876#193876\">this answer</a> and the linked blog post to learn about the problems with this pattern and how to make it work safe.</p>\n"
},
{
"answer_id": 13555,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": false,
"text": "<p>MERGE is one of the new features in SQL Server 2008, by the way.</p>\n"
},
{
"answer_id": 25318,
"author": "Dima Malenko",
"author_id": 2586,
"author_profile": "https://Stackoverflow.com/users/2586",
"pm_score": 3,
"selected": false,
"text": "<p>If to be used with SQL Server 2000/2005 the original code needs to be enclosed in transaction to make sure that data remain consistent in concurrent scenario.</p>\n\n<pre><code>BEGIN TRANSACTION Upsert\nupdate myTable set Col1=@col1, Col2=@col2 where ID=@ID\nif @@rowcount = 0\ninsert into myTable (Col1, Col2) values (@col1, @col2)\nCOMMIT TRANSACTION Upsert\n</code></pre>\n\n<p>This will incur additional performance cost, but will ensure data integrity.</p>\n\n<p>Add, as already suggested, MERGE should be used where available.</p>\n"
},
{
"answer_id": 35364,
"author": "Natron",
"author_id": 3682,
"author_profile": "https://Stackoverflow.com/users/3682",
"pm_score": 2,
"selected": false,
"text": "<p>Big fan of the UPSERT, really cuts down on the code to manage. Here is another way I do it: One of the input parameters is ID, if the ID is NULL or 0, you know it's an INSERT, otherwise it's an update. Assumes the application knows if there is an ID, so wont work in all situations, but will cut the executes in half if you do.</p>\n"
},
{
"answer_id": 39529,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 1,
"selected": false,
"text": "<p>Your logic seems sound, but you might want to consider adding some code to prevent the insert if you had passed in a specific primary key.</p>\n\n<p>Otherwise, if you're always doing an insert if the update didn't affect any records, what happens when someone deletes the record before you \"UPSERT\" runs? Now the record you were trying to update doesn't exist, so it'll create a record instead. That probably isn't the behavior you were looking for.</p>\n"
},
{
"answer_id": 40476,
"author": "Simon Munro",
"author_id": 3893,
"author_profile": "https://Stackoverflow.com/users/3893",
"pm_score": 3,
"selected": false,
"text": "<p>If you are not doing a merge in SQL 2008 you must change it to:</p>\n\n<p>if @@rowcount = 0 and @@error=0</p>\n\n<p>otherwise if the update fails for some reason then it will try and to an insert afterwards because the rowcount on a failed statement is 0</p>\n"
},
{
"answer_id": 80790,
"author": "Tomas Tintera",
"author_id": 15136,
"author_profile": "https://Stackoverflow.com/users/15136",
"pm_score": 3,
"selected": false,
"text": "<p>You not only need to run it in transaction, it also needs high isolation level. I fact default isolation level is Read Commited and this code need Serializable. </p>\n\n<pre><code>SET transaction isolation level SERIALIZABLE\nBEGIN TRANSACTION Upsert\nUPDATE myTable set Col1=@col1, Col2=@col2 where ID=@ID\nif @@rowcount = 0\n begin\n INSERT into myTable (ID, Col1, Col2) values (@ID @col1, @col2)\n end\nCOMMIT TRANSACTION Upsert\n</code></pre>\n\n<p>Maybe adding also the @@error check and rollback could be good idea.</p>\n"
},
{
"answer_id": 193876,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 6,
"selected": false,
"text": "<p>Please read the <a href=\"http://samsaffron.com/blog/archive/2007/04/04/14.aspx\" rel=\"noreferrer\">post on my blog</a> for a good, safe pattern you can use. There are a lot of considerations, and the accepted answer on this question is far from safe. </p>\n\n<p>For a quick answer try the following pattern. It will work fine on SQL 2000 and above. SQL 2005 gives you error handling which opens up other options and SQL 2008 gives you a MERGE command. </p>\n\n<pre><code>begin tran\n update t with (serializable)\n set hitCount = hitCount + 1\n where pk = @id\n if @@rowcount = 0\n begin\n insert t (pk, hitCount)\n values (@id,1)\n end\ncommit tran\n</code></pre>\n"
},
{
"answer_id": 10399131,
"author": "thughes78013",
"author_id": 1367900,
"author_profile": "https://Stackoverflow.com/users/1367900",
"pm_score": 2,
"selected": false,
"text": "<p>Modified Dima Malenko post:</p>\n\n<pre><code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE \n\nBEGIN TRANSACTION UPSERT \n\nUPDATE MYTABLE \nSET COL1 = @col1, \n COL2 = @col2 \nWHERE ID = @ID \n\nIF @@rowcount = 0 \n BEGIN \n INSERT INTO MYTABLE \n (ID, \n COL1, \n COL2) \n VALUES (@ID, \n @col1, \n @col2) \n END \n\nIF @@Error > 0 \n BEGIN \n INSERT INTO MYERRORTABLE \n (ID, \n COL1, \n COL2) \n VALUES (@ID, \n @col1, \n @col2) \n END \n\nCOMMIT TRANSACTION UPSERT \n</code></pre>\n\n<p>You can trap the error and send the record to a failed insert table. <br />\nI needed to do this because we are taking whatever data is send via WSDL and if possible fixing it internally. </p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:
```
update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)
```
My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.
The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.
Is my logic sound here?
Is this how you would combine an insert and update into a stored proc? | Your assumption is right, this is the optimal way to do it and it's called [upsert/merge](http://en.wikipedia.org/wiki/Upsert).
[Importance of UPSERT - from sqlservercentral.com](http://www.sqlservercentral.com/articles/T-SQL/61773/):
>
> For every update in the case mentioned above we are removing one
> additional read from the table if we
> use the UPSERT instead of EXISTS.
> Unfortunately for an Insert, both the
> UPSERT and IF EXISTS methods use the
> same number of reads on the table.
> Therefore the check for existence
> should only be done when there is a
> very valid reason to justify the
> additional I/O. The optimized way to
> do things is to make sure that you
> have little reads as possible on the
> DB.
>
>
> The best strategy is to attempt the
> update. If no rows are affected by the
> update then insert. In most
> circumstances, the row will already
> exist and only one I/O will be
> required.
>
>
>
**Edit**:
Please check out [this answer](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server/193876#193876) and the linked blog post to learn about the problems with this pattern and how to make it work safe. |
13,569 | <p>In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.</p>
<p>I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.</p>
<p>Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach?</p>
| [
{
"answer_id": 13571,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": false,
"text": "<p>Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.</p>\n\n<p>Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.</p>\n"
},
{
"answer_id": 16740,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 3,
"selected": false,
"text": "<p>Personally I use PDO, but I think that is mainly a question of preference.</p>\n\n<p>PDO has some features that help agains SQL injection (<a href=\"http://de.php.net/manual/de/pdo.prepared-statements.php\" rel=\"noreferrer\">prepared statements</a>), but if you are careful with your SQL you can achieve that with mysqli, too.</p>\n\n<p>Moving to another database is not so much a reason to use PDO. As long as you don't use \"special SQL features\", you can switch from one DB to another. However as soon as you use for example \"SELECT ... LIMIT 1\" you can't go to MS-SQL where it is \"SELECT TOP 1 ...\". So this is problematic anyway.</p>\n"
},
{
"answer_id": 49787,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 5,
"selected": false,
"text": "<p>I've started using PDO because the statement support is better, in my opinion. I'm using an ActiveRecord-esque data-access layer, and it's much easier to implement dynamically generated statements. MySQLi's parameter binding must be done in a single function/method call, so if you don't know until runtime how many parameters you'd like to bind, you're forced to use <code>call_user_func_array()</code> (I believe that's the right function name) for selects. And forget about simple dynamic result binding.</p>\n\n<p>Most of all, I like PDO because it's a very reasonable level of abstraction. It's easy to use it in completely abstracted systems where you don't want to write SQL, but it also makes it easy to use a more optimized, pure query type of system, or to mix-and-match the two.</p>\n"
},
{
"answer_id": 55400,
"author": "Dave Gregory",
"author_id": 5677,
"author_profile": "https://Stackoverflow.com/users/5677",
"pm_score": 4,
"selected": false,
"text": "<p>PDO is the standard, it's what most developers will expect to use. mysqli was essentially a bespoke solution to a particular problem, but it has all the problems of the other DBMS-specific libraries. PDO is where all the hard work and clever thinking will go.</p>\n"
},
{
"answer_id": 127218,
"author": "mike",
"author_id": 19217,
"author_profile": "https://Stackoverflow.com/users/19217",
"pm_score": -1,
"selected": false,
"text": "<p>There's one thing to keep in mind.</p>\n\n<p>Mysqli does not support fetch_assoc() function which would return the columns with keys representing column names. Of course it's possible to write your own function to do that, it's not even very long, but I had <strong>really</strong> hard time writing it (for non-believers: if it seems easy to you, try it on your own some time and don't cheat :) )</p>\n"
},
{
"answer_id": 127319,
"author": "Unlabeled Meat",
"author_id": 20291,
"author_profile": "https://Stackoverflow.com/users/20291",
"pm_score": 2,
"selected": false,
"text": "<p>One thing PDO has that MySQLi doesn't that I really like is PDO's ability to return a result as an object of a specified class type (e.g. <code>$pdo->fetchObject('MyClass')</code>). MySQLi's <code>fetch_object()</code> will only return an <code>stdClass</code> object.</p>\n"
},
{
"answer_id": 368758,
"author": "Tom",
"author_id": 26155,
"author_profile": "https://Stackoverflow.com/users/26155",
"pm_score": 4,
"selected": false,
"text": "<p>Here's something else to keep in mind: For now (PHP 5.2) the PDO library is <b>buggy</b>. It's full of strange bugs. For example: before storing a <code>PDOStatement</code> in a variable, the variable should be <code>unset()</code> to avoid a ton of bugs. Most of these have been fixed in PHP 5.3 and they will be released in early 2009 in PHP 5.3 which will probably have many other bugs. You should focus on using PDO for PHP 6.1 if you want a stable release and using PDO for PHP 5.3 if you want to help the community.</p>\n"
},
{
"answer_id": 368990,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": false,
"text": "<p>Well, you could argue with the object oriented aspect, the prepared statements, the fact that it becomes a standard, etc. But I know that most of the time, convincing somebody works better with a killer feature. So there it is:</p>\n\n<p>A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. If you don't want to use an <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"noreferrer\">ORM</a> (cause it's a just a quick script) but you do like object mapping, it's REALLY cool :</p>\n\n<pre><code>class Student {\n\n public $id;\n public $first_name;\n public $last_name\n\n public function getFullName() {\n return $this->first_name.' '.$this->last_name\n }\n}\n\ntry \n{\n $dbh = new PDO(\"mysql:host=$hostname;dbname=school\", $username, $password)\n\n $stmt = $dbh->query(\"SELECT * FROM students\");\n\n /* MAGIC HAPPENS HERE */\n\n $stmt->setFetchMode(PDO::FETCH_INTO, new Student);\n\n\n foreach($stmt as $student)\n {\n echo $student->getFullName().'<br />';\n } \n\n $dbh = null;\n}\ncatch(PDOException $e)\n{\n echo $e->getMessage();\n}\n</code></pre>\n"
},
{
"answer_id": 736849,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>In sense of speed of execution MySQLi wins, but unless you have a good wrapper using MySQLi, its functions dealing with prepared statements are awful.</p>\n\n<p>There are still bugs in mine, but if anyone wants it, <a href=\"http://gorilla3d.com/blog/entry/2008-08-03/improved-mysqli-db-wrapper-prepared-statements\" rel=\"nofollow noreferrer\">here it is</a>.</p>\n\n<p>So in short, if you are looking for a speed gain, then MySQLi; if you want ease of use, then PDO.</p>\n"
},
{
"answer_id": 3937381,
"author": "Dobb",
"author_id": 476285,
"author_profile": "https://Stackoverflow.com/users/476285",
"pm_score": 2,
"selected": false,
"text": "<p>In my <a href=\"http://pbox.ca/1628i\" rel=\"nofollow\">benchmark script</a>, each method is tested 10000 times and the difference of the total time for each method is printed. You should this on your own configuration, I'm sure results will vary!</p>\n\n<p>These are my results: </p>\n\n<ul>\n<li>\"<code>SELECT NULL\" -> PGO()</code> faster by ~ 0.35 seconds</li>\n<li>\"<code>SHOW TABLE STATUS\" -> mysqli()</code> faster by ~ 2.3 seconds</li>\n<li>\"<code>SELECT * FROM users\" -> mysqli()</code> faster by ~ 33 seconds</li>\n</ul>\n\n<p>Note: by using ->fetch_row() for mysqli, the column names are not added to the array, I didn't find a way to do that in PGO. But even if I use ->fetch_array() , mysqli is slightly slower but still faster than PGO (except for SELECT NULL).</p>\n"
},
{
"answer_id": 6825215,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 3,
"selected": false,
"text": "<p>Another notable (good) difference about PDO is that it's <a href=\"http://php.net/manual/en/pdo.quote.php\"><code>PDO::quote()</code></a> method automatically adds the enclosing quotes, whereas <a href=\"http://php.net/manual/en/mysqli.real-escape-string.php\"><code>mysqli::real_escape_string()</code></a> (and similars) don't:</p>\n\n<blockquote>\n <p>PDO::quote() places quotes around the input string (if required) and\n escapes special characters within the input string, using a quoting\n style appropriate to the underlying driver.</p>\n</blockquote>\n"
},
{
"answer_id": 10254595,
"author": "Dfranc3373",
"author_id": 1327815,
"author_profile": "https://Stackoverflow.com/users/1327815",
"pm_score": 3,
"selected": false,
"text": "<p>PDO will make it a lot easier to scale if your site/web app gets really being as you can daily set up Master and slave connections to distribute the load across the database, plus PHP is heading towards moving to PDO as a standard.</p>\n\n<p><a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\">PDO Info</a></p>\n\n<p><a href=\"http://www.oracle.com/technetwork/articles/dsl/white-php-part1-355135.html\">Scaling a Web Application</a></p>\n"
},
{
"answer_id": 14303765,
"author": "Your Common Sense",
"author_id": 285587,
"author_profile": "https://Stackoverflow.com/users/285587",
"pm_score": 3,
"selected": false,
"text": "<p><em>Edited answer.</em></p>\n\n<p>After having some experience with both these APIs, I would say that there are 2 blocking level features which renders mysqli unusable with native prepared statements.<br>\nThey were already mentioned in 2 excellent (yet way underrated) answers:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/4351461/285587\"><strong>Binding values to arbitrary number of placeholders</strong></a></li>\n<li><a href=\"https://stackoverflow.com/a/127218/285587\"><strong>Returning data as a mere array</strong></a> </li>\n</ol>\n\n<p>(both also mentioned in <a href=\"https://stackoverflow.com/a/49787/285587\">this answer</a>)</p>\n\n<p>For some reason mysqli failed with both.<br>\nNowadays it got some improvement for the second one (<a href=\"http://php.net/manual/en/mysqli-stmt.get-result.php\" rel=\"nofollow noreferrer\">get_result</a>), but it works only on mysqlnd installations, means you can't rely on this function in your scripts. </p>\n\n<p>Yet it doesn't have bind-by-value even to this day. </p>\n\n<p>So, there is only one choice: <strong>PDO</strong></p>\n\n<p>All the other reasons, such as </p>\n\n<ul>\n<li>named placeholders (this syntax sugar is way overrated)</li>\n<li>different databases support (nobody actually ever used it)</li>\n<li>fetch into object (just useless syntax sugar)</li>\n<li>speed difference (there is none)</li>\n</ul>\n\n<p>aren't of any significant importance.</p>\n\n<p>At the same time both these APIs lacks some <strong>real important features</strong>, like</p>\n\n<ul>\n<li>identifier placeholder</li>\n<li>placeholder for the complex data types to make dynamical binding less toilsome</li>\n<li>shorter application code.</li>\n</ul>\n\n<p>So, to cover the <em>real</em> life needs, one have to create their own abstraction library, based on one of these APIs, implementing manually parsed placeholders. In this case I'd prefer mysqli, for it has lesser level of abstraction.</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.
I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.
Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach? | Well, you could argue with the object oriented aspect, the prepared statements, the fact that it becomes a standard, etc. But I know that most of the time, convincing somebody works better with a killer feature. So there it is:
A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. If you don't want to use an [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) (cause it's a just a quick script) but you do like object mapping, it's REALLY cool :
```
class Student {
public $id;
public $first_name;
public $last_name
public function getFullName() {
return $this->first_name.' '.$this->last_name
}
}
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=school", $username, $password)
$stmt = $dbh->query("SELECT * FROM students");
/* MAGIC HAPPENS HERE */
$stmt->setFetchMode(PDO::FETCH_INTO, new Student);
foreach($stmt as $student)
{
echo $student->getFullName().'<br />';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
``` |
13,578 | <p>The need arose, in our product, to determine how long the current user has been logged on to Windows (specifically, Vista). It seems there is no straight forward API function for this and I couldn't find anything relevant with WMI (although I'm no expert with WMI, so I might have missed something).</p>
<p>Any ideas?</p>
| [
{
"answer_id": 13581,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 1,
"selected": false,
"text": "<p>In WMI do: \"select * from Win32_Session\"\nthere you'll have \"StartTime\" value.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 13600,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 3,
"selected": true,
"text": "<p>For people not familiar with WMI (like me), here are some links:</p>\n\n<ul>\n<li>MSDN page on using WMI from various languages: <a href=\"http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx</a></li>\n<li>reference about Win32_Session: <a href=\"http://msdn.microsoft.com/en-us/library/aa394422(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394422(VS.85).aspx</a>, but the objects in Win32_session are of type Win32_LogonSession (<a href=\"http://msdn.microsoft.com/en-us/library/aa394189(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394189(VS.85).aspx</a>), which has more interesting properties.</li>\n<li><a href=\"http://www.ks-soft.net/hostmon.eng/wmi/index.htm\" rel=\"nofollow noreferrer\">WMI Explorer</a> - a tool you can use to easily run queries like the one Michal posted.</li>\n</ul>\n\n<p>And here's example querying Win32_Session from VBS:</p>\n\n<pre><code>strComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n & \"{impersonationLevel=impersonate}!\\\\\" _\n & strComputer & \"\\root\\cimv2\")\nSet sessions = objWMIService.ExecQuery _\n (\"select * from Win32_Session\")\n\nFor Each objSession in sessions\n Wscript.Echo objSession.StartTime\nNext\n</code></pre>\n\n<p>It alerts 6 sessions for my personal computer, perhaps you can filter by LogonType to only list the real (\"interactive\") users. I couldn't see how you can select the session of the \"current user\".</p>\n\n<p>[edit] and here's a result from Google to your problem: <a href=\"http://forum.sysinternals.com/forum_posts.asp?TID=3755\" rel=\"nofollow noreferrer\">http://forum.sysinternals.com/forum_posts.asp?TID=3755</a></p>\n"
},
{
"answer_id": 543364,
"author": "Matt Hanson",
"author_id": 5473,
"author_profile": "https://Stackoverflow.com/users/5473",
"pm_score": 0,
"selected": false,
"text": "<p>Using WMI, the Win32Session is a great start. As well, it should be pointed out that if you're on a network you can use Win32_NetworkLoginProfile to get all sorts of info.</p>\n\n<pre><code>Set logins = objWMIService.ExecQuery _\n (\"select * from Win32_NetworkLoginProfile\")\nFor Each objSession in logins\n Wscript.Echo objSession.LastLogon\nNext\n</code></pre>\n\n<p>Other bits of info you can collect include the user name, last logoff, as well as various profile related stuff.</p>\n"
},
{
"answer_id": 43794118,
"author": "Gnat",
"author_id": 478380,
"author_profile": "https://Stackoverflow.com/users/478380",
"pm_score": 2,
"selected": false,
"text": "<p>In Powershell and WMI, the following one-line command will return a list of objects showing the user and the time they logged on.</p>\n\n<pre><code>Get-WmiObject win32_networkloginprofile | ? {$_.lastlogon -ne $null} | % {[PSCustomObject]@{User=$_.caption; LastLogon=[Management.ManagementDateTimeConverter]::ToDateTime($_.lastlogon)}}\n</code></pre>\n\n<p>Explanation:</p>\n\n<ul>\n<li>Retrieve the list of logged in users from WMI</li>\n<li>Filter out any non-interactive users (effectively removes <code>NT AUTHORITY\\SYSTEM</code>)</li>\n<li>Reformats the user and logon time for readability</li>\n</ul>\n\n<p>References:</p>\n\n<ul>\n<li>The WMI object to use: <a href=\"https://forum.sysinternals.com/topic3755.html\" rel=\"nofollow noreferrer\">https://forum.sysinternals.com/topic3755.html</a></li>\n<li>Formatting the date/time: <a href=\"https://blogs.msdn.microsoft.com/powershell/2009/08/12/get-systemuptime-and-working-with-the-wmi-date-format/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/powershell/2009/08/12/get-systemuptime-and-working-with-the-wmi-date-format/</a></li>\n</ul>\n"
},
{
"answer_id": 64367682,
"author": "mhmd",
"author_id": 12484958,
"author_profile": "https://Stackoverflow.com/users/12484958",
"pm_score": 2,
"selected": false,
"text": "<p>You can simply use CMD or PowerShell to query the users using the command:</p>\n<pre><code>C:\\> query user\nUSERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME\njohn rdp-tcp#56 9 Active . 5/3/2020 10:19 AM\nmax rdp-tcp#5 30 Active 5+23:42 9/4/2020 7:31 PM\nyee 35 Disc 6:41 10/14/2020 6:37 PM\nmohammd rdp-tcp#3 37 Active . 10/15/2020 7:51 AM\n</code></pre>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596/"
] | The need arose, in our product, to determine how long the current user has been logged on to Windows (specifically, Vista). It seems there is no straight forward API function for this and I couldn't find anything relevant with WMI (although I'm no expert with WMI, so I might have missed something).
Any ideas? | For people not familiar with WMI (like me), here are some links:
* MSDN page on using WMI from various languages: <http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx>
* reference about Win32\_Session: <http://msdn.microsoft.com/en-us/library/aa394422(VS.85).aspx>, but the objects in Win32\_session are of type Win32\_LogonSession (<http://msdn.microsoft.com/en-us/library/aa394189(VS.85).aspx>), which has more interesting properties.
* [WMI Explorer](http://www.ks-soft.net/hostmon.eng/wmi/index.htm) - a tool you can use to easily run queries like the one Michal posted.
And here's example querying Win32\_Session from VBS:
```
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set sessions = objWMIService.ExecQuery _
("select * from Win32_Session")
For Each objSession in sessions
Wscript.Echo objSession.StartTime
Next
```
It alerts 6 sessions for my personal computer, perhaps you can filter by LogonType to only list the real ("interactive") users. I couldn't see how you can select the session of the "current user".
[edit] and here's a result from Google to your problem: <http://forum.sysinternals.com/forum_posts.asp?TID=3755> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.