qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
138,948 | <p>I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support <code>äöå</code> etc. for regular Finnish text and Cyrillic alphabets like <code>ЦжФ</code> for special cases.</p>
<p>My setup is the following:</p>
<ul>
<li>Development environment: Windows XP</li>
<li>Production environment: Debian</li>
</ul>
<p>Database used: MySQL 5.x</p>
<p>Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site.</p>
<p>How to achieve this?</p>
| [
{
"answer_id": 138950,
"author": "kosoant",
"author_id": 15114,
"author_profile": "https://Stackoverflow.com/users/15114",
"pm_score": 10,
"selected": true,
"text": "<p><em>Answering myself as the FAQ of this site encourages it. This works for me: </em></p>\n\n<p>Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which \"understands\" those characters.</p>\n\n<p>To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:</p>\n\n<h2>Configuring Tomcat's server.xml</h2>\n\n<p>It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:</p>\n\n<pre><code><Connector port=\"8080\" maxHttpHeaderSize=\"8192\"\n maxThreads=\"150\" minSpareThreads=\"25\" maxSpareThreads=\"75\"\n enableLookups=\"false\" redirectPort=\"8443\" acceptCount=\"100\"\n connectionTimeout=\"20000\" disableUploadTimeout=\"true\" \n compression=\"on\" \n compressionMinSize=\"128\" \n noCompressionUserAgents=\"gozilla, traviata\" \n compressableMimeType=\"text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript\"\n URIEncoding=\"UTF-8\"\n/>\n</code></pre>\n\n<p>The key part being <b>URIEncoding=\"UTF-8\"</b> in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded.\nAs a result, when the user writes the following to the address bar of the browser:</p>\n\n<pre><code> https://localhost:8443/ID/Users?action=search&name=*ж*\n</code></pre>\n\n<p>the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as <b>%D0%B6</b>.</p>\n\n<p><i>POST request are not affected by this.</i></p>\n\n<h2> CharsetFilter </h2>\n\n<p>Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:</p>\n\n<pre><code>package fi.foo.filters;\n\nimport javax.servlet.*;\nimport java.io.IOException;\n\npublic class CharsetFilter implements Filter {\n\n private String encoding;\n\n public void init(FilterConfig config) throws ServletException {\n encoding = config.getInitParameter(\"requestEncoding\");\n if (encoding == null) encoding = \"UTF-8\";\n }\n\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)\n throws IOException, ServletException {\n // Respect the client-specified character encoding\n // (see HTTP specification section 3.4.1)\n if (null == request.getCharacterEncoding()) {\n request.setCharacterEncoding(encoding);\n }\n\n // Set the default response content type and encoding\n response.setContentType(\"text/html; charset=UTF-8\");\n response.setCharacterEncoding(\"UTF-8\");\n\n next.doFilter(request, response);\n }\n\n public void destroy() {\n }\n}\n</code></pre>\n\n<p>This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8. </p>\n\n<p>The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application. </p>\n\n<p>This filter has to be added to the <b>web.xml</b> or the deployment descriptor of the webapp:</p>\n\n<pre><code> <!--CharsetFilter start--> \n\n <filter>\n <filter-name>CharsetFilter</filter-name>\n <filter-class>fi.foo.filters.CharsetFilter</filter-class>\n <init-param>\n <param-name>requestEncoding</param-name>\n <param-value>UTF-8</param-value>\n </init-param>\n </filter>\n\n <filter-mapping>\n <filter-name>CharsetFilter</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</code></pre>\n\n<p>The instructions for making this filter are found at the <a href=\"http://wiki.apache.org/tomcat/Tomcat/UTF-8\" rel=\"noreferrer\">tomcat wiki (<a href=\"http://wiki.apache.org/tomcat/Tomcat/UTF-8\" rel=\"noreferrer\">http://wiki.apache.org/tomcat/Tomcat/UTF-8</a>)</a> </p>\n\n<h2> JSP page encoding </h2>\n\n<p>In your <strong>web.xml</strong>, add the following:</p>\n\n<pre><code><jsp-config>\n <jsp-property-group>\n <url-pattern>*.jsp</url-pattern>\n <page-encoding>UTF-8</page-encoding>\n </jsp-property-group>\n</jsp-config>\n</code></pre>\n\n<p>Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:</p>\n\n<pre><code> <%@page pageEncoding=\"UTF-8\" contentType=\"text/html; charset=UTF-8\"%>\n</code></pre>\n\n<p>If some kind of a layout with different JSP-fragments is used, then this is needed in <b>all</b> of them.</p>\n\n<h2> HTML-meta tags </h2>\n\n<p>JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding.\nThen it's time to tell the browser in which encoding the html page is:</p>\n\n<p>This is done with the following at the top of each xhtml page produced by the webapp:</p>\n\n<pre><code> <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fi\">\n <head>\n <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />\n ...\n</code></pre>\n\n<h2> JDBC-connection </h2>\n\n<p>When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in <b>context.xml</b> or wherever the JDBC connection is defiend as follows: </p>\n\n<pre><code> <Resource name=\"jdbc/AppDB\" \n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n maxActive=\"20\" maxIdle=\"10\" maxWait=\"10000\"\n username=\"foo\"\n password=\"bar\"\n driverClassName=\"com.mysql.jdbc.Driver\" url=\"jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&amp;characterEncoding=UTF-8\"\n />\n</code></pre>\n\n<h2> MySQL database and tables</h2>\n\n<p>The used database must use UTF-8 encoding. This is achieved by creating the database with the following:</p>\n\n<pre><code> CREATE DATABASE `ID_development` \n /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;\n</code></pre>\n\n<p>Then, all of the tables need to be in UTF-8 also:</p>\n\n<pre><code> CREATE TABLE `Users` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(30) collate utf8_swedish_ci default NULL\n PRIMARY KEY (`id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;\n</code></pre>\n\n<p>The key part being <b>CHARSET=utf8</b>.</p>\n\n<h2> MySQL server configuration </h2>\n\n<p>MySQL serveri has to be configured also. Typically this is done in Windows by modifying <b>my.ini</b> -file and in Linux by configuring <b>my.cnf</b> -file.\nIn those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.</p>\n\n<pre><code> [client]\n port=3306\n default-character-set=utf8\n\n [mysql]\n default-character-set=utf8\n</code></pre>\n\n<h2> Mysql procedures and functions </h2>\n\n<p>These also need to have the character set defined. For example:</p>\n\n<pre><code> DELIMITER $$\n\n DROP FUNCTION IF EXISTS `pathToNode` $$\n CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8\n READS SQL DATA\n BEGIN\n\n DECLARE path VARCHAR(255) CHARACTER SET utf8;\n\n SET path = NULL;\n\n ...\n\n RETURN path;\n\n END $$\n\n DELIMITER ;\n</code></pre>\n\n<h2> GET requests: latin1 and UTF-8 </h2>\n\n<p>If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:</p>\n\n<pre><code> https://localhost:8443/ID/Users?action=search&name=Petteri\n https://localhost:8443/ID/Users?action=search&name=ж\n</code></pre>\n\n<p>Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string \"Petteri\" is handled correctly.</p>\n\n<p>The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as <b>%D0%B6</b>. </p>\n\n<p>If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as <b>%D0%B6</b>. </p>\n\n<p>The end result is that all users with name \"Petteri\" are found and also all users with the name \"ж\" are found.</p>\n\n<h3>But what about äåö?</h3>\n\n<p>HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following</p>\n\n<pre><code> https://localhost:8443/ID/Users?action=search&name=*Päivi*\n</code></pre>\n\n<p>in to the encoded version</p>\n\n<pre><code> https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*\n</code></pre>\n\n<p>In latin1 the character <b>ä</b> is encoded as <b>%E4</b>. <em>Even though the page/request/everything is defined to use UTF-8</em>. The UTF-8 encoded version of ä is <b>%C3%A4</b></p>\n\n<p>The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8.\n<b>Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8</b></p>\n\n<h2> Stuff to read </h2>\n\n<p>A very big thank you for the writers of the following for giving the answers for my problem:</p>\n\n<ul>\n<li> http://tagunov.tripod.com/i18n/i18n.html </li>\n<li> http://wiki.apache.org/tomcat/Tomcat/UTF-8 </li>\n<li> http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/ </li>\n<li> http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html </li>\n<li> http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html </li>\n<li> http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html </li>\n<li> http://jeppesn.dk/utf-8.html </li>\n<li> http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html </li>\n<li> http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html </li>\n<li> http://www.utf8-chartable.de/ </li>\n</ul>\n\n<h2>Important Note</h2>\n\n<p><a href=\"/questions/tagged/mysql\" class=\"post-tag\" title=\"show questions tagged 'mysql'\" rel=\"tag\">mysql</a> supports the <a href=\"http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane\" rel=\"noreferrer\">Basic Multilingual Plane</a> using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of <code>VARBINARY</code> column type or use the <a href=\"http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html\" rel=\"noreferrer\"><code>utf8mb4</code> character set</a> (which requires MySQL 5.5.3 or later). Just be aware that using the <code>utf8</code> character set in MySQL won't work 100% of the time.</p>\n\n<h2>Tomcat with Apache</h2>\n\n<p>One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:</p>\n\n<ol>\n<li>Add URIEncoding=\"UTF-8\" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <code><Connector port=\"8009\" protocol=\"AJP/1.3\" redirectPort=\"8443\" URIEncoding=\"UTF-8\"/></code></li>\n<li>Goto your apache folder i.e. <code>/etc/httpd/conf</code> and add <code>AddDefaultCharset utf-8</code> in <code>httpd.conf file</code>. <strong>Note:</strong> First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.</li>\n</ol>\n"
},
{
"answer_id": 144558,
"author": "stian",
"author_id": 17542,
"author_profile": "https://Stackoverflow.com/users/17542",
"pm_score": 4,
"selected": false,
"text": "<p>I think you summed it up quite well in your own answer. </p>\n\n<p>In the process of UTF-8-ing(?) from end to end you might also want to make sure java itself is using UTF-8. Use -Dfile.encoding=utf-8 as parameter to the JVM (can be configured in catalina.bat).</p>\n"
},
{
"answer_id": 1847079,
"author": "Mike Mountrakis",
"author_id": 224789,
"author_profile": "https://Stackoverflow.com/users/224789",
"pm_score": 1,
"selected": false,
"text": "<p>This is for Greek Encoding in MySql tables when we want to access them using Java:</p>\n\n<p>Use the following connection setup in your JBoss connection pool (mysql-ds.xml)</p>\n\n<pre><code><connection-url>jdbc:mysql://192.168.10.123:3308/mydatabase</connection-url>\n<driver-class>com.mysql.jdbc.Driver</driver-class>\n<user-name>nts</user-name>\n<password>xaxaxa!</password>\n<connection-property name=\"useUnicode\">true</connection-property>\n<connection-property name=\"characterEncoding\">greek</connection-property>\n</code></pre>\n\n<p>If you don't want to put this in a JNDI connection pool, you can configure it as a JDBC-url like the next line illustrates:</p>\n\n<pre><code>jdbc:mysql://192.168.10.123:3308/mydatabase?characterEncoding=greek\n</code></pre>\n\n<p>For me and Nick, so we never forget it and waste time anymore.....</p>\n"
},
{
"answer_id": 1889473,
"author": "Mike Mountrakis",
"author_id": 229797,
"author_profile": "https://Stackoverflow.com/users/229797",
"pm_score": -1,
"selected": false,
"text": "<p>In case you have specified in connection pool (mysql-ds.xml), in your Java code you can open the connection as follows:</p>\n\n<pre><code>DriverManager.registerDriver(new com.mysql.jdbc.Driver());\nConnection conn = DriverManager.getConnection(\n \"jdbc:mysql://192.168.1.12:3308/mydb?characterEncoding=greek\",\n \"Myuser\", \"mypass\");\n</code></pre>\n"
},
{
"answer_id": 2293521,
"author": "Jay",
"author_id": 113453,
"author_profile": "https://Stackoverflow.com/users/113453",
"pm_score": 1,
"selected": false,
"text": "<p>Nice detailed answer. just wanted to add one more thing which will definitely help others to see the UTF-8 encoding on URLs in action .</p>\n\n<p>Follow the steps below to enable UTF-8 encoding on URLs in firefox.</p>\n\n<ol>\n<li><p>type \"about:config\" in the address bar.</p></li>\n<li><p>Use the filter input type to search for \"network.standard-url.encode-query-utf8\" property.</p></li>\n<li>the above property will be false by default, turn that to TRUE.</li>\n<li>restart the browser.</li>\n</ol>\n\n<p>UTF-8 encoding on URLs works by default in IE6/7/8 and chrome.</p>\n"
},
{
"answer_id": 2828629,
"author": "John",
"author_id": 340505,
"author_profile": "https://Stackoverflow.com/users/340505",
"pm_score": 2,
"selected": false,
"text": "<p>I want also to add from <a href=\"http://wiki.netbeans.org/FaqI18nProjectEncoding\" rel=\"nofollow noreferrer\">here</a> this part solved my utf problem:</p>\n\n<pre><code>runtime.encoding=<encoding>\n</code></pre>\n"
},
{
"answer_id": 6762974,
"author": "caarlos0",
"author_id": 405013,
"author_profile": "https://Stackoverflow.com/users/405013",
"pm_score": 0,
"selected": false,
"text": "<p>I'm with a similar problem, but, in filenames of a file I'm compressing with apache commons.\nSo, i resolved it with this command: </p>\n\n<pre><code>convmv --notest -f cp1252 -t utf8 * -r\n</code></pre>\n\n<p>it works very well for me. Hope it help anyone ;)</p>\n"
},
{
"answer_id": 11130588,
"author": "bnguyen82",
"author_id": 1196285,
"author_profile": "https://Stackoverflow.com/users/1196285",
"pm_score": 0,
"selected": false,
"text": "<p>For my case of displaying Unicode character from message bundles, I don't need to apply \"JSP page encoding\" section to display Unicode on my jsp page. All I need is \"CharsetFilter\" section.</p>\n"
},
{
"answer_id": 21409344,
"author": "Raedwald",
"author_id": 545127,
"author_profile": "https://Stackoverflow.com/users/545127",
"pm_score": 4,
"selected": false,
"text": "<p>To add to <a href=\"https://stackoverflow.com/a/138950/545127\">kosoant's answer</a>, if you are using Spring, rather than writing your own Servlet filter, you can use the class <code>org.springframework.web.filter.CharacterEncodingFilter</code> they provide, configuring it like the following in your web.xml:</p>\n\n<pre><code> <filter>\n <filter-name>encoding-filter</filter-name>\n <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>\n <init-param>\n <param-name>encoding</param-name>\n <param-value>UTF-8</param-value>\n </init-param>\n <init-param>\n <param-name>forceEncoding</param-name>\n <param-value>FALSE</param-value>\n </init-param>\n </filter>\n <filter-mapping>\n <filter-name>encoding-filter</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</code></pre>\n"
},
{
"answer_id": 33714167,
"author": "David",
"author_id": 2083318,
"author_profile": "https://Stackoverflow.com/users/2083318",
"pm_score": 0,
"selected": false,
"text": "<p>One other point that hasn't been mentioned relates to Java Servlets working with Ajax. I have situations where a web page is picking up utf-8 text from the user sending this to a JavaScript file which includes it in a URI sent to the Servlet. The Servlet queries a database, captures the result and returns it as XML to the JavaScript file which formats it and inserts the formatted response into the original web page.</p>\n\n<p>In one web app I was following an early Ajax book's instructions for wrapping up the JavaScript in constructing the URI. The example in the book used the escape() method, which I discovered (the hard way) is wrong. For utf-8 you must use encodeURIComponent().</p>\n\n<p>Few people seem to roll their own Ajax these days, but I thought I might as well add this. </p>\n"
},
{
"answer_id": 41541501,
"author": "Alireza Fattahi",
"author_id": 2648077,
"author_profile": "https://Stackoverflow.com/users/2648077",
"pm_score": 0,
"selected": false,
"text": "<p>About <code>CharsetFilter</code> mentioned in @kosoant answer ....</p>\n\n<p>There is a build in <code>Filter</code> in tomcat <code>web.xml</code> (located at <code>conf/web.xml</code>). The filter is named <code>setCharacterEncodingFilter</code> and is commented by default. You can uncomment this ( Please remember to uncomment its <code>filter-mapping</code> too )</p>\n\n<p>Also there is no need to set <code>jsp-config</code> in your <code>web.xml</code> (I have test it for Tomcat 7+ )</p>\n"
},
{
"answer_id": 45088544,
"author": "MrSalesi",
"author_id": 3600935,
"author_profile": "https://Stackoverflow.com/users/3600935",
"pm_score": 0,
"selected": false,
"text": "<p>Some time you can solve problem through MySQL Administrator wizard. In </p>\n\n<blockquote>\n <p>Startup variables > Advanced > </p>\n</blockquote>\n\n<p>and set Def. char Set:utf8</p>\n\n<p>Maybe this config need restart MySQL.</p>\n"
},
{
"answer_id": 49864030,
"author": "Rogelio Triviño",
"author_id": 555002,
"author_profile": "https://Stackoverflow.com/users/555002",
"pm_score": 1,
"selected": false,
"text": "<p>Previous responses didn't work with my problem. It was only in production, with tomcat and apache mod_proxy_ajp. Post body lost non ascii chars by ?\nThe problem finally was with JVM defaultCharset (US-ASCII in a default instalation: Charset dfset = Charset.defaultCharset();)\nso, the solution was run tomcat server with a modifier to run the JVM with UTF-8 as default charset:</p>\n\n<pre><code>JAVA_OPTS=\"$JAVA_OPTS -Dfile.encoding=UTF-8\" \n</code></pre>\n\n<p>(add this line to catalina.sh and service tomcat restart)</p>\n\n<p>Maybe you must also change linux system variable (edit ~/.bashrc and ~/.profile for permanent change, see <a href=\"https://perlgeek.de/en/article/set-up-a-clean-utf8-environment\" rel=\"nofollow noreferrer\">https://perlgeek.de/en/article/set-up-a-clean-utf8-environment</a>)</p>\n\n<blockquote>\n <p>export LC_ALL=en_US.UTF-8<br>\n export LANG=en_US.UTF-8 </p>\n \n <p>export LANGUAGE=en_US.UTF-8</p>\n</blockquote>\n"
},
{
"answer_id": 54835821,
"author": "Andrei Veshtard",
"author_id": 5917460,
"author_profile": "https://Stackoverflow.com/users/5917460",
"pm_score": 0,
"selected": false,
"text": "<p>Faced the same issue on Spring MVC 5 + Tomcat 9 + JSP.<br>\nAfter the long research, came to an elegant solution (<strong>no</strong> need <strong>filters</strong> and <strong>no</strong> need <strong>changes</strong> in the Tomcat <strong>server.xml</strong> (starting from 8.0.0-RC3 version))</p>\n\n<ol>\n<li><p>In the WebMvcConfigurer implementation set default encoding for messageSource (for reading data from messages source files in the UTF-8 encoding.</p>\n\n<pre><code>@Configuration\n@EnableWebMvc\n@ComponentScan(\"{package.with.components}\")\npublic class WebApplicationContextConfig implements WebMvcConfigurer {\n\n @Bean\n public MessageSource messageSource() {\n final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();\n\n messageSource.setBasenames(\"messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n\n return messageSource;\n }\n\n /* other beans and methods */\n\n}\n</code></pre></li>\n<li><p>In the DispatcherServletInitializer implementation @Override the onStartup method and set request and resource character encoding in it.</p>\n\n<pre><code>public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {\n\n @Override\n public void onStartup(final ServletContext servletContext) throws ServletException {\n\n // https://wiki.apache.org/tomcat/FAQ/CharacterEncoding\n servletContext.setRequestCharacterEncoding(\"UTF-8\");\n servletContext.setResponseCharacterEncoding(\"UTF-8\");\n\n super.onStartup(servletContext);\n }\n\n /* servlet mappings, root and web application configs, other methods */\n\n}\n</code></pre></li>\n<li><p>Save all message source and view files in UTF-8 encoding.</p></li>\n<li><p>Add <%@ page contentType=\"text/html;charset=UTF-8\" %> <strong>or</strong> <%@ page pageEncoding=\"UTF-8\" %> in each *.jsp file <strong>or</strong> add jsp-config descriptor to web.xml</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id=\"WebApp_ID\" version=\"3.0\">\n <display-name>AppName</display-name>\n\n <jsp-config>\n <jsp-property-group>\n <url-pattern>*.jsp</url-pattern>\n <page-encoding>UTF-8</page-encoding>\n </jsp-property-group>\n </jsp-config>\n</web-app>\n</code></pre></li>\n</ol>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/138948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15114/"
]
| I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support `äöå` etc. for regular Finnish text and Cyrillic alphabets like `ЦжФ` for special cases.
My setup is the following:
* Development environment: Windows XP
* Production environment: Debian
Database used: MySQL 5.x
Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site.
How to achieve this? | *Answering myself as the FAQ of this site encourages it. This works for me:*
Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.
To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:
Configuring Tomcat's server.xml
-------------------------------
It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:
```
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"
compression="on"
compressionMinSize="128"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
URIEncoding="UTF-8"
/>
```
The key part being **URIEncoding="UTF-8"** in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded.
As a result, when the user writes the following to the address bar of the browser:
```
https://localhost:8443/ID/Users?action=search&name=*ж*
```
the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as **%D0%B6**.
*POST request are not affected by this.*
CharsetFilter
--------------
Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:
```
package fi.foo.filters;
import javax.servlet.*;
import java.io.IOException;
public class CharsetFilter implements Filter {
private String encoding;
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("requestEncoding");
if (encoding == null) encoding = "UTF-8";
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
throws IOException, ServletException {
// Respect the client-specified character encoding
// (see HTTP specification section 3.4.1)
if (null == request.getCharacterEncoding()) {
request.setCharacterEncoding(encoding);
}
// Set the default response content type and encoding
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
next.doFilter(request, response);
}
public void destroy() {
}
}
```
This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8.
The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.
This filter has to be added to the **web.xml** or the deployment descriptor of the webapp:
```
<!--CharsetFilter start-->
<filter>
<filter-name>CharsetFilter</filter-name>
<filter-class>fi.foo.filters.CharsetFilter</filter-class>
<init-param>
<param-name>requestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
The instructions for making this filter are found at the [tomcat wiki (<http://wiki.apache.org/tomcat/Tomcat/UTF-8>)](http://wiki.apache.org/tomcat/Tomcat/UTF-8)
JSP page encoding
------------------
In your **web.xml**, add the following:
```
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
```
Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:
```
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
```
If some kind of a layout with different JSP-fragments is used, then this is needed in **all** of them.
HTML-meta tags
---------------
JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding.
Then it's time to tell the browser in which encoding the html page is:
This is done with the following at the top of each xhtml page produced by the webapp:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
...
```
JDBC-connection
----------------
When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in **context.xml** or wherever the JDBC connection is defiend as follows:
```
<Resource name="jdbc/AppDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="20" maxIdle="10" maxWait="10000"
username="foo"
password="bar"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&characterEncoding=UTF-8"
/>
```
MySQL database and tables
--------------------------
The used database must use UTF-8 encoding. This is achieved by creating the database with the following:
```
CREATE DATABASE `ID_development`
/*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;
```
Then, all of the tables need to be in UTF-8 also:
```
CREATE TABLE `Users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(30) collate utf8_swedish_ci default NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;
```
The key part being **CHARSET=utf8**.
MySQL server configuration
---------------------------
MySQL serveri has to be configured also. Typically this is done in Windows by modifying **my.ini** -file and in Linux by configuring **my.cnf** -file.
In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.
```
[client]
port=3306
default-character-set=utf8
[mysql]
default-character-set=utf8
```
Mysql procedures and functions
-------------------------------
These also need to have the character set defined. For example:
```
DELIMITER $$
DROP FUNCTION IF EXISTS `pathToNode` $$
CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
READS SQL DATA
BEGIN
DECLARE path VARCHAR(255) CHARACTER SET utf8;
SET path = NULL;
...
RETURN path;
END $$
DELIMITER ;
```
GET requests: latin1 and UTF-8
-------------------------------
If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:
```
https://localhost:8443/ID/Users?action=search&name=Petteri
https://localhost:8443/ID/Users?action=search&name=ж
```
Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.
The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as **%D0%B6**.
If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as **%D0%B6**.
The end result is that all users with name "Petteri" are found and also all users with the name "ж" are found.
### But what about äåö?
HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following
```
https://localhost:8443/ID/Users?action=search&name=*Päivi*
```
in to the encoded version
```
https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*
```
In latin1 the character **ä** is encoded as **%E4**. *Even though the page/request/everything is defined to use UTF-8*. The UTF-8 encoded version of ä is **%C3%A4**
The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8.
**Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8**
Stuff to read
--------------
A very big thank you for the writers of the following for giving the answers for my problem:
* http://tagunov.tripod.com/i18n/i18n.html
* http://wiki.apache.org/tomcat/Tomcat/UTF-8
* http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/
* http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html
* http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html
* http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html
* http://jeppesn.dk/utf-8.html
* http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html
* http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso\_table.html
* http://www.utf8-chartable.de/
Important Note
--------------
[mysql](/questions/tagged/mysql "show questions tagged 'mysql'") supports the [Basic Multilingual Plane](http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane) using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of `VARBINARY` column type or use the [`utf8mb4` character set](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html) (which requires MySQL 5.5.3 or later). Just be aware that using the `utf8` character set in MySQL won't work 100% of the time.
Tomcat with Apache
------------------
One more thing If you are using Apache + Tomcat + mod\_JK connector then you also need to do following changes:
1. Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod\_JK connector. `<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>`
2. Goto your apache folder i.e. `/etc/httpd/conf` and add `AddDefaultCharset utf-8` in `httpd.conf file`. **Note:** First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also. |
138,981 | <p>Is there any way to find out if a file is a directory?</p>
<p>I have the file name in a variable. In Perl I can do this:</p>
<pre><code>if(-d $var) { print "it's a directory\n" }
</code></pre>
| [
{
"answer_id": 138995,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 7,
"selected": true,
"text": "<p>You can do it like so:</p>\n\n<pre><code>IF EXIST %VAR%\\NUL ECHO It's a directory\n</code></pre>\n\n<p>However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:</p>\n\n<pre><code>FOR %%i IN (%VAR%) DO IF EXIST %%~si\\NUL ECHO It's a directory\n</code></pre>\n\n<p>The <code>%%~si</code> converts <code>%%i</code> to an 8.3 filename. To see all the other tricks you can perform with <code>FOR</code> variables enter <code>HELP FOR</code> at a command prompt.</p>\n\n<p>(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the <code>%%</code> with <code>%</code> in both places.)</p>\n"
},
{
"answer_id": 138996,
"author": "RomanM",
"author_id": 14587,
"author_profile": "https://Stackoverflow.com/users/14587",
"pm_score": 1,
"selected": false,
"text": "<p>Based on <a href=\"http://www.faqs.org/faqs/msdos-programmer-faq/part3/section-7.html\" rel=\"nofollow noreferrer\">this article</a> titled \"How can a batch file test existence of a directory\" it's \"not entirely reliable\".</p>\n\n<p>BUT I just tested this:</p>\n\n<pre><code>@echo off\nIF EXIST %1\\NUL goto print\nECHO not dir\npause\nexit\n:print\nECHO It's a directory\npause\n</code></pre>\n\n<p>and it seems to work</p>\n"
},
{
"answer_id": 140663,
"author": "pestophagous",
"author_id": 10278,
"author_profile": "https://Stackoverflow.com/users/10278",
"pm_score": 2,
"selected": false,
"text": "<h2>The NUL technique seems to only work on 8.3 compliant file names.</h2>\n\n<h3>(In other words, `D:\\Documents and Settings` is \"bad\" and `D:\\DOCUME~1` is \"good\")</h3>\n\n<hr>\n\n<p>I think there is some difficulty using the \"NUL\" tecnique when there are SPACES in the directory name, such as \"Documents and Settings.\"</p>\n\n<p>I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\\system32\\cmd.exe</p>\n\n<p>Here are some examples of what DID NOT work and what DOES WORK for me:</p>\n\n<p>(These are all demonstrations done \"live\" at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)</p>\n\n<p><strong>This DID NOT work:</strong></p>\n\n<p><code>D:\\Documents and Settings>if exist \"D:\\Documents and Settings\\NUL\" echo yes</code></p>\n\n<p><strong>This DID NOT work:</strong></p>\n\n<p><code>D:\\Documents and Settings>if exist D:\\Documents and Settings\\NUL echo yes</code></p>\n\n<p><strong>This DOES work (for me):</strong></p>\n\n<p><code>D:\\Documents and Settings>cd ..</code></p>\n\n<p><code>D:\\>REM get the short 8.3 name for the file</code></p>\n\n<p><code>D:\\>dir /x</code></p>\n\n<p><code>Volume in drive D has no label.</code>\n<code>Volume Serial Number is 34BE-F9C9</code></p>\n\n<p><code>Directory of D:\\</code>\n<BR>\n<code>09/25/2008 05:09 PM <DIR> 2008</code><BR>\n<code>09/25/2008 05:14 PM <DIR> 200809~1.25 2008.09.25</code><BR>\n<code>09/23/2008 03:44 PM <DIR> BOOST_~3 boost_repo_working_copy</code><BR>\n<code>09/02/2008 02:13 PM 486,128 CHROME~1.EXE ChromeSetup.exe</code><BR>\n<code>02/14/2008 12:32 PM <DIR> cygwin</code><BR></p>\n\n<p>[[Look right here !!!! ]]<br>\n<code>09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings</code><BR></p>\n\n<p><code>09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt</code><BR>\n<code>01/21/2008 06:58 PM <DIR> NATION~1 National Instruments Downloads</code><BR>\n<code>10/12/2007 11:25 AM <DIR> NVIDIA</code><BR>\n<code>05/13/2008 09:42 AM <DIR> Office10</code><BR>\n<code>09/19/2008 11:08 AM <DIR> PROGRA~1 Program Files</code><BR>\n<code>12/02/1999 02:54 PM 24,576 setx.exe</code><BR>\n<code>09/15/2008 11:19 AM <DIR> TEMP</code><BR>\n<code>02/14/2008 12:26 PM <DIR> tmp</code><BR>\n<code>01/21/2008 07:05 PM <DIR> VXIPNP</code><BR>\n<code>09/23/2008 12:15 PM <DIR> WINDOWS</code><BR>\n<code>02/21/2008 03:49 PM <DIR> wx28</code><BR>\n<code>02/29/2008 01:47 PM <DIR> WXWIDG~2 wxWidgets</code><BR>\n<code>3 File(s) 510,704 bytes</code><BR>\n<code>20 Dir(s) 238,250,901,504 bytes free</code><BR></p>\n\n<p><code>D:\\>REM now use the \\NUL test with the 8.3 name</code></p>\n\n<p><code>D:\\>if exist d:\\docume~1\\NUL echo yes</code></p>\n\n<p><code>yes</code></p>\n\n<p><strong>This works, but it's sort of silly, because the dot already implies i am in a directory:</strong></p>\n\n<p><code>D:\\Documents and Settings>if exist .\\NUL echo yes</code></p>\n"
},
{
"answer_id": 143935,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.</p>\n\n<pre><code>@echo off\nif [%1]==[] goto usage\n\nfor /f \"delims=\" %%i in (\"%~1\") do set MYPATH=\"%%~fi\"\npushd %MYPATH% 2>nul\nif errorlevel 1 goto notdir\ngoto isdir\n\n:notdir\necho not a directory\ngoto exit\n\n:isdir\npopd\necho is a directory\ngoto exit\n\n:usage\necho Usage: %0 DIRECTORY_TO_TEST\n\n:exit\n</code></pre>\n\n<p>Sample output with the above saved as \"isdir.bat\":</p>\n\n<pre><code>C:\\>isdir c:\\Windows\\system32\nis a directory\n\nC:\\>isdir c:\\Windows\\system32\\wow32.dll\nnot a directory\n\nC:\\>isdir c:\\notadir\nnot a directory\n\nC:\\>isdir \"C:\\Documents and Settings\"\nis a directory\n\nC:\\>isdir \\\nis a directory\n\nC:\\>isdir \\\\ninja\\SharedDocs\\cpu-z\nis a directory\n\nC:\\>isdir \\\\ninja\\SharedDocs\\cpu-z\\cpuz.ini\nnot a directory\n</code></pre>\n"
},
{
"answer_id": 1466528,
"author": "Gerard",
"author_id": 3370464,
"author_profile": "https://Stackoverflow.com/users/3370464",
"pm_score": 7,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>if exist %1\\* echo Directory\n</code></pre>\n\n<p>Works with directory names that contains spaces:</p>\n\n<pre><code>C:\\>if exist \"c:\\Program Files\\*\" echo Directory\nDirectory\n</code></pre>\n\n<p>Note that the quotes are necessary if the directory contains spaces:</p>\n\n<pre><code>C:\\>if exist c:\\Program Files\\* echo Directory\n</code></pre>\n\n<p>Can also be expressed as:</p>\n\n<pre><code>C:\\>SET D=\"C:\\Program Files\"\nC:\\>if exist %D%\\* echo Directory\nDirectory\n</code></pre>\n\n<p>This is safe to try at home, kids!</p>\n"
},
{
"answer_id": 3663155,
"author": "TechGuy",
"author_id": 441881,
"author_profile": "https://Stackoverflow.com/users/441881",
"pm_score": 0,
"selected": false,
"text": "<p>One issue with using <code>%%~si\\NUL</code> method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think <code>%%~si</code> resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.</p>\n\n<p>An alternative method:</p>\n\n<pre><code>dir /AD %F% 2>&1 | findstr /C:\"Not Found\">NUL:&&(goto IsFile)||(goto IsDir)\n\n:IsFile\n echo %F% is a file\n goto done\n\n:IsDir\n echo %F% is a directory\n goto done\n\n:done\n</code></pre>\n\n<p>You can replace <code>(goto IsFile)||(goto IsDir)</code> with other batch commands:<br>\n<code>(echo Is a File)||(echo is a Directory)</code></p>\n"
},
{
"answer_id": 3668165,
"author": "Kimae",
"author_id": 442469,
"author_profile": "https://Stackoverflow.com/users/442469",
"pm_score": 2,
"selected": false,
"text": "<p>I use this:</p>\n\n<pre><code>if not [%1] == [] (\n pushd %~dpn1 2> nul\n if errorlevel == 1 pushd %~dp1\n)\n</code></pre>\n"
},
{
"answer_id": 3728742,
"author": "batchman61",
"author_id": 449765,
"author_profile": "https://Stackoverflow.com/users/449765",
"pm_score": 6,
"selected": false,
"text": "<p>Recently failed with different approaches from the above. Quite sure they worked in the past, maybe related to dfs here. Now using the <a href=\"http://ss64.com/nt/syntax-args.html\" rel=\"noreferrer\">files attributes</a> and cut first char</p>\n\n<pre class=\"lang-dos prettyprint-override\"><code>@echo off\nSETLOCAL ENABLEEXTENSIONS\nset ATTR=%~a1\nset DIRATTR=%ATTR:~0,1%\nif /I \"%DIRATTR%\"==\"d\" echo %1 is a folder\n:EOF\n</code></pre>\n"
},
{
"answer_id": 3845794,
"author": "Gerard",
"author_id": 3370464,
"author_profile": "https://Stackoverflow.com/users/3370464",
"pm_score": 4,
"selected": false,
"text": "<p>Further to my previous offering, I find this also works:</p>\n\n<pre><code>if exist %1\\ echo Directory\n</code></pre>\n\n<p>No quotes around %1 are needed because the caller will supply them.\nThis saves one entire keystroke over my answer of a year ago ;-)</p>\n"
},
{
"answer_id": 6671967,
"author": "user117529",
"author_id": 117529,
"author_profile": "https://Stackoverflow.com/users/117529",
"pm_score": 0,
"selected": false,
"text": "<p>Under Windows 7 and XP, I can't get it to tell files vs. dirs on mapped drives. The following script:</p>\n\n<pre>\n@echo off\nif exist c:\\temp\\data.csv echo data.csv is a file\nif exist c:\\temp\\data.csv\\ echo data.csv is a directory\nif exist c:\\temp\\data.csv\\nul echo data.csv is a directory\nif exist k:\\temp\\nonexistent.txt echo nonexistent.txt is a file\nif exist k:\\temp\\something.txt echo something.txt is a file\nif exist k:\\temp\\something.txt\\ echo something.txt is a directory\nif exist k:\\temp\\something.txt\\nul echo something.txt is a directory\n</pre>\n\n<p>produces:</p>\n\n<pre>\ndata.csv is a file\nsomething.txt is a file\nsomething.txt is a directory\nsomething.txt is a directory\n</pre>\n\n<p>So beware if your script might be fed a mapped or UNC path. The pushd solution below seems to be the most foolproof.</p>\n"
},
{
"answer_id": 7567407,
"author": "Aziz",
"author_id": 937064,
"author_profile": "https://Stackoverflow.com/users/937064",
"pm_score": 3,
"selected": false,
"text": "<p>This works perfectly</p>\n\n<pre><code>if exist \"%~1\\\" echo Directory\n</code></pre>\n\n<p>we need to use %~1 to remove quotes from %1, and add a backslash at end. Then put thw whole into qutes again.</p>\n"
},
{
"answer_id": 11460289,
"author": "gialloporpora",
"author_id": 1207623,
"author_profile": "https://Stackoverflow.com/users/1207623",
"pm_score": 0,
"selected": false,
"text": "<p>This is the code that I use in my BATCH files</p>\n\n<pre><code>```\n@echo off\nset param=%~1\nset tempfile=__temp__.txt\ndir /b/ad > %tempfile%\nset isfolder=false\nfor /f \"delims=\" %%i in (temp.txt) do if /i \"%%i\"==\"%param%\" set isfolder=true\ndel %tempfile%\necho %isfolder%\nif %isfolder%==true echo %param% is a directory\n</code></pre>\n\n<p>```</p>\n"
},
{
"answer_id": 11666547,
"author": "Cedric",
"author_id": 1554180,
"author_profile": "https://Stackoverflow.com/users/1554180",
"pm_score": 2,
"selected": false,
"text": "<p>A very simple way is to check if the child exists.</p>\n\n<p>If a child does not have any child, the <code>exist</code> command will return false.</p>\n\n<pre><code>IF EXIST %1\\. (\n echo %1 is a folder\n) else (\n echo %1 is a file\n)\n</code></pre>\n\n<p>You may have some false negative if you don't have sufficient access right (I have not tested it).</p>\n"
},
{
"answer_id": 16017962,
"author": "Lucien Baron",
"author_id": 2282964,
"author_profile": "https://Stackoverflow.com/users/2282964",
"pm_score": -1,
"selected": false,
"text": "<p>Can't we just test with this : </p>\n\n<pre><code>IF [%~x1] == [] ECHO Directory\n</code></pre>\n\n<p>It seems to work for me.</p>\n"
},
{
"answer_id": 16985458,
"author": "user966939",
"author_id": 966939,
"author_profile": "https://Stackoverflow.com/users/966939",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my solution:</p>\n\n<pre><code>REM make sure ERRORLEVEL is 0\nTYPE NUL\n\nREM try to PUSHD into the path (store current dir and switch to another one)\nPUSHD \"insert path here...\" >NUL 2>&1\n\nREM if ERRORLEVEL is still 0, it's most definitely a directory\nIF %ERRORLEVEL% EQU 0 command...\n\nREM if needed/wanted, go back to previous directory\nPOPD\n</code></pre>\n"
},
{
"answer_id": 27097127,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution after many tests with if exist, pushd, dir /AD, etc...</p>\n\n<pre><code>@echo off\ncd /d C:\\\nfor /f \"delims=\" %%I in ('dir /a /ogn /b') do (\n call :isdir \"%%I\"\n if errorlevel 1 (echo F: %%~fI) else echo D: %%~fI\n)\ncmd/k\n\n:isdir\necho.%~a1 | findstr /b \"d\" >nul\nexit /b %errorlevel%\n\n:: Errorlevel\n:: 0 = folder\n:: 1 = file or item not found\n</code></pre>\n\n<ul>\n<li>It works with files that have no extension</li>\n<li>It works with folders named folder.ext</li>\n<li>It works with UNC path</li>\n<li>It works with double-quoted full path or with just the dirname or filename only.</li>\n<li>It works even if you don't have read permissions</li>\n<li>It works with Directory Links (Junctions).</li>\n<li>It works with files whose path contains a Directory Link.</li>\n</ul>\n"
},
{
"answer_id": 28439918,
"author": "Samuel",
"author_id": 1045004,
"author_profile": "https://Stackoverflow.com/users/1045004",
"pm_score": 2,
"selected": false,
"text": "<p>This works and also handles paths with spaces in them:</p>\n\n<pre><code>dir \"%DIR%\" > NUL 2>&1\n\nif not errorlevel 1 (\n echo Directory exists.\n) else (\n echo Directory does not exist.\n)\n</code></pre>\n\n<p>Probably not the most efficient but easier to read than the other solutions in my opinion.</p>\n"
},
{
"answer_id": 28956749,
"author": "Explorer09",
"author_id": 4606310,
"author_profile": "https://Stackoverflow.com/users/4606310",
"pm_score": 2,
"selected": false,
"text": "<p>A variation of @batchman61's approach (checking the Directory attribute).</p>\n\n<p>This time I use an external 'find' command.</p>\n\n<p>(Oh, and note the <code>&&</code> trick. This is to avoid the long boring <code>IF ERRORLEVEL</code> syntax.)</p>\n\n<pre><code>@ECHO OFF\nSETLOCAL EnableExtensions\nECHO.%~a1 | find \"d\" >NUL 2>NUL && (\n ECHO %1 is a directory\n)\n</code></pre>\n\n<p>Outputs yes on:</p>\n\n<ul>\n<li>Directories.</li>\n<li>Directory symbolic links or junctions.</li>\n<li><em>Broken</em> directory symbolic links or junctions. (Doesn't try to resolve links.)</li>\n<li>Directories which you have no read permission on (e.g. \"C:\\System Volume Information\")</li>\n</ul>\n"
},
{
"answer_id": 33329575,
"author": "Frank N",
"author_id": 444255,
"author_profile": "https://Stackoverflow.com/users/444255",
"pm_score": 2,
"selected": false,
"text": "<p>If you can <code>cd</code> into it, it's a directory:</p>\n\n<pre><code>set cwd=%cd%\n\ncd /D \"%1\" 2> nul\n@IF %errorlevel%==0 GOTO end\n\ncd /D \"%~dp1\"\n@echo This is a file.\n\n@goto end2\n:end\n@echo This is a directory\n:end2\n\n@REM restore prior directory\n@cd %cwd%\n</code></pre>\n"
},
{
"answer_id": 46326332,
"author": "M. Jamal",
"author_id": 8642578,
"author_profile": "https://Stackoverflow.com/users/8642578",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to post my own function script about this subject hope to be useful for someone one day.</p>\n\n<pre><code>@pushd %~dp1\n@if not exist \"%~nx1\" (\n popd\n exit /b 0\n) else (\n if exist \"%~nx1\\*\" (\n popd\n exit /b 1\n ) else (\n popd\n exit /b 3\n )\n)\n</code></pre>\n\n<p>This batch script checks if file/folder is exist and if it is a file or a folder.</p>\n\n<p><strong>Usage:</strong></p>\n\n<p>script.bat \"PATH\"</p>\n\n<p><strong>Exit code(s):</strong></p>\n\n<p>0: file/folder doesn't exist.</p>\n\n<p>1: exists, and it is a folder.</p>\n\n<p>3: exists, and it is a file.</p>\n"
},
{
"answer_id": 51579264,
"author": "Константин Ван",
"author_id": 4510033,
"author_profile": "https://Stackoverflow.com/users/4510033",
"pm_score": 2,
"selected": false,
"text": "<p><code>CD</code> returns an <code>EXIT_FAILURE</code> when the specified directory does not exist. And you got <a href=\"https://stackoverflow.com/a/3455609/4510033\"><em>conditional processing symbols</em></a>, so you could do like the below for this.</p>\n\n<pre><code>SET cd_backup=%cd%\n(CD \"%~1\" && CD %cd_backup%) || GOTO Error\n\n:Error\nCD %cd_backup%\n</code></pre>\n"
},
{
"answer_id": 59896046,
"author": "Ste",
"author_id": 8262102,
"author_profile": "https://Stackoverflow.com/users/8262102",
"pm_score": 0,
"selected": false,
"text": "<p>If your objective is to only process directories then this will be useful.</p>\n\n<p>This is taken from the <a href=\"https://ss64.com/nt/for_d.html\" rel=\"nofollow noreferrer\">https://ss64.com/nt/for_d.html</a></p>\n\n<blockquote>\n <p>Example... List every subfolder, below the folder C:\\Work\\ that has a name starting with \"User\":</p>\n\n<pre><code>CD \\Work\nFOR /D /r %%G in (\"User*\") DO Echo We found\n</code></pre>\n</blockquote>\n\n<p><code>FOR /D</code> or <code>FOR /D /R</code></p>\n\n<pre><code>@echo off\ncd /d \"C:\\your directory here\"\nfor /d /r %%A in (\"*\") do echo We found a folder: %%~nxA\npause\n</code></pre>\n\n<p>Remove <code>/r</code> to only go one folder deep. The <code>/r</code> switch is recursive and undocumented in the command below.</p>\n\n<p>The <code>for /d</code> help taken from command <code>for /?</code></p>\n\n<blockquote>\n <p>FOR /D %variable IN (set) DO command [command-parameters]</p>\n \n <p>If set contains wildcards, then specifies to match against directory\n names instead of file names.</p>\n</blockquote>\n"
},
{
"answer_id": 67907737,
"author": "k1dfr0std",
"author_id": 9135863,
"author_profile": "https://Stackoverflow.com/users/9135863",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking for this recently as well, and had stumbled upon a solution which has worked for me, but I do not know of any limitations it has (as I have yet to discover them). I believe this answer is similar in nature to TechGuy's answer above, but I want to add another level of viability. Either way, I have had great success expanding the argument into a full fledged file path, and I believe you have to use <code>setlocal enableextensions</code> for this to work properly.</p>\n<p>Using below I can tell if a file is a directory, or opposite. A lot of this depends on what the user is actually needing. If you prefer to work with a construct searching for <code>errorlevel</code> vs <code>&&</code> and <code>||</code> in your work you can of course do so. Sometimes an if construct for <code>errorlevel</code> can give you a little more flexibility since you do not have to use a <code>GOTO</code> command which can sometimes break your environment conditions.</p>\n<pre><code>@Echo Off\nsetlocal enableextensions\n\nDir /b /a:D "%~f1" && Echo Arg1 is a Folder || Echo Arg1 is NOT a Folder\n\nDir /b /a:-D "%~f1" && Echo Arg1 is a File || Echo Arg1 is NOT a File\n\npause\n</code></pre>\n<p>Using this you could simply drag and drop your file(s) onto the tool you are building to parse them out. Conversely, if you are using other means to comb your file structure and you already have the file and are not dragging/dropping them onto the batch file, you could implement this:</p>\n<pre><code>@Echo Off\nsetlocal enableextensions\n\n\nDir /b /s "C:\\SomeFolderIAmCombing\\*" >"%~dp0SomeFiletogoThroughlater.txt"\n\nFor /f "Usebackq Delims=" %%a in ("%~dp0SomeFiletogoThroughlater.txt") do (\n Call:DetectDir "%%a"\n)\n\nREM Do some stuff after parsing through Files/Directories if needed. \nREM GOTO:EOF below is used to skip all the subroutines below.\n\nREM Using ' CALL:DetectDir "%%a" ' with the for loop keeps the for \nREM loop environment running in the background while still parsing the given file\nREM in a clean environment where GOTO and other commmands do not need Variable Expansion.\n\nGOTO:EOF\n\n:DetectDir [File or Folder being checked]\n\nREM Checks if Arg1 is a Directory. If yes, go to Dir coding. If not, go to File coding.\nDir /b /a:D "%~f1" && Echo Arg1 is a Folder & GOTO:IsDir || Echo Arg1 is NOT a Folder & GOTO:IsFile\n\nREM Checks if Arg1 is NOT a Directory. If Yes, go to File coding. If not, go to Dir coding\nDir /b /a:-D "%~f1" && Echo Arg1 is a File & GOTO:IsFile || Echo Arg1 is NOT a File & GOTO:IsDir\n\n:IsDir\n REM Do your stuff to the Folder\nGOTO:EOF\n\n:IsFile\n REM do your stuff to the File\nGOTO:EOF\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/138981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
]
| Is there any way to find out if a file is a directory?
I have the file name in a variable. In Perl I can do this:
```
if(-d $var) { print "it's a directory\n" }
``` | You can do it like so:
```
IF EXIST %VAR%\NUL ECHO It's a directory
```
However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:
```
FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
```
The `%%~si` converts `%%i` to an 8.3 filename. To see all the other tricks you can perform with `FOR` variables enter `HELP FOR` at a command prompt.
(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the `%%` with `%` in both places.) |
138,994 | <p>I have a procedure with a lot of </p>
<pre><code>i := i +1;
</code></pre>
<p>in it and I think </p>
<pre><code> inc(i);
</code></pre>
<p>looks a lot better. Is there a performance difference or does the function call just get inlined by the compiler? I know this probably doesn't matter at all to my app, I'm just curious.</p>
<p>EDIT: I did some gauging of the performance and found the difference to be very small, in fact as small as 5.1222741794670901427682121946224e-8! So it really doesn't matter. And optimization options really didn't change the outcome much. Thanks for all tips and suggestions!</p>
| [
{
"answer_id": 139008,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 4,
"selected": true,
"text": "<p>Modern compilers optimize the code.<br>\ninc(i) and i:= i+1; are pretty much the same.</p>\n\n<p>Use whichever you prefer.</p>\n\n<p>Edit: As Jim McKeeth corrected: with Overflow Checking there is a difference. Inc does not do a range checking.</p>\n"
},
{
"answer_id": 139066,
"author": "Ondrej Kelle",
"author_id": 11480,
"author_profile": "https://Stackoverflow.com/users/11480",
"pm_score": 2,
"selected": false,
"text": "<p>You can verify it in the CPU window while debugging. The generated CPU instructions are the same for both cases.</p>\n\n<p>I agree <code>Inc(I);</code> looks better although this may be subjective.</p>\n\n<p>Correction: I just found this in the documentation for Inc:</p>\n\n<blockquote>\n <p>\"On some platforms, Inc may generate\n optimized code, especially useful in\n tight loops.\"</p>\n</blockquote>\n\n<p>So it's probably advisable to stick to Inc.</p>\n"
},
{
"answer_id": 139069,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 1,
"selected": false,
"text": "<p>You could always write both pieces of code (in separate procedures), put a breakpoint in the code and compare the assembler in the CPU window.</p>\n\n<p>In general, I'd use inc(i) wherever it's obviously being used only as a loop/index of some sort, and + 1 wherever the 1 would make the code easier to maintain (ie, it might conceivable change to another integer in the future) or just more readable from an algorithm/spec point of view.</p>\n"
},
{
"answer_id": 139176,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>\"On some platforms, Inc may generate optimized code, especially useful in tight loops.\"\nFor optimized compiler such as Delphi it doesn't care. That is about old compilers (e.g. Turbo Pascal)</p>\n"
},
{
"answer_id": 139196,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 3,
"selected": false,
"text": "<p>It all depends on the type of \"i\". In Delphi, one normally declares loop-variables as \"i: Integer\", but it could as well be \"i: PChar\" which resolves to PAnsiChar on everything below Delphi 2009 and FPC (I'm guessing here), and to PWideChar on Delphi 2009 and Delphi.NET (also guessing).</p>\n\n<p>Since Delphi 2009 can do pointer-math, Inc(i) can also be done on typed-pointers (if they are defined with POINTER_MATH turned on).</p>\n\n<p>For example:</p>\n\n<pre><code>type\n PSomeRecord = ^RSomeRecord;\n RSomeRecord = record\n Value1: Integer;\n Value2: Double;\n end;\n\nvar\n i: PSomeRecord; \n\nprocedure Test;\nbegin\n Inc(i); // This line increases i with SizeOf(RSomeRecord) bytes, thanks to POINTER_MATH !\nend;\n</code></pre>\n\n<p>As the other anwsers already said : It's relativly easy to see what the compiler made of your code by opening up :</p>\n\n<blockquote>\n <p>Views > Debug Windows > CPU Windows > Disassembly</p>\n</blockquote>\n\n<p>Note, that compiler options like OPTIMIZATION, OVERFLOW_CHECKS and RANGE_CHECKS might influence the final result, so you should take care to have the settings according to your preference.</p>\n\n<p>A tip on this : In every unit, $INCLUDE a file that steers the compiler options, this way, you won't loose settings when your .bdsproj or .dproj is somehow damaged. (Look at the sourcecode of the JCL for a good example on this)</p>\n"
},
{
"answer_id": 143191,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 4,
"selected": false,
"text": "<p>There is a huge difference if <strong>Overflow Checking</strong> is turned on. Basically <em>Inc <strong>does not</strong> do overflow checking</em>. Do as was suggested and use the disassembly window to see the difference when you have those compiler options turned on (it is different for each).</p>\n\n<p>If those options are turned off, then there is no difference. Rule of thumb, use Inc when you don't care about a range checking failure (since you won't get an exception!).</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/138994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
]
| I have a procedure with a lot of
```
i := i +1;
```
in it and I think
```
inc(i);
```
looks a lot better. Is there a performance difference or does the function call just get inlined by the compiler? I know this probably doesn't matter at all to my app, I'm just curious.
EDIT: I did some gauging of the performance and found the difference to be very small, in fact as small as 5.1222741794670901427682121946224e-8! So it really doesn't matter. And optimization options really didn't change the outcome much. Thanks for all tips and suggestions! | Modern compilers optimize the code.
inc(i) and i:= i+1; are pretty much the same.
Use whichever you prefer.
Edit: As Jim McKeeth corrected: with Overflow Checking there is a difference. Inc does not do a range checking. |
138,999 | <p>I just started learning JSP technology, and came across a wall.</p>
<p><em>How do you output HTML from a method in <%! ... %> JSP declaration block?</em></p>
<p>This doesn't work:</p>
<pre><code><%!
void someOutput() {
out.println("Some Output");
}
%>
...
<% someOutput(); %>
</code></pre>
<p>Server says there's no “out”.</p>
<p><strong>U:</strong> I do know how to rewrite code with this method returning a string, but is there a way to do this inside <%! void () { } %> ? Though it may be non-optimal, it's still interesting.</p>
| [
{
"answer_id": 139018,
"author": "Ashley Mercer",
"author_id": 13065,
"author_profile": "https://Stackoverflow.com/users/13065",
"pm_score": 5,
"selected": false,
"text": "<p>You can't use the 'out' variable (nor any of the other \"predeclared\" scriptlet variables) inside directives.</p>\n\n<p>The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start \"<%\"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called \"out\". This is why you can use the \"out\" parameter directly in scriptlets. Directives, on the other hand (which start with \"<%!\") get translated as separate Java methods.</p>\n\n<p>As an example, a very simple page (let's call it foo.jsp):</p>\n\n<pre><code><html>\n <head/>\n <body>\n <%!\n String someOutput() {\n return \"Some output\";\n }\n %>\n <% someOutput(); %>\n </body>\n</html>\n</code></pre>\n\n<p>would end up looking something like this (with a lot of the detail ignored for clarity):</p>\n\n<pre><code>public final class foo_jsp\n{\n // This is where the request comes in\n public void _jspService(HttpServletRequest request, HttpServletResponse response) \n throws IOException, ServletException\n {\n // JspWriter instance is gotten from a factory\n // This is why you can use 'out' directly in scriptlets\n JspWriter out = ...; \n\n // Snip\n\n out.write(\"<html>\");\n out.write(\"<head/>\");\n out.write(\"<body>\");\n out.write(someOutput()); // i.e. write the results of the method call\n out.write(\"</body>\");\n out.write(\"</html>\");\n }\n\n // Directive gets translated as separate method - note\n // there is no 'out' variable declared in scope\n private String someOutput()\n {\n return \"Some output\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 139061,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 4,
"selected": false,
"text": "<p>I suppose this would help:</p>\n\n<pre><code><%! \n String someOutput() {\n return \"Some Output\";\n }\n%>\n...\n<%= someOutput() %>\n</code></pre>\n\n<p>Anyway, it isn't a good idea to have code in a view.</p>\n"
},
{
"answer_id": 140674,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<p>All you need to do is pass the JspWriter object into your method as a parameter i.e.</p>\n\n<pre><code>void someOutput(JspWriter stream)\n</code></pre>\n\n<p>Then call it via:</p>\n\n<pre><code><% someOutput(out) %>\n</code></pre>\n\n<p>The writer object is a local variable inside _jspService so you need to pass it into your utility method. The same would apply for all the other built in references (e.g. request, response, session). </p>\n\n<p>A great way to see whats going on is to use Tomcat as your server and drill down into the 'work' directory for the '.java' file generated from your 'jsp' page. Alternatively in weblogic you can use the 'weblogic.jspc' page compiler to view the Java that will be generated when the page is requested. </p>\n"
},
{
"answer_id": 10996495,
"author": "Dave",
"author_id": 1451197,
"author_profile": "https://Stackoverflow.com/users/1451197",
"pm_score": 4,
"selected": false,
"text": "<pre><code><%!\nprivate void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)\n{ \n try{ myOut.println(\"<div>\"+Bits+\"</div>\"); } \n catch(Exception eek) { }\n}\n%>\n...\n<%\n myFunc(\"more difficult than it should be\",out);\n%>\n</code></pre>\n\n<p>Try this, it worked for me!</p>\n"
},
{
"answer_id": 17661925,
"author": "hestellezg",
"author_id": 2093371,
"author_profile": "https://Stackoverflow.com/users/2093371",
"pm_score": -1,
"selected": false,
"text": "<p>You can do something like this:\n<br></p>\n\n<pre><code><%\n\nout.print(\"<p>Hey!</p>\"); \nout.print(\"<p>How are you?</p>\");\n\n%>\n</code></pre>\n"
},
{
"answer_id": 22159610,
"author": "Martin",
"author_id": 1021426,
"author_profile": "https://Stackoverflow.com/users/1021426",
"pm_score": 2,
"selected": false,
"text": "<p>You can do something like this:</p>\n\n<pre><code><%!\nString myMethod(String input) {\n return \"test \" + input;\n}\n%>\n\n<%= myMethod(\"1 2 3\") %>\n</code></pre>\n\n<p>This will output <code>test 1 2 3</code> to the page.</p>\n"
},
{
"answer_id": 22427128,
"author": "Jer Yango",
"author_id": 1501637,
"author_profile": "https://Stackoverflow.com/users/1501637",
"pm_score": 3,
"selected": false,
"text": "<p>A simple alternative would be the following:</p>\n\n<pre><code><%!\n String myVariable = \"Test\";\n pageContext.setAttribute(\"myVariable\", myVariable);\n%>\n\n<c:out value=\"myVariable\"/>\n<h1>${myVariable}</h1>\n</code></pre>\n\n<p>The you could simply use the variable in any way within the jsp code</p>\n"
},
{
"answer_id": 32263319,
"author": "Alaa Abuzaghleh",
"author_id": 1345798,
"author_profile": "https://Stackoverflow.com/users/1345798",
"pm_score": 2,
"selected": false,
"text": "<p>too late to answer it but this help others </p>\n\n<pre><code><%! \n public void printChild(Categories cat, HttpServletResponse res ){\n try{\n if(cat.getCategoriesSet().size() >0){\n res.getWriter().write(\"\") ; \n }\n }catch(Exception exp){\n\n }\n }\n\n%>\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/138999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764/"
]
| I just started learning JSP technology, and came across a wall.
*How do you output HTML from a method in <%! ... %> JSP declaration block?*
This doesn't work:
```
<%!
void someOutput() {
out.println("Some Output");
}
%>
...
<% someOutput(); %>
```
Server says there's no “out”.
**U:** I do know how to rewrite code with this method returning a string, but is there a way to do this inside <%! void () { } %> ? Though it may be non-optimal, it's still interesting. | You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives.
The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods.
As an example, a very simple page (let's call it foo.jsp):
```
<html>
<head/>
<body>
<%!
String someOutput() {
return "Some output";
}
%>
<% someOutput(); %>
</body>
</html>
```
would end up looking something like this (with a lot of the detail ignored for clarity):
```
public final class foo_jsp
{
// This is where the request comes in
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// JspWriter instance is gotten from a factory
// This is why you can use 'out' directly in scriptlets
JspWriter out = ...;
// Snip
out.write("<html>");
out.write("<head/>");
out.write("<body>");
out.write(someOutput()); // i.e. write the results of the method call
out.write("</body>");
out.write("</html>");
}
// Directive gets translated as separate method - note
// there is no 'out' variable declared in scope
private String someOutput()
{
return "Some output";
}
}
``` |
139,000 | <p>I hope someone might be able to help me here. I've tried to simplify my example as best I can.</p>
<p>I have an absolutely positioned DIV, which for this example I've made fill the browser window. This div has the overflow:auto attribute to provide scroll bars when the content is too big for the DIV to display.</p>
<p>Within the DIV I have a table to present some data, and it's width is 100%.</p>
<p>When the content becomes too large vertically, I expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar. However in IE7 what happens is the horizontal scroll bar also appears, despite there still being enough space horizontally for all the content in the div.</p>
<p>This is IE specific - firefox works perfectly.</p>
<p>Full source below. Any help greatly appreciated.</p>
<p>Tony</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Table sizing bug?</title>
<style>
#maxsize
{
position: absolute;
left: 5px;
right: 5px;
top: 5px;
bottom: 5px;
border: 5px solid silver;
overflow: auto;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="maxsize">
<p>This will be fine until such time as the vertical size forces a
vertical scroll bar. At this point I'd expect the table to re-size
to now take into account of the new vertical scroll bar. Instead,
IE7 keeps the table the full size and introduces a horizontal
scroll bar.
</p>
<table width="100%" cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>E</td>
<td>F</td>
<td>G</td>
<td>H</td>
<td>I</td>
<td>J</td>
<td>K</td>
<td>L</td>
<td>M</td>
<td>N</td>
<td>O</td>
<td>P</td>
<td>Q</td>
<td>R</td>
</tr>
</tbody>
</table>
<p>Resize the browser window vertically so this content doesn't
fit any more</p>
<p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p>
<p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p>
</div>
</form>
</body>
</html>
</code></pre>
<hr>
<p><strong>added 03/16/10...</strong> thought it might be interesting to point out that GWT's source code points to this question in a comment... <a href="http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&q=%22hack%20to%20account%20for%20the%22%20scrollpanel&sa=N&cd=1&ct=rc&l=48" rel="noreferrer">http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&q=%22hack%20to%20account%20for%20the%22%20scrollpanel&sa=N&cd=1&ct=rc&l=48</a></p>
| [
{
"answer_id": 139024,
"author": "Patcouch22",
"author_id": 19226,
"author_profile": "https://Stackoverflow.com/users/19226",
"pm_score": 0,
"selected": false,
"text": "<p>This looks like it should fix your problem, as long as you are not apposed to condition statements. <a href=\"http://blog.josh420.com/archives/2007/11/fixing-the-ie-overflow-vertical-scrollbar-bug.aspx\" rel=\"nofollow noreferrer\">Fixing IE overflow</a></p>\n"
},
{
"answer_id": 139091,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 3,
"selected": false,
"text": "<p>Change:</p>\n\n<pre><code>overflow: auto;\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>overflow-y:hidden;\noverflow-x:auto;\n</code></pre>\n"
},
{
"answer_id": 341926,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, this is a quirk of IE. There's no way using pure XHTML and CSS to get it to work the same as Firefox.</p>\n\n<p>You could do it using JavaScript to detect the size of the window and set the width of the table dynamically. I can add more detail on that if you really wanted to go that route.</p>\n"
},
{
"answer_id": 474635,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Okay, this one plagued me for a LONG time. I have made far too many designs that have extra padding on the right, allowing for IEs complete disregard for their own scrollbar.</p>\n\n<p>The answer is: nest two divs, give them both hasLayout, set the inner one to overflow.</p>\n\n<pre><code><!-- zoom: 1 is a proprietary IE property. It doesn't really do anything here, except give hasLayout -->\n\n<div style=\"zoom: 1;\">\n <div style=\"zoom: 1; overflow: auto\">\n <table style=\"width: 100%\"...\n ...\n </table>\n </div>\n</div>\n</code></pre>\n\n<p><a href=\"http://www.satzansatz.de/cssd/onhavinglayout.html\" rel=\"noreferrer\">http://www.satzansatz.de/cssd/onhavinglayout.html</a>\n<br>\nGo there to read more about having layout</p>\n"
},
{
"answer_id": 879515,
"author": "cetnar",
"author_id": 104796,
"author_profile": "https://Stackoverflow.com/users/104796",
"pm_score": 5,
"selected": false,
"text": "<p>I had a problem with excessive horizonal bar in IE7. I've used D Carter's solution slighty changed</p>\n\n<pre><code><div style=\"zoom: 1; overflow: auto;\">\n <div id=\"myDiv\" style=\"zoom: 1;\">\n <table style=\"width: 100%\"...\n ...\n </table>\n </div>\n</div>\n</code></pre>\n\n<p>To work in IE browser lesser than 7 you need add:</p>\n\n<pre><code><!--[if lt IE 7]><style> #myDiv { overflow: auto; } </style><![endif]-->\n</code></pre>\n"
},
{
"answer_id": 1539977,
"author": "Joel Webber",
"author_id": 186651,
"author_profile": "https://Stackoverflow.com/users/186651",
"pm_score": 3,
"selected": false,
"text": "<p>Eran Galperin's solution fails to account for the fact that simply turning off horizontal scrolling will still allow the table to underlap the vertical scrollbar. I assume this is because IE is calculating the meaning of \"100%\" before deciding that it needs a vertical scrollbar, then failing to re-adjust for the remaining horizontal space available.</p>\n\n<p>cetnar's solution above nails it, though:</p>\n\n<pre><code><div style=\"zoom: 1; overflow: auto;\">\n <div id=\"myDiv\" style=\"zoom: 1;\">\n <table style=\"width: 100%\">\n ...\n </table>\n </div>\n</div>\n</code></pre>\n\n<p>This works properly on IE6 and 7 in my tests. From what I can tell, the \"\" hack doesn't appear to actually be necessary on IE6.</p>\n"
},
{
"answer_id": 1560366,
"author": "Robert Munteanu",
"author_id": 112671,
"author_profile": "https://Stackoverflow.com/users/112671",
"pm_score": 2,
"selected": false,
"text": "<p>This is <a href=\"http://code.google.com/p/google-web-toolkit/source/detail?r=6354\" rel=\"nofollow noreferrer\">reported fixed in GWT trunk</a>.</p>\n"
},
{
"answer_id": 5180060,
"author": "Steve Tchorzewski",
"author_id": 642877,
"author_profile": "https://Stackoverflow.com/users/642877",
"pm_score": 1,
"selected": false,
"text": "<p>If it's the body tag that insists on having the horizontal scroll (I guess because I have child elements set to 100%) you can add this to your CSS to fix the problem in IE7 (or 8 compatibility mode):</p>\n\n<pre><code>html{overflow-x:hidden;}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I hope someone might be able to help me here. I've tried to simplify my example as best I can.
I have an absolutely positioned DIV, which for this example I've made fill the browser window. This div has the overflow:auto attribute to provide scroll bars when the content is too big for the DIV to display.
Within the DIV I have a table to present some data, and it's width is 100%.
When the content becomes too large vertically, I expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar. However in IE7 what happens is the horizontal scroll bar also appears, despite there still being enough space horizontally for all the content in the div.
This is IE specific - firefox works perfectly.
Full source below. Any help greatly appreciated.
Tony
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Table sizing bug?</title>
<style>
#maxsize
{
position: absolute;
left: 5px;
right: 5px;
top: 5px;
bottom: 5px;
border: 5px solid silver;
overflow: auto;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="maxsize">
<p>This will be fine until such time as the vertical size forces a
vertical scroll bar. At this point I'd expect the table to re-size
to now take into account of the new vertical scroll bar. Instead,
IE7 keeps the table the full size and introduces a horizontal
scroll bar.
</p>
<table width="100%" cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>E</td>
<td>F</td>
<td>G</td>
<td>H</td>
<td>I</td>
<td>J</td>
<td>K</td>
<td>L</td>
<td>M</td>
<td>N</td>
<td>O</td>
<td>P</td>
<td>Q</td>
<td>R</td>
</tr>
</tbody>
</table>
<p>Resize the browser window vertically so this content doesn't
fit any more</p>
<p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p>
<p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p>
</div>
</form>
</body>
</html>
```
---
**added 03/16/10...** thought it might be interesting to point out that GWT's source code points to this question in a comment... <http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&q=%22hack%20to%20account%20for%20the%22%20scrollpanel&sa=N&cd=1&ct=rc&l=48> | I had a problem with excessive horizonal bar in IE7. I've used D Carter's solution slighty changed
```
<div style="zoom: 1; overflow: auto;">
<div id="myDiv" style="zoom: 1;">
<table style="width: 100%"...
...
</table>
</div>
</div>
```
To work in IE browser lesser than 7 you need add:
```
<!--[if lt IE 7]><style> #myDiv { overflow: auto; } </style><![endif]-->
``` |
139,010 | <p>I need to find out the file/directory name that a .lnk is pointing to using c#.</p>
<p>What is the simplest way to do this?</p>
<p>Thanks.</p>
| [
{
"answer_id": 139032,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 4,
"selected": false,
"text": "<p>This may help:</p>\n\n<p><a href=\"http://www.neowin.net/forum/index.php?s=3ad7f1ffb995ba84999376f574e9250f&showtopic=658928&st=0&p=589667108&#entry589667108\" rel=\"noreferrer\">http://www.neowin.net/forum/index.php?s=3ad7f1ffb995ba84999376f574e9250f&showtopic=658928&st=0&p=589667108&#entry589667108</a></p>\n\n<p>In essence...</p>\n\n<p>Add reference to Windows Script Host Object Model in COM tab of Add Reference dialogue.</p>\n\n<pre><code>IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();\n\nIWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(link);\n\nConsole.WriteLine(shortcut.TargetPath);\n</code></pre>\n"
},
{
"answer_id": 139220,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 2,
"selected": false,
"text": "<p>Adding to what Kev said...</p>\n\n<p>If you are using <em>csc.exe</em> instead of Visual Studio, to add a reference to the Windows Script Host Object Model, you have to:</p>\n\n<ul>\n<li><p>Use the <em>tlbimp.exe</em> tool to create a managed assembly:</p>\n\n<p>tlbimp.exe c:\\windows\\system32\\wshom.ocx /out:IWshRuntimeLibrary.dll</p></li>\n<li><p>Reference the .dll using the /r switch in <em>csc.exe</em>:</p>\n\n<p>csc.exe Lnk.cs /r:IWshRuntimeLibrary.dll</p></li>\n</ul>\n"
},
{
"answer_id": 220870,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 6,
"selected": false,
"text": "<p>I wrote this for video browser, it works really well </p>\n\n<pre><code>#region Signitures imported from http://pinvoke.net\n\n[DllImport(\"shfolder.dll\", CharSet = CharSet.Auto)]\ninternal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);\n\n[Flags()]\nenum SLGP_FLAGS\n{\n /// <summary>Retrieves the standard short (8.3 format) file name</summary>\n SLGP_SHORTPATH = 0x1,\n /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>\n SLGP_UNCPRIORITY = 0x2,\n /// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary>\n SLGP_RAWPATH = 0x4\n}\n\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\nstruct WIN32_FIND_DATAW\n{\n public uint dwFileAttributes;\n public long ftCreationTime;\n public long ftLastAccessTime;\n public long ftLastWriteTime;\n public uint nFileSizeHigh;\n public uint nFileSizeLow;\n public uint dwReserved0;\n public uint dwReserved1;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string cFileName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]\n public string cAlternateFileName;\n}\n\n[Flags()]\nenum SLR_FLAGS\n{\n /// <summary>\n /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,\n /// the high-order word of fFlags can be set to a time-out value that specifies the\n /// maximum amount of time to be spent resolving the link. The function returns if the\n /// link cannot be resolved within the time-out duration. If the high-order word is set\n /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds\n /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out\n /// duration, in milliseconds.\n /// </summary>\n SLR_NO_UI = 0x1,\n /// <summary>Obsolete and no longer used</summary>\n SLR_ANY_MATCH = 0x2,\n /// <summary>If the link object has changed, update its path and list of identifiers.\n /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine\n /// whether or not the link object has changed.</summary>\n SLR_UPDATE = 0x4,\n /// <summary>Do not update the link information</summary>\n SLR_NOUPDATE = 0x8,\n /// <summary>Do not execute the search heuristics</summary>\n SLR_NOSEARCH = 0x10,\n /// <summary>Do not use distributed link tracking</summary>\n SLR_NOTRACK = 0x20,\n /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks\n /// removable media across multiple devices based on the volume name. It also uses the\n /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter\n /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>\n SLR_NOLINKINFO = 0x40,\n /// <summary>Call the Microsoft Windows Installer</summary>\n SLR_INVOKE_MSI = 0x80\n}\n\n\n/// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>\n[ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(\"000214F9-0000-0000-C000-000000000046\")]\ninterface IShellLinkW\n{\n /// <summary>Retrieves the path and file name of a Shell link object</summary>\n void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);\n /// <summary>Retrieves the list of item identifiers for a Shell link object</summary>\n void GetIDList(out IntPtr ppidl);\n /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>\n void SetIDList(IntPtr pidl);\n /// <summary>Retrieves the description string for a Shell link object</summary>\n void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);\n /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>\n void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);\n /// <summary>Retrieves the name of the working directory for a Shell link object</summary>\n void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);\n /// <summary>Sets the name of the working directory for a Shell link object</summary>\n void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);\n /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>\n void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);\n /// <summary>Sets the command-line arguments for a Shell link object</summary>\n void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);\n /// <summary>Retrieves the hot key for a Shell link object</summary>\n void GetHotkey(out short pwHotkey);\n /// <summary>Sets a hot key for a Shell link object</summary>\n void SetHotkey(short wHotkey);\n /// <summary>Retrieves the show command for a Shell link object</summary>\n void GetShowCmd(out int piShowCmd);\n /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>\n void SetShowCmd(int iShowCmd);\n /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>\n void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,\n int cchIconPath, out int piIcon);\n /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>\n void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);\n /// <summary>Sets the relative path to the Shell link object</summary>\n void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);\n /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>\n void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);\n /// <summary>Sets the path and file name of a Shell link object</summary>\n void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);\n\n}\n\n[ComImport, Guid(\"0000010c-0000-0000-c000-000000000046\"),\nInterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IPersist\n{\n [PreserveSig]\n void GetClassID(out Guid pClassID);\n}\n\n\n[ComImport, Guid(\"0000010b-0000-0000-C000-000000000046\"),\nInterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IPersistFile : IPersist\n{\n new void GetClassID(out Guid pClassID);\n [PreserveSig]\n int IsDirty();\n\n [PreserveSig]\n void Load([In, MarshalAs(UnmanagedType.LPWStr)]\n string pszFileName, uint dwMode);\n\n [PreserveSig]\n void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName,\n [In, MarshalAs(UnmanagedType.Bool)] bool fRemember);\n\n [PreserveSig]\n void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName);\n\n [PreserveSig]\n void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);\n}\n\nconst uint STGM_READ = 0;\nconst int MAX_PATH = 260;\n\n// CLSID_ShellLink from ShlGuid.h \n[\n ComImport(),\n Guid(\"00021401-0000-0000-C000-000000000046\")\n]\npublic class ShellLink\n{\n}\n\n#endregion \n\n\npublic static string ResolveShortcut(string filename)\n{\n ShellLink link = new ShellLink();\n ((IPersistFile)link).Load(filename, STGM_READ);\n // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. \n // ((IShellLinkW)link).Resolve(hwnd, 0) \n StringBuilder sb = new StringBuilder(MAX_PATH);\n WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();\n ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);\n return sb.ToString(); \n}\n</code></pre>\n"
},
{
"answer_id": 69596621,
"author": "DMike92",
"author_id": 1056540,
"author_profile": "https://Stackoverflow.com/users/1056540",
"pm_score": -1,
"selected": false,
"text": "<p>Or simply test <code>mydir</code> and if it does not exists, <code>mydir.lnk</code> with <code>File.Exixts()</code>.</p>\n<p>Works for a file.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I need to find out the file/directory name that a .lnk is pointing to using c#.
What is the simplest way to do this?
Thanks. | I wrote this for video browser, it works really well
```
#region Signitures imported from http://pinvoke.net
[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
[Flags()]
enum SLGP_FLAGS
{
/// <summary>Retrieves the standard short (8.3 format) file name</summary>
SLGP_SHORTPATH = 0x1,
/// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>
SLGP_UNCPRIORITY = 0x2,
/// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary>
SLGP_RAWPATH = 0x4
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct WIN32_FIND_DATAW
{
public uint dwFileAttributes;
public long ftCreationTime;
public long ftLastAccessTime;
public long ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[Flags()]
enum SLR_FLAGS
{
/// <summary>
/// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
/// the high-order word of fFlags can be set to a time-out value that specifies the
/// maximum amount of time to be spent resolving the link. The function returns if the
/// link cannot be resolved within the time-out duration. If the high-order word is set
/// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
/// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
/// duration, in milliseconds.
/// </summary>
SLR_NO_UI = 0x1,
/// <summary>Obsolete and no longer used</summary>
SLR_ANY_MATCH = 0x2,
/// <summary>If the link object has changed, update its path and list of identifiers.
/// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
/// whether or not the link object has changed.</summary>
SLR_UPDATE = 0x4,
/// <summary>Do not update the link information</summary>
SLR_NOUPDATE = 0x8,
/// <summary>Do not execute the search heuristics</summary>
SLR_NOSEARCH = 0x10,
/// <summary>Do not use distributed link tracking</summary>
SLR_NOTRACK = 0x20,
/// <summary>Disable distributed link tracking. By default, distributed link tracking tracks
/// removable media across multiple devices based on the volume name. It also uses the
/// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
/// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>
SLR_NOLINKINFO = 0x40,
/// <summary>Call the Microsoft Windows Installer</summary>
SLR_INVOKE_MSI = 0x80
}
/// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>
[ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
interface IShellLinkW
{
/// <summary>Retrieves the path and file name of a Shell link object</summary>
void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);
/// <summary>Retrieves the list of item identifiers for a Shell link object</summary>
void GetIDList(out IntPtr ppidl);
/// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>
void SetIDList(IntPtr pidl);
/// <summary>Retrieves the description string for a Shell link object</summary>
void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
/// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
/// <summary>Retrieves the name of the working directory for a Shell link object</summary>
void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
/// <summary>Sets the name of the working directory for a Shell link object</summary>
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
/// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>
void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
/// <summary>Sets the command-line arguments for a Shell link object</summary>
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
/// <summary>Retrieves the hot key for a Shell link object</summary>
void GetHotkey(out short pwHotkey);
/// <summary>Sets a hot key for a Shell link object</summary>
void SetHotkey(short wHotkey);
/// <summary>Retrieves the show command for a Shell link object</summary>
void GetShowCmd(out int piShowCmd);
/// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>
void SetShowCmd(int iShowCmd);
/// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>
void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
int cchIconPath, out int piIcon);
/// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
/// <summary>Sets the relative path to the Shell link object</summary>
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
/// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>
void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
/// <summary>Sets the path and file name of a Shell link object</summary>
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
}
[ComImport, Guid("0000010c-0000-0000-c000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPersist
{
[PreserveSig]
void GetClassID(out Guid pClassID);
}
[ComImport, Guid("0000010b-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPersistFile : IPersist
{
new void GetClassID(out Guid pClassID);
[PreserveSig]
int IsDirty();
[PreserveSig]
void Load([In, MarshalAs(UnmanagedType.LPWStr)]
string pszFileName, uint dwMode);
[PreserveSig]
void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
[In, MarshalAs(UnmanagedType.Bool)] bool fRemember);
[PreserveSig]
void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName);
[PreserveSig]
void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);
}
const uint STGM_READ = 0;
const int MAX_PATH = 260;
// CLSID_ShellLink from ShlGuid.h
[
ComImport(),
Guid("00021401-0000-0000-C000-000000000046")
]
public class ShellLink
{
}
#endregion
public static string ResolveShortcut(string filename)
{
ShellLink link = new ShellLink();
((IPersistFile)link).Load(filename, STGM_READ);
// TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
// ((IShellLinkW)link).Resolve(hwnd, 0)
StringBuilder sb = new StringBuilder(MAX_PATH);
WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
return sb.ToString();
}
``` |
139,012 | <p>Does anyone know how I can achieve the following effect in OpenGL:</p>
<ul>
<li>Change the brightness of the rendered scene</li>
<li>Or implementing a Gamma setting in OpenGL</li>
</ul>
<p>I have tried by changing the ambient parameter of the light and the type of light (directional and omnidirectional) but the result was not uniform. TIA.</p>
<p>Thanks for your help, some additional information:
* I can't use any windows specifics API.
* The gamma setting should not affect the whole window as I must have different gamma for different views.</p>
| [
{
"answer_id": 139038,
"author": "Harald Scheirich",
"author_id": 22080,
"author_profile": "https://Stackoverflow.com/users/22080",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.gamedev.net/community/forums/topic.asp?topic_id=435400\" rel=\"nofollow noreferrer\">http://www.gamedev.net/community/forums/topic.asp?topic_id=435400</a> might be an answer to your question otherwise you could probably implement a gamma correction as a pixel shader</p>\n"
},
{
"answer_id": 139054,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>On win32 you can use SetDeviceGammaRamp to adjust the overall brightness / gamma. However, this affects the entire display so it's not a good idea unless your app is fullscreen.</p>\n\n<p>The portable alternative is to either draw the entire scene brighter or dimmer (which is a hassle), or to slap a fullscreen alpha-blended quad over the whole scene to brighten or darken it as desired. Neither of these approaches can affect the gamma-curve, only the overall brightness; to adjust the gamma you need grab the entire scene into a texture and then render it back to the screen via a pixel-shader that runs each texel through a gamma function.</p>\n\n<p>Ok, having read the updated question, what you need is a quad with blending set up to darken or brighten everything underneath it. Eg.</p>\n\n<pre><code>if( brightness > 1 )\n{\n glBlendFunc( GL_DEST_COLOR, GL_ONE );\n glColor3f( brightness-1, brightness-1, brightness-1 );\n}\nelse\n{\n glBlendFunc( GL_ZERO, GL_SRC_COLOR );\n glColor3f( brightness, brightness, brightness );\n}\nglEnable( GL_BLEND );\n\ndraw_quad();\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18564/"
]
| Does anyone know how I can achieve the following effect in OpenGL:
* Change the brightness of the rendered scene
* Or implementing a Gamma setting in OpenGL
I have tried by changing the ambient parameter of the light and the type of light (directional and omnidirectional) but the result was not uniform. TIA.
Thanks for your help, some additional information:
\* I can't use any windows specifics API.
\* The gamma setting should not affect the whole window as I must have different gamma for different views. | On win32 you can use SetDeviceGammaRamp to adjust the overall brightness / gamma. However, this affects the entire display so it's not a good idea unless your app is fullscreen.
The portable alternative is to either draw the entire scene brighter or dimmer (which is a hassle), or to slap a fullscreen alpha-blended quad over the whole scene to brighten or darken it as desired. Neither of these approaches can affect the gamma-curve, only the overall brightness; to adjust the gamma you need grab the entire scene into a texture and then render it back to the screen via a pixel-shader that runs each texel through a gamma function.
Ok, having read the updated question, what you need is a quad with blending set up to darken or brighten everything underneath it. Eg.
```
if( brightness > 1 )
{
glBlendFunc( GL_DEST_COLOR, GL_ONE );
glColor3f( brightness-1, brightness-1, brightness-1 );
}
else
{
glBlendFunc( GL_ZERO, GL_SRC_COLOR );
glColor3f( brightness, brightness, brightness );
}
glEnable( GL_BLEND );
draw_quad();
``` |
139,015 | <p>I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:</p>
<pre><code>my @search_results = `grep -i -l \"$string\" *.pdf`;
</code></pre>
<p>where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.</p>
<p>What can I do that's easiest?</p>
<p>Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.</p>
<p>Final solution using Adam Bellaire's suggestion below:</p>
<pre><code>@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
</code></pre>
| [
{
"answer_id": 139077,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 4,
"selected": true,
"text": "<p>The PerlMonks thread <a href=\"http://www.perlmonks.org/?node_id=582868\" rel=\"noreferrer\">here</a> talks about this problem.</p>\n\n<p>It seems that for your situation, it might be simplest to get <strong>pdftotext</strong> (the command line tool), then you can do something like:</p>\n\n<pre><code>my @search_results = `pdftotext myfile.pdf - | grep -i -l \\\"$string\\\"`;\n</code></pre>\n"
},
{
"answer_id": 139130,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I second Adam Bellaire solution. I used pdftotext utility to create full-text index of my ebook library. It's somewhat slow but does its job. As for full-text, try PLucene or KinoSearch to store full-text index.</p>\n"
},
{
"answer_id": 139255,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to look at <a href=\"http://search.cpan.org/perldoc?PDF::Core\" rel=\"nofollow noreferrer\">PDF::Core</a>.</p>\n"
},
{
"answer_id": 139432,
"author": "mintywalker",
"author_id": 22682,
"author_profile": "https://Stackoverflow.com/users/22682",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest fulltext index/seach I've used is mysql. You just insert into the table with the appropriate index on it. You need to spend some time working out the relative weightings for fields (a match in the title might score higher than a match in the body), but this is all possible, albeit with some hairy sql.</p>\n\n<p>Plucene is deprecated (there hasn't been any active work on it in the last two years afaik) in favour of KinoSearch. KinoSearch grew, in part, out of understanding the architectural limitations of Plucene.</p>\n\n<p>If you have ~300 pdfs, then once you've extracted the text from the PDF (assuming the PDF has text and not just images of text ;) and depending on your query volumes you may find grep is sufficient. </p>\n\n<p>However, I'd strongly suggest the mysql/kinosearch route as they have covered a lot of ground (stemming, stopwords, term weighting, token parsing) that you don't benefit from getting bogged down with.</p>\n\n<p>KinoSearch is probably faster than the mysql route, but the mysql route gives you more widely used standard software/tools/developer-experience. And you get the ability to use the power of sql to augement your freetext search queries.</p>\n\n<p>So unless you're talking HUGE data-sets and insane query volumes, my money would be on mysql.</p>\n"
},
{
"answer_id": 151907,
"author": "Chris Dolan",
"author_id": 14783,
"author_profile": "https://Stackoverflow.com/users/14783",
"pm_score": 2,
"selected": false,
"text": "<p>My library, <a href=\"http://search.cpan.org/dist/CAM-PDF/\" rel=\"nofollow noreferrer\">CAM::PDF</a>, has support for extracting text, but it's an inherently hard problem given the graphical orientation of PDF syntax. So, the output is sometimes gibberish. CAM::PDF bundles a <a href=\"http://search.cpan.org/dist/CAM-PDF/bin/getpdftext.pl\" rel=\"nofollow noreferrer\">getpdftext.pl</a> program, or you can invoke the functionality like so:</p>\n\n<pre><code>my $doc = CAM::PDF->new($filename) || die \"$CAM::PDF::errstr\\n\";\nfor my $pagenum (1 .. $doc->numPages()) {\n my $text = $doc->getPageText($pagenum);\n print $text;\n}\n</code></pre>\n"
},
{
"answer_id": 162992,
"author": "jm4",
"author_id": 20441,
"author_profile": "https://Stackoverflow.com/users/20441",
"pm_score": 0,
"selected": false,
"text": "<p>You could try Lucene (the Perl port is called Plucene). The searches are incredibly fast and I know that PDFBox already knows how to index PDF files with Lucene. PDFBox is Java, but chances are there is something very similar somewhere in CPAN. Even if you can't find something that already adds PDF files to a Lucene index it shouldn't be more than a few lines of code to do it yourself. Lucene will give you quite a few more searching options than simply looking for a string in a file.</p>\n\n<p>There's also a very quick and dirty way. Text in a PDF file is actually stored as plain text. If you open a PDF in a text editor or use 'strings' you can see the text in there. The binary junk is usually embedded fonts, images, etc.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
]
| I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | The PerlMonks thread [here](http://www.perlmonks.org/?node_id=582868) talks about this problem.
It seems that for your situation, it might be simplest to get **pdftotext** (the command line tool), then you can do something like:
```
my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`;
``` |
139,046 | <p>I need to write code that picks up PGP-encrypted files from an FTP location and processes them. The files will be encrypted with my public key (not that I have one yet). Obviously, I need a PGP library that I can use from within Microsoft Access. Can you recommend one that is easy to use? </p>
<p>I'm looking for something that doesn't require a huge amount of PKI knowledge. Ideally, something that will easily generate the one-off private/public key pair, and then have a simple routine for decryption.</p>
| [
{
"answer_id": 139104,
"author": "Birger",
"author_id": 11485,
"author_profile": "https://Stackoverflow.com/users/11485",
"pm_score": 1,
"selected": false,
"text": "<p>I would look for a command line encrypter / decrypter and just call the exe from within your Access application, with the right parameters.</p>\n\n<p>There is no PGP encrypter / decrypter in VBA that I know of.</p>\n"
},
{
"answer_id": 139141,
"author": "cleg",
"author_id": 29503,
"author_profile": "https://Stackoverflow.com/users/29503",
"pm_score": 1,
"selected": false,
"text": "<p>I am not familiar with VBA for Access, but i think that the best solution (perhaps easiest) would be run external command-line PGP utility.</p>\n"
},
{
"answer_id": 139147,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 2,
"selected": false,
"text": "<p>PGP has a commandline option for decrypting files. </p>\n\n<p>We have a batchfile that does the decryption, passing in the filename to be decrypted:</p>\n\n<p>Batch file:</p>\n\n<pre><code>\"C:\\Program Files\\Network Associates\\PGPNT\\pgp\" +FORCE %1 -z *password* \n</code></pre>\n\n<p>We than call that from a VBS:</p>\n\n<pre><code> Command = \"decrypt.bat \"\"\" & FolderName & FileName & \"\"\"\"\n\n 'Executes the command script.\n Set objShell = WScript.CreateObject (\"WSCript.shell\")\n Command = \"cmd /c \" & Command\n objShell.run Command, 1, True\n</code></pre>\n\n<p>Hope that points you in a useful direction.</p>\n"
},
{
"answer_id": 139204,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 1,
"selected": false,
"text": "<p>There is a DLL you can call directly from your VBA application without having to span an external program: <a href=\"http://www.easybyte.com/products/cryptocx.html\" rel=\"nofollow noreferrer\">CryptoCX</a>. PGP has also a DLL you can call.</p>\n"
},
{
"answer_id": 139500,
"author": "hurcane",
"author_id": 21363,
"author_profile": "https://Stackoverflow.com/users/21363",
"pm_score": 4,
"selected": true,
"text": "<p>A command line solution is good. If your database is an internal application, not to be redistributed, I can recommend <a href=\"http://www.gnupg.org\" rel=\"noreferrer\">Gnu Privacy Guard</a>. This command-line based tool will allow you to do anything that you need to with regard to the OpenPGP standard.</p>\n\n<p>Within Access, you can use the Shell() command in a Macro like this:</p>\n\n<pre><code>Public Sub DecryptFile(ByVal FileName As String)\n Dim strCommand As String\n strCommand = \"C:\\Program Files\\GNU\\GnuPG\\gpg.exe \" _\n & \"--batch --passphrase \"\"My PassPhrase that I used\"\"\" & FileName\n Shell strCommand, vbNormalFocus\nEnd Sub\n</code></pre>\n\n<p>This will run the command-line tool to decrypt the file. This syntax uses a plaintext version of your secret passphrase. This is not the most secure solution, but is acceptable if your database is internal and only used by trusted personnel. GnuPG supports other techniques to secure the passphrase.</p>\n"
},
{
"answer_id": 382528,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 2,
"selected": false,
"text": "<p>Stu... I once had to write a \"Secure SMTP\" server in Java... The easiest, and quickest way to do this is to download and/or purchase PGP. They have an SDK that you can use to access in anything you want.</p>\n\n<p>I'd have to go back and see if I had to write a COM wrapper, or if they already had one. (I wrote this SMTP server about 10 years ago). Anyways, don't get discouraged. About 5 years ago, I wrote an entire PGP based application (based on the openPGP RFC) in C++, but the catch was, I was <em>NOT</em> allowed to use any existing libraries. So I had to write all that stuff myself. And, I used GPG, OpenPGP, and PGP for testing, etc....</p>\n\n<p>So, I could even provide help for you on how to decode this stuff in VBA. It's not impossible, (it may be slow as hell, but not impossible), and I'm NOT one to \"shell out and run cmdline stuff to do work like this for you, as it will open you up to some SERIOUS security risks, as hurcane's suggestion (for example) will cause your passphrase to be displayed to tools like ProcExp). The first step is learning how PKE works, etc. Then, the steps you need to do to get what you want.</p>\n\n<p>This is something I'd be interested in helping with since I'm always one to write code that everyone says can't be done. :) Plus, I own the source code of the app I wrote, because of of mergers, closures, etc...</p>\n\n<p>It was originally written for the Oil and Gas industry, so I know it's secure. That's not to say I don't have <em>ANY</em> security flaws in the code, but I think it's stable. I know I have an issue with my Chinese Remainder Threory code.. For some reason when I use that short-cut, I can't decode the data correctly, but if I use the RSA \"long way\" it works...</p>\n\n<p>Now, this application was never fully finished, so I don't support things like DSA Key-pairs, but I do support RSA key pairs, with SHA1, MD5, using IDEA, AES, (I <em>THINK</em> my 3DES code does not work correctly, but I may have fixed that since). I didn't implement compression yet, etc... But, I'd love a reason to go back and work on this code again.</p>\n\n<p>I /COULD/ make you a COM object that you could call from VBA passing the original Base64 data in, along with the Base64 key data, (or a pointer to a key file on disk), and a passpsshrase to decode files....</p>\n\n<p>Think about it... Let me know..</p>\n\n<p>Over the years, I have collected vbScript code for doing things like MD5, SHA1, IDEA, and other crypto routines, but I didn't write them. Hell, you could probably just interface with Microsoft's CryptoAPI, and break each action down to it's core parts and still get it to work. (You will not find a Micosoft CryptoAPI call like \"DecryptPGP()\"... It'd all have to be done in chunks).</p>\n\n<p>Lemme know if I can help.</p>\n"
},
{
"answer_id": 383100,
"author": "Eugene Mayevski 'Callback",
"author_id": 47961,
"author_profile": "https://Stackoverflow.com/users/47961",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://www.eldos.com/sbbdev/activex-pgp.php\" rel=\"nofollow noreferrer\">OpenPGPBlackbox (ActiveX edition)</a> for this</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21379/"
]
| I need to write code that picks up PGP-encrypted files from an FTP location and processes them. The files will be encrypted with my public key (not that I have one yet). Obviously, I need a PGP library that I can use from within Microsoft Access. Can you recommend one that is easy to use?
I'm looking for something that doesn't require a huge amount of PKI knowledge. Ideally, something that will easily generate the one-off private/public key pair, and then have a simple routine for decryption. | A command line solution is good. If your database is an internal application, not to be redistributed, I can recommend [Gnu Privacy Guard](http://www.gnupg.org). This command-line based tool will allow you to do anything that you need to with regard to the OpenPGP standard.
Within Access, you can use the Shell() command in a Macro like this:
```
Public Sub DecryptFile(ByVal FileName As String)
Dim strCommand As String
strCommand = "C:\Program Files\GNU\GnuPG\gpg.exe " _
& "--batch --passphrase ""My PassPhrase that I used""" & FileName
Shell strCommand, vbNormalFocus
End Sub
```
This will run the command-line tool to decrypt the file. This syntax uses a plaintext version of your secret passphrase. This is not the most secure solution, but is acceptable if your database is internal and only used by trusted personnel. GnuPG supports other techniques to secure the passphrase. |
139,055 | <p>I'm using Subversive plugin in Ganymede, but after today's update it stopped working - it just doesn't see any valid svn connectors (I've already been using 1.2.0 dev version of SVNKit, instead of a stable one, because Subversive / Ganymede could not handle it; now it can't handle even the dev one). Any ideas how to make it work? Are subversive guys releasing a new version of their plugin / connectors soon?</p>
| [
{
"answer_id": 139160,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using <a href=\"http://subclipse.tigris.org/\" rel=\"nofollow noreferrer\">Subclipse</a> in Ganymede successfully, maybe could you switch? I do recall having problems with SvnKit also, I'm using the JavaHL client.</p>\n"
},
{
"answer_id": 143379,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 4,
"selected": true,
"text": "<p>I had a similar problem right after the update. It turned out that I had been getting the connectors (the base connector and both the SVNKit and JavaHL connectors) from the Polarion site that had \"ganymede\" in the URL. Instead, I should have been using the general URL.</p>\n\n<p>Checking my current configuration, you should be using this update URL:</p>\n\n<pre><code>http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/\n</code></pre>\n\n<p>The one I had been using, that should be deprecated if you are using it, is:</p>\n\n<pre><code>http://www.polarion.org/projects/subversive/download/eclipse/2.0/ganymede-site/\n</code></pre>\n\n<p>Note the difference. Once I changed that, I was able to download the 2.0.3 versions of the connectors, and Subversion again worked for me.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688/"
]
| I'm using Subversive plugin in Ganymede, but after today's update it stopped working - it just doesn't see any valid svn connectors (I've already been using 1.2.0 dev version of SVNKit, instead of a stable one, because Subversive / Ganymede could not handle it; now it can't handle even the dev one). Any ideas how to make it work? Are subversive guys releasing a new version of their plugin / connectors soon? | I had a similar problem right after the update. It turned out that I had been getting the connectors (the base connector and both the SVNKit and JavaHL connectors) from the Polarion site that had "ganymede" in the URL. Instead, I should have been using the general URL.
Checking my current configuration, you should be using this update URL:
```
http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/
```
The one I had been using, that should be deprecated if you are using it, is:
```
http://www.polarion.org/projects/subversive/download/eclipse/2.0/ganymede-site/
```
Note the difference. Once I changed that, I was able to download the 2.0.3 versions of the connectors, and Subversion again worked for me. |
139,076 | <p>I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?</p>
<pre><code>String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
</code></pre>
<p>Note: My input is a <strong>String</strong>. My output is a <strong>String</strong>. </p>
<p>(Basic) mock result:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
</code></pre>
| [
{
"answer_id": 139096,
"author": "Lorenzo Boccaccia",
"author_id": 2273540,
"author_profile": "https://Stackoverflow.com/users/2273540",
"pm_score": 8,
"selected": false,
"text": "<pre class=\"lang-java prettyprint-override\"><code>Transformer transformer = TransformerFactory.newInstance().newTransformer();\ntransformer.setOutputProperty(OutputKeys.INDENT, "yes");\ntransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");\n// initialize StreamResult with File object to save to file\nStreamResult result = new StreamResult(new StringWriter());\nDOMSource source = new DOMSource(doc);\ntransformer.transform(source, result);\nString xmlString = result.getWriter().toString();\nSystem.out.println(xmlString);\n</code></pre>\n<p>Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.</p>\n"
},
{
"answer_id": 139333,
"author": "Kevin Hakanson",
"author_id": 22514,
"author_profile": "https://Stackoverflow.com/users/22514",
"pm_score": 4,
"selected": false,
"text": "<p>Since you are starting with a <code>String</code>, you need to covert to a <code>DOM</code> object (e.g. <code>Node</code>) before you can use the <code>Transformer</code>. However, if you know your XML string is valid, and you don't want to incur the memory overhead of parsing a string into a DOM, then running a transform over the DOM to get a string back - you could just do some old fashioned character by character parsing. Insert a newline and spaces after every <code></...></code> characters, keep and indent counter (to determine the number of spaces) that you increment for every <code><...></code> and decrement for every <code></...></code> you see.</p>\n\n<p>Disclaimer - I did a cut/paste/text edit of the functions below, so they may not compile as is.</p>\n\n<pre><code>public static final Element createDOM(String strXML) \n throws ParserConfigurationException, SAXException, IOException {\n\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setValidating(true);\n DocumentBuilder db = dbf.newDocumentBuilder();\n InputSource sourceXML = new InputSource(new StringReader(strXML));\n Document xmlDoc = db.parse(sourceXML);\n Element e = xmlDoc.getDocumentElement();\n e.normalize();\n return e;\n}\n\npublic static final void prettyPrint(Node xml, OutputStream out)\n throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {\n Transformer tf = TransformerFactory.newInstance().newTransformer();\n tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n tf.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n tf.setOutputProperty(OutputKeys.INDENT, \"yes\");\n tf.transform(new DOMSource(xml), new StreamResult(out));\n}\n</code></pre>\n"
},
{
"answer_id": 139426,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 7,
"selected": false,
"text": "<p>Here's an answer to my own question. I combined the answers from the various results to write a class that pretty prints XML.</p>\n\n<p>No guarantees on how it responds with invalid XML or large documents.</p>\n\n<pre><code>package ecb.sdw.pretty;\n\nimport org.apache.xml.serialize.OutputFormat;\nimport org.apache.xml.serialize.XMLSerializer;\nimport org.w3c.dom.Document;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.io.Writer;\n\n/**\n * Pretty-prints xml, supplied as a string.\n * <p/>\n * eg.\n * <code>\n * String formattedXml = new XmlFormatter().format(\"<tag><nested>hello</nested></tag>\");\n * </code>\n */\npublic class XmlFormatter {\n\n public XmlFormatter() {\n }\n\n public String format(String unformattedXml) {\n try {\n final Document document = parseXmlFile(unformattedXml);\n\n OutputFormat format = new OutputFormat(document);\n format.setLineWidth(65);\n format.setIndenting(true);\n format.setIndent(2);\n Writer out = new StringWriter();\n XMLSerializer serializer = new XMLSerializer(out, format);\n serializer.serialize(document);\n\n return out.toString();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n private Document parseXmlFile(String in) {\n try {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n InputSource is = new InputSource(new StringReader(in));\n return db.parse(is);\n } catch (ParserConfigurationException e) {\n throw new RuntimeException(e);\n } catch (SAXException e) {\n throw new RuntimeException(e);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void main(String[] args) {\n String unformattedXml =\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><QueryMessage\\n\" +\n \" xmlns=\\\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\\\"\\n\" +\n \" xmlns:query=\\\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\\\">\\n\" +\n \" <Query>\\n\" +\n \" <query:CategorySchemeWhere>\\n\" +\n \" \\t\\t\\t\\t\\t <query:AgencyID>ECB\\n\\n\\n\\n</query:AgencyID>\\n\" +\n \" </query:CategorySchemeWhere>\\n\" +\n \" </Query>\\n\\n\\n\\n\\n\" +\n \"</QueryMessage>\";\n\n System.out.println(new XmlFormatter().format(unformattedXml));\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 139929,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 1,
"selected": false,
"text": "<p>There is a very nice command line XML utility called xmlstarlet(<a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">http://xmlstar.sourceforge.net/</a>) that can do a lot of things which a lot of people use.</p>\n<p>You could execute this program programmatically using Runtime.exec and then read in the formatted output file. It has more options and better error reporting than a few lines of Java code can provide.</p>\n<p>download xmlstarlet : <a href=\"http://sourceforge.net/project/showfiles.php?group_id=66612&package_id=64589\" rel=\"nofollow noreferrer\">http://sourceforge.net/project/showfiles.php?group_id=66612&package_id=64589</a></p>\n"
},
{
"answer_id": 260314,
"author": "mlo55",
"author_id": 32993,
"author_profile": "https://Stackoverflow.com/users/32993",
"pm_score": 5,
"selected": false,
"text": "<p>I've pretty printed in the past using the <strong>org.dom4j.io.OutputFormat.createPrettyPrint()</strong> method</p>\n\n<pre><code>public String prettyPrint(final String xml){ \n\n if (StringUtils.isBlank(xml)) {\n throw new RuntimeException(\"xml was null or blank in prettyPrint()\");\n }\n\n final StringWriter sw;\n\n try {\n final OutputFormat format = OutputFormat.createPrettyPrint();\n final org.dom4j.Document document = DocumentHelper.parseText(xml);\n sw = new StringWriter();\n final XMLWriter writer = new XMLWriter(sw, format);\n writer.write(document);\n }\n catch (Exception e) {\n throw new RuntimeException(\"Error pretty printing xml:\\n\" + xml, e);\n }\n return sw.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 592146,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 3,
"selected": false,
"text": "<p>Regarding comment that \"you must first build a DOM tree\": No, you need not and should not do that.</p>\n\n<p>Instead, create a StreamSource (new StreamSource(new StringReader(str)), and feed that to the identity transformer mentioned. That'll use SAX parser, and result will be much faster.\nBuilding an intermediate tree is pure overhead for this case.\nOtherwise the top-ranked answer is good.</p>\n"
},
{
"answer_id": 962225,
"author": "Jonik",
"author_id": 56285,
"author_profile": "https://Stackoverflow.com/users/56285",
"pm_score": 4,
"selected": false,
"text": "<p>If using a 3rd party XML library is ok, you can get away with something significantly simpler than what the currently <a href=\"https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java/139096#139096\">highest-voted</a> <a href=\"https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java/139333#139333\">answers</a> suggest. </p>\n\n<p>It was stated that both input and output should be Strings, so here's a utility method that does just that, implemented with the <strong><a href=\"http://xom.nu\" rel=\"nofollow noreferrer\">XOM</a></strong> library:</p>\n\n<pre><code>import nu.xom.*;\nimport java.io.*;\n\n[...]\n\npublic static String format(String xml) throws ParsingException, IOException {\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n Serializer serializer = new Serializer(out);\n serializer.setIndent(4); // or whatever you like\n serializer.write(new Builder().build(xml, \"\"));\n return out.toString(\"UTF-8\");\n}\n</code></pre>\n\n<p>I tested that it works, and the results <em>do not</em> depend on your JRE version or anything like that. To see how to customise the output format to your liking, take a look at the <a href=\"http://xom.nu/apidocs/nu/xom/Serializer.html\" rel=\"nofollow noreferrer\"><code>Serializer</code></a> API.</p>\n\n<p>This actually came out longer than I thought - some extra lines were needed because <code>Serializer</code> wants an <code>OutputStream</code> to write to. But note that there's very little code for actual XML twiddling here.</p>\n\n<p>(This answer is part of my evaluation of XOM, which was <a href=\"https://stackoverflow.com/questions/831865/what-java-xml-library-do-you-recommend-to-replace-dom4j/833241#833241\">suggested</a> as one option in my <a href=\"https://stackoverflow.com/questions/831865/what-java-xml-library-do-you-recommend-to-replace-dom4j\">question about the best Java XML library</a> to replace dom4j. For the record, with dom4j you could achieve this with similar ease using <a href=\"http://dom4j.org/dom4j-1.6.1/apidocs/org/dom4j/io/XMLWriter.html\" rel=\"nofollow noreferrer\"><code>XMLWriter</code></a> and <a href=\"http://dom4j.org/dom4j-1.6.1/apidocs/org/dom4j/io/OutputFormat.html\" rel=\"nofollow noreferrer\"><code>OutputFormat</code></a>. <strong>Edit</strong>: ...as demonstrated in <a href=\"https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java/260314#260314\">mlo55's answer</a>.)</p>\n"
},
{
"answer_id": 1264912,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/1264849/pretty-printing-output-from-javax-xml-transform-transformer-with-only-standard-ja/1264872#1264872\">a simpler solution based on this answer</a>:</p>\n<pre><code>public static String prettyFormat(String input, int indent) {\n try {\n Source xmlInput = new StreamSource(new StringReader(input));\n StringWriter stringWriter = new StringWriter();\n StreamResult xmlOutput = new StreamResult(stringWriter);\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n transformerFactory.setAttribute("indent-number", indent);\n transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");\n transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");\n Transformer transformer = transformerFactory.newTransformer(); \n transformer.setOutputProperty(OutputKeys.INDENT, "yes");\n transformer.transform(xmlInput, xmlOutput);\n return xmlOutput.getWriter().toString();\n } catch (Exception e) {\n throw new RuntimeException(e); // simple exception handling, please review it\n }\n}\n\npublic static String prettyFormat(String input) {\n return prettyFormat(input, 2);\n}\n</code></pre>\n<p>testcase:</p>\n<pre><code>prettyFormat("<root><child>aaa</child><child/></root>");\n</code></pre>\n<p>returns:</p>\n<pre><code><?xml version="1.0" encoding="UTF-8"?>\n<root>\n <child>aaa</child>\n <child/>\n</root>\n</code></pre>\n<p>//Ignore: Original edit just needs missing s in the Class name in code. redundant six characters added to get over 6 characters validation on SO</p>\n"
},
{
"answer_id": 1948577,
"author": "Sandeep Phukan",
"author_id": 237114,
"author_profile": "https://Stackoverflow.com/users/237114",
"pm_score": 4,
"selected": false,
"text": "<p>Hmmm... faced something like this and it is a known bug ... \njust add this OutputProperty ..</p>\n\n<pre><code>transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, \"8\");\n</code></pre>\n\n<p>Hope this helps ...</p>\n"
},
{
"answer_id": 2599074,
"author": "Mark Pope",
"author_id": 237733,
"author_profile": "https://Stackoverflow.com/users/237733",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a way of doing it using <a href=\"http://www.dom4j.org/dom4j-1.6.1/\" rel=\"noreferrer\">dom4j</a>:</p>\n\n<p>Imports:</p>\n\n<pre><code>import org.dom4j.Document; \nimport org.dom4j.DocumentHelper; \nimport org.dom4j.io.OutputFormat; \nimport org.dom4j.io.XMLWriter;\n</code></pre>\n\n<p>Code: </p>\n\n<pre><code>String xml = \"<your xml='here'/>\"; \nDocument doc = DocumentHelper.parseText(xml); \nStringWriter sw = new StringWriter(); \nOutputFormat format = OutputFormat.createPrettyPrint(); \nXMLWriter xw = new XMLWriter(sw, format); \nxw.write(doc); \nString result = sw.toString();\n</code></pre>\n"
},
{
"answer_id": 2920419,
"author": "David Easley",
"author_id": 65555,
"author_profile": "https://Stackoverflow.com/users/65555",
"pm_score": 4,
"selected": false,
"text": "<p>Kevin Hakanson said:\n\"However, if you know your XML string is valid, and you don't want to incur the memory overhead of parsing a string into a DOM, then running a transform over the DOM to get a string back - you could just do some old fashioned character by character parsing. Insert a newline and spaces after every characters, keep and indent counter (to determine the number of spaces) that you increment for every <...> and decrement for every you see.\"</p>\n\n<p>Agreed. Such an approach is much faster and has far fewer dependencies.</p>\n\n<p>Example solution:</p>\n\n<pre><code>/**\n * XML utils, including formatting.\n */\npublic class XmlUtils\n{\n private static XmlFormatter formatter = new XmlFormatter(2, 80);\n\n public static String formatXml(String s)\n {\n return formatter.format(s, 0);\n }\n\n public static String formatXml(String s, int initialIndent)\n {\n return formatter.format(s, initialIndent);\n }\n\n private static class XmlFormatter\n {\n private int indentNumChars;\n private int lineLength;\n private boolean singleLine;\n\n public XmlFormatter(int indentNumChars, int lineLength)\n {\n this.indentNumChars = indentNumChars;\n this.lineLength = lineLength;\n }\n\n public synchronized String format(String s, int initialIndent)\n {\n int indent = initialIndent;\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < s.length(); i++)\n {\n char currentChar = s.charAt(i);\n if (currentChar == '<')\n {\n char nextChar = s.charAt(i + 1);\n if (nextChar == '/')\n indent -= indentNumChars;\n if (!singleLine) // Don't indent before closing element if we're creating opening and closing elements on a single line.\n sb.append(buildWhitespace(indent));\n if (nextChar != '?' && nextChar != '!' && nextChar != '/')\n indent += indentNumChars;\n singleLine = false; // Reset flag.\n }\n sb.append(currentChar);\n if (currentChar == '>')\n {\n if (s.charAt(i - 1) == '/')\n {\n indent -= indentNumChars;\n sb.append(\"\\n\");\n }\n else\n {\n int nextStartElementPos = s.indexOf('<', i);\n if (nextStartElementPos > i + 1)\n {\n String textBetweenElements = s.substring(i + 1, nextStartElementPos);\n\n // If the space between elements is solely newlines, let them through to preserve additional newlines in source document.\n if (textBetweenElements.replaceAll(\"\\n\", \"\").length() == 0)\n {\n sb.append(textBetweenElements + \"\\n\");\n }\n // Put tags and text on a single line if the text is short.\n else if (textBetweenElements.length() <= lineLength * 0.5)\n {\n sb.append(textBetweenElements);\n singleLine = true;\n }\n // For larger amounts of text, wrap lines to a maximum line length.\n else\n {\n sb.append(\"\\n\" + lineWrap(textBetweenElements, lineLength, indent, null) + \"\\n\");\n }\n i = nextStartElementPos - 1;\n }\n else\n {\n sb.append(\"\\n\");\n }\n }\n }\n }\n return sb.toString();\n }\n }\n\n private static String buildWhitespace(int numChars)\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < numChars; i++)\n sb.append(\" \");\n return sb.toString();\n }\n\n /**\n * Wraps the supplied text to the specified line length.\n * @lineLength the maximum length of each line in the returned string (not including indent if specified).\n * @indent optional number of whitespace characters to prepend to each line before the text.\n * @linePrefix optional string to append to the indent (before the text).\n * @returns the supplied text wrapped so that no line exceeds the specified line length + indent, optionally with\n * indent and prefix applied to each line.\n */\n private static String lineWrap(String s, int lineLength, Integer indent, String linePrefix)\n {\n if (s == null)\n return null;\n\n StringBuilder sb = new StringBuilder();\n int lineStartPos = 0;\n int lineEndPos;\n boolean firstLine = true;\n while(lineStartPos < s.length())\n {\n if (!firstLine)\n sb.append(\"\\n\");\n else\n firstLine = false;\n\n if (lineStartPos + lineLength > s.length())\n lineEndPos = s.length() - 1;\n else\n {\n lineEndPos = lineStartPos + lineLength - 1;\n while (lineEndPos > lineStartPos && (s.charAt(lineEndPos) != ' ' && s.charAt(lineEndPos) != '\\t'))\n lineEndPos--;\n }\n sb.append(buildWhitespace(indent));\n if (linePrefix != null)\n sb.append(linePrefix);\n\n sb.append(s.substring(lineStartPos, lineEndPos + 1));\n lineStartPos = lineEndPos + 1;\n }\n return sb.toString();\n }\n\n // other utils removed for brevity\n}\n</code></pre>\n"
},
{
"answer_id": 3026021,
"author": "Kristoffer Lindvall",
"author_id": 299075,
"author_profile": "https://Stackoverflow.com/users/299075",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem and I'm having great success with JTidy (<a href=\"http://jtidy.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">http://jtidy.sourceforge.net/index.html</a>)</p>\n\n<p>Example:</p>\n\n<pre><code>Tidy t = new Tidy();\nt.setIndentContent(true);\nDocument d = t.parseDOM(\n new ByteArrayInputStream(\"HTML goes here\", null);\n\nOutputStream out = new ByteArrayOutputStream();\nt.pprint(d, out);\nString html = out.toString();\n</code></pre>\n"
},
{
"answer_id": 4472580,
"author": "khylo",
"author_id": 249672,
"author_profile": "https://Stackoverflow.com/users/249672",
"pm_score": 6,
"selected": false,
"text": "<p>Just to note that top rated answer requires the use of xerces.</p>\n\n<p>If you don't want to add this external dependency then you can simply use the standard jdk libraries (which actually are built using xerces internally).</p>\n\n<p>N.B. There was a bug with jdk version 1.5 see <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446</a> but it is resolved now.,</p>\n\n<p>(Note if an error occurs this will return the original text)</p>\n\n<pre><code>package com.test;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.xml.sax.InputSource;\n\npublic class XmlTest {\n public static void main(String[] args) {\n XmlTest t = new XmlTest();\n System.out.println(t.formatXml(\"<a><b><c/><d>text D</d><e value='0'/></b></a>\"));\n }\n\n public String formatXml(String xml){\n try{\n Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();\n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n //serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n //serializer.setOutputProperty(\"{http://xml.customer.org/xslt}indent-amount\", \"2\");\n Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream()); \n serializer.transform(xmlSource, res);\n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n }catch(Exception e){\n //TODO log error\n return xml;\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 5227490,
"author": "Synesso",
"author_id": 45525,
"author_profile": "https://Stackoverflow.com/users/45525",
"pm_score": 3,
"selected": false,
"text": "<p>Using scala:</p>\n\n<pre><code>import xml._\nval xml = XML.loadString(\"<tag><nested>hello</nested></tag>\")\nval formatted = new PrettyPrinter(150, 2).format(xml)\nprintln(formatted)\n</code></pre>\n\n<p>You can do this in Java too, if you depend on the scala-library.jar. It looks like this:</p>\n\n<pre><code>import scala.xml.*;\n\npublic class FormatXML {\n public static void main(String[] args) {\n String unformattedXml = \"<tag><nested>hello</nested></tag>\";\n PrettyPrinter pp = new PrettyPrinter(150, 3);\n String formatted = pp.format(XML.loadString(unformattedXml), TopScope$.MODULE$);\n System.out.println(formatted);\n }\n}\n</code></pre>\n\n<p>The <code>PrettyPrinter</code> object is constructed with two ints, the first being max line length and the second being the indentation step.</p>\n"
},
{
"answer_id": 7714473,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 3,
"selected": false,
"text": "<p>Just for future reference, here's a solution that worked for me (thanks to a comment that @George Hawkins posted in one of the answers):</p>\n\n<pre><code>DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\nDOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\nLSSerializer writer = impl.createLSSerializer();\nwriter.getDomConfig().setParameter(\"format-pretty-print\", Boolean.TRUE);\nLSOutput output = impl.createLSOutput();\nByteArrayOutputStream out = new ByteArrayOutputStream();\noutput.setByteStream(out);\nwriter.write(document, output);\nString xmlStr = new String(out.toByteArray());\n</code></pre>\n"
},
{
"answer_id": 11351356,
"author": "JFK",
"author_id": 851774,
"author_profile": "https://Stackoverflow.com/users/851774",
"pm_score": 1,
"selected": false,
"text": "<p>I have found that in Java 1.6.0_32 the normal method to pretty print an XML <strong><em>string</em></strong> (using a Transformer with a null or identity xslt) does not behave as I would like if tags are merely separated by whitespace, as opposed to having no separating text. I tried using <code><xsl:strip-space elements=\"*\"/></code> in my template to no avail. The simplest solution I found was to strip the space the way I wanted using a SAXSource and XML filter. Since my solution was for logging I also extended this to work with incomplete XML fragments. Note the normal method seems to work fine if you use a DOMSource but I did not want to use this because of the incompleteness and memory overhead. </p>\n\n<pre><code>public static class WhitespaceIgnoreFilter extends XMLFilterImpl\n{\n\n @Override\n public void ignorableWhitespace(char[] arg0,\n int arg1,\n int arg2) throws SAXException\n {\n //Ignore it then...\n }\n\n @Override\n public void characters( char[] ch,\n int start,\n int length) throws SAXException\n {\n if (!new String(ch, start, length).trim().equals(\"\")) \n super.characters(ch, start, length); \n }\n}\n\npublic static String prettyXML(String logMsg, boolean allowBadlyFormedFragments) throws SAXException, IOException, TransformerException\n {\n TransformerFactory transFactory = TransformerFactory.newInstance();\n transFactory.setAttribute(\"indent-number\", new Integer(2));\n Transformer transformer = transFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n StringWriter out = new StringWriter();\n XMLReader masterParser = SAXHelper.getSAXParser(true);\n XMLFilter parser = new WhitespaceIgnoreFilter();\n parser.setParent(masterParser);\n\n if(allowBadlyFormedFragments)\n {\n transformer.setErrorListener(new ErrorListener()\n {\n @Override\n public void warning(TransformerException exception) throws TransformerException\n {\n }\n\n @Override\n public void fatalError(TransformerException exception) throws TransformerException\n {\n }\n\n @Override\n public void error(TransformerException exception) throws TransformerException\n {\n }\n });\n }\n\n try\n {\n transformer.transform(new SAXSource(parser, new InputSource(new StringReader(logMsg))), new StreamResult(out));\n }\n catch (TransformerException e)\n {\n if(e.getCause() != null && e.getCause() instanceof SAXParseException)\n {\n if(!allowBadlyFormedFragments || !\"XML document structures must start and end within the same entity.\".equals(e.getCause().getMessage()))\n {\n throw e;\n }\n }\n else\n {\n throw e;\n }\n }\n out.flush();\n return out.toString();\n }\n</code></pre>\n"
},
{
"answer_id": 11519668,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 8,
"selected": true,
"text": "<p>Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.</p>\n\n<pre><code>import org.w3c.dom.Node;\nimport org.w3c.dom.bootstrap.DOMImplementationRegistry;\nimport org.w3c.dom.ls.DOMImplementationLS;\nimport org.w3c.dom.ls.LSSerializer;\nimport org.xml.sax.InputSource;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport java.io.StringReader;\n\n/**\n * Pretty-prints xml, supplied as a string.\n * <p/>\n * eg.\n * <code>\n * String formattedXml = new XmlFormatter().format(\"<tag><nested>hello</nested></tag>\");\n * </code>\n */\npublic class XmlFormatter {\n\n public String format(String xml) {\n\n try {\n final InputSource src = new InputSource(new StringReader(xml));\n final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();\n final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith(\"<?xml\"));\n\n //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,\"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl\");\n\n\n final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\n final LSSerializer writer = impl.createLSSerializer();\n\n writer.getDomConfig().setParameter(\"format-pretty-print\", Boolean.TRUE); // Set this to true if the output needs to be beautified.\n writer.getDomConfig().setParameter(\"xml-declaration\", keepDeclaration); // Set this to true if the declaration is needed to be outputted.\n\n return writer.writeToString(document);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void main(String[] args) {\n String unformattedXml =\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><QueryMessage\\n\" +\n \" xmlns=\\\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\\\"\\n\" +\n \" xmlns:query=\\\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\\\">\\n\" +\n \" <Query>\\n\" +\n \" <query:CategorySchemeWhere>\\n\" +\n \" \\t\\t\\t\\t\\t <query:AgencyID>ECB\\n\\n\\n\\n</query:AgencyID>\\n\" +\n \" </query:CategorySchemeWhere>\\n\" +\n \" </Query>\\n\\n\\n\\n\\n\" +\n \"</QueryMessage>\";\n\n System.out.println(new XmlFormatter().format(unformattedXml));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19236572,
"author": "max",
"author_id": 767434,
"author_profile": "https://Stackoverflow.com/users/767434",
"pm_score": 2,
"selected": false,
"text": "<p>For those searching for a quick and dirty solution - which doesn't need the XML to be 100% valid. e.g. in case of REST / SOAP logging (you never know what the others send ;-))</p>\n\n<p>I found and advanced a code snipped I found online which I think is still missing here as a valid possible approach: </p>\n\n<pre><code>public static String prettyPrintXMLAsString(String xmlString) {\n /* Remove new lines */\n final String LINE_BREAK = \"\\n\";\n xmlString = xmlString.replaceAll(LINE_BREAK, \"\");\n StringBuffer prettyPrintXml = new StringBuffer();\n /* Group the xml tags */\n Pattern pattern = Pattern.compile(\"(<[^/][^>]+>)?([^<]*)(</[^>]+>)?(<[^/][^>]+/>)?\");\n Matcher matcher = pattern.matcher(xmlString);\n int tabCount = 0;\n while (matcher.find()) {\n String str1 = (null == matcher.group(1) || \"null\".equals(matcher.group())) ? \"\" : matcher.group(1);\n String str2 = (null == matcher.group(2) || \"null\".equals(matcher.group())) ? \"\" : matcher.group(2);\n String str3 = (null == matcher.group(3) || \"null\".equals(matcher.group())) ? \"\" : matcher.group(3);\n String str4 = (null == matcher.group(4) || \"null\".equals(matcher.group())) ? \"\" : matcher.group(4);\n\n if (matcher.group() != null && !matcher.group().trim().equals(\"\")) {\n printTabs(tabCount, prettyPrintXml);\n if (!str1.equals(\"\") && str3.equals(\"\")) {\n ++tabCount;\n }\n if (str1.equals(\"\") && !str3.equals(\"\")) {\n --tabCount;\n prettyPrintXml.deleteCharAt(prettyPrintXml.length() - 1);\n }\n\n prettyPrintXml.append(str1);\n prettyPrintXml.append(str2);\n prettyPrintXml.append(str3);\n if (!str4.equals(\"\")) {\n prettyPrintXml.append(LINE_BREAK);\n printTabs(tabCount, prettyPrintXml);\n prettyPrintXml.append(str4);\n }\n prettyPrintXml.append(LINE_BREAK);\n }\n }\n return prettyPrintXml.toString();\n}\n\nprivate static void printTabs(int count, StringBuffer stringBuffer) {\n for (int i = 0; i < count; i++) {\n stringBuffer.append(\"\\t\");\n }\n}\n\npublic static void main(String[] args) {\n String x = new String(\n \"<soap:Envelope xmlns:soap=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>INVALID_MESSAGE</faultstring><detail><ns3:XcbSoapFault xmlns=\\\"\\\" xmlns:ns3=\\\"http://www.someapp.eu/xcb/types/xcb/v1\\\"><CauseCode>20007</CauseCode><CauseText>INVALID_MESSAGE</CauseText><DebugInfo>Problems creating SAAJ object model</DebugInfo></ns3:XcbSoapFault></detail></soap:Fault></soap:Body></soap:Envelope>\");\n System.out.println(prettyPrintXMLAsString(x));\n}\n</code></pre>\n\n<p>here is the output:</p>\n\n<pre><code><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <soap:Fault>\n <faultcode>soap:Client</faultcode>\n <faultstring>INVALID_MESSAGE</faultstring>\n <detail>\n <ns3:XcbSoapFault xmlns=\"\" xmlns:ns3=\"http://www.someapp.eu/xcb/types/xcb/v1\">\n <CauseCode>20007</CauseCode>\n <CauseText>INVALID_MESSAGE</CauseText>\n <DebugInfo>Problems creating SAAJ object model</DebugInfo>\n </ns3:XcbSoapFault>\n </detail>\n </soap:Fault>\n </soap:Body>\n</soap:Envelope>\n</code></pre>\n"
},
{
"answer_id": 21736245,
"author": "milosmns",
"author_id": 2102748,
"author_profile": "https://Stackoverflow.com/users/2102748",
"pm_score": 3,
"selected": false,
"text": "<p>If you're sure that you have a valid XML, this one is simple, and avoids XML DOM trees. Maybe has some bugs, do comment if you see anything</p>\n\n<pre><code>public String prettyPrint(String xml) {\n if (xml == null || xml.trim().length() == 0) return \"\";\n\n int stack = 0;\n StringBuilder pretty = new StringBuilder();\n String[] rows = xml.trim().replaceAll(\">\", \">\\n\").replaceAll(\"<\", \"\\n<\").split(\"\\n\");\n\n for (int i = 0; i < rows.length; i++) {\n if (rows[i] == null || rows[i].trim().length() == 0) continue;\n\n String row = rows[i].trim();\n if (row.startsWith(\"<?\")) {\n // xml version tag\n pretty.append(row + \"\\n\");\n } else if (row.startsWith(\"</\")) {\n // closing tag\n String indent = repeatString(\" \", --stack);\n pretty.append(indent + row + \"\\n\");\n } else if (row.startsWith(\"<\")) {\n // starting tag\n String indent = repeatString(\" \", stack++);\n pretty.append(indent + row + \"\\n\");\n } else {\n // tag data\n String indent = repeatString(\" \", stack);\n pretty.append(indent + row + \"\\n\");\n }\n }\n\n return pretty.toString().trim();\n }\n</code></pre>\n"
},
{
"answer_id": 24650999,
"author": "codeskraps",
"author_id": 619587,
"author_profile": "https://Stackoverflow.com/users/619587",
"pm_score": 3,
"selected": false,
"text": "<p>slightly improved version from <a href=\"https://stackoverflow.com/a/21736245/619587\">milosmns</a>...</p>\n\n<pre><code>public static String getPrettyXml(String xml) {\n if (xml == null || xml.trim().length() == 0) return \"\";\n\n int stack = 0;\n StringBuilder pretty = new StringBuilder();\n String[] rows = xml.trim().replaceAll(\">\", \">\\n\").replaceAll(\"<\", \"\\n<\").split(\"\\n\");\n\n for (int i = 0; i < rows.length; i++) {\n if (rows[i] == null || rows[i].trim().length() == 0) continue;\n\n String row = rows[i].trim();\n if (row.startsWith(\"<?\")) {\n pretty.append(row + \"\\n\");\n } else if (row.startsWith(\"</\")) {\n String indent = repeatString(--stack);\n pretty.append(indent + row + \"\\n\");\n } else if (row.startsWith(\"<\") && row.endsWith(\"/>\") == false) {\n String indent = repeatString(stack++);\n pretty.append(indent + row + \"\\n\");\n if (row.endsWith(\"]]>\")) stack--;\n } else {\n String indent = repeatString(stack);\n pretty.append(indent + row + \"\\n\");\n }\n }\n\n return pretty.toString().trim();\n}\n\nprivate static String repeatString(int stack) {\n StringBuilder indent = new StringBuilder();\n for (int i = 0; i < stack; i++) {\n indent.append(\" \");\n }\n return indent.toString();\n} \n</code></pre>\n"
},
{
"answer_id": 26361221,
"author": "Wojtek",
"author_id": 2685402,
"author_profile": "https://Stackoverflow.com/users/2685402",
"pm_score": 1,
"selected": false,
"text": "<p>The solutions I have found here for Java 1.6+ do not reformat the code if it is already formatted. The one that worked for me (and re-formatted already formatted code) was the following.</p>\n\n<pre><code>import org.apache.xml.security.c14n.CanonicalizationException;\nimport org.apache.xml.security.c14n.Canonicalizer;\nimport org.apache.xml.security.c14n.InvalidCanonicalizerException;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.bootstrap.DOMImplementationRegistry;\nimport org.w3c.dom.ls.DOMImplementationLS;\nimport org.w3c.dom.ls.LSSerializer;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\nimport java.io.IOException;\nimport java.io.StringReader;\n\npublic class XmlUtils {\n public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {\n Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);\n byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());\n return new String(canonXmlBytes);\n }\n\n public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {\n InputSource src = new InputSource(new StringReader(input));\n Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();\n Boolean keepDeclaration = input.startsWith(\"<?xml\");\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n writer.getDomConfig().setParameter(\"format-pretty-print\", Boolean.TRUE);\n writer.getDomConfig().setParameter(\"xml-declaration\", keepDeclaration);\n return writer.writeToString(document);\n }\n}\n</code></pre>\n\n<p>It is a good tool to use in your unit tests for full-string xml comparison. </p>\n\n<pre><code>private void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {\n String canonicalExpected = prettyFormat(toCanonicalXml(expected));\n String canonicalActual = prettyFormat(toCanonicalXml(actual));\n assertEquals(canonicalExpected, canonicalActual);\n}\n</code></pre>\n"
},
{
"answer_id": 27681201,
"author": "ThomasRS",
"author_id": 459579,
"author_profile": "https://Stackoverflow.com/users/459579",
"pm_score": 2,
"selected": false,
"text": "<p>As an alternative to the answers from <a href=\"https://stackoverflow.com/users/767434/max\">max</a>, <a href=\"https://stackoverflow.com/users/619587/codeskraps\">codeskraps</a>, <a href=\"https://stackoverflow.com/users/65555/david-easley\">David Easley</a> and <a href=\"https://stackoverflow.com/users/2102748/milosmns\">milosmns</a>, have a look at my lightweight, high-performance pretty-printer library: <a href=\"https://github.com/greenbird/xml-formatter-core\" rel=\"nofollow noreferrer\">xml-formatter</a></p>\n\n<pre><code>// construct lightweight, threadsafe, instance\nPrettyPrinter prettyPrinter = PrettyPrinterBuilder.newPrettyPrinter().build();\n\nStringBuilder buffer = new StringBuilder();\nString xml = ..; // also works with char[] or Reader\n\nif(prettyPrinter.process(xml, buffer)) {\n // valid XML, print buffer\n} else {\n // invalid XML, print xml\n}\n</code></pre>\n\n<p>Sometimes, like when running mocked SOAP services directly from file, it is good to have a pretty-printer which also handles already pretty-printed XML:</p>\n\n<pre><code>PrettyPrinter prettyPrinter = PrettyPrinterBuilder.newPrettyPrinter().ignoreWhitespace().build();\n</code></pre>\n\n<p>As some have commented, pretty-printing is just a way of presenting XML in a more human-readable form - whitespace strictly does not belong in your XML data. </p>\n\n<p>The library is intended for pretty-printing for logging purposes, and also includes functions for filtering (subtree removal / anonymization) and pretty-printing of XML in CDATA and Text nodes.</p>\n"
},
{
"answer_id": 29994838,
"author": "vsnyc",
"author_id": 2063026,
"author_profile": "https://Stackoverflow.com/users/2063026",
"pm_score": 1,
"selected": false,
"text": "<p>I saw <a href=\"https://stackoverflow.com/a/5227490/2063026\">one answer</a> using <code>Scala</code>, so here is another one in <code>Groovy</code>, just in case someone finds it interesting. The default indentation is 2 steps, <code>XmlNodePrinter</code> constructor can be passed another value as well.</p>\n\n<pre><code>def xml = \"<tag><nested>hello</nested></tag>\"\ndef stringWriter = new StringWriter()\ndef node = new XmlParser().parseText(xml);\nnew XmlNodePrinter(new PrintWriter(stringWriter)).print(node)\nprintln stringWriter.toString()\n</code></pre>\n\n<p>Usage from Java if groovy jar is in classpath</p>\n\n<pre><code> String xml = \"<tag><nested>hello</nested></tag>\";\n StringWriter stringWriter = new StringWriter();\n Node node = new XmlParser().parseText(xml);\n new XmlNodePrinter(new PrintWriter(stringWriter)).print(node);\n System.out.println(stringWriter.toString());\n</code></pre>\n"
},
{
"answer_id": 30171112,
"author": "BijanE",
"author_id": 2339693,
"author_profile": "https://Stackoverflow.com/users/2339693",
"pm_score": 2,
"selected": false,
"text": "<p>Using jdom2 : <a href=\"http://www.jdom.org/\" rel=\"nofollow\">http://www.jdom.org/</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.StringReader;\nimport org.jdom2.input.SAXBuilder;\nimport org.jdom2.output.Format;\nimport org.jdom2.output.XMLOutputter;\n\nString prettyXml = new XMLOutputter(Format.getPrettyFormat()).\n outputString(new SAXBuilder().build(new StringReader(uglyXml)));\n</code></pre>\n"
},
{
"answer_id": 30213453,
"author": "Georgy Gobozov",
"author_id": 423868,
"author_profile": "https://Stackoverflow.com/users/423868",
"pm_score": 3,
"selected": false,
"text": "<p>All above solutions didn't work for me, then I found this <a href=\"http://myshittycode.com/2014/02/10/java-properly-indenting-xml-string/\" rel=\"noreferrer\">http://myshittycode.com/2014/02/10/java-properly-indenting-xml-string/</a></p>\n\n<p>The clue is remove whitespaces with XPath</p>\n\n<pre><code> String xml = \"<root>\" +\n \"\\n \" +\n \"\\n<name>Coco Puff</name>\" +\n \"\\n <total>10</total> </root>\";\n\ntry {\n Document document = DocumentBuilderFactory.newInstance()\n .newDocumentBuilder()\n .parse(new InputSource(new ByteArrayInputStream(xml.getBytes(\"utf-8\"))));\n\n XPath xPath = XPathFactory.newInstance().newXPath();\n NodeList nodeList = (NodeList) xPath.evaluate(\"//text()[normalize-space()='']\",\n document,\n XPathConstants.NODESET);\n\n for (int i = 0; i < nodeList.getLength(); ++i) {\n Node node = nodeList.item(i);\n node.getParentNode().removeChild(node);\n }\n\n Transformer transformer = TransformerFactory.newInstance().newTransformer();\n transformer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n\n StringWriter stringWriter = new StringWriter();\n StreamResult streamResult = new StreamResult(stringWriter);\n\n transformer.transform(new DOMSource(document), streamResult);\n\n System.out.println(stringWriter.toString());\n}\ncatch (Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n"
},
{
"answer_id": 31571512,
"author": "Anand",
"author_id": 1343090,
"author_profile": "https://Stackoverflow.com/users/1343090",
"pm_score": 3,
"selected": false,
"text": "<p>Just another solution which works for us</p>\n\n<pre><code>import java.io.StringWriter;\nimport org.dom4j.DocumentHelper;\nimport org.dom4j.io.OutputFormat;\nimport org.dom4j.io.XMLWriter;\n\n**\n * Pretty Print XML String\n * \n * @param inputXmlString\n * @return\n */\npublic static String prettyPrintXml(String xml) {\n\n final StringWriter sw;\n\n try {\n final OutputFormat format = OutputFormat.createPrettyPrint();\n final org.dom4j.Document document = DocumentHelper.parseText(xml);\n sw = new StringWriter();\n final XMLWriter writer = new XMLWriter(sw, format);\n writer.write(document);\n }\n catch (Exception e) {\n throw new RuntimeException(\"Error pretty printing xml:\\n\" + xml, e);\n }\n return sw.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 32119396,
"author": "comonad",
"author_id": 460175,
"author_profile": "https://Stackoverflow.com/users/460175",
"pm_score": 1,
"selected": false,
"text": "<p>In case you do not need indentation that much but a few line breaks, it could be sufficient to simply regex...</p>\n\n<pre><code>String leastPrettifiedXml = uglyXml.replaceAll(\"><\", \">\\n<\");\n</code></pre>\n\n<p>The code is nice, not the result because of missing indentation. </p>\n\n<hr>\n\n<p>(For solutions with indentation, see other answers.)</p>\n"
},
{
"answer_id": 37221093,
"author": "Sireesh Yarlagadda",
"author_id": 2057902,
"author_profile": "https://Stackoverflow.com/users/2057902",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code> try\n {\n TransformerFactory transFactory = TransformerFactory.newInstance();\n Transformer transformer = null;\n transformer = transFactory.newTransformer();\n StringWriter buffer = new StringWriter();\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n transformer.transform(new DOMSource(element),\n new StreamResult(buffer)); \n String str = buffer.toString();\n System.out.println(\"XML INSIDE IS #########################################\"+str);\n return element;\n }\n catch (TransformerConfigurationException e)\n {\n e.printStackTrace();\n }\n catch (TransformerException e)\n {\n e.printStackTrace();\n }\n</code></pre>\n"
},
{
"answer_id": 37599612,
"author": "maks tkach",
"author_id": 6068492,
"author_profile": "https://Stackoverflow.com/users/6068492",
"pm_score": 3,
"selected": false,
"text": "<p>This code below working perfectly</p>\n\n<pre><code>import javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\nimport javax.xml.transform.stream.StreamSource;\n\nString formattedXml1 = prettyFormat(\"<root><child>aaa</child><child/></root>\");\n\npublic static String prettyFormat(String input) {\n return prettyFormat(input, \"2\");\n}\n\npublic static String prettyFormat(String input, String indent) {\n Source xmlInput = new StreamSource(new StringReader(input));\n StringWriter stringWriter = new StringWriter();\n try {\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", indent);\n transformer.transform(xmlInput, new StreamResult(stringWriter));\n\n String pretty = stringWriter.toString();\n pretty = pretty.replace(\"\\r\\n\", \"\\n\");\n return pretty; \n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47107329,
"author": "Steve T",
"author_id": 3465795,
"author_profile": "https://Stackoverflow.com/users/3465795",
"pm_score": 0,
"selected": false,
"text": "<p>I should have looked for this page first before coming up with my own solution! Anyway, mine uses Java recursion to parse the xml page. This code is totally self-contained and does not rely on third party libraries. Also .. it uses recursion!</p>\n\n<pre><code>// you call this method passing in the xml text\npublic static void prettyPrint(String text){\n prettyPrint(text, 0);\n}\n\n// \"index\" corresponds to the number of levels of nesting and/or the number of tabs to print before printing the tag\npublic static void prettyPrint(String xmlText, int index){\n boolean foundTagStart = false;\n StringBuilder tagChars = new StringBuilder();\n String startTag = \"\";\n String endTag = \"\";\n String[] chars = xmlText.split(\"\");\n // find the next start tag\n for(String ch : chars){\n if(ch.equalsIgnoreCase(\"<\")){\n tagChars.append(ch);\n foundTagStart = true;\n } else if(ch.equalsIgnoreCase(\">\") && foundTagStart){\n startTag = tagChars.append(ch).toString();\n String tempTag = startTag;\n endTag = (tempTag.contains(\"\\\"\") ? (tempTag.split(\" \")[0] + \">\") : tempTag).replace(\"<\", \"</\"); // <startTag attr1=1 attr2=2> => </startTag>\n break;\n } else if(foundTagStart){\n tagChars.append(ch);\n }\n }\n // once start and end tag are calculated, print start tag, then content, then end tag\n if(foundTagStart){\n int startIndex = xmlText.indexOf(startTag);\n int endIndex = xmlText.indexOf(endTag);\n // handle if matching tags NOT found\n if((startIndex < 0) || (endIndex < 0)){\n if(startIndex < 0) {\n // no start tag found\n return;\n } else {\n // start tag found, no end tag found (handles single tags aka \"<mytag/>\" or \"<?xml ...>\")\n printTabs(index);\n System.out.println(startTag);\n // move on to the next tag\n // NOTE: \"index\" (not index+1) because next tag is on same level as this one\n prettyPrint(xmlText.substring(startIndex+startTag.length(), xmlText.length()), index);\n return;\n }\n // handle when matching tags found\n } else {\n String content = xmlText.substring(startIndex+startTag.length(), endIndex);\n boolean isTagContainsTags = content.contains(\"<\"); // content contains tags\n printTabs(index);\n if(isTagContainsTags){ // ie: <tag1><tag2>stuff</tag2></tag1>\n System.out.println(startTag);\n prettyPrint(content, index+1); // \"index+1\" because \"content\" is nested\n printTabs(index);\n } else {\n System.out.print(startTag); // ie: <tag1>stuff</tag1> or <tag1></tag1>\n System.out.print(content);\n }\n System.out.println(endTag);\n int nextIndex = endIndex + endTag.length();\n if(xmlText.length() > nextIndex){ // if there are more tags on this level, continue\n prettyPrint(xmlText.substring(nextIndex, xmlText.length()), index);\n }\n }\n } else {\n System.out.print(xmlText);\n }\n}\n\nprivate static void printTabs(int counter){\n while(counter-- > 0){ \n System.out.print(\"\\t\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 51272975,
"author": "user3083990",
"author_id": 3083990,
"author_profile": "https://Stackoverflow.com/users/3083990",
"pm_score": 3,
"selected": false,
"text": "<p>I mix all of them and writing one small program. It is reading from the xml file and printing out. Just Instead of xzy give your file path.</p>\n\n<pre><code> public static void main(String[] args) throws Exception {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setValidating(false);\n DocumentBuilder db = dbf.newDocumentBuilder();\n Document doc = db.parse(new FileInputStream(new File(\"C:/Users/xyz.xml\")));\n prettyPrint(doc);\n\n}\n\nprivate static String prettyPrint(Document document)\n throws TransformerException {\n TransformerFactory transformerFactory = TransformerFactory\n .newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n transformer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n DOMSource source = new DOMSource(document);\n StringWriter strWriter = new StringWriter();\n StreamResult result = new StreamResult(strWriter);transformer.transform(source, result);\n System.out.println(strWriter.getBuffer().toString());\n\n return strWriter.getBuffer().toString();\n\n}\n</code></pre>\n"
},
{
"answer_id": 54683129,
"author": "Valentyn Kolesnikov",
"author_id": 1947482,
"author_profile": "https://Stackoverflow.com/users/1947482",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/javadev/underscore-java\" rel=\"nofollow noreferrer\">Underscore-java</a> has static method <code>U.formatXml(string)</code>. <a href=\"https://www.jdoodle.com/embed/v0/QaB\" rel=\"nofollow noreferrer\">Live example</a></p>\n<pre><code>import com.github.underscore.U;\n\npublic class MyClass {\n public static void main(String args[]) {\n String xml = "<tag><nested>hello</nested></tag>";\n\n System.out.println(U.formatXml("<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><root>" + xml + "</root>"));\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code><?xml version="1.0" encoding="UTF-8"?>\n<root>\n <tag>\n <nested>hello</nested>\n </tag>\n</root>\n</code></pre>\n"
},
{
"answer_id": 56006254,
"author": "Benson Githinji",
"author_id": 6740199,
"author_profile": "https://Stackoverflow.com/users/6740199",
"pm_score": 2,
"selected": false,
"text": "<p><strong>I always use the below function:</strong></p>\n\n<pre><code>public static String prettyPrintXml(String xmlStringToBeFormatted) {\n String formattedXmlString = null;\n try {\n DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n documentBuilderFactory.setValidating(true);\n DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();\n InputSource inputSource = new InputSource(new StringReader(xmlStringToBeFormatted));\n Document document = documentBuilder.parse(inputSource);\n\n Transformer transformer = TransformerFactory.newInstance().newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n\n StreamResult streamResult = new StreamResult(new StringWriter());\n DOMSource dOMSource = new DOMSource(document);\n transformer.transform(dOMSource, streamResult);\n formattedXmlString = streamResult.getWriter().toString().trim();\n } catch (Exception ex) {\n StringWriter sw = new StringWriter();\n ex.printStackTrace(new PrintWriter(sw));\n System.err.println(sw.toString());\n }\n return formattedXmlString;\n}\n</code></pre>\n"
},
{
"answer_id": 56531539,
"author": "Faisal K",
"author_id": 8332759,
"author_profile": "https://Stackoverflow.com/users/8332759",
"pm_score": -1,
"selected": false,
"text": "<p>I was trying to achieve something similar, but without any external dependency. The application was already using DOM to format just for logging the XMLs!</p>\n\n<p>Here is my sample snippet</p>\n\n<pre><code>public void formatXML(final String unformattedXML) {\n final int length = unformattedXML.length();\n final int indentSpace = 3;\n final StringBuilder newString = new StringBuilder(length + length / 10);\n final char space = ' ';\n int i = 0;\n int indentCount = 0;\n char currentChar = unformattedXML.charAt(i++);\n char previousChar = currentChar;\n boolean nodeStarted = true;\n newString.append(currentChar);\n for (; i < length - 1;) {\n currentChar = unformattedXML.charAt(i++);\n if(((int) currentChar < 33) && !nodeStarted) {\n continue;\n }\n switch (currentChar) {\n case '<':\n if ('>' == previousChar && '/' != unformattedXML.charAt(i - 1) && '/' != unformattedXML.charAt(i) && '!' != unformattedXML.charAt(i)) {\n indentCount++;\n }\n newString.append(System.lineSeparator());\n for (int j = indentCount * indentSpace; j > 0; j--) {\n newString.append(space);\n }\n newString.append(currentChar);\n nodeStarted = true;\n break;\n case '>':\n newString.append(currentChar);\n nodeStarted = false;\n break;\n case '/':\n if ('<' == previousChar || '>' == unformattedXML.charAt(i)) {\n indentCount--;\n }\n newString.append(currentChar);\n break;\n default:\n newString.append(currentChar);\n }\n previousChar = currentChar;\n }\n newString.append(unformattedXML.charAt(length - 1));\n System.out.println(newString.toString());\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
]
| I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?
```
String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
```
Note: My input is a **String**. My output is a **String**.
(Basic) mock result:
```
<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
``` | Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.
```
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
/**
* Pretty-prints xml, supplied as a string.
* <p/>
* eg.
* <code>
* String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
* </code>
*/
public class XmlFormatter {
public String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
//May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
return writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String unformattedXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
" xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
" xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
" <Query>\n" +
" <query:CategorySchemeWhere>\n" +
" \t\t\t\t\t <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
" </query:CategorySchemeWhere>\n" +
" </Query>\n\n\n\n\n" +
"</QueryMessage>";
System.out.println(new XmlFormatter().format(unformattedXml));
}
}
``` |
139,088 | <p>when i use setDefaultLookAndFeelDecorated(true) method in Java
why is the Frame appear FullScreen when i maximize the Frame ?
and how can i disaple the FullScreen mode in this method ?</p>
| [
{
"answer_id": 139126,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want your JFrame to be maximize-able then then call .setResizable(false); on it. </p>\n"
},
{
"answer_id": 144142,
"author": "Angelo van der Sijpt",
"author_id": 19144,
"author_profile": "https://Stackoverflow.com/users/19144",
"pm_score": 3,
"selected": true,
"text": "<p>Setting <code>setDefaultLookAndFeelDecorated</code> to true causes the decorations to be handled by the look and feel; this means that a System look-and-feel on both Windows and Mac (I have no Linux at hand now) retains the borders you would expect them of a native window, e.g. staying clear of the taskbar in Windows.</p>\n\n<p>When using the Cross Platform look-and-feel, a.k.a. Metal, which is the default on Windows, the Windows version will take over the entire screen, making it look like a full-screen window. On Mac, the OS refuses to give away its own titlebar, and draws a complete Metal frame (including the title bar) in a Mac-native window.</p>\n\n<p>So, in short, if you want to make sure the taskbar gets respected, use the Windows system look-and-feel on Windows. You can set it by using something like</p>\n\n<pre><code>UIManager.setLookAndFeel((LookAndFeel) Class.forName(UIManager.getCrossPlatformLookAndFeelClassName()).newInstance());\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
]
| when i use setDefaultLookAndFeelDecorated(true) method in Java
why is the Frame appear FullScreen when i maximize the Frame ?
and how can i disaple the FullScreen mode in this method ? | Setting `setDefaultLookAndFeelDecorated` to true causes the decorations to be handled by the look and feel; this means that a System look-and-feel on both Windows and Mac (I have no Linux at hand now) retains the borders you would expect them of a native window, e.g. staying clear of the taskbar in Windows.
When using the Cross Platform look-and-feel, a.k.a. Metal, which is the default on Windows, the Windows version will take over the entire screen, making it look like a full-screen window. On Mac, the OS refuses to give away its own titlebar, and draws a complete Metal frame (including the title bar) in a Mac-native window.
So, in short, if you want to make sure the taskbar gets respected, use the Windows system look-and-feel on Windows. You can set it by using something like
```
UIManager.setLookAndFeel((LookAndFeel) Class.forName(UIManager.getCrossPlatformLookAndFeelClassName()).newInstance());
``` |
139,090 | <p>I have a DLL that's loaded into a 3rd party parent process as an extension. From this DLL I instantiate external processes (my own) by using CreateProcess API. This works great in 99.999% of the cases but sometimes this suddenly fails and stops working permanently (maybe a restart of the parent process would solve this but this is undesirable and I don't want to recommend that until I solve the problem.) The failure is symptomized by external process not being invoked any more even though CreteProcess() doesn't report an error and by GetExitCodeProcess() returning 128. Here's the simplified version of what I'm doing:</p>
<pre><code>STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
if(!CreateProcess(
NULL, // No module name (use command line).
"<my command line>",
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
CREATE_SUSPENDED, // Create suspended.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi)) // Pointer to PROCESS_INFORMATION structure.
{
// Handle error.
}
else
{
// Do something.
// Resume the external process thread.
DWORD resumeThreadResult = ResumeThread(pi.hThread);
// ResumeThread() returns 1 which is OK
// (it means that the thread was suspended but then restarted)
// Wait for the external process to finish.
DWORD waitForSingelObjectResult = WaitForSingleObject(pi.hProcess, INFINITE);
// WaitForSingleObject() returns 0 which is OK.
// Get the exit code of the external process.
DWORD exitCode;
if(!GetExitCodeProcess(pi.hProcess, &exitCode))
{
// Handle error.
}
else
{
// There is no error but exitCode is 128, a value that
// doesn't exist in the external process (and even if it
// existed it doesn't matter as it isn't being invoked any more)
// Error code 128 is ERROR_WAIT_NO_CHILDREN which would make some
// sense *if* GetExitCodeProcess() returned FALSE and then I were to
// get ERROR_WAIT_NO_CHILDREN with GetLastError()
}
// PROCESS_INFORMATION handles for process and thread are closed.
}
</code></pre>
<p>External process can be manually invoked from Windows Explorer or command line and it starts just fine on its own. Invoked like that it, before doing any real work, creates a log file and logs some information about it. But invoked like described above this logging information doesn't appear at all so I'm assuming that the main thread of the external process never enters main() (I'm testing that assumption now.)</p>
<p>There is at least one thing I could do to try to circumvent the problem (not start the thread suspended) but I would first like to understand the root of the failure first. Does anyone has any idea what could cause this and how to fix it?</p>
| [
{
"answer_id": 139230,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 1,
"selected": false,
"text": "<p>Quoting from the MSDN article on <a href=\"http://msdn.microsoft.com/en-us/library/aa915088.aspx\" rel=\"nofollow noreferrer\">GetExitCodeProcess</a>:</p>\n\n<p>The following termination statuses can be returned if the process has terminated:</p>\n\n<ul>\n<li>The exit value specified in the\nExitProcess or TerminateProcess\nfunction </li>\n<li>The return value from the\nmain or WinMain function of the\nprocess </li>\n<li>The exception value for an\nunhandled exception that caused the\nprocess to terminate</li>\n</ul>\n\n<p>Given the scenario you described, I think the most likely cause ist the third: An unhandled exception. Have a look at the source of the processes you create.</p>\n"
},
{
"answer_id": 146351,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 0,
"selected": false,
"text": "<p>There are 2 issues that i could think of from your code sample</p>\n\n<p>1.Get yourusage of the first 2 paramaters to the creatprocess command working first. Hard code the paths and invoke notepad.exe and see if that comes up. keep tweaking this until you have notepad running.</p>\n\n<p>2.Contrary to your comment, If you have passed the currentdirectory parameter for the new process as NULL, it will use the current working directory of the process to start the new process from and not the parent' starting directory. </p>\n\n<p>I assume that your external process exe cannot start properly due to dll dependencies that cannot be resolved in the new path. </p>\n\n<p>ps : In the debugger watch for @err,hr which will tell you the explanation for the last error code, </p>\n"
},
{
"answer_id": 230692,
"author": "Nader Shirazie",
"author_id": 16529,
"author_profile": "https://Stackoverflow.com/users/16529",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look at Desktop Heap memory.</p>\n\n<p>Essentially the desktop heap issue comes down to exhausted resources (eg starting too many processes). When your app runs out of these resources, one of the symptoms is that you won't be able to start a new process, and the call to CreateProcess will fail with code 128.</p>\n\n<p>Note that the context you run in also has some effect. For example, running as a service, you will run out of desktop heap much faster than if you're testing your code in a console app.</p>\n\n<p>This <a href=\"http://blogs.msdn.com/ntdebugging/archive/2007/01/04/desktop-heap-overview.aspx\" rel=\"nofollow noreferrer\">post</a> has a lot of good information about desktop heap</p>\n\n<p><a href=\"http://support.microsoft.com/kb/126962\" rel=\"nofollow noreferrer\">Microsoft Support</a> also has some useful information.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a DLL that's loaded into a 3rd party parent process as an extension. From this DLL I instantiate external processes (my own) by using CreateProcess API. This works great in 99.999% of the cases but sometimes this suddenly fails and stops working permanently (maybe a restart of the parent process would solve this but this is undesirable and I don't want to recommend that until I solve the problem.) The failure is symptomized by external process not being invoked any more even though CreteProcess() doesn't report an error and by GetExitCodeProcess() returning 128. Here's the simplified version of what I'm doing:
```
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
if(!CreateProcess(
NULL, // No module name (use command line).
"<my command line>",
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
CREATE_SUSPENDED, // Create suspended.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi)) // Pointer to PROCESS_INFORMATION structure.
{
// Handle error.
}
else
{
// Do something.
// Resume the external process thread.
DWORD resumeThreadResult = ResumeThread(pi.hThread);
// ResumeThread() returns 1 which is OK
// (it means that the thread was suspended but then restarted)
// Wait for the external process to finish.
DWORD waitForSingelObjectResult = WaitForSingleObject(pi.hProcess, INFINITE);
// WaitForSingleObject() returns 0 which is OK.
// Get the exit code of the external process.
DWORD exitCode;
if(!GetExitCodeProcess(pi.hProcess, &exitCode))
{
// Handle error.
}
else
{
// There is no error but exitCode is 128, a value that
// doesn't exist in the external process (and even if it
// existed it doesn't matter as it isn't being invoked any more)
// Error code 128 is ERROR_WAIT_NO_CHILDREN which would make some
// sense *if* GetExitCodeProcess() returned FALSE and then I were to
// get ERROR_WAIT_NO_CHILDREN with GetLastError()
}
// PROCESS_INFORMATION handles for process and thread are closed.
}
```
External process can be manually invoked from Windows Explorer or command line and it starts just fine on its own. Invoked like that it, before doing any real work, creates a log file and logs some information about it. But invoked like described above this logging information doesn't appear at all so I'm assuming that the main thread of the external process never enters main() (I'm testing that assumption now.)
There is at least one thing I could do to try to circumvent the problem (not start the thread suspended) but I would first like to understand the root of the failure first. Does anyone has any idea what could cause this and how to fix it? | Quoting from the MSDN article on [GetExitCodeProcess](http://msdn.microsoft.com/en-us/library/aa915088.aspx):
The following termination statuses can be returned if the process has terminated:
* The exit value specified in the
ExitProcess or TerminateProcess
function
* The return value from the
main or WinMain function of the
process
* The exception value for an
unhandled exception that caused the
process to terminate
Given the scenario you described, I think the most likely cause ist the third: An unhandled exception. Have a look at the source of the processes you create. |
139,115 | <p>Here is the scenario:</p>
<p>I have a winforms application using NHibernate. When launched, I populate a DataGridView with the results of a NHibernate query. This part works fine. If I update a record in that list and flush the session, the update takes in the database. Upon closing the form after the update, I call a method to retrieve a list of objects to populate the DataGridView again to pick up the change and also get any other changes that may have occurred by somebody else. The problem is that the record that got updated, NHibernate doesn't reflect the change in the list it gives me. When I insert or delete a record, everything works fine. It is just when I update, that I get this behavior. I narrowed it down to NHibernate with their caching mechanism. I cannot figure out a way to make NHibernate retrieve from the database instead of using the cache after an update occurs. I posted on the NHibernate forums, but the suggestions they gave me didn't work. I stated this and nobody replied back. I am not going to state what I have tried in case I didn't do it right. If you answer with something that I tried exactly, I will state it in the comments of your answer.</p>
<p>This is the code that I use to retrieve the list:</p>
<pre><code>public IList<WorkOrder> FindBy(string fromDate, string toDate)
{
IQuery query = _currentSession.CreateQuery("from WorkOrder wo where wo.Date >= ? and wo.Date <= ?");
query.SetParameter(0, fromDate);
query.SetParameter(1, toDate);
return query.List<WorkOrder>();
}
</code></pre>
<p>The session is passed to the class when it is constructed. I can post my mapping file also, but I am not sure if there is anything wrong with it, since everything else works. Anybody seen this before? This is the first project that I have used NHibernate, thanks for the help.</p>
| [
{
"answer_id": 139133,
"author": "Richard",
"author_id": 20038,
"author_profile": "https://Stackoverflow.com/users/20038",
"pm_score": 0,
"selected": false,
"text": "<p>what about refresh? - see <a href=\"http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/manipulatingdata.html#manipulatingdata-update-lock\" rel=\"nofollow noreferrer\">9.2. Loading an object</a> of the docs:</p>\n\n<p>\"sess.Save(cat);\nsess.Flush(); //force the SQL INSERT\nsess.Refresh(cat); //re-read the state (after the trigger executes)\n\"</p>\n"
},
{
"answer_id": 191800,
"author": "Watson",
"author_id": 25807,
"author_profile": "https://Stackoverflow.com/users/25807",
"pm_score": 2,
"selected": false,
"text": "<p>After your update, Evict the object from the first level cache.</p>\n\n<pre><code>Session.Update(obj);\nSession.Evict(obj);\n</code></pre>\n\n<p>You may want to commit and/or flush first.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1117/"
]
| Here is the scenario:
I have a winforms application using NHibernate. When launched, I populate a DataGridView with the results of a NHibernate query. This part works fine. If I update a record in that list and flush the session, the update takes in the database. Upon closing the form after the update, I call a method to retrieve a list of objects to populate the DataGridView again to pick up the change and also get any other changes that may have occurred by somebody else. The problem is that the record that got updated, NHibernate doesn't reflect the change in the list it gives me. When I insert or delete a record, everything works fine. It is just when I update, that I get this behavior. I narrowed it down to NHibernate with their caching mechanism. I cannot figure out a way to make NHibernate retrieve from the database instead of using the cache after an update occurs. I posted on the NHibernate forums, but the suggestions they gave me didn't work. I stated this and nobody replied back. I am not going to state what I have tried in case I didn't do it right. If you answer with something that I tried exactly, I will state it in the comments of your answer.
This is the code that I use to retrieve the list:
```
public IList<WorkOrder> FindBy(string fromDate, string toDate)
{
IQuery query = _currentSession.CreateQuery("from WorkOrder wo where wo.Date >= ? and wo.Date <= ?");
query.SetParameter(0, fromDate);
query.SetParameter(1, toDate);
return query.List<WorkOrder>();
}
```
The session is passed to the class when it is constructed. I can post my mapping file also, but I am not sure if there is anything wrong with it, since everything else works. Anybody seen this before? This is the first project that I have used NHibernate, thanks for the help. | After your update, Evict the object from the first level cache.
```
Session.Update(obj);
Session.Evict(obj);
```
You may want to commit and/or flush first. |
139,118 | <p>Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:</p>
<pre><code>document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
</code></pre>
<p>etc</p>
| [
{
"answer_id": 139132,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "<p>If you take a look at <a href=\"http://www.jquery.com\" rel=\"noreferrer\">JQuery</a>, you can do something like:</p>\n\n<pre><code><iframe id=\"my_iframe\" ...></iframe>\n\n$('#my_iframe').contents().find('html').html();\n</code></pre>\n\n<p>This is assuming that your iframe parent and child reside on the same server, due to the <a href=\"http://en.wikipedia.org/wiki/Same_origin_policy\" rel=\"noreferrer\">Same Origin Policy</a> in Javascript.</p>\n"
},
{
"answer_id": 139155,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 4,
"selected": false,
"text": "<p>I think this is what you want:</p>\n\n<pre><code>window.frames['iframe01'].document.body.innerHTML \n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake</p>\n\n<p>This will work:</p>\n\n<pre><code>window.frames[0].document.body.innerHTML \n</code></pre>\n\n<p>I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place. </p>\n\n<p>I like @ravz's jquery answer below.</p>\n"
},
{
"answer_id": 139178,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 1,
"selected": false,
"text": "<p>Don't forget that you can not cross domains because of security.</p>\n\n<p>So if this is the case, you should use <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON</a>.</p>\n"
},
{
"answer_id": 3510256,
"author": "cypher",
"author_id": 381786,
"author_profile": "https://Stackoverflow.com/users/381786",
"pm_score": 4,
"selected": false,
"text": "<p>Having something like the following would work.</p>\n\n<pre><code><iframe id = \"testframe\" onload = populateIframe(this.id);></iframe>\n\n// The following function should be inside a script tag\n\nfunction populateIframe(id) { \n\n var text = \"This is a Test\"\nvar iframe = document.getElementById(id); \n\nvar doc; \n\nif(iframe.contentDocument) { \n doc = iframe.contentDocument; \n} else {\n doc = iframe.contentWindow.document; \n}\n\ndoc.body.innerHTML = text; \n\n }\n</code></pre>\n"
},
{
"answer_id": 7289262,
"author": "Sourabh",
"author_id": 912359,
"author_profile": "https://Stackoverflow.com/users/912359",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the contentDocument or contentWindow property for that purpose. \nHere is the sample code. </p>\n\n<pre><code>function gethtml() {\n const x = document.getElementById(\"myframe\")\n const y = x.contentWindow || x.contentDocument\n const z = y.document ? y.document : y\n alert(z.body.innerHTML)\n}\n</code></pre>\n\n<p>here, <code>myframe</code> is the id of your iframe. \nNote: You can't extract the content out of an iframe from a src outside you domain. </p>\n"
},
{
"answer_id": 13843635,
"author": "ravi404",
"author_id": 948301,
"author_profile": "https://Stackoverflow.com/users/948301",
"pm_score": 2,
"selected": false,
"text": "<p>Conroy's answer was right. In the case you need only stuff from body tag, just use: </p>\n\n<pre><code>$('#my_iframe').contents().find('body').html();\n</code></pre>\n"
},
{
"answer_id": 24305538,
"author": "user1175106",
"author_id": 1175106,
"author_profile": "https://Stackoverflow.com/users/1175106",
"pm_score": 0,
"selected": false,
"text": "<pre><code>document.getElementById('iframe01').outerHTML\n</code></pre>\n"
},
{
"answer_id": 28533733,
"author": "Zsolt",
"author_id": 4570333,
"author_profile": "https://Stackoverflow.com/users/4570333",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the source from another domain if you install the ForceCORS filter on Firefox. When you turn on this filter, it will bypass the security feature in the browser and your script will work even if you try to read another webpage. For example, you could open FoxNews.com in an iframe and then read its source. The reason modern web brwosers deny this ability by default is because if the other domain includes a piece of JavaScript and you're reading that and displaying it on your page, it could contain malicious code and pose a security threat. So, whenever you're displaying data from another domain on your page, you must beware of this real threat and implement a way to filter out all JavaScript code from your text before you're going to display it. Remember, when a supposed piece of raw text contains some code enclosed within script tags, they won't show up when you display it on your page, nevertheless they will run! So, realize this is a threat.</p>\n\n<p><a href=\"http://www-jo.se/f.pfleger/forcecors\" rel=\"nofollow\">http://www-jo.se/f.pfleger/forcecors</a></p>\n"
},
{
"answer_id": 50576488,
"author": "Agha Ali Abbas",
"author_id": 4659158,
"author_profile": "https://Stackoverflow.com/users/4659158",
"pm_score": -1,
"selected": false,
"text": "<p>You can get html out of an iframe using this code\niframe = document.getElementById('frame');\ninnerHtml = iframe.contentDocument.documentElement.innerHTML</p>\n"
},
{
"answer_id": 54197533,
"author": "Ahsan Horani",
"author_id": 4453224,
"author_profile": "https://Stackoverflow.com/users/4453224",
"pm_score": 1,
"selected": false,
"text": "<p>This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.</p>\n\n<pre><code><div id='myframe'>\n\n <?php \n /* \n Use below function to display final HTML inside this div\n */\n\n //Display Frame\n echo displayFrame(); \n ?>\n\n</div>\n\n<?php\n\n/* \n Function to display frame from another domain \n*/\n\nfunction displayFrame()\n{\n $webUrl = 'http://[external-web-domain.com]/';\n\n //Get HTML from the URL\n $content = file_get_contents($webUrl);\n\n //Add custom JS to returned HTML content\n $customJS = \"\n <script>\n\n /* Here I am writing a sample jQuery to hide the navigation menu\n You can write your own jQuery for this content\n */\n //Hide Navigation bar\n jQuery(\\\".navbar\\\").hide();\n\n </script>\";\n\n //Append Custom JS with HTML\n $html = $content . $customJS;\n\n //Return customized HTML\n return $html;\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:
```
document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
```
etc | I think this is what you want:
```
window.frames['iframe01'].document.body.innerHTML
```
**EDIT:**
I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake
This will work:
```
window.frames[0].document.body.innerHTML
```
I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place.
I like @ravz's jquery answer below. |
139,131 | <p>i have a number of jsp files under web-inf folder. Inside my web.xml i specify an errorppage for 404 amd 403 and java.lang.exception. Do i need to include a page directive for each of my jsp's or will they automatically get forwarded to the exception handling page because they are under web-inf?</p>
<p>If this is true does this mean that jsps which are not placed under web-inf do need to have the page directive added in order to forward them to the exception handling page?</p>
<p>thank you , im just trying to understand the consequences of web-inf</p>
| [
{
"answer_id": 139174,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": true,
"text": "<p>You just need to have whatever errorpage you would like to use in your app available with all the other jsps. So in the following example you would just need to have the error pages in the root of the context path(where all of the other jsps are). Anytime the webapp receives a 404 or 403 error it will try to display one of these pages. .</p>\n\n<pre><code><error-page> \n <error-code>404</error-code> \n <location>/404Error.jsp</location> \n</error-page>\n<error-page> \n <error-code>403</error-code> \n <location>/403Error.jsp</location> \n</error-page>\n</code></pre>\n\n<p>Just make sure 404Error.jsp and 403Error.jsp contain: </p>\n\n<pre><code><%@ page isErrorPage=\"true\" %>\n</code></pre>\n\n<p>If you are actually using jsps for error pages (instead of just static html)</p>\n"
},
{
"answer_id": 139296,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>ok so just to clarify; my jsps dont need to be in the web-inf folder in order for my web descriptor to pick up the exception and forward to the error page</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| i have a number of jsp files under web-inf folder. Inside my web.xml i specify an errorppage for 404 amd 403 and java.lang.exception. Do i need to include a page directive for each of my jsp's or will they automatically get forwarded to the exception handling page because they are under web-inf?
If this is true does this mean that jsps which are not placed under web-inf do need to have the page directive added in order to forward them to the exception handling page?
thank you , im just trying to understand the consequences of web-inf | You just need to have whatever errorpage you would like to use in your app available with all the other jsps. So in the following example you would just need to have the error pages in the root of the context path(where all of the other jsps are). Anytime the webapp receives a 404 or 403 error it will try to display one of these pages. .
```
<error-page>
<error-code>404</error-code>
<location>/404Error.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/403Error.jsp</location>
</error-page>
```
Just make sure 404Error.jsp and 403Error.jsp contain:
```
<%@ page isErrorPage="true" %>
```
If you are actually using jsps for error pages (instead of just static html) |
139,157 | <p>I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them. </p>
<p>So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight.</p>
<p>There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way?</p>
| [
{
"answer_id": 139185,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 1,
"selected": false,
"text": "<p>You could:</p>\n\n<ul>\n<li>Give it (\"it\" being your text) a onclick event</li>\n<li>First click sets a variable to the current time</li>\n<li>Second click checks to see if that variable is x time from the current, current time (so a double click over, for example, 500ms, doesn't register as a double click)</li>\n<li>If it <em>is</em> a double click, do something to the page like adding hidden HTML, doing document.focus(). You'll have to experiment with these as some might cause unwanted scrolling.</li>\n</ul>\n"
},
{
"answer_id": 139195,
"author": "Vijesh VP",
"author_id": 22016,
"author_profile": "https://Stackoverflow.com/users/22016",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this is what you are looking for.</p>\n<pre><code><script type="text/javascript">\n function clearSelection() {\n var sel;\n if (document.selection && document.selection.empty) {\n document.selection.empty();\n } else if (window.getSelection) {\n sel = window.getSelection();\n if (sel && sel.removeAllRanges)\n sel.removeAllRanges();\n }\n } \n</script>\n\n<div ondblclick="clearSelection()">Some text goes here.</div>\n</code></pre>\n"
},
{
"answer_id": 141935,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 2,
"selected": false,
"text": "<p>You could use this CSS to simply hide the selection color (not supported by IE):</p>\n<pre class=\"lang-css prettyprint-override\"><code>#id::-moz-selection {\n background: transparent;\n}\n\n#id::selection {\n background: transparent;\n}\n</code></pre>\n"
},
{
"answer_id": 142801,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 6,
"selected": true,
"text": "<p>In (Mozilla, Firefox, Camino, Safari, Google Chrome) you can use this:</p>\n<pre><code>div.noSelect {\n -moz-user-select: none; /* mozilla browsers */\n -khtml-user-select: none; /* webkit browsers */\n}\n</code></pre>\n<p>For IE there is no CSS option, but you can capture the ondragstart event, and return false;</p>\n<p><strong>Update</strong></p>\n<p>Browser support for this property has expanded since 2008.</p>\n<pre><code>div.noSelect {\n -webkit-user-select: none; /* Safari */\n -ms-user-select: none; /* IE 10 and IE 11 */\n user-select: none; /* Standard syntax */\n}\n</code></pre>\n<p><a href=\"https://css-tricks.com/almanac/properties/u/user-select/\" rel=\"nofollow noreferrer\">https://www.w3schools.com/csSref/css3_pr_user-select.php</a></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/315650/"
]
| I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them.
So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight.
There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way? | In (Mozilla, Firefox, Camino, Safari, Google Chrome) you can use this:
```
div.noSelect {
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit browsers */
}
```
For IE there is no CSS option, but you can capture the ondragstart event, and return false;
**Update**
Browser support for this property has expanded since 2008.
```
div.noSelect {
-webkit-user-select: none; /* Safari */
-ms-user-select: none; /* IE 10 and IE 11 */
user-select: none; /* Standard syntax */
}
```
[https://www.w3schools.com/csSref/css3\_pr\_user-select.php](https://css-tricks.com/almanac/properties/u/user-select/) |
139,180 | <p>I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.</p>
<p>I want to call the <code>help</code> function on each one. In Ruby I can do something like <code>ClassName.methods</code> to get a list of all the methods available on that class. Is there something similar in Python?</p>
<p>e.g. something like:</p>
<pre><code>from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
</code></pre>
| [
{
"answer_id": 139193,
"author": "camflan",
"author_id": 22445,
"author_profile": "https://Stackoverflow.com/users/22445",
"pm_score": 9,
"selected": false,
"text": "<p>You can use <code>dir(module)</code> to see all available methods/attributes. Also check out PyDocs.</p>\n"
},
{
"answer_id": 139198,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 9,
"selected": true,
"text": "<p>Use the <a href=\"https://docs.python.org/3/library/inspect.html\" rel=\"noreferrer\"><code>inspect</code></a> module:</p>\n<pre><code>from inspect import getmembers, isfunction\n\nfrom somemodule import foo\nprint(getmembers(foo, isfunction))\n</code></pre>\n<p>Also see the <a href=\"https://docs.python.org/3/library/pydoc.html\" rel=\"noreferrer\"><code>pydoc</code></a> module, the <code>help()</code> function in the interactive interpreter and the <code>pydoc</code> command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.</p>\n"
},
{
"answer_id": 139258,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 6,
"selected": false,
"text": "<pre><code>import types\nimport yourmodule\n\nprint([getattr(yourmodule, a) for a in dir(yourmodule)\n if isinstance(getattr(yourmodule, a), types.FunctionType)])\n</code></pre>\n"
},
{
"answer_id": 140106,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 8,
"selected": false,
"text": "<p>Once you've <code>import</code>ed the module, you can just do:</p>\n<pre><code>help(modulename)\n</code></pre>\n<p>... To get the docs on all the functions at once, interactively. Or you can use:</p>\n<pre><code>dir(modulename)\n</code></pre>\n<p>... To simply list the names of all the functions and variables defined in the module.</p>\n"
},
{
"answer_id": 142501,
"author": "Algorias",
"author_id": 22893,
"author_profile": "https://Stackoverflow.com/users/22893",
"pm_score": 5,
"selected": false,
"text": "<p>This will do the trick:</p>\n\n<pre><code>dir(module) \n</code></pre>\n\n<p>However, if you find it annoying to read the returned list, just use the following loop to get one name per line.</p>\n\n<pre><code>for i in dir(module): print i\n</code></pre>\n"
},
{
"answer_id": 9794849,
"author": "adnan",
"author_id": 407743,
"author_profile": "https://Stackoverflow.com/users/407743",
"pm_score": 7,
"selected": false,
"text": "<p>Use <a href=\"https://docs.python.org/3/library/inspect.html#inspect.getmembers\" rel=\"noreferrer\"><code>inspect.getmembers</code></a> to get all the variables/classes/functions etc. in a module, and pass in <a href=\"https://docs.python.org/3/library/inspect.html#inspect.isfunction\" rel=\"noreferrer\"><code>inspect.isfunction</code></a> as the predicate to get just the functions:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from inspect import getmembers, isfunction\nfrom my_project import my_module\n \nfunctions_list = getmembers(my_module, isfunction)\n</code></pre>\n<p><code>getmembers</code> returns a list of tuples <code>(object_name, object)</code> sorted alphabetically by name.</p>\n<p>You can replace <code>isfunction</code> with any of the other <code>isXXX</code> functions in the <a href=\"https://docs.python.org/3/library/inspect.html\" rel=\"noreferrer\"><code>inspect</code> module</a>.</p>\n"
},
{
"answer_id": 10079706,
"author": "bmu",
"author_id": 1301710,
"author_profile": "https://Stackoverflow.com/users/1301710",
"pm_score": 5,
"selected": false,
"text": "<p><code>dir(module)</code> is the standard way when using a script or the standard interpreter, as mentioned in most answers.</p>\n\n<p>However with an interactive python shell like <a href=\"http://ipython.org\">IPython</a> you can use tab-completion to get an overview of all objects defined in the module. \nThis is much more convenient, than using a script and <code>print</code> to see what is defined in the module.</p>\n\n<ul>\n<li><code>module.<tab></code> will show you all objects defined in the module (functions, classes and so on)</li>\n<li><code>module.ClassX.<tab></code> will show you the methods and attributes of a class</li>\n<li><code>module.function_xy?</code> or <code>module.ClassX.method_xy?</code> will show you the docstring of that function / method</li>\n<li><code>module.function_x??</code> or <code>module.SomeClass.method_xy??</code> will show you the source code of the function / method. </li>\n</ul>\n"
},
{
"answer_id": 30584102,
"author": "ckb",
"author_id": 1668964,
"author_profile": "https://Stackoverflow.com/users/1668964",
"pm_score": 3,
"selected": false,
"text": "<p>None of these answers will work if you are unable to import said Python file without import errors. This was the case for me when I was inspecting a file which comes from a large code base with a lot of dependencies. The following will process the file as text and search for all method names that start with \"def\" and print them and their line numbers.</p>\n\n<pre><code>import re\npattern = re.compile(\"def (.*)\\(\")\nfor i, line in enumerate(open('Example.py')):\n for match in re.finditer(pattern, line):\n print '%s: %s' % (i+1, match.groups()[0])\n</code></pre>\n"
},
{
"answer_id": 31005891,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 6,
"selected": false,
"text": "<p>For completeness' sake, I'd like to point out that sometimes you may want to <em>parse</em> code instead of importing it. An <code>import</code> will <em>execute</em> top-level expressions, and that could be a problem.</p>\n\n<p>For example, I'm letting users select entry point functions for packages being made with <a href=\"https://docs.python.org/dev/library/zipapp.html\" rel=\"noreferrer\">zipapp</a>. Using <code>import</code> and <code>inspect</code> risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.</p>\n\n<p>Instead I use the <a href=\"https://docs.python.org/3.2/library/ast.html#module-ast\" rel=\"noreferrer\">ast</a> module to list all the top-level functions:</p>\n\n<pre><code>import ast\nimport sys\n\ndef top_level_functions(body):\n return (f for f in body if isinstance(f, ast.FunctionDef))\n\ndef parse_ast(filename):\n with open(filename, \"rt\") as file:\n return ast.parse(file.read(), filename=filename)\n\nif __name__ == \"__main__\":\n for filename in sys.argv[1:]:\n print(filename)\n tree = parse_ast(filename)\n for func in top_level_functions(tree.body):\n print(\" %s\" % func.name)\n</code></pre>\n\n<p>Putting this code in <code>list.py</code> and using itself as input, I get:</p>\n\n<pre><code>$ python list.py list.py\nlist.py\n top_level_functions\n parse_ast\n</code></pre>\n\n<p>Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.</p>\n\n<p>Though, a downside is that you can't detect functions that are generated at runtime, like <code>foo = lambda x,y: x*y</code>.</p>\n"
},
{
"answer_id": 40118371,
"author": "Vishal Lamba",
"author_id": 7038953,
"author_profile": "https://Stackoverflow.com/users/7038953",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the following method to get list all the functions in your module from shell:</p>\n\n<p><code>import module</code></p>\n\n<pre><code>module.*?\n</code></pre>\n"
},
{
"answer_id": 41549607,
"author": "Saurya Man Patel",
"author_id": 6538142,
"author_profile": "https://Stackoverflow.com/users/6538142",
"pm_score": 2,
"selected": false,
"text": "<p>Except dir(module) or help(module) mentioned in previous answers, you can also try:<br>\n - Open ipython <br>\n - import module_name <br>\n - type module_name, press tab. It'll open a small window with listing all functions in the python module. <br>\nIt looks very neat. <br></p>\n\n<p>Here is snippet listing all functions of hashlib module</p>\n\n<pre><code>(C:\\Program Files\\Anaconda2) C:\\Users\\lenovo>ipython\nPython 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]\nType \"copyright\", \"credits\" or \"license\" for more information.\n\nIPython 5.1.0 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython's features.\n%quickref -> Quick reference.\nhelp -> Python's own help system.\nobject? -> Details about 'object', use 'object??' for extra details.\n\nIn [1]: import hashlib\n\nIn [2]: hashlib.\n hashlib.algorithms hashlib.new hashlib.sha256\n hashlib.algorithms_available hashlib.pbkdf2_hmac hashlib.sha384\n hashlib.algorithms_guaranteed hashlib.sha1 hashlib.sha512\n hashlib.md5 hashlib.sha224\n</code></pre>\n"
},
{
"answer_id": 46105518,
"author": "Cireo",
"author_id": 2284490,
"author_profile": "https://Stackoverflow.com/users/2284490",
"pm_score": 5,
"selected": false,
"text": "<p>For code that you <strong>do not wish to evaluate</strong>, I recommend an AST-based approach (like <a href=\"https://stackoverflow.com/users/21028/csl\">csl</a>'s answer), e.g.:</p>\n<pre><code>import ast\n\nsource = open(<filepath_to_parse>).read()\nfunctions = [f.name for f in ast.parse(source).body\n if isinstance(f, ast.FunctionDef)]\n</code></pre>\n<p>For <strong>everything else</strong>, the inspect module is correct:</p>\n<pre><code>import inspect\n\nimport <module_to_inspect> as module\n\nfunctions = inspect.getmembers(module, inspect.isfunction)\n</code></pre>\n<p>This gives a list of 2-tuples in the form <code>[(<name:str>, <value:function>), ...]</code>.</p>\n<p>The simple answer above is hinted at in various responses and comments, but not called out explicitly.</p>\n"
},
{
"answer_id": 49490170,
"author": "Xantium",
"author_id": 8372104,
"author_profile": "https://Stackoverflow.com/users/8372104",
"pm_score": 4,
"selected": false,
"text": "<p>For global functions <code>dir()</code> is the command to use (as mentioned in most of these answers), however this lists both public functions and non-public functions together. </p>\n\n<p>For example running:</p>\n\n<pre><code>>>> import re\n>>> dir(re)\n</code></pre>\n\n<p>Returns functions/classes like:</p>\n\n<pre><code>'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'\n</code></pre>\n\n<p>Some of which are not generally meant for general programming use (but by the module itself, except in the case of DunderAliases like <code>__doc__</code>, <code>__file__</code> ect). For this reason it may not be useful to list them with the public ones (this is how Python knows what to get when using <code>from module import *</code>).</p>\n\n<p><code>__all__</code> could be used to solve this problem, it returns a list of all the public functions and classes in a module (those that <em>do not</em> start with underscores - <code>_</code>). See \n<a href=\"https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python\">Can someone explain __all__ in Python?</a> for the use of <code>__all__</code>.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>>>> import re\n>>> re.__all__\n['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']\n>>>\n</code></pre>\n\n<p>All the functions and classes with underscores have been removed, leaving only those that are defined as public and can therefore be used via <code>import *</code>.</p>\n\n<p>Note that <code>__all__</code> is not always defined. If it is not included then an <code>AttributeError</code> is raised. </p>\n\n<p>A case of this is with the ast module:</p>\n\n<pre><code>>>> import ast\n>>> ast.__all__\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: module 'ast' has no attribute '__all__'\n>>>\n</code></pre>\n"
},
{
"answer_id": 52351591,
"author": "Manish Kumar",
"author_id": 6436791,
"author_profile": "https://Stackoverflow.com/users/6436791",
"pm_score": 1,
"selected": false,
"text": "<p>This will append all the functions that are defined in your_module in a list.</p>\n\n<pre><code>result=[]\nfor i in dir(your_module):\n if type(getattr(your_module, i)).__name__ == \"function\":\n result.append(getattr(your_module, i))\n</code></pre>\n"
},
{
"answer_id": 60745386,
"author": "eid",
"author_id": 8549873,
"author_profile": "https://Stackoverflow.com/users/8549873",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import sys\nfrom inspect import getmembers, isfunction\nfcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]\n</code></pre>\n"
},
{
"answer_id": 60968677,
"author": "Julien Faujanet",
"author_id": 12419998,
"author_profile": "https://Stackoverflow.com/users/12419998",
"pm_score": 2,
"selected": false,
"text": "<pre><code>r = globals()\nsep = '\\n'+100*'*'+'\\n' # To make it clean to read.\nfor k in list(r.keys()):\n try:\n if str(type(r[k])).count('function'):\n print(sep+k + ' : \\n' + str(r[k].__doc__))\n except Exception as e:\n print(e)\n</code></pre>\n\n<hr>\n\n<p>Output :</p>\n\n<pre><code>******************************************************************************************\nGetNumberOfWordsInTextFile : \n\n Calcule et retourne le nombre de mots d'un fichier texte\n :param path_: le chemin du fichier à analyser\n :return: le nombre de mots du fichier\n\n******************************************************************************************\n\n write_in : \n\n Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode a,\n :param path_: le path du fichier texte\n :param data_: la liste des données à écrire ou un bloc texte directement\n :return: None\n\n\n ******************************************************************************************\n write_in_as_w : \n\n Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode w,\n :param path_: le path du fichier texte\n :param data_: la liste des données à écrire ou un bloc texte directement\n :return: None\n</code></pre>\n"
},
{
"answer_id": 63268485,
"author": "Karthik Nandula",
"author_id": 7130405,
"author_profile": "https://Stackoverflow.com/users/7130405",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://docs.python.org/3/tutorial/modules.html#the-dir-function\" rel=\"nofollow noreferrer\">Python documentation</a> provides the perfect solution for this which uses the built-in function <code>dir</code>.</p>\n<p>You can just use <em>dir(module_name)</em> and then it will return a list of the functions within that module.</p>\n<p>For example, <em>dir(time)</em> will return</p>\n<p><code>['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']</code></p>\n<p>which is the list of functions the 'time' module contains.</p>\n"
},
{
"answer_id": 65308505,
"author": "Boris Verkhovskiy",
"author_id": 3064538,
"author_profile": "https://Stackoverflow.com/users/3064538",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>vars(module)</code> then filter out anything that isn't a function using <a href=\"https://docs.python.org/3/library/inspect.html#inspect.isfunction\" rel=\"nofollow noreferrer\"><code>inspect.isfunction</code></a>:</p>\n<pre><code>import inspect\nimport my_module\n\nmy_module_functions = [f for _, f in vars(my_module).values() if inspect.isfunction(f)]\n</code></pre>\n<p>The advantage of <a href=\"https://docs.python.org/3/library/functions.html#vars\" rel=\"nofollow noreferrer\"><code>vars</code></a> over <a href=\"https://docs.python.org/3/library/functions.html#dir\" rel=\"nofollow noreferrer\"><code>dir</code></a> or <a href=\"https://docs.python.org/3/library/inspect.html#inspect.getmembers\" rel=\"nofollow noreferrer\"><code>inspect.getmembers</code></a> is that it returns the functions in the order they were defined instead of sorted alphabetically.</p>\n<p>Also, this will include functions that are imported by <code>my_module</code>, if you want to filter those out to get only functions that are defined in <code>my_module</code>, see my question <a href=\"https://stackoverflow.com/questions/65251833/get-all-defined-functions-in-python-module\">Get all defined functions in Python module</a>.</p>\n"
},
{
"answer_id": 65745550,
"author": "Guimoute",
"author_id": 9282844,
"author_profile": "https://Stackoverflow.com/users/9282844",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to get the list of all the functions defined in the <strong>current file</strong>, you can do it that way:</p>\n<pre><code># Get this script's name.\nimport os\nscript_name = os.path.basename(__file__).rstrip(".py")\n\n# Import it from its path so that you can use it as a Python object.\nimport importlib.util\nspec = importlib.util.spec_from_file_location(script_name, __file__)\nx = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(x)\n\n# List the functions defined in it.\nfrom inspect import getmembers, isfunction\nlist_of_functions = getmembers(x, isfunction)\n</code></pre>\n<p>As an application example, I use that for calling all the functions defined in my unit testing scripts.</p>\n<p>This is a combination of codes adapted from the answers of <a href=\"https://stackoverflow.com/a/139198/9282844\">Thomas Wouters</a> and <a href=\"https://stackoverflow.com/a/9794849/9282844\">adrian</a> here, and from <a href=\"https://stackoverflow.com/a/67692/9282844\">Sebastian Rittau</a> on a different question.</p>\n"
},
{
"answer_id": 67014346,
"author": "Josh Peak",
"author_id": 622276,
"author_profile": "https://Stackoverflow.com/users/622276",
"pm_score": 3,
"selected": false,
"text": "<h1>Finding the names (and callable objects) in the current script <code>__main__</code></h1>\n<p>I was trying to create a standalone python script that used only the standard library to find functions in the current file with the prefix <code>task_</code> to create a minimal homebrewed version of what <code>npm run</code> provides.</p>\n<h2>TL;DR</h2>\n<p>If you are running a standalone script you want to run <code>inspect.getmembers</code> on the <code>module</code> which is defined in <code>sys.modules['__main__']</code>. Eg,</p>\n<pre class=\"lang-py prettyprint-override\"><code>inspect.getmembers(sys.modules['__main__'], inspect.isfunction)\n</code></pre>\n<p>But I wanted to filter the list of methods by prefix and strip the prefix to create a lookup dictionary.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _inspect_tasks():\n import inspect\n return { f[0].replace('task_', ''): f[1] \n for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)\n if f[0].startswith('task_')\n }\n</code></pre>\n<p>Example Output:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>{\n 'install': <function task_install at 0x105695940>,\n 'dev': <function task_dev at 0x105695b80>,\n 'test': <function task_test at 0x105695af0>\n}\n</code></pre>\n<h2>Longer Version</h2>\n<p>I wanted the names of the methods to define CLI task names without having to repeat myself.</p>\n<h3><code>./tasks.py</code></h3>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\nimport sys\nfrom subprocess import run\n\ndef _inspect_tasks():\n import inspect\n return { f[0].replace('task_', ''): f[1] \n for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)\n if f[0].startswith('task_')\n }\n\ndef _cmd(command, args):\n return run(command.split(" ") + args)\n\ndef task_install(args):\n return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)\n\ndef task_test(args):\n return _cmd("python3 -m pytest", args)\n\ndef task_dev(args):\n return _cmd("uvicorn api.v1:app", args)\n\nif __name__ == "__main__":\n tasks = _inspect_tasks()\n\n if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():\n tasks[sys.argv[1]](sys.argv[2:])\n else:\n print(f"Must provide a task from the following: {list(tasks.keys())}")\n</code></pre>\n<p>Example no arguments:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>λ ./tasks.py\nMust provide a task from the following: ['install', 'dev', 'test']\n</code></pre>\n<p>Example running test with extra arguments:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>λ ./tasks.py test -qq\ns.ssss.sF..Fs.sssFsss..ssssFssFs....s.s \n</code></pre>\n<p>You get the point. As my projects get more and more involved, it's going to be easier to keep a script up to date than to keep the README up to date and I can abstract it down to just:</p>\n<pre><code>./tasks.py install\n./tasks.py dev\n./tasks.py test\n./tasks.py publish\n./tasks.py logs\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6527/"
]
| I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the `help` function on each one. In Ruby I can do something like `ClassName.methods` to get a list of all the methods available on that class. Is there something similar in Python?
e.g. something like:
```
from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
``` | Use the [`inspect`](https://docs.python.org/3/library/inspect.html) module:
```
from inspect import getmembers, isfunction
from somemodule import foo
print(getmembers(foo, isfunction))
```
Also see the [`pydoc`](https://docs.python.org/3/library/pydoc.html) module, the `help()` function in the interactive interpreter and the `pydoc` command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk. |
139,199 | <p>I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code:</p>
<pre><code>sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'"
</code></pre>
<p>Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command. </p>
<p>We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in.</p>
<p>I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice. </p>
<p>What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful.</p>
<hr/>
<p>UPDATE:</p>
<p>I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it.</p>
<p>And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string.</p>
<p>I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.</p>
| [
{
"answer_id": 139215,
"author": "Rob",
"author_id": 18505,
"author_profile": "https://Stackoverflow.com/users/18505",
"pm_score": -1,
"selected": false,
"text": "<p>It might work, but it seems a little hokey to me. I'd recommend verifing that each string is valid by testing it against a regular expression instead.</p>\n"
},
{
"answer_id": 139218,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": -1,
"selected": false,
"text": "<p>While you might find a solution that works for strings, for numerical predicates you need to also make sure they're only passing in numbers (simple check is can it be parsed as int/double/decimal?).</p>\n\n<p>It's a lot of extra work.</p>\n"
},
{
"answer_id": 139219,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 3,
"selected": false,
"text": "<p>It's a bad idea anyway as you seem to know.</p>\n\n<p>What about something like escaping the quote in string like this: \\'</p>\n\n<p>Your replace would result in: \\''</p>\n\n<p>If the backslash escapes the first quote, then the second quote has ended the string.</p>\n"
},
{
"answer_id": 139221,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 1,
"selected": false,
"text": "<p>What ugly code all that sanitisation of user input would be! Then the clunky StringBuilder for the SQL statement. The prepared statement method results in much cleaner code, and the SQL Injection benefits are a really nice addition.</p>\n\n<p>Also why reinvent the wheel?</p>\n"
},
{
"answer_id": 139235,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than changing a single quote to (what looks like) two single quotes, why not just change it to an apostrophe, a quote, or remove it entirely?</p>\n\n<p>Either way, it's a bit of a kludge... especially when you legitimately have things (like names) which may use single quotes...</p>\n\n<p>NOTE: Your method also assumes everyone working on your app always remembers to sanitize input before it hits the database, which probably isn't realistic most of the time.</p>\n"
},
{
"answer_id": 139247,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>If you have parameterised queries available you should be using them at all times. All it takes is for one query to slip through the net and your DB is at risk.</p>\n"
},
{
"answer_id": 139264,
"author": "tom.dietrich",
"author_id": 15769,
"author_profile": "https://Stackoverflow.com/users/15769",
"pm_score": 3,
"selected": false,
"text": "<p>Input sanitation is not something you want to half-ass. Use your whole ass. Use regular expressions on text fields. TryCast your numerics to the proper numeric type, and report a validation error if it doesn't work. It is very easy to search for attack patterns in your input, such as ' --. Assume all input from the user is hostile.</p>\n"
},
{
"answer_id": 139270,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 5,
"selected": false,
"text": "<p>In a nutshell: Never do query escaping yourself. You're bound to get something wrong. Instead, use parameterized queries, or if you can't do that for some reason, use an existing library that does this for you. There's no reason to be doing it yourself.</p>\n"
},
{
"answer_id": 139274,
"author": "Pontus Gagge",
"author_id": 20402,
"author_profile": "https://Stackoverflow.com/users/20402",
"pm_score": 4,
"selected": false,
"text": "<p>I've used this technique when dealing with 'advanced search' functionality, where building a query from scratch was the only viable answer. (Example: allow the user to search for products based on an unlimited set of constraints on product attributes, displaying columns and their permitted values as GUI controls to reduce the learning threshold for users.)</p>\n\n<p>In itself it is safe AFAIK. As another answerer pointed out, however, you may also need to deal with backspace escaping (albeit not when passing the query to SQL Server using ADO or ADO.NET, at least -- can't vouch for all databases or technologies). </p>\n\n<p>The snag is that you really have to be certain which strings contain user input (always potentially malicious), and which strings are valid SQL queries. One of the traps is if you use values from the database -- were those values originally user-supplied? If so, they must also be escaped. My answer is to try to sanitize as late as possible (but no later!), when constructing the SQL query. </p>\n\n<p>However, in most cases, parameter binding is the way to go -- it's just simpler. </p>\n"
},
{
"answer_id": 139810,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 8,
"selected": true,
"text": "<p>First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy.<br>\nWorse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always be done.<br>\nSome research papers on the subject:</p>\n\n<ul>\n<li><a href=\"http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf\" rel=\"noreferrer\">http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf</a></li>\n<li><a href=\"http://www.it-docs.net/ddata/4954.pdf\" rel=\"noreferrer\">http://www.it-docs.net/ddata/4954.pdf</a> (Disclosure, this last one was mine ;) )</li>\n<li><a href=\"https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf\" rel=\"noreferrer\">https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf</a> (based on the previous paper, which is no longer available)</li>\n</ul>\n\n<p>Point is, any blacklist you do (and too-permissive whitelists) can be bypassed. The last link to my paper shows situations where even quote escaping can be bypassed. </p>\n\n<p>Even if these situations do not apply to you, it's still a bad idea. Moreover, unless your app is trivially small, you're going to have to deal with maintenance, and maybe a certain amount of governance: how do you ensure that its done right, everywhere all the time?</p>\n\n<p>The proper way to do it:</p>\n\n<ul>\n<li>Whitelist validation: type, length, format or accepted values</li>\n<li>If you want to blacklist, go right ahead. Quote escaping is good, but within context of the other mitigations.</li>\n<li>Use Command and Parameter objects, to preparse and validate</li>\n<li>Call parameterized queries only.</li>\n<li>Better yet, use Stored Procedures exclusively. </li>\n<li>Avoid using dynamic SQL, and dont use string concatenation to build queries.</li>\n<li>If using SPs, you can also limit permissions in the database to executing the needed SPs only, and not access tables directly. </li>\n<li>you can also easily verify that the entire codebase only accesses the DB through SPs...</li>\n</ul>\n"
},
{
"answer_id": 141445,
"author": "Invalid Character",
"author_id": 9610,
"author_profile": "https://Stackoverflow.com/users/9610",
"pm_score": 3,
"selected": false,
"text": "<p>Simple answer: It will work sometimes, but not all the time.\nYou want to use white-list validation on <strong>everything</strong> you do, but I realize that's not always possible, so you're forced to go with the best guess blacklist. Likewise, you want to use parametrized stored procs in <strong>everything</strong>, but once again, that's not always possible, so you're forced to use sp_execute with parameters.</p>\n\n<p>There are ways around any usable blacklist you can come up with (and some whitelists too).</p>\n\n<p>A decent writeup is here: <a href=\"http://www.owasp.org/index.php/Top_10_2007-A2\" rel=\"noreferrer\">http://www.owasp.org/index.php/Top_10_2007-A2</a></p>\n\n<p>If you need to do this as a quick fix to give you time to get a real one in place, do it. But don't think you're safe.</p>\n"
},
{
"answer_id": 150101,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 3,
"selected": false,
"text": "<p>There are two ways to do it, no exceptions, to be safe from SQL-injections; prepared statements or prameterized stored procedures.</p>\n"
},
{
"answer_id": 219992,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>Yeah, that should work right up until someone runs <a href=\"http://msdn.microsoft.com/en-us/library/ms174393.aspx\" rel=\"nofollow noreferrer\">SET QUOTED_IDENTIFIER OFF</a> and uses a double quote on you.</p>\n<p>Edit: It isn't as simple as not allowing the malicious user to turn off quoted identifiers:</p>\n<blockquote>\n<p>The SQL Server Native Client ODBC driver and SQL Server Native Client OLE DB Provider for SQL Server automatically set QUOTED_IDENTIFIER to ON when connecting. This can be configured in ODBC data sources, in ODBC connection attributes, or OLE DB connection properties. <b>The default for SET QUOTED_IDENTIFIER is OFF for connections from DB-Library applications.</b></p>\n<p>When a stored procedure is created, the <b>SET QUOTED_IDENTIFIER and SET ANSI_NULLS settings are captured and used for subsequent invocations of that stored procedure</b>.</p>\n<p>SET QUOTED_IDENTIFIER also <b>corresponds to the QUOTED_IDENTIFER setting of ALTER DATABASE.</b></p>\n<p>SET QUOTED_IDENTIFIER is <b>set at parse time</b>. Setting at parse time means that if the SET statement is present in the batch or stored procedure, it takes effect, regardless of whether code execution actually reaches that point; and the SET statement takes effect before any statements are executed.</p>\n</blockquote>\n<p>There's a lot of ways QUOTED_IDENTIFIER could be off without you necessarily knowing it. Admittedly - this isn't the smoking gun exploit you're looking for, but it's a pretty big attack surface. Of course, if you also escaped double quotes - then we're back where we started. ;)</p>\n"
},
{
"answer_id": 225813,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<p>Your defence would fail if: </p>\n\n<ul>\n<li>the query is expecting a number rather than a string</li>\n<li>there were any other way to represent a single quotation mark, including: \n\n<ul>\n<li>an escape sequence such as \\039 </li>\n<li>a unicode character </li>\n</ul></li>\n</ul>\n\n<p>(in the latter case, it would have to be something which were expanded only after you've done your replace)</p>\n"
},
{
"answer_id": 291198,
"author": "Rob Kraft",
"author_id": 37749,
"author_profile": "https://Stackoverflow.com/users/37749",
"pm_score": 2,
"selected": false,
"text": "<p>Patrick, are you adding single quotes around ALL input, even numeric input? If you have numeric input, but are not putting the single quotes around it, then you have an exposure.</p>\n"
},
{
"answer_id": 376674,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 5,
"selected": false,
"text": "<p>Okay, this response will relate to the update of the question: </p>\n\n<blockquote>\n <p>\"If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.\"</p>\n</blockquote>\n\n<p>Now, besides the MySQL backslash escaping - and taking into account that we're actually talking about MSSQL, there are actually 3 possible ways of still SQL injecting your code</p>\n\n<blockquote>\n <p>sSanitizedInput = \"'\" & Replace(sInput, \"'\", \"''\") & \"'\"</p>\n</blockquote>\n\n<p>Take into account that these will not all be valid at all times, and are very dependant on your actual code around it:</p>\n\n<ol>\n<li>Second-order SQL Injection - if an SQL query is rebuilt based upon data retrieved from the database <strong>after escaping</strong>, the data is concatenated unescaped and may be indirectly SQL-injected. See </li>\n<li>String truncation - (a bit more complicated) - Scenario is you have two fields, say a username and password, and the SQL concatenates both of them. And both fields (or just the first) has a hard limit on length. For instance, the username is limited to 20 characters. Say you have this code:</li>\n</ol>\n\n<blockquote>\n<pre><code>username = left(Replace(sInput, \"'\", \"''\"), 20)\n</code></pre>\n</blockquote>\n\n<p>Then what you get - is the username, escaped, and then trimmed to 20 characters. The problem here - I'll stick my quote in the 20th character (e.g. after 19 a's), and your escaping quote will be trimmed (in the 21st character). Then the SQL</p>\n\n<pre><code>sSQL = \"select * from USERS where username = '\" + username + \"' and password = '\" + password + \"'\"\n</code></pre>\n\n<p>combined with the aforementioned malformed username will result in the password already being <em>outside</em> the quotes, and will just contain the payload directly.<br>\n 3. Unicode Smuggling - In certain situations, it is possible to pass a high-level unicode character that <em>looks</em> like a quote, but <em>isn't</em> - until it gets to the database, where suddenly <em>it is</em>. Since it isn't a quote when you validate it, it will go through easy... See my previous response for more details, and link to original research.</p>\n"
},
{
"answer_id": 564766,
"author": "Jørn Jensen",
"author_id": 34585,
"author_profile": "https://Stackoverflow.com/users/34585",
"pm_score": 4,
"selected": false,
"text": "<p>I realize this is a long time after the question was asked, but ..</p>\n\n<p>One way to launch an attack on the 'quote the argument' procedure is with string truncation.\nAccording to MSDN, in SQL Server 2000 SP4 (and SQL Server 2005 SP1), a too long string will be quietly truncated. </p>\n\n<p>When you quote a string, the string increases in size. Every apostrophe is repeated.\nThis can then be used to push parts of the SQL outside the buffer. So you could effectively trim away parts of a where clause.</p>\n\n<p>This would probably be mostly useful in a 'user admin' page scenario where you could abuse the 'update' statement to not do all the checks it was supposed to do.</p>\n\n<p>So if you decide to quote all the arguments, make sure you know what goes on with the string sizes and see to it that you don't run into truncation.</p>\n\n<p>I would recommend going with parameters. Always. Just wish I could enforce that in the database. And as a side effect, you are more likely to get better cache hits because more of the statements look the same. (This was certainly true on Oracle 8)</p>\n"
},
{
"answer_id": 35529646,
"author": "miroxlav",
"author_id": 2392157,
"author_profile": "https://Stackoverflow.com/users/2392157",
"pm_score": -1,
"selected": false,
"text": "<h1>Yes, you can, if...</h1>\n\n<p>After studying the topic, I think input sanitized as you suggested is safe, but only under these rules:</p>\n\n<ol>\n<li><p>you never allow string values coming from users to become anything else than string literals (i.e. avoid giving configuration option: \"Enter additional SQL column names/expressions here:\"). Value types other than strings (numbers, dates, ...): convert them to their native data types and provide a routine for SQL literal from each data type.</p>\n\n<ul>\n<li>SQL statements are problematic to validate</li>\n</ul></li>\n<li><p>you either use <code>nvarchar</code>/<code>nchar</code> columns (and prefix string literals with <code>N</code>) OR limit values going into <code>varchar</code>/<code>char</code> columns to ASCII characters only (e.g. throw exception when creating SQL statement)</p>\n\n<ul>\n<li>this way you will be avoiding automatic apostrophe conversion from CHAR(700) to CHAR(39) (and maybe other similar Unicode hacks)</li>\n</ul></li>\n<li><p>you always validate value length to fit actual column length (throw exception if longer)</p>\n\n<ul>\n<li>there was a known defect in SQL Server allowing to bypass SQL error thrown on truncation (leading to silent truncation)</li>\n</ul></li>\n<li><p>you ensure that <code>SET QUOTED_IDENTIFIER</code> is always <code>ON</code></p>\n\n<ul>\n<li>beware, it is taken into effect in parse-time, i.e. even in inaccessible sections of code</li>\n</ul></li>\n</ol>\n\n<p>Complying with these 4 points, you should be safe. If you violate any of them, a way for SQL injection opens.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22392/"
]
| I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code:
```
sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'"
```
Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command.
We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in.
I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice.
What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful.
---
UPDATE:
I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it.
And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string.
I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it. | First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy.
Worse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always be done.
Some research papers on the subject:
* <http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf>
* <http://www.it-docs.net/ddata/4954.pdf> (Disclosure, this last one was mine ;) )
* <https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf> (based on the previous paper, which is no longer available)
Point is, any blacklist you do (and too-permissive whitelists) can be bypassed. The last link to my paper shows situations where even quote escaping can be bypassed.
Even if these situations do not apply to you, it's still a bad idea. Moreover, unless your app is trivially small, you're going to have to deal with maintenance, and maybe a certain amount of governance: how do you ensure that its done right, everywhere all the time?
The proper way to do it:
* Whitelist validation: type, length, format or accepted values
* If you want to blacklist, go right ahead. Quote escaping is good, but within context of the other mitigations.
* Use Command and Parameter objects, to preparse and validate
* Call parameterized queries only.
* Better yet, use Stored Procedures exclusively.
* Avoid using dynamic SQL, and dont use string concatenation to build queries.
* If using SPs, you can also limit permissions in the database to executing the needed SPs only, and not access tables directly.
* you can also easily verify that the entire codebase only accesses the DB through SPs... |
139,212 | <p>I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail.</p>
<p>How can I add cookies from a Python CookieJar to ZSI requests?</p>
| [
{
"answer_id": 145610,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": true,
"text": "<p>If you read the <a href=\"https://pywebsvcs.svn.sourceforge.net/svnroot/pywebsvcs/trunk/zsi/ZSI/client.py\" rel=\"nofollow noreferrer\">_Binding class in client.py of ZSI</a> you can see that it has a variable cookies, which is an instance of <a href=\"http://docs.python.org/lib/module-Cookie.html\" rel=\"nofollow noreferrer\">Cookie.SimpleCookie</a>. Following the <a href=\"http://pywebsvcs.sourceforge.net/zsi.html#SECTION003210000000000000000\" rel=\"nofollow noreferrer\">ZSI example</a> and the <a href=\"http://docs.python.org/lib/cookie-example.html\" rel=\"nofollow noreferrer\">Cookie example</a> that is how it should work:</p>\n\n<pre><code>b = Binding(url='/cgi-bin/simple-test', tracefile=fp)\nb.cookies['foo'] = 'bar'\n</code></pre>\n"
},
{
"answer_id": 148379,
"author": "danivovich",
"author_id": 17583,
"author_profile": "https://Stackoverflow.com/users/17583",
"pm_score": 0,
"selected": false,
"text": "<p>Additionally, the Binding class also allows any header to be added. So I figured out that I can just add a \"Cookie\" header for each cookie I need to add. This worked well for the code generated by wsdl2py, just adding the cookies right after the binding is formed in the SOAP client class. Adding a parameter to the generated class to take in the cookies as a dictionary is easy and then they can easily be iterated through and added.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17583/"
]
| I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail.
How can I add cookies from a Python CookieJar to ZSI requests? | If you read the [\_Binding class in client.py of ZSI](https://pywebsvcs.svn.sourceforge.net/svnroot/pywebsvcs/trunk/zsi/ZSI/client.py) you can see that it has a variable cookies, which is an instance of [Cookie.SimpleCookie](http://docs.python.org/lib/module-Cookie.html). Following the [ZSI example](http://pywebsvcs.sourceforge.net/zsi.html#SECTION003210000000000000000) and the [Cookie example](http://docs.python.org/lib/cookie-example.html) that is how it should work:
```
b = Binding(url='/cgi-bin/simple-test', tracefile=fp)
b.cookies['foo'] = 'bar'
``` |
139,214 | <p>The most egregiously redundant code construct I often see involves using the code sequence</p>
<pre><code>if (condition)
return true;
else
return false;
</code></pre>
<p>instead of simply writing</p>
<pre><code>return (condition);
</code></pre>
<p>I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?</p>
| [
{
"answer_id": 139231,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 2,
"selected": false,
"text": "<p>Returning uselessly at the end:</p>\n\n<pre><code> // stuff\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 139237,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 2,
"selected": false,
"text": "<p>Using .tostring on a string</p>\n"
},
{
"answer_id": 139249,
"author": "Otherside",
"author_id": 18697,
"author_profile": "https://Stackoverflow.com/users/18697",
"pm_score": 3,
"selected": false,
"text": "<pre><code>if (condition == true)\n{\n ...\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (condition)\n{\n ...\n}\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>or even worse and turning around the conditional test:</p>\n\n<pre><code>if (condition == false)\n{\n ...\n}\n</code></pre>\n\n<p>which is easily read as</p>\n\n<pre><code>if (condition) then ...\n</code></pre>\n"
},
{
"answer_id": 139263,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 4,
"selected": false,
"text": "<pre><code>if (foo == true)\n{\n do stuff\n}\n</code></pre>\n\n<p>I keep telling the developer that does that that it should be</p>\n\n<pre><code>if ((foo == true) == true)\n{\n do stuff\n}\n</code></pre>\n\n<p>but he hasn't gotten the hint yet.</p>\n"
},
{
"answer_id": 139284,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<pre><code>void myfunction() {\n if(condition) {\n // Do some stuff\n if(othercond) {\n // Do more stuff\n }\n }\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>void myfunction() {\n if(!condition)\n return;\n\n // Do some stuff\n\n if(!othercond)\n return;\n\n // Do more stuff\n}\n</code></pre>\n"
},
{
"answer_id": 139320,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 2,
"selected": false,
"text": "<p>I once had a guy who repeatedly did this:</p>\n\n<pre><code>bool a;\nbool b;\n...\nif (a == true)\n b = true;\nelse\n b = false;\n</code></pre>\n"
},
{
"answer_id": 139337,
"author": "Otherside",
"author_id": 18697,
"author_profile": "https://Stackoverflow.com/users/18697",
"pm_score": 2,
"selected": false,
"text": "<p>Putting an <code>exit</code> statement as first statement in a function to disable the execution of that function, instead of one of the following options:</p>\n\n<ul>\n<li>Completely removing the function</li>\n<li>Commenting the function body</li>\n<li>Keeping the function but deleting all the code</li>\n</ul>\n\n<p>Using the <code>exit</code> as first statement makes it very hard to spot, you can easily read over it.</p>\n"
},
{
"answer_id": 139347,
"author": "RossFabricant",
"author_id": 20754,
"author_profile": "https://Stackoverflow.com/users/20754",
"pm_score": 2,
"selected": false,
"text": "<p>Declaring separately from assignment in languages other than C: </p>\n\n<pre><code>int foo; \nfoo = GetFoo();\n</code></pre>\n"
},
{
"answer_id": 139367,
"author": "RossFabricant",
"author_id": 20754,
"author_profile": "https://Stackoverflow.com/users/20754",
"pm_score": 3,
"selected": false,
"text": "<p>Using comments instead of source control:<br>\n-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.<br>\n-Adding comments like \"RWF Change\" instead of just making the change and letting source control assign the blame. </p>\n"
},
{
"answer_id": 139395,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 3,
"selected": false,
"text": "<p>Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:</p>\n\n<pre><code>return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);\n</code></pre>\n\n<p>:-)</p>\n"
},
{
"answer_id": 139399,
"author": "ComSubVie",
"author_id": 15709,
"author_profile": "https://Stackoverflow.com/users/15709",
"pm_score": 1,
"selected": false,
"text": "<p>I often run into the following:</p>\n\n<pre><code>function foo() {\n if ( something ) {\n return;\n } else {\n do_something();\n }\n}\n</code></pre>\n\n<p>But it doesn't help telling them that the else is useless here. It has to be either</p>\n\n<pre><code>function foo() {\n if ( something ) {\n return;\n }\n do_something();\n}\n</code></pre>\n\n<p>or - depending on the length of checks that are done before do_something():</p>\n\n<pre><code>function foo() {\n if ( !something ) {\n do_something();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 139420,
"author": "RossFabricant",
"author_id": 20754,
"author_profile": "https://Stackoverflow.com/users/20754",
"pm_score": 0,
"selected": false,
"text": "<p>Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower. </p>\n"
},
{
"answer_id": 139424,
"author": "PiedPiper",
"author_id": 19315,
"author_profile": "https://Stackoverflow.com/users/19315",
"pm_score": 2,
"selected": false,
"text": "<p>Redundant code is not in itself an error. But if you're really trying to save every character</p>\n\n<pre><code>return (condition);\n</code></pre>\n\n<p>is redundant too. You can write:</p>\n\n<pre><code>return condition;\n</code></pre>\n"
},
{
"answer_id": 139435,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "<p>Fear of null (this also can lead to serious problems):</p>\n\n<pre><code>if (name != null)\n person.Name = name;\n</code></pre>\n\n<p>Redundant if's (not using else):</p>\n\n<pre><code>if (!IsPostback)\n{\n // do something\n}\nif (IsPostback)\n{\n // do something else\n}\n</code></pre>\n\n<p>Redundant checks (Split never returns null):</p>\n\n<pre><code>string[] words = sentence.Split(' ');\nif (words != null)\n</code></pre>\n\n<p>More on checks (the second check is redundant if you are going to loop)</p>\n\n<pre><code>if (myArray != null && myArray.Length > 0)\n foreach (string s in myArray)\n</code></pre>\n\n<p>And my favorite for ASP.NET: Scattered <code>DataBind</code>s all over the code in order to make the page render. </p>\n"
},
{
"answer_id": 139548,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "<p>Copy paste redundancy:</p>\n\n<pre><code>if (x > 0)\n{\n // a lot of code to calculate z\n y = x + z;\n}\nelse\n{\n // a lot of code to calculate z\n y = x - z;\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (x > 0)\n y = x + CalcZ(x);\nelse\n y = x - CalcZ(x);\n</code></pre>\n\n<p>or even better (or more obfuscated)</p>\n\n<pre><code>y = x + (x > 0 ? 1 : -1) * CalcZ(x)\n</code></pre>\n"
},
{
"answer_id": 147843,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 2,
"selected": false,
"text": "<p>Allocating elements on the heap instead of the stack.</p>\n\n<pre><code>{\n char buff = malloc(1024);\n /* ... */\n free(buff);\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>{\n char buff[1024];\n /* ... */\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>{ \n struct foo *x = (struct foo *)malloc(sizeof(struct foo));\n x->a = ...;\n bar(x);\n free(x);\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>{\n struct foo x;\n x.a = ...;\n bar(&x);\n}\n</code></pre>\n"
},
{
"answer_id": 154965,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": false,
"text": "<p>From nightmarish code reviews.....</p>\n\n<pre><code>char s[100];\n</code></pre>\n\n<p>followed by</p>\n\n<pre><code>memset(s,0,100);\n</code></pre>\n\n<p>followed by</p>\n\n<pre><code>s[strlen(s)] = 0;\n</code></pre>\n\n<p>with lots of nasty</p>\n\n<pre><code>if (strcmp(s, \"1\") == 0)\n</code></pre>\n\n<p>littered about the code.</p>\n"
},
{
"answer_id": 162204,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>Redundant .ToString() invocations:</p>\n\n<pre><code>const int foo = 5;\nConsole.WriteLine(\"Number of Items: \" + foo.ToString());\n</code></pre>\n\n<p>Unnecessary string formatting:</p>\n\n<pre><code>const int foo = 5;\nConsole.WriteLine(\"Number of Items: {0}\", foo);\n</code></pre>\n"
},
{
"answer_id": 976141,
"author": "Nat",
"author_id": 99389,
"author_profile": "https://Stackoverflow.com/users/99389",
"pm_score": 2,
"selected": false,
"text": "<p>The most common redundant code construct I see is code that is never called from anywhere in the program. </p>\n\n<p>The other is design patterns used where there is no point in using them. For example, writing \"new BobFactory().createBob()\" everywhere, instead of just writing \"new Bob()\".</p>\n\n<p>Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20520/"
]
| The most egregiously redundant code construct I often see involves using the code sequence
```
if (condition)
return true;
else
return false;
```
instead of simply writing
```
return (condition);
```
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review? | ```
if (foo == true)
{
do stuff
}
```
I keep telling the developer that does that that it should be
```
if ((foo == true) == true)
{
do stuff
}
```
but he hasn't gotten the hint yet. |
139,245 | <p>How to get the relative path in t sql? Take for example a <code>.sql</code> file is located in the folder <code>D:\temp</code>, I want to get path of the file hello.txt in the folder <code>D:\temp\App_Data</code>. How to use the relative path reference?</p>
<p>Let's say I am executing the sql file inside the SQL server management studio.</p>
| [
{
"answer_id": 139431,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 3,
"selected": false,
"text": "<p>The .sql file is just.... a file. It doesn't have any sense of its own location. It's the thing that excutes it (which you didn't specify) that would have a sense of its location, the file's location.</p>\n\n<p>I notice that you mentioned an App_Data folder, so I guess that ASP.NET is involved. If you want to use relative paths in your web app, see MapPath </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx</a></p>\n"
},
{
"answer_id": 139793,
"author": "Tadmas",
"author_id": 3750,
"author_profile": "https://Stackoverflow.com/users/3750",
"pm_score": 2,
"selected": false,
"text": "<p>When T-SQL is executing, it is running in a batch on the server, not on the client machine running Management Studio (or any other SQL client). The client just sends the text contents of the .sql file to the server to be executed. So, unless that file is located on the database server, I highly doubt you're going to be able to interact with it from a SQL script.</p>\n"
},
{
"answer_id": 169730,
"author": "GilM",
"author_id": 10192,
"author_profile": "https://Stackoverflow.com/users/10192",
"pm_score": 4,
"selected": true,
"text": "<p>The server is executing the t-sql. It doesn't know where the client loaded the file from. You'll have to have the path embedded within the script.</p>\n\n<pre><code>DECLARE @RelDir varchar(1000)\nSET @RelDir = 'D:\\temp\\'\n...\n</code></pre>\n\n<p>Perhaps you can programmatically place the path into the SET command within the .sql script file, or perhaps you can use sqlcmd and pass the relative directory in as a variable.</p>\n"
},
{
"answer_id": 7944400,
"author": "bernd_k",
"author_id": 522317,
"author_profile": "https://Stackoverflow.com/users/522317",
"pm_score": 1,
"selected": false,
"text": "<p>The t-sql script is first preprocessed by QueryAnalyzer, SSMS or sqlcmd on the client side. These programs are aware of the file localcation and could easily handle relative pathes similar To Oeacle sqlplus.</p>\n\n<p>Obviously this is just a design decision from Microsoft and I dare say a rather stupid one.</p>\n"
},
{
"answer_id": 15553094,
"author": "Kelly Davis",
"author_id": 1587986,
"author_profile": "https://Stackoverflow.com/users/1587986",
"pm_score": 0,
"selected": false,
"text": "<p>well it's not a Microsoft thing first off... it's an industry standard thing.\nsecond your solution for running T-SQL with a relative path is to use a batch script or something to inject your path statement IE:</p>\n\n<pre><code>@echo OFF\nSETLOCAL DisableDelayedExpansion\nFOR /F \"usebackq delims=\" %%a in (`\"findstr /n ^^ t-SQL.SQL\"`) do (\n set \"var=%%a\"\n SETLOCAL EnableDelayedExpansion\n set \"var=!var:*:=!\"\n set RunLocation=%~dp0\n echo(%~dp0!var! > newsql.sql\n ENDLOCAL\n)\n sqlcmd newsql.sql\n</code></pre>\n\n<p>or something like that anyway </p>\n"
},
{
"answer_id": 26897979,
"author": "mateuscb",
"author_id": 461958,
"author_profile": "https://Stackoverflow.com/users/461958",
"pm_score": 4,
"selected": false,
"text": "<p>I had a similiar problem, and solved it using sqlcmd variables in conjunction with the %CD% pseudo-variable. Took a bit of trial and error to combine all the pieces. But eventually got it all working. This example expects the <code>script.sql</code> file to be in the same directory as the <code>runscript.bat</code>. </p>\n\n<p><strong>runscript.bat</strong></p>\n\n<pre><code>sqlcmd -S .\\SQLINSTANCE -v FullScriptDir=\"%CD%\" -i script.sql -b\n</code></pre>\n\n<p><strong>script.sql</strong></p>\n\n<pre><code>BULK INSERT [dbo].[ValuesFromCSV]\nFROM '$(FullScriptDir)\\values.csv'\nwith\n(\n fieldterminator = ',',\n rowterminator = '\\n'\n)\ngo\n</code></pre>\n"
},
{
"answer_id": 37771241,
"author": "water",
"author_id": 6159495,
"author_profile": "https://Stackoverflow.com/users/6159495",
"pm_score": 1,
"selected": false,
"text": "<p>I tried method from mateuscb's comments.\nI found it can not work ,i do not know why,then I managed after several test.\nIt can work with the script below:</p>\n\n<p><strong>runscript.bat</strong></p>\n\n<pre><code>@set FullScriptDir=%CD%\nsqlcmd -S .\\SQLINSTANCE -i script.sql\n</code></pre>\n\n<p><strong>script.sql</strong></p>\n\n<pre><code>BULK INSERT [dbo].[ValuesFromCSV]\nFROM '$(FullScriptDir)\\values.csv'\nwith\n(\n fieldterminator = ',',\n rowterminator = '\\n'\n)\ngo\n</code></pre>\n\n<p>Just for your information for further discussion.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
| How to get the relative path in t sql? Take for example a `.sql` file is located in the folder `D:\temp`, I want to get path of the file hello.txt in the folder `D:\temp\App_Data`. How to use the relative path reference?
Let's say I am executing the sql file inside the SQL server management studio. | The server is executing the t-sql. It doesn't know where the client loaded the file from. You'll have to have the path embedded within the script.
```
DECLARE @RelDir varchar(1000)
SET @RelDir = 'D:\temp\'
...
```
Perhaps you can programmatically place the path into the SET command within the .sql script file, or perhaps you can use sqlcmd and pass the relative directory in as a variable. |
139,260 | <p>I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). </p>
<p>I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this:</p>
<pre><code>MemoryStream stream = new MemoryStream();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1"));
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument(); //Start doc
</code></pre>
<p>Then I add my Norwegian text like this:</p>
<pre><code>xmlTextWriter.WriteCData(myNorwegianText);
</code></pre>
<p>Then I write the file to disk like this:</p>
<pre><code>FileStream myFile = new FileStream(myPath, FileMode.Create);
StreamWriter sw = new StreamWriter(myFile);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
sw.Write(content);
sw.Flush();
myFile.Flush();
myFile.Close();
</code></pre>
<p>Now the problem is that in the file on this, all the Norwegian characters look funny.</p>
<p>I'm probably doing the above in some stupid way. Any suggestions on how to fix it?</p>
| [
{
"answer_id": 139307,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "<p>Which encoding do you use for displaying the result file? If it is not in ISO-8859-1, it will not display correctly.</p>\n\n<p>Is there a reason to use this specific encoding, instead of for example UTF8?</p>\n"
},
{
"answer_id": 139372,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 5,
"selected": true,
"text": "<p>Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. </p>\n\n<p>If you still want to do the double write, for whatever reason, do one of two things. Either</p>\n\n<ol>\n<li><p>Make sure that the StreamReader and StreamWriter objects you use <em>all</em> use the <em>same</em> encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or</p></li>\n<li><p>Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway.</p></li>\n</ol>\n"
},
{
"answer_id": 139441,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>Both your StreamWriter and your StreamReader are using UTF-8, because you're not specifying the encoding. That's why things are getting corrupted.</p>\n\n<p>As tomasr said, using a FileStream to start with would be simpler - but also MemoryStream has the handy \"WriteTo\" method which lets you copy it to a FileStream very easily.</p>\n\n<p>I hope you've got a using statement in your real code, by the way - you don't want to leave your file handle open if something goes wrong while you're writing to it.</p>\n\n<p>Jon</p>\n"
},
{
"answer_id": 139612,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 3,
"selected": false,
"text": "<p>You need to set the encoding everytime you write a string or read binary data as a string.</p>\n\n<pre><code> Encoding encoding = Encoding.GetEncoding(\"ISO-8859-1\");\n\n FileStream myFile = new FileStream(myPath, FileMode.Create);\n StreamWriter sw = new StreamWriter(myFile, encoding);\n\n stream.Position = 0;\n StreamReader sr = new StreamReader(stream, encoding);\n string content = sr.ReadToEnd();\n\n sw.Write(content);\n sw.Flush();\n\n myFile.Flush();\n myFile.Close();\n</code></pre>\n"
},
{
"answer_id": 13536234,
"author": "Troy Alford",
"author_id": 1454806,
"author_profile": "https://Stackoverflow.com/users/1454806",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned in above answers, the biggest issue here is the <code>Encoding</code>, which is being defaulted due to being unspecified.</p>\n\n<p>When you do not specify an <code>Encoding</code> for this kind of conversion, the default of <code>UTF-8</code> is used - which may or may not match your scenario. You are also converting the data needlessly by pushing it into a <code>MemoryStream</code> and then out into a <code>FileStream</code>.</p>\n\n<p>If your original data is not <code>UTF-8</code>, what will happen here is that the first transition into the <code>MemoryStream</code> will attempt to decode using default <code>Encoding</code> of <code>UTF-8</code> - and corrupt your data as a result. When you then write out to the <code>FileStream</code>, which is also using <code>UTF-8</code> as encoding by default, you simply persist that corruption into the file.</p>\n\n<p>In order to fix the issue, you likely need to specify <code>Encoding</code> into your <code>Stream</code> objects.</p>\n\n<p>You can actually skip the <code>MemoryStream</code> process entirely, also - which will be faster and more efficient. Your updated code might look something more like:</p>\n\n<pre><code>FileStream fs = new FileStream(myPath, FileMode.Create);\n\nXmlTextWriter xmlTextWriter = \n new XmlTextWriter(fs, Encoding.GetEncoding(\"ISO-8859-1\"));\n\nxmlTextWriter.Formatting = Formatting.Indented;\nxmlTextWriter.WriteStartDocument(); //Start doc\n\nxmlTextWriter.WriteCData(myNorwegianText);\n\nStreamWriter sw = new StreamWriter(fs);\n\nfs.Position = 0;\nStreamReader sr = new StreamReader(fs);\nstring content = sr.ReadToEnd();\n\nsw.Write(content);\nsw.Flush();\n\nfs.Flush();\nfs.Close();\n</code></pre>\n"
},
{
"answer_id": 35490926,
"author": "mauro.Joestar",
"author_id": 5879824,
"author_profile": "https://Stackoverflow.com/users/5879824",
"pm_score": 0,
"selected": false,
"text": "<p>After investigating, this is that worked best for me:</p>\n\n<pre><code>var doc = new XDocument(new XDeclaration(\"1.0\", \"ISO-8859-1\", \"\"));\n using (XmlWriter writer = doc.CreateWriter()){\n writer.WriteStartDocument();\n writer.WriteStartElement(\"Root\");\n writer.WriteElementString(\"Foo\", \"value\");\n writer.WriteEndElement();\n writer.WriteEndDocument();\n }\n doc.Save(\"dte.xml\");\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5795/"
]
| I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå).
I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this:
```
MemoryStream stream = new MemoryStream();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1"));
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument(); //Start doc
```
Then I add my Norwegian text like this:
```
xmlTextWriter.WriteCData(myNorwegianText);
```
Then I write the file to disk like this:
```
FileStream myFile = new FileStream(myPath, FileMode.Create);
StreamWriter sw = new StreamWriter(myFile);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
sw.Write(content);
sw.Flush();
myFile.Flush();
myFile.Close();
```
Now the problem is that in the file on this, all the Norwegian characters look funny.
I'm probably doing the above in some stupid way. Any suggestions on how to fix it? | Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work.
If you still want to do the double write, for whatever reason, do one of two things. Either
1. Make sure that the StreamReader and StreamWriter objects you use *all* use the *same* encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or
2. Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway. |
139,261 | <p>For testing purposes I have to generate a file of a certain size (to test an upload limit). </p>
<p>What is a command to create a file of a certain size on Linux?</p>
| [
{
"answer_id": 139278,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 5,
"selected": false,
"text": "<p>Use this command:</p>\n\n<pre>\ndd if=$INPUT-FILE of=$OUTPUT-FILE bs=$BLOCK-SIZE count=$NUM-BLOCKS\n</pre>\n\n<p>To create a big (empty) file, set <code>$INPUT-FILE=/dev/zero</code>.<br>\nTotal size of the file will be <code>$BLOCK-SIZE * $NUM-BLOCKS</code>.<br>\nNew file created will be <code>$OUTPUT-FILE</code>.</p>\n"
},
{
"answer_id": 139282,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": false,
"text": "<pre><code>dd if=/dev/zero of=my_file.txt count=12345\n</code></pre>\n"
},
{
"answer_id": 139287,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 4,
"selected": false,
"text": "<p>you could do:</p>\n\n<pre><code>[dsm@localhost:~]$ perl -e 'print \"\\0\" x 100' > filename.ext\n</code></pre>\n\n<p>Where you replace 100 with the number of bytes you want written.</p>\n"
},
{
"answer_id": 139289,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 9,
"selected": true,
"text": "<p>For small files:</p>\n<pre><code>dd if=/dev/zero of=upload_test bs=file_size count=1\n</code></pre>\n<p>Where <code>file_size</code> is the size of your test file in bytes.</p>\n<p>For big files:</p>\n<pre><code>dd if=/dev/zero of=upload_test bs=1M count=size_in_megabytes\n</code></pre>\n"
},
{
"answer_id": 139415,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": false,
"text": "<p>Just to follow up <a href=\"https://stackoverflow.com/questions/139261/how-to-create-a-file-with-a-given-size-in-linux#139338\">Tom's</a> post, you can use dd to create sparse files as well:</p>\n\n<pre><code>dd if=/dev/zero of=the_file bs=1 count=0 seek=12345\n</code></pre>\n\n<p>This will create a file with a \"hole\" in it on most unixes - the data won't actually be written to disk, or take up any space until something other than zero is written into it.</p>\n"
},
{
"answer_id": 245239,
"author": "Benedikt Waldvogel",
"author_id": 4308,
"author_profile": "https://Stackoverflow.com/users/4308",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it programmatically:</p>\n\n<pre><code>#include <unistd.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <stdlib.h>\n\nint main() {\n int fd = creat(\"/tmp/foo.txt\", 0644);\n ftruncate(fd, SIZE_IN_BYTES);\n close(fd);\n return 0;\n}\n</code></pre>\n\n<p>This approach is especially useful to subsequently <a href=\"https://stackoverflow.com/search?q=mmap\">mmap</a> the file into memory.</p>\n\n<p>use the following command to check that the file has the correct size:</p>\n\n<pre><code># du -B1 --apparent-size /tmp/foo.txt\n</code></pre>\n\n<p><b>Be careful:</b></p>\n\n<pre><code># du /tmp/foo.txt\n</code></pre>\n\n<p>will probably print <strong>0</strong> because it is allocated as <a href=\"http://en.wikipedia.org/wiki/Sparse_file\" rel=\"nofollow noreferrer\">Sparse file</a> if supported by your filesystem.</p>\n\n<p>see also: <a href=\"http://linux.die.net/man/2/open\" rel=\"nofollow noreferrer\">man 2 open</a> and <a href=\"http://linux.die.net/man/2/truncate\" rel=\"nofollow noreferrer\">man 2 truncate</a></p>\n"
},
{
"answer_id": 8706411,
"author": "steve",
"author_id": 495637,
"author_profile": "https://Stackoverflow.com/users/495637",
"pm_score": 5,
"selected": false,
"text": "<p>On OSX (and Solaris, apparently), the <code>mkfile</code> command is available as well:</p>\n\n<pre><code>mkfile 10g big_file\n</code></pre>\n\n<p>This makes a 10 GB file named \"big_file\". Found this approach <a href=\"http://linuxcommando.blogspot.com/2008/02/create-file-of-given-size.html\" rel=\"noreferrer\">here.</a></p>\n"
},
{
"answer_id": 8706714,
"author": "jørgensen",
"author_id": 1091587,
"author_profile": "https://Stackoverflow.com/users/1091587",
"pm_score": 8,
"selected": false,
"text": "<p>Please, modern is easier, and faster. On Linux, (pick one)</p>\n\n<pre><code>truncate -s 10G foo\nfallocate -l 5G bar\n</code></pre>\n\n<p>It <em>needs</em> to be stated that <code>truncate</code> on a file system supporting sparse files will create a sparse file and <code>fallocate</code> will not. A sparse file is one where the allocation units that make up the file are not <em>actually</em> allocated until used. The meta-data for the file <em>will</em> however take up some considerable space but likely no where near the actual size of the file. You should consult resources about sparse files for more information as there are advantages and disadvantages to this type of file. A non-sparse file has its blocks (allocation units) allocated ahead of time which means the space is reserved as far as the file system sees it. Also <code>fallocate</code> nor <code>truncate</code> will not set the contents of the file to a specified value <em>like</em> <code>dd</code>, instead the contents of a file allocated with <code>fallocate</code> or <code>truncate</code> may be any trash value that existed in the allocated units during creation and this behavior may or may not be desired. The <code>dd</code> is the slowest because it actually writes the value or chunk of data to the entire file stream as specified with it's command line options. </p>\n\n<p><em>This behavior could potentially be different - depending on file system used and conformance of that file system to any standard or specification. Therefore it is advised that proper research is done to ensure that the appropriate method is used.</em></p>\n"
},
{
"answer_id": 13055390,
"author": "user1772090",
"author_id": 1772090,
"author_profile": "https://Stackoverflow.com/users/1772090",
"pm_score": 2,
"selected": false,
"text": "<p>As shell command:</p>\n\n<pre><code>< /dev/zero head -c 1048576 > output\n</code></pre>\n"
},
{
"answer_id": 18833290,
"author": "devin",
"author_id": 45777,
"author_profile": "https://Stackoverflow.com/users/45777",
"pm_score": 4,
"selected": false,
"text": "<p>Some of these answers have you using <code>/dev/zero</code> for the source of your data. If your testing network upload speeds, this may not be the best idea if your application is doing any compression, a file full of zeros compresses <em>really</em> well. Using this command to generate the file</p>\n\n<pre><code> dd if=/dev/zero of=upload_test bs=10000 count=1\n</code></pre>\n\n<p>I could compress <code>upload_test</code> down to about 200 bytes. So you could put yourself in a situation where you think your uploading a 10KB file but it would actually be much less.</p>\n\n<p>What I suggest is using <code>/dev/urandom</code> instead of <code>/dev/zero</code>. I couldn't compress the output of <code>/dev/urandom</code> very much at all.</p>\n"
},
{
"answer_id": 19051306,
"author": "BЈовић",
"author_id": 476681,
"author_profile": "https://Stackoverflow.com/users/476681",
"pm_score": 3,
"selected": false,
"text": "<p>There are lots of answers, but none explained nicely what else can be done. Looking into <a href=\"http://linux.die.net/man/1/dd\" rel=\"noreferrer\">man pages for dd</a>, it is possible to better specify the size of a file.</p>\n\n<p>This is going to create /tmp/zero_big_data_file.bin filled with zeros, that has size of 20 megabytes :</p>\n\n<pre><code> dd if=/dev/zero of=/tmp/zero_big_data_file.bin bs=1M count=20\n</code></pre>\n\n<p>This is going to create /tmp/zero_1000bytes_data_file.bin filled with zeros, that has size of 1000 bytes :</p>\n\n<pre><code> dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin bs=1kB count=1\n</code></pre>\n\n<p>or </p>\n\n<pre><code> dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin bs=1000 count=1\n</code></pre>\n\n<hr>\n\n<ul>\n<li>In all examples, bs is block size, and count is number of blocks</li>\n<li>BLOCKS and BYTES may be followed by the following multiplicative suffixes: c =1, w =2, b =512, kB =1000, K =1024, MB =1000*1000, M =1024*1024, xM =M GB =1000*1000*1000, G =1024*1024*1024, and so on for T, P, E, Z, Y. </li>\n</ul>\n"
},
{
"answer_id": 38504877,
"author": "Berkay92",
"author_id": 5291413,
"author_profile": "https://Stackoverflow.com/users/5291413",
"pm_score": 3,
"selected": false,
"text": "<p>This will generate 4 MB text file with random characters in current directory and its name \"4mb.txt\"\nYou can change parameters to generate different sizes and names.</p>\n\n<pre><code>base64 /dev/urandom | head -c 4000000 > 4mb.txt\n</code></pre>\n"
},
{
"answer_id": 59553998,
"author": "qin",
"author_id": 3358215,
"author_profile": "https://Stackoverflow.com/users/3358215",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>fallocate</code> if you don't want to wait for disk.</p>\n\n<p>Example:</p>\n\n<pre><code>fallocate -l 100G BigFile\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Usage:\n fallocate [options] <filename>\n\nPreallocate space to, or deallocate space from a file.\n\nOptions:\n -c, --collapse-range remove a range from the file\n -d, --dig-holes detect zeroes and replace with holes\n -i, --insert-range insert a hole at range, shifting existing data\n -l, --length <num> length for range operations, in bytes\n -n, --keep-size maintain the apparent size of the file\n -o, --offset <num> offset for range operations, in bytes\n -p, --punch-hole replace a range with a hole (implies -n)\n -z, --zero-range zero and ensure allocation of a range\n -x, --posix use posix_fallocate(3) instead of fallocate(2)\n -v, --verbose verbose mode\n\n -h, --help display this help\n -V, --version display version\n</code></pre>\n"
},
{
"answer_id": 74584789,
"author": "linux.cnf",
"author_id": 10000566,
"author_profile": "https://Stackoverflow.com/users/10000566",
"pm_score": 0,
"selected": false,
"text": "<p>Kindly run below command for quickly creating larger file with certain size\nin linux</p>\n<pre><code>for i in {1..10};do fallocate -l 2G filename$i;done\n</code></pre>\n<p>explanation:-Above command will create 10 files with 10GB size in just few seconds.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120/"
]
| For testing purposes I have to generate a file of a certain size (to test an upload limit).
What is a command to create a file of a certain size on Linux? | For small files:
```
dd if=/dev/zero of=upload_test bs=file_size count=1
```
Where `file_size` is the size of your test file in bytes.
For big files:
```
dd if=/dev/zero of=upload_test bs=1M count=size_in_megabytes
``` |
139,288 | <p>what is an efficient way to get a certain time for the next day in Java?
Let's say I want the long for tomorrow 03:30:00.
Setting Calendar fields and Date formatting are obvious.
Better or smarter ideas, thanks for sharing them!</p>
<p>Okami</p>
| [
{
"answer_id": 139319,
"author": "Brandon DuRette",
"author_id": 17834,
"author_profile": "https://Stackoverflow.com/users/17834",
"pm_score": 2,
"selected": false,
"text": "<p>I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i.e., \"better or smarter ideas\") with <code>Date</code>s almost always lands you in trouble. Heck, just using <code>java.util.Date</code> is asking for trouble. </p>\n\n<p>Added: Many have recommended <a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow noreferrer\">Joda Time</a> in other Date-related threads.</p>\n"
},
{
"answer_id": 139323,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 0,
"selected": false,
"text": "<p>I would consider using the predefined api the smart way to do this.</p>\n"
},
{
"answer_id": 139344,
"author": "Brian Knoblauch",
"author_id": 15689,
"author_profile": "https://Stackoverflow.com/users/15689",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure why you wouldn't just use the Calendar object? It's easy and maintainable. I agree about not using Date, pretty much everything useful about it is now deprecated. :(</p>\n"
},
{
"answer_id": 139349,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 5,
"selected": true,
"text": "<p>I take the brute force approach</p>\n\n<pre><code>// make it now\nCalendar dateCal = Calendar.getInstance();\n// make it tomorrow\ndateCal.add(Calendar.DAY_OF_YEAR, 1);\n// Now set it to the time you want\ndateCal.set(Calendar.HOUR_OF_DAY, hours);\ndateCal.set(Calendar.MINUTE, minutes);\ndateCal.set(Calendar.SECOND, seconds);\ndateCal.set(Calendar.MILLISECOND, 0);\nreturn dateCal.getTime();\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11450/"
]
| what is an efficient way to get a certain time for the next day in Java?
Let's say I want the long for tomorrow 03:30:00.
Setting Calendar fields and Date formatting are obvious.
Better or smarter ideas, thanks for sharing them!
Okami | I take the brute force approach
```
// make it now
Calendar dateCal = Calendar.getInstance();
// make it tomorrow
dateCal.add(Calendar.DAY_OF_YEAR, 1);
// Now set it to the time you want
dateCal.set(Calendar.HOUR_OF_DAY, hours);
dateCal.set(Calendar.MINUTE, minutes);
dateCal.set(Calendar.SECOND, seconds);
dateCal.set(Calendar.MILLISECOND, 0);
return dateCal.getTime();
``` |
139,325 | <p>How to set all the values in a <code>std::map</code> to the same value, without using a loop iterating over each value? </p>
| [
{
"answer_id": 139377,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "<p>Using a loop <em>is</em> by far the simplest method. In fact, it’s a one-liner:<sup>[C++17]</sup></p>\n<pre><code>for (auto& [_, v] : mymap) v = value;\n</code></pre>\n<p>Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use <code>std::fill</code>.</p>\n<p>To use them anyway (pre-C++20), we need to write adapters — in the case of <code>std::fill</code>, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do <em>not</em> advise using it as-is. Use a library (such as <a href=\"https://www.boost.org/doc/libs/1_74_0/libs/iterator/doc/function_output_iterator.html\" rel=\"nofollow noreferrer\">Boost.Iterator</a>) for a more general, production-strength implementation.</p>\n<pre><code>template <typename M>\nstruct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> {\n using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>;\n using underlying = typename M::iterator;\n using typename base_type::value_type;\n using typename base_type::reference;\n\n value_iter(underlying i) : i(i) {}\n\n value_iter& operator++() {\n ++i;\n return *this;\n }\n\n value_iter operator++(int) {\n auto copy = *this;\n i++;\n return copy;\n }\n\n reference operator*() { return i->second; }\n\n bool operator ==(value_iter other) const { return i == other.i; }\n bool operator !=(value_iter other) const { return i != other.i; }\n\nprivate:\n underlying i;\n};\n\ntemplate <typename M>\nauto value_begin(M& map) { return value_iter<M>(map.begin()); }\n\ntemplate <typename M>\nauto value_end(M& map) { return value_iter<M>(map.end()); }\n</code></pre>\n<p>With this, we can use <code>std::fill</code>:</p>\n<pre><code>std::fill(value_begin(mymap), value_end(mymap), value);\n</code></pre>\n"
},
{
"answer_id": 139570,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 2,
"selected": false,
"text": "<p>The boost::assign library has all sorts of neat stuff to help out initializing the contents of a container. My thought that this could be used to avoid explicitly iterating through the map. Unfortunately, maps are curious beasts difficult to initialize because the keys must be unique. The bottom line is that a simple for loop is probably the best way to initialize a map. It may not be super elegant, but it gets the job done and is immediatly comprehensible by anyone with any acquaintance with the STL.</p>\n\n<pre><code>map <int,string> myMap;\nfor( int k=0;k<1000;k++)\n myMap.insert(pair<int,string>(k,string(\"\")));\n</code></pre>\n\n<p>The rest of this post describes the journey I took to reach the above conclusion.</p>\n\n<p>The boost::assign makes it simple to assign a small number of values to a map.</p>\n\n<pre><code>map<string,int> m; \ninsert( m )( \"Bar\", 1 )( \"Foo\", 2 );\n</code></pre>\n\n<p>or</p>\n\n<pre><code> map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);\n</code></pre>\n\n<p>In your case, where you want to initialize the entire map with the same value, there are the utilities repeat and repeat_fun.<br>\nSomething like this should work with a multimap ( untested code snippet )</p>\n\n<pre><code>pair<int,string> init( 0,string(\"\"));\nmultimap <int,string> myMap = repeat(1000,init);\n</code></pre>\n\n<p>As Konrad Rudolph as pointed out, you cannot initialize a map with the same exact value, because the keys must be unique.</p>\n\n<p>This makes life much more complex ( fun? ). Something like this, perhaps:</p>\n\n<pre><code>map <int,string> myMap;\n\nstruct nextkey\n{\n int start;\n nextkey( s ) : start( s ) {}\n pair<int,string> operator () ()\n{\n return pair<int,string>(start++,string(\"\"));\n}\n};\n\nmyMap = repeat_fun(1000,nextkey(0));\n</code></pre>\n\n<p>Now, this is getting so complex, I now think a simple iteration IS the way to go</p>\n\n<pre><code>map <int,string> myMap;\nfor( int k=0;k<1000;k++)\n myMap.insert(pair<int,string>(k,string(\"\")));\n</code></pre>\n"
},
{
"answer_id": 30972901,
"author": "Benjamin Smith",
"author_id": 2715107,
"author_profile": "https://Stackoverflow.com/users/2715107",
"pm_score": 2,
"selected": false,
"text": "<p>I encountered the same problem but found that the range returned by boost::adaptors::values is mutable, so it can then be used with normal algorithms such as std::fill.</p>\n\n<pre><code>#include <boost/range/adaptor/map.hpp>\nauto my_values = boost::adaptors::values(my_map);\nstd::fill(my_values.begin(), my_values.end(), 123);\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6841/"
]
| How to set all the values in a `std::map` to the same value, without using a loop iterating over each value? | Using a loop *is* by far the simplest method. In fact, it’s a one-liner:[C++17]
```
for (auto& [_, v] : mymap) v = value;
```
Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use `std::fill`.
To use them anyway (pre-C++20), we need to write adapters — in the case of `std::fill`, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do *not* advise using it as-is. Use a library (such as [Boost.Iterator](https://www.boost.org/doc/libs/1_74_0/libs/iterator/doc/function_output_iterator.html)) for a more general, production-strength implementation.
```
template <typename M>
struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> {
using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>;
using underlying = typename M::iterator;
using typename base_type::value_type;
using typename base_type::reference;
value_iter(underlying i) : i(i) {}
value_iter& operator++() {
++i;
return *this;
}
value_iter operator++(int) {
auto copy = *this;
i++;
return copy;
}
reference operator*() { return i->second; }
bool operator ==(value_iter other) const { return i == other.i; }
bool operator !=(value_iter other) const { return i != other.i; }
private:
underlying i;
};
template <typename M>
auto value_begin(M& map) { return value_iter<M>(map.begin()); }
template <typename M>
auto value_end(M& map) { return value_iter<M>(map.end()); }
```
With this, we can use `std::fill`:
```
std::fill(value_begin(mymap), value_end(mymap), value);
``` |
139,358 | <p>In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box)</p>
| [
{
"answer_id": 139404,
"author": "Otherside",
"author_id": 18697,
"author_profile": "https://Stackoverflow.com/users/18697",
"pm_score": 2,
"selected": false,
"text": "<p>Since the scripting in innosetup is loosely based on Delphi, the controls should have some events like <code>OnEnter</code> (= control got focus) and <code>OnExit</code> (= control lost focus). You can assign procedures to these events, something like this:\n ComboBox.OnExit := ComboBoxExit;</p>\n\n<pre><code>procedure ComboBoxExit(Sender: TObject);\nbegin\n\nend;\n</code></pre>\n\n<p>I don't have access to Innosetup right now, so you will need to lookup the available events and parameters for the procedures.</p>\n"
},
{
"answer_id": 157659,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": true,
"text": "<p>Took me some time to work it out, but after being pointed in the right direction by Otherside, I finally got it (works for version 5.2):</p>\n\n<pre><code>[Code]\n\nvar \n MyCustomPage : TWizardPage;\n\nprocedure MyEditField_OnChange(Sender: TObject);\nbegin\n MsgBox('TEST', mbError, MB_OK);\nend;\n\nfunction MyCustomPage_Create(PreviousPageId: Integer): Integer;\nvar \n MyEditField: TEdit;\nbegin\n MyCustomPage := CreateCustomPage(PreviousPageId, 'Caption', 'Description');\n MyEditField := TEdit.Create(MyCustomPage);\n MyEditField.OnChange := @MyEditField_OnChange;\nend;\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22114/"
]
| In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box) | Took me some time to work it out, but after being pointed in the right direction by Otherside, I finally got it (works for version 5.2):
```
[Code]
var
MyCustomPage : TWizardPage;
procedure MyEditField_OnChange(Sender: TObject);
begin
MsgBox('TEST', mbError, MB_OK);
end;
function MyCustomPage_Create(PreviousPageId: Integer): Integer;
var
MyEditField: TEdit;
begin
MyCustomPage := CreateCustomPage(PreviousPageId, 'Caption', 'Description');
MyEditField := TEdit.Create(MyCustomPage);
MyEditField.OnChange := @MyEditField_OnChange;
end;
``` |
139,365 | <p>I've begun to use TDD. As mentioned in <a href="https://stackoverflow.com/questions/64333/what-is-the-downside-to-test-driven-development#64402">an earlier question</a> the biggest difficulty is handling interface changes. How do you reduce the impact on your test cases as requirements change?</p>
| [
{
"answer_id": 139378,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 0,
"selected": false,
"text": "<p>You write the tests before you write the code for the new interface.</p>\n"
},
{
"answer_id": 139380,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 3,
"selected": false,
"text": "<p>I <em>think</em> this is one of the reasons for the trendy argument that interfaces are used too much.</p>\n\n<p>However, I disagree.</p>\n\n<p>When requirements change -- so should your tests. Right? I mean, if the criteria for which you've written the test is no longer valid, then you should rewrite or eliminate that test.</p>\n\n<p>I hope this helps, but I think I may have misunderstood your question.</p>\n"
},
{
"answer_id": 139390,
"author": "Martin Klinke",
"author_id": 1793,
"author_profile": "https://Stackoverflow.com/users/1793",
"pm_score": 0,
"selected": false,
"text": "<p>If you are following the Test First approach, there should in theory be no impact of interface changes on your test code. After all, when you need to change an interface, you'd first change the test case(s) to match the requirements and then go ahead and change your interfaces/implementation until the tests pass.</p>\n"
},
{
"answer_id": 139419,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 2,
"selected": false,
"text": "<p>There <strong>will be</strong> an impact. You just have to accept that changing the interface will require time to change the associated test cases first. There is no way around this.</p>\n\n<p>However then you consider the time you save by not trying to find an elusive bug in this interface later and not fixing that bug during the release week it is totally worth it.</p>\n"
},
{
"answer_id": 139888,
"author": "spiv",
"author_id": 22701,
"author_profile": "https://Stackoverflow.com/users/22701",
"pm_score": 4,
"selected": true,
"text": "<p>Changing an interface requires updating code that uses that interface. Test code isn't any different from non-test code in this respect. It's unavoidable that tests for that interface will need to change.</p>\n\n<p>Often when an interface changes you find that \"too many\" tests break, i.e. tests for largely unrelated functionality turn out to depend on that interface. That can be a sign that your tests are overly broad and need refactoring. There are many possible ways this can happen, but here's an example that hopefully shows the general idea as well as a particular case.</p>\n\n<p>For instance if the way to construct an Account object has changed, and this requires updating all or most of your tests for your Order class, something is wrong. Most of your Order unit tests probably don't care about how an account is made, so refactor tests like this:</p>\n\n<pre><code>def test_add_item_to_order(self):\n acct = Account('Joe', 'Bloggs')\n shipping_addr = Address('123 Elm St', 'etc' 'etc')\n order = Order(acct, shipping_addr)\n item = OrderItem('Purple Widget')\n order.addItem(item)\n self.assertEquals([item], order.items)\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>def make_order(self):\n acct = Account('Joe', 'Bloggs')\n shipping_addr = Address('123 Elm St', 'etc' 'etc')\n return Order(acct, shipping_addr)\n\ndef make_order_item(self):\n return OrderItem('Purple Widget')\n\ndef test_add_item_to_order(self):\n order = self.make_order()\n item = self.make_order_item()\n order.addItem(item)\n self.assertEquals([item], order.items)\n</code></pre>\n\n<p>This particular pattern is a <a href=\"http://xunitpatterns.com/Creation%20Method.html\" rel=\"noreferrer\">Creation Method</a>.</p>\n\n<p>An advantage here is that your test methods for Order are insulated from how Accounts and Addresses are created; if those interfaces change you only have one place to change, rather than every single test that happens to use Accounts and Addresses.</p>\n\n<p>In short: tests are code too, and like all code, sometimes they need refactoring.</p>\n"
},
{
"answer_id": 145408,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 1,
"selected": false,
"text": "<p>In TDD, your tests aren't tests. They are executable specifications. IOW: they are an executable encoding of your requirements. <em>Always</em> keep that in mind.</p>\n\n<p>Now, suddenly it becomes obvious: if your requirements change, the tests <em>must</em> change! That's the whole point of TDD!</p>\n\n<p>If you were doing waterfall, you would have to change your specification document. In TDD, you have to do the same, except that your specification isn't written in Word, it's written in xUnit.</p>\n"
},
{
"answer_id": 145500,
"author": "Hibri",
"author_id": 15946,
"author_profile": "https://Stackoverflow.com/users/15946",
"pm_score": 0,
"selected": false,
"text": "<p>When interfaces change, you should expect tests to break. If too many tests break, this means that your system is too tightly coupled and too many things depend on that interface. You should expect a few tests to break, but not a lot. </p>\n\n<p>Having tests break is a good thing, any change in your code should break tests.</p>\n"
},
{
"answer_id": 659156,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If requirements change then your tests should be the first thing to change, rather than the interface. </p>\n\n<p>I would start by modifying the interface design in the first appropriate test, updating the interface to pass the newly-breaking test. Once the interface is updated to pass the test, you should see other tests break (as they will be using the outdated interface). </p>\n\n<p>It should be a matter of updating the remaining failing tests with the new interface design to get them passing again. </p>\n\n<p>Updating the interface in a test driven manner will ensure that the changes are actually necessary, and are testable.</p>\n"
},
{
"answer_id": 939077,
"author": "dmitrynikolaev",
"author_id": 115939,
"author_profile": "https://Stackoverflow.com/users/115939",
"pm_score": 1,
"selected": false,
"text": "<p>\"What we should do to prevents our code and tests from requiments dependency? Seems that nothing. Every time when requiments changed we must change our code & tests. But maybe we can simplify our work? Yes, we can. And the key principle is: incapsulation of code that might be changed.\"</p>\n\n<p><a href=\"http://dmitry-nikolaev.blogspot.com/2009/05/atch-your-changes.html\" rel=\"nofollow noreferrer\">http://dmitry-nikolaev.blogspot.com/2009/05/atch-your-changes.html</a></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16496/"
]
| I've begun to use TDD. As mentioned in [an earlier question](https://stackoverflow.com/questions/64333/what-is-the-downside-to-test-driven-development#64402) the biggest difficulty is handling interface changes. How do you reduce the impact on your test cases as requirements change? | Changing an interface requires updating code that uses that interface. Test code isn't any different from non-test code in this respect. It's unavoidable that tests for that interface will need to change.
Often when an interface changes you find that "too many" tests break, i.e. tests for largely unrelated functionality turn out to depend on that interface. That can be a sign that your tests are overly broad and need refactoring. There are many possible ways this can happen, but here's an example that hopefully shows the general idea as well as a particular case.
For instance if the way to construct an Account object has changed, and this requires updating all or most of your tests for your Order class, something is wrong. Most of your Order unit tests probably don't care about how an account is made, so refactor tests like this:
```
def test_add_item_to_order(self):
acct = Account('Joe', 'Bloggs')
shipping_addr = Address('123 Elm St', 'etc' 'etc')
order = Order(acct, shipping_addr)
item = OrderItem('Purple Widget')
order.addItem(item)
self.assertEquals([item], order.items)
```
to this:
```
def make_order(self):
acct = Account('Joe', 'Bloggs')
shipping_addr = Address('123 Elm St', 'etc' 'etc')
return Order(acct, shipping_addr)
def make_order_item(self):
return OrderItem('Purple Widget')
def test_add_item_to_order(self):
order = self.make_order()
item = self.make_order_item()
order.addItem(item)
self.assertEquals([item], order.items)
```
This particular pattern is a [Creation Method](http://xunitpatterns.com/Creation%20Method.html).
An advantage here is that your test methods for Order are insulated from how Accounts and Addresses are created; if those interfaces change you only have one place to change, rather than every single test that happens to use Accounts and Addresses.
In short: tests are code too, and like all code, sometimes they need refactoring. |
139,474 | <p>I'd like to capture the output of <a href="http://us3.php.net/manual/en/function.var-dump.php" rel="noreferrer"><code>var_dump</code></a> to a string.</p>
<p>The PHP documentation says;</p>
<blockquote>
<p>As with anything that outputs its result directly to the browser, the <a href="http://us3.php.net/manual/en/ref.outcontrol.php" rel="noreferrer">output-control functions</a> can be used to capture the output of this function, and save it in a string (for example).</p>
</blockquote>
<p>What would be an example of how that might work?</p>
<p><code>print_r()</code> isn't a valid possibility, because it's not going to give me the information that I need.</p>
| [
{
"answer_id": 139491,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 10,
"selected": true,
"text": "<p>Use output buffering:</p>\n\n<pre><code><?php\nob_start();\nvar_dump($someVar);\n$result = ob_get_clean();\n?>\n</code></pre>\n"
},
{
"answer_id": 139498,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 6,
"selected": false,
"text": "<p>You could also do this:</p>\n\n<pre><code>$dump = print_r($variable, true);\n</code></pre>\n"
},
{
"answer_id": 139553,
"author": "inxilpro",
"author_id": 12549,
"author_profile": "https://Stackoverflow.com/users/12549",
"pm_score": 10,
"selected": false,
"text": "<h1>Try <a href=\"http://php.net/var_export\" rel=\"noreferrer\"><code>var_export</code></a></h1>\n\n<p>You may want to check out <a href=\"http://php.net/var_export\" rel=\"noreferrer\"><code>var_export</code></a> — while it doesn't provide the same output as <code>var_dump</code> it does provide a second <code>$return</code> parameter which will cause it to return its output rather than print it:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$debug = var_export($my_var, true);\n</code></pre>\n\n<h2>Why?</h2>\n\n<p>I prefer this one-liner to using <code>ob_start</code> and <code>ob_get_clean()</code>. I also find that the output is a little easier to read, since it's just PHP code.</p>\n\n<p>The difference between <code>var_dump</code> and <code>var_export</code> is that <code>var_export</code> returns a <em>\"parsable string representation of a variable\"</em> while <code>var_dump</code> simply dumps information about a variable. What this means in practice is that <code>var_export</code> gives you valid PHP code (but may not give you quite as much information about the variable, especially if you're working with <a href=\"http://php.net/manual/en/language.types.resource.php\" rel=\"noreferrer\">resources</a>).</p>\n\n<h3>Demo:</h3>\n\n<pre class=\"lang-php prettyprint-override\"><code>$demo = array(\n \"bool\" => false,\n \"int\" => 1,\n \"float\" => 3.14,\n \"string\" => \"hello world\",\n \"array\" => array(),\n \"object\" => new stdClass(),\n \"resource\" => tmpfile(),\n \"null\" => null,\n);\n\n// var_export -- nice, one-liner\n$debug_export = var_export($demo, true);\n\n// var_dump\nob_start();\nvar_dump($demo);\n$debug_dump = ob_get_clean();\n\n// print_r -- included for completeness, though not recommended\n$debug_printr = print_r($demo, true);\n</code></pre>\n\n<h2>The difference in output:</h2>\n\n<h3>var_export (<code>$debug_export</code> in above example):</h3>\n\n<pre class=\"lang-php prettyprint-override\"><code> array (\n 'bool' => false,\n 'int' => 1,\n 'float' => 3.1400000000000001,\n 'string' => 'hello world',\n 'array' => \n array (\n ),\n 'object' => \n stdClass::__set_state(array(\n )),\n 'resource' => NULL, // Note that this resource pointer is now NULL\n 'null' => NULL,\n)\n</code></pre>\n\n<h3>var_dump (<code>$debug_dump</code> in above example):</h3>\n\n<pre><code> array(8) {\n [\"bool\"]=>\n bool(false)\n [\"int\"]=>\n int(1)\n [\"float\"]=>\n float(3.14)\n [\"string\"]=>\n string(11) \"hello world\"\n [\"array\"]=>\n array(0) {\n }\n [\"object\"]=>\n object(stdClass)#1 (0) {\n }\n [\"resource\"]=>\n resource(4) of type (stream)\n [\"null\"]=>\n NULL\n}\n</code></pre>\n\n<h3>print_r (<code>$debug_printr</code> in above example):</h3>\n\n<pre><code>Array\n(\n [bool] => \n [int] => 1\n [float] => 3.14\n [string] => hello world\n [array] => Array\n (\n )\n\n [object] => stdClass Object\n (\n )\n\n [resource] => Resource id #4\n [null] => \n)\n</code></pre>\n\n<h2>Caveat: <code>var_export</code> does not handle circular references</h2>\n\n<p>If you're trying to dump a variable with circular references, calling <code>var_export</code> will result in a PHP warning:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> $circular = array();\n $circular['self'] =& $circular;\n var_export($circular);\n</code></pre>\n\n<p>Results in: </p>\n\n<pre><code> Warning: var_export does not handle circular references in example.php on line 3\n array (\n 'self' => \n array (\n 'self' => NULL,\n ),\n )\n</code></pre>\n\n<p>Both <code>var_dump</code> and <code>print_r</code>, on the other hand, will output the string <code>*RECURSION*</code> when encountering circular references.</p>\n"
},
{
"answer_id": 147343,
"author": "Sergey Stolyarov",
"author_id": 15958,
"author_profile": "https://Stackoverflow.com/users/15958",
"pm_score": 4,
"selected": false,
"text": "<p>You may also try to use the <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow noreferrer\"><code>serialize()</code></a> function. Sometimes it is very useful for debugging purposes.</p>\n"
},
{
"answer_id": 1966366,
"author": "selfawaresoup",
"author_id": 235308,
"author_profile": "https://Stackoverflow.com/users/235308",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to have a look at a variable's contents during runtime, consider using a real debugger like XDebug. That way you don't need to mess up your source code, and you can use a debugger even while normal users visit your application. They won't notice.</p>\n"
},
{
"answer_id": 18085031,
"author": "ZurabWeb",
"author_id": 1016530,
"author_profile": "https://Stackoverflow.com/users/1016530",
"pm_score": 4,
"selected": false,
"text": "<p>Also <code>echo json_encode($dataobject);</code> might be helpful</p>\n"
},
{
"answer_id": 19344690,
"author": "Khandad Niazi",
"author_id": 1842394,
"author_profile": "https://Stackoverflow.com/users/1842394",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the complete solution as a function:</p>\n\n<pre><code>function varDumpToString ($var)\n{\n ob_start();\n var_dump($var);\n return ob_get_clean();\n}\n</code></pre>\n"
},
{
"answer_id": 19890427,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": 4,
"selected": false,
"text": "<p>if you are using PHP>=7.0.0</p>\n<pre><code>function return_var_dump(...$args): string\n{\n ob_start();\n try {\n var_dump(...$args);\n return ob_get_clean();\n } catch (\\Throwable $ex) {\n // PHP8 ArgumentCountError for 0 arguments, probably..\n // in php<8 this was just a warning\n ob_end_clean();\n throw $ex;\n }\n}\n</code></pre>\n<p>or if you are using PHP >=5.3.0:</p>\n<pre><code>function return_var_dump(){\n ob_start();\n call_user_func_array('var_dump', func_get_args());\n return ob_get_clean();\n}\n</code></pre>\n<p>or if you are using PHP<5.3.0 (this function is actually compatible all the way back to PHP4)</p>\n<pre><code>function return_var_dump(){\n $args = func_get_args(); // For <5.3.0 support ...\n ob_start();\n call_user_func_array('var_dump', $args);\n return ob_get_clean();\n}\n</code></pre>\n<p>(prior to 5.3.0 there was a bug with func_get_args if used directly as an argument for another function call, so you had to put it in a variable and use the variable, instead of using it directly as an argument..)</p>\n"
},
{
"answer_id": 25835613,
"author": "Younis Bensalah",
"author_id": 1322787,
"author_profile": "https://Stackoverflow.com/users/1322787",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://php.net/var_dump\" rel=\"nofollow noreferrer\">From the PHP manual</a>:</p>\n\n<blockquote>\n <p>This function displays structured information about one or more expressions that includes its type and value.</p>\n</blockquote>\n\n<p>So, here is the <em>real</em> return version of PHP's <code>var_dump()</code>, which actually accepts a variable-length argument list:</p>\n\n<pre><code>function var_dump_str()\n{\n $argc = func_num_args();\n $argv = func_get_args();\n\n if ($argc > 0) {\n ob_start();\n call_user_func_array('var_dump', $argv);\n $result = ob_get_contents();\n ob_end_clean();\n return $result;\n }\n\n return '';\n}\n</code></pre>\n"
},
{
"answer_id": 28039196,
"author": "Dev C",
"author_id": 4472749,
"author_profile": "https://Stackoverflow.com/users/4472749",
"pm_score": -1,
"selected": false,
"text": "<p>From <a href=\"http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html\" rel=\"nofollow\">http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html</a>:</p>\n\n<blockquote>\n <p>var_dump and print_r functions can only output directly to browser. So the output of these functions can only retrieved by using output control functions of php. Below method may be useful to save the output.</p>\n\n<pre><code>function assignVarDumpValueToString($object) {\n ob_start();\n var_dump($object);\n $result = ob_get_clean();\n return $result;\n}\n</code></pre>\n</blockquote>\n\n<p>ob_get_clean() can only clear last data entered to internal buffer. So\nob_get_contents method will be useful if you have multiple entries.</p>\n\n<p>From the same source as above:</p>\n\n<blockquote>\n<pre><code>function varDumpToErrorLog( $var=null ){\n ob_start(); // start reading the internal buffer\n var_dump( $var); \n $grabbed_information = ob_get_contents(); // assigning the internal buffer contents to variable\n ob_end_clean(); // clearing the internal buffer.\n error_log( $grabbed_information); // saving the information to error_log\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 50130617,
"author": "Charlie Vieillard",
"author_id": 2568082,
"author_profile": "https://Stackoverflow.com/users/2568082",
"pm_score": 2,
"selected": false,
"text": "<p>This maybe a bit off topic.</p>\n\n<p>I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.</p>\n\n<pre><code>fwrite(fopen('php://stdout', 'w'), var_export($object, true));\n</code></pre>\n"
},
{
"answer_id": 55884110,
"author": "Wadih M.",
"author_id": 76673,
"author_profile": "https://Stackoverflow.com/users/76673",
"pm_score": 1,
"selected": false,
"text": "<p>I really like <code>var_dump()</code>'s verbose output and wasn't satisfied with <code>var_export()</code>'s or <code>print_r()</code>'s output because it didn't give as much information (e.g. data type missing, length missing).</p>\n\n<p>To write secure and predictable code, sometimes it's useful to differentiate between an empty string and a null. Or between a 1 and a true. Or between a null and a false. So I want my data type in the output. </p>\n\n<p>Although helpful, I didn't find a clean and simple solution in the existing responses to convert the colored output of <code>var_dump()</code> to a human-readable output into a string without the html tags and including all the details from <code>var_dump()</code>. </p>\n\n<p>Note that if you have a colored <code>var_dump()</code>, it means that you have Xdebug installed which overrides php's default <code>var_dump()</code> to add html colors.</p>\n\n<p>For that reason, I created this slight variation giving exactly what I need: </p>\n\n<pre><code>function dbg_var_dump($var)\n {\n ob_start();\n var_dump($var);\n $result = ob_get_clean();\n return strip_tags(strtr($result, ['=&gt;' => '=>']));\n }\n</code></pre>\n\n<p>Returns the below nice string:</p>\n\n<pre><code>array (size=6)\n 'functioncall' => string 'add-time-property' (length=17)\n 'listingid' => string '57' (length=2)\n 'weekday' => string '0' (length=1)\n 'starttime' => string '00:00' (length=5)\n 'endtime' => string '00:00' (length=5)\n 'price' => string '' (length=0)\n</code></pre>\n\n<p>Hope it helps someone. </p>\n"
},
{
"answer_id": 57455169,
"author": "vuchkov",
"author_id": 3809048,
"author_profile": "https://Stackoverflow.com/users/3809048",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Long string</strong>: Just use <code>echo($var);</code> instead of <code>dump($var);</code>.</p>\n\n<p><strong>Object</strong> or <strong>Array</strong>: <code>var_dump('<pre>'.json_encode($var).'</pre>);'</code></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
| I'd like to capture the output of [`var_dump`](http://us3.php.net/manual/en/function.var-dump.php) to a string.
The PHP documentation says;
>
> As with anything that outputs its result directly to the browser, the [output-control functions](http://us3.php.net/manual/en/ref.outcontrol.php) can be used to capture the output of this function, and save it in a string (for example).
>
>
>
What would be an example of how that might work?
`print_r()` isn't a valid possibility, because it's not going to give me the information that I need. | Use output buffering:
```
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
``` |
139,484 | <p>I have two (UNIX) programs A and B that read and write from stdin/stdout.</p>
<p>My first problem is how to connect the stdout of A to stdin of B <em>and</em> the stdout of B to the stdin of A. I.e., something like A | B but a bidirectional pipe. I suspect I could solve this by <a href="http://tldp.org/LDP/abs/html/x16834.html" rel="noreferrer">using exec to redirect</a> but I could not get it to work. The programs are interactive so a temporary file would not work.</p>
<p>The second problem is that I would like to duplicate each direction and pipe a duplicate via a logging program to stdout so that I can see the (text-line based) traffic that pass between the programs. Here I may get away with tee >(...) if I can solve the first problem.</p>
<p>Both these problems seems like they should have well known solutions but I have not be able to find anything.</p>
<p>I would prefer a POSIX shell solution, or at least something that works in bash on cygwin.</p>
<p>Thanks to your answers I came up with the following solution. The A/B commands uses nc to listen to two ports. The logging program uses sed (with -u for unbuffered processing).</p>
<pre><code>bash-3.2$ fifodir=$(mktemp -d)
bash-3.2$ mkfifo "$fifodir/echoAtoB"
bash-3.2$ mkfifo "$fifodir/echoBtoA"
bash-3.2$ sed -u 's/^/A->B: /' "$fifodir/echoAtoB" &
bash-3.2$ sed -u 's/^/B->A: /' "$fifodir/echoBtoA" &
bash-3.2$ mkfifo "$fifodir/loopback"
bash-3.2$ nc -l -p 47002 < "$fifodir/loopback" \
| tee "$fifodir/echoAtoB" \
| nc -l -p 47001 \
| tee "$fifodir/echoBtoA" > "$fifodir/loopback"
</code></pre>
<p>This listens for connection to port 47001 and 47002 and echos all traffic to standard output.</p>
<p>In shell 2 do:</p>
<pre><code>bash-3.2$ nc localhost 47001
</code></pre>
<p>In shell 3 do:</p>
<pre><code>bash-3.2$ nc localhost 47002
</code></pre>
<p>Now lines entered in shell 2 will be written to shell 3 and vice versa and the traffic logged to shell 1, something like:</p>
<pre><code>B->A: input to port 47001
A->B: input to port 47002
</code></pre>
<p>The above has been tested on Cygwin</p>
<p>Update: The script above stopped working after a few days(!). Apparently it can deadlock. Some of the suggestions in the answers may be more reliable.</p>
| [
{
"answer_id": 139495,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://bisqwit.iki.fi/source/twinpipe.html\" rel=\"noreferrer\">http://bisqwit.iki.fi/source/twinpipe.html</a></p>\n"
},
{
"answer_id": 139518,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 3,
"selected": false,
"text": "<p>You could probably get away with named pipes:</p>\n\n<pre><code>mkfifo pipe\ngawk '$1' < pipe | gawk '$1' > pipe\n</code></pre>\n"
},
{
"answer_id": 139532,
"author": "sherbang",
"author_id": 5026,
"author_profile": "https://Stackoverflow.com/users/5026",
"pm_score": 4,
"selected": false,
"text": "<p>How about a named pipe?</p>\n\n<pre><code># mkfifo foo\n# A < foo | B > foo\n# rm foo\n</code></pre>\n\n<p>For your second part I believe tee is the correct answer. So it becomes:</p>\n\n<pre><code># A < foo | tee logfile | B > foo\n</code></pre>\n"
},
{
"answer_id": 139602,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://expect.nist.gov/\" rel=\"nofollow noreferrer\">Expect</a>.</p>\n\n<blockquote>\n <p>Expect is a tool for automating interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc.</p>\n</blockquote>\n\n<p>You could use the following code (taken from the <em>Exploring Expect</em> book) as a starting point - it connects the output of proc1 to the input of proc2 and vice versa, as you requested:</p>\n\n<pre><code>#!/usr/bin/expect -f\nspawn proc1\nset proc1 $spawn_id\nspawn proc2\ninteract -u $proc1\n</code></pre>\n"
},
{
"answer_id": 139629,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "<p>This question is similar to <a href=\"https://stackoverflow.com/questions/40244/how-to-make-a-pipe-loop-in-bash\">one</a> I asked before. The solutions proposed by others were to use named pipes, but I suspect you don't have them in cygwin. Currently I'm sticking to <a href=\"https://stackoverflow.com/questions/40244/how-to-make-a-pipe-loop-in-bash#43332\">my own (attempt at a) solution</a>, but it requires <code>/dev/fd/0</code> which you probably also don't have.</p>\n\n<p>Although I don't really like the passing-command-lines-as-strings aspect of <code>twinpipe</code> (mentioned by JeeBee (<a href=\"https://stackoverflow.com/questions/139484/connecting-input-andoutput-between-of-two-commands-in-shellbash#139495\">139495</a>)), it might be your only option in cygwin.</p>\n"
},
{
"answer_id": 527491,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I spent a lot of time on this, gave it up, and last decided to use ksh (the Korn shell), which allows this.</p>\n\n<pre><code>cmd1 |& cmd2 >&p <&p\n</code></pre>\n\n<p>where <code>|&</code> is a (pipe) operator to start a co-process and <code>&p</code> is file descriptor of that co-process.</p>\n"
},
{
"answer_id": 7911486,
"author": "basicer",
"author_id": 800316,
"author_profile": "https://Stackoverflow.com/users/800316",
"pm_score": 2,
"selected": false,
"text": "<p>I had this problem at one point, and I threw together this simple C program.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <unistd.h>\n\n#define PERROR_AND_DIE(_x_) {perror(_x_); _exit(1);}\n\nint main(int argc, char **argv) {\n int fd0[2];\n int fd1[2];\n\n\n if ( argc != 3 ) {\n fprintf(stdout, \"Usage %s: \\\"[command 1]\\\" \\\"[command 2]\\\"\\n\", argv[0]);\n _exit(1);\n }\n\n if ( pipe(fd0) || pipe(fd1) ) PERROR_AND_DIE(\"pipe\")\n\n pid_t id = fork();\n if ( id == -1 ) PERROR_AND_DIE(\"fork\");\n\n if ( id ) {\n if ( -1 == close(0) ) PERROR_AND_DIE(\"P1: close 0\");\n if ( -1 == dup2(fd0[0], 0) ) PERROR_AND_DIE(\"P1: dup 0\"); //Read my STDIN from this pipe\n\n if ( -1 == close(1) ) PERROR_AND_DIE(\"P1: close 1\");\n if ( -1 == dup2(fd1[1], 1) ) PERROR_AND_DIE(\"P1: dup 1\"); //Write my STDOUT here\n execl(\"/bin/sh\", \"/bin/sh\", \"-c\", argv[1], NULL);\n PERROR_AND_DIE(\"P1: exec\")\n }\n\n if ( -1 == close(0) ) PERROR_AND_DIE(\"P2: close 0\");\n if ( -1 == dup2(fd1[0], 0) ) PERROR_AND_DIE(\"P2: dup 0\");\n\n if ( -1 == close(1) ) PERROR_AND_DIE(\"P2: close 1\");\n if ( -1 == dup2(fd0[1], 1) ) PERROR_AND_DIE(\"P2: dup 1\");\n\n\n execl(\"/bin/sh\", \"/bin/sh\", \"-c\", argv[2], NULL);\n PERROR_AND_DIE(\"P2: exec\")\n}\n</code></pre>\n"
},
{
"answer_id": 13626580,
"author": "mmaruska",
"author_id": 890091,
"author_profile": "https://Stackoverflow.com/users/890091",
"pm_score": 0,
"selected": false,
"text": "<p>I'd suggest \"coproc\":</p>\n\n<pre><code>#! /bin/bash\n# initiator needs argument\n\nif [ $# -gt 0 ]; then\n a=$1\n echo \"Question $a\"\nelse\n read a\nfi\n\nif [ $# -gt 0 ]; then\n read a\n echo \"$a\" >&2\nelse\n echo \"Answer to $a is ...\"\nfi\n\nexit 0\n</code></pre>\n\n<p>Then see this session:</p>\n\n<pre><code>$ coproc ./dialog\n$ ./dialog test < /dev/fd/${COPROC[0]} > /dev/fd/${COPROC[1]}\nAnswer to Question test is ...\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22676/"
]
| I have two (UNIX) programs A and B that read and write from stdin/stdout.
My first problem is how to connect the stdout of A to stdin of B *and* the stdout of B to the stdin of A. I.e., something like A | B but a bidirectional pipe. I suspect I could solve this by [using exec to redirect](http://tldp.org/LDP/abs/html/x16834.html) but I could not get it to work. The programs are interactive so a temporary file would not work.
The second problem is that I would like to duplicate each direction and pipe a duplicate via a logging program to stdout so that I can see the (text-line based) traffic that pass between the programs. Here I may get away with tee >(...) if I can solve the first problem.
Both these problems seems like they should have well known solutions but I have not be able to find anything.
I would prefer a POSIX shell solution, or at least something that works in bash on cygwin.
Thanks to your answers I came up with the following solution. The A/B commands uses nc to listen to two ports. The logging program uses sed (with -u for unbuffered processing).
```
bash-3.2$ fifodir=$(mktemp -d)
bash-3.2$ mkfifo "$fifodir/echoAtoB"
bash-3.2$ mkfifo "$fifodir/echoBtoA"
bash-3.2$ sed -u 's/^/A->B: /' "$fifodir/echoAtoB" &
bash-3.2$ sed -u 's/^/B->A: /' "$fifodir/echoBtoA" &
bash-3.2$ mkfifo "$fifodir/loopback"
bash-3.2$ nc -l -p 47002 < "$fifodir/loopback" \
| tee "$fifodir/echoAtoB" \
| nc -l -p 47001 \
| tee "$fifodir/echoBtoA" > "$fifodir/loopback"
```
This listens for connection to port 47001 and 47002 and echos all traffic to standard output.
In shell 2 do:
```
bash-3.2$ nc localhost 47001
```
In shell 3 do:
```
bash-3.2$ nc localhost 47002
```
Now lines entered in shell 2 will be written to shell 3 and vice versa and the traffic logged to shell 1, something like:
```
B->A: input to port 47001
A->B: input to port 47002
```
The above has been tested on Cygwin
Update: The script above stopped working after a few days(!). Apparently it can deadlock. Some of the suggestions in the answers may be more reliable. | <http://bisqwit.iki.fi/source/twinpipe.html> |
139,513 | <p>I made a class from Linq to SQL Clasees with VS 2008 SP1 Framework 3.5 SP1, in this case I extended the partial</p>
<pre><code>partial void UpdateMyTable(MyTable instance){
// Business logic
// Validation rules, etc.
}
</code></pre>
<p>My problem is when I execute db.SubmitChanges(), it executes UpdateMyTable and makes the validations but it doesn't update, I get this error:</p>
<pre><code>[Exception: Deliver]
System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) +197
System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) +255
System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +76
System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331
System.Data.Linq.DataContext.SubmitChanges() +19
</code></pre>
| [
{
"answer_id": 139625,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<ul>\n<li>if you provide this method, you must perform the update in the method.</li>\n</ul>\n\n<hr>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb882671.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb882671.aspx</a></p>\n\n<ul>\n<li>If you implement the Insert, Update and Delete methods in your partial class, the LINQ to SQL runtime will call them <strong>instead</strong> of its own default methods when SubmitChanges is called.</li>\n</ul>\n\n<p>Try <strong>MiTabla.OnValidate</strong></p>\n"
},
{
"answer_id": 146432,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to implement this method but not do the update yourself you make the method call ExecuteDynamicUpdate(item);</p>\n\n<p>Likewise ExecuteDynamicDelete and ExecuteDynamicInsert for DeleteMyTable and InsertMyTable respectively.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19710/"
]
| I made a class from Linq to SQL Clasees with VS 2008 SP1 Framework 3.5 SP1, in this case I extended the partial
```
partial void UpdateMyTable(MyTable instance){
// Business logic
// Validation rules, etc.
}
```
My problem is when I execute db.SubmitChanges(), it executes UpdateMyTable and makes the validations but it doesn't update, I get this error:
```
[Exception: Deliver]
System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) +197
System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) +255
System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +76
System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331
System.Data.Linq.DataContext.SubmitChanges() +19
``` | * if you provide this method, you must perform the update in the method.
---
<http://msdn.microsoft.com/en-us/library/bb882671.aspx>
* If you implement the Insert, Update and Delete methods in your partial class, the LINQ to SQL runtime will call them **instead** of its own default methods when SubmitChanges is called.
Try **MiTabla.OnValidate** |
139,525 | <p>I have an Xtext/Xpand (oAW 4.3, Eclipse 3.4) generator plug-in, which I run together with the editor plug-in in a second workbench. There, I'd like to run Xpand workflows programmatically on the model file I create. If I set the model file using the absolute path of the IFile I have, e.g. with:</p>
<pre><code>String dslFile = file.getLocation().makeAbsolute().toOSString();
</code></pre>
<p>Or if I use a file URI retrieved with:</p>
<pre><code>String dslFile = file.getLocationURI().toString();
</code></pre>
<p>The file is not found:</p>
<pre><code>org.eclipse.emf.ecore.resource.Resource$IOWrappedException: Resource '/absolute/path/to/my/existing/dsl.file' does not exist.
at org.openarchitectureware.xtext.parser.impl.AbstractParserComponent.invokeInternal(AbstractParserComponent.java:55)
</code></pre>
<p>To what value should I set the model file attribute (dslFile) in the map I hand to the WorkflowRunner:</p>
<pre><code>Map properties = new HashMap();
properties.put("modelFile", dslFile);
</code></pre>
<p>I also tried leaving the properties empty and referencing the model file relative to the workflow file (inside the workflow file), but that yields a FileNotFoundException. Running all of this in a normal app (not in a second workbench) works fine.</p>
| [
{
"answer_id": 192038,
"author": "Fabian Steeg",
"author_id": 18154,
"author_profile": "https://Stackoverflow.com/users/18154",
"pm_score": 1,
"selected": true,
"text": "<p>I found help at the <a href=\"http://openarchitectureware.org/forum/viewtopic.php?showtopic=10197\" rel=\"nofollow noreferrer\">openArchitectureWare forum</a>. Basically using</p>\n\n<pre><code>properties.put(\"modelFile\", file.getLocation().makeAbsolute().toOSString());\n</code></pre>\n\n<p>works, but you need to specify looking it up via URI in the workflow you are calling:</p>\n\n<pre><code><component class=\"org.eclipse.mwe.emf.Reader\">\n <uri value='${modelFile}'/>\n <modelSlot value='theModel'/>\n</component>\n</code></pre>\n"
},
{
"answer_id": 919828,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>2 important things for people looking in here...the TE used a IFLE for the \"file.get....\", and the correct syntax for paths is \"file:/c:/myOSbla\".</p>\n"
},
{
"answer_id": 3146098,
"author": "Richard Gomes",
"author_id": 62131,
"author_profile": "https://Stackoverflow.com/users/62131",
"pm_score": 0,
"selected": false,
"text": "<p>This is a sample application <strong>Launcher.java</strong> (sitting in the default package):</p>\n\n<pre><code>import gnu.getopt.Getopt;\nimport gnu.getopt.LongOpt;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher;\n\npublic class Launcher implements Runnable {\n\n //\n // main program\n //\n\n public static void main(final String[] args) {\n new Launcher(args).run();\n }\n\n\n //\n // private final fields\n //\n\n private static final String defaultModelDir = \"src/main/resources/model\";\n private static final String defaultTargetDir = \"target/generated/pageflow-maven-plugin/java\";\n private static final String defaultFileEncoding = \"UTF-8\";\n\n private static final LongOpt[] longopts = new LongOpt[] {\n new LongOpt(\"baseDir\", LongOpt.REQUIRED_ARGUMENT, new StringBuffer(), 'b'),\n new LongOpt(\"modelDir\", LongOpt.REQUIRED_ARGUMENT, new StringBuffer(), 'm'),\n new LongOpt(\"targetDir\", LongOpt.REQUIRED_ARGUMENT, new StringBuffer(), 't'),\n new LongOpt(\"encoding\", LongOpt.REQUIRED_ARGUMENT, new StringBuffer(), 'e'),\n new LongOpt(\"help\", LongOpt.NO_ARGUMENT, null, 'h'),\n new LongOpt(\"verbose\", LongOpt.NO_ARGUMENT, null, 'v'),\n };\n\n\n private final String[] args;\n\n //\n // public constructors\n //\n\n public Launcher(final String[] args) {\n this.args = args;\n }\n\n\n public void run() {\n final String cwd = System.getProperty(\"user.dir\");\n String baseDir = cwd;\n String modelDir = defaultModelDir;\n String targetDir = defaultTargetDir;\n String encoding = defaultFileEncoding;\n boolean verbose = false;\n\n final StringBuffer sb = new StringBuffer();\n final Getopt g = new Getopt(\"pageflow-dsl-generator\", this.args, \"b:m:t:e:hv;\", longopts);\n g.setOpterr(false); // We'll do our own error handling\n int c;\n while ((c = g.getopt()) != -1)\n switch (c) {\n case 'b':\n baseDir = g.getOptarg();\n break;\n case 'm':\n modelDir = g.getOptarg();\n break;\n case 't':\n targetDir = g.getOptarg();\n break;\n case 'e':\n encoding = g.getOptarg();\n break;\n case 'h':\n printUsage();\n System.exit(0);\n break;\n case 'v':\n verbose = true;\n break;\n case '?':\n default:\n System.out.println(\"The option '\" + (char) g.getOptopt() + \"' is not valid\");\n printUsage();\n System.exit(1);\n break;\n }\n\n String absoluteModelDir;\n String absoluteTargetDir;\n\n try {\n absoluteModelDir = checkDir(baseDir, modelDir, false, true);\n absoluteTargetDir = checkDir(baseDir, targetDir, true, true);\n } catch (final IOException e) {\n throw new RuntimeException(e.getMessage(), e.getCause());\n }\n\n if (verbose) {\n System.err.println(String.format(\"modeldir = %s\", absoluteModelDir));\n System.err.println(String.format(\"targetdir = %s\", absoluteTargetDir));\n System.err.println(String.format(\"encoding = %s\", encoding));\n }\n\n Mwe2Launcher.main(\n new String[] {\n \"workflow.PageflowGenerator\",\n \"-p\", \"modelDir=\".concat(absoluteModelDir),\n \"-p\", \"targetDir=\".concat(absoluteTargetDir),\n \"-p\", \"fileEncoding=\".concat(encoding)\n });\n\n }\n\n\n private void printUsage() {\n System.err.println(\"Syntax: [-b <baseDir>] [-m <modelDir>] [-t <targetDir>] [-e <encoding>] [-h] [-v]\");\n System.err.println(\"Options:\");\n System.err.println(\" -b, --baseDir project home directory, e.g: /home/workspace/myapp\");\n System.err.println(\" -m, --modelDir default is: \".concat(defaultModelDir));\n System.err.println(\" -t, --targetDir default is: \".concat(defaultTargetDir));\n System.err.println(\" -e, --encoding default is: \".concat(defaultFileEncoding));\n System.err.println(\" -h, --help this help text\");\n System.err.println(\" -v, --verbose verbose mode\");\n }\n\n private String checkDir(final String basedir, final String dir, final boolean create, final boolean fail) throws IOException {\n final StringBuilder sb = new StringBuilder();\n sb.append(basedir).append('/').append(dir);\n final File f = new File(sb.toString()).getCanonicalFile();\n final String absolutePath = f.getAbsolutePath();\n if (create) {\n if (f.isDirectory()) return absolutePath;\n if (f.mkdirs()) return absolutePath;\n } else {\n if (f.isDirectory()) return absolutePath;\n }\n if (!fail) return null;\n throw new IOException(String.format(\"Failed to locate or create directory %s\", absolutePath));\n }\n\n private String checkFile(final String basedir, final String file, final boolean fail) throws IOException {\n final StringBuilder sb = new StringBuilder();\n sb.append(basedir).append('/').append(file);\n final File f = new File(sb.toString()).getCanonicalFile();\n final String absolutePath = f.getAbsolutePath();\n if (f.isFile()) return absolutePath;\n if (!fail) return null;\n throw new IOException(String.format(\"Failed to find or locate directory %s\", absolutePath));\n }\n\n}\n</code></pre>\n\n<p>... and this is its <strong>pom.xml</strong>:</p>\n\n<pre><code><project\n xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.vaadin</groupId>\n <artifactId>pageflow-dsl-generator</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n\n <build>\n <sourceDirectory>src</sourceDirectory>\n\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-jar-plugin</artifactId>\n <configuration>\n <archive>\n <index>true</index>\n <manifest>\n <mainClass>Launcher</mainClass>\n </manifest>\n </archive>\n </configuration>\n </plugin>\n </plugins>\n\n </build>\n\n\n\n <dependencies>\n <dependency>\n <groupId>urbanophile</groupId>\n <artifactId>java-getopt</artifactId>\n <version>1.0.9</version>\n </dependency>\n </dependencies>\n\n</project>\n</code></pre>\n\n<p>Unfortunately, this pom.xml is not intended to package it (not yet, at least).\nFor instructions regarding packaging, have a look at\n<a href=\"http://zarnekow.blogspot.com/2010/06/how-to-deploy-xtext-standalone.html\" rel=\"nofollow noreferrer\">link text</a></p>\n\n<p>Have fun :)</p>\n\n<p>Richard Gomes</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18154/"
]
| I have an Xtext/Xpand (oAW 4.3, Eclipse 3.4) generator plug-in, which I run together with the editor plug-in in a second workbench. There, I'd like to run Xpand workflows programmatically on the model file I create. If I set the model file using the absolute path of the IFile I have, e.g. with:
```
String dslFile = file.getLocation().makeAbsolute().toOSString();
```
Or if I use a file URI retrieved with:
```
String dslFile = file.getLocationURI().toString();
```
The file is not found:
```
org.eclipse.emf.ecore.resource.Resource$IOWrappedException: Resource '/absolute/path/to/my/existing/dsl.file' does not exist.
at org.openarchitectureware.xtext.parser.impl.AbstractParserComponent.invokeInternal(AbstractParserComponent.java:55)
```
To what value should I set the model file attribute (dslFile) in the map I hand to the WorkflowRunner:
```
Map properties = new HashMap();
properties.put("modelFile", dslFile);
```
I also tried leaving the properties empty and referencing the model file relative to the workflow file (inside the workflow file), but that yields a FileNotFoundException. Running all of this in a normal app (not in a second workbench) works fine. | I found help at the [openArchitectureWare forum](http://openarchitectureware.org/forum/viewtopic.php?showtopic=10197). Basically using
```
properties.put("modelFile", file.getLocation().makeAbsolute().toOSString());
```
works, but you need to specify looking it up via URI in the workflow you are calling:
```
<component class="org.eclipse.mwe.emf.Reader">
<uri value='${modelFile}'/>
<modelSlot value='theModel'/>
</component>
``` |
139,580 | <p>I'm working on some code for a loosely coupled cluster. To achieve optimal performance during jobs, I have the cluster remap its data each time a child enters or exits. This will eventually be made optional, but for now it performs its data balancing by default. My balancing is basically just making sure that each child never has more than the average number of files per machine, plus one. The plus one is for the remainder if the division isn't clean. And since the remainder will <em>always</em> be less than the number of children [except 0 case, but we can exclude that], children after a balancing will have at most avg + 1.</p>
<p>Everything seems fine, until I realized my algorithm is O(n!). Go down the list of children, find out the avg, remainder, who has too many and who has too few. For each child in the too many list, go through list, send to each child who has too few.</p>
<p>Is there a better solution to this? I feel there must be.</p>
<p>Edit: Here is some psuedocode to show how i derived O(n!):</p>
<pre><code>foreach ( child in children ) {
if ( child.dataLoad > avg + 1 ) {
foreach ( child2 in children ) {
if ( child != child2 && child2.dataLoad < avg ) {
sendLoad(child, child2)
}
}
}
}
</code></pre>
<p>Edit: O(n^2). Foreach n, n => n*n => n^2. I guess I didn't have enough coffee this morning! ;)</p>
<p>In the future I'd like to move to a more flexible and resilient distribution method[weights and hueristics], but for now, a uniform distribution of data works.</p>
| [
{
"answer_id": 139656,
"author": "zvrba",
"author_id": 2583,
"author_profile": "https://Stackoverflow.com/users/2583",
"pm_score": 2,
"selected": false,
"text": "<p>I think that your analysis is incorrect:</p>\n\n<ul>\n<li>walking through the list to find out the average is O(n)</li>\n<li>making lists of children with too many or too few data chunks is also O(n)</li>\n<li>moving data is proportional to the amount of data</li>\n</ul>\n\n<p>How did you arrive to O(n!)?</p>\n\n<p>You can sort the list [O(n lg n) in the number of children], so that on the front you have children with too much work, and at the end children with too little work. Then traverse the list from both ends simultaneously: one iterator points to a child with excess data, the other to a child with lack of data. Transfer data, and move either one iterator forward, or the other backward.</p>\n"
},
{
"answer_id": 139827,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 3,
"selected": true,
"text": "<p>@zvrba: You do not even have to sort the list. When traversing the list the second time just move all items with less the average workload to the end of the list (you can keep a pointer to the last item at your first traversal). The order does not have to be perfect, it just changes when the iterators have to be augmented or decreased in your last step.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/139580/balanced-distribution-algorithm#139656\">See previous answer</a></p>\n\n<p>The last step would look something like:</p>\n\n<p>In the second step keep a pointer to the first item with less than average workload in child2 (to prevent the necessity to have a double link list).</p>\n\n<pre><code>for each child in list {\n if child2 == nil then assert(\"Error in logic\");\n while child.workload > avg + 1 {\n sendwork(child, child2, min(avg + 1 - child2.workload, child.workload - (avg + 1)))\n if child2.workload == avg + 1 then child2 = child2.next;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 139914,
"author": "zvrba",
"author_id": 2583,
"author_profile": "https://Stackoverflow.com/users/2583",
"pm_score": 1,
"selected": false,
"text": "<p>The code you have posted has complexity O(n^2). Still, it is possible to do it in linear time as malach has observed, where n is the number of items in the children list.</p>\n\n<p>Consider: the inner loop has n iterations, and it is executed <em>at most</em> n times. n*n = n^2.</p>\n"
},
{
"answer_id": 139958,
"author": "Justin Sheehy",
"author_id": 11944,
"author_profile": "https://Stackoverflow.com/users/11944",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to try a completely different approach, such as consistent hashing.</p>\n\n<p>See here for a relatively easy introduction to the topic:\n<a href=\"http://www8.org/w8-papers/2a-webserver/caching/paper2.html\" rel=\"nofollow noreferrer\">http://www8.org/w8-papers/2a-webserver/caching/paper2.html</a></p>\n\n<p>(There are deeper papers available as well, starting with Karger et al)</p>\n\n<p>I have created a working implementation of consistent hashing in Erlang that you can examine if you wish:</p>\n\n<p><a href=\"http://distributerl.googlecode.com/svn/trunk/chash.erl\" rel=\"nofollow noreferrer\">http://distributerl.googlecode.com/svn/trunk/chash.erl</a></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8945/"
]
| I'm working on some code for a loosely coupled cluster. To achieve optimal performance during jobs, I have the cluster remap its data each time a child enters or exits. This will eventually be made optional, but for now it performs its data balancing by default. My balancing is basically just making sure that each child never has more than the average number of files per machine, plus one. The plus one is for the remainder if the division isn't clean. And since the remainder will *always* be less than the number of children [except 0 case, but we can exclude that], children after a balancing will have at most avg + 1.
Everything seems fine, until I realized my algorithm is O(n!). Go down the list of children, find out the avg, remainder, who has too many and who has too few. For each child in the too many list, go through list, send to each child who has too few.
Is there a better solution to this? I feel there must be.
Edit: Here is some psuedocode to show how i derived O(n!):
```
foreach ( child in children ) {
if ( child.dataLoad > avg + 1 ) {
foreach ( child2 in children ) {
if ( child != child2 && child2.dataLoad < avg ) {
sendLoad(child, child2)
}
}
}
}
```
Edit: O(n^2). Foreach n, n => n\*n => n^2. I guess I didn't have enough coffee this morning! ;)
In the future I'd like to move to a more flexible and resilient distribution method[weights and hueristics], but for now, a uniform distribution of data works. | @zvrba: You do not even have to sort the list. When traversing the list the second time just move all items with less the average workload to the end of the list (you can keep a pointer to the last item at your first traversal). The order does not have to be perfect, it just changes when the iterators have to be augmented or decreased in your last step.
[See previous answer](https://stackoverflow.com/questions/139580/balanced-distribution-algorithm#139656)
The last step would look something like:
In the second step keep a pointer to the first item with less than average workload in child2 (to prevent the necessity to have a double link list).
```
for each child in list {
if child2 == nil then assert("Error in logic");
while child.workload > avg + 1 {
sendwork(child, child2, min(avg + 1 - child2.workload, child.workload - (avg + 1)))
if child2.workload == avg + 1 then child2 = child2.next;
}
}
``` |
139,592 | <p>I've got a generic dictionary <code>Dictionary<string, T></code> that I would like to essentially make a Clone() of ..any suggestions. </p>
| [
{
"answer_id": 139626,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": false,
"text": "<p>(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)</p>\n\n<p>How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.</p>\n\n<p>For instance, if you don't mind the value being a shallow clone:</p>\n\n<pre><code>var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,\n entry => entry.Value);\n</code></pre>\n\n<p>If you've already constrained T to implement ICloneable:</p>\n\n<pre><code>var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, \n entry => (T) entry.Value.Clone());\n</code></pre>\n\n<p>(Those are untested, but should work.)</p>\n"
},
{
"answer_id": 139841,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "<p>Okay, the .NET 2.0 answers:</p>\n\n<p>If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)</p>\n\n<p>If you <em>do</em> need to clone the values, you can use something like this:</p>\n\n<pre><code>public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>\n (Dictionary<TKey, TValue> original) where TValue : ICloneable\n{\n Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,\n original.Comparer);\n foreach (KeyValuePair<TKey, TValue> entry in original)\n {\n ret.Add(entry.Key, (TValue) entry.Value.Clone());\n }\n return ret;\n}\n</code></pre>\n\n<p>That relies on <code>TValue.Clone()</code> being a suitably deep clone as well, of course.</p>\n"
},
{
"answer_id": 140114,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 4,
"selected": false,
"text": "<p>For .NET 2.0 you could implement a class which inherits from <code>Dictionary</code> and implements <code>ICloneable</code>.</p>\n\n<pre><code>public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable\n{\n public IDictionary<TKey, TValue> Clone()\n {\n CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();\n\n foreach (KeyValuePair<TKey, TValue> pair in this)\n {\n clone.Add(pair.Key, (TValue)pair.Value.Clone());\n }\n\n return clone;\n }\n}\n</code></pre>\n\n<p>You can then clone the dictionary simply by calling the <code>Clone</code> method. Of course this implementation requires that the value type of the dictionary implements <code>ICloneable</code>, but otherwise a generic implementation isn't practical at all.</p>\n"
},
{
"answer_id": 140279,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 3,
"selected": false,
"text": "<p>You could always use serialization. You could serialize the object then deserialize it. That will give you a deep copy of the Dictionary and all the items inside of it. Now you can create a deep copy of any object that is marked as [Serializable] without writing any special code.</p>\n\n<p>Here are two methods that will use Binary Serialization. If you use these methods you simply call </p>\n\n<pre><code>object deepcopy = FromBinary(ToBinary(yourDictionary));\n\npublic Byte[] ToBinary()\n{\n MemoryStream ms = null;\n Byte[] byteArray = null;\n try\n {\n BinaryFormatter serializer = new BinaryFormatter();\n ms = new MemoryStream();\n serializer.Serialize(ms, this);\n byteArray = ms.ToArray();\n }\n catch (Exception unexpected)\n {\n Trace.Fail(unexpected.Message);\n throw;\n }\n finally\n {\n if (ms != null)\n ms.Close();\n }\n return byteArray;\n}\n\npublic object FromBinary(Byte[] buffer)\n{\n MemoryStream ms = null;\n object deserializedObject = null;\n\n try\n {\n BinaryFormatter serializer = new BinaryFormatter();\n ms = new MemoryStream();\n ms.Write(buffer, 0, buffer.Length);\n ms.Position = 0;\n deserializedObject = serializer.Deserialize(ms);\n }\n finally\n {\n if (ms != null)\n ms.Close();\n }\n return deserializedObject;\n}\n</code></pre>\n"
},
{
"answer_id": 1499136,
"author": "loty",
"author_id": 181952,
"author_profile": "https://Stackoverflow.com/users/181952",
"pm_score": 2,
"selected": false,
"text": "<p>Binary Serialization method works fine but in my tests it showed to be 10x slower than a non-serialization implementation of clone. Tested it on <code>Dictionary<string , List<double>></code></p>\n"
},
{
"answer_id": 4265943,
"author": "Herald Smit",
"author_id": 518635,
"author_profile": "https://Stackoverflow.com/users/518635",
"pm_score": 7,
"selected": false,
"text": "<pre><code>Dictionary<string, int> dictionary = new Dictionary<string, int>();\n\nDictionary<string, int> copy = new Dictionary<string, int>(dictionary);\n</code></pre>\n"
},
{
"answer_id": 32451470,
"author": "nikssa23",
"author_id": 1080516,
"author_profile": "https://Stackoverflow.com/users/1080516",
"pm_score": 3,
"selected": false,
"text": "<p>The best way for me is this:</p>\n\n<pre><code>Dictionary<int, int> copy= new Dictionary<int, int>(yourListOrDictionary);\n</code></pre>\n"
},
{
"answer_id": 39109022,
"author": "Arvind",
"author_id": 2766943,
"author_profile": "https://Stackoverflow.com/users/2766943",
"pm_score": 0,
"selected": false,
"text": "<p>Try this if key/values are ICloneable:</p>\n\n<pre><code> public static Dictionary<K,V> CloneDictionary<K,V>(Dictionary<K,V> dict) where K : ICloneable where V : ICloneable\n {\n Dictionary<K, V> newDict = null;\n\n if (dict != null)\n {\n // If the key and value are value types, just use copy constructor.\n if (((typeof(K).IsValueType || typeof(K) == typeof(string)) &&\n (typeof(V).IsValueType) || typeof(V) == typeof(string)))\n {\n newDict = new Dictionary<K, V>(dict);\n }\n else // prepare to clone key or value or both\n {\n newDict = new Dictionary<K, V>();\n\n foreach (KeyValuePair<K, V> kvp in dict)\n {\n K key;\n if (typeof(K).IsValueType || typeof(K) == typeof(string))\n {\n key = kvp.Key;\n }\n else\n {\n key = (K)kvp.Key.Clone();\n }\n V value;\n if (typeof(V).IsValueType || typeof(V) == typeof(string))\n {\n value = kvp.Value;\n }\n else\n {\n value = (V)kvp.Value.Clone();\n }\n\n newDict[key] = value;\n }\n }\n }\n\n return newDict;\n }\n</code></pre>\n"
},
{
"answer_id": 49430077,
"author": "BonifatiusK",
"author_id": 1613529,
"author_profile": "https://Stackoverflow.com/users/1613529",
"pm_score": 3,
"selected": false,
"text": "<p>This works fine for me</p>\n\n<pre><code> // assuming this fills the List\n List<Dictionary<string, string>> obj = this.getData(); \n\n List<Dictionary<string, string>> objCopy = new List<Dictionary<string, string>>(obj);\n</code></pre>\n\n<p>As Tomer Wolberg describes in the comments, this does not work if the value type is a mutable class. </p>\n"
},
{
"answer_id": 61707825,
"author": "peter feldman",
"author_id": 5738262,
"author_profile": "https://Stackoverflow.com/users/5738262",
"pm_score": 5,
"selected": false,
"text": "<p>That's what helped me, when I was trying to deep copy a Dictionary < string, string > </p>\n\n<pre><code>Dictionary<string, string> dict2 = new Dictionary<string, string>(dict);\n</code></pre>\n\n<p>Good luck</p>\n"
},
{
"answer_id": 64354962,
"author": "MSA",
"author_id": 4924495,
"author_profile": "https://Stackoverflow.com/users/4924495",
"pm_score": 0,
"selected": false,
"text": "<p>In the case you have a Dictionary of "object" and object can be anything like (double, int, ... or ComplexClass):</p>\n<pre><code>Dictionary<string, object> dictSrc { get; set; }\n\npublic class ComplexClass : ICloneable\n{\n \n private Point3D ...;\n private Vector3D ....;\n [...]\n\n public object Clone()\n {\n ComplexClass clone = new ComplexClass();\n clone = (ComplexClass)this.MemberwiseClone();\n return clone;\n }\n\n}\n\n\ndictSrc["toto"] = new ComplexClass()\ndictSrc["tata"] = 12.3\n...\n\ndictDest = dictSrc.ToDictionary(entry => entry.Key,\n entry => ((entry.Value is ICloneable) ? (entry.Value as ICloneable).Clone() : entry.Value) );\n\n\n</code></pre>\n"
},
{
"answer_id": 69558172,
"author": "Sariato",
"author_id": 14407593,
"author_profile": "https://Stackoverflow.com/users/14407593",
"pm_score": 0,
"selected": false,
"text": "<p>Here is some real "true deep copying" without knowing type with some recursive walk, good for the beginnig. It is good for nested types and almost any tricky type I think. I did not added nested arrays handling yet, but you can modify it by your choice.</p>\n<pre><code>Dictionary<string, Dictionary<string, dynamic>> buildInfoDict =\n new Dictionary<string, Dictionary<string, dynamic>>()\n {\n {"tag",new Dictionary<string,dynamic>(){\n { "attrName", "tag" },\n { "isCss", "False" },\n { "turnedOn","True" },\n { "tag",null }\n } },\n {"id",new Dictionary<string,dynamic>(){\n { "attrName", "id" },\n { "isCss", "False" },\n { "turnedOn","True" },\n { "id",null }\n } },\n {"width",new Dictionary<string,dynamic>(){\n { "attrName", "width" },\n { "isCss", "True" },\n { "turnedOn","True" },\n { "width","20%" }\n } },\n {"height",new Dictionary<string,dynamic>(){\n { "attrName", "height" },\n { "isCss", "True" },\n { "turnedOn","True" },\n { "height","20%" }\n } },\n {"text",new Dictionary<string,dynamic>(){\n { "attrName", null },\n { "isCss", "False" },\n { "turnedOn","True" },\n { "text","" }\n } },\n {"href",new Dictionary<string,dynamic>(){\n { "attrName", null },\n { "isCss", "False" },\n { "flags", "removeAttrIfTurnedOff" },\n { "turnedOn","True" },\n { "href","about:blank" }\n } }\n };\n\nvar cln=clone(buildInfoDict);\n\npublic static dynamic clone(dynamic obj)\n{\n dynamic cloneObj = null;\n if (IsAssignableFrom(obj, typeof(IDictionary)))\n {\n cloneObj = Activator.CreateInstance(obj.GetType());\n foreach (var key in obj.Keys)\n {\n cloneObj[key] = clone(obj[key]);\n }\n\n }\n else if (IsNumber(obj) || obj.GetType() == typeof(string))\n {\n cloneObj = obj;\n }\n else\n {\n Debugger.Break();\n }\n return cloneObj;\n}\n\n\npublic static bool IsAssignableFrom(this object obj, Type ObjType = null, Type ListType = null, bool HandleBaseTypes = false)\n{\n if (ObjType == null)\n {\n ObjType = obj.GetType();\n }\n\n bool Res;\n\n do\n {\n Res = (ObjType.IsGenericType && ObjType.GetGenericTypeDefinition().IsAssignableFrom(ListType)) ||\n (ListType == null && ObjType.IsAssignableFrom(obj.GetType()));\n ObjType = ObjType.BaseType;\n } while ((!Res && ObjType != null) && HandleBaseTypes && ObjType != typeof(object));\n\n return Res;\n}\n\npublic static bool IsNumber(this object value)\n{\n return value is sbyte\n || value is byte\n || value is short\n || value is ushort\n || value is int\n || value is uint\n || value is long\n || value is ulong\n || value is float\n || value is double\n || value is decimal;\n}\n</code></pre>\n"
},
{
"answer_id": 71386057,
"author": "Paul Yao",
"author_id": 4425192,
"author_profile": "https://Stackoverflow.com/users/4425192",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another way to clone a dictionary, assuming you know to do the "right" thing as far as handling whatever is hiding behind the "T" (a.k.a. "object") in your specific circumstances.</p>\n<pre><code>internal static Dictionary<string, object> Clone(Dictionary<string, object> dictIn) \n {\n Dictionary<string, object> dictOut = new Dictionary<string, object>();\n \n IDictionaryEnumerator enumMyDictionary = dictIn.GetEnumerator();\n while (enumMyDictionary.MoveNext())\n {\n string strKey = (string)enumMyDictionary.Key;\n object oValue = enumMyDictionary.Value;\n dictOut.Add(strKey, oValue);\n }\n \n return dictOut; \n }\n</code></pre>\n"
},
{
"answer_id": 71985784,
"author": "schwartz",
"author_id": 6414026,
"author_profile": "https://Stackoverflow.com/users/6414026",
"pm_score": 0,
"selected": false,
"text": "<p>I would evaluate if T was a value or reference type. In the case T was a value type I would use the constructor of Dictionary, and in the case when T was a reference type I would make sure T inherited from ICloneable.</p>\n<p>It will give</p>\n<pre><code> private static IDictionary<string, T> Copy<T>(this IDictionary<string, T> dict)\n where T : ICloneable\n {\n if (typeof(T).IsValueType)\n {\n return new Dictionary<string, T>(dict);\n }\n else\n {\n var copy = new Dictionary<string, T>();\n foreach (var pair in dict)\n {\n copy[pair.Key] = pair.Value;\n }\n return copy;\n }\n }\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4398/"
]
| I've got a generic dictionary `Dictionary<string, T>` that I would like to essentially make a Clone() of ..any suggestions. | Okay, the .NET 2.0 answers:
If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)
If you *do* need to clone the values, you can use something like this:
```
public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
(Dictionary<TKey, TValue> original) where TValue : ICloneable
{
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
original.Comparer);
foreach (KeyValuePair<TKey, TValue> entry in original)
{
ret.Add(entry.Key, (TValue) entry.Value.Clone());
}
return ret;
}
```
That relies on `TValue.Clone()` being a suitably deep clone as well, of course. |
139,593 | <p>I have the following code:</p>
<pre><code>info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents
</code></pre>
<p>I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at <code>WaitForExit</code>. Note also this code does NOT hang for smaller outputs (like 3KB).</p>
<p>Is it possible that the internal <code>StandardOutput</code> in <code>ProcessStartInfo</code> can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?</p>
| [
{
"answer_id": 139604,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 7,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx\" rel=\"noreferrer\">documentation</a> for <code>Process.StandardOutput</code> says to read before you wait otherwise you can deadlock, snippet copied below:</p>\n\n<pre><code> // Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = \"Write500Lines.exe\";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();\n</code></pre>\n"
},
{
"answer_id": 139653,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "<p>We have this issue as well (or a variant).</p>\n\n<p>Try the following:</p>\n\n<p>1) Add a timeout to p.WaitForExit(nnnn); where nnnn is in milliseconds.</p>\n\n<p>2) Put the ReadToEnd call before the WaitForExit call. This <em>is</em> what we've seen MS recommend.</p>\n"
},
{
"answer_id": 5441188,
"author": "song",
"author_id": 677841,
"author_profile": "https://Stackoverflow.com/users/677841",
"pm_score": -1,
"selected": false,
"text": "<p>This post maybe outdated but i found out the main cause why it usually hang is due to stack overflow for the redirectStandardoutput or if you have redirectStandarderror.</p>\n\n<p>As the output data or the error data is large, it will cause a hang time as it is still processing for indefinite duration.</p>\n\n<p>so to resolve this issue:</p>\n\n<pre><code>p.StartInfo.RedirectStandardoutput = False\np.StartInfo.RedirectStandarderror = False\n</code></pre>\n"
},
{
"answer_id": 7608823,
"author": "Mark Byers",
"author_id": 61974,
"author_profile": "https://Stackoverflow.com/users/61974",
"pm_score": 10,
"selected": true,
"text": "<p>The problem is that if you redirect <code>StandardOutput</code> and/or <code>StandardError</code> the internal buffer can become full. Whatever order you use, there can be a problem:</p>\n\n<ul>\n<li>If you wait for the process to exit before reading <code>StandardOutput</code> the process can block trying to write to it, so the process never ends.</li>\n<li>If you read from <code>StandardOutput</code> using ReadToEnd then <em>your</em> process can block if the process never closes <code>StandardOutput</code> (for example if it never terminates, or if it is blocked writing to <code>StandardError</code>).</li>\n</ul>\n\n<p>The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both <code>StandardOutput</code> and <code>StandardError</code> you can do this:</p>\n\n<p>EDIT: See answers below for how avoid an <strong>ObjectDisposedException</strong> if the timeout occurs.</p>\n\n<pre><code>using (Process process = new Process())\n{\n process.StartInfo.FileName = filename;\n process.StartInfo.Arguments = arguments;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n\n StringBuilder output = new StringBuilder();\n StringBuilder error = new StringBuilder();\n\n using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))\n using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))\n {\n process.OutputDataReceived += (sender, e) => {\n if (e.Data == null)\n {\n outputWaitHandle.Set();\n }\n else\n {\n output.AppendLine(e.Data);\n }\n };\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data == null)\n {\n errorWaitHandle.Set();\n }\n else\n {\n error.AppendLine(e.Data);\n }\n };\n\n process.Start();\n\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n if (process.WaitForExit(timeout) &&\n outputWaitHandle.WaitOne(timeout) &&\n errorWaitHandle.WaitOne(timeout))\n {\n // Process completed. Check process.ExitCode here.\n }\n else\n {\n // Timed out.\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10086961,
"author": "stevejay",
"author_id": 604006,
"author_profile": "https://Stackoverflow.com/users/604006",
"pm_score": 5,
"selected": false,
"text": "<p>Mark Byers' answer is excellent, but I would just add the following: </p>\n\n<p>The <code>OutputDataReceived</code> and <code>ErrorDataReceived</code> delegates need to be removed before the <code>outputWaitHandle</code> and <code>errorWaitHandle</code> get disposed. If the process continues to output data after the timeout has been exceeded and then terminates, the <code>outputWaitHandle</code> and <code>errorWaitHandle</code> variables will be accessed after being disposed.</p>\n\n<p>(FYI I had to add this caveat as an answer as I couldn't comment on his post.) </p>\n"
},
{
"answer_id": 11035292,
"author": "Kuzman Marinov",
"author_id": 1456498,
"author_profile": "https://Stackoverflow.com/users/1456498",
"pm_score": 1,
"selected": false,
"text": "<p>I thing that this is simple and better approach (we don't need <code>AutoResetEvent</code>):</p>\n\n<pre><code>public static string GGSCIShell(string Path, string Command)\n{\n using (Process process = new Process())\n {\n process.StartInfo.WorkingDirectory = Path;\n process.StartInfo.FileName = Path + @\"\\ggsci.exe\";\n process.StartInfo.CreateNoWindow = true;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardInput = true;\n process.StartInfo.UseShellExecute = false;\n\n StringBuilder output = new StringBuilder();\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n output.AppendLine(e.Data);\n }\n };\n\n process.Start();\n process.StandardInput.WriteLine(Command);\n process.BeginOutputReadLine();\n\n\n int timeoutParts = 10;\n int timeoutPart = (int)TIMEOUT / timeoutParts;\n do\n {\n Thread.Sleep(500);//sometimes halv scond is enough to empty output buff (therefore \"exit\" will be accepted without \"timeoutPart\" waiting)\n process.StandardInput.WriteLine(\"exit\");\n timeoutParts--;\n }\n while (!process.WaitForExit(timeoutPart) && timeoutParts > 0);\n\n if (timeoutParts <= 0)\n {\n output.AppendLine(\"------ GGSCIShell TIMEOUT: \" + TIMEOUT + \"ms ------\");\n }\n\n string result = output.ToString();\n return result;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22956924,
"author": "Karol Tyl",
"author_id": 1343408,
"author_profile": "https://Stackoverflow.com/users/1343408",
"pm_score": 4,
"selected": false,
"text": "<p>The problem with unhandled ObjectDisposedException happens when the process is timed out. In such case the other parts of the condition:</p>\n\n<pre><code>if (process.WaitForExit(timeout) \n && outputWaitHandle.WaitOne(timeout) \n && errorWaitHandle.WaitOne(timeout))\n</code></pre>\n\n<p>are not executed. I resolved this problem in a following way:</p>\n\n<pre><code>using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))\nusing (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))\n{\n using (Process process = new Process())\n {\n // preparing ProcessStartInfo\n\n try\n {\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data == null)\n {\n outputWaitHandle.Set();\n }\n else\n {\n outputBuilder.AppendLine(e.Data);\n }\n };\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data == null)\n {\n errorWaitHandle.Set();\n }\n else\n {\n errorBuilder.AppendLine(e.Data);\n }\n };\n\n process.Start();\n\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n if (process.WaitForExit(timeout))\n {\n exitCode = process.ExitCode;\n }\n else\n {\n // timed out\n }\n\n output = outputBuilder.ToString();\n }\n finally\n {\n outputWaitHandle.WaitOne(timeout);\n errorWaitHandle.WaitOne(timeout);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27920086,
"author": "Marcell",
"author_id": 4090002,
"author_profile": "https://Stackoverflow.com/users/4090002",
"pm_score": -1,
"selected": false,
"text": "<p>I was having the same issue, but the reason was different. It would however happen under Windows 8, but not under Windows 7. The following line seems to have caused the problem.</p>\n\n<pre><code>pProcess.StartInfo.UseShellExecute = False\n</code></pre>\n\n<p>The solution was to NOT disable UseShellExecute. I now received a Shell popup window, which is unwanted, but much better than the program waiting for nothing particular to happen. So I added the following work-around for that:</p>\n\n<pre><code>pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden\n</code></pre>\n\n<p>Now the only thing bothering me is to why this is happening under Windows 8 in the first place.</p>\n"
},
{
"answer_id": 32457135,
"author": "Elina Maliarsky",
"author_id": 5257482,
"author_profile": "https://Stackoverflow.com/users/5257482",
"pm_score": 2,
"selected": false,
"text": "<p>I solved it this way:</p>\n\n<pre><code> Process proc = new Process();\n proc.StartInfo.FileName = batchFile;\n proc.StartInfo.UseShellExecute = false;\n proc.StartInfo.CreateNoWindow = true;\n proc.StartInfo.RedirectStandardError = true;\n proc.StartInfo.RedirectStandardInput = true;\n proc.StartInfo.RedirectStandardOutput = true;\n proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; \n proc.Start();\n StreamWriter streamWriter = proc.StandardInput;\n StreamReader outputReader = proc.StandardOutput;\n StreamReader errorReader = proc.StandardError;\n while (!outputReader.EndOfStream)\n {\n string text = outputReader.ReadLine(); \n streamWriter.WriteLine(text);\n }\n\n while (!errorReader.EndOfStream)\n { \n string text = errorReader.ReadLine();\n streamWriter.WriteLine(text);\n }\n\n streamWriter.Close();\n proc.WaitForExit();\n</code></pre>\n\n<p>I redirected both input, output and error and handled reading from output and error streams.\nThis solution works for SDK 7- 8.1, both for Windows 7 and Windows 8 </p>\n"
},
{
"answer_id": 34687299,
"author": "Jon",
"author_id": 3072057,
"author_profile": "https://Stackoverflow.com/users/3072057",
"pm_score": 3,
"selected": false,
"text": "<p>Rob answered it and saved me few more hours of trials. Read the output/error buffer before waiting:</p>\n\n<pre><code>// Read the output stream first and then wait.\nstring output = p.StandardOutput.ReadToEnd();\np.WaitForExit();\n</code></pre>\n"
},
{
"answer_id": 39872058,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 5,
"selected": false,
"text": "<p>This is a more modern awaitable, Task Parallel Library (TPL) based solution for .NET 4.5 and above.</p>\n\n<h1>Usage Example</h1>\n\n<pre><code>try\n{\n var exitCode = await StartProcess(\n \"dotnet\", \n \"--version\", \n @\"C:\\\",\n 10000, \n Console.Out, \n Console.Out);\n Console.WriteLine($\"Process Exited with Exit Code {exitCode}!\");\n}\ncatch (TaskCanceledException)\n{\n Console.WriteLine(\"Process Timed Out!\");\n}\n</code></pre>\n\n<h1>Implementation</h1>\n\n<pre><code>public static async Task<int> StartProcess(\n string filename,\n string arguments,\n string workingDirectory= null,\n int? timeout = null,\n TextWriter outputTextWriter = null,\n TextWriter errorTextWriter = null)\n{\n using (var process = new Process()\n {\n StartInfo = new ProcessStartInfo()\n {\n CreateNoWindow = true,\n Arguments = arguments,\n FileName = filename,\n RedirectStandardOutput = outputTextWriter != null,\n RedirectStandardError = errorTextWriter != null,\n UseShellExecute = false,\n WorkingDirectory = workingDirectory\n }\n })\n {\n var cancellationTokenSource = timeout.HasValue ?\n new CancellationTokenSource(timeout.Value) :\n new CancellationTokenSource();\n\n process.Start();\n\n var tasks = new List<Task>(3) { process.WaitForExitAsync(cancellationTokenSource.Token) };\n if (outputTextWriter != null)\n {\n tasks.Add(ReadAsync(\n x =>\n {\n process.OutputDataReceived += x;\n process.BeginOutputReadLine();\n },\n x => process.OutputDataReceived -= x,\n outputTextWriter,\n cancellationTokenSource.Token));\n }\n\n if (errorTextWriter != null)\n {\n tasks.Add(ReadAsync(\n x =>\n {\n process.ErrorDataReceived += x;\n process.BeginErrorReadLine();\n },\n x => process.ErrorDataReceived -= x,\n errorTextWriter,\n cancellationTokenSource.Token));\n }\n\n await Task.WhenAll(tasks);\n return process.ExitCode;\n }\n}\n\n/// <summary>\n/// Waits asynchronously for the process to exit.\n/// </summary>\n/// <param name=\"process\">The process to wait for cancellation.</param>\n/// <param name=\"cancellationToken\">A cancellation token. If invoked, the task will return\n/// immediately as cancelled.</param>\n/// <returns>A Task representing waiting for the process to end.</returns>\npublic static Task WaitForExitAsync(\n this Process process,\n CancellationToken cancellationToken = default(CancellationToken))\n{\n process.EnableRaisingEvents = true;\n\n var taskCompletionSource = new TaskCompletionSource<object>();\n\n EventHandler handler = null;\n handler = (sender, args) =>\n {\n process.Exited -= handler;\n taskCompletionSource.TrySetResult(null);\n };\n process.Exited += handler;\n\n if (cancellationToken != default(CancellationToken))\n {\n cancellationToken.Register(\n () =>\n {\n process.Exited -= handler;\n taskCompletionSource.TrySetCanceled();\n });\n }\n\n return taskCompletionSource.Task;\n}\n\n/// <summary>\n/// Reads the data from the specified data recieved event and writes it to the\n/// <paramref name=\"textWriter\"/>.\n/// </summary>\n/// <param name=\"addHandler\">Adds the event handler.</param>\n/// <param name=\"removeHandler\">Removes the event handler.</param>\n/// <param name=\"textWriter\">The text writer.</param>\n/// <param name=\"cancellationToken\">The cancellation token.</param>\n/// <returns>A task representing the asynchronous operation.</returns>\npublic static Task ReadAsync(\n this Action<DataReceivedEventHandler> addHandler,\n Action<DataReceivedEventHandler> removeHandler,\n TextWriter textWriter,\n CancellationToken cancellationToken = default(CancellationToken))\n{\n var taskCompletionSource = new TaskCompletionSource<object>();\n\n DataReceivedEventHandler handler = null;\n handler = new DataReceivedEventHandler(\n (sender, e) =>\n {\n if (e.Data == null)\n {\n removeHandler(handler);\n taskCompletionSource.TrySetResult(null);\n }\n else\n {\n textWriter.WriteLine(e.Data);\n }\n });\n\n addHandler(handler);\n\n if (cancellationToken != default(CancellationToken))\n {\n cancellationToken.Register(\n () =>\n {\n removeHandler(handler);\n taskCompletionSource.TrySetCanceled();\n });\n }\n\n return taskCompletionSource.Task;\n}\n</code></pre>\n"
},
{
"answer_id": 41722847,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 2,
"selected": false,
"text": "<p>I tried to make a class that would solve your problem using asynchronous stream read, by taking in account Mark Byers, Rob, stevejay answers. Doing so I realised that there is a bug related to asynchronous process output stream read.</p>\n\n<p>I reported that bug at Microsoft: <a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/3119134\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/details/3119134</a></p>\n\n<p>Summary:</p>\n\n<blockquote>\n <p>You can't do that:</p>\n \n <p>process.BeginOutputReadLine(); process.Start();</p>\n \n <p>You will receive System.InvalidOperationException : StandardOut has\n not been redirected or the process hasn't started yet.</p>\n \n <p>============================================================================================================================</p>\n \n <p>Then you have to start asynchronous output read after the process is\n started:</p>\n \n <p>process.Start(); process.BeginOutputReadLine();</p>\n \n <p>Doing so, make a race condition because the output stream can receive\n data before you set it to asynchronous:</p>\n</blockquote>\n\n<pre><code>process.Start(); \n// Here the operating system could give the cpu to another thread. \n// For example, the newly created thread (Process) and it could start writing to the output\n// immediately before next line would execute. \n// That create a race condition.\nprocess.BeginOutputReadLine();\n</code></pre>\n\n<blockquote>\n <p>============================================================================================================================</p>\n \n <p>Then some people could say that you just have to read the stream\n before you set it to asynchronous. But the same problem occurs. There\n will be a race condition between the synchronous read and set the\n stream into asynchronous mode.</p>\n \n <p>============================================================================================================================</p>\n \n <p>There is no way to acheive safe asynchronous read of an output stream\n of a process in the actual way \"Process\" and \"ProcessStartInfo\" has\n been designed.</p>\n</blockquote>\n\n<p>You are probably better using asynchronous read like suggested by other users for your case. But you should be aware that you could miss some information due to race condition.</p>\n"
},
{
"answer_id": 42140736,
"author": "omriman12",
"author_id": 2338687,
"author_profile": "https://Stackoverflow.com/users/2338687",
"pm_score": 1,
"selected": false,
"text": "<p>None of the answers above is doing the job.</p>\n\n<p>Rob solution hangs and 'Mark Byers' solution get the disposed exception.(I tried the \"solutions\" of the other answers).</p>\n\n<p>So I decided to suggest another solution:</p>\n\n<pre><code>public void GetProcessOutputWithTimeout(Process process, int timeoutSec, CancellationToken token, out string output, out int exitCode)\n{\n string outputLocal = \"\"; int localExitCode = -1;\n var task = System.Threading.Tasks.Task.Factory.StartNew(() =>\n {\n outputLocal = process.StandardOutput.ReadToEnd();\n process.WaitForExit();\n localExitCode = process.ExitCode;\n }, token);\n\n if (task.Wait(timeoutSec, token))\n {\n output = outputLocal;\n exitCode = localExitCode;\n }\n else\n {\n exitCode = -1;\n output = \"\";\n }\n}\n\nusing (var process = new Process())\n{\n process.StartInfo = ...;\n process.Start();\n string outputUnicode; int exitCode;\n GetProcessOutputWithTimeout(process, PROCESS_TIMEOUT, out outputUnicode, out exitCode);\n}\n</code></pre>\n\n<p>This code debugged and works perfectly.</p>\n"
},
{
"answer_id": 43211575,
"author": "Marko Avlijaš",
"author_id": 5712410,
"author_profile": "https://Stackoverflow.com/users/5712410",
"pm_score": 1,
"selected": false,
"text": "<h2>Introduction</h2>\n\n<p>Currently accepted answer doesn't work (throws exception) and there are too many workarounds but no complete code. This is obviously wasting lots of people's time because this is a popular question.</p>\n\n<p>Combining Mark Byers' answer and Karol Tyl's answer I wrote full code based on how I want to use the Process.Start method.</p>\n\n<h2>Usage</h2>\n\n<p>I have used it to create progress dialog around git commands. This is how I've used it:</p>\n\n<pre><code> private bool Run(string fullCommand)\n {\n Error = \"\";\n int timeout = 5000;\n\n var result = ProcessNoBS.Start(\n filename: @\"C:\\Program Files\\Git\\cmd\\git.exe\",\n arguments: fullCommand,\n timeoutInMs: timeout,\n workingDir: @\"C:\\test\");\n\n if (result.hasTimedOut)\n {\n Error = String.Format(\"Timeout ({0} sec)\", timeout/1000);\n return false;\n }\n\n if (result.ExitCode != 0)\n {\n Error = (String.IsNullOrWhiteSpace(result.stderr)) \n ? result.stdout : result.stderr;\n return false;\n }\n\n return true;\n }\n</code></pre>\n\n<p>In theory you can also combine stdout and stderr, but I haven't tested that.</p>\n\n<h2>Code</h2>\n\n<pre><code>public struct ProcessResult\n{\n public string stdout;\n public string stderr;\n public bool hasTimedOut;\n private int? exitCode;\n\n public ProcessResult(bool hasTimedOut = true)\n {\n this.hasTimedOut = hasTimedOut;\n stdout = null;\n stderr = null;\n exitCode = null;\n }\n\n public int ExitCode\n {\n get \n {\n if (hasTimedOut)\n throw new InvalidOperationException(\n \"There was no exit code - process has timed out.\");\n\n return (int)exitCode;\n }\n set\n {\n exitCode = value;\n }\n }\n}\n\npublic class ProcessNoBS\n{\n public static ProcessResult Start(string filename, string arguments,\n string workingDir = null, int timeoutInMs = 5000,\n bool combineStdoutAndStderr = false)\n {\n using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))\n using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))\n {\n using (var process = new Process())\n {\n var info = new ProcessStartInfo();\n\n info.CreateNoWindow = true;\n info.FileName = filename;\n info.Arguments = arguments;\n info.UseShellExecute = false;\n info.RedirectStandardOutput = true;\n info.RedirectStandardError = true;\n\n if (workingDir != null)\n info.WorkingDirectory = workingDir;\n\n process.StartInfo = info;\n\n StringBuilder stdout = new StringBuilder();\n StringBuilder stderr = combineStdoutAndStderr\n ? stdout : new StringBuilder();\n\n var result = new ProcessResult();\n\n try\n {\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data == null)\n outputWaitHandle.Set();\n else\n stdout.AppendLine(e.Data);\n };\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data == null)\n errorWaitHandle.Set();\n else\n stderr.AppendLine(e.Data);\n };\n\n process.Start();\n\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n if (process.WaitForExit(timeoutInMs))\n result.ExitCode = process.ExitCode;\n // else process has timed out \n // but that's already default ProcessResult\n\n result.stdout = stdout.ToString();\n if (combineStdoutAndStderr)\n result.stderr = null;\n else\n result.stderr = stderr.ToString();\n\n return result;\n }\n finally\n {\n outputWaitHandle.WaitOne(timeoutInMs);\n errorWaitHandle.WaitOne(timeoutInMs);\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 44428790,
"author": "Alexis Coles",
"author_id": 960750,
"author_profile": "https://Stackoverflow.com/users/960750",
"pm_score": 1,
"selected": false,
"text": "<p>I know that this is supper old but, after reading this whole page none of the solutions was working for me, although I didn't try Muhammad Rehan as the code was a little hard to follow, although I guess he was on the right track. When I say it didn't work that's not entirely true, sometimes it would work fine, I guess it is something to do with the length of the output before an EOF mark.</p>\n\n<p>Anyway, the solution that worked for me was to use different threads to read the StandardOutput and StandardError and write the messages.</p>\n\n<pre><code> StreamWriter sw = null;\n var queue = new ConcurrentQueue<string>();\n\n var flushTask = new System.Timers.Timer(50);\n flushTask.Elapsed += (s, e) =>\n {\n while (!queue.IsEmpty)\n {\n string line = null;\n if (queue.TryDequeue(out line))\n sw.WriteLine(line);\n }\n sw.FlushAsync();\n };\n flushTask.Start();\n\n using (var process = new Process())\n {\n try\n {\n process.StartInfo.FileName = @\"...\";\n process.StartInfo.Arguments = $\"...\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n\n process.Start();\n\n var outputRead = Task.Run(() =>\n {\n while (!process.StandardOutput.EndOfStream)\n {\n queue.Enqueue(process.StandardOutput.ReadLine());\n }\n });\n\n var errorRead = Task.Run(() =>\n {\n while (!process.StandardError.EndOfStream)\n {\n queue.Enqueue(process.StandardError.ReadLine());\n }\n });\n\n var timeout = new TimeSpan(hours: 0, minutes: 10, seconds: 0);\n\n if (Task.WaitAll(new[] { outputRead, errorRead }, timeout) &&\n process.WaitForExit((int)timeout.TotalMilliseconds))\n {\n if (process.ExitCode != 0)\n {\n throw new Exception($\"Failed run... blah blah\");\n }\n }\n else\n {\n throw new Exception($\"process timed out after waiting {timeout}\");\n }\n }\n catch (Exception e)\n {\n throw new Exception($\"Failed to succesfully run the process.....\", e);\n }\n }\n }\n</code></pre>\n\n<p>Hope this helps someone, who thought this could be so hard!</p>\n"
},
{
"answer_id": 47213952,
"author": "ergohack",
"author_id": 4151626,
"author_profile": "https://Stackoverflow.com/users/4151626",
"pm_score": 3,
"selected": false,
"text": "<p>Credit to <a href=\"https://stackoverflow.com/users/1536933/em0\" title=\"EM0\">EM0</a> for <a href=\"https://stackoverflow.com/a/17600012/4151626\">https://stackoverflow.com/a/17600012/4151626</a></p>\n\n<p>The other solutions (including EM0's) still deadlocked for my application, due to internal timeouts and the use of both StandardOutput and StandardError by the spawned application. Here is what worked for me:</p>\n\n<pre><code>Process p = new Process()\n{\n StartInfo = new ProcessStartInfo()\n {\n FileName = exe,\n Arguments = args,\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true\n }\n};\np.Start();\n\nstring cv_error = null;\nThread et = new Thread(() => { cv_error = p.StandardError.ReadToEnd(); });\net.Start();\n\nstring cv_out = null;\nThread ot = new Thread(() => { cv_out = p.StandardOutput.ReadToEnd(); });\not.Start();\n\np.WaitForExit();\not.Join();\net.Join();\n</code></pre>\n\n<p>Edit: added initialization of StartInfo to code sample </p>\n"
},
{
"answer_id": 48564890,
"author": "flapster",
"author_id": 4177026,
"author_profile": "https://Stackoverflow.com/users/4177026",
"pm_score": 1,
"selected": false,
"text": "<p>After reading all the posts here, i settled on the consolidated solution of Marko Avlijaš.\n<strong>However</strong>, it did not solve all of my issues.</p>\n\n<p>In our environment we have a Windows Service which is scheduled to run hundreds of different .bat .cmd .exe,... etc. files which have accumulated over the years and were written by many different people and in different styles. We have no control over the writing of the programs & scripts, we are just responsible for scheduling, running, and reporting on success/failure.</p>\n\n<p>So i tried pretty much all of the suggestions here with different levels of success. Marko's answer was almost perfect, but when run as a service, it didnt always capture stdout. I never got to the bottom of why not.</p>\n\n<p>The only solution we found that works in ALL our cases is this : <a href=\"http://csharptest.net/319/using-the-processrunner-class/index.html\" rel=\"nofollow noreferrer\">http://csharptest.net/319/using-the-processrunner-class/index.html</a></p>\n"
},
{
"answer_id": 53504707,
"author": "Yepeekai",
"author_id": 413464,
"author_profile": "https://Stackoverflow.com/users/413464",
"pm_score": 2,
"selected": false,
"text": "<p>I think with async, it is possible to have a more elegant solution and not having deadlocks even when using both standardOutput and standardError:</p>\n\n<pre><code>using (Process process = new Process())\n{\n process.StartInfo.FileName = filename;\n process.StartInfo.Arguments = arguments;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n\n process.Start();\n\n var tStandardOutput = process.StandardOutput.ReadToEndAsync();\n var tStandardError = process.StandardError.ReadToEndAsync();\n\n if (process.WaitForExit(timeout))\n {\n string output = await tStandardOutput;\n string errors = await tStandardError;\n\n // Process completed. Check process.ExitCode here.\n }\n else\n {\n // Timed out.\n }\n}\n</code></pre>\n\n<p>It is base on Mark Byers answer.\nIf you are not in an async method, you can use <code>string output = tStandardOutput.result;</code> instead of <code>await</code></p>\n"
},
{
"answer_id": 54191042,
"author": "Sam Hobbs",
"author_id": 2392247,
"author_profile": "https://Stackoverflow.com/users/2392247",
"pm_score": -1,
"selected": false,
"text": "<p>Let us call the sample code posted here the redirector and the other program the redirected. If it were me then I would probably write a test redirected program that can be used to duplicate the problem.</p>\n\n<p>So I did. For test data I used the ECMA-334 C# Language Specificationv PDF; it is about 5MB. The following is the important part of that.</p>\n\n<pre><code>StreamReader stream = null;\ntry { stream = new StreamReader(Path); }\ncatch (Exception ex)\n{\n Console.Error.WriteLine(\"Input open error: \" + ex.Message);\n return;\n}\nConsole.SetIn(stream);\nint datasize = 0;\ntry\n{\n string record = Console.ReadLine();\n while (record != null)\n {\n datasize += record.Length + 2;\n record = Console.ReadLine();\n Console.WriteLine(record);\n }\n}\ncatch (Exception ex)\n{\n Console.Error.WriteLine($\"Error: {ex.Message}\");\n return;\n}\n</code></pre>\n\n<p>The datasize value does not match the actual file size but that does not matter. It is not clear if a PDF file always uses both CR and LF at the end of lines but that does not matter for this. You can use any other large text file to test with.</p>\n\n<p>Using that the sample redirector code hangs when I write the large amount of data but not when I write a small amount.</p>\n\n<p>I tried very much to somehow trace the execution of that code and I could not. I commented out the lines of the redirected program that disabled creation of a console for the redirected program to try to get a separate console window but I could not.</p>\n\n<p>Then I found <a href=\"https://blogs.msdn.microsoft.com/jmstall/2006/09/28/how-to-start-a-console-app-in-a-new-window-the-parents-window-or-no-window\" rel=\"nofollow noreferrer\">How to start a console app in a new window, the parent’s window, or no window</a>. So apparently we cannot (easily) have a separate console when one console program starts another console program without ShellExecute and since ShellExecute does not support redirection we must share a console, even if we specify no window for the other process.</p>\n\n<p>I assume that if the redirected program fills up a buffer somewhere then it must wait for the data to be read and if at that point no data is read by the redirector then it is a deadlock.</p>\n\n<p>The solution is to not use ReadToEnd and to read the data while the data is being written but it is not necessary to use asynchronous reads. The solution can be quite simple. The following works for me with the 5 MB PDF.</p>\n\n<pre><code>ProcessStartInfo info = new ProcessStartInfo(TheProgram);\ninfo.CreateNoWindow = true;\ninfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\ninfo.RedirectStandardOutput = true;\ninfo.UseShellExecute = false;\nProcess p = Process.Start(info);\nstring record = p.StandardOutput.ReadLine();\nwhile (record != null)\n{\n Console.WriteLine(record);\n record = p.StandardOutput.ReadLine();\n}\np.WaitForExit();\n</code></pre>\n\n<p>Another possibility is to use a GUI program to do the redirection. The preceding code works in a WPF application except with obvious modifications.</p>\n"
},
{
"answer_id": 56490740,
"author": "eglasius",
"author_id": 66372,
"author_profile": "https://Stackoverflow.com/users/66372",
"pm_score": 1,
"selected": false,
"text": "<p>Workaround I ended up using to avoid all the complexity:</p>\n\n<pre><code>var outputFile = Path.GetTempFileName();\ninfo = new System.Diagnostics.ProcessStartInfo(\"TheProgram.exe\", String.Join(\" \", args) + \" > \" + outputFile + \" 2>&1\");\ninfo.CreateNoWindow = true;\ninfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\ninfo.UseShellExecute = false;\nSystem.Diagnostics.Process p = System.Diagnostics.Process.Start(info);\np.WaitForExit();\nConsole.WriteLine(File.ReadAllText(outputFile)); //need the StandardOutput contents\n</code></pre>\n\n<p>So I create a temp file, redirect both the output and error to it by using <code>> outputfile > 2>&1</code> and then just read the file after the process has finished.</p>\n\n<p>The other solutions are fine for scenarios where you want to do other stuff with the output, but for simple stuff this avoids a lot of complexity.</p>\n"
},
{
"answer_id": 57940402,
"author": "Deepscorn",
"author_id": 884195,
"author_profile": "https://Stackoverflow.com/users/884195",
"pm_score": 1,
"selected": false,
"text": "<p>I've read many of the answers and made my own. Not sure this one will fix in any case, but it fixes in my environment. I'm just not using WaitForExit and use WaitHandle.WaitAll on both output & error end signals. I will be glad, if someone will see possible problems with that. Or if it will help someone. For me it's better because not uses timeouts.</p>\n\n<pre><code>private static int DoProcess(string workingDir, string fileName, string arguments)\n{\n int exitCode;\n using (var process = new Process\n {\n StartInfo =\n {\n WorkingDirectory = workingDir,\n WindowStyle = ProcessWindowStyle.Hidden,\n CreateNoWindow = true,\n UseShellExecute = false,\n FileName = fileName,\n Arguments = arguments,\n RedirectStandardError = true,\n RedirectStandardOutput = true\n },\n EnableRaisingEvents = true\n })\n {\n using (var outputWaitHandle = new AutoResetEvent(false))\n using (var errorWaitHandle = new AutoResetEvent(false))\n {\n process.OutputDataReceived += (sender, args) =>\n {\n // ReSharper disable once AccessToDisposedClosure\n if (args.Data != null) Debug.Log(args.Data);\n else outputWaitHandle.Set();\n };\n process.ErrorDataReceived += (sender, args) =>\n {\n // ReSharper disable once AccessToDisposedClosure\n if (args.Data != null) Debug.LogError(args.Data);\n else errorWaitHandle.Set();\n };\n\n process.Start();\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n WaitHandle.WaitAll(new WaitHandle[] { outputWaitHandle, errorWaitHandle });\n\n exitCode = process.ExitCode;\n }\n }\n return exitCode;\n}\n</code></pre>\n"
},
{
"answer_id": 73454991,
"author": "Koby Douek",
"author_id": 1694368,
"author_profile": "https://Stackoverflow.com/users/1694368",
"pm_score": 0,
"selected": false,
"text": "<p>In my case I had an error so I just waited in vain for a normal ouput.</p>\n<p>I switched the order from this:</p>\n<pre><code>string result = process.StandardOutput.ReadToEnd();\nstring error = process.StandardError.ReadToEnd();\n</code></pre>\n<p>To this:</p>\n<pre><code>string error = process.StandardError.ReadToEnd();\n\nif (string.IsNullOrEmpty(error))\n string result = process.StandardOutput.ReadToEnd();\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
]
| I have the following code:
```
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents
```
I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at `WaitForExit`. Note also this code does NOT hang for smaller outputs (like 3KB).
Is it possible that the internal `StandardOutput` in `ProcessStartInfo` can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong? | The problem is that if you redirect `StandardOutput` and/or `StandardError` the internal buffer can become full. Whatever order you use, there can be a problem:
* If you wait for the process to exit before reading `StandardOutput` the process can block trying to write to it, so the process never ends.
* If you read from `StandardOutput` using ReadToEnd then *your* process can block if the process never closes `StandardOutput` (for example if it never terminates, or if it is blocked writing to `StandardError`).
The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both `StandardOutput` and `StandardError` you can do this:
EDIT: See answers below for how avoid an **ObjectDisposedException** if the timeout occurs.
```
using (Process process = new Process())
{
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) => {
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(timeout) &&
outputWaitHandle.WaitOne(timeout) &&
errorWaitHandle.WaitOne(timeout))
{
// Process completed. Check process.ExitCode here.
}
else
{
// Timed out.
}
}
}
``` |
139,623 | <p>How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript.</p>
<p>So far I have the following but it has no time delay</p>
<pre><code><body onload="document.location='newPage.html'">
</code></pre>
| [
{
"answer_id": 139660,
"author": "slashnick",
"author_id": 21030,
"author_profile": "https://Stackoverflow.com/users/21030",
"pm_score": 5,
"selected": true,
"text": "<p>A meta refresh is ugly but will work. The following will go to the new url after 5 seconds: </p>\n\n<pre><code><meta http-equiv=\"refresh\" content=\"5;url=http://example.com/\"/>\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Meta_refresh\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Meta_refresh</a></p>\n"
},
{
"answer_id": 139661,
"author": "hubbardr",
"author_id": 22457,
"author_profile": "https://Stackoverflow.com/users/22457",
"pm_score": 1,
"selected": false,
"text": "<p>Put this is in the head:</p>\n\n<pre><code><meta http-equiv=\"refresh\" content=\"5;url=newPage.html\">\n</code></pre>\n\n<p>This will redirect after 5 seconds. Make 0 to redirect onload. </p>\n"
},
{
"answer_id": 139662,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 1,
"selected": false,
"text": "<p>You can use good ole' <a href=\"http://webmaster.indiana.edu/tool_guide_info/refresh_metatag.shtml\" rel=\"nofollow noreferrer\">META REFRESH</a>, no JS required, although those are (I think) deprecated.</p>\n"
},
{
"answer_id": 139680,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>If you are going the JS route just use</p>\n\n<pre><code>setTimeout(\"window.location.href = 'newPage.html';\", 5000);\n</code></pre>\n"
},
{
"answer_id": 139740,
"author": "Huuuze",
"author_id": 10040,
"author_profile": "https://Stackoverflow.com/users/10040",
"pm_score": 1,
"selected": false,
"text": "<p>The Meta Refresh is the way to go, but here is the JavaScript solution:</p>\n\n<pre><code><body onload=\"setTimeout('window.location = \\'newpage.html\\'', 5000)\">\n</code></pre>\n\n<p>More details can be found <a href=\"http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 141456,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "<p>The JavaScript method, without invoking <code>eval</code> in the the <code>setTimeout</code>:</p>\n\n<pre><code><body onload=\"setTimeout(function(){window.location.href='newpage.html'}, 5000)\">\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
| How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript.
So far I have the following but it has no time delay
```
<body onload="document.location='newPage.html'">
``` | A meta refresh is ugly but will work. The following will go to the new url after 5 seconds:
```
<meta http-equiv="refresh" content="5;url=http://example.com/"/>
```
<http://en.wikipedia.org/wiki/Meta_refresh> |
139,630 | <p>What's the difference between <code>TRUNCATE</code> and <code>DELETE</code> in SQL?</p>
<p>If your answer is platform specific, please indicate that.</p>
| [
{
"answer_id": 139633,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 9,
"selected": true,
"text": "<p>Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.</p>\n\n<p><hr></p>\n\n<h1>General Overview</h1>\n\n<p>If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.</p>\n\n<p>Various system-specific issues have to be considered, as detailed below.</p>\n\n<p><hr></p>\n\n<h1>Statement type</h1>\n\n<p>Delete is DML, Truncate is DDL (<a href=\"https://stackoverflow.com/q/2578194/276052\">What is DDL and DML?</a>)</p>\n\n<p><hr></p>\n\n<h1>Commit and Rollback</h1>\n\n<p>Variable by vendor</p>\n\n<p><strong>SQL*Server</strong></p>\n\n<p>Truncate can be rolled back.</p>\n\n<p><strong>PostgreSQL</strong></p>\n\n<p>Truncate can be rolled back.</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.</p>\n\n<p>However, see Flashback below.</p>\n\n<p><hr></p>\n\n<h1>Space reclamation</h1>\n\n<p>Delete does not recover space, Truncate recovers space</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.</p>\n\n<p><hr></p>\n\n<h1>Row scope</h1>\n\n<p>Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.</p>\n\n<p><hr></p>\n\n<h1>Object types</h1>\n\n<p>Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)</p>\n\n<p><hr></p>\n\n<h1>Data Object Identity</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>Delete does not affect the data object id, but truncate assigns a new data object id <em>unless</em> there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.</p>\n\n<p><hr></p>\n\n<h1>Flashback (Oracle)</h1>\n\n<p>Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.</p>\n\n<p>However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition</p>\n\n<p><a href=\"https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle\">Use of FLASHBACK in Oracle</a>\n<a href=\"http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638\" rel=\"noreferrer\">http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638</a></p>\n\n<p><hr></p>\n\n<h1>Privileges</h1>\n\n<p>Variable</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.</p>\n\n<p><hr></p>\n\n<h1>Redo/Undo</h1>\n\n<p>Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.</p>\n\n<p><hr></p>\n\n<h1>Indexes</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>A truncate operation renders unusable indexes usable again. Delete does not.</p>\n\n<p><hr></p>\n\n<h1>Foreign Keys</h1>\n\n<p>A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.</p>\n\n<p><hr></p>\n\n<h1>Table Locking</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.</p>\n\n<p><hr></p>\n\n<h1>Triggers</h1>\n\n<p>DML triggers do not fire on a truncate.</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>DDL triggers are available.</p>\n\n<p><hr></p>\n\n<h1>Remote Execution</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>Truncate cannot be issued over a database link.</p>\n\n<p><hr></p>\n\n<h1>Identity Columns</h1>\n\n<p><strong>SQL*Server</strong></p>\n\n<p>Truncate resets the sequence for IDENTITY column types, delete does not.</p>\n\n<p><hr></p>\n\n<h1>Result set</h1>\n\n<p>In most implementations, a <code>DELETE</code> statement can return to the client the rows that were deleted.</p>\n\n<p>e.g. in an Oracle PL/SQL subprogram you could:</p>\n\n<pre><code>DELETE FROM employees_temp\nWHERE employee_id = 299 \nRETURNING first_name,\n last_name\nINTO emp_first_name,\n emp_last_name;\n</code></pre>\n"
},
{
"answer_id": 139646,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 4,
"selected": false,
"text": "<p>With SQL Server or MySQL, if there is a PK with auto increment, truncate will reset the counter.</p>\n"
},
{
"answer_id": 139648,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 0,
"selected": false,
"text": "<p>In short, truncate doesn't log anything (so is much faster but can't be undone) whereas delete is logged (and can be part of a larger transaction, will rollback etc). If you have data that you don't want in a table in dev it is normally better to truncate as you don't run the risk of filling up the transaction log</p>\n"
},
{
"answer_id": 139649,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 1,
"selected": false,
"text": "<p>The biggest difference is that truncate is non logged operation while delete is.</p>\n\n<p>Simply it means that in case of a database crash , you cannot recover the data operated upon by truncate but with delete you can. </p>\n\n<p>More details <a href=\"http://doc.ddart.net/mssql/sql70/8_des_02_8.htm\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 139764,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 4,
"selected": false,
"text": "<p>\"Truncate doesn't log anything\" is correct. I'd go further:</p>\n\n<p>Truncate is not executed in the context of a transaction. </p>\n\n<p>The speed advantage of truncate over delete should be obvious. That advantage ranges from trivial to enormous, depending on your situation.</p>\n\n<p>However, I've seen truncate unintentionally break referential integrity, and violate other constraints. The power that you gain by modifying data outside a transaction has to be balanced against the responsibility that you inherit when you walk the tightrope without a net.</p>\n"
},
{
"answer_id": 139803,
"author": "Jordan Ogren",
"author_id": 21888,
"author_profile": "https://Stackoverflow.com/users/21888",
"pm_score": 0,
"selected": false,
"text": "<p>A big reason it is handy, is when you need to refresh the data in a multi-million row table, but don't want to rebuild it. \"Delete *\" would take forever, whereas the perfomance impact of Truncate would be negligible.</p>\n"
},
{
"answer_id": 139877,
"author": "polara",
"author_id": 8754,
"author_profile": "https://Stackoverflow.com/users/8754",
"pm_score": 5,
"selected": false,
"text": "<p>All good answers, to which I must add:</p>\n\n<p>Since <code>TRUNCATE TABLE</code> is a DDL (<a href=\"https://en.wikipedia.org/wiki/Data_definition_language\" rel=\"noreferrer\">Data Defination Language</a>), not a DML (<a href=\"https://en.wikipedia.org/wiki/Data_manipulation_language\" rel=\"noreferrer\">Data Manipulation Langauge</a>) command, the <code>Delete Triggers</code> do not run.</p>\n"
},
{
"answer_id": 142509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Can't do DDL over a dblink.</p>\n"
},
{
"answer_id": 142672,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 0,
"selected": false,
"text": "<p>I'd comment on matthieu's post, but I don't have the rep yet...</p>\n\n<p>In MySQL, the auto increment counter gets reset with truncate, but not with delete.</p>\n"
},
{
"answer_id": 142687,
"author": "databyss",
"author_id": 9094,
"author_profile": "https://Stackoverflow.com/users/9094",
"pm_score": -1,
"selected": false,
"text": "<p>TRUNCATE is fast, DELETE is slow.</p>\n\n<p>Although, TRUNCATE has no accountability.</p>\n"
},
{
"answer_id": 143667,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, DELETE is slower, TRUNCATE is faster. Why? </p>\n\n<p>DELETE must read the records, check constraints, update the block, update indexes, and generate redo/undo. All of that takes time.</p>\n\n<p>TRUNCATE simply adjusts a pointer in the database for the table (the High Water Mark) and poof! the data is gone. </p>\n\n<p>This is Oracle specific, AFAIK.</p>\n"
},
{
"answer_id": 143811,
"author": "CaptainPicard",
"author_id": 15203,
"author_profile": "https://Stackoverflow.com/users/15203",
"pm_score": 2,
"selected": false,
"text": "<p>A small correction to the original answer - delete also generates significant amounts of redo (as undo is itself protected by redo). This can be seen from autotrace output:</p>\n\n<pre><code>SQL> delete from t1;\n\n10918 rows deleted.\n\nElapsed: 00:00:00.58\n\nExecution Plan\n----------------------------------------------------------\n 0 DELETE STATEMENT Optimizer=FIRST_ROWS (Cost=43 Card=1)\n 1 0 DELETE OF 'T1'\n 2 1 TABLE ACCESS (FULL) OF 'T1' (TABLE) (Cost=43 Card=1)\n\n\n\n\nStatistics\n----------------------------------------------------------\n 30 recursive calls\n 12118 db block gets\n 213 consistent gets\n 142 physical reads\n 3975328 redo size\n 441 bytes sent via SQL*Net to client\n 537 bytes received via SQL*Net from client\n 4 SQL*Net roundtrips to/from client\n 2 sorts (memory)\n 0 sorts (disk)\n 10918 rows processed\n</code></pre>\n"
},
{
"answer_id": 689578,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In SQL Server 2005 I believe that you <strong>can</strong> rollback a truncate</p>\n"
},
{
"answer_id": 1873309,
"author": "Sachin Chourasiya",
"author_id": 184862,
"author_profile": "https://Stackoverflow.com/users/184862",
"pm_score": 4,
"selected": false,
"text": "<p><code>TRUNCATE</code> is the DDL statement whereas <code>DELETE</code> is a DML statement. Below are the differences between the two: </p>\n\n<ol>\n<li><p>As <code>TRUNCATE</code> is a DDL (<a href=\"https://en.wikipedia.org/wiki/Data_definition_language\" rel=\"noreferrer\">Data definition language</a>) statement it does not require a commit to make the changes permanent. And this is the reason why rows deleted by truncate could not be rollbacked. On the other hand <code>DELETE</code> is a DML (<a href=\"https://en.wikipedia.org/wiki/Data_manipulation_language\" rel=\"noreferrer\">Data manipulation language</a>) statement hence requires explicit commit to make its effect permanent.</p></li>\n<li><p><code>TRUNCATE</code> always removes all the rows from a table, leaving the table empty and the table structure intact whereas <code>DELETE</code> may remove conditionally if the where clause is used.</p></li>\n<li><p>The rows deleted by <code>TRUNCATE TABLE</code> statement cannot be restored and you can not specify the where clause in the <code>TRUNCATE</code> statement.</p></li>\n<li><p><code>TRUNCATE</code> statements does not fire triggers as opposed of on delete trigger on <code>DELETE</code> statement</p></li>\n</ol>\n\n<p><a href=\"http://forums.oracle.com/forums/thread.jspa?threadID=636943\" rel=\"noreferrer\">Here</a> is the very good link relevant to the topic.</p>\n"
},
{
"answer_id": 12900557,
"author": "Bhaumik Patel",
"author_id": 1218422,
"author_profile": "https://Stackoverflow.com/users/1218422",
"pm_score": 8,
"selected": false,
"text": "<p>The difference between truncate and delete is listed below:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>+----------------------------------------+----------------------------------------------+\n| Truncate | Delete |\n+----------------------------------------+----------------------------------------------+\n| We can't Rollback after performing | We can Rollback after delete. |\n| Truncate. | |\n| | |\n| Example: | Example: |\n| BEGIN TRAN | BEGIN TRAN |\n| TRUNCATE TABLE tranTest | DELETE FROM tranTest |\n| SELECT * FROM tranTest | SELECT * FROM tranTest |\n| ROLLBACK | ROLLBACK |\n| SELECT * FROM tranTest | SELECT * FROM tranTest |\n+----------------------------------------+----------------------------------------------+\n| Truncate reset identity of table. | Delete does not reset identity of table. |\n+----------------------------------------+----------------------------------------------+\n| It locks the entire table. | It locks the table row. |\n+----------------------------------------+----------------------------------------------+\n| Its DDL(Data Definition Language) | Its DML(Data Manipulation Language) |\n| command. | command. |\n+----------------------------------------+----------------------------------------------+\n| We can't use WHERE clause with it. | We can use WHERE to filter data to delete. |\n+----------------------------------------+----------------------------------------------+\n| Trigger is not fired while truncate. | Trigger is fired. |\n+----------------------------------------+----------------------------------------------+\n| Syntax : | Syntax : |\n| 1) TRUNCATE TABLE table_name | 1) DELETE FROM table_name |\n| | 2) DELETE FROM table_name WHERE |\n| | example_column_id IN (1,2,3) |\n+----------------------------------------+----------------------------------------------+\n</code></pre>\n"
},
{
"answer_id": 17331424,
"author": "Bhushan Patil",
"author_id": 2525987,
"author_profile": "https://Stackoverflow.com/users/2525987",
"pm_score": 1,
"selected": false,
"text": "<p>DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.</p>\n\n<p>The Syntax of a SQL DELETE statement is:</p>\n\n<p>DELETE FROM table_name [WHERE condition];</p>\n\n<p>TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.</p>\n"
},
{
"answer_id": 18673219,
"author": "user27332",
"author_id": 2704077,
"author_profile": "https://Stackoverflow.com/users/2704077",
"pm_score": 2,
"selected": false,
"text": "<p><strong>DELETE</strong></p>\n\n<blockquote>\n<pre><code>DELETE is a DML command\nDELETE you can rollback\nDelete = Only Delete- so it can be rolled back\nIn DELETE you can write conditions using WHERE clause\nSyntax – Delete from [Table] where [Condition]\n</code></pre>\n</blockquote>\n\n<p><strong>TRUNCATE</strong></p>\n\n<blockquote>\n<pre><code>TRUNCATE is a DDL command\nYou can't rollback in TRUNCATE, TRUNCATE removes the record permanently\nTruncate = Delete+Commit -so we can't roll back\nYou can't use conditions(WHERE clause) in TRUNCATE\nSyntax – Truncate table [Table]\n</code></pre>\n</blockquote>\n\n<p>For more details visit</p>\n\n<p><a href=\"http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/\" rel=\"nofollow\">http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/</a></p>\n"
},
{
"answer_id": 21347852,
"author": "user2587360",
"author_id": 2587360,
"author_profile": "https://Stackoverflow.com/users/2587360",
"pm_score": 0,
"selected": false,
"text": "<p>It is not that truncate does not log anything in SQL Server. truncate does not log any information but it log the deallocation of data page for the table on which you fired TRUNCATE.</p>\n\n<p>and truncated record can be rollback if we define transaction at beginning and we can recover the truncated record after rollback it. But can not recover truncated records from the transaction log backup after committed truncated transaction.</p>\n"
},
{
"answer_id": 25032124,
"author": "Vinay Pandit",
"author_id": 3890653,
"author_profile": "https://Stackoverflow.com/users/3890653",
"pm_score": 0,
"selected": false,
"text": "<p>Truncate can also be Rollbacked here the exapmle</p>\n\n<pre><code>begin Tran\ndelete from Employee\n\nselect * from Employee\nRollback\nselect * from Employee\n</code></pre>\n"
},
{
"answer_id": 25411028,
"author": "wpzone4u",
"author_id": 3961310,
"author_profile": "https://Stackoverflow.com/users/3961310",
"pm_score": 3,
"selected": false,
"text": "<p>If accidentally you removed all the data from table using Delete/Truncate. You can rollback committed transaction. Restore the last backup and run transaction log till the time when Delete/Truncate is about to happen.</p>\n\n<p>The related information below is from <a href=\"http://programmerzone4u.blogspot.in/2014/08/difference-between-delete-truncate-in.html\" rel=\"noreferrer\">a blog post</a>:</p>\n\n<blockquote>\n <p>While working on database, we are using Delete and Truncate without\n knowing the differences between them. In this article we will discuss\n the difference between Delete and Truncate in Sql.</p>\n \n <p>Delete:</p>\n \n <ul>\n <li>Delete is a DML command.</li>\n <li>Delete statement is executed using a row lock,each row in the table is locked for deletion.</li>\n <li>We can specify filters in where clause.</li>\n <li>It deletes specified data if where condition exists.</li>\n <li>Delete activities a trigger because the operation are logged individually.</li>\n <li>Slower than Truncate because it Keeps logs</li>\n </ul>\n \n <p>Truncate</p>\n \n <ul>\n <li>Truncate is a DDL command.</li>\n <li>Truncate table always lock the table and page but not each row.As it removes all the data.</li>\n <li>Cannot use Where condition. </li>\n <li>It Removes all the data.</li>\n <li>Truncate table cannot activate a trigger because the operation does not log individual row deletions.</li>\n <li>Faster in performance wise, because it doesn't keep any logs.</li>\n </ul>\n \n <p>Note: Delete and Truncate both can be rolled back when used with\n Transaction. If Transaction is done, means committed then we can not\n rollback Truncate command, but we can still rollback Delete command\n from Log files, as delete write records them in Log file in case it is\n needed to rollback in future from log files.</p>\n \n <p>If you have a Foreign key constraint referring to the table you are\n trying to truncate, this won't work even if the referring table has no\n data in it. This is because the foreign key checking is done with DDL\n rather than DML. This can be got around by temporarily disabling the\n foreign key constraint(s) to the table.</p>\n \n <p>Delete table is a logged operation. So the deletion of each row gets\n logged in the transaction log, which makes it slow. Truncate table\n also deletes all the rows in a table, but it won't log the deletion of\n each row instead it logs the deallocation of the data pages of the\n table, which makes it faster.</p>\n \n <p>~ If accidentally you removed all the data from table using\n Delete/Truncate. You can rollback committed transaction. Restore the\n last backup and run transaction log till the time when Delete/Truncate\n is about to happen.</p>\n</blockquote>\n"
},
{
"answer_id": 25429583,
"author": "SQLnbe",
"author_id": 2619386,
"author_profile": "https://Stackoverflow.com/users/2619386",
"pm_score": 2,
"selected": false,
"text": "<p>TRUNCATE can be rolled back if wrapped in a transaction. </p>\n\n<p>Please see the two references below and test yourself:-</p>\n\n<p><a href=\"http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/\" rel=\"nofollow\">http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/</a> </p>\n\n<p><a href=\"http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx\" rel=\"nofollow\">http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx</a></p>\n\n<p>The TRUNCATE vs. DELETE is one of the infamous questions during SQL interviews. Just make sure you explain it properly to the Interviewer or it might cost you the job. The problem is that not many are aware so most likely they will consider the answer as wrong if you tell them that YES Truncate can be rolled back.</p>\n"
},
{
"answer_id": 25453312,
"author": "wpzone4u",
"author_id": 3961310,
"author_profile": "https://Stackoverflow.com/users/3961310",
"pm_score": 0,
"selected": false,
"text": "<p>Truncate and Delete in SQL are two commands which is used to remove or delete data from table. Though quite basic in nature both Sql commands can create lot of trouble until you are familiar with details before using it.\nAn Incorrect choice of command can result is either very slow process or can even blew up log segment, if too much data needs to be removed and log segment is not enough. That's why it's critical to know when to use truncate and delete command in SQL but before using these you should be aware of the Differences between Truncate and Delete, and based upon them, we should be able to find out when DELETE is better option for removing data or TRUNCATE should be used to purge tables.</p>\n\n<p>Refer check <a href=\"http://programmerzone4u.blogspot.in/2014/08/when-to-use-truncate-and-delete-command.html\" rel=\"nofollow\">click here</a></p>\n"
},
{
"answer_id": 26208605,
"author": "Gerald",
"author_id": 3236901,
"author_profile": "https://Stackoverflow.com/users/3236901",
"pm_score": 0,
"selected": false,
"text": "<p>By issuing a TRUNCATE TABLE statement, you are instructing SQL Server to delete every record within a table, without any logging or transaction processing taking place.</p>\n"
},
{
"answer_id": 26213647,
"author": "westyside",
"author_id": 310809,
"author_profile": "https://Stackoverflow.com/users/310809",
"pm_score": 2,
"selected": false,
"text": "<p>One further difference of the two operations is that if the table contains an identity column, the counter for that column is reset 1 (or to the seed value defined for the column) under TRUNCATE. DELETE does not have this affect.</p>\n"
},
{
"answer_id": 29488350,
"author": "MyUserQuestion",
"author_id": 4747684,
"author_profile": "https://Stackoverflow.com/users/4747684",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<h3>DELETE</h3>\n<p>The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.</p>\n<h3>TRUNCATE</h3>\n<p>TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.</p>\n<h3>DROP</h3>\n<p>The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.</p>\n<hr />\n<p>DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.</p>\n</blockquote>\n<p>From: <a href=\"http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands\" rel=\"nofollow noreferrer\">http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands</a></p>\n"
},
{
"answer_id": 29644760,
"author": "Mohit Singh",
"author_id": 2455366,
"author_profile": "https://Stackoverflow.com/users/2455366",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n<h3>DROP</h3>\n<p>The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.</p>\n<h3>TRUNCATE</h3>\n<p>TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.</p>\n<h3>DELETE</h3>\n<p>The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.</p>\n</blockquote>\n<p>From: <a href=\"http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands\" rel=\"noreferrer\">http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands</a></p>\n"
},
{
"answer_id": 33541277,
"author": "Mangal Pardeshi",
"author_id": 5485173,
"author_profile": "https://Stackoverflow.com/users/5485173",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my detailed answer on <a href=\"http://mangalpardeshi.blogspot.in/2009/07/delete-vs-truncate.html\" rel=\"noreferrer\">the difference between DELETE and TRUNCATE in SQL Server</a></p>\n\n<p>• <strong>Remove Data</strong> : First thing first, both can be used to remove the rows from table.<br>\nBut a DELETE can be used to remove the rows not only from a Table but also from a VIEW or the result of an OPENROWSET or OPENQUERY subject to provider capabilities. </p>\n\n<p>• <strong>FROM Clause</strong> : With DELETE you can also delete rows from one table/view/rowset_function_limited based on rows from another table by using another FROM clause. In that FROM clause you can also write normal JOIN conditions. Actually you can create a DELETE statement from a SELECT statement that doesn’t contain any aggregate functions by replacing SELECT with DELETE and removing column names.<br>\nWith TRUNCATE you can’t do that. </p>\n\n<p>• <strong>WHERE</strong> : A TRUNCATE cannot have WHERE Conditions, but a DELETE can. That means with TRUNCATE you can’t delete a specific row or specific group of rows. \nTRUNCATE TABLE is similar to the DELETE statement with no WHERE clause.</p>\n\n<p>• <strong>Performance</strong> : TRUNCATE TABLE is faster and uses fewer system and transaction log resources. \nAnd one of the reason is locks used by either statements. The DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row.</p>\n\n<p>• <strong>Transaction log</strong> : DELETE statement removes rows one at a time and makes individual entries in the transaction log for each row.<br>\nTRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.</p>\n\n<p>• <strong>Pages</strong> : After a DELETE statement is executed, the table can still contain empty pages. \nTRUNCATE removes the data by deallocating the data pages used to store the table data.</p>\n\n<p>• <strong>Trigger</strong> : TRUNCATE does not activate the delete triggers on the table. So you must be very careful while using TRUNCATE. One should never use a TRUNCATE if delete Trigger is defined on the table to do some automatic cleanup or logging action when rows are deleted.</p>\n\n<p>• <strong>Identity Column</strong> : With TRUNCATE if the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. \nDELETE doesn’t reset the identity counter. So if you want to retain the identity counter, use DELETE instead.</p>\n\n<p>• <strong>Replication</strong> : DELETE can be used against table used in transactional replication or merge replication.<br>\nWhile TRUNCATE cannot be used against the tables involved in transactional replication or merge replication. </p>\n\n<p>• <strong>Rollback</strong> : DELETE statement can be rolled back.<br>\nTRUNCATE can also be rolled back provided it is enclosed in a TRANSACTION block and session is not closed. Once session is closed you won't be able to Rollback TRUNCATE.</p>\n\n<p>• <strong>Restrictions</strong> : The DELETE statement may fail if it violates a trigger or tries to remove a row referenced by data in another table with a FOREIGN KEY constraint. If the DELETE removes multiple rows, and any one of the removed rows violates a trigger or constraint, the statement is canceled, an error is returned, and no rows are removed.<br>\nAnd if DELETE is used against View, that View must be an Updatable view. \nTRUNCATE cannot be used against the table used in Indexed view.<br>\nTRUNCATE cannot be used against the table referenced by a FOREIGN KEY constraint, unless a table that has a foreign key that references itself.</p>\n"
},
{
"answer_id": 37228916,
"author": "Shamseer K",
"author_id": 4133590,
"author_profile": "https://Stackoverflow.com/users/4133590",
"pm_score": 5,
"selected": false,
"text": "<p>Summary of Delete Vs Truncate in SQL server<br/>\nFor Complete Article follow this link : <a href=\"http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/\" rel=\"noreferrer\">http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Bil4e.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Bil4e.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Taken from dotnet mob article :<a href=\"http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/\" rel=\"noreferrer\">Delete Vs Truncate in SQL Server</a></p>\n"
},
{
"answer_id": 37781756,
"author": "Ali",
"author_id": 6457961,
"author_profile": "https://Stackoverflow.com/users/6457961",
"pm_score": 0,
"selected": false,
"text": "<p>DELETE statement can have a WHERE clause to delete specific records whereas TRUNCATE statement does not require any and wipes the entire table.\nImportantly, the DELETE statement logs the deleted date whereas the TRUNCATE statement does not.</p>\n"
},
{
"answer_id": 43488613,
"author": "Mykhailo Seniutovych",
"author_id": 7111692,
"author_profile": "https://Stackoverflow.com/users/7111692",
"pm_score": 0,
"selected": false,
"text": "<p>One more difference specific to microsoft sql server is with <code>delete</code> you can use <code>output</code> statement to track what records have been deleted, e.g.:</p>\n\n<pre><code>delete from [SomeTable]\noutput deleted.Id, deleted.Name\n</code></pre>\n\n<p>You cannot do this with <code>truncate</code>.</p>\n"
},
{
"answer_id": 43628085,
"author": "Rishish",
"author_id": 7787019,
"author_profile": "https://Stackoverflow.com/users/7787019",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Truncate</strong> command is used to re-initialize the table, it is a DDL command which delete all the rows of table.Whereas <strong>DELETE</strong> is a DML command which is used to delete row or set of rows according to some condition, if condition is not specified then this command will delete all the rows from the table. </p>\n"
},
{
"answer_id": 73405812,
"author": "Pawel W",
"author_id": 10461682,
"author_profile": "https://Stackoverflow.com/users/10461682",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a summary of some important differences between these sql commands:</p>\n<p><strong>sql truncate command:</strong></p>\n<p><strong>1)</strong> It is a DDL (Data Definition Language) command, therefore commands such as COMMIT and ROLLBACK do not apply to this command (the exceptions here are PostgreSQL and MSSQL, whose implementation of the TRUNCATE command allows the command to be used in a transaction)</p>\n<p><strong>2)</strong> You cannot undo the operation of deleting records, it occurs automatically and is irreversible (except for the above exceptions - provided, however, that the operation is included in the TRANSACTION block and the session is not closed). In case of Oracle - Includes two implicit commits, one before and one after the statement is executed. Therefore, the command cannot be withdrawn while a runtime error will result in commit anyway</p>\n<p><strong>3)</strong> Deletes all records from the table, records cannot be limited to deletion. For Oracle, when the table is split per partition, individual partitions can be truncated (TRUNCATE) in isolation, making it possible to partially remove all data from the table</p>\n<p><strong>4)</strong> Frees up the space occupied by the data in the table (in the TABLESPACE - on disk). For Oracle - if you use the REUSE STORAGE clause, the data segments will not be rolled back, i.e. you will keep space from the deleted rows allocated to the table, which can be a bit more efficient if the table is to be reloaded with data. The high mark will be reset</p>\n<p><strong>5)</strong> TRUNCATE works much faster than DELETE</p>\n<p><strong>6)</strong> Oracle Flashback in the case of TRUNCATE prevents going back to pre-operative states</p>\n<p><strong>7)</strong> Oracle - TRUNCATE cannot be granted (GRANT) without using DROP ANY TABLE</p>\n<p><strong>8)</strong> The TRUNCATE operation makes unusable indexes usable again</p>\n<p><strong>9)</strong> TRUNCATE cannot be used when the enabled foreign key refers to another table, then you can:</p>\n<ul>\n<li>execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or</li>\n<li>execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;</li>\n</ul>\n<p><strong>10)</strong> TRUNCATE requires an exclusive table lock, therefore, turning off exclusive table lock is a way to prevent TRUNCATE operation on the table</p>\n<p><strong>11)</strong> DML triggers do not fire after executing TRUNCATE (so be very careful in this case, you should not use TRUNCATE, if a delete trigger is defined in the table to perform an automatic table cleanup or a logon action after row deletion). On Oracle, DDL triggers are fired</p>\n<p><strong>12)</strong> Oracle - TRUNCATE cannot be used in the case of: database link\n<strong>13)</strong> TRUNCATE does not return the number of records deleted</p>\n<p><strong>14)</strong> Transaction log - one log indicating page deallocation (removes data, releasing allocation of data pages used for storing table data and writes only page deallocations to the transaction log) - faster execution than DELETE. TRUNCATE only needs to adjust the pointer in the database to the table (High Water Mark) and the data is immediately deleted, therefore it uses less system resources and transaction logs</p>\n<p><strong>15)</strong> Performance (acquired lock) - table and page lock - does not degrade performance during execution</p>\n<p><strong>16)</strong> TRUNCATE cannot be used on tables involved in transactional replication or merge replication</p>\n<p><strong>sql delete command:</strong></p>\n<p><strong>1)</strong> It is a DML (Data Manipulation Language) command, therefore the following commands are used for this command: COMMIT and ROLLBACK</p>\n<p><strong>2)</strong> You can undo the operation of removing records by using the ROLLBACK command</p>\n<p><strong>3)</strong> Deletes all or some records from the table, you can limit the records to be deleted by using the WHERE clause</p>\n<p><strong>4)</strong> Does not free the space occupied by the data in the table (in the TABLESPACE - on the disk)</p>\n<p><strong>5)</strong> DELETE works much slower than TRUNCATE</p>\n<p><strong>6)</strong> Oracle Flashback works for DELETE</p>\n<p><strong>7)</strong> Oracle - For DELETE, you can use the GRANT command</p>\n<p><strong>8)</strong> The DELETE operation does not make unusable indexes usable again</p>\n<p><strong>9)</strong> DELETE in case foreign key enabled refers to another table, can (or not) be applied depending on foreign key configuration (if not), please:</p>\n<ul>\n<li>execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or</li>\n<li>execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;</li>\n</ul>\n<p><strong>10)</strong> DELETE requires a shared table lock</p>\n<p><strong>11)</strong> Triggers fire</p>\n<p><strong>12)</strong> DELETE can be used in the case of: database link</p>\n<p><strong>13)</strong> DELETE returns the number of records deleted</p>\n<p><strong>14)</strong> Transaction log - for each deleted record (deletes rows one at a time and records an entry in the transaction log for each deleted row) - slower execution than TRUNCATE. The table may still contain blank pages after executing the DELETE statement. DELETE needs to read records, check constraints, update block, update indexes, and generate redo / undo. All of this takes time, hence it takes time much longer than with TRUNCATE</p>\n<p><strong>15)</strong> Performance (acquired lock) - record lock - reduces performance during execution - each record in the table is locked for deletion</p>\n<p><strong>16)</strong> DELETE can be used on a table used in transactional replication or merge replication</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6742/"
]
| What's the difference between `TRUNCATE` and `DELETE` in SQL?
If your answer is platform specific, please indicate that. | Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
---
General Overview
================
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
---
Statement type
==============
Delete is DML, Truncate is DDL ([What is DDL and DML?](https://stackoverflow.com/q/2578194/276052))
---
Commit and Rollback
===================
Variable by vendor
**SQL\*Server**
Truncate can be rolled back.
**PostgreSQL**
Truncate can be rolled back.
**Oracle**
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
---
Space reclamation
=================
Delete does not recover space, Truncate recovers space
**Oracle**
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
---
Row scope
=========
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
**Oracle**
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
---
Object types
============
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
---
Data Object Identity
====================
**Oracle**
Delete does not affect the data object id, but truncate assigns a new data object id *unless* there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
---
Flashback (Oracle)
==================
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
[Use of FLASHBACK in Oracle](https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle)
<http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638>
---
Privileges
==========
Variable
**Oracle**
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
---
Redo/Undo
=========
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
---
Indexes
=======
**Oracle**
A truncate operation renders unusable indexes usable again. Delete does not.
---
Foreign Keys
============
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
---
Table Locking
=============
**Oracle**
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
---
Triggers
========
DML triggers do not fire on a truncate.
**Oracle**
DDL triggers are available.
---
Remote Execution
================
**Oracle**
Truncate cannot be issued over a database link.
---
Identity Columns
================
**SQL\*Server**
Truncate resets the sequence for IDENTITY column types, delete does not.
---
Result set
==========
In most implementations, a `DELETE` statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
```
DELETE FROM employees_temp
WHERE employee_id = 299
RETURNING first_name,
last_name
INTO emp_first_name,
emp_last_name;
``` |
139,639 | <p>I am working with Reporting Services and Sharepoint, I have an application that leverages reporting services however a client would like our application integrated into sharepoint. Currently we are tightly coupled to the ReportService.asmx webservice which exposes various methods for performing operations. Reporting Services has something called "Sharepoint Integration mode" when enabled the report server works differently and Sharepoint is used to manage the reports. Sharepoint adds a new web service called ReportService2006.asmx which is almost exactly the same. </p>
<p>Now our application uses a web reference to the ReportService and uses various objects exposed by the service. ReportService2006 has exactly the same objects but they are obviously in a different namespace e.g I have 2 web references - 1 to each service so there is an object MyApplication.ReportService.CatalogItem and another MyApplication.ReportService2006.CatalogItem.</p>
<p>I've tried to use dependency injection to absract the Service out of our application coupled with a factory pattern to determine which implementation of my interface to instantiate. Heres my interface. I've simplified it to include only the calls I need for this application.</p>
<pre><code>using System;
using NetworkUserEncrypt.ReportService;
namespace MyApplication.Service
{
public interface IReportingService
{
CatalogItem CreateDataSource(string DataSource, string Parent, bool Overwrite, DataSourceDefinition Definition, Property[] Properties);
void DeleteItem(string Item);
DataSourceDefinition GetDataSourceContents(string DataSource);
byte[] GetReportDefinition(string Report);
CatalogItem[] ListChildren(string Item);
}
}
</code></pre>
<p>So I have 2 implementations of this each instantiating a different web service e.g:</p>
<pre><code>namespace MyApp.Service.Implementation
{
class ReportingServiceImpl : IReportingService
{
ReportingService _service = null;
public ReportingServiceImpl()
{
ReportingService _service = new ReportingService();
}
/* SNIP */
}
}
</code></pre>
<p>and</p>
<pre><code>namespace MyApp.Service.Implementation
{
class ReportingService2006Impl : IReportingService
{
ReportingService2006 _service = null;
public ReportingService2006Impl()
{
ReportingService2006 _service = new ReportingService2006();
}
/* SNIP */
}
}
</code></pre>
<p>So the plan is I can inject these into my ServiceWrapper at run time. However - if you'll notice the interface is tied to the ReportService and some of the methods return objects that are from the web reference e.g. CatalogItem. Thus my project won't build because my implementation for ReportService2006 is referencing the CatalogItem from a different namespace.</p>
<p>Any ideas? Am I going totally the wrong direction with this?</p>
| [
{
"answer_id": 139633,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 9,
"selected": true,
"text": "<p>Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.</p>\n\n<p><hr></p>\n\n<h1>General Overview</h1>\n\n<p>If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.</p>\n\n<p>Various system-specific issues have to be considered, as detailed below.</p>\n\n<p><hr></p>\n\n<h1>Statement type</h1>\n\n<p>Delete is DML, Truncate is DDL (<a href=\"https://stackoverflow.com/q/2578194/276052\">What is DDL and DML?</a>)</p>\n\n<p><hr></p>\n\n<h1>Commit and Rollback</h1>\n\n<p>Variable by vendor</p>\n\n<p><strong>SQL*Server</strong></p>\n\n<p>Truncate can be rolled back.</p>\n\n<p><strong>PostgreSQL</strong></p>\n\n<p>Truncate can be rolled back.</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.</p>\n\n<p>However, see Flashback below.</p>\n\n<p><hr></p>\n\n<h1>Space reclamation</h1>\n\n<p>Delete does not recover space, Truncate recovers space</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.</p>\n\n<p><hr></p>\n\n<h1>Row scope</h1>\n\n<p>Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.</p>\n\n<p><hr></p>\n\n<h1>Object types</h1>\n\n<p>Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)</p>\n\n<p><hr></p>\n\n<h1>Data Object Identity</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>Delete does not affect the data object id, but truncate assigns a new data object id <em>unless</em> there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.</p>\n\n<p><hr></p>\n\n<h1>Flashback (Oracle)</h1>\n\n<p>Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.</p>\n\n<p>However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition</p>\n\n<p><a href=\"https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle\">Use of FLASHBACK in Oracle</a>\n<a href=\"http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638\" rel=\"noreferrer\">http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638</a></p>\n\n<p><hr></p>\n\n<h1>Privileges</h1>\n\n<p>Variable</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.</p>\n\n<p><hr></p>\n\n<h1>Redo/Undo</h1>\n\n<p>Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.</p>\n\n<p><hr></p>\n\n<h1>Indexes</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>A truncate operation renders unusable indexes usable again. Delete does not.</p>\n\n<p><hr></p>\n\n<h1>Foreign Keys</h1>\n\n<p>A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.</p>\n\n<p><hr></p>\n\n<h1>Table Locking</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.</p>\n\n<p><hr></p>\n\n<h1>Triggers</h1>\n\n<p>DML triggers do not fire on a truncate.</p>\n\n<p><strong>Oracle</strong></p>\n\n<p>DDL triggers are available.</p>\n\n<p><hr></p>\n\n<h1>Remote Execution</h1>\n\n<p><strong>Oracle</strong></p>\n\n<p>Truncate cannot be issued over a database link.</p>\n\n<p><hr></p>\n\n<h1>Identity Columns</h1>\n\n<p><strong>SQL*Server</strong></p>\n\n<p>Truncate resets the sequence for IDENTITY column types, delete does not.</p>\n\n<p><hr></p>\n\n<h1>Result set</h1>\n\n<p>In most implementations, a <code>DELETE</code> statement can return to the client the rows that were deleted.</p>\n\n<p>e.g. in an Oracle PL/SQL subprogram you could:</p>\n\n<pre><code>DELETE FROM employees_temp\nWHERE employee_id = 299 \nRETURNING first_name,\n last_name\nINTO emp_first_name,\n emp_last_name;\n</code></pre>\n"
},
{
"answer_id": 139646,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 4,
"selected": false,
"text": "<p>With SQL Server or MySQL, if there is a PK with auto increment, truncate will reset the counter.</p>\n"
},
{
"answer_id": 139648,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 0,
"selected": false,
"text": "<p>In short, truncate doesn't log anything (so is much faster but can't be undone) whereas delete is logged (and can be part of a larger transaction, will rollback etc). If you have data that you don't want in a table in dev it is normally better to truncate as you don't run the risk of filling up the transaction log</p>\n"
},
{
"answer_id": 139649,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 1,
"selected": false,
"text": "<p>The biggest difference is that truncate is non logged operation while delete is.</p>\n\n<p>Simply it means that in case of a database crash , you cannot recover the data operated upon by truncate but with delete you can. </p>\n\n<p>More details <a href=\"http://doc.ddart.net/mssql/sql70/8_des_02_8.htm\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 139764,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 4,
"selected": false,
"text": "<p>\"Truncate doesn't log anything\" is correct. I'd go further:</p>\n\n<p>Truncate is not executed in the context of a transaction. </p>\n\n<p>The speed advantage of truncate over delete should be obvious. That advantage ranges from trivial to enormous, depending on your situation.</p>\n\n<p>However, I've seen truncate unintentionally break referential integrity, and violate other constraints. The power that you gain by modifying data outside a transaction has to be balanced against the responsibility that you inherit when you walk the tightrope without a net.</p>\n"
},
{
"answer_id": 139803,
"author": "Jordan Ogren",
"author_id": 21888,
"author_profile": "https://Stackoverflow.com/users/21888",
"pm_score": 0,
"selected": false,
"text": "<p>A big reason it is handy, is when you need to refresh the data in a multi-million row table, but don't want to rebuild it. \"Delete *\" would take forever, whereas the perfomance impact of Truncate would be negligible.</p>\n"
},
{
"answer_id": 139877,
"author": "polara",
"author_id": 8754,
"author_profile": "https://Stackoverflow.com/users/8754",
"pm_score": 5,
"selected": false,
"text": "<p>All good answers, to which I must add:</p>\n\n<p>Since <code>TRUNCATE TABLE</code> is a DDL (<a href=\"https://en.wikipedia.org/wiki/Data_definition_language\" rel=\"noreferrer\">Data Defination Language</a>), not a DML (<a href=\"https://en.wikipedia.org/wiki/Data_manipulation_language\" rel=\"noreferrer\">Data Manipulation Langauge</a>) command, the <code>Delete Triggers</code> do not run.</p>\n"
},
{
"answer_id": 142509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Can't do DDL over a dblink.</p>\n"
},
{
"answer_id": 142672,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 0,
"selected": false,
"text": "<p>I'd comment on matthieu's post, but I don't have the rep yet...</p>\n\n<p>In MySQL, the auto increment counter gets reset with truncate, but not with delete.</p>\n"
},
{
"answer_id": 142687,
"author": "databyss",
"author_id": 9094,
"author_profile": "https://Stackoverflow.com/users/9094",
"pm_score": -1,
"selected": false,
"text": "<p>TRUNCATE is fast, DELETE is slow.</p>\n\n<p>Although, TRUNCATE has no accountability.</p>\n"
},
{
"answer_id": 143667,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, DELETE is slower, TRUNCATE is faster. Why? </p>\n\n<p>DELETE must read the records, check constraints, update the block, update indexes, and generate redo/undo. All of that takes time.</p>\n\n<p>TRUNCATE simply adjusts a pointer in the database for the table (the High Water Mark) and poof! the data is gone. </p>\n\n<p>This is Oracle specific, AFAIK.</p>\n"
},
{
"answer_id": 143811,
"author": "CaptainPicard",
"author_id": 15203,
"author_profile": "https://Stackoverflow.com/users/15203",
"pm_score": 2,
"selected": false,
"text": "<p>A small correction to the original answer - delete also generates significant amounts of redo (as undo is itself protected by redo). This can be seen from autotrace output:</p>\n\n<pre><code>SQL> delete from t1;\n\n10918 rows deleted.\n\nElapsed: 00:00:00.58\n\nExecution Plan\n----------------------------------------------------------\n 0 DELETE STATEMENT Optimizer=FIRST_ROWS (Cost=43 Card=1)\n 1 0 DELETE OF 'T1'\n 2 1 TABLE ACCESS (FULL) OF 'T1' (TABLE) (Cost=43 Card=1)\n\n\n\n\nStatistics\n----------------------------------------------------------\n 30 recursive calls\n 12118 db block gets\n 213 consistent gets\n 142 physical reads\n 3975328 redo size\n 441 bytes sent via SQL*Net to client\n 537 bytes received via SQL*Net from client\n 4 SQL*Net roundtrips to/from client\n 2 sorts (memory)\n 0 sorts (disk)\n 10918 rows processed\n</code></pre>\n"
},
{
"answer_id": 689578,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In SQL Server 2005 I believe that you <strong>can</strong> rollback a truncate</p>\n"
},
{
"answer_id": 1873309,
"author": "Sachin Chourasiya",
"author_id": 184862,
"author_profile": "https://Stackoverflow.com/users/184862",
"pm_score": 4,
"selected": false,
"text": "<p><code>TRUNCATE</code> is the DDL statement whereas <code>DELETE</code> is a DML statement. Below are the differences between the two: </p>\n\n<ol>\n<li><p>As <code>TRUNCATE</code> is a DDL (<a href=\"https://en.wikipedia.org/wiki/Data_definition_language\" rel=\"noreferrer\">Data definition language</a>) statement it does not require a commit to make the changes permanent. And this is the reason why rows deleted by truncate could not be rollbacked. On the other hand <code>DELETE</code> is a DML (<a href=\"https://en.wikipedia.org/wiki/Data_manipulation_language\" rel=\"noreferrer\">Data manipulation language</a>) statement hence requires explicit commit to make its effect permanent.</p></li>\n<li><p><code>TRUNCATE</code> always removes all the rows from a table, leaving the table empty and the table structure intact whereas <code>DELETE</code> may remove conditionally if the where clause is used.</p></li>\n<li><p>The rows deleted by <code>TRUNCATE TABLE</code> statement cannot be restored and you can not specify the where clause in the <code>TRUNCATE</code> statement.</p></li>\n<li><p><code>TRUNCATE</code> statements does not fire triggers as opposed of on delete trigger on <code>DELETE</code> statement</p></li>\n</ol>\n\n<p><a href=\"http://forums.oracle.com/forums/thread.jspa?threadID=636943\" rel=\"noreferrer\">Here</a> is the very good link relevant to the topic.</p>\n"
},
{
"answer_id": 12900557,
"author": "Bhaumik Patel",
"author_id": 1218422,
"author_profile": "https://Stackoverflow.com/users/1218422",
"pm_score": 8,
"selected": false,
"text": "<p>The difference between truncate and delete is listed below:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>+----------------------------------------+----------------------------------------------+\n| Truncate | Delete |\n+----------------------------------------+----------------------------------------------+\n| We can't Rollback after performing | We can Rollback after delete. |\n| Truncate. | |\n| | |\n| Example: | Example: |\n| BEGIN TRAN | BEGIN TRAN |\n| TRUNCATE TABLE tranTest | DELETE FROM tranTest |\n| SELECT * FROM tranTest | SELECT * FROM tranTest |\n| ROLLBACK | ROLLBACK |\n| SELECT * FROM tranTest | SELECT * FROM tranTest |\n+----------------------------------------+----------------------------------------------+\n| Truncate reset identity of table. | Delete does not reset identity of table. |\n+----------------------------------------+----------------------------------------------+\n| It locks the entire table. | It locks the table row. |\n+----------------------------------------+----------------------------------------------+\n| Its DDL(Data Definition Language) | Its DML(Data Manipulation Language) |\n| command. | command. |\n+----------------------------------------+----------------------------------------------+\n| We can't use WHERE clause with it. | We can use WHERE to filter data to delete. |\n+----------------------------------------+----------------------------------------------+\n| Trigger is not fired while truncate. | Trigger is fired. |\n+----------------------------------------+----------------------------------------------+\n| Syntax : | Syntax : |\n| 1) TRUNCATE TABLE table_name | 1) DELETE FROM table_name |\n| | 2) DELETE FROM table_name WHERE |\n| | example_column_id IN (1,2,3) |\n+----------------------------------------+----------------------------------------------+\n</code></pre>\n"
},
{
"answer_id": 17331424,
"author": "Bhushan Patil",
"author_id": 2525987,
"author_profile": "https://Stackoverflow.com/users/2525987",
"pm_score": 1,
"selected": false,
"text": "<p>DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.</p>\n\n<p>The Syntax of a SQL DELETE statement is:</p>\n\n<p>DELETE FROM table_name [WHERE condition];</p>\n\n<p>TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.</p>\n"
},
{
"answer_id": 18673219,
"author": "user27332",
"author_id": 2704077,
"author_profile": "https://Stackoverflow.com/users/2704077",
"pm_score": 2,
"selected": false,
"text": "<p><strong>DELETE</strong></p>\n\n<blockquote>\n<pre><code>DELETE is a DML command\nDELETE you can rollback\nDelete = Only Delete- so it can be rolled back\nIn DELETE you can write conditions using WHERE clause\nSyntax – Delete from [Table] where [Condition]\n</code></pre>\n</blockquote>\n\n<p><strong>TRUNCATE</strong></p>\n\n<blockquote>\n<pre><code>TRUNCATE is a DDL command\nYou can't rollback in TRUNCATE, TRUNCATE removes the record permanently\nTruncate = Delete+Commit -so we can't roll back\nYou can't use conditions(WHERE clause) in TRUNCATE\nSyntax – Truncate table [Table]\n</code></pre>\n</blockquote>\n\n<p>For more details visit</p>\n\n<p><a href=\"http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/\" rel=\"nofollow\">http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/</a></p>\n"
},
{
"answer_id": 21347852,
"author": "user2587360",
"author_id": 2587360,
"author_profile": "https://Stackoverflow.com/users/2587360",
"pm_score": 0,
"selected": false,
"text": "<p>It is not that truncate does not log anything in SQL Server. truncate does not log any information but it log the deallocation of data page for the table on which you fired TRUNCATE.</p>\n\n<p>and truncated record can be rollback if we define transaction at beginning and we can recover the truncated record after rollback it. But can not recover truncated records from the transaction log backup after committed truncated transaction.</p>\n"
},
{
"answer_id": 25032124,
"author": "Vinay Pandit",
"author_id": 3890653,
"author_profile": "https://Stackoverflow.com/users/3890653",
"pm_score": 0,
"selected": false,
"text": "<p>Truncate can also be Rollbacked here the exapmle</p>\n\n<pre><code>begin Tran\ndelete from Employee\n\nselect * from Employee\nRollback\nselect * from Employee\n</code></pre>\n"
},
{
"answer_id": 25411028,
"author": "wpzone4u",
"author_id": 3961310,
"author_profile": "https://Stackoverflow.com/users/3961310",
"pm_score": 3,
"selected": false,
"text": "<p>If accidentally you removed all the data from table using Delete/Truncate. You can rollback committed transaction. Restore the last backup and run transaction log till the time when Delete/Truncate is about to happen.</p>\n\n<p>The related information below is from <a href=\"http://programmerzone4u.blogspot.in/2014/08/difference-between-delete-truncate-in.html\" rel=\"noreferrer\">a blog post</a>:</p>\n\n<blockquote>\n <p>While working on database, we are using Delete and Truncate without\n knowing the differences between them. In this article we will discuss\n the difference between Delete and Truncate in Sql.</p>\n \n <p>Delete:</p>\n \n <ul>\n <li>Delete is a DML command.</li>\n <li>Delete statement is executed using a row lock,each row in the table is locked for deletion.</li>\n <li>We can specify filters in where clause.</li>\n <li>It deletes specified data if where condition exists.</li>\n <li>Delete activities a trigger because the operation are logged individually.</li>\n <li>Slower than Truncate because it Keeps logs</li>\n </ul>\n \n <p>Truncate</p>\n \n <ul>\n <li>Truncate is a DDL command.</li>\n <li>Truncate table always lock the table and page but not each row.As it removes all the data.</li>\n <li>Cannot use Where condition. </li>\n <li>It Removes all the data.</li>\n <li>Truncate table cannot activate a trigger because the operation does not log individual row deletions.</li>\n <li>Faster in performance wise, because it doesn't keep any logs.</li>\n </ul>\n \n <p>Note: Delete and Truncate both can be rolled back when used with\n Transaction. If Transaction is done, means committed then we can not\n rollback Truncate command, but we can still rollback Delete command\n from Log files, as delete write records them in Log file in case it is\n needed to rollback in future from log files.</p>\n \n <p>If you have a Foreign key constraint referring to the table you are\n trying to truncate, this won't work even if the referring table has no\n data in it. This is because the foreign key checking is done with DDL\n rather than DML. This can be got around by temporarily disabling the\n foreign key constraint(s) to the table.</p>\n \n <p>Delete table is a logged operation. So the deletion of each row gets\n logged in the transaction log, which makes it slow. Truncate table\n also deletes all the rows in a table, but it won't log the deletion of\n each row instead it logs the deallocation of the data pages of the\n table, which makes it faster.</p>\n \n <p>~ If accidentally you removed all the data from table using\n Delete/Truncate. You can rollback committed transaction. Restore the\n last backup and run transaction log till the time when Delete/Truncate\n is about to happen.</p>\n</blockquote>\n"
},
{
"answer_id": 25429583,
"author": "SQLnbe",
"author_id": 2619386,
"author_profile": "https://Stackoverflow.com/users/2619386",
"pm_score": 2,
"selected": false,
"text": "<p>TRUNCATE can be rolled back if wrapped in a transaction. </p>\n\n<p>Please see the two references below and test yourself:-</p>\n\n<p><a href=\"http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/\" rel=\"nofollow\">http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/</a> </p>\n\n<p><a href=\"http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx\" rel=\"nofollow\">http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx</a></p>\n\n<p>The TRUNCATE vs. DELETE is one of the infamous questions during SQL interviews. Just make sure you explain it properly to the Interviewer or it might cost you the job. The problem is that not many are aware so most likely they will consider the answer as wrong if you tell them that YES Truncate can be rolled back.</p>\n"
},
{
"answer_id": 25453312,
"author": "wpzone4u",
"author_id": 3961310,
"author_profile": "https://Stackoverflow.com/users/3961310",
"pm_score": 0,
"selected": false,
"text": "<p>Truncate and Delete in SQL are two commands which is used to remove or delete data from table. Though quite basic in nature both Sql commands can create lot of trouble until you are familiar with details before using it.\nAn Incorrect choice of command can result is either very slow process or can even blew up log segment, if too much data needs to be removed and log segment is not enough. That's why it's critical to know when to use truncate and delete command in SQL but before using these you should be aware of the Differences between Truncate and Delete, and based upon them, we should be able to find out when DELETE is better option for removing data or TRUNCATE should be used to purge tables.</p>\n\n<p>Refer check <a href=\"http://programmerzone4u.blogspot.in/2014/08/when-to-use-truncate-and-delete-command.html\" rel=\"nofollow\">click here</a></p>\n"
},
{
"answer_id": 26208605,
"author": "Gerald",
"author_id": 3236901,
"author_profile": "https://Stackoverflow.com/users/3236901",
"pm_score": 0,
"selected": false,
"text": "<p>By issuing a TRUNCATE TABLE statement, you are instructing SQL Server to delete every record within a table, without any logging or transaction processing taking place.</p>\n"
},
{
"answer_id": 26213647,
"author": "westyside",
"author_id": 310809,
"author_profile": "https://Stackoverflow.com/users/310809",
"pm_score": 2,
"selected": false,
"text": "<p>One further difference of the two operations is that if the table contains an identity column, the counter for that column is reset 1 (or to the seed value defined for the column) under TRUNCATE. DELETE does not have this affect.</p>\n"
},
{
"answer_id": 29488350,
"author": "MyUserQuestion",
"author_id": 4747684,
"author_profile": "https://Stackoverflow.com/users/4747684",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<h3>DELETE</h3>\n<p>The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.</p>\n<h3>TRUNCATE</h3>\n<p>TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.</p>\n<h3>DROP</h3>\n<p>The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.</p>\n<hr />\n<p>DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.</p>\n</blockquote>\n<p>From: <a href=\"http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands\" rel=\"nofollow noreferrer\">http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands</a></p>\n"
},
{
"answer_id": 29644760,
"author": "Mohit Singh",
"author_id": 2455366,
"author_profile": "https://Stackoverflow.com/users/2455366",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n<h3>DROP</h3>\n<p>The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.</p>\n<h3>TRUNCATE</h3>\n<p>TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.</p>\n<h3>DELETE</h3>\n<p>The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.</p>\n</blockquote>\n<p>From: <a href=\"http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands\" rel=\"noreferrer\">http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands</a></p>\n"
},
{
"answer_id": 33541277,
"author": "Mangal Pardeshi",
"author_id": 5485173,
"author_profile": "https://Stackoverflow.com/users/5485173",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my detailed answer on <a href=\"http://mangalpardeshi.blogspot.in/2009/07/delete-vs-truncate.html\" rel=\"noreferrer\">the difference between DELETE and TRUNCATE in SQL Server</a></p>\n\n<p>• <strong>Remove Data</strong> : First thing first, both can be used to remove the rows from table.<br>\nBut a DELETE can be used to remove the rows not only from a Table but also from a VIEW or the result of an OPENROWSET or OPENQUERY subject to provider capabilities. </p>\n\n<p>• <strong>FROM Clause</strong> : With DELETE you can also delete rows from one table/view/rowset_function_limited based on rows from another table by using another FROM clause. In that FROM clause you can also write normal JOIN conditions. Actually you can create a DELETE statement from a SELECT statement that doesn’t contain any aggregate functions by replacing SELECT with DELETE and removing column names.<br>\nWith TRUNCATE you can’t do that. </p>\n\n<p>• <strong>WHERE</strong> : A TRUNCATE cannot have WHERE Conditions, but a DELETE can. That means with TRUNCATE you can’t delete a specific row or specific group of rows. \nTRUNCATE TABLE is similar to the DELETE statement with no WHERE clause.</p>\n\n<p>• <strong>Performance</strong> : TRUNCATE TABLE is faster and uses fewer system and transaction log resources. \nAnd one of the reason is locks used by either statements. The DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row.</p>\n\n<p>• <strong>Transaction log</strong> : DELETE statement removes rows one at a time and makes individual entries in the transaction log for each row.<br>\nTRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.</p>\n\n<p>• <strong>Pages</strong> : After a DELETE statement is executed, the table can still contain empty pages. \nTRUNCATE removes the data by deallocating the data pages used to store the table data.</p>\n\n<p>• <strong>Trigger</strong> : TRUNCATE does not activate the delete triggers on the table. So you must be very careful while using TRUNCATE. One should never use a TRUNCATE if delete Trigger is defined on the table to do some automatic cleanup or logging action when rows are deleted.</p>\n\n<p>• <strong>Identity Column</strong> : With TRUNCATE if the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. \nDELETE doesn’t reset the identity counter. So if you want to retain the identity counter, use DELETE instead.</p>\n\n<p>• <strong>Replication</strong> : DELETE can be used against table used in transactional replication or merge replication.<br>\nWhile TRUNCATE cannot be used against the tables involved in transactional replication or merge replication. </p>\n\n<p>• <strong>Rollback</strong> : DELETE statement can be rolled back.<br>\nTRUNCATE can also be rolled back provided it is enclosed in a TRANSACTION block and session is not closed. Once session is closed you won't be able to Rollback TRUNCATE.</p>\n\n<p>• <strong>Restrictions</strong> : The DELETE statement may fail if it violates a trigger or tries to remove a row referenced by data in another table with a FOREIGN KEY constraint. If the DELETE removes multiple rows, and any one of the removed rows violates a trigger or constraint, the statement is canceled, an error is returned, and no rows are removed.<br>\nAnd if DELETE is used against View, that View must be an Updatable view. \nTRUNCATE cannot be used against the table used in Indexed view.<br>\nTRUNCATE cannot be used against the table referenced by a FOREIGN KEY constraint, unless a table that has a foreign key that references itself.</p>\n"
},
{
"answer_id": 37228916,
"author": "Shamseer K",
"author_id": 4133590,
"author_profile": "https://Stackoverflow.com/users/4133590",
"pm_score": 5,
"selected": false,
"text": "<p>Summary of Delete Vs Truncate in SQL server<br/>\nFor Complete Article follow this link : <a href=\"http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/\" rel=\"noreferrer\">http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Bil4e.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Bil4e.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Taken from dotnet mob article :<a href=\"http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/\" rel=\"noreferrer\">Delete Vs Truncate in SQL Server</a></p>\n"
},
{
"answer_id": 37781756,
"author": "Ali",
"author_id": 6457961,
"author_profile": "https://Stackoverflow.com/users/6457961",
"pm_score": 0,
"selected": false,
"text": "<p>DELETE statement can have a WHERE clause to delete specific records whereas TRUNCATE statement does not require any and wipes the entire table.\nImportantly, the DELETE statement logs the deleted date whereas the TRUNCATE statement does not.</p>\n"
},
{
"answer_id": 43488613,
"author": "Mykhailo Seniutovych",
"author_id": 7111692,
"author_profile": "https://Stackoverflow.com/users/7111692",
"pm_score": 0,
"selected": false,
"text": "<p>One more difference specific to microsoft sql server is with <code>delete</code> you can use <code>output</code> statement to track what records have been deleted, e.g.:</p>\n\n<pre><code>delete from [SomeTable]\noutput deleted.Id, deleted.Name\n</code></pre>\n\n<p>You cannot do this with <code>truncate</code>.</p>\n"
},
{
"answer_id": 43628085,
"author": "Rishish",
"author_id": 7787019,
"author_profile": "https://Stackoverflow.com/users/7787019",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Truncate</strong> command is used to re-initialize the table, it is a DDL command which delete all the rows of table.Whereas <strong>DELETE</strong> is a DML command which is used to delete row or set of rows according to some condition, if condition is not specified then this command will delete all the rows from the table. </p>\n"
},
{
"answer_id": 73405812,
"author": "Pawel W",
"author_id": 10461682,
"author_profile": "https://Stackoverflow.com/users/10461682",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a summary of some important differences between these sql commands:</p>\n<p><strong>sql truncate command:</strong></p>\n<p><strong>1)</strong> It is a DDL (Data Definition Language) command, therefore commands such as COMMIT and ROLLBACK do not apply to this command (the exceptions here are PostgreSQL and MSSQL, whose implementation of the TRUNCATE command allows the command to be used in a transaction)</p>\n<p><strong>2)</strong> You cannot undo the operation of deleting records, it occurs automatically and is irreversible (except for the above exceptions - provided, however, that the operation is included in the TRANSACTION block and the session is not closed). In case of Oracle - Includes two implicit commits, one before and one after the statement is executed. Therefore, the command cannot be withdrawn while a runtime error will result in commit anyway</p>\n<p><strong>3)</strong> Deletes all records from the table, records cannot be limited to deletion. For Oracle, when the table is split per partition, individual partitions can be truncated (TRUNCATE) in isolation, making it possible to partially remove all data from the table</p>\n<p><strong>4)</strong> Frees up the space occupied by the data in the table (in the TABLESPACE - on disk). For Oracle - if you use the REUSE STORAGE clause, the data segments will not be rolled back, i.e. you will keep space from the deleted rows allocated to the table, which can be a bit more efficient if the table is to be reloaded with data. The high mark will be reset</p>\n<p><strong>5)</strong> TRUNCATE works much faster than DELETE</p>\n<p><strong>6)</strong> Oracle Flashback in the case of TRUNCATE prevents going back to pre-operative states</p>\n<p><strong>7)</strong> Oracle - TRUNCATE cannot be granted (GRANT) without using DROP ANY TABLE</p>\n<p><strong>8)</strong> The TRUNCATE operation makes unusable indexes usable again</p>\n<p><strong>9)</strong> TRUNCATE cannot be used when the enabled foreign key refers to another table, then you can:</p>\n<ul>\n<li>execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or</li>\n<li>execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;</li>\n</ul>\n<p><strong>10)</strong> TRUNCATE requires an exclusive table lock, therefore, turning off exclusive table lock is a way to prevent TRUNCATE operation on the table</p>\n<p><strong>11)</strong> DML triggers do not fire after executing TRUNCATE (so be very careful in this case, you should not use TRUNCATE, if a delete trigger is defined in the table to perform an automatic table cleanup or a logon action after row deletion). On Oracle, DDL triggers are fired</p>\n<p><strong>12)</strong> Oracle - TRUNCATE cannot be used in the case of: database link\n<strong>13)</strong> TRUNCATE does not return the number of records deleted</p>\n<p><strong>14)</strong> Transaction log - one log indicating page deallocation (removes data, releasing allocation of data pages used for storing table data and writes only page deallocations to the transaction log) - faster execution than DELETE. TRUNCATE only needs to adjust the pointer in the database to the table (High Water Mark) and the data is immediately deleted, therefore it uses less system resources and transaction logs</p>\n<p><strong>15)</strong> Performance (acquired lock) - table and page lock - does not degrade performance during execution</p>\n<p><strong>16)</strong> TRUNCATE cannot be used on tables involved in transactional replication or merge replication</p>\n<p><strong>sql delete command:</strong></p>\n<p><strong>1)</strong> It is a DML (Data Manipulation Language) command, therefore the following commands are used for this command: COMMIT and ROLLBACK</p>\n<p><strong>2)</strong> You can undo the operation of removing records by using the ROLLBACK command</p>\n<p><strong>3)</strong> Deletes all or some records from the table, you can limit the records to be deleted by using the WHERE clause</p>\n<p><strong>4)</strong> Does not free the space occupied by the data in the table (in the TABLESPACE - on the disk)</p>\n<p><strong>5)</strong> DELETE works much slower than TRUNCATE</p>\n<p><strong>6)</strong> Oracle Flashback works for DELETE</p>\n<p><strong>7)</strong> Oracle - For DELETE, you can use the GRANT command</p>\n<p><strong>8)</strong> The DELETE operation does not make unusable indexes usable again</p>\n<p><strong>9)</strong> DELETE in case foreign key enabled refers to another table, can (or not) be applied depending on foreign key configuration (if not), please:</p>\n<ul>\n<li>execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or</li>\n<li>execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;</li>\n</ul>\n<p><strong>10)</strong> DELETE requires a shared table lock</p>\n<p><strong>11)</strong> Triggers fire</p>\n<p><strong>12)</strong> DELETE can be used in the case of: database link</p>\n<p><strong>13)</strong> DELETE returns the number of records deleted</p>\n<p><strong>14)</strong> Transaction log - for each deleted record (deletes rows one at a time and records an entry in the transaction log for each deleted row) - slower execution than TRUNCATE. The table may still contain blank pages after executing the DELETE statement. DELETE needs to read records, check constraints, update block, update indexes, and generate redo / undo. All of this takes time, hence it takes time much longer than with TRUNCATE</p>\n<p><strong>15)</strong> Performance (acquired lock) - record lock - reduces performance during execution - each record in the table is locked for deletion</p>\n<p><strong>16)</strong> DELETE can be used on a table used in transactional replication or merge replication</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
]
| I am working with Reporting Services and Sharepoint, I have an application that leverages reporting services however a client would like our application integrated into sharepoint. Currently we are tightly coupled to the ReportService.asmx webservice which exposes various methods for performing operations. Reporting Services has something called "Sharepoint Integration mode" when enabled the report server works differently and Sharepoint is used to manage the reports. Sharepoint adds a new web service called ReportService2006.asmx which is almost exactly the same.
Now our application uses a web reference to the ReportService and uses various objects exposed by the service. ReportService2006 has exactly the same objects but they are obviously in a different namespace e.g I have 2 web references - 1 to each service so there is an object MyApplication.ReportService.CatalogItem and another MyApplication.ReportService2006.CatalogItem.
I've tried to use dependency injection to absract the Service out of our application coupled with a factory pattern to determine which implementation of my interface to instantiate. Heres my interface. I've simplified it to include only the calls I need for this application.
```
using System;
using NetworkUserEncrypt.ReportService;
namespace MyApplication.Service
{
public interface IReportingService
{
CatalogItem CreateDataSource(string DataSource, string Parent, bool Overwrite, DataSourceDefinition Definition, Property[] Properties);
void DeleteItem(string Item);
DataSourceDefinition GetDataSourceContents(string DataSource);
byte[] GetReportDefinition(string Report);
CatalogItem[] ListChildren(string Item);
}
}
```
So I have 2 implementations of this each instantiating a different web service e.g:
```
namespace MyApp.Service.Implementation
{
class ReportingServiceImpl : IReportingService
{
ReportingService _service = null;
public ReportingServiceImpl()
{
ReportingService _service = new ReportingService();
}
/* SNIP */
}
}
```
and
```
namespace MyApp.Service.Implementation
{
class ReportingService2006Impl : IReportingService
{
ReportingService2006 _service = null;
public ReportingService2006Impl()
{
ReportingService2006 _service = new ReportingService2006();
}
/* SNIP */
}
}
```
So the plan is I can inject these into my ServiceWrapper at run time. However - if you'll notice the interface is tied to the ReportService and some of the methods return objects that are from the web reference e.g. CatalogItem. Thus my project won't build because my implementation for ReportService2006 is referencing the CatalogItem from a different namespace.
Any ideas? Am I going totally the wrong direction with this? | Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
---
General Overview
================
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
---
Statement type
==============
Delete is DML, Truncate is DDL ([What is DDL and DML?](https://stackoverflow.com/q/2578194/276052))
---
Commit and Rollback
===================
Variable by vendor
**SQL\*Server**
Truncate can be rolled back.
**PostgreSQL**
Truncate can be rolled back.
**Oracle**
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
---
Space reclamation
=================
Delete does not recover space, Truncate recovers space
**Oracle**
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
---
Row scope
=========
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
**Oracle**
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
---
Object types
============
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
---
Data Object Identity
====================
**Oracle**
Delete does not affect the data object id, but truncate assigns a new data object id *unless* there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
---
Flashback (Oracle)
==================
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
[Use of FLASHBACK in Oracle](https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle)
<http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638>
---
Privileges
==========
Variable
**Oracle**
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
---
Redo/Undo
=========
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
---
Indexes
=======
**Oracle**
A truncate operation renders unusable indexes usable again. Delete does not.
---
Foreign Keys
============
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
---
Table Locking
=============
**Oracle**
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
---
Triggers
========
DML triggers do not fire on a truncate.
**Oracle**
DDL triggers are available.
---
Remote Execution
================
**Oracle**
Truncate cannot be issued over a database link.
---
Identity Columns
================
**SQL\*Server**
Truncate resets the sequence for IDENTITY column types, delete does not.
---
Result set
==========
In most implementations, a `DELETE` statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
```
DELETE FROM employees_temp
WHERE employee_id = 299
RETURNING first_name,
last_name
INTO emp_first_name,
emp_last_name;
``` |
139,650 | <p>I have normally hand written xml like this:</p>
<pre><code><tag><?= $value ?></tag>
</code></pre>
<p>Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?</p>
| [
{
"answer_id": 139671,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 4,
"selected": true,
"text": "<p>Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using.</p>\n\n<p>Good XML tools also save a bunch of repetitive typing of tags.</p>\n"
},
{
"answer_id": 139675,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 1,
"selected": false,
"text": "<p>Use the generator.</p>\n\n<p>The advantage of using a generator is you have consistent markup and don't run the risk of fat-fingering a bracket or quote, or forgetting to encode something. This is crucial because these mistakes will not be found until runtime, unless you have significant tests to ensure otherwise.</p>\n"
},
{
"answer_id": 139678,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 3,
"selected": false,
"text": "<p>If you're dealing with a small bit of XML, there's little harm in doing it by hand (as long as you can avoid typos). However, with larger documents you're frequently better off using an editor, which can validate your doc against the schema and protect against typos.</p>\n"
},
{
"answer_id": 139681,
"author": "Enrico Murru",
"author_id": 68336,
"author_profile": "https://Stackoverflow.com/users/68336",
"pm_score": 1,
"selected": false,
"text": "<p>hand writing isn't always the best practice, because in large XML ou can write wrong tags and can be difficult to find the reason of an error. So I suggest to use XMl parsers to create XML files.</p>\n"
},
{
"answer_id": 139722,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "<p>Always use a tool of some kind. XML can be very complex, I know that the PHP guys are used to working with hackey little stuff, but its a huge code smell in the .NET world if someone doesn't use System.XML for creating XML.</p>\n"
},
{
"answer_id": 139855,
"author": "hakamadare",
"author_id": 17597,
"author_profile": "https://Stackoverflow.com/users/17597",
"pm_score": 2,
"selected": false,
"text": "<p>using a good XML generator will greatly reduce potential errors due to fat-fingering, lapse of attention, or whatever other human frailty. there are several different levels of machine assistance to choose from, however:</p>\n\n<ol>\n<li><p>at the very least, use a programmer's text editor that does syntax highlighting and auto-indentation. just noticing that your text is a different color than you expect, or not lining up the way you expect, can tip you off to a typo you might otherwise have missed.</p></li>\n<li><p>better yet, take a step back and write the XML as a data structure of whatever language you prefer, than convert that data structure to XML. Perl gives you modules such as the lightweight <a href=\"http://search.cpan.org/author/GRANTM/XML-Simple-2.18/lib/XML/Simple.pm\" rel=\"nofollow noreferrer\">XML::Simple</a> for small jobs or the heftier <a href=\"http://search.cpan.org/~bholzman/XML-Generator-1.01/Generator.pm\" rel=\"nofollow noreferrer\">XML::Generator</a>; using <code>XML::Simple</code> is just a matter of arranging your content into a standard Perl hash of hashes and running it through the appropriate method.</p></li>\n</ol>\n\n<p>-steve</p>\n"
},
{
"answer_id": 140203,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the <a href=\"http://de3.php.net/manual/en/book.dom.php\" rel=\"nofollow noreferrer\">DOM extenstion</a> which can be quite cumbersome to code against. My personal opinion is that the most effective way to write XML documents from ground up is the <a href=\"http://de3.php.net/manual/en/intro.xmlwriter.php\" rel=\"nofollow noreferrer\">XMLWriter extension</a> that comes with PHP and is enabled by default in recent versions.</p>\n\n<pre><code>$w=new XMLWriter();\n$w->openMemory();\n$w->startDocument('1.0','UTF-8');\n$w->startElement(\"root\");\n $w->writeAttribute(\"ah\", \"OK\");\n $w->text('Wow, it works!');\n$w->endElement();\necho htmlentities($w->outputMemory(true));\n</code></pre>\n"
},
{
"answer_id": 142771,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "<p>Producing XML via any sort of string manipulation opens the door for bugs to get into your code. The extremely simple example you posted, for instance, won't produce well-formed XML if $value contains an ampersand. </p>\n\n<p>There aren't a lot of edge cases in XML, but there are enough that it's a waste of time to write your own code to handle them. (And if you don't handle them, your code will unexpectedly fail someday. Nobody wants that.) Any good XML tool will automatically handle those cases.</p>\n"
},
{
"answer_id": 156417,
"author": "Hans",
"author_id": 24031,
"author_profile": "https://Stackoverflow.com/users/24031",
"pm_score": 0,
"selected": false,
"text": "<p>The XML tools in eclipse are really useful too. Just create a new xml schema and document, and you can easily use most of the graphical tools. I do like to point out that a prior understanding of how schemas work will be of use.</p>\n"
},
{
"answer_id": 394211,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Speed may be an issue... handwritten can be a lot faster.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
| I have normally hand written xml like this:
```
<tag><?= $value ?></tag>
```
Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that? | Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using.
Good XML tools also save a bunch of repetitive typing of tags. |
139,670 | <p>In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return.</p>
<p>Eg:</p>
<pre><code>insert into table values ('test1
test2
test3
test4');
</code></pre>
<p>When I retrieve it, I get the message in a line </p>
<p>test1 test2 test3 test4</p>
<p>The carriage return is treated as a single character.</p>
<p>Is there way to get the carriage returns or its just the way its going to be stored?</p>
<p>Thanks for the help guys!!!</p>
<p>Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert.</p>
<p>I return the data to the app development (C++) and may be some data or report viewer.</p>
<p>I don't want to manipulate on the data.</p>
| [
{
"answer_id": 139687,
"author": "Dejan",
"author_id": 11471,
"author_profile": "https://Stackoverflow.com/users/11471",
"pm_score": 2,
"selected": false,
"text": "<p>Can you please clarify how you retrieve the data back from the database? What tool do you use? The data probably contains the carriage returns but it's not displayed if you get the results in grid (try the results in text option)</p>\n"
},
{
"answer_id": 139690,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 0,
"selected": false,
"text": "<p>You might need to put in a \"\\n\" instead of a literal carriage return. </p>\n"
},
{
"answer_id": 139692,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 5,
"selected": false,
"text": "<p>You can store Carriage return in the database. The problem here is that you are using SQL Server Management Studio to display the results of your query. You probably have it configured to show the results in a grid. Change the configuration of SSMS to show results to text and you will see the carriage returns.</p>\n\n<p>Right click in the query window -> Results To -> Results To Text</p>\n\n<p>Run your query again.</p>\n"
},
{
"answer_id": 139697,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 0,
"selected": false,
"text": "<p>The carriage return is stored as is. The problem here is that your sql client is not understanding it. If you did a raw dump of this data you'll see that the carriage returns are there in the data.</p>\n\n<p>I use DBArtisan at work and it seems to work fine. However isql seems to have the same problem that you reported.</p>\n"
},
{
"answer_id": 139701,
"author": "Axeman",
"author_id": 22108,
"author_profile": "https://Stackoverflow.com/users/22108",
"pm_score": 2,
"selected": false,
"text": "<p>IIRC, using chr(13) + chr(10) should works.</p>\n\n<pre><code>insert into table values ('test1' + chr(13) + chr(10) + 'test2' );\n</code></pre>\n"
},
{
"answer_id": 139706,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 0,
"selected": false,
"text": "<p>Is this result in your HTML or in Query analyser? If it's in HTML, have a look at the source code and it might appear correct there, in which case you'd have to replace the crlf characters with <code><br /></code> tags.</p>\n\n<p>I'm also thinking that there used to be attributes you could add to an HTML textarea to force it to send carriage returns in certain ways -- soft or hard? I haven't looked that up, perhaps someone could do that.</p>\n\n<p>But SQL Server does save the two characters in my experience. In fact I did exactly as you described here a few days ago using SQL 2005 and each line break has two unprintable characters.</p>\n"
},
{
"answer_id": 139758,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 3,
"selected": false,
"text": "<pre><code>INSERT INTO table values('test1' + CHAR(10) + 'test2' + CHAR(10) + 'test3' + CHAR(10) + 'test4')\n</code></pre>\n\n<p>This should do it. To see the effect, switch the query result window to plain text output.</p>\n\n<p>Regards</p>\n"
},
{
"answer_id": 18869060,
"author": "Mario",
"author_id": 1018005,
"author_profile": "https://Stackoverflow.com/users/1018005",
"pm_score": 0,
"selected": false,
"text": "<p>I am using SQLite to store multiline texbox and got something like that when retrieving data stored and showing it on any object (txtboxes, labels, etc.). Anytime I copied data into NotePad/WordPad or similar, I could see that carriage returns were stored, they simply weren't show in the ASP page.</p>\n\n<p>Found the answer here:</p>\n\n<p><a href=\"http://www.mikesdotnetting.com/Article/20/How-to-retain-carriage-returns-or-line-breaks-in-an-ASP.NET-web-page\" rel=\"nofollow\">http://www.mikesdotnetting.com/Article/20/How-to-retain-carriage-returns-or-line-breaks-in-an-ASP.NET-web-page</a></p>\n\n<p>hope that helps.</p>\n\n<p>My code example:</p>\n\n<p>C#:</p>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n String str = Request.QueryString[\"idNoticia\"];\n this.dsNewsDetails.FilterExpression = \"idNoticia=\" + str;\n }\n</code></pre>\n\n<p>ASPX:</p>\n\n<pre><code> <asp:Label ID=\"BodyLabel\" \n runat=\"server\" style=\"font-size: medium\" \n Text='<%# Eval(\"body\").ToString().Replace(Environment.NewLine,\"<br/>\") %>' Width=\"100%\" />\n</code></pre>\n\n<p>Note: as mentioned in the link provided, Environment.NewLine works both for C# and VB</p>\n"
},
{
"answer_id": 47196096,
"author": "Ankit Mahajan",
"author_id": 4495887,
"author_profile": "https://Stackoverflow.com/users/4495887",
"pm_score": 0,
"selected": false,
"text": "<p>If you switch the output to plain text you can see the data in different lines.\nTo switch output go to <code>Tools>Options>Query Results</code>and set default destination to: text.\nYou can also try hitting <code>Ctrl+p</code> before executing query. Hope it helps.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21968/"
]
| In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return.
Eg:
```
insert into table values ('test1
test2
test3
test4');
```
When I retrieve it, I get the message in a line
test1 test2 test3 test4
The carriage return is treated as a single character.
Is there way to get the carriage returns or its just the way its going to be stored?
Thanks for the help guys!!!
Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert.
I return the data to the app development (C++) and may be some data or report viewer.
I don't want to manipulate on the data. | You can store Carriage return in the database. The problem here is that you are using SQL Server Management Studio to display the results of your query. You probably have it configured to show the results in a grid. Change the configuration of SSMS to show results to text and you will see the carriage returns.
Right click in the query window -> Results To -> Results To Text
Run your query again. |
139,686 | <p>The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their justification.</p>
<p>It's easy to demonstrate in c that redundant initialisation is optimised out:</p>
<pre><code>$ less test.c
#include <stdio.h>
main()
{
#ifdef INIT_LOC
int a = 33;
int b;
memset(&b,66,sizeof(b));
#else
int a;
int b;
#endif
a = 0;
b = 0;
printf ("a = %i, b = %i\n", a, b);
}
$ gcc --version
gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
</code></pre>
<p>[Not Optimised:]</p>
<pre><code>$ gcc test.c -S -o no_init.s; gcc test.c -S -D INIT_LOC=1 -o init.s; diff no_in
it.s init.s
22a23,28
> movl $33, -4(%ebp)
> movl $4, 8(%esp)
> movl $66, 4(%esp)
> leal -8(%ebp), %eax
> movl %eax, (%esp)
> call _memset
33a40
> .def _memset; .scl 3; .type 32; .endef
</code></pre>
<p>[Optimised:]</p>
<pre><code>$ gcc test.c -O -S -o no_init.s; gcc test.c -O -S -D INIT_LOC=1 -o init.s; diff
no_init.s init.s
$
</code></pre>
<p>So WRT performance under what circumstances is mandatory variable initialisation NOT a good idea?</p>
<p>IF applicable, no need to restrict answers to c/c++ but please be clear about the language/environment (and reproducible evidence much preferred over speculation!)</p>
| [
{
"answer_id": 139731,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes you need a variable as a placeholder (e.g. using the <code>ftime</code> functions), so it doesn't make sense to initialize them before calling the initialization function.</p>\n\n<p>However it wouldn't be bad, in my opinion, to annotate the fact that you are aware of the pitfalls, something in the way of</p>\n\n<pre><code>uninitialized time_t t;\ntime( &t );\n</code></pre>\n"
},
{
"answer_id": 139738,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if it is necessary to \"make them mandatory\", but I personally think it is always better to initialize variables. If the purpose of the application is to be as tight as possible then C/C++ is open for that purpose. However, I think many of us have been burned a time or two by not initializing a variable and assuming it contains a valid value (e.g. pointer) when it really doesn't. A pointer with an address of zero is much easier to check for than if it has random garbage from the last memory contents at that particular location. I think in most cases, it is no longer a matter of performance but a matter of clarity and safety.</p>\n"
},
{
"answer_id": 139744,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 4,
"selected": false,
"text": "<p>Short answer: declare the variable as close to first use as possible and initialize to \"zero\" if you still need to.</p>\n\n<p>Long answer: If you declare a variable at the start of a function, and don't use it until later, you should reconsider your placement of the variable to as local a scope as possible. You can then usually assign to it the needed value right away.</p>\n\n<p>If you must declare it uninitialized because it gets assigned in a conditional, or passed by reference and assigned to, initializing it to a null-equivalent value is a good idea. The compiler can sometimes save you if you compile under -Wall, as it will warn if you read from a variable before initializing it. However, it fails to warn you if you pass it to a function.</p>\n\n<p>If you play it safe and set it to a null-equivalent, you have done no harm if the function you pass it to overwrites it. If, however, the function you pass it to uses the value, you can pretty much be guaranteed failing an assert (if you have one), or at least segfaulting the second you use a null object. Random initialization can do all sorts of bad things, including \"work\".</p>\n"
},
{
"answer_id": 139762,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 1,
"selected": false,
"text": "<p>Performance? Nowadays? Maybe back when CPUs ran at 10mhz it did make sense, but today its hardly a problem. Always initialise them.</p>\n"
},
{
"answer_id": 139766,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 0,
"selected": false,
"text": "<p>As you've showed with respect to performacne it does not make a difference. The compiler will (in optimized builds) detect if a local variable is written without beeing read from and remove the code unless it has other side-effects.</p>\n\n<p>That said: If you initialize stuff with simple statements just to be sure it's initialized it's fine to do so.. I personally don't do it, for a single reason:</p>\n\n<p>It tricks the guys who may later maintain your code into thinking that the initialization is required. That little foo = 0; will increase the code-complexity. Other than that it's just a matter of taste.</p>\n\n<p>If you unnessesary initialize variables via complex statements it may have a side-effect.</p>\n\n<p>For example:</p>\n\n<pre><code> float x = sqrt(0);\n</code></pre>\n\n<p>May be optimized by your compiler if you are lucky and work with a clever compiler. With a not so clever compiler it may as well result in a costly and unnessesary function-call because sqrt can - as a side-effect - set the errno variable.</p>\n\n<p>If you call functions that you have defined yourself my best bet is, that the compiler always assumes that they may have side-effects and don't optimize them out. That may be different if the function happen to be in the same translation unit or you have whole program optimization turned on.</p>\n"
},
{
"answer_id": 139806,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 1,
"selected": false,
"text": "<p>In C/C++ I totally agree with you.</p>\n\n<p>In Perl when I create a variable it is automatically put to a default value.</p>\n\n<pre><code>my ($val1, $val2, $val3, $val4);\nprint $val1, \"\\n\";\nprint $val1 + 1, \"\\n\";\nprint $val2 + 2, \"\\n\";\nprint $val3 = $val3 . 'Hello, SO!', \"\\n\";\nprint ++$val4 +4, \"\\n\";\n</code></pre>\n\n<p>They are all set to undef initially. Undef is a false value, and a place holder. Due to the dynamic typing if I add a number to it, it assumes that my variable is a number and replaces undef with the eqivilent false value 0. If i do string operations a false version of a string is an empty string, and that gets automatically substituted.</p>\n\n<pre><code>[jeremy@localhost Code]$ ./undef.pl\n\n1\n2\nHello, SO!\n5\n</code></pre>\n\n<p>So for Perl at least declare early and don't worry. Especially as most programs have many variables. You use less lines and it looks cleaner without explicit initializing.</p>\n\n<pre><code> my($x, $y, $z);\n</code></pre>\n\n<p>:-)</p>\n\n<pre><code> my $x = 0;\n my $y = 0;\n my $z = 0;\n</code></pre>\n"
},
{
"answer_id": 139818,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 3,
"selected": false,
"text": "<p>This is a great example of <strong>Premature optimization is the root of all evil</strong></p>\n\n<p>The full quote is:</p>\n\n<blockquote>\n <p>There is no doubt that the grail of efficiency leads to abuse. Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a <em>strong negative impact when debugging and maintenance are considered</em>. <strong>We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.</strong>\n Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.</p>\n</blockquote>\n\n<p>This came from <a href=\"http://shreevatsa.wordpress.com/2008/05/16/premature-optimization-is-the-root-of-all-evil/\" rel=\"nofollow noreferrer\">Donald Knuth</a>. who are you going to believe...your colleagues or Knuth?<br>\nI know where my money is...</p>\n\n<p>To get back to the original question: \"Should we MANDATE initialization?\"<br>\nI would phrase it as so:</p>\n\n<blockquote>\n <p>Variables <strong>should</strong> be initialize, except in situation where it can be demonstrated there is a <em>significant</em> performance gain to be realized by not initializing. Come armed with hard numbers...</p>\n</blockquote>\n"
},
{
"answer_id": 139858,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes a variable is used to \"collect\" the result of a longer block of nested ifs/elses... In those cases I sometimes keep the variable uninitialized, because it <em>should</em> be initialized later by one of the conditional branches.</p>\n\n<p>The trick is: if I leave it uninitialized at first and then there's a bug in the long if/else block so the variable is never assigned, I can see that bug in Valgrind :-) which of course requires to frequently run the code (ideally the regular tests) through Valgrind.</p>\n"
},
{
"answer_id": 139868,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 1,
"selected": false,
"text": "<p>Always initialize local variables to zero at least. As you saw, there's no real performance it.</p>\n\n<pre><code>int i = 0;\nstruct myStruct m = {0};\n</code></pre>\n\n<p>You're basically adding 1 or 2 assembly instructions, if that. In fact, many C runtimes will do this for you on a \"Release\" build and you won't be changing a thing.</p>\n\n<p>But you should initalize it because you will now have that guarantee.</p>\n\n<p>One reason not to initialize has to do with debugging. Some runtimes, eg. MS CRT, will initialize memory with predetermined and documented patterns that you can identify. So when you're pouring through memory, you can see that the memory is indeed uninitialized and that hasn't been used and reset. That can be helpful in debugging. But that's during debugging.</p>\n"
},
{
"answer_id": 139936,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 2,
"selected": false,
"text": "<p>It should be <em>mostly</em> mandatory. The reason for this has nothing to do with <em>performance</em> but rather the danger of using an unitialized variable. However, there are cases where it simply looks ridiculous. For example, I have seen:</p>\n\n<pre><code>struct stat s;\ns.st_dev = -1;\ns.st_ino = -1;\ns.st_mode = S_IRWXU;\ns.st_nlink = 0;\ns.st_size = 0;\n// etc...\ns.st_st_ctime = -1;\nif(stat(path, &s) != 0) {\n // handle error\n return;\n}\n</code></pre>\n\n<p>WTF???</p>\n\n<p>Note that we are handling the error right away, so there is no question about what happens if the stat fails.</p>\n"
},
{
"answer_id": 139940,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 3,
"selected": false,
"text": "<p>If you think that an initialization is redundant, it is. My goal is to write code that is as humanly readable as possible. Unnecessary initialization confuses future reader.</p>\n\n<p>C compilers are getting pretty good at catching usage of unitialized variables, so the danger of that is now minimal.</p>\n\n<p>Don't forget, by making \"fake\" initialization, you trade one danger - crashing on using garbage (which leads to a bug that is very easy to find and fix) on another - program taking wrong action based on fake value (which leads to a bug that is very difficult to find). The choice depends on the application. For some, it is critical never to crash. For majority, it is better to catch the bug ASAP.</p>\n"
},
{
"answer_id": 140040,
"author": "Marcin",
"author_id": 22724,
"author_profile": "https://Stackoverflow.com/users/22724",
"pm_score": 2,
"selected": false,
"text": "<p>This pertains to C++ only, but there is a definite distinction between the two methods.\nLet's assume you have a class <code> MyStuff</code>, and you want to initialize it by another class. You could do something like:</p>\n\n<pre><code>// Initialize MyStuff instance y\n// ...\nMyStuff x = y;\n// ...\n</code></pre>\n\n<p>What this actually does is call the copy constructor of x. It's the same as:</p>\n\n<pre><code>MyStuff x(y);\n</code></pre>\n\n<p>This is different than this code:</p>\n\n<pre><code>MyStuff x; // This calls the MyStuff default constructor.\nx = y; // This calls the MyStuff assignment operator.\n</code></pre>\n\n<p>Of course, completely different code is called when copy constructing vs. default constructing + assigning. Also, a single call to the copy constructor is likely to be more efficient than construction followed by assignment.</p>\n"
},
{
"answer_id": 140250,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>As a simple example, can you determine what this will be initialised to (C/C++)?</p>\n\n<pre><code>bool myVar;\n</code></pre>\n\n<p>We had an issue in a product that would sometimes draw an image on screen and sometimes not, usually depending on who's machine it was built with. It turned out that on my machine it was being initialised to false, and on a colleagues machine it was being initialised to true.</p>\n"
},
{
"answer_id": 140901,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 0,
"selected": false,
"text": "<p>I think it is in most cases a bad idea to initialize variables with an default value, because it simply hides bugs, that are easily found with uninitialized variables. If you forget to get and set the actual value, or delete the get code by accident, you probably never notice it because 0 is in many cases a reasonable value. Mostly it is much easier to trigger those bugs with an value >> 0.</p>\n\n<p>For example:</p>\n\n<pre><code>\nvoid func(int n)\n{\n int i = 0;\n\n ... // Many lines of code\n\n for (;i < n; i++)\n do_something(i);\n</code></pre>\n\n<p>After some time you are going to add some other stuff.</p>\n\n<pre><code>\nvoid func(int n)\n{\n int i = 0;\n\n for (i = 0; i < 3; i++)\n do_something_else(i);\n\n ... // Many lines of code\n\n for (;i < n; i++)\n do_something(i);\n</code></pre>\n\n<p>Now your second loop won't start with 0, but with 3, depending on what the function does it can be very difficult to find, that there is even a bug.</p>\n"
},
{
"answer_id": 153289,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 0,
"selected": false,
"text": "<p>Just a secondary observation. Initializations are only EASILY optimized on primitive types or when assigned by const functions.</p>\n\n<p>a= foo();</p>\n\n<p>a= foo2();</p>\n\n<p>Cannot be easily optimized because foo may have side effects.</p>\n\n<p>Also heap allocations before time might result in huge performance hits. Take a code like</p>\n\n<pre><code>void foo(int x)\n</code></pre>\n\n<p>{</p>\n\n<p>ClassA *instance= new ClassA();</p>\n\n<p>//... do something not \"instance\" related...\n if(x>5)\n {</p>\n\n<pre><code>delete instance;\n\nreturn;\n</code></pre>\n\n<p>}</p>\n\n<p>//.. do something that uses instance</p>\n\n<p>}</p>\n\n<p>On that case, simply declare instance just when you will use it, and initialize it only there. And no The compiler Cannot optimize that for you since the constructor may have side effects that code reordering would change.</p>\n\n<p>edit: I fail at using the code listing feature :P</p>\n"
},
{
"answer_id": 153411,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<p>Let me tell you a story about a product I worked on in 1992 and later that, for the purposes of this story, we'll call Stackrobat. I was assigned a bug that caused the application to crash on the Mac, but not on Windows, oh and the bug was not reproducible reliably. It took QA the better part of a week to come up with a recipe that worked maybe 1 in 10 times.</p>\n\n<p>It was hell tracking down the root cause since the actual crash happened well after the action that did it.</p>\n\n<p>Ultimately, I tracked it down by writing a custom code profiler for the compiler. The compiler would quite happily inject calls to global prof_begin() and prof_end() functions and you were free to implement them yourselves. I wrote a profiler that took the return address from the stack, found the stack frame creation instruction, located the block on the stack that represented the locals for the function and coated them with a tasty layer of crap that would cause a bus error if any element was dereferenced.</p>\n\n<p>This caught something like a half dozen errors of pointers being used before initialization, including the bug I was looking for.</p>\n\n<p>What happened was that most of the time the stack happened to have values that were apparently benign if they were dereferenced. Other times the values would cause the app to shotgun its own heap, taking out the app sometime much later.</p>\n\n<p>I spent more than two weeks trying to find this bug.</p>\n\n<p>Lesson: initialize your locals. If someone barks performance at you, show them this comment and tell them that you'd rather spend two weeks running profiling code and fixing bottlenecks rather than having to track down bugs like this. Debugging tools and heap checkers have gotten way better since I had to do this, but quite frankly they got better to compensate for bugs from poor practices like this.</p>\n\n<p>Unless you're running on a tiny system (embedded, etc), initialization of locals should be nearly free. MOVE/LOAD instructions are very, very fast. Write the code to be solid and maintainable first. Refactor it to be performant second.</p>\n"
},
{
"answer_id": 283127,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "<p>Yes: <em>always</em> initialize your variables unless you have a <em>very</em> good reason not to. If my code doesn't require a particular initial value, I'll often initialize a variable to a value that will <em>guarantee</em> a blatant error if the code that follows is broken.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22640/"
]
| The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their justification.
It's easy to demonstrate in c that redundant initialisation is optimised out:
```
$ less test.c
#include <stdio.h>
main()
{
#ifdef INIT_LOC
int a = 33;
int b;
memset(&b,66,sizeof(b));
#else
int a;
int b;
#endif
a = 0;
b = 0;
printf ("a = %i, b = %i\n", a, b);
}
$ gcc --version
gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
```
[Not Optimised:]
```
$ gcc test.c -S -o no_init.s; gcc test.c -S -D INIT_LOC=1 -o init.s; diff no_in
it.s init.s
22a23,28
> movl $33, -4(%ebp)
> movl $4, 8(%esp)
> movl $66, 4(%esp)
> leal -8(%ebp), %eax
> movl %eax, (%esp)
> call _memset
33a40
> .def _memset; .scl 3; .type 32; .endef
```
[Optimised:]
```
$ gcc test.c -O -S -o no_init.s; gcc test.c -O -S -D INIT_LOC=1 -o init.s; diff
no_init.s init.s
$
```
So WRT performance under what circumstances is mandatory variable initialisation NOT a good idea?
IF applicable, no need to restrict answers to c/c++ but please be clear about the language/environment (and reproducible evidence much preferred over speculation!) | Short answer: declare the variable as close to first use as possible and initialize to "zero" if you still need to.
Long answer: If you declare a variable at the start of a function, and don't use it until later, you should reconsider your placement of the variable to as local a scope as possible. You can then usually assign to it the needed value right away.
If you must declare it uninitialized because it gets assigned in a conditional, or passed by reference and assigned to, initializing it to a null-equivalent value is a good idea. The compiler can sometimes save you if you compile under -Wall, as it will warn if you read from a variable before initializing it. However, it fails to warn you if you pass it to a function.
If you play it safe and set it to a null-equivalent, you have done no harm if the function you pass it to overwrites it. If, however, the function you pass it to uses the value, you can pretty much be guaranteed failing an assert (if you have one), or at least segfaulting the second you use a null object. Random initialization can do all sorts of bad things, including "work". |
139,739 | <p>I've been doing a massive code review and one pattern I notice all over the place is this:</p>
<pre><code>public bool MethodName()
{
bool returnValue = false;
if (expression)
{
// do something
returnValue = MethodCall();
}
else
{
// do something else
returnValue = Expression;
}
return returnValue;
}
</code></pre>
<p>This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?</p>
<p>I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.</p>
| [
{
"answer_id": 139754,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<p>I would have used ternary, to reduce control structures...</p>\n\n<pre>\n<code>\nreturn expression ? MethodCall() : Expression;\n</code>\n</pre>\n"
},
{
"answer_id": 139769,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 0,
"selected": false,
"text": "<p>They both accomplish the same task. Some say that a method should only have one entry and one exit point. </p>\n"
},
{
"answer_id": 139770,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "<p>Some learning institutes and books advocate the single return practice.</p>\n\n<p>Whether it's better or not is subjective.</p>\n"
},
{
"answer_id": 139772,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 0,
"selected": false,
"text": "<p>I use this, too. The idea is that resources can be freed in the normal flow of the program. If you jump out of a method at 20 different places, and you need to call cleanUp() before, you'll have to add yet another cleanup method 20 times (or refactor everything)</p>\n"
},
{
"answer_id": 139774,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect I will be in the minority but I like the style presented in the example. It is easy to add a log statement and set a breakpoint, IMO. Plus, when used in a consistent way, it seems easier to \"pattern match\" than having multiple returns.</p>\n\n<p>I'm not sure there is a \"correct\" answer on this, however.</p>\n"
},
{
"answer_id": 139775,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>I guess that the coder has taken the design of defining an object toReturn at the top of the method (e.g., List<Foo> toReturn = new ArrayList<Foo>();) and then populating it during the method call, and somehow decided to apply it to a boolean return type, which is odd. </p>\n\n<p>Could also be a side effect of a coding standard that states that you can't return in the middle of a method body, only at the end.</p>\n"
},
{
"answer_id": 139780,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 0,
"selected": false,
"text": "<p>Even if no code is executed after the return value is assigned now it does not mean that some code will not have to be added later.</p>\n\n<p>It's not the smallest piece of code which could be used but it is very refactoring-friendly.</p>\n"
},
{
"answer_id": 139784,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation.</p>\n\n<p>The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points.</p>\n\n<p>Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns.</p>\n"
},
{
"answer_id": 139788,
"author": "Nenad Dobrilovic",
"author_id": 22062,
"author_profile": "https://Stackoverflow.com/users/22062",
"pm_score": 1,
"selected": false,
"text": "<p>That looks like a part of a bad OOP design. Perhaps it should be refactored on the higher level than inside of a single method.</p>\n\n<p>Otherwise, I prefer using a ternary operator, like this:</p>\n\n<pre><code>return expression ? MethodCall() : Expression;\n</code></pre>\n\n<p>It is shorter and more readable.</p>\n"
},
{
"answer_id": 139797,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "<p>Delphi forces this pattern by automatically creating a variable called \"Result\" which will be of the function's return type. Whatever \"Result\" is when the function exits, is your return value. So there's no \"return\" keyword at all.</p>\n\n<pre><code>function MethodName : boolean;\nbegin\n Result := False;\n if Expression then begin\n //do something\n Result := MethodCall;\n end\n else begin\n //do something else\n Result := Expression;\n end;\n\n //possibly more code\nend;\n</code></pre>\n"
},
{
"answer_id": 139937,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 0,
"selected": false,
"text": "<p>The pattern used is verbose - but it's also easier to debug if you want to know the return value without opening the Registers window and checking EAX.</p>\n"
},
{
"answer_id": 217592,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 1,
"selected": false,
"text": "<p>Return from a method right away in any of these situations:</p>\n\n<ol>\n<li>You've found a boundary condition and need to return a unique or sentinel value: <code>if (node.next = null) return NO_VALUE_FOUND;</code></li>\n<li>A required value/state is false, so the rest of the method does not apply (aka a guard clause). E.g.: <code>if (listeners == null) return null;</code></li>\n<li>The method's purpose is to find and return a specific value, e.g.: <code>if (nodes[i].value == searchValue) return i;</code></li>\n<li>You're in a clause which returns a unique value from the method not used elsewhere in the method: <code>if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount();</code></li>\n</ol>\n\n<p>Otherwise, it is useful to have only one return statement so that it's easier to add debug logging, resource cleanup and follow the logic. I try to handle all the above 4 cases first, if they apply, then declare a variable named <code>result(s)</code> as late as possible and assign values to that as needed.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
]
| I've been doing a massive code review and one pattern I notice all over the place is this:
```
public bool MethodName()
{
bool returnValue = false;
if (expression)
{
// do something
returnValue = MethodCall();
}
else
{
// do something else
returnValue = Expression;
}
return returnValue;
}
```
This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?
I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned. | I would have used ternary, to reduce control structures...
```
return expression ? MethodCall() : Expression;
``` |
139,759 | <p>Is there any way to list all the files that have changed between two tags in CVS?</p>
<p>Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases.</p>
<p>It would also work if I could find all files that had changed between two dates.</p>
| [
{
"answer_id": 139871,
"author": "Decio Lira",
"author_id": 12423,
"author_profile": "https://Stackoverflow.com/users/12423",
"pm_score": 6,
"selected": true,
"text": "<p>I suppose this command would help:</p>\n\n<pre><code>cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs\n</code></pre>\n\n<p>where <code>RELEASE_1_0</code> and <code>RELEASE_1_1</code> are the names of your tags.</p>\n\n<p>You can find a little more information on cvs diff command <a href=\"http://www.network-theory.co.uk/docs/cvsmanual/diffexamples.html\" rel=\"noreferrer\">here</a></p>\n\n<p>plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box.</p>\n\n<p>Hope it helps <code>;)</code></p>\n"
},
{
"answer_id": 139923,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 2,
"selected": false,
"text": "<p>DLira's method gives a lot of detail, including all the changes. </p>\n\n<p>To just get a list of files, this works:</p>\n\n<pre><code>cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 | grep \"Index:\" > diffs\n</code></pre>\n"
},
{
"answer_id": 140164,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 1,
"selected": false,
"text": "<p>The best tool I've found for this is a perl script called <a href=\"http://www.red-bean.com/cvs2cl/\" rel=\"nofollow noreferrer\">cvs2cl.pl</a>. This can generate a change list in several different formats. It has many different options, but I've used the tag-to-tag options like this:</p>\n\n<pre><code>cvs2cl.pl --delta dev_release_1_2_3:dev_release_1_6_8\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cvs2cl.pl --delta dev_release_1_2_3:HEAD\n</code></pre>\n\n<p>I have also done comparisons using dates with the same tool.</p>\n"
},
{
"answer_id": 212972,
"author": "Sally",
"author_id": 6539,
"author_profile": "https://Stackoverflow.com/users/6539",
"pm_score": 5,
"selected": false,
"text": "<p>I prefer using <code>rdiff</code> and <code>-s</code> option</p>\n\n<pre><code>cvs rdiff -s -r RELEASE_1_0 -r RELEASE_1_1 module > diffs\n</code></pre>\n\n<p><code>rdiff</code> does not require a sandbox; <code>-s</code> gives you a summary of the changes.</p>\n"
},
{
"answer_id": 1622631,
"author": "Taufiq",
"author_id": 102076,
"author_profile": "https://Stackoverflow.com/users/102076",
"pm_score": 4,
"selected": false,
"text": "<p>To get a list of files that have changed between one version and another using the standard cvs commands:</p>\n\n<pre><code>cvs -q log -NSR -rV-1-0-69::V-1-0-70 2>/dev/null >log.txt\n</code></pre>\n\n<p>Or alternatively, to get a list of commit comments just drop the <code>-R</code>:</p>\n\n<pre><code>cvs -q log -NS -rV-1-0-69::V-1-0-70 2>/dev/null >log.txt\n</code></pre>\n\n<p>Where you replace <code>V-1-0-69</code> and <code>V-1-0-70</code> with the revisions you're comparing.</p>\n"
},
{
"answer_id": 2343054,
"author": "Michael",
"author_id": 48767,
"author_profile": "https://Stackoverflow.com/users/48767",
"pm_score": 4,
"selected": false,
"text": "<p>To get the list of files between two dates using CVS:</p>\n\n<pre><code>cvs diff -N -c -D YYYY-MM-DD -D YYYY-MM-DD | grep \"Index:\" > diff.out\n</code></pre>\n\n<p>More information on accepted dates for the -D flag: <a href=\"http://docs.freebsd.org/info/cvs/cvs.info.Common_options.html\" rel=\"noreferrer\">http://docs.freebsd.org/info/cvs/cvs.info.Common_options.html</a></p>\n"
},
{
"answer_id": 3222641,
"author": "tkrille",
"author_id": 388804,
"author_profile": "https://Stackoverflow.com/users/388804",
"pm_score": 3,
"selected": false,
"text": "<pre><code>cvs log -d \">=DATE\" -N -S -R > cvs.log\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3464/"
]
| Is there any way to list all the files that have changed between two tags in CVS?
Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases.
It would also work if I could find all files that had changed between two dates. | I suppose this command would help:
```
cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs
```
where `RELEASE_1_0` and `RELEASE_1_1` are the names of your tags.
You can find a little more information on cvs diff command [here](http://www.network-theory.co.uk/docs/cvsmanual/diffexamples.html)
plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box.
Hope it helps `;)` |
139,794 | <p>Let's say we have <code>index.php</code> and it is stored in <code>/home/user/public/www</code> and <code>index.php</code> calls the class <code>Foo->bar()</code> from the file <code>inc/app/Foo.class.php</code>. </p>
<p>I'd like the bar function in the <code>Foo</code> class to get a hold of the path <code>/home/user/public/www</code> in this instance — I don't want to use a global variable, pass a variable, etc.</p>
| [
{
"answer_id": 139825,
"author": "RobbieGee",
"author_id": 6752,
"author_profile": "https://Stackoverflow.com/users/6752",
"pm_score": 1,
"selected": false,
"text": "<p>Found it. getcwd().</p>\n"
},
{
"answer_id": 139830,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://us3.php.net/debug_backtrace\" rel=\"noreferrer\">debug_backtrace</a> to look at the calling path and get the file calling this function.</p>\n\n<p>A short example:</p>\n\n<pre><code>class Foo {\n function bar() { \n $trace = debug_backtrace();\n echo \"calling file was \".$trace[0]['file'].\"\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 139845,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 2,
"selected": false,
"text": "<p><code>getcwd()</code> gets the current working directory</p>\n\n<p>It can be changed for a variety of reasons by 3rd party modules, includes or even your own code by issuing a <code>chdir()</code>.</p>\n\n<p><code>debug_backtrace()</code> as Devon suggested is the answer you're looking for.</p>\n"
},
{
"answer_id": 139874,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 5,
"selected": true,
"text": "<p>Wouldn't this get you the directory of the running script more easily?</p>\n\n<pre><code>$dir=dirname($_SERVER[\"SCRIPT_FILENAME\"])\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752/"
]
| Let's say we have `index.php` and it is stored in `/home/user/public/www` and `index.php` calls the class `Foo->bar()` from the file `inc/app/Foo.class.php`.
I'd like the bar function in the `Foo` class to get a hold of the path `/home/user/public/www` in this instance — I don't want to use a global variable, pass a variable, etc. | Wouldn't this get you the directory of the running script more easily?
```
$dir=dirname($_SERVER["SCRIPT_FILENAME"])
``` |
139,809 | <p>I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?</p>
| [
{
"answer_id": 139886,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 5,
"selected": true,
"text": "<p>You don't need to inherit from <code>ServiceHost</code>. There are other approaches to your problem.</p>\n\n<p>You can pass an instance of the service class, instead of a type to <code>ServiceHost</code>. Thus, you can create the instance before you start the <code>ServiceHost</code>, and add your own event handlers to any events it exposes.</p>\n\n<p>Here's some sample code:</p>\n\n<pre><code>MyService svc = new MyService();\nsvc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);\nServiceHost host = new ServiceHost(svc);\nhost.Open();\n</code></pre>\n\n<p>There are some caveats when using this approach, as described in <a href=\"http://msdn.microsoft.com/en-us/library/ms585487.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms585487.aspx</a></p>\n\n<p>Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.</p>\n"
},
{
"answer_id": 4295649,
"author": "Pankaj Awasthi",
"author_id": 522781,
"author_profile": "https://Stackoverflow.com/users/522781",
"pm_score": 0,
"selected": false,
"text": "<pre><code>using ...\nusing ...\n\nnamespace MyWCFNamespace\n{\n class Program {\n\n static void Main(string[] args){\n //instantiate the event receiver\n Consumer c = new Consumer();\n\n // instantiate the event source\n WCFService svc = new WCFService();\n svc.WCFEvent += new SomeEventHandler(c.ProcessTheRaisedEvent);\n\n using(ServiceHost host = new ServiceHost(svc))\n {\n host.Open();\n Console.Readline();\n }\n }\n }\n\n\n public class Consumer()\n {\n public void ProcessTheRaisedEvent(object sender, MyEventArgs e)\n {\n Console.WriteLine(e.From.toString() + \"\\t\" + e.To.ToString());\n }\n }\n}\n\n\nnamespace MyWCFNamespace\n{\n public delegate void SomeEventHandler(object sender,MyEventArgs e)\n\n [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]\n public class WCFService : IWCFService \n {\n public event SomeEventHandler WCFEvent;\n\n public void someMethod(Message message)\n {\n MyEventArgs e = new MyEventArgs(message);\n OnWCFEvent(e);\n }\n\n public void OnWCFEvent(MyEventArgs e)\n {\n SomeEventHandler handler = WCFEvent;\n if(handler!=null)\n {\n handler(this,e);\n }\n }\n\n // to do \n // Implement WCFInterface methods here\n }\n\n\n public class MyEventArgs:EventArgs\n {\n private Message _message;\n public MyEventArgs(Message message) \n {\n this._message=message;\n }\n }\n public class Message\n {\n string _from;\n string _to;\n public string From {get{return _from;} set {_from=value;}}\n public string To {get{return _to;} set {_to=value;}}\n public Message(){}\n public Message(string from,string to)\n this._from=from;\n this._to=to;\n }\n}\n</code></pre>\n\n<p>You can define your WCF service with <code>InstanceContextMode = InstanceContextMode.Single</code>.</p>\n\n<pre><code>TestService svc = new TestService();\nsvc.SomeEvent += new MyEventHandler(receivingObject.OnSomeEvent);\nServiceHost host = new ServiceHost(svc);\nhost.Open();\n\n[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] // so that a single service instance is created\n public class TestService : ITestService\n {\n public event MyEventHandler SomeEvent;\n ...\n ...\n }\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8033/"
]
| I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost? | You don't need to inherit from `ServiceHost`. There are other approaches to your problem.
You can pass an instance of the service class, instead of a type to `ServiceHost`. Thus, you can create the instance before you start the `ServiceHost`, and add your own event handlers to any events it exposes.
Here's some sample code:
```
MyService svc = new MyService();
svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();
```
There are some caveats when using this approach, as described in <http://msdn.microsoft.com/en-us/library/ms585487.aspx>
Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen. |
139,819 | <p>The following test fails:</p>
<pre><code>#!/usr/bin/env python
def f(*args):
"""
>>> t = 1, -1
>>> f(*map(lambda i: lambda: i, t))
[1, -1]
>>> f(*(lambda: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda: i for i in t]) # -> [-1, -1]
[1, -1]
"""
alist = [a() for a in args]
print(alist)
if __name__ == '__main__':
import doctest; doctest.testmod()
</code></pre>
<p>In other words:</p>
<pre><code>>>> t = 1, -1
>>> args = []
>>> for i in t:
... args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
... args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
... args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]
</code></pre>
| [
{
"answer_id": 139880,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "<p>The lambda captures variables, not values, hence the code</p>\n\n<pre><code>lambda : i\n</code></pre>\n\n<p>will always return the value i is <strong>currently</strong> bound to in the closure. By the time it gets called, this value has been set to -1.</p>\n\n<p>To get what you want, you'll need to capture the actual binding at the time the lambda is created, by:</p>\n\n<pre><code>>>> f(*(lambda i=i: i for i in t)) # -> [-1, -1]\n[1, -1]\n>>> f(*[lambda i=i: i for i in t]) # -> [-1, -1]\n[1, -1]\n</code></pre>\n"
},
{
"answer_id": 139899,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": true,
"text": "<p>They are different, because the value of <code>i</code> in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in <code>f</code>.<br>\nBy that time, <code>i</code> is bound to the last value if <code>t</code>, which is -1.</p>\n\n<p>So basically, this is what the list comprehension does (likewise for the genexp):</p>\n\n<pre><code>x = []\ni = 1 # 1. from t\nx.append(lambda: i)\ni = -1 # 2. from t\nx.append(lambda: i)\n</code></pre>\n\n<p>Now the lambdas carry around a closure that references <code>i</code>, but <code>i</code> is bound to -1 in both cases, because that is the last value it was assigned to.</p>\n\n<p>If you want to make sure that the lambda receives the current value of <code>i</code>, do</p>\n\n<pre><code>f(*[lambda u=i: u for i in t])\n</code></pre>\n\n<p>This way, you force the evaluation of <code>i</code> at the time the closure is created.</p>\n\n<p><strong>Edit</strong>: There is one difference between generator expressions and list comprehensions: the latter leak the loop variable into the surrounding scope.</p>\n"
},
{
"answer_id": 141113,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>Expression <code>f = lambda: i</code> is equivalent to:</p>\n\n<pre><code>def f():\n return i\n</code></pre>\n\n<p>Expression <code>g = lambda i=i: i</code> is equivalent to:</p>\n\n<pre><code>def g(i=i):\n return i\n</code></pre>\n\n<p><code>i</code> is a <a href=\"http://docs.python.org/ref/naming.html\" rel=\"nofollow noreferrer\">free variable</a> in the first case and it is bound to the function parameter in the second case i.e., it is a local variable in that case. Values for default parameters are evaluated at the time of function definition. </p>\n\n<p>Generator expression is the nearest enclosing scope (where <code>i</code> is defined) for <code>i</code> name in the <code>lambda</code> expression, therefore <code>i</code> is resolved in that block:</p>\n\n<pre><code>f(*(lambda: i for i in (1, -1)) # -> [-1, -1]\n</code></pre>\n\n<p><code>i</code> is a local variable of the <code>lambda i: ...</code> block, therefore the object it refers to is defined in that block:</p>\n\n<pre><code>f(*map(lambda i: lambda: i, (1,-1))) # -> [1, -1]\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
]
| The following test fails:
```
#!/usr/bin/env python
def f(*args):
"""
>>> t = 1, -1
>>> f(*map(lambda i: lambda: i, t))
[1, -1]
>>> f(*(lambda: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda: i for i in t]) # -> [-1, -1]
[1, -1]
"""
alist = [a() for a in args]
print(alist)
if __name__ == '__main__':
import doctest; doctest.testmod()
```
In other words:
```
>>> t = 1, -1
>>> args = []
>>> for i in t:
... args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
... args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
... args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]
``` | They are different, because the value of `i` in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in `f`.
By that time, `i` is bound to the last value if `t`, which is -1.
So basically, this is what the list comprehension does (likewise for the genexp):
```
x = []
i = 1 # 1. from t
x.append(lambda: i)
i = -1 # 2. from t
x.append(lambda: i)
```
Now the lambdas carry around a closure that references `i`, but `i` is bound to -1 in both cases, because that is the last value it was assigned to.
If you want to make sure that the lambda receives the current value of `i`, do
```
f(*[lambda u=i: u for i in t])
```
This way, you force the evaluation of `i` at the time the closure is created.
**Edit**: There is one difference between generator expressions and list comprehensions: the latter leak the loop variable into the surrounding scope. |
139,821 | <p>What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message.</p>
| [
{
"answer_id": 139965,
"author": "willem",
"author_id": 22702,
"author_profile": "https://Stackoverflow.com/users/22702",
"pm_score": 2,
"selected": false,
"text": "<p>Ensure that you use a webHttpBinding on your endpoint (and not an httpBinding or wsHttpBinding). Here's my endpoint config...</p>\n\n<pre><code> <endpoint address=\"\" binding=\"webHttpBinding\" bindingConfiguration=\"\"\n contract=\"WcfCore.ICustomer\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n</code></pre>\n"
},
{
"answer_id": 140017,
"author": "kgriffs",
"author_id": 21784,
"author_profile": "https://Stackoverflow.com/users/21784",
"pm_score": 4,
"selected": true,
"text": "<p>I discovered that you can add the following to the ServiceHost directive in the *.svc file, and it will automatically setup WebHttpBinding and WebHttpBehavior for you:</p>\n\n<pre><code>Factory=\"System.ServiceModel.Activation.WebServiceHostFactory\"\n</code></pre>\n\n<p>Note that the namespace is a little different from what is mentioned elsewhere on the web (such as in <a href=\"http://msdn.microsoft.com/en-us/magazine/cc135976.aspx\" rel=\"nofollow noreferrer\">this MSDN article</a>).</p>\n\n<p>After doing this, I was able to delete the entire section from web.config and everything still worked!</p>\n"
},
{
"answer_id": 140047,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 1,
"selected": false,
"text": "<p>You need to ensure that you have an address for your service host e.g</p>\n\n<pre><code><services>\n <service name=\"SomeLib.SomeService\">\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:8080/somebase\"/>\n </baseAddresses>\n </host>\n<!-- And one EndPoint **basicHttpBinding** WILL WORK !!! -->\n\n <endpoint \n address=\"basic\"\n binding=\"basicHttpBinding\"\n contract=\"SomeLib.SomeContract\"/>\n</service>\n</services>\n</code></pre>\n\n<p>So now, if you are self hosting via a console app for e.g...you can invoke your host via:</p>\n\n<pre><code>WebChannelFactory<IServiceContract> factory =\n new WebChannelFactory<IServiceContract>(\n new Uri(\"http://localhost:8080/somebase\"));\n</code></pre>\n\n<p>When the console app starts up, the address will be browsable even if its self hosted and you should be able to invoke your actions based on your webget uri templates.</p>\n\n<p>This minimum config will let you invoke WCF RestFULLY via selfhosting. If you're hosting in IIS it would essentially work the same way, except the svc file replaces our custom host.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21784/"
]
| What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message. | I discovered that you can add the following to the ServiceHost directive in the \*.svc file, and it will automatically setup WebHttpBinding and WebHttpBehavior for you:
```
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
```
Note that the namespace is a little different from what is mentioned elsewhere on the web (such as in [this MSDN article](http://msdn.microsoft.com/en-us/magazine/cc135976.aspx)).
After doing this, I was able to delete the entire section from web.config and everything still worked! |
139,833 | <p>I am using StringReplace to replace &gt and &lt by the char itself in a generated XML like this:</p>
<pre><code>StringReplace(xml.Text,'&gt;','>',[rfReplaceAll]) ;
StringReplace(xml.Text,'&lt;','<',[rfReplaceAll]) ;
</code></pre>
<p>The thing is it takes way tooo long to replace every occurence of &gt.</p>
<p>Do you purpose any better idea to make it faster?</p>
| [
{
"answer_id": 139876,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is that you are iterating the entire string size twice (one for replacing &gt; by > and another one to replace &lt; by <).</p>\n\n<p>You should iterate with a for and simply check ahead whenever you find a & for a gt; or lt; and do the immediate replace and then skipping 3 characters ((g|l)t;). This way it can do that in proportional time to the size of the string <strong>xml.Text</strong>.</p>\n\n<hr>\n\n<p>A simple C# example as I do not know Delphi but should do for you to get the general idea.</p>\n\n<pre><code>String s = \"&lt;xml&gt;test&lt;/xml&gt;\";\nchar[] input = s.ToCharArray();\nchar[] res = new char[s.Length];\nint j = 0;\nfor (int i = 0, count = input.Length; i < count; ++i)\n{\n if (input[i] == '&')\n {\n if (i < count - 3)\n {\n if (input[i + 1] == 'l' || input[i + 1] == 'g')\n {\n if (input[i + 2] == 't' && input[i + 3] == ';')\n {\n res[j++] = input[i + 1] == 'l' ? '<' : '>';\n i += 3;\n continue;\n }\n }\n }\n }\n\n res[j++] = input[i];\n}\nConsole.WriteLine(new string(res, 0, j));\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code><xml>test</xml>\n</code></pre>\n"
},
{
"answer_id": 140022,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 2,
"selected": false,
"text": "<p>Untested conversion of the C# code written by Jorge Ferreira.</p>\n\n<pre><code>function ReplaceLtGt(const s: string): string;\nvar\n inPtr, outPtr: integer;\nbegin\n SetLength(Result, Length(s));\n inPtr := 1;\n outPtr := 1;\n while inPtr <= Length(s) do begin\n if (s[inPtr] = '&') and ((inPtr + 3) <= Length(s)) and\n (s[inPtr+1] in ['l', 'g']) and (s[inPtr+2] = 't') and\n (s[inPtr+3] = ';') then\n begin\n if s[inPtr+1] = 'l' then\n Result[outPtr] := '<'\n else\n Result[outPtr] := '>';\n Inc(inPtr, 3);\n end\n else begin\n Result[outPtr] := Result[inPtr];\n Inc(inPtr);\n end;\n Inc(outPtr);\n end;\n SetLength(Result, outPtr - 1);\nend;\n</code></pre>\n"
},
{
"answer_id": 140124,
"author": "Germán Estévez -Neftalí-",
"author_id": 17487,
"author_profile": "https://Stackoverflow.com/users/17487",
"pm_score": 4,
"selected": true,
"text": "<p>Try <a href=\"http://www.koders.com/delphi/fidFB386C5C240FD5E72013C882ADD7600FDF60E6C7.aspx?s=socket\" rel=\"noreferrer\">FastStrings.pas</a> from Peter Morris.</p>\n"
},
{
"answer_id": 140173,
"author": "mj2008",
"author_id": 5544,
"author_profile": "https://Stackoverflow.com/users/5544",
"pm_score": 2,
"selected": false,
"text": "<p>Systools (Turbopower, <a href=\"https://sourceforge.net/projects/tpsystools/\" rel=\"nofollow noreferrer\">now open source</a>) has a ReplaceStringAllL function that does all of them in a string.</p>\n"
},
{
"answer_id": 142511,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using Delphi 2009, this operation is about 3 times faster with TStringBuilder than with ReplaceString. It's Unicode safe, too.</p>\n\n<p>I used the text from <a href=\"http://www.CodeGear.com\" rel=\"nofollow noreferrer\">http://www.CodeGear.com</a> with all occurrences of \"<\" and \">\" changed to <code>\"&lt;\"</code> and <code>\"&gt;\"</code> as my starting point.</p>\n\n<p>Including string assignments and creating/freeing objects, these took about 25ms and 75ms respectively on my system:</p>\n\n<pre><code>function TForm1.TestStringBuilder(const aString: string): string;\nvar\n sb: TStringBuilder;\nbegin\n StartTimer;\n sb := TStringBuilder.Create;\n sb.Append(aString);\n sb.Replace('&gt;', '>');\n sb.Replace('&lt;', '<');\n Result := sb.ToString();\n FreeAndNil(sb);\n StopTimer;\nend;\n\nfunction TForm1.TestStringReplace(const aString: string): string;\nbegin\n StartTimer;\n Result := StringReplace(aString,'&gt;','>',[rfReplaceAll]) ;\n Result := StringReplace(Result,'&lt;','<',[rfReplaceAll]) ;\n StopTimer;\nend;\n</code></pre>\n"
},
{
"answer_id": 145594,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": false,
"text": "<p>You should definitely look at the Fastcode project pages: <a href=\"http://fastcode.sourceforge.net/\" rel=\"noreferrer\">http://fastcode.sourceforge.net/</a></p>\n\n<p>They ran a challenge for a faster StringReplace (Ansi StringReplace challenge), and the 'winner' was 14 times faster than the Delphi RTL.</p>\n\n<p>Several of the fastcode functions have been included within Delphi itself in recent versions (D2007 on, I think), so the performance improvement may vary dramatically depending on which Delphi version you are using.</p>\n\n<p>As mentioned before, you should really be looking at a Unicode-based solution if you're serious about processing XML.</p>\n"
},
{
"answer_id": 41981197,
"author": "rkawano",
"author_id": 1293235,
"author_profile": "https://Stackoverflow.com/users/1293235",
"pm_score": 2,
"selected": false,
"text": "<p>When you are dealing with a multiline text files, you can get some performance by processing it line by line. This approach reduced time in about 90% to replaces on >1MB xml file.</p>\n\n<pre><code>procedure ReplaceMultilineString(xml: TStrings);\nvar\n i: Integer;\n line: String;\nbegin\n for i:=0 to xml.Count-1 do\n begin\n line := xml[i];\n line := StringReplace(line, '&gt;', '>', [rfReplaceAll]);\n line := StringReplace(line, '&lt;', '<', [rfReplaceAll]);\n xml[i] := line;\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 52686169,
"author": "dawood karimy",
"author_id": 1647162,
"author_profile": "https://Stackoverflow.com/users/1647162",
"pm_score": 0,
"selected": false,
"text": "<p>it's work like charm so fast trust it</p>\n\n<pre><code> Function NewStringReplace(const S, OldPattern, NewPattern: string; Flags: TReplaceFlags): string;\nvar\n OldPat,Srch: string; // Srch and Oldp can contain uppercase versions of S,OldPattern\n PatLength,NewPatLength,P,i,PatCount,PrevP: Integer;\n c,d: pchar;\nbegin\n PatLength:=Length(OldPattern);\n if PatLength=0 then begin\n Result:=S;\n exit;\n end;\n\n if rfIgnoreCase in Flags then begin\n Srch:=AnsiUpperCase(S);\n OldPat:=AnsiUpperCase(OldPattern);\n end else begin\n Srch:=S;\n OldPat:=OldPattern;\n end;\n\n PatLength:=Length(OldPat);\n if Length(NewPattern)=PatLength then begin\n //Result length will not change\n Result:=S;\n P:=1;\n repeat\n P:=PosEx(OldPat,Srch,P);\n if P>0 then begin\n for i:=1 to PatLength do\n Result[P+i-1]:=NewPattern[i];\n if not (rfReplaceAll in Flags) then exit;\n inc(P,PatLength);\n end;\n until p=0;\n end else begin\n //Different pattern length -> Result length will change\n //To avoid creating a lot of temporary strings, we count how many\n //replacements we're going to make.\n P:=1; PatCount:=0;\n repeat\n P:=PosEx(OldPat,Srch,P);\n if P>0 then begin\n inc(P,PatLength);\n inc(PatCount);\n if not (rfReplaceAll in Flags) then break;\n end;\n until p=0;\n if PatCount=0 then begin\n Result:=S;\n exit;\n end;\n NewPatLength:=Length(NewPattern);\n SetLength(Result,Length(S)+PatCount*(NewPatLength-PatLength));\n P:=1; PrevP:=0;\n c:=pchar(Result); d:=pchar(S);\n repeat\n P:=PosEx(OldPat,Srch,P);\n if P>0 then begin\n for i:=PrevP+1 to P-1 do begin\n c^:=d^;\n inc(c); inc(d);\n end;\n for i:=1 to NewPatLength do begin\n c^:=NewPattern[i];\n inc(c);\n end;\n if not (rfReplaceAll in Flags) then exit;\n inc(P,PatLength);\n inc(d,PatLength);\n PrevP:=P-1;\n end else begin\n for i:=PrevP+1 to Length(S) do begin\n c^:=d^;\n inc(c); inc(d);\n end;\n end;\n until p=0;\n end;\nend;\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
]
| I am using StringReplace to replace > and < by the char itself in a generated XML like this:
```
StringReplace(xml.Text,'>','>',[rfReplaceAll]) ;
StringReplace(xml.Text,'<','<',[rfReplaceAll]) ;
```
The thing is it takes way tooo long to replace every occurence of >.
Do you purpose any better idea to make it faster? | Try [FastStrings.pas](http://www.koders.com/delphi/fidFB386C5C240FD5E72013C882ADD7600FDF60E6C7.aspx?s=socket) from Peter Morris. |
139,835 | <p>I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.</p>
<p>This form uses these styles:</p>
<pre><code>this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );
this.SetStyle( ControlStyles.UserPaint, true );
this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
this.SetStyle( ControlStyles.ResizeRedraw, true );
</code></pre>
<p>And has these non-default property values:</p>
<pre><code>this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
</code></pre>
<p>I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work.</p>
| [
{
"answer_id": 139970,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same properties in my application and Right click doesn't work either, so this is not <em>your problem</em>, it appears to be the way windows forms respond when they have no border.</p>\n\n<p>If you set your border to the normal value, you will be able to have right click in the taskbar and such. </p>\n\n<p>For right click on other controls, you'll need to set the ContextMenuStrip and provide your \"menu\". But I'm not sure if this works when you have it without border. I have been unable to make it work.</p>\n"
},
{
"answer_id": 159897,
"author": "Bill",
"author_id": 14547,
"author_profile": "https://Stackoverflow.com/users/14547",
"pm_score": 4,
"selected": true,
"text": "<p>A borderless window, if I am not mistaken, is flagged such that it offers no system menu, and that it does not appear in the taskbar. </p>\n\n<p>The fact that any given window does not have a border and does not appear in the taskbar is the result of the style flags set on the window. These particular Style flags can be set using the <code>GetWindowLong</code> and <code>SetWindowLong</code> API calls. However you have to be careful as certain styles just don't work together. </p>\n\n<p>I have written a number of custom controls over the years and I am constantly coaxing windows to become something they weren't originally intended to be.<br>\nFor example I have written my own dropdown control where I needed a window to behave as a popup and not to activate.<br>\nThe following code will do that. Note that the code appears in the <code>OnHandleCreated</code> event handler. This is because the flags need to be changed just after the handle is setup which indicates that Windows has already set what it thinks the flags should be.</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\nprotected override void OnHandleCreated(EventArgs e) {\n uint dwWindowProperty;\n\n User32.SetParent(this.Handle, IntPtr.Zero);\n\n dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.EXSTYLE );\n dwWindowProperty = dwWindowProperty | (uint)User32.WSEX.TOOLWINDOW | (uint)User32.WSEX.NOACTIVATE;\n User32.SetWindowLong( this.Handle, User32.GWL.EXSTYLE, dwWindowProperty );\n\n dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.STYLE );\n dwWindowProperty = ( dwWindowProperty & ~(uint)User32.WS.CHILD ) | (uint)User32.WS.POPUP; \n User32.SetWindowLong( this.Handle, User32.GWL.STYLE, dwWindowProperty );\n base.OnHandleCreated (e);\n}\n\n\n//this is a fragment of my User32 library wrapper needed for the previous code segment.\nclass User32 \n{\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n\n [DllImport(\"user32.dll\", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]\n public static extern int SetWindowLong( IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong); \n\n [DllImport(\"user32.dll\", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]\n public static extern uint GetWindowLong( IntPtr hWnd, User32.GWL gwlIndex );\n\n [FlagsAttribute] \n public enum WS: uint { \n POPUP = 0x80000000,\n CHILD = 0x40000000,\n }\n\n public enum GWL {\n STYLE = -16,\n EXSTYLE = -20\n }\n\n [FlagsAttribute]\n public enum WSEX: uint {\n TOP = 0x0,\n TOPMOST = 0x8,\n TOOLWINDOW = 0x80,\n NOACTIVATE = 0x08000000,\n }\n}\n</code></pre>\n\n<p>Unfortunately the <code>SysMenu</code> style cannot be set without using the <code>Caption</code> style, so I can't say if this is a problem in your implementation.</p>\n\n<p>You can check out the original style list and the extend style list at these two links:<br>\n<a href=\"https://learn.microsoft.com/en-us/windows/desktop/winmsg/window-styles\" rel=\"nofollow noreferrer\">Window Styles</a><br>\n<a href=\"https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createwindowexw\" rel=\"nofollow noreferrer\">CreateWindowEx</a></p>\n"
},
{
"answer_id": 450149,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code> protected override void WndProc( ref System.Windows.Forms.Message m )\n { // RightClickMenu\n if ( m.Msg == 0x313 )\n {\n this.contextMenuStrip1.Show(this, this.PointToClient(new Point(m.LParam.ToInt32())));\n }}\n</code></pre>\n\n<p>This detects rightclick on the applications taskbar \"area\"..</p>\n\n<p>maybe it will help ?</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4898/"
]
| I have a C# WinForms borderless window, for which I override WndProc and handle the WM\_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.
This form uses these styles:
```
this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );
this.SetStyle( ControlStyles.UserPaint, true );
this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
this.SetStyle( ControlStyles.ResizeRedraw, true );
```
And has these non-default property values:
```
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
```
I've tried handling WM\_NCRBUTTONDOWN and WM\_NCRBUTTONUP, and send the WM\_GETSYSMENU message, but it didn't work. | A borderless window, if I am not mistaken, is flagged such that it offers no system menu, and that it does not appear in the taskbar.
The fact that any given window does not have a border and does not appear in the taskbar is the result of the style flags set on the window. These particular Style flags can be set using the `GetWindowLong` and `SetWindowLong` API calls. However you have to be careful as certain styles just don't work together.
I have written a number of custom controls over the years and I am constantly coaxing windows to become something they weren't originally intended to be.
For example I have written my own dropdown control where I needed a window to behave as a popup and not to activate.
The following code will do that. Note that the code appears in the `OnHandleCreated` event handler. This is because the flags need to be changed just after the handle is setup which indicates that Windows has already set what it thinks the flags should be.
```
using System.Runtime.InteropServices;
protected override void OnHandleCreated(EventArgs e) {
uint dwWindowProperty;
User32.SetParent(this.Handle, IntPtr.Zero);
dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.EXSTYLE );
dwWindowProperty = dwWindowProperty | (uint)User32.WSEX.TOOLWINDOW | (uint)User32.WSEX.NOACTIVATE;
User32.SetWindowLong( this.Handle, User32.GWL.EXSTYLE, dwWindowProperty );
dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.STYLE );
dwWindowProperty = ( dwWindowProperty & ~(uint)User32.WS.CHILD ) | (uint)User32.WS.POPUP;
User32.SetWindowLong( this.Handle, User32.GWL.STYLE, dwWindowProperty );
base.OnHandleCreated (e);
}
//this is a fragment of my User32 library wrapper needed for the previous code segment.
class User32
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]
public static extern int SetWindowLong( IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong);
[DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]
public static extern uint GetWindowLong( IntPtr hWnd, User32.GWL gwlIndex );
[FlagsAttribute]
public enum WS: uint {
POPUP = 0x80000000,
CHILD = 0x40000000,
}
public enum GWL {
STYLE = -16,
EXSTYLE = -20
}
[FlagsAttribute]
public enum WSEX: uint {
TOP = 0x0,
TOPMOST = 0x8,
TOOLWINDOW = 0x80,
NOACTIVATE = 0x08000000,
}
}
```
Unfortunately the `SysMenu` style cannot be set without using the `Caption` style, so I can't say if this is a problem in your implementation.
You can check out the original style list and the extend style list at these two links:
[Window Styles](https://learn.microsoft.com/en-us/windows/desktop/winmsg/window-styles)
[CreateWindowEx](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createwindowexw) |
139,859 | <p>On <strong>Linux/NPTL</strong>, threads are created as some kind of process.</p>
<p>I can see some of my process have a weird cmdline:</p>
<pre><code>cat /proc/5590/cmdline
hald-addon-storage: polling /dev/scd0 (every 2 sec)
</code></pre>
<p>Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging.</p>
<p><em>/me now investigating in HAL source</em></p>
| [
{
"answer_id": 139935,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p><code>argv</code> points to writable strings. Just write stuff to them:</p>\n\n<pre><code>#include <string.h>\n#include <unistd.h>\n\nint\nmain(int argc, char** argv)\n{\n strcpy(argv[0], \"Hello, world!\");\n sleep(10);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 139963,
"author": "elmarco",
"author_id": 1277510,
"author_profile": "https://Stackoverflow.com/users/1277510",
"pm_score": 0,
"selected": false,
"text": "<p>Bah.. the code is not that nice, the trick is to reuse the environ (here argv_buffer) pointer:</p>\n\n<pre><code>memset (argv_buffer[0] + len, 0, argv_size - len);\nargv_buffer[1] = NULL;\n</code></pre>\n\n<p>Any better idea?</p>\n\n<p>Is that working for different threads?</p>\n"
},
{
"answer_id": 140001,
"author": "miguel.de.icaza",
"author_id": 16929,
"author_profile": "https://Stackoverflow.com/users/16929",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to do this in a portable way, something that will work across multiple Unix variations, there are very few options available.</p>\n\n<p>What you have to do is that your caller process must call exec with the <code>argv [0]</code> argument pointing to the name that you would like to see in the process output, and the filename pointing to the actual executable.</p>\n\n<p>You can try this behavior from the shell by using:</p>\n\n<pre><code>exec -a \"This is my cute name\" bash\n</code></pre>\n\n<p>That will replace the current bash process with one named <code>\"This is my cute name\"</code>.</p>\n\n<p>For doing this in C, you can look at the source code of <code>sendmail</code> or any other piece of software that has been ported extensively and find all the variations that are needed across operating systems to support this.</p>\n\n<p>Some operating systems have a <code>setproctitle(3)</code> API, some others allow you to override the contents of <code>argv [0]</code> and show that result.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277510/"
]
| On **Linux/NPTL**, threads are created as some kind of process.
I can see some of my process have a weird cmdline:
```
cat /proc/5590/cmdline
hald-addon-storage: polling /dev/scd0 (every 2 sec)
```
Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging.
*/me now investigating in HAL source* | If you want to do this in a portable way, something that will work across multiple Unix variations, there are very few options available.
What you have to do is that your caller process must call exec with the `argv [0]` argument pointing to the name that you would like to see in the process output, and the filename pointing to the actual executable.
You can try this behavior from the shell by using:
```
exec -a "This is my cute name" bash
```
That will replace the current bash process with one named `"This is my cute name"`.
For doing this in C, you can look at the source code of `sendmail` or any other piece of software that has been ported extensively and find all the variations that are needed across operating systems to support this.
Some operating systems have a `setproctitle(3)` API, some others allow you to override the contents of `argv [0]` and show that result. |
139,867 | <p>Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.</p>
| [
{
"answer_id": 140235,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 6,
"selected": false,
"text": "<p>This code gets 242 countries in Sun Java 6:</p>\n\n<pre><code>String[] countryCodes = Locale.getISOCountries();\n</code></pre>\n\n<p>Though <a href=\"http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm\" rel=\"noreferrer\">the ISO website</a> claims there are 249 <em>ISO 3166-1-alpha-2 code elements</em>, though the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Locale.html\" rel=\"noreferrer\">javadoc</a> links to the same information.</p>\n"
},
{
"answer_id": 2298525,
"author": "Christophe Desguez",
"author_id": 277209,
"author_profile": "https://Stackoverflow.com/users/277209",
"pm_score": 2,
"selected": false,
"text": "<p>There is an easy way to generate this enum with the language name.\nExecute this code to generate the list of enum fields to paste :</p>\n\n<pre><code> /**\n * This is the code used to generate the enum content\n */\n public static void main(String[] args) {\n String[] codes = java.util.Locale.getISOLanguages();\n for (String isoCode: codes) {\n Locale locale = new Locale(isoCode);\n System.out.println(isoCode.toUpperCase() + \"(\\\"\" + locale.getDisplayLanguage(locale) + \"\\\"),\");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 3782185,
"author": "Bozho",
"author_id": 203907,
"author_profile": "https://Stackoverflow.com/users/203907",
"pm_score": 4,
"selected": false,
"text": "<p>Here's how I generated an enum with country code + country name:</p>\n\n<pre><code>package countryenum;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\n\npublic class CountryEnumGenerator {\n public static void main(String[] args) {\n String[] countryCodes = Locale.getISOCountries();\n List<Country> list = new ArrayList<Country>(countryCodes.length);\n\n for (String cc : countryCodes) {\n list.add(new Country(cc.toUpperCase(), new Locale(\"\", cc).getDisplayCountry()));\n }\n\n Collections.sort(list);\n\n for (Country c : list) {\n System.out.println(\"/**\" + c.getName() + \"*/\");\n System.out.println(c.getCode() + \"(\\\"\" + c.getName() + \"\\\"),\");\n }\n\n }\n}\n\nclass Country implements Comparable<Country> {\n private String code;\n private String name;\n\n public Country(String code, String name) {\n super();\n this.code = code;\n this.name = name;\n }\n\n public String getCode() {\n return code;\n }\n\n\n public void setCode(String code) {\n this.code = code;\n }\n\n\n public String getName() {\n return name;\n }\n\n\n public void setName(String name) {\n this.name = name;\n }\n\n\n @Override\n public int compareTo(Country o) {\n return this.name.compareTo(o.name);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8264635,
"author": "bruno.braga",
"author_id": 1015901,
"author_profile": "https://Stackoverflow.com/users/1015901",
"pm_score": 0,
"selected": false,
"text": "<p>This still does not answer the question. I was also looking for a kind of enumerator for this, and did not find anything. Some examples using hashtable here, but represent the same as the built-in get</p>\n\n<p>I would go for a different approach. So I created a script in python to automatically generate the list in Java:</p>\n\n<pre><code>#!/usr/bin/python\nf = open(\"data.txt\", 'r')\ndata = []\ncc = {}\n\nfor l in f:\n t = l.split('\\t')\n cc = { 'code': str(t[0]).strip(), \n 'name': str(t[1]).strip()\n }\n data.append(cc)\nf.close()\n\nfor c in data:\n print \"\"\"\n/**\n * Defines the <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">ISO_3166-1_alpha-2</a> \n * for <b><i>%(name)s</i></b>.\n * <p>\n * This constant holds the value of <b>{@value}</b>.\n *\n * @since 1.0\n *\n */\n public static final String %(code)s = \\\"%(code)s\\\";\"\"\" % c\n</code></pre>\n\n<p>where the data.txt file is a simple copy&paste from Wikipedia table (just remove all extra lines, making sure you have a country code and country name per line).</p>\n\n<p>Then just place this into your static class:</p>\n\n<pre><code>/**\n * Holds <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">ISO_3166-1_alpha-2</a>\n * constant values for all countries. \n * \n * @since 1.0\n * \n * </p>\n */\npublic class CountryCode {\n\n /**\n * Constructor defined as <code>private</code> purposefully to ensure this \n * class is only used to access its static properties and/or methods. \n */\n private CountryCode() { }\n\n /**\n * Defines the <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">ISO_3166-1_alpha-2</a> \n * for <b><i>Andorra</i></b>.\n * <p>\n * This constant holds the value of <b>{@value}</b>.\n *\n * @since 1.0\n *\n */\n public static final String AD = \"AD\";\n\n //\n // and the list goes on! ...\n //\n}\n</code></pre>\n"
},
{
"answer_id": 11084479,
"author": "Takahiko Kawasaki",
"author_id": 1174054,
"author_profile": "https://Stackoverflow.com/users/1174054",
"pm_score": 7,
"selected": false,
"text": "<p>Now an implementation of country code (<a href=\"http://en.wikipedia.org/wiki/ISO_3166-1\" rel=\"nofollow noreferrer\">ISO 3166-1</a> <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\" rel=\"nofollow noreferrer\">alpha-2</a>/<a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3\" rel=\"nofollow noreferrer\">alpha-3</a>/<a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_numeric\" rel=\"nofollow noreferrer\">numeric</a>) list as Java enum is available at GitHub under Apache License version 2.0.</p>\n<p><strong>Example:</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>CountryCode cc = CountryCode.getByCode("JP");\n\nSystem.out.println("Country name = " + cc.getName()); // "Japan"\nSystem.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2()); // "JP"\nSystem.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3()); // "JPN"\nSystem.out.println("ISO 3166-1 numeric code = " + cc.getNumeric()); // 392\n</code></pre>\n<hr />\n<p><strong>Last Edit</strong> 2016-Jun-09</p>\n<p>CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode (<a href=\"http://en.wikipedia.org/wiki/ISO_639-1\" rel=\"nofollow noreferrer\">ISO 639-1</a>), LanguageAlpha3Code (<a href=\"http://en.wikipedia.org/wiki/ISO_639-2\" rel=\"nofollow noreferrer\">ISO 639-2</a>), LocaleCode, ScriptCode (<a href=\"http://en.wikipedia.org/wiki/ISO_15924\" rel=\"nofollow noreferrer\">ISO 15924</a>) and CurrencyCode (<a href=\"http://en.wikipedia.org/wiki/ISO_4217\" rel=\"nofollow noreferrer\">ISO 4217</a>) and registered into the Maven Central Repository.</p>\n<p><strong>Maven</strong></p>\n<pre class=\"lang-xml prettyprint-override\"><code><dependency>\n <groupId>com.neovisionaries</groupId>\n <artifactId>nv-i18n</artifactId>\n <version>1.29</version>\n</dependency>\n</code></pre>\n<p><strong>Gradle</strong></p>\n<pre><code>dependencies {\n compile 'com.neovisionaries:nv-i18n:1.29'\n}\n</code></pre>\n<p><strong>GitHub</strong></p>\n<p><a href=\"https://github.com/TakahikoKawasaki/nv-i18n\" rel=\"nofollow noreferrer\">https://github.com/TakahikoKawasaki/nv-i18n</a></p>\n<p><strong>Javadoc</strong></p>\n<p><a href=\"https://takahikokawasaki.github.io/nv-i18n/\" rel=\"nofollow noreferrer\">https://takahikokawasaki.github.io/nv-i18n/</a></p>\n<p><strong>OSGi</strong></p>\n<pre><code>Bundle-SymbolicName: com.neovisionaries.i18n\nExport-Package: com.neovisionaries.i18n;version="1.28.0"\n</code></pre>\n"
},
{
"answer_id": 19242155,
"author": "george_h",
"author_id": 1387501,
"author_profile": "https://Stackoverflow.com/users/1387501",
"pm_score": 0,
"selected": false,
"text": "<p>I didn't know about this question till I had just recently open-sourced my Java enum for exactly this purpose! Amazing coincidence!</p>\n\n<p>I put the whole source code on my blog with BSD caluse 3 license so I don't think anyone would have any beefs about it.</p>\n\n<p>Can be found here.\n<a href=\"https://subversivebytes.wordpress.com/2013/10/07/java-iso-3166-java-enum/\" rel=\"nofollow\">https://subversivebytes.wordpress.com/2013/10/07/java-iso-3166-java-enum/</a></p>\n\n<p>Hope it is useful and eases development pains.</p>\n"
},
{
"answer_id": 19428277,
"author": "sskular",
"author_id": 1158832,
"author_profile": "https://Stackoverflow.com/users/1158832",
"pm_score": 3,
"selected": false,
"text": "<p>If you are already going to rely on Java locale, then I suggest using a simple HashMap instead of creating new classes for countries etc.</p>\n\n<p>Here's how I would use it if I were to rely on the Java Localization only:</p>\n\n<pre><code>private HashMap<String, String> countries = new HashMap<String, String>();\nString[] countryCodes = Locale.getISOCountries();\n\nfor (String cc : countryCodes) {\n // country name , country code map\n countries.put(new Locale(\"\", cc).getDisplayCountry(), cc.toUpperCase());\n}\n</code></pre>\n\n<p>After you fill the map, you can get the ISO code from the country name whenever you need it.\nOr you can make it a ISO code to Country name map as well, just modify the 'put' method accordingly.</p>\n"
},
{
"answer_id": 25677643,
"author": "Ben Dowling",
"author_id": 36191,
"author_profile": "https://Stackoverflow.com/users/36191",
"pm_score": 1,
"selected": false,
"text": "<p>Not a java enum, but a JSON version of this is available at <a href=\"http://country.io/names.json\" rel=\"nofollow\">http://country.io/names.json</a></p>\n"
},
{
"answer_id": 33394455,
"author": "abdielou",
"author_id": 3984100,
"author_profile": "https://Stackoverflow.com/users/3984100",
"pm_score": 2,
"selected": false,
"text": "<p>If anyone is already using the Amazon AWS SDK it includes <code>com.amazonaws.services.route53domains.model.CountryCode</code>. I know this is not ideal but it's an alternative if you already use the AWS SDK. For most cases I would use Takahiko's <code>nv-i18n</code> since, as he mentions, it implements ISO 3166-1.</p>\n"
},
{
"answer_id": 46319693,
"author": "Hervian",
"author_id": 6095334,
"author_profile": "https://Stackoverflow.com/users/6095334",
"pm_score": 0,
"selected": false,
"text": "<p>I have created an enum, which you address by the english country name. See <a href=\"https://github.com/Hervian/country-util\" rel=\"nofollow noreferrer\">country-util</a>.<br>\nOn each enum you can call <code>getLocale()</code> to get the Java Locale. </p>\n\n<p>From the Locale you can get all the information you are used to, fx the ISO-3166-1 two letter country code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum Country{\n\n ANDORRA(new Locale(\"AD\")),\n AFGHANISTAN(new Locale(\"AF\")),\n ANTIGUA_AND_BARBUDA(new Locale(\"AG\")),\n ANGUILLA(new Locale(\"AI\")),\n //etc\n ZAMBIA(new Locale(\"ZM\")),\n ZIMBABWE(new Locale(\"ZW\"));\n\n private Locale locale;\n\n private Country(Locale locale){\n this.locale = locale;\n }\n\n public Locale getLocale(){\n return locale;\n }\n</code></pre>\n\n<p>Pro: </p>\n\n<ul>\n<li>Light weight</li>\n<li>Maps to Java Locales</li>\n<li>Addressable by full country name </li>\n<li>Enum values are not hardcoded, but generated by a call to Locale.getISOCountries(). That is: Simply recompile the project against the newest java version to get any changes made to the list of countries reflected in the enum.</li>\n</ul>\n\n<p>Con: </p>\n\n<ul>\n<li>Not in Maven repository</li>\n<li>Most likely simpler / less expressive than the other solutions, which I don't know.</li>\n<li>Created for my own needs / not as such maintained. - You should probably clone the repo.</li>\n</ul>\n"
},
{
"answer_id": 60513422,
"author": "Noel Yap",
"author_id": 807037,
"author_profile": "https://Stackoverflow.com/users/807037",
"pm_score": 1,
"selected": false,
"text": "<p>AWS Java SDK has <a href=\"https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/route53domains/model/CountryCode.html\" rel=\"nofollow noreferrer\">CountryCode</a>.</p>\n"
},
{
"answer_id": 71560055,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 0,
"selected": false,
"text": "<p>There is standard <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.IsoCountryCode.html\" rel=\"nofollow noreferrer\"><code>java.util.Locale.IsoCountryCode</code></a> since Java 9.</p>\n"
},
{
"answer_id": 72963576,
"author": "ADJ",
"author_id": 870834,
"author_profile": "https://Stackoverflow.com/users/870834",
"pm_score": 0,
"selected": false,
"text": "<p>I found the IsoCountry list <a href=\"http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/LocaleISOData.java#l226\" rel=\"nofollow noreferrer\">here</a>, it has 2 and 3 char country codes</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12531/"
]
| Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time. | Now an implementation of country code ([ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) [alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)/[alpha-3](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3)/[numeric](http://en.wikipedia.org/wiki/ISO_3166-1_numeric)) list as Java enum is available at GitHub under Apache License version 2.0.
**Example:**
```java
CountryCode cc = CountryCode.getByCode("JP");
System.out.println("Country name = " + cc.getName()); // "Japan"
System.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2()); // "JP"
System.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3()); // "JPN"
System.out.println("ISO 3166-1 numeric code = " + cc.getNumeric()); // 392
```
---
**Last Edit** 2016-Jun-09
CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode ([ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1)), LanguageAlpha3Code ([ISO 639-2](http://en.wikipedia.org/wiki/ISO_639-2)), LocaleCode, ScriptCode ([ISO 15924](http://en.wikipedia.org/wiki/ISO_15924)) and CurrencyCode ([ISO 4217](http://en.wikipedia.org/wiki/ISO_4217)) and registered into the Maven Central Repository.
**Maven**
```xml
<dependency>
<groupId>com.neovisionaries</groupId>
<artifactId>nv-i18n</artifactId>
<version>1.29</version>
</dependency>
```
**Gradle**
```
dependencies {
compile 'com.neovisionaries:nv-i18n:1.29'
}
```
**GitHub**
<https://github.com/TakahikoKawasaki/nv-i18n>
**Javadoc**
<https://takahikokawasaki.github.io/nv-i18n/>
**OSGi**
```
Bundle-SymbolicName: com.neovisionaries.i18n
Export-Package: com.neovisionaries.i18n;version="1.28.0"
``` |
139,889 | <p>I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with <a href="http://httpd.apache.org/docs/2.0/mod/core.html#serveralias" rel="noreferrer">ServerAlias</a>) or do I <a href="http://httpd.apache.org/docs/2.0/mod/mod_alias.html#redirect" rel="noreferrer">Redirect</a> the request? </p>
<p>Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used?</p>
<p>Common vhost examples will have:</p>
<pre><code>ServerName example.net
ServerAlias www.example.net
</code></pre>
<p>Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site?</p>
<p>UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load.</p>
<p>UPDATE and ANSWER: Thanks Paul for finding the <a href="http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html" rel="noreferrer">Google link</a> which instructs us to "help your fellow webmasters by <strong>not</strong> perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&brand=riedell or www.example.com/skates.asp?brand=riedell&color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."</p>
| [
{
"answer_id": 139911,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 6,
"selected": true,
"text": "<p>Redirecting is better, then there is always one, canonical domain for your content. <strike>I hear Google penalises multiple domains hosting the same content, but I can't find a source for that at the moment (edit, <a href=\"http://www.searchenginejournal.com/duplicate-content-penalty-how-to-lose-google-ranking-fast/1886/\" rel=\"noreferrer\">here's one article</a>, but from 2005, which is ancient history in Internet years!)</strike> <em>(not correct, see edit below)</em></p>\n\n<p>Here's some mod-rewrite rules to redirect to a canonical domain:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} !^www\\.foobar\\.com [NC]\nRewriteCond %{HTTP_HOST} !^$\nRewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent]\n</code></pre>\n\n<p>That checks that the host isn't the canonical domain (www.foobar.com) and checks that a domain has actually been specified, before deciding to redirect the request to the canonical domain.</p>\n\n<p><strong>Further Edit</strong>: <a href=\"http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html\" rel=\"noreferrer\">Here's an article straight from the horses mouth</a> - seems it's not as big an issue as you might think. Please read this article CAREFULLY as it distinguishes between duplicate content on the same site (as in \"www.example.com/skates.asp?color=black&brand=riedell and www.example.com/skates.asp?brand=riedell&color=black\") and specifically says \"Don't create multiple pages, subdomains, or domains with substantially duplicate content.\"</p>\n"
},
{
"answer_id": 139957,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 0,
"selected": false,
"text": "<p>Nowadays I doubt it matters. If you see both entries in google, then you know you're doing it wrong.</p>\n"
},
{
"answer_id": 140007,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>If half the links to your site refer to one URL and half refer to another, each URL is only going to get half the pagerank. Even if Google doesn't penalize your rank for having duplicate content, you're going to suffer.</p>\n"
},
{
"answer_id": 140008,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 1,
"selected": false,
"text": "<p>Server aliasing can cause problems with CGI session continuity: since cookies are attached to the domain they were served from, CGI scripts have to be carefully written so that they are aware of the aliasing, or all links within and into the site have to be relative, or both - it is much harder to avoid niggly little hard-to-debug problems due to the browser serving you different cookies based on whether the user last entered your site through name.tld or www.name.tld.</p>\n"
},
{
"answer_id": 140011,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 2,
"selected": false,
"text": "<p>If they are entirely different domain names, you will want to redirect because otherwise cookies can not be shared between the two. If a user logs into your website at example1.com, they will need to log in again if they visit example2.com.</p>\n\n<p>If they are just different subdomains (example.com vs www.example.com) this won't matter.</p>\n"
},
{
"answer_id": 140200,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<p>SSL certificates can also be an issue (wild card certs mitigate this but are more expensive).</p>\n\n<p>So if the cert is only bound to www.example.com, it won't validate for example.com. If this circumstance applies to your case, then carefully handling, redirects and hyperlink references in your html and javascript is very important.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15948/"
]
| I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with [ServerAlias](http://httpd.apache.org/docs/2.0/mod/core.html#serveralias)) or do I [Redirect](http://httpd.apache.org/docs/2.0/mod/mod_alias.html#redirect) the request?
Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used?
Common vhost examples will have:
```
ServerName example.net
ServerAlias www.example.net
```
Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site?
UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load.
UPDATE and ANSWER: Thanks Paul for finding the [Google link](http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html) which instructs us to "help your fellow webmasters by **not** perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&brand=riedell or www.example.com/skates.asp?brand=riedell&color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content." | Redirecting is better, then there is always one, canonical domain for your content. I hear Google penalises multiple domains hosting the same content, but I can't find a source for that at the moment (edit, [here's one article](http://www.searchenginejournal.com/duplicate-content-penalty-how-to-lose-google-ranking-fast/1886/), but from 2005, which is ancient history in Internet years!) *(not correct, see edit below)*
Here's some mod-rewrite rules to redirect to a canonical domain:
```
RewriteCond %{HTTP_HOST} !^www\.foobar\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent]
```
That checks that the host isn't the canonical domain (www.foobar.com) and checks that a domain has actually been specified, before deciding to redirect the request to the canonical domain.
**Further Edit**: [Here's an article straight from the horses mouth](http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html) - seems it's not as big an issue as you might think. Please read this article CAREFULLY as it distinguishes between duplicate content on the same site (as in "www.example.com/skates.asp?color=black&brand=riedell and www.example.com/skates.asp?brand=riedell&color=black") and specifically says "Don't create multiple pages, subdomains, or domains with substantially duplicate content." |
139,909 | <p>I have a problem with setting the TTL on my Datagram packets. I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0</p>
| [
{
"answer_id": 139917,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 4,
"selected": true,
"text": "<p>Basically you have to set an special system property telling the JVM to use an IPv4 stack:</p>\n\n<pre><code>-Djava.net.preferIPv4Stack=true\n</code></pre>\n"
},
{
"answer_id": 20336403,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 0,
"selected": false,
"text": "<p>To implement pfranza's fix in Oracle, where you don't have a command line:</p>\n\n<p>Set the property <code>java.net.preferIPv4Stack=true</code> in each Oracle session as follows before calling the java code containing the multicast call with the following PL/SQL snippet:</p>\n\n<pre><code>ret := dbms_java.set_property('java.net.preferIPv4Stack','true');\n</code></pre>\n\n<p>If the call is successful it will return NULL.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a problem with setting the TTL on my Datagram packets. I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0 | Basically you have to set an special system property telling the JVM to use an IPv4 stack:
```
-Djava.net.preferIPv4Stack=true
``` |
139,948 | <p>I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed.</p>
<p>How can this be accomplished? Ive included a sample of my current code below.</p>
<p>sample.aspx</p>
<pre><code><asp:textbox id=foo runat=server />
<asp:requiredfieldvalidator id=val runat=server controltovalidate=foo />
<asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') />
</code></pre>
<p>sample.aspx.vb</p>
<pre><code>Sub Page_Load()
If Page.IsPostback() Then
Page.Validate()
If Page.IsValid Then
'process page here'
End If
End If
End Sub
</code></pre>
<p>Thanks for any help.</p>
| [
{
"answer_id": 139977,
"author": "Dean",
"author_id": 11802,
"author_profile": "https://Stackoverflow.com/users/11802",
"pm_score": 1,
"selected": false,
"text": "<p>can you not use the EnableClientScript property for the validator control allowing you to carry out the validation on the client side on your submit the validation will then fire?? </p>\n"
},
{
"answer_id": 140072,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 1,
"selected": false,
"text": "<p>The thing is that the Return Confirm fires prior to the validator's javascript. which all has to do with lifecycles and stuff.</p>\n\n<p>If you're wanting to definitely have that behavior, what you'll need to do is change all of your validators to custom validators, roll out your own JS validation routines for the custom validators, and then call the confirm at the end of the validation routine as the final call.</p>\n\n<p>if <strong><em>MAY</em></strong> change the sequence of firing, if you add the JS for the return confirm coding to the button in a HIJAX method where it's assigned to the onClick event after the page has been loaded fully into the browser--but I've never utilized that methodology for that capability, so don't quote me there.</p>\n"
},
{
"answer_id": 140101,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>The Validators are fired by a onsubmit handler on the form.</p>\n\n<p>if your override form.onsubmit you'll lose the validator firing, though you may be able to manually provide the JS needed.</p>\n"
},
{
"answer_id": 140207,
"author": "Mcbeev",
"author_id": 12762,
"author_profile": "https://Stackoverflow.com/users/12762",
"pm_score": 1,
"selected": false,
"text": "<p>What about using the ASP.NET Control Toolkit's ValidatorCallout control? From: <a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ValidatorCallout/ValidatorCallout.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ValidatorCallout/ValidatorCallout.aspx</a></p>\n\n<p>ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an input field and a validator control as you normally would. Then add the ValidatorCallout and set its TargetControlID property to reference the validator control. </p>\n\n<p>I haven't used this one, but it seems to me that it would get you the client side validation that you want.</p>\n"
},
{
"answer_id": 490584,
"author": "cofiem",
"author_id": 31567,
"author_profile": "https://Stackoverflow.com/users/31567",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to be a very common problem.</p>\n\n<p>The workaround:</p>\n\n<p>Validate the page first, then call <code>confirm</code>, as shown <a href=\"http://www.codedigest.com/CodeDigest/73-Fire-Validator-Controls-Before-JavaScript-Confirm-Box-Fires-in-ASP-Net-Page.aspx\" rel=\"noreferrer\">here</a> and <a href=\"http://www.stevekinsey.com/2007/06/04/onclientclick-and-form-validation-controls/\" rel=\"noreferrer\">here</a>.\nThis does have the drawback of calling the validation twice - once in your code, and once in the generated code in the submit <code>onclick</code>.</p>\n\n<p>How to make this work properly, i.e. Validate the page first (and only once), then show the <code>confirm</code> box, I do not yet know.</p>\n\n<p>Edit: <a href=\"http://www.dotnetjohn.com/articles.aspx?articleid=39\" rel=\"noreferrer\">Here</a>'s a useful suggestion:</p>\n\n<blockquote>\n <p>What ASP.NET does behind the scenes\n when validation controls exist, is add\n an autogenerated onClick event for\n each button. This OnClick event would\n supercede the custom OnClick event. So to\n overcome this I did the following:</p>\n \n <ol>\n <li>add CausesValidation = False </li>\n <li>added Validate() and IsValid code to the onClick event\n behind the page to simulate the now\n missing autogenerated validation code\n behind the button.</li>\n </ol>\n</blockquote>\n\n<p>Edit 2: A complete example</p>\n\n<pre><code><asp:Button ID=\"btnSubmit\" runat=\"server\" Text=\"Submit\" OnClientClick=\"if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}\" CausesValidation=\"false\" />\n</code></pre>\n"
},
{
"answer_id": 10314013,
"author": "Aniruddha Ghosh",
"author_id": 1355916,
"author_profile": "https://Stackoverflow.com/users/1355916",
"pm_score": 0,
"selected": false,
"text": "<p>You should validate the page on the client itself.</p>\n\n<pre><code>function validate()\n{\n Page_ClientValidate();\n if (Page_IsValid)\n // do your processing here\n\n return Page_IsValid;\n}\n</code></pre>\n\n<p>This method can be called on the \"onClientClick\" event of the button and in the code-behind, you can if the page is valid and do the processing if the client-side validation is successful.</p>\n\n<p>So, on the click event of the button, you can do - </p>\n\n<pre><code>protected void SubmitButton_Click(object sender, EventArgs e) \n{ \n if (!this.isValid)\n return;\n\n // do the processing here\n}\n</code></pre>\n"
},
{
"answer_id": 17341235,
"author": "Raghubir Singh",
"author_id": 1049297,
"author_profile": "https://Stackoverflow.com/users/1049297",
"pm_score": 2,
"selected": false,
"text": "<h2>Confirm box in code behind after validation check</h2>\n\n<pre><code> <asp:Button ID=\"btnSave\" runat=\"server\" OnClientClick=\"javascript:return ConfirmSubmit()\" OnClick=\"btnSave_Click\" Text=\"Save\" /> \n\n\n//---javascript -----\nfunction ConfirmSubmit()\n{\n Page_ClientValidate();\n if(Page_IsValid) {\n return confirm('Are you sure?');\n }\n return Page_IsValid;\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed.
How can this be accomplished? Ive included a sample of my current code below.
sample.aspx
```
<asp:textbox id=foo runat=server />
<asp:requiredfieldvalidator id=val runat=server controltovalidate=foo />
<asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') />
```
sample.aspx.vb
```
Sub Page_Load()
If Page.IsPostback() Then
Page.Validate()
If Page.IsValid Then
'process page here'
End If
End If
End Sub
```
Thanks for any help. | This seems to be a very common problem.
The workaround:
Validate the page first, then call `confirm`, as shown [here](http://www.codedigest.com/CodeDigest/73-Fire-Validator-Controls-Before-JavaScript-Confirm-Box-Fires-in-ASP-Net-Page.aspx) and [here](http://www.stevekinsey.com/2007/06/04/onclientclick-and-form-validation-controls/).
This does have the drawback of calling the validation twice - once in your code, and once in the generated code in the submit `onclick`.
How to make this work properly, i.e. Validate the page first (and only once), then show the `confirm` box, I do not yet know.
Edit: [Here](http://www.dotnetjohn.com/articles.aspx?articleid=39)'s a useful suggestion:
>
> What ASP.NET does behind the scenes
> when validation controls exist, is add
> an autogenerated onClick event for
> each button. This OnClick event would
> supercede the custom OnClick event. So to
> overcome this I did the following:
>
>
> 1. add CausesValidation = False
> 2. added Validate() and IsValid code to the onClick event
> behind the page to simulate the now
> missing autogenerated validation code
> behind the button.
>
>
>
Edit 2: A complete example
```
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}" CausesValidation="false" />
``` |
139,954 | <p>I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.</p>
<p>Basically, i have an URL like /products.aspx?categoryid=foo&productid=bar</p>
<p>Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.</p>
<p>But i need to map it to /products/foo/bar. (without "category")</p>
<p>Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)</p>
<p>P.S. Sorry for my bad English.</p>
| [
{
"answer_id": 139986,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 4,
"selected": true,
"text": "<p><em>(your English is just fine, no need to apologize!)</em></p>\n\n<p>You can define a route like this:</p>\n\n<pre><code>routes.MapRoute(\"productsByCategory\", \"products/{category}/{productid}\",\n new { controller=\"products\", action=\"findByCategory\" })\n</code></pre>\n\n<p>This will match</p>\n\n<p><code>products/foo/bar</code> and call an action looking like this:</p>\n\n<pre><code>public class ProductsController : Controller\n{\n ...\n\n public ActionResult FindByCategory(string category, string productid)\n {\n ....\n }\n}\n</code></pre>\n\n<p>does this help?</p>\n"
},
{
"answer_id": 140783,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 0,
"selected": false,
"text": "<p>You also might consider making a Controller to test out your custom routes...</p>\n\n<p>Check out <a href=\"http://weblogs.asp.net/stephenwalther/archive/2008/08/03/asp-net-mvc-tip-29-build-a-controller-to-debug-your-custom-routes.aspx\" rel=\"nofollow noreferrer\">Stephen Walther's blog entry</a> about it.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19610/"
]
| I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.
Basically, i have an URL like /products.aspx?categoryid=foo&productid=bar
Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.
But i need to map it to /products/foo/bar. (without "category")
Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)
P.S. Sorry for my bad English. | *(your English is just fine, no need to apologize!)*
You can define a route like this:
```
routes.MapRoute("productsByCategory", "products/{category}/{productid}",
new { controller="products", action="findByCategory" })
```
This will match
`products/foo/bar` and call an action looking like this:
```
public class ProductsController : Controller
{
...
public ActionResult FindByCategory(string category, string productid)
{
....
}
}
```
does this help? |
139,979 | <p>I have a C# interface with certain method parameters declared as <code>object</code> types. However, the actual type passed around can differ depending on the class implementing the interface:</p>
<pre><code>public interface IMyInterface
{
void MyMethod(object arg);
}
public class MyClass1 : IMyInterface
{
public void MyMethod(object arg)
{
MyObject obj = (MyObject) arg;
// do something with obj...
}
}
public class MyClass2 : IMyInterface
{
public void MyMethod(object arg)
{
byte[] obj = (byte[]) arg;
// do something with obj...
}
}
</code></pre>
<p>The problem with MyClass2 is that the conversion of <code>byte[]</code> to and from <code>object</code> is <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx" rel="noreferrer">boxing and unboxing</a>, which are computationally expensive operations affecting performance.</p>
<p>Would solving this problem with a <a href="http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx" rel="noreferrer">generic interface</a> avoid boxing/unboxing?</p>
<pre><code>public interface IMyInterface<T>
{
void MyMethod(T arg);
}
public class MyClass1 : IMyInterface<MyObject>
{
public void MyMethod(MyObject arg)
{
// typecast no longer necessary
//MyObject obj = (MyObject) arg;
// do something with arg...
}
}
public class MyClass2 : IMyInterface<byte[]>
{
public void MyMethod(byte[] arg)
{
// typecast no longer necessary
//byte[] obj = (byte[]) arg;
// do something with arg...
}
}
</code></pre>
<p>How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?</p>
<p>Thank you!</p>
| [
{
"answer_id": 139994,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>The problem with MyClass2 is that the\n conversion of byte[] to and from\n object is boxing and unboxing, which\n are computationally expensive\n operations affecting performance.</p>\n</blockquote>\n\n<p>There is no boxing involved with array types, even one with value type elements. An array is a reference type.</p>\n\n<p>The overhead on (byte[]) arg is minimal at best.</p>\n"
},
{
"answer_id": 139995,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I can't speak to Mono, but using a generic interface <em>should</em> solve the boxing/unboxing issue in the MS runtime.</p>\n"
},
{
"answer_id": 139999,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type. </p>\n\n<p>This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient.</p>\n"
},
{
"answer_id": 140018,
"author": "miguel.de.icaza",
"author_id": 16929,
"author_profile": "https://Stackoverflow.com/users/16929",
"pm_score": 4,
"selected": false,
"text": "<p>You will get the same benefits in Mono that you do in .NET.</p>\n\n<p>We strongly recommend that you use Mono 1.9 or Mono 2.0 RCx in general, as generics support only matured with 1.9.</p>\n"
},
{
"answer_id": 140264,
"author": "Phil Bennett",
"author_id": 2995,
"author_profile": "https://Stackoverflow.com/users/2995",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, in .Net (MS not sure about mono) generics are implemented at compile time so there is no boxing or unboxing going on at all. Contrast to java generics which are syntactic sugar that just perform the casts for you in the background (at least it was this way once). The main problem with generics is you can't treat generic containers polymorphically, but that is a bit off your topic :-)</p>\n"
},
{
"answer_id": 176441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Given you're using a recent version of mono, 2.0 if you can.</p>\n\n<p>Generic interface performance on Mono is very good, on pair with regular interface dispatch.</p>\n\n<p>Dispatch of generic virtual methods[1] is terrible on all released versions of mono, it has improved in 1.9 thou.</p>\n\n<p>The problem is not that bad as the performance issue with generic virtual methods has been fixed for the next release of mono (2.2), which is scheduled to the end of this year.</p>\n\n<p>[1] A generic virtual method is something like:</p>\n\n<p>public interface Foo {</p>\n\n<pre><code> void Bla<T> (T a, T b);\n</code></pre>\n\n<p>}</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2576/"
]
| I have a C# interface with certain method parameters declared as `object` types. However, the actual type passed around can differ depending on the class implementing the interface:
```
public interface IMyInterface
{
void MyMethod(object arg);
}
public class MyClass1 : IMyInterface
{
public void MyMethod(object arg)
{
MyObject obj = (MyObject) arg;
// do something with obj...
}
}
public class MyClass2 : IMyInterface
{
public void MyMethod(object arg)
{
byte[] obj = (byte[]) arg;
// do something with obj...
}
}
```
The problem with MyClass2 is that the conversion of `byte[]` to and from `object` is [boxing and unboxing](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx), which are computationally expensive operations affecting performance.
Would solving this problem with a [generic interface](http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx) avoid boxing/unboxing?
```
public interface IMyInterface<T>
{
void MyMethod(T arg);
}
public class MyClass1 : IMyInterface<MyObject>
{
public void MyMethod(MyObject arg)
{
// typecast no longer necessary
//MyObject obj = (MyObject) arg;
// do something with arg...
}
}
public class MyClass2 : IMyInterface<byte[]>
{
public void MyMethod(byte[] arg)
{
// typecast no longer necessary
//byte[] obj = (byte[]) arg;
// do something with arg...
}
}
```
How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?
Thank you! | I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type.
This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient. |
139,991 | <p>I have two functions, <code>f</code> and <code>g</code>, which call each other recursively. Unfortunately, when <code>f</code> calls <code>g</code>, it has not yet been declared, so I get an "unbound variable" error. How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ?</p>
| [
{
"answer_id": 140386,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>Mutual Recursion. Use <strong><code>and</code></strong> instead of <strong><code>fun</code></strong> between the two functions.</p>\n"
},
{
"answer_id": 140405,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 4,
"selected": true,
"text": "<p>Use <code>and</code>:</p>\n\n<pre><code>fun f x = ... \nand g x = ...\n</code></pre>\n\n<p>More info <a href=\"http://www.dcs.napier.ac.uk/~cs66/course-notes/sml/lesson8.htm\" rel=\"noreferrer\">here</a>.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/139991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10307/"
]
| I have two functions, `f` and `g`, which call each other recursively. Unfortunately, when `f` calls `g`, it has not yet been declared, so I get an "unbound variable" error. How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ? | Use `and`:
```
fun f x = ...
and g x = ...
```
More info [here](http://www.dcs.napier.ac.uk/~cs66/course-notes/sml/lesson8.htm). |
140,000 | <p>I don't want to change how the Status field works I just want to change the labels to
the states that the old system uses. (the old systems consists of spreadsheets and paper :P
<br>
We are using 3.0</p>
<pre>
* UNCONFIRMED --> PRELIMARY
* NEW --> DESIGN REVIEW
* ASSIGNED --> STR1
* RESOLVED --> STR2
* REOPEN
* VERIIFED --> BMR
* CLOSED --> TCG
</pre>
| [
{
"answer_id": 140168,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>If you log into the bugzilla system as an administrator you'll see on the bottom a link that says \"Field Values\", click that, on the next page you'll see \"Resolution\", go there then click on the resolution you'd like to change,</p>\n"
},
{
"answer_id": 140363,
"author": "Sally",
"author_id": 6539,
"author_profile": "https://Stackoverflow.com/users/6539",
"pm_score": 3,
"selected": true,
"text": "<p>I think this can be done by modifying the templates look here: </p>\n\n<p><a href=\"http://www.bugzilla.org/docs/2.22/html/cust-templates.html\" rel=\"nofollow noreferrer\">http://www.bugzilla.org/docs/2.22/html/cust-templates.html</a></p>\n\n<p>specifically:\n<strong>global/variables.none.tmpl</strong></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6539/"
]
| I don't want to change how the Status field works I just want to change the labels to
the states that the old system uses. (the old systems consists of spreadsheets and paper :P
We are using 3.0
```
* UNCONFIRMED --> PRELIMARY
* NEW --> DESIGN REVIEW
* ASSIGNED --> STR1
* RESOLVED --> STR2
* REOPEN
* VERIIFED --> BMR
* CLOSED --> TCG
``` | I think this can be done by modifying the templates look here:
<http://www.bugzilla.org/docs/2.22/html/cust-templates.html>
specifically:
**global/variables.none.tmpl** |
140,002 | <p>I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.</p>
<p>Here is the relevant part of my function:</p>
<pre><code>Function GetSomeStuff()
'
' Get a recordset...
'
Dim stuff
Set stuff = CreateObject("Scripting.Dictionary")
rs.MoveFirst
Do Until rs.EOF
stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value
rs.MoveNext
Loop
GetSomeStuff = stuff
End Function
</code></pre>
<p>How do I call this function and use the returned dictionary?</p>
<p>EDIT: I've tried this:</p>
<pre><code>Dim someStuff
someStuff = GetSomeStuff
</code></pre>
<p>and</p>
<pre><code>Dim someStuff
Set someStuff = GetSomeStuff
</code></pre>
<p>When I try to access someStuff, I get an error:</p>
<pre><code>Microsoft VBScript runtime error: Object required: 'GetSomeStuff'
</code></pre>
<p>EDIT 2: Trying this in the function:</p>
<pre><code>Set GetSomeStuff = stuff
</code></pre>
<p>Results in this error:</p>
<pre><code>Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment.
</code></pre>
| [
{
"answer_id": 140064,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code>Dim returnedStuff\nSet returnedStuff = GetSomeStuff()\n</code></pre>\n\n<p>Then \"For Each\" iterating over the dictionary? There's an example of using the Dictionary (albeit for VB6, the gist of it is the same though!) <a href=\"http://www.kamath.com/tutorials/tut009_dictionary.asp\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 140141,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried doing<br><code>\nset GetSomeStuff = stuff</code><br>\nin the last line of the function?</p>\n"
},
{
"answer_id": 140163,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": true,
"text": "<p>I wasn't too sure of what was your problem, so I experimented a bit.</p>\n\n<p>It appears that you just missed that to assign a reference to an object, you have to use <code>set</code>, even for a return value:</p>\n\n<pre><code>Function GetSomeStuff\n Dim stuff\n Set stuff = CreateObject(\"Scripting.Dictionary\")\n stuff.Add \"A\", \"Anaconda\"\n stuff.Add \"B\", \"Boa\"\n stuff.Add \"C\", \"Cobra\"\n\n Set GetSomeStuff = stuff\nEnd Function\n\nSet d = GetSomeStuff\nWscript.Echo d.Item(\"A\")\nWscript.Echo d.Exists(\"B\")\nitems = d.Items\nFor i = 0 To UBound(items)\n Wscript.Echo items(i)\nNext\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2441/"
]
| I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.
Here is the relevant part of my function:
```
Function GetSomeStuff()
'
' Get a recordset...
'
Dim stuff
Set stuff = CreateObject("Scripting.Dictionary")
rs.MoveFirst
Do Until rs.EOF
stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value
rs.MoveNext
Loop
GetSomeStuff = stuff
End Function
```
How do I call this function and use the returned dictionary?
EDIT: I've tried this:
```
Dim someStuff
someStuff = GetSomeStuff
```
and
```
Dim someStuff
Set someStuff = GetSomeStuff
```
When I try to access someStuff, I get an error:
```
Microsoft VBScript runtime error: Object required: 'GetSomeStuff'
```
EDIT 2: Trying this in the function:
```
Set GetSomeStuff = stuff
```
Results in this error:
```
Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment.
``` | I wasn't too sure of what was your problem, so I experimented a bit.
It appears that you just missed that to assign a reference to an object, you have to use `set`, even for a return value:
```
Function GetSomeStuff
Dim stuff
Set stuff = CreateObject("Scripting.Dictionary")
stuff.Add "A", "Anaconda"
stuff.Add "B", "Boa"
stuff.Add "C", "Cobra"
Set GetSomeStuff = stuff
End Function
Set d = GetSomeStuff
Wscript.Echo d.Item("A")
Wscript.Echo d.Exists("B")
items = d.Items
For i = 0 To UBound(items)
Wscript.Echo items(i)
Next
``` |
140,033 | <p>Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.:</p>
<pre><code>class foo;
typedef boost::shared_ptr<foo> foo_sp;
typeded std::map<int, foo_sp> foo_sp_map;
foo_sp_map m;
</code></pre>
<p>If I add a new foo_sp to the map but the key used already exists, will the existing entry be deleted? For example:</p>
<pre><code>foo_sp_map m;
void func1()
{
foo_sp p(new foo);
m[0] = p;
}
void func2()
{
foo_sp p2(new foo);
m[0] = p2;
}
</code></pre>
<p>Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing.</p>
| [
{
"answer_id": 140048,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 4,
"selected": true,
"text": "<p>First off, your question title says boost::auto_ptr, but you actually mean boost::shared_ptr</p>\n\n<p>And yes, the original pointer will be freed (if there are no further shared references to it).</p>\n"
},
{
"answer_id": 140084,
"author": "keraba",
"author_id": 22725,
"author_profile": "https://Stackoverflow.com/users/22725",
"pm_score": 0,
"selected": false,
"text": "<p>Since stackoverflow won't allow me to comment, I'll just answer. :/</p>\n\n<p>I don't see \"p\" going out of scope, so the object pointed to by it will <em>not</em> be freed. \"p\" will still point to it.</p>\n"
},
{
"answer_id": 140112,
"author": "Harald Scheirich",
"author_id": 22080,
"author_profile": "https://Stackoverflow.com/users/22080",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on what happens in your ... section</p>\n\n<p>Your container class contains <em>copies</em> of instances of foo_sp, when you execute <code>m[0] = p2;</code> the copy of <code>p</code> that was originally in that place goes out of scope. At that time it will be deleted <em>if there are no other foo_sp refers to it</em>.</p>\n\n<p>If the copy that was declared in the second line <code>foo_sp p(new foo);</code> is still around then the memory will not be deallocated. The entry will be delete once all references to it have been removed. </p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| Assume I have a class foo, and wish to use a std::map to store some boost::shared\_ptrs, e.g.:
```
class foo;
typedef boost::shared_ptr<foo> foo_sp;
typeded std::map<int, foo_sp> foo_sp_map;
foo_sp_map m;
```
If I add a new foo\_sp to the map but the key used already exists, will the existing entry be deleted? For example:
```
foo_sp_map m;
void func1()
{
foo_sp p(new foo);
m[0] = p;
}
void func2()
{
foo_sp p2(new foo);
m[0] = p2;
}
```
Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing. | First off, your question title says boost::auto\_ptr, but you actually mean boost::shared\_ptr
And yes, the original pointer will be freed (if there are no further shared references to it). |
140,043 | <p>How do I loop into all the resources in the resourcemanager?</p>
<p>Ie:
foreach (string resource in ResourceManager)
//Do something with the recource.</p>
<p>Thanks</p>
| [
{
"answer_id": 140060,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 6,
"selected": true,
"text": "<p>Use ResourceManager.<a href=\"http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.getresourceset.aspx\" rel=\"noreferrer\">GetResourceSet</a>() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach).</p>\n\n<hr>\n\n<p>To answer Nico's question: you can count the elements of an <code>IEnumerable</code> by casting it to the generic <code>IEnumerable<object></code> and use the <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.count.aspx\" rel=\"noreferrer\"><code>Enumerable.Count<T>()</code></a> extension method, which is new in C# 3.5:</p>\n\n<pre><code>using System.Linq;\n\n...\n\nvar resourceSet = resourceManager.GetResourceSet(..);\nvar count = resSet.Cast<object>().Count();\n</code></pre>\n"
},
{
"answer_id": 140257,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 1,
"selected": false,
"text": "<p>I wonder why would you like to loop through all of the resources.</p>\n\n<p>Anyway, <code>ResourceManager</code> needs to be instantiated giving it a <code>Type</code> or the base name where to lookup for resources. Then you will be able to retrieve a <code>ResourceSet</code> but for a given <code>CultureInfo</code>, ergo if you want to obtain all the resources for a given `ResourceManager</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17766/"
]
| How do I loop into all the resources in the resourcemanager?
Ie:
foreach (string resource in ResourceManager)
//Do something with the recource.
Thanks | Use ResourceManager.[GetResourceSet](http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.getresourceset.aspx)() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach).
---
To answer Nico's question: you can count the elements of an `IEnumerable` by casting it to the generic `IEnumerable<object>` and use the [`Enumerable.Count<T>()`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.count.aspx) extension method, which is new in C# 3.5:
```
using System.Linq;
...
var resourceSet = resourceManager.GetResourceSet(..);
var count = resSet.Cast<object>().Count();
``` |
140,044 | <p>I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.</p>
<p>Any sample code would be greatly appreciated!</p>
<p>Link to API: <a href="http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf" rel="nofollow noreferrer">http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf</a></p>
| [
{
"answer_id": 148494,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:</p>\n\n<pre><code>using System.Net;\nusing System.Text;\nusing System;\n\nnamespace RightNowSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n string serviceUrl = \"http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php\";\n WebClient webClient = new WebClient();\n string requestXml = \n@\"<connector>\n<function name=\"\"ans_get\"\">\n<parameter name=\"\"args\"\" type=\"\"pair\"\">\n<pair name=\"\"id\"\" type=\"\"integer\"\">33</pair>\n<pair name=\"\"sub_tbl\"\" type='pair'>\n<pair name=\"\"tbl_id\"\" type=\"\"integer\"\">164</pair>\n</pair>\n</parameter>\n</function>\n</connector>\";\n\n string secString = \"\";\n string postData = string.Format(\"xml_doc={0}, sec_string={1}\", requestXml, secString);\n byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);\n\n byte[] responseDataBytes = webClient.UploadData(serviceUrl, \"POST\", postDataBytes);\n string responseData = Encoding.UTF8.GetString(responseDataBytes);\n\n Console.WriteLine(responseData);\n }\n }\n}\n</code></pre>\n\n<p>I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.</p>\n"
},
{
"answer_id": 24749911,
"author": "Friyank",
"author_id": 3065532,
"author_profile": "https://Stackoverflow.com/users/3065532",
"pm_score": 0,
"selected": false,
"text": "<p>This will Create a Contact in Right now</p>\n\n<pre><code> class Program\n{\n private RightNowSyncPortClient _Service;\n public Program()\n {\n _Service = new RightNowSyncPortClient();\n _Service.ClientCredentials.UserName.UserName = \"Rightnow UID\";\n _Service.ClientCredentials.UserName.Password = \"Right now password\";\n }\n private Contact Contactinfo()\n {\n Contact newContact = new Contact();\n PersonName personName = new PersonName();\n personName.First = \"conatctname\";\n personName.Last = \"conatctlastname\";\n newContact.Name = personName;\n Email[] emailArray = new Email[1];\n emailArray[0] = new Email();\n emailArray[0].action = ActionEnum.add;\n emailArray[0].actionSpecified = true;\n emailArray[0].Address = \"[email protected]\";\n NamedID addressType = new NamedID();\n ID addressTypeID = new ID();\n addressTypeID.id = 1;\n addressType.ID = addressTypeID;\n addressType.ID.idSpecified = true;\n emailArray[0].AddressType = addressType;\n emailArray[0].Invalid = false;\n emailArray[0].InvalidSpecified = true;\n newContact.Emails = emailArray;\n return newContact;\n }\n public long CreateContact()\n {\n Contact newContact = Contactinfo();\n //Set the application ID in the client info header\n ClientInfoHeader clientInfoHeader = new ClientInfoHeader();\n clientInfoHeader.AppID = \".NET Getting Started\";\n //Set the create processing options, allow external events and rules to execute\n CreateProcessingOptions createProcessingOptions = new CreateProcessingOptions();\n createProcessingOptions.SuppressExternalEvents = false;\n createProcessingOptions.SuppressRules = false;\n RNObject[] createObjects = new RNObject[] { newContact };\n //Invoke the create operation on the RightNow server\n RNObject[] createResults = _Service.Create(clientInfoHeader, createObjects, createProcessingOptions);\n\n //We only created a single contact, this will be at index 0 of the results\n newContact = createResults[0] as Contact;\n return newContact.ID.id;\n }\n\n static void Main(string[] args)\n {\n Program RBSP = new Program();\n try\n {\n long newContactID = RBSP.CreateContact();\n System.Console.WriteLine(\"New Contact Created with ID: \" + newContactID);\n }\n catch (FaultException ex)\n {\n Console.WriteLine(ex.Code);\n Console.WriteLine(ex.Message);\n }\n\n System.Console.Read();\n\n }\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483/"
]
| I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.
Any sample code would be greatly appreciated!
Link to API: <http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf> | I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:
```
using System.Net;
using System.Text;
using System;
namespace RightNowSample
{
class Program
{
static void Main(string[] args)
{
string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php";
WebClient webClient = new WebClient();
string requestXml =
@"<connector>
<function name=""ans_get"">
<parameter name=""args"" type=""pair"">
<pair name=""id"" type=""integer"">33</pair>
<pair name=""sub_tbl"" type='pair'>
<pair name=""tbl_id"" type=""integer"">164</pair>
</pair>
</parameter>
</function>
</connector>";
string secString = "";
string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes);
string responseData = Encoding.UTF8.GetString(responseDataBytes);
Console.WriteLine(responseData);
}
}
}
```
I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you. |
140,054 | <p>I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently.</p>
<p>Is there are way to do something like this:</p>
<pre><code>installutil.exe myservice.exe /customarg1=username /customarg2=password
</code></pre>
| [
{
"answer_id": 140086,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 0,
"selected": false,
"text": "<p>No, installutil doesn't support that.</p>\n\n<p>Of course if you wrote an installer; with a <a href=\"http://arcanecode.wordpress.com/2007/05/23/windows-services-in-c-adding-the-installer-part-3/\" rel=\"nofollow noreferrer\">custom action</a> then you would be able to use that as part of an MSI or via installutil.</p>\n"
},
{
"answer_id": 140285,
"author": "Dean Hill",
"author_id": 3106,
"author_profile": "https://Stackoverflow.com/users/3106",
"pm_score": 7,
"selected": true,
"text": "<p>Bravo to my co-worker (Bruce Eddy). He found a way we can make this command-line call:</p>\n\n<pre><code>installutil.exe /user=uname /password=pw myservice.exe\n</code></pre>\n\n<p>It is done by overriding OnBeforeInstall in the installer class:</p>\n\n<pre><code>namespace Test\n{\n [RunInstaller(true)]\n public class TestInstaller : Installer\n {\n private ServiceInstaller serviceInstaller;\n private ServiceProcessInstaller serviceProcessInstaller;\n\n public OregonDatabaseWinServiceInstaller()\n {\n serviceInstaller = new ServiceInstaller();\n serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;\n serviceInstaller.ServiceName = \"Test\";\n serviceInstaller.DisplayName = \"Test Service\";\n serviceInstaller.Description = \"Test\";\n serviceInstaller.StartType = ServiceStartMode.Automatic;\n Installers.Add(serviceInstaller);\n\n serviceProcessInstaller = new ServiceProcessInstaller();\n serviceProcessInstaller.Account = ServiceAccount.User; \n Installers.Add(serviceProcessInstaller);\n }\n\n public string GetContextParameter(string key)\n {\n string sValue = \"\";\n try\n {\n sValue = this.Context.Parameters[key].ToString();\n }\n catch\n {\n sValue = \"\";\n }\n return sValue;\n }\n\n\n // Override the 'OnBeforeInstall' method.\n protected override void OnBeforeInstall(IDictionary savedState)\n {\n base.OnBeforeInstall(savedState);\n\n string username = GetContextParameter(\"user\").Trim();\n string password = GetContextParameter(\"password\").Trim();\n\n if (username != \"\")\n serviceProcessInstaller.Username = username;\n if (password != \"\")\n serviceProcessInstaller.Password = password;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1613862,
"author": "william",
"author_id": 195358,
"author_profile": "https://Stackoverflow.com/users/195358",
"pm_score": -1,
"selected": false,
"text": "<p>You can also force your service to run as User using \n<strong>ServiceProcessInstaller::Account = ServiceAccount.User</strong>;</p>\n\n<p>A popup asking \"[domain\\]user, password\" will appear during service installation.</p>\n\n<pre><code>public class MyServiceInstaller : Installer\n{\n /// Public Constructor for WindowsServiceInstaller\n public MyServiceInstaller()\n {\n ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();\n ServiceInstaller serviceInstaller = new ServiceInstaller();\n\n //# Service Account Information\n serviceProcessInstaller.Account = ServiceAccount.User; // and not LocalSystem;\n ....\n</code></pre>\n"
},
{
"answer_id": 2864048,
"author": "Jimbo",
"author_id": 344870,
"author_profile": "https://Stackoverflow.com/users/344870",
"pm_score": 6,
"selected": false,
"text": "<p>A much easier way than the posts above and with no extra code in your installer is to use the following:</p>\n\n<blockquote>\n <p>installUtil.exe /username=domain\\username /password=password /unattended C:\\My.exe</p>\n</blockquote>\n\n<p>Just ensure the account you use is valid. If not you will receive a \"No mapping between account names and security id's was done\" exception</p>\n"
},
{
"answer_id": 17425522,
"author": "Josua",
"author_id": 948287,
"author_profile": "https://Stackoverflow.com/users/948287",
"pm_score": 2,
"selected": false,
"text": "<p><code>InstallUtil.exe</code> sets StartupType=Manual</p>\n\n<p>In case you want to autostart the service, use:</p>\n\n<p><code>sc config MyServiceName start= auto</code></p>\n\n<p>(note there there has to be a space after '=')</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3106/"
]
| I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently.
Is there are way to do something like this:
```
installutil.exe myservice.exe /customarg1=username /customarg2=password
``` | Bravo to my co-worker (Bruce Eddy). He found a way we can make this command-line call:
```
installutil.exe /user=uname /password=pw myservice.exe
```
It is done by overriding OnBeforeInstall in the installer class:
```
namespace Test
{
[RunInstaller(true)]
public class TestInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
public OregonDatabaseWinServiceInstaller()
{
serviceInstaller = new ServiceInstaller();
serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "Test";
serviceInstaller.DisplayName = "Test Service";
serviceInstaller.Description = "Test";
serviceInstaller.StartType = ServiceStartMode.Automatic;
Installers.Add(serviceInstaller);
serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Account = ServiceAccount.User;
Installers.Add(serviceProcessInstaller);
}
public string GetContextParameter(string key)
{
string sValue = "";
try
{
sValue = this.Context.Parameters[key].ToString();
}
catch
{
sValue = "";
}
return sValue;
}
// Override the 'OnBeforeInstall' method.
protected override void OnBeforeInstall(IDictionary savedState)
{
base.OnBeforeInstall(savedState);
string username = GetContextParameter("user").Trim();
string password = GetContextParameter("password").Trim();
if (username != "")
serviceProcessInstaller.Username = username;
if (password != "")
serviceProcessInstaller.Password = password;
}
}
}
``` |
140,104 | <p>If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?</p>
| [
{
"answer_id": 140154,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 8,
"selected": true,
"text": "<p>There is a <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx\" rel=\"noreferrer\"><code>WebOperationContext</code></a> that you can access and it has a <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.outgoingresponse.aspx\" rel=\"noreferrer\"><code>OutgoingResponse</code></a> property of type <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.aspx\" rel=\"noreferrer\"><code>OutgoingWebResponseContext</code></a> which has a <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.statuscode.aspx\" rel=\"noreferrer\"><code>StatusCode</code></a> property that can be set.</p>\n\n<pre><code>WebOperationContext ctx = WebOperationContext.Current;\nctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;\n</code></pre>\n"
},
{
"answer_id": 140667,
"author": "JarrettV",
"author_id": 16340,
"author_profile": "https://Stackoverflow.com/users/16340",
"pm_score": 5,
"selected": false,
"text": "<p>For 404 there is a built in method on the <strong>WebOperationContext.Current.OutgoingResponse</strong> called <strong>SetStatusAsNotFound(string message)</strong> that will set the status code to 404 and a status description with one call. </p>\n\n<p>Note there is also, <strong>SetStatusAsCreated(Uri location)</strong> that will set the status code to 201 and location header with one call.</p>\n"
},
{
"answer_id": 4266353,
"author": "Graeme Bradbury",
"author_id": 5889,
"author_profile": "https://Stackoverflow.com/users/5889",
"pm_score": 6,
"selected": false,
"text": "<p>If you need to return a reason body then have a look at <a href=\"http://msdn.microsoft.com/en-us/library/dd989924.aspx\">WebFaultException</a> </p>\n\n<p>For example </p>\n\n<pre><code>throw new WebFaultException<string>(\"Bar wasn't Foo'd\", HttpStatusCode.BadRequest );\n</code></pre>\n"
},
{
"answer_id": 5354506,
"author": "Hydtechie",
"author_id": 666306,
"author_profile": "https://Stackoverflow.com/users/666306",
"pm_score": 2,
"selected": false,
"text": "<p>If you wish to see the status description in the header, REST method should make sure to return null from the Catch() section as below:</p>\n\n<pre><code>catch (ArgumentException ex)\n{\n WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;\n WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message;\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 5541302,
"author": "OnlyMahesh",
"author_id": 646272,
"author_profile": "https://Stackoverflow.com/users/646272",
"pm_score": 0,
"selected": false,
"text": "<p>This did not work for me for WCF Data Services. Instead, you can use DataServiceException in case of Data Services. Found the following post useful.\n<a href=\"http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/thread/f0cbab98-fcd7-4248-af81-5f74b019d8de\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/thread/f0cbab98-fcd7-4248-af81-5f74b019d8de</a></p>\n"
},
{
"answer_id": 32045262,
"author": "user5234326",
"author_id": 5234326,
"author_profile": "https://Stackoverflow.com/users/5234326",
"pm_score": 1,
"selected": false,
"text": "<pre><code>WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;\nthrow new WebException(\"令牌码不正确\", new InvalidTokenException());\n</code></pre>\n\n<p>ref:<a href=\"https://social.msdn.microsoft.com/Forums/en-US/f6671de3-34ce-4b70-9a77-39ecf5d1b9c3/weboperationcontext-http-statuses-and-exceptions?forum=wcf\" rel=\"nofollow\">https://social.msdn.microsoft.com/Forums/en-US/f6671de3-34ce-4b70-9a77-39ecf5d1b9c3/weboperationcontext-http-statuses-and-exceptions?forum=wcf</a></p>\n"
},
{
"answer_id": 50505480,
"author": "eitzo",
"author_id": 4338015,
"author_profile": "https://Stackoverflow.com/users/4338015",
"pm_score": 3,
"selected": false,
"text": "<p>You can also return a statuscode and reason body with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.web.weboperationcontext?view=netframework-4.7.2\" rel=\"noreferrer\">WebOperationContext</a>'s <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.web.outgoingwebresponsecontext.statuscode?view=netframework-4.7.2\" rel=\"noreferrer\">StatusCode</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.web.outgoingwebresponsecontext.statusdescription?view=netframework-4.7.2\" rel=\"noreferrer\">StatusDescription</a>:</p>\n\n<pre><code>WebOperationContext context = WebOperationContext.Current;\ncontext.OutgoingResponse.StatusCode = HttpStatusCode.OK;\ncontext.OutgoingResponse.StatusDescription = \"Your Message\";\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21784/"
]
| If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method? | There is a [`WebOperationContext`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx) that you can access and it has a [`OutgoingResponse`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.outgoingresponse.aspx) property of type [`OutgoingWebResponseContext`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.aspx) which has a [`StatusCode`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.statuscode.aspx) property that can be set.
```
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
``` |
140,131 | <p>I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.</p>
<p>I couldn't have phrased it better than the person that posted <a href="http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html" rel="noreferrer">the same question here</a>.</p>
<p>But to keep it original, I'll phrase it my own way: suppose I have a string <code>"00A0BF"</code> that I would like interpreted as the</p>
<pre><code>byte[] {0x00,0xA0,0xBf}
</code></pre>
<p>what should I do?</p>
<p>I am a Java novice and ended up using <code>BigInteger</code> and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple. </p>
| [
{
"answer_id": 140147,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 7,
"selected": false,
"text": "<p>The Hex class in commons-codec should do that for you.</p>\n\n<p><a href=\"http://commons.apache.org/codec/\" rel=\"noreferrer\">http://commons.apache.org/codec/</a></p>\n\n<pre><code>import org.apache.commons.codec.binary.Hex;\n...\nbyte[] decoded = Hex.decodeHex(\"00A0BF\");\n// 0x00 0xA0 0xBF\n</code></pre>\n"
},
{
"answer_id": 140166,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 2,
"selected": false,
"text": "<p>I've always used a method like</p>\n\n<pre><code>public static final byte[] fromHexString(final String s) {\n String[] v = s.split(\" \");\n byte[] arr = new byte[v.length];\n int i = 0;\n for(String val: v) {\n arr[i++] = Integer.decode(\"0x\" + val).byteValue();\n\n }\n return arr;\n}\n</code></pre>\n\n<p>this method splits on space delimited hex values but it wouldn't be hard to make it split the string on any other criteria such as into groupings of two characters. </p>\n"
},
{
"answer_id": 140181,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": -1,
"selected": false,
"text": "<p>I think will do it for you. I cobbled it together from a similar function that returned the data as a string:</p>\n\n<pre><code>private static byte[] decode(String encoded) {\n byte result[] = new byte[encoded/2];\n char enc[] = encoded.toUpperCase().toCharArray();\n StringBuffer curr;\n for (int i = 0; i < enc.length; i += 2) {\n curr = new StringBuffer(\"\");\n curr.append(String.valueOf(enc[i]));\n curr.append(String.valueOf(enc[i + 1]));\n result[i] = (byte) Integer.parseInt(curr.toString(), 16);\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 140188,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "<p>EDIT: as pointed out by @mmyers, this method doesn't work on input that contains substrings corresponding to bytes with the high bit set ("80" - "FF"). The explanation is at <a href=\"https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6259307\" rel=\"nofollow noreferrer\">Bug ID: 6259307 Byte.parseByte not working as advertised in the SDK Documentation</a>.</p>\n<pre><code>public static final byte[] fromHexString(final String s) {\n byte[] arr = new byte[s.length()/2];\n for ( int start = 0; start < s.length(); start += 2 )\n {\n String thisByte = s.substring(start, start+2);\n arr[start/2] = Byte.parseByte(thisByte, 16);\n }\n return arr;\n}\n</code></pre>\n"
},
{
"answer_id": 140430,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a method that actually works (based on several previous semi-correct answers):</p>\n\n<pre><code>private static byte[] fromHexString(final String encoded) {\n if ((encoded.length() % 2) != 0)\n throw new IllegalArgumentException(\"Input string must contain an even number of characters\");\n\n final byte result[] = new byte[encoded.length()/2];\n final char enc[] = encoded.toCharArray();\n for (int i = 0; i < enc.length; i += 2) {\n StringBuilder curr = new StringBuilder(2);\n curr.append(enc[i]).append(enc[i + 1]);\n result[i/2] = (byte) Integer.parseInt(curr.toString(), 16);\n }\n return result;\n}\n</code></pre>\n\n<p>The only possible issue that I can see is if the input string is extremely long; calling toCharArray() makes a copy of the string's internal array.</p>\n\n<p>EDIT: Oh, and by the way, bytes are signed in Java, so your input string converts to [0, -96, -65] instead of [0, 160, 191]. But you probably knew that already.</p>\n"
},
{
"answer_id": 140592,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 5,
"selected": false,
"text": "<p>Actually, I think the BigInteger is solution is very nice:</p>\n\n<pre><code>new BigInteger(\"00A0BF\", 16).toByteArray();\n</code></pre>\n\n<p>Edit: <strong>Not safe for leading zeros</strong>, as noted by the poster.</p>\n"
},
{
"answer_id": 140861,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 11,
"selected": true,
"text": "<p>Update (2021) - <strong>Java 17</strong> now includes <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html\" rel=\"noreferrer\"><code>java.util.HexFormat</code></a> (only took 25 years):</p>\n<p><code>HexFormat.of().parseHex(s)</code></p>\n<hr>\nFor older versions of Java:\n<p>Here's a solution that I think is better than any posted so far:</p>\n<pre><code>/* s must be an even-length string. */\npublic static byte[] hexStringToByteArray(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i+1), 16));\n }\n return data;\n}\n</code></pre>\n<p>Reasons why it is an improvement:</p>\n<ul>\n<li><p>Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)</p>\n</li>\n<li><p>Doesn't convert the String into a <code>char[]</code>, or create StringBuilder and String objects for every single byte.</p>\n</li>\n<li><p>No library dependencies that may not be available</p>\n</li>\n</ul>\n<p>Feel free to add argument checking via <code>assert</code> or exceptions if the argument is not known to be safe.</p>\n"
},
{
"answer_id": 1703094,
"author": "Sniper",
"author_id": 207215,
"author_profile": "https://Stackoverflow.com/users/207215",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>BigInteger()</code> Method from java.math is very Slow and not recommandable.</p>\n\n<p><code>Integer.parseInt(HEXString, 16)</code></p>\n\n<p>can cause problems with some characters without\nconverting to Digit / Integer</p>\n\n<p>a Well Working method:</p>\n\n<pre><code>Integer.decode(\"0xXX\") .byteValue()\n</code></pre>\n\n<p>Function:</p>\n\n<pre><code>public static byte[] HexStringToByteArray(String s) {\n byte data[] = new byte[s.length()/2];\n for(int i=0;i < s.length();i+=2) {\n data[i/2] = (Integer.decode(\"0x\"+s.charAt(i)+s.charAt(i+1))).byteValue();\n }\n return data;\n}\n</code></pre>\n\n<p>Have Fun, Good Luck</p>\n"
},
{
"answer_id": 2448414,
"author": "David V",
"author_id": 294072,
"author_profile": "https://Stackoverflow.com/users/294072",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static byte[] hex2ba(String sHex) throws Hex2baException {\n if (1==sHex.length()%2) {\n throw(new Hex2baException(\"Hex string need even number of chars\"));\n }\n\n byte[] ba = new byte[sHex.length()/2];\n for (int i=0;i<sHex.length()/2;i++) {\n ba[i] = (Integer.decode(\n \"0x\"+sHex.substring(i*2, (i+1)*2))).byteValue();\n }\n return ba;\n}\n</code></pre>\n"
},
{
"answer_id": 3408174,
"author": "Kernel Panic",
"author_id": 411092,
"author_profile": "https://Stackoverflow.com/users/411092",
"pm_score": 2,
"selected": false,
"text": "<p>I like the Character.digit solution, but here is how I solved it</p>\n\n<pre><code>public byte[] hex2ByteArray( String hexString ) {\n String hexVal = \"0123456789ABCDEF\";\n byte[] out = new byte[hexString.length() / 2];\n\n int n = hexString.length();\n\n for( int i = 0; i < n; i += 2 ) {\n //make a bit representation in an int of the hex value \n int hn = hexVal.indexOf( hexString.charAt( i ) );\n int ln = hexVal.indexOf( hexString.charAt( i + 1 ) );\n\n //now just shift the high order nibble and add them together\n out[i/2] = (byte)( ( hn << 4 ) | ln );\n }\n\n return out;\n}\n</code></pre>\n"
},
{
"answer_id": 4586527,
"author": "GrkEngineer",
"author_id": 118999,
"author_profile": "https://Stackoverflow.com/users/118999",
"pm_score": 5,
"selected": false,
"text": "<p>The <code>HexBinaryAdapter</code> provides the ability to marshal and unmarshal between <code>String</code> and <code>byte[]</code>.</p>\n\n<pre><code>import javax.xml.bind.annotation.adapters.HexBinaryAdapter;\n\npublic byte[] hexToBytes(String hexString) {\n HexBinaryAdapter adapter = new HexBinaryAdapter();\n byte[] bytes = adapter.unmarshal(hexString);\n return bytes;\n}\n</code></pre>\n\n<p>That's just an example I typed in...I actually just use it as is and don't need to make a separate method for using it.</p>\n"
},
{
"answer_id": 5942951,
"author": "Vladislav Rastrusny",
"author_id": 173677,
"author_profile": "https://Stackoverflow.com/users/173677",
"pm_score": 8,
"selected": false,
"text": "<p><strong>One-liners:</strong></p>\n\n<pre><code>import javax.xml.bind.DatatypeConverter;\n\npublic static String toHexString(byte[] array) {\n return DatatypeConverter.printHexBinary(array);\n}\n\npublic static byte[] toByteArray(String s) {\n return DatatypeConverter.parseHexBinary(s);\n}\n</code></pre>\n\n<p><strong>Warnings</strong>: </p>\n\n<ul>\n<li>in Java 9 Jigsaw this is no longer part of the (default) java.se root\nset so it will result in a ClassNotFoundException unless you specify\n--add-modules java.se.ee (thanks to @<code>eckes</code>)</li>\n<li>Not available on Android (thanks to <code>Fabian</code> for noting that), but you can just <a href=\"https://stackoverflow.com/a/11139098/173677\">take the source code</a> if your system lacks <code>javax.xml</code> for some reason. Thanks to @<code>Bert Regelink</code> for extracting the source.</li>\n</ul>\n"
},
{
"answer_id": 9854133,
"author": "Clayton Balabanov",
"author_id": 1149783,
"author_profile": "https://Stackoverflow.com/users/1149783",
"pm_score": 1,
"selected": false,
"text": "<p>I found Kernel Panic to have the solution most useful to me, but ran into problems if the hex string was an odd number. solved it this way:</p>\n\n<pre><code>boolean isOdd(int value)\n{\n return (value & 0x01) !=0;\n}\n\nprivate int hexToByte(byte[] out, int value)\n{\n String hexVal = \"0123456789ABCDEF\"; \n String hexValL = \"0123456789abcdef\";\n String st = Integer.toHexString(value);\n int len = st.length();\n if (isOdd(len))\n {\n len+=1; // need length to be an even number.\n st = (\"0\" + st); // make it an even number of chars\n }\n out[0]=(byte)(len/2);\n for (int i =0;i<len;i+=2)\n {\n int hh = hexVal.indexOf(st.charAt(i));\n if (hh == -1) hh = hexValL.indexOf(st.charAt(i));\n int lh = hexVal.indexOf(st.charAt(i+1));\n if (lh == -1) lh = hexValL.indexOf(st.charAt(i+1));\n out[(i/2)+1] = (byte)((hh << 4)|lh);\n }\n return (len/2)+1;\n}\n</code></pre>\n\n<p>I am adding a number of hex numbers to an array, so i pass the reference to the array I am using, and the int I need converted and returning the relative position of the next hex number. So the final byte array has [0] number of hex pairs, [1...] hex pairs, then the number of pairs... </p>\n"
},
{
"answer_id": 11139098,
"author": "Bert Regelink",
"author_id": 1239858,
"author_profile": "https://Stackoverflow.com/users/1239858",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p><strong>One-liners:</strong></p>\n\n<pre><code>import javax.xml.bind.DatatypeConverter;\n\npublic static String toHexString(byte[] array) {\n return DatatypeConverter.printHexBinary(array);\n}\n\npublic static byte[] toByteArray(String s) {\n return DatatypeConverter.parseHexBinary(s);\n}\n</code></pre>\n</blockquote>\n\n<p>For those of you interested in the actual code behind the <strong>One-liners</strong> from <a href=\"https://stackoverflow.com/users/173677/fractalizer\">FractalizeR</a> (I needed that since javax.xml.bind is not available for Android (by default)), this comes from <a href=\"http://www.docjar.com/html/api/com/sun/xml/internal/bind/DatatypeConverterImpl.java.html\" rel=\"noreferrer\">com.sun.xml.internal.bind.DatatypeConverterImpl.java</a> :</p>\n\n<pre><code>public byte[] parseHexBinary(String s) {\n final int len = s.length();\n\n // \"111\" is not a valid hex encoding.\n if( len%2 != 0 )\n throw new IllegalArgumentException(\"hexBinary needs to be even-length: \"+s);\n\n byte[] out = new byte[len/2];\n\n for( int i=0; i<len; i+=2 ) {\n int h = hexToBin(s.charAt(i ));\n int l = hexToBin(s.charAt(i+1));\n if( h==-1 || l==-1 )\n throw new IllegalArgumentException(\"contains illegal character for hexBinary: \"+s);\n\n out[i/2] = (byte)(h*16+l);\n }\n\n return out;\n}\n\nprivate static int hexToBin( char ch ) {\n if( '0'<=ch && ch<='9' ) return ch-'0';\n if( 'A'<=ch && ch<='F' ) return ch-'A'+10;\n if( 'a'<=ch && ch<='f' ) return ch-'a'+10;\n return -1;\n}\n\nprivate static final char[] hexCode = \"0123456789ABCDEF\".toCharArray();\n\npublic String printHexBinary(byte[] data) {\n StringBuilder r = new StringBuilder(data.length*2);\n for ( byte b : data) {\n r.append(hexCode[(b >> 4) & 0xF]);\n r.append(hexCode[(b & 0xF)]);\n }\n return r.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 13296284,
"author": "Sean Coffey",
"author_id": 1810344,
"author_profile": "https://Stackoverflow.com/users/1810344",
"pm_score": 2,
"selected": false,
"text": "<p>The Code presented by Bert Regelink simply does not work. \nTry the following:</p>\n\n<pre><code>import javax.xml.bind.DatatypeConverter;\nimport java.io.*;\n\npublic class Test\n{ \n @Test\n public void testObjectStreams( ) throws IOException, ClassNotFoundException\n { \n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n\n String stringTest = \"TEST\";\n oos.writeObject( stringTest );\n\n oos.close();\n baos.close();\n\n byte[] bytes = baos.toByteArray();\n String hexString = DatatypeConverter.printHexBinary( bytes);\n byte[] reconvertedBytes = DatatypeConverter.parseHexBinary(hexString);\n\n assertArrayEquals( bytes, reconvertedBytes );\n\n ByteArrayInputStream bais = new ByteArrayInputStream(reconvertedBytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n\n String readString = (String) ois.readObject();\n\n assertEquals( stringTest, readString);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 15656440,
"author": "jontro",
"author_id": 429972,
"author_profile": "https://Stackoverflow.com/users/429972",
"pm_score": 5,
"selected": false,
"text": "<p>You can now use <a href=\"https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/io/BaseEncoding.html\" rel=\"noreferrer\">BaseEncoding</a> in <code>guava</code> to accomplish this.</p>\n\n<pre><code>BaseEncoding.base16().decode(string);\n</code></pre>\n\n<p>To reverse it use </p>\n\n<pre><code>BaseEncoding.base16().encode(bytes);\n</code></pre>\n"
},
{
"answer_id": 16590535,
"author": "Philip Helger",
"author_id": 15254,
"author_profile": "https://Stackoverflow.com/users/15254",
"pm_score": 1,
"selected": false,
"text": "<p>Based on the op voted solution, the following should be a bit more efficient:</p>\n\n<pre><code> public static byte [] hexStringToByteArray (final String s) {\n if (s == null || (s.length () % 2) == 1)\n throw new IllegalArgumentException ();\n final char [] chars = s.toCharArray ();\n final int len = chars.length;\n final byte [] data = new byte [len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16));\n }\n return data;\n }\n</code></pre>\n\n<p>Because: the initial conversion to a char array spares the length checks in charAt</p>\n"
},
{
"answer_id": 27326948,
"author": "Alejandro",
"author_id": 4330776,
"author_profile": "https://Stackoverflow.com/users/4330776",
"pm_score": -1,
"selected": false,
"text": "<p>For Me this was the solution, HEX=\"FF01\" then split to FF(255) and 01(01) </p>\n\n<pre><code>private static byte[] BytesEncode(String encoded) {\n //System.out.println(encoded.length());\n byte result[] = new byte[encoded.length() / 2];\n char enc[] = encoded.toUpperCase().toCharArray();\n String curr = \"\";\n for (int i = 0; i < encoded.length(); i=i+2) {\n curr = encoded.substring(i,i+2);\n System.out.println(curr);\n if(i==0){\n result[i]=((byte) Integer.parseInt(curr, 16));\n }else{\n result[i/2]=((byte) Integer.parseInt(curr, 16));\n }\n\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 33523093,
"author": "Miao1007",
"author_id": 4016014,
"author_profile": "https://Stackoverflow.com/users/4016014",
"pm_score": 4,
"selected": false,
"text": "<p>In android ,if you are working with hex, you can try <a href=\"https://github.com/square/okio\" rel=\"noreferrer\">okio</a>.</p>\n\n<p>simple usage:</p>\n\n<pre><code>byte[] bytes = ByteString.decodeHex(\"c000060000\").toByteArray();\n</code></pre>\n\n<p>and result will be </p>\n\n<pre><code>[-64, 0, 6, 0, 0]\n</code></pre>\n"
},
{
"answer_id": 39970426,
"author": "Conor Svensson",
"author_id": 3211687,
"author_profile": "https://Stackoverflow.com/users/3211687",
"pm_score": 2,
"selected": false,
"text": "<p>For what it's worth, here's another version which supports odd length strings, without resorting to string concatenation.</p>\n\n<pre><code>public static byte[] hexStringToByteArray(String input) {\n int len = input.length();\n\n if (len == 0) {\n return new byte[] {};\n }\n\n byte[] data;\n int startIdx;\n if (len % 2 != 0) {\n data = new byte[(len / 2) + 1];\n data[0] = (byte) Character.digit(input.charAt(0), 16);\n startIdx = 1;\n } else {\n data = new byte[len / 2];\n startIdx = 0;\n }\n\n for (int i = startIdx; i < len; i += 2) {\n data[(i + 1) / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)\n + Character.digit(input.charAt(i+1), 16));\n }\n return data;\n}\n</code></pre>\n"
},
{
"answer_id": 43799515,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 0,
"selected": false,
"text": "<p>My formal solution:</p>\n\n<pre><code>/**\n * Decodes a hexadecimally encoded binary string.\n * <p>\n * Note that this function does <em>NOT</em> convert a hexadecimal number to a\n * binary number.\n *\n * @param hex Hexadecimal representation of data.\n * @return The byte[] representation of the given data.\n * @throws NumberFormatException If the hexadecimal input string is of odd\n * length or invalid hexadecimal string.\n */\npublic static byte[] hex2bin(String hex) throws NumberFormatException {\n if (hex.length() % 2 > 0) {\n throw new NumberFormatException(\"Hexadecimal input string must have an even length.\");\n }\n byte[] r = new byte[hex.length() / 2];\n for (int i = hex.length(); i > 0;) {\n r[i / 2 - 1] = (byte) (digit(hex.charAt(--i)) | (digit(hex.charAt(--i)) << 4));\n }\n return r;\n}\n\nprivate static int digit(char ch) {\n int r = Character.digit(ch, 16);\n if (r < 0) {\n throw new NumberFormatException(\"Invalid hexadecimal string: \" + ch);\n }\n return r;\n}\n</code></pre>\n\n<p>Is like the <a href=\"http://php.net/manual/en/function.hex2bin.php\" rel=\"nofollow noreferrer\">PHP hex2bin() Function</a> but in Java style.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>String data = new String(hex2bin(\"6578616d706c65206865782064617461\"));\n// data value: \"example hex data\"\n</code></pre>\n"
},
{
"answer_id": 49853711,
"author": "Andy Brown",
"author_id": 1763035,
"author_profile": "https://Stackoverflow.com/users/1763035",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a preference for Java 8 streams as your coding style then this can be achieved using just JDK primitives.</p>\n\n<pre><code>String hex = \"0001027f80fdfeff\";\n\nbyte[] converted = IntStream.range(0, hex.length() / 2)\n .map(i -> Character.digit(hex.charAt(i * 2), 16) << 4 | Character.digit(hex.charAt((i * 2) + 1), 16))\n .collect(ByteArrayOutputStream::new,\n ByteArrayOutputStream::write,\n (s1, s2) -> s1.write(s2.toByteArray(), 0, s2.size()))\n .toByteArray();\n</code></pre>\n\n<p>The <code>, 0, s2.size()</code> parameters in the collector concatenate function can be omitted if you don't mind catching <code>IOException</code>.</p>\n"
},
{
"answer_id": 52015636,
"author": "DrPhill",
"author_id": 7347085,
"author_profile": "https://Stackoverflow.com/users/7347085",
"pm_score": 0,
"selected": false,
"text": "<p>Late to the party, but I have amalgamated the answer above by DaveL into a class with the reverse action - just in case it helps. </p>\n\n<pre><code>public final class HexString {\n private static final char[] digits = \"0123456789ABCDEF\".toCharArray();\n\n private HexString() {}\n\n public static final String fromBytes(final byte[] bytes) {\n final StringBuilder buf = new StringBuilder();\n for (int i = 0; i < bytes.length; i++) {\n buf.append(HexString.digits[(bytes[i] >> 4) & 0x0f]);\n buf.append(HexString.digits[bytes[i] & 0x0f]);\n }\n return buf.toString();\n }\n\n public static final byte[] toByteArray(final String hexString) {\n if ((hexString.length() % 2) != 0) {\n throw new IllegalArgumentException(\"Input string must contain an even number of characters\");\n }\n final int len = hexString.length();\n final byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)\n + Character.digit(hexString.charAt(i + 1), 16));\n }\n return data;\n }\n}\n</code></pre>\n\n<p>And JUnit test class:</p>\n\n<pre><code>public class TestHexString {\n\n @Test\n public void test() {\n String[] tests = {\"0FA1056D73\", \"\", \"00\", \"0123456789ABCDEF\", \"FFFFFFFF\"};\n\n for (int i = 0; i < tests.length; i++) {\n String in = tests[i];\n byte[] bytes = HexString.toByteArray(in);\n String out = HexString.fromBytes(bytes);\n System.out.println(in); //DEBUG\n System.out.println(out); //DEBUG\n Assert.assertEquals(in, out);\n\n }\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 52501458,
"author": "tigger",
"author_id": 5758166,
"author_profile": "https://Stackoverflow.com/users/5758166",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a very old thread, but still like to add my penny worth.</p>\n\n<p>If I really need to code up a simple hex string to binary converter, I'd like to do it as follows.</p>\n\n<pre><code>public static byte[] hexToBinary(String s){\n\n /*\n * skipped any input validation code\n */\n\n byte[] data = new byte[s.length()/2];\n\n for( int i=0, j=0; \n i<s.length() && j<data.length; \n i+=2, j++)\n {\n data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);\n }\n\n return data;\n}\n</code></pre>\n"
},
{
"answer_id": 71455588,
"author": "lbruun",
"author_id": 2282938,
"author_profile": "https://Stackoverflow.com/users/2282938",
"pm_score": 0,
"selected": false,
"text": "<p>If your needs are more than just the occasional conversion then you can use <a href=\"https://github.com/lbruun/hexutils\" rel=\"nofollow noreferrer\">HexUtils</a>.</p>\n<p>Example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>byte[] byteArray = Hex.hexStrToBytes("00A0BF");\n</code></pre>\n<p>This is the most simple case. Your input may contain delimiters (think MAC addresses, certificate thumbprints, etc), your input may be streaming, etc. In such cases it gets easier to justify to pull in an external library like <a href=\"https://github.com/lbruun/hexutils\" rel=\"nofollow noreferrer\">HexUtils</a>, however small.</p>\n<p>With JDK 17 the <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html\" rel=\"nofollow noreferrer\">HexFormat</a> class will fulfill most needs and the need for something like HexUtils is greatly diminished. However, HexUtils can still be used for things like converting very large amounts to/from hex (streaming) or pretty printing hex (think wire dumps) which the JDK HexFormat class cannot do.</p>\n<p>(full disclosure: I'm the author of HexUtils)</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11798/"
]
| I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.
I couldn't have phrased it better than the person that posted [the same question here](http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html).
But to keep it original, I'll phrase it my own way: suppose I have a string `"00A0BF"` that I would like interpreted as the
```
byte[] {0x00,0xA0,0xBf}
```
what should I do?
I am a Java novice and ended up using `BigInteger` and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple. | Update (2021) - **Java 17** now includes [`java.util.HexFormat`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html) (only took 25 years):
`HexFormat.of().parseHex(s)`
---
For older versions of Java:
Here's a solution that I think is better than any posted so far:
```
/* s must be an even-length string. */
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
```
Reasons why it is an improvement:
* Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)
* Doesn't convert the String into a `char[]`, or create StringBuilder and String objects for every single byte.
* No library dependencies that may not be available
Feel free to add argument checking via `assert` or exceptions if the argument is not known to be safe. |
140,133 | <p>I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed.</p>
<pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
</code></pre>
<p>Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers.</p>
<p><strong>UPDATE:</strong><br>
I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally. </p>
<pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
$(popupWindow.window).unload(function() { alert('hello'); });
</code></pre>
<p>Does anybody have any idea as to why the unload event could be raised when the window is loading?</p>
<p>One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do:</p>
<pre><code>popupWindow.onunload = function(){alert('hello')};
</code></pre>
<p>It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the <code>popupWindow.closed</code> property inside of the event to ensure the window was really closed.</p>
| [
{
"answer_id": 140183,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://developer.mozilla.org/en/DOM/window.onunload\" rel=\"nofollow noreferrer\">window.onUnload</a></p>\n"
},
{
"answer_id": 140186,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 1,
"selected": false,
"text": "<p>You'd have to have the onBeforeUnload event call a method to notify your handler. </p>\n\n<p>See this page for a demo.</p>\n\n<p><a href=\"https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm</a></p>\n"
},
{
"answer_id": 140318,
"author": "Philip Tinney",
"author_id": 14930,
"author_profile": "https://Stackoverflow.com/users/14930",
"pm_score": 2,
"selected": false,
"text": "<p>The jQuery code example for the unload event </p>\n\n<p><code>$(window).unload( function () { alert(\"Bye now!\"); } );</code></p>\n\n<p>From the <a href=\"http://docs.jquery.com/Events/unload#fn\" rel=\"nofollow noreferrer\">jQuery unload documentation</a></p>\n\n<p>Edit:</p>\n\n<p>I played around and was not able to get the parent window to be able to set the unload. The only way I could get it to work, was by having the script present in the popup window html. The popup window also needed to load jQuery. I have nothing to base this on, but I believe the unload is being triggered, because essentially the popup window is being unloaded from the scope of the parent window. Just a guess.</p>\n"
},
{
"answer_id": 140344,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<p>There's one tiny catch I have to mention in relation to the previous mentions of onunload based on my previous experience:</p>\n\n<p>Opera 9.0.x-9.2.x only runs window.onUnload if the user navigates away from a page. If the user instead closes the window, the event will never fire. I suspect this was done to combat the self-reloading popup problem (where a popup could reopen itself on page close).</p>\n\n<p>This has most likely persisted to Opera 9.5.x. Other browsers may also implement this, but I don't believe IE or Firefox do.</p>\n"
},
{
"answer_id": 1164449,
"author": "Elzo Valugi",
"author_id": 95353,
"author_profile": "https://Stackoverflow.com/users/95353",
"pm_score": 0,
"selected": false,
"text": "<p>From what I checked the jQuery unload is just a wrapper for the native function. I could be wrong as I didn't dug that deep.</p>\n\n<p>This example worked for me.</p>\n\n<pre><code>$(document).ready(function(){\n $(window).unload( function (){\n alert('preget');\n $.get(\n '/some.php',\n { request: 'some' }\n );\n alert('postget');\n });\n});\n</code></pre>\n\n<p>Remember that some <a href=\"http://msdn.microsoft.com/en-us/library/ms536973(VS.85).aspx\" rel=\"nofollow noreferrer\">browsers block the window.open requests on unload, IE for example</a>.</p>\n"
},
{
"answer_id": 2199551,
"author": "Magnus Ottosson",
"author_id": 266169,
"author_profile": "https://Stackoverflow.com/users/266169",
"pm_score": 4,
"selected": false,
"text": "<p>I created a watcher that checks if the window has been closed:</p>\n\n<pre><code>var w = window.open(\"http://www.google.com\", \"_blank\", 'top=442,width=480,height=460,resizable=yes', true);\nvar watchClose = setInterval(function() {\n if (w.closed) {\n clearTimeout(watchClose);\n //Do something here...\n }\n }, 200);\n</code></pre>\n"
},
{
"answer_id": 2381646,
"author": "rmoorman",
"author_id": 286499,
"author_profile": "https://Stackoverflow.com/users/286499",
"pm_score": 3,
"selected": false,
"text": "<p>I tried the watcher approach but ran in to the \"permission denied\" issue while using this in IE6. This happens due to the closed property not being fully accessible around the event of closing the window ... but fortunately with a try { } catch construction it works though :o)</p>\n\n<pre><code>var w = window.open(\"http://www.google.com\", \"_blank\", 'top=442,width=480,height=460,resizable=yes', true);\n\nvar watchClose = setInterval(function() {\n try {\n if (w.closed) {\n clearTimeout(watchClose);\n //Do something here...\n }\n } catch (e) {}\n}, 200);\n</code></pre>\n\n<p>Thank you magnus</p>\n"
},
{
"answer_id": 6267685,
"author": "Rodrigo Waltenberg",
"author_id": 443395,
"author_profile": "https://Stackoverflow.com/users/443395",
"pm_score": 2,
"selected": false,
"text": "<p>I think I figured out what's happening:</p>\n\n<p>When you use <code>window.open</code> it opens a new window with location \"about:blank\" and then changes it to the url you provided at the function call.</p>\n\n<p>So, the unload event is bound before the change from \"about:blank\" to the right url and is fired when the changing occurs.</p>\n\n<p>I got it working with JQuery doing this:</p>\n\n<pre><code>$(function(){\n var win = window.open('http://url-at-same-domain.com','Test', 'width=600,height=500');\n $(win).unload(function(){\n if(this.location == 'about:blank')\n {\n $(this).unload(function(){\n // do something here\n });\n }\n });\n});\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
| I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed.
```
var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
```
Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers.
**UPDATE:**
I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally.
```
var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
$(popupWindow.window).unload(function() { alert('hello'); });
```
Does anybody have any idea as to why the unload event could be raised when the window is loading?
One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do:
```
popupWindow.onunload = function(){alert('hello')};
```
It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the `popupWindow.closed` property inside of the event to ensure the window was really closed. | I created a watcher that checks if the window has been closed:
```
var w = window.open("http://www.google.com", "_blank", 'top=442,width=480,height=460,resizable=yes', true);
var watchClose = setInterval(function() {
if (w.closed) {
clearTimeout(watchClose);
//Do something here...
}
}, 200);
``` |
140,137 | <p>I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that. </p>
<p>Does anyone know how to create a custom 404 error page in Umbraco?
Is there a way to create a custom error page for runtime errors?</p>
| [
{
"answer_id": 140169,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 4,
"selected": false,
"text": "<p>In <code>/config/umbracoSettings.config</code> modify <code><error404>1</error404></code> \"<em>1</em>\" with the id of the page you want to show.</p>\n\n<pre><code><errors>\n <error404>1</error404> \n</errors>\n</code></pre>\n\n<p>Other ways to do it can be found at <a href=\"http://our.umbraco.org/wiki/how-tos/how-to-implement-your-own-404-handler\" rel=\"noreferrer\" title=\"Umbraco not found handlers\">Not found handlers</a></p>\n"
},
{
"answer_id": 1129888,
"author": "Dirk De Grave",
"author_id": 137107,
"author_profile": "https://Stackoverflow.com/users/137107",
"pm_score": 3,
"selected": false,
"text": "<p>umbraco also supports culture dependent error pages in case you're working with multilingual sites...</p>\n\n<p>Config changes a tiny bit. Instead of</p>\n\n<pre><code><errors>\n <error404>1050</error404>\n</errors>\n</code></pre>\n\n<p>you'd now write</p>\n\n<pre><code><errors>\n <errorPage culture=\"default\">1</errorPage>-->\n <errorPage culture=\"en-US\">200</errorPage>-->\n</errors>\n</code></pre>\n\n<p>Cheers,\n/Dirk</p>\n"
},
{
"answer_id": 3837977,
"author": "Shri Ganesh",
"author_id": 463711,
"author_profile": "https://Stackoverflow.com/users/463711",
"pm_score": 1,
"selected": false,
"text": "<p>First create an error page (and template) in your umbraco installation. Let us say error.aspx. Publish it. \nThen edit <strong>config/umbracoSettings.config</strong>.</p>\n\n<pre><code>Under <errors> section\n <error404>1111</error404>\n</code></pre>\n\n<p>Where <strong>1111</strong> is the <strong>umbraco node ID</strong> for the error.aspx page</p>\n\n<p>Node ID can be found by hovering mouse on the error node in <strong>content</strong> section. It's usually a 4 digit number.</p>\n\n<p>Then edit the <strong>web.config</strong>:</p>\n\n<pre><code> In <appSettings> section\n change <customErrors mode as show below:\n<customErrors mode=\"RemoteOnly\" defaultRedirect=\"~/Error.aspx\"/>\n</code></pre>\n"
},
{
"answer_id": 5789295,
"author": "marapet",
"author_id": 63733,
"author_profile": "https://Stackoverflow.com/users/63733",
"pm_score": 0,
"selected": false,
"text": "<p>Currently <code>umbracoSettings.conf</code> has to be configured the following way in order to make it work in a multilingual way:</p>\n\n<pre><code> <errors>\n <!-- the id of the page that should be shown if the page is not found -->\n <!-- <errorPage culture=\"default\">1</errorPage>-->\n <!-- <errorPage culture=\"en-US\">200</errorPage>-->\n <error404>\n <errorPage culture=\"default\">1</errorPage>\n <errorPage culture=\"ru-RU\">1</errorPage>\n <errorPage culture=\"en-US\">2</errorPage>\n </error404>\n </errors>\n</code></pre>\n\n<p>Please note the <code>error404</code> element which surrounds the <code>errorPage</code> elements, as well as the comments omitting this small yet important detail...</p>\n"
},
{
"answer_id": 10881390,
"author": "Sprague",
"author_id": 143095,
"author_profile": "https://Stackoverflow.com/users/143095",
"pm_score": 3,
"selected": false,
"text": "<p>As stated by other posters, modify the errors section as indicated (including culture if needed.) In addition, add the following in the web config to enable passthrough of errors to umbraco:</p>\n\n<p>In /config/umbracoSettings.config (the file itself explains its usage):</p>\n\n<pre><code><errors>\n <!-- the id of the page that should be shown if the page is not found -->\n <!-- <errorPage culture=\"default\">1</errorPage>-->\n <!-- <errorPage culture=\"en-US\">200</errorPage>-->\n <error404>2664</error404>\n</errors>\n</code></pre>\n\n<p>In /web.config</p>\n\n<pre><code><system.webServer>\n <!-- Some other existing stuff -->\n <httpErrors existingResponse=\"PassThrough\" />\n</system.webServer>\n</code></pre>\n\n<p>(Note: This is .NET 4)</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483/"
]
| I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that.
Does anyone know how to create a custom 404 error page in Umbraco?
Is there a way to create a custom error page for runtime errors? | In `/config/umbracoSettings.config` modify `<error404>1</error404>` "*1*" with the id of the page you want to show.
```
<errors>
<error404>1</error404>
</errors>
```
Other ways to do it can be found at [Not found handlers](http://our.umbraco.org/wiki/how-tos/how-to-implement-your-own-404-handler "Umbraco not found handlers") |
140,149 | <p>I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete?</p>
| [
{
"answer_id": 140185,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 6,
"selected": true,
"text": "<p>As far as I know, there <strong>is no way</strong> to safely delete them except programatically (they're intended for apps to create and remove during install) but it is trivial to do from a <a href=\"http://Microsoft.com/PowerShell\" rel=\"noreferrer\">PowerShell</a> command-line console. Just run this command:</p>\n\n<pre><code>[Diagnostics.PerformanceCounterCategory]::Delete( \"Your Category Name\" )\n</code></pre>\n\n<p><strong>HOWEVER: (EDIT)</strong></p>\n\n<p>You <em>can</em> delete the registry key that's created, and that will make the category vanish. </p>\n\n<p>For a category called \"Inventory\" you can delete the whole key at <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Inventory</code> ... and although <em>I wouldn't be willing to bet that cleans up everything</em>, it <strong>will</strong> make the category disappear. (If you run <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"noreferrer\">Process Monitor</a> while running the Delete() method, you can see can a lot of other activity happening, and there doesn't seem to be any other <em>changes</em> made).</p>\n\n<p>It's important to note that <strong>as I said originally</strong>: when you get that error from Visual Studio, it might be that it's already deleted and you need to refresh the view in VS. In my testing, I had to restart applications in order to get them to actually get a clean list of the available categories.</p>\n\n<p>You can check the full list of categories from PowerShell to see if it's listed:</p>\n\n<pre><code>[Diagnostics.PerformanceCounterCategory]::GetCategories() | Format-Table -auto\n</code></pre>\n\n<p>But if you check them, then delete the registry key ... they'll still show up, until you restart PowerShell (if you start another instance, you can run the same query over there, and it will NOT show the deleted item, but re-running GetCategories in the first one will continue showing it.</p>\n\n<p>By the way, you can filter that list if you want to using -like for patterns, or -match for full regular expressions:</p>\n\n<pre><code>[Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -like \"*network*\" } | Format-Table -auto\n[Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -match \"^SQL.*Stat.*\" } | Format-Table -auto\n</code></pre>\n"
},
{
"answer_id": 140240,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 0,
"selected": false,
"text": "<p>You could disable it using the microsoft resource kit tool - install it from </p>\n\n<p><a href=\"http://download.microsoft.com/download/win2000platform/exctrlst/1.00.0.1/nt5/en-us/exctrlst_setup.exe\" rel=\"nofollow noreferrer\">http://download.microsoft.com/download/win2000platform/exctrlst/1.00.0.1/nt5/en-us/exctrlst_setup.exe</a></p>\n\n<p>or disable it from the registry manually (have not tried) described here </p>\n\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/94214.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/94214.mspx?mfr=true</a></p>\n"
},
{
"answer_id": 1017515,
"author": "Kieran Benton",
"author_id": 5777,
"author_profile": "https://Stackoverflow.com/users/5777",
"pm_score": 4,
"selected": false,
"text": "<p>You could also use LinqPad, as that doesn't involve an install of any kind - <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">http://www.linqpad.net/</a>.</p>\n\n<p>Run the following code as a \"C# Statement(s)\":</p>\n\n<p><code>System.Diagnostics.PerformanceCounterCategory.Delete(\"Name of category to delete\");</code></p>\n\n<p>I'd run it twice, first time to do the actual delete, second time to get an error message to confirm the delete was successful.</p>\n"
},
{
"answer_id": 20259410,
"author": "Grant",
"author_id": 625227,
"author_profile": "https://Stackoverflow.com/users/625227",
"pm_score": 2,
"selected": false,
"text": "<p>I know this question if old but I found a way to do this non-programatically:\n<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa372130%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa372130%28v=vs.85%29.aspx</a></p>\n\n<p>Use unlodctr from command prompt, you might also need to use lodctr /q to query your category.</p>\n\n<p>Or do it the hard way by modifying the registry key (don't delete it):\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib\\009\n<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa373172%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa373172%28v=vs.85%29.aspx</a></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16881/"
]
| I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete? | As far as I know, there **is no way** to safely delete them except programatically (they're intended for apps to create and remove during install) but it is trivial to do from a [PowerShell](http://Microsoft.com/PowerShell) command-line console. Just run this command:
```
[Diagnostics.PerformanceCounterCategory]::Delete( "Your Category Name" )
```
**HOWEVER: (EDIT)**
You *can* delete the registry key that's created, and that will make the category vanish.
For a category called "Inventory" you can delete the whole key at `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Inventory` ... and although *I wouldn't be willing to bet that cleans up everything*, it **will** make the category disappear. (If you run [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) while running the Delete() method, you can see can a lot of other activity happening, and there doesn't seem to be any other *changes* made).
It's important to note that **as I said originally**: when you get that error from Visual Studio, it might be that it's already deleted and you need to refresh the view in VS. In my testing, I had to restart applications in order to get them to actually get a clean list of the available categories.
You can check the full list of categories from PowerShell to see if it's listed:
```
[Diagnostics.PerformanceCounterCategory]::GetCategories() | Format-Table -auto
```
But if you check them, then delete the registry key ... they'll still show up, until you restart PowerShell (if you start another instance, you can run the same query over there, and it will NOT show the deleted item, but re-running GetCategories in the first one will continue showing it.
By the way, you can filter that list if you want to using -like for patterns, or -match for full regular expressions:
```
[Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -like "*network*" } | Format-Table -auto
[Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -match "^SQL.*Stat.*" } | Format-Table -auto
``` |
140,162 | <p>In a servlet I do the following:</p>
<pre><code> Context context = new InitialContext();
value = (String) context.lookup("java:comp/env/propertyName");
</code></pre>
<p>On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key <em>propertyName</em>?</p>
<p>In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.</p>
| [
{
"answer_id": 143749,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 1,
"selected": false,
"text": "<p>One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more <code><env-entry></code> tags. For example, something like the following:</p>\n\n<pre><code><env-entry>\n <description>My string property</descriptor>\n <env-entry-name>propertyName</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>Your string goes here</env-entry-value>\n</env-entry>\n</code></pre>\n\n<p>Each env-entry tag declares a new environment variable that you can then access from the <code>java:comp/env</code> context.</p>\n\n<p>Once you add the necessary <code>env-entry</code>'s you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work.</p>\n"
},
{
"answer_id": 5325475,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to put your properties in a file and make the name and location of the file a resource-ref of type URL in web.xml. The value of the resource is set in geronimo-web.xml.</p>\n\n<p>Your web.xml will have the following entry:</p>\n\n<pre><code><resource-ref>\n <res-ref-name>configFileName</res-ref-name>\n <res-type>java.net.URL</res-type>\n</resource-ref>\n</code></pre>\n\n<p>In geronimo-web.xml you define the value for the configFileName</p>\n\n<pre><code><name:resource-ref>\n <name:ref-name>configFileName</name:ref-name>\n <name:url>file:///etc/myConfigFile</name:url>\n</name:resource-ref>\n</code></pre>\n\n<p>In java you have the following code to lookup the value:</p>\n\n<pre><code>initialContext = new InitialContext();\nURL url = (URL) initialContext.lookup(\"java:comp/env/configFileName\");\nString configFileName = url.getPath();\n</code></pre>\n\n<p>Then you have to open the file and read whatever value is in there.</p>\n\n<p>The result of all this is that you have the properties in a file on the filesystem. It will not be overwritten if you redeploy your application.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2985/"
]
| In a servlet I do the following:
```
Context context = new InitialContext();
value = (String) context.lookup("java:comp/env/propertyName");
```
On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key *propertyName*?
In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web. | One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more `<env-entry>` tags. For example, something like the following:
```
<env-entry>
<description>My string property</descriptor>
<env-entry-name>propertyName</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Your string goes here</env-entry-value>
</env-entry>
```
Each env-entry tag declares a new environment variable that you can then access from the `java:comp/env` context.
Once you add the necessary `env-entry`'s you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work. |
140,182 | <p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p>
<p>Right now I'm doing this...</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
</code></pre>
<p>so if I do sth like</p>
<pre><code>>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
</code></pre>
<p>It changes the (...) with 'ooo'.</p>
<p>Do you guys know whether with python regular expressions we can do this?</p>
<p>thanks a lot guys!!</p>
| [
{
"answer_id": 140208,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 1,
"selected": false,
"text": "<p>Of course. See the 'sub' and 'subn' methods of compiled regular expressions, or the 're.sub' and 're.subn' functions. You can either make it replace the matches with a string argument you give, or you can pass a callable (such as a function) which will be called to supply the replacement. See <a href=\"https://docs.python.org/library/re.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/re.html</a></p>\n"
},
{
"answer_id": 140209,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 4,
"selected": true,
"text": "<pre><code>sub (replacement, string[, count = 0])\n</code></pre>\n\n<p><a href=\"https://docs.python.org/howto/regex.html#search-and-replace\" rel=\"nofollow noreferrer\">sub</a> returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged.</p>\n\n<pre><code> p = re.compile( '(blue|white|red)')\n >>> p.sub( 'colour', 'blue socks and red shoes')\n 'colour socks and colour shoes'\n >>> p.sub( 'colour', 'blue socks and red shoes', count=1)\n 'colour socks and red shoes'\n</code></pre>\n"
},
{
"answer_id": 140218,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "<p>You want to use <a href=\"https://docs.python.org/2/library/re.html#re.sub\" rel=\"nofollow noreferrer\">re.sub</a>:</p>\n\n<pre><code>>>> import re\n>>> re.sub(r'aaa...bbb', 'aaaooobbb', \"hola aaaiiibbb como estas?\")\n'hola aaaooobbb como estas?'\n</code></pre>\n\n<p>To re-use variable parts from the pattern, use <code>\\g<n></code> in the replacement string to access the n-th <code>()</code> group:</p>\n\n<pre><code>>>> re.sub( \"(svcOrdNbr +)..\", \"\\g<1>XX\", \"svcOrdNbr IASZ0080\")\n'svcOrdNbr XXSZ0080'\n</code></pre>\n"
},
{
"answer_id": 140776,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to continue using the syntax you mentioned (replace the match value instead of replacing the part that didn't match), and considering you will only have one group, you could use the code below.</p>\n\n<pre><code>def getExpandedText(pattern, text, replaceValue):\n m = re.search(pattern, text)\n expandedText = text[:m.start(1)] + replaceValue + text[m.end(1):]\n return expandedText\n</code></pre>\n"
},
{
"answer_id": 142188,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def getExpandedText(pattern,text,*group):\n r\"\"\" Searches for pattern in the text and replaces\n all captures with the values in group.\n\n Tag renaming:\n >>> html = '<div> abc <span id=\"x\"> def </span> ghi </div>'\n >>> getExpandedText(r'</?(span\\b)[^>]*>', html, 'div')\n '<div> abc <div id=\"x\"> def </div> ghi </div>'\n\n Nested groups, capture-references:\n >>> getExpandedText(r'A(.*?Z(.*?))B', \"abAcdZefBgh\", r'<\\2>')\n 'abA<ef>Bgh'\n \"\"\"\n pattern = re.compile(pattern)\n ret = []\n last = 0\n for m in pattern.finditer(text):\n for i in xrange(0,len(m.groups())):\n start,end = m.span(i+1)\n\n # nested or skipped group\n if start < last or group[i] is None:\n continue\n\n # text between the previous and current match\n if last < start:\n ret.append(text[last:start])\n\n last = end\n ret.append(m.expand(group[i]))\n\n ret.append(text[last:])\n return ''.join(ret)\n</code></pre>\n\n<p><strong>Edit:</strong> Allow capture-references in the replacement strings.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293/"
]
| When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value...
Right now I'm doing this...
```
def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
```
so if I do sth like
```
>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
```
It changes the (...) with 'ooo'.
Do you guys know whether with python regular expressions we can do this?
thanks a lot guys!! | ```
sub (replacement, string[, count = 0])
```
[sub](https://docs.python.org/howto/regex.html#search-and-replace) returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged.
```
p = re.compile( '(blue|white|red)')
>>> p.sub( 'colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub( 'colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'
``` |
140,204 | <p>Given a typical class:</p>
<pre>
struct Whatever
{
void Doit();
};
Whatever w;
</pre>
<p>what is the best way to get the member function to be called by a C void* based callback such as pthread_create() or a signal handler ?</p>
<pre>
pthread_t pid;
pthread_create(&pid, 0, ... &w.Doit() ... );
</pre>
| [
{
"answer_id": 140230,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 1,
"selected": false,
"text": "<p>The member function MUST be static. Non-static have an implied \"this\" argument. Pass the pointer to your Whatever instance as the void* so that the static member can get at the instance.</p>\n"
},
{
"answer_id": 140232,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 3,
"selected": false,
"text": "<p>Most C callbacks allow to specify an argument e.g.</p>\n\n<pre><code>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,\n void *(*start_routine)(void*), void *arg);\n</code></pre>\n\n<p>So you could have </p>\n\n<pre><code>void myclass_doit(void* x)\n{\n MyClass* c = reinterpret_cast<MyClass*>(x);\n c->doit();\n}\n\npthread_create(..., &myclass_doit, (void*)(&obj));\n</code></pre>\n"
},
{
"answer_id": 140233,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 0,
"selected": false,
"text": "<p>See this <a href=\"http://www.newty.de/fpt/callback.html#member\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>Basically, it's not directly possible, because:\n\"Pointers to non-static members are different to ordinary C function pointers since they need the this-pointer of a class object to be passed. Thus ordinary function pointers and [pointers to] non-static member functions have different and incompatible signatures\"</p>\n"
},
{
"answer_id": 140238,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": "<p>Use a C-function wrapper like this:</p>\n\n<pre><code>struct Whatever\n{\n void Doit();\n};\n\nextern \"C\" static int DoItcallback (void * arg)\n{\n Whatever * w = (Whatever *) arg;\n w->DoIt();\n return something;\n}\n</code></pre>\n\n<p>Only works if you can pass the pointer to the class somehow. Most callback mechanisms allow this.</p>\n\n<p>Afaik this is the only method to do this. You can't directly call a method from C without lots of hacking.</p>\n"
},
{
"answer_id": 140259,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 0,
"selected": false,
"text": "<p>While I haven't used it from C, for doing callbacks, I highly recommend looking at <a href=\"http://libsigc.sourceforge.net/\" rel=\"nofollow noreferrer\">libsigc++</a>. It's been exactly what I've needed a number of times when doing C++ callbacks.</p>\n"
},
{
"answer_id": 140274,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "<p>Is the member function private? If not, use the standard idiom:</p>\n\n<pre><code>void* pthread_foo_caller(void* arg) {\n Foo* foo = static_cast<Foo*>(arg);\n foo->bar();\n return NULL;\n}\n</code></pre>\n\n<p>If the member function is private, you can declare a static method in the class that takes a \"this\" pointer and calls the appropriate method. For example: </p>\n\n<pre><code>class Foo {\n public:\n static pthread_foo_caller(void* arg);\n ...\n};\n\nvoid* Foo::pthread_foo_caller(void* arg) {\n Foo* foo = static_cast<Foo*>(arg);\n foo->private_bar();\n return NULL;\n}\n</code></pre>\n"
},
{
"answer_id": 140514,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a simple way to do it, don't forget to manage the lifetime of your \"MemberFunction\" object properly.</p>\n\n<pre><code>#include \n\nclass MyClass\n{\npublic:\n void DoStuff()\n {\n printf(\"Doing Stuff!\");\n }\n};\n\nstruct MemberFunction\n{\n virtual ~MemberFunction(){}\n virtual void Invoke() = 0;\n};\n\nvoid InvokeMember(void *ptr)\n{\n static_cast(ptr)->Invoke();\n}\n\ntemplate \nstruct MemberFunctionOnT : MemberFunction\n{\n typedef void (T::*function_t)();\npublic:\n MemberFunctionOnT(T* obj, function_t fun)\n {\n m_obj = obj;\n m_fun = fun;\n }\n\n void Invoke()\n {\n (m_obj->*m_fun)();\n }\nprivate:\n T *m_obj;\n function_t m_fun;\n};\n\ntemplate \n\nMemberFunction* NewMemberFunction(T *obj, void (T::*fun)())\n{ \n return new MemberFunctionOnT(obj, fun); \n}\n\n//simulate a C-style function offering callback functionality.\nvoid i_will_call_you_later(void (*fun)(void*), void *arg)\n{\n fun(arg);\n}\n\nint main()\n{\n //Sample usage.\n MyClass foo;\n\n MemberFunction *arg = NewMemberFunction(&foo, &MyClass::DoStuff);\n i_will_call_you_later(&InvokeMember, arg);\n return 0;\n}</code></pre>\n"
},
{
"answer_id": 141549,
"author": "keraba",
"author_id": 22725,
"author_profile": "https://Stackoverflow.com/users/22725",
"pm_score": 3,
"selected": false,
"text": "<p>The most concise solution is to define, in a header file shared by all your code:</p>\n\n<pre>\ntemplate <typename T, void (T::*M)()>\nvoid* thunk(\n void* p)\n{\n T* pt = static_cast<T*>(p);\n\n (pt->*M)();\n\n return 0;\n}\n</pre>\n\n<p>You probably want to define 4 versions: one each where the thunk returns void and void<code>*</code>, and one each where the member function returns void and void<code>*</code>. That way the compiler can match the best one, depending on the circumstances (and in fact it will complain if everything doesn't match.)</p>\n\n<p>Then all you have to type every time you run into one of these situations is:</p>\n\n<p>pthread_create(&pid, 0, &thunk<Whatever, &Whatever::doit>, &w);</p>\n\n<p>This will even work when the method is private, as long as the method is referenced from within the class's code. (If not, I have to wonder why the code is referencing a private method.)</p>\n"
},
{
"answer_id": 141662,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "<p>One thing you should be aware of is that if you write code like this:</p>\n\n<pre><code>try {\n CallIntoCFunctionThatCallsMeBack((void *)this, fCallTheDoItFunction);\n} catch (MyException &err)\n{\n stderr << \"badness.\";\n}\n\nvoid fCallTheDoItFunction(void *cookie)\n{\n MyClass* c = reinterpret_cast<MyClass*>(cookie);\n if (c->IsInvalid())\n throw MyException;\n c->DoIt();\n}\n</code></pre>\n\n<p>You may run into some serious trouble depending on your compiler. It turns out that in some compilers while optimizing, they see a single C call in a try/catch block and exclaim with joy, \"I am calling a C function that, because it is good old fashioned C, cannot throw! Calloo-cally! I shall remove all vestiges of the try/catch since it will never be reached.</p>\n\n<p>Silly compiler.</p>\n\n<p>Don't call into C that calls you back and expect to be able to catch.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22725/"
]
| Given a typical class:
```
struct Whatever
{
void Doit();
};
Whatever w;
```
what is the best way to get the member function to be called by a C void\* based callback such as pthread\_create() or a signal handler ?
```
pthread_t pid;
pthread_create(&pid, 0, ... &w.Doit() ... );
``` | Most C callbacks allow to specify an argument e.g.
```
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
```
So you could have
```
void myclass_doit(void* x)
{
MyClass* c = reinterpret_cast<MyClass*>(x);
c->doit();
}
pthread_create(..., &myclass_doit, (void*)(&obj));
``` |
140,205 | <p>I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like</p>
<pre><code>StudentID StartDate EndDate Field1 Field2
1 9/3/2007 10/20/2007 3 True
1 10/21/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
</code></pre>
<p>The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like</p>
<pre><code>StudentID StartDate EndDate Field1 Field2
1 9/3/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
</code></pre>
<p>What would be the SELECT statement for this query?</p>
| [
{
"answer_id": 140222,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "<p>In my experience, I have to combine the ranges in post-processing (not in SQL but in my script). I'm not sure that a SQL can do this, particularly because you can never know exactly how many date ranges need to be chained in any particular case. If this can be done though, I'd love to know too. </p>\n\n<p><strong>EDIT:</strong> My answer is assuming that you have more than one range of dates per student, not just a start and an end. If you only have the one date range with no gaps, then the other mentioned solutions are the way to go.</p>\n"
},
{
"answer_id": 140226,
"author": "Scott Bevington",
"author_id": 9544,
"author_profile": "https://Stackoverflow.com/users/9544",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT StudentID, MIN(startdate) AS startdate, MAX(enddate), field1, field2\nFROM tablex\nGROUP BY StudentID, field1, field2\n</code></pre>\n\n<p>That would yield you the result assuming the wasn't a gap between on student's time range.</p>\n"
},
{
"answer_id": 140227,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select StudentID, min(StartDate) StartDate, max(EndDate) EndDate, Field1, Field2 \n from table\n group by StudentID, Field1, Field2\n</code></pre>\n"
},
{
"answer_id": 140428,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 0,
"selected": false,
"text": "<p>If the min()/max() solutions are not good enough (e.g. if the dates are not contiguous and you want to group separate date ranges separately), I wonder if something using Oracle's START WITH and CONNECT BY clauses would work. Which, of course, wouldn't work on every database.</p>\n"
},
{
"answer_id": 140504,
"author": "CindyH",
"author_id": 12897,
"author_profile": "https://Stackoverflow.com/users/12897",
"pm_score": 0,
"selected": false,
"text": "<p>EDIT: Make another set of SQL for Access. I tested all of this, but piece by piece because I don't know how to make several statements at one time in Access. Since I also don't know how to do comments, you can see the comments in the SQL version, below.</p>\n\n<pre><code>select \nstudentid, min(startdate) as Starter, max(enddate) as Ender, field1, field2, \nmax(startDate) - Min(endDate) as MaxGap \ninto tempIDs\nfrom student \ngroup by studentid, field1, field2 ; \n\ndelete from tempIDs where MaxGap > 1;\n\nUPDATE student INNER JOIN TempIDs ON Student.studentID = TempIDS.StudentID\nSET Student.StartDate = [TempIDs].[Starter],\n Student.EndDate = [TempIDs].[Ender];\n</code></pre>\n\n<p>I think this is it, in SQL Server - I didn't do it in Access. I haven't tested it for fancy conditions such as overlapping several records, etc., but this should get you started. It updates all the duplicate, small-gap records, leaving extras in the database. MSDN has a page on eliminating duplicates: <a href=\"http://support.microsoft.com/kb/139444\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/139444</a></p>\n\n<pre><code>select \nstudentid, min(startdate) as StartDate, max(enddate) as EndDate, field1, field2, \ndatediff(dd, Min(endDate),max(startDate)) as MaxGap \ninto #tempIDs\nfrom #student \ngroup by studentid, field1, field2 \n\n-- Update the relevant records. Keeps two copies of the massaged record \n-- - extra will need to be deleted.\n\nupdate #student \nset startdate = #TempIDS.startdate, enddate = #tempIDS.EndDate\nfrom #tempIDS \nwhere #student.studentid = #TempIDs.StudentID and MaxGap < 2\n</code></pre>\n"
},
{
"answer_id": 140596,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": true,
"text": "<p>The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should point you in the right direction.</p>\n\n<p>You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer.</p>\n\n<pre><code>CREATE VIEW dbo.StudentStartDates\nAS\n SELECT\n S.StudentID,\n S.StartDate,\n S.Field1,\n S.Field2\n FROM\n dbo.Students S\n LEFT OUTER JOIN dbo.Students PREV ON\n PREV.StudentID = S.StudentID AND\n PREV.Field1 = S.Field1 AND\n PREV.Field2 = S.Field2 AND\n PREV.EndDate = DATEADD(dy, -1, S.StartDate)\n WHERE PREV.StudentID IS NULL\nGO\n\nCREATE VIEW dbo.StudentEndDates\nAS\n SELECT\n S.StudentID,\n S.EndDate,\n S.Field1,\n S.Field2\n FROM\n dbo.Students S\n LEFT OUTER JOIN dbo.Students NEXT ON\n NEXT.StudentID = S.StudentID AND\n NEXT.Field1 = S.Field1 AND\n NEXT.Field2 = S.Field2 AND\n NEXT.StartDate = DATEADD(dy, 1, S.EndDate)\n WHERE NEXT.StudentID IS NULL\nGO\n\n\nSELECT\n SD.StudentID,\n SD.StartDate,\n ED.EndDate,\n SD.Field1,\n SD.Field2\nFROM\n dbo.StudentStartDates SD\nINNER JOIN dbo.StudentEndDates ED ON\n ED.StudentID = SD.StudentID AND\n ED.Field1 = SD.Field1 AND\n ED.Field2 = SD.Field2 AND\n ED.EndDate > SD.StartDate AND\n NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate)\nGO\n</code></pre>\n"
},
{
"answer_id": 141443,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered a non-equi join? That would look something like this:</p>\n\n<pre><code>SELECT A.StudentID, A.StartDate, A.EndDate, A.Field1, A.Field2\nFROM tblEnrollment AS A LEFT JOIN tblEnrollment AS B ON (A.StudentID = B.StudentID) \n AND (A.EndDate=B.StartDate-1)\nWHERE B.StudentID Is Null;\n</code></pre>\n\n<p>What that gives you is all the records that don't have a corresponing record that starts the day after the ending date of the first record.</p>\n\n<p>[Caveat: Beware that you can only edit a non-equi join in the Access query designer in SQL View -- switching to Design View could cause the join to be lost (though if you do switch Access tells you about the problem, and if you immediately switch back to SQL View, you won't lose it)]</p>\n\n<p>If you then UNION that with this:</p>\n\n<pre><code>SELECT A.StudentID, A.StartDate, B.EndDate, A.Field1, A.Field2\nFROM tblEnrollment AS A INNER JOIN tblEnrollment AS B ON (A.StudentID = B.StudentID) \n AND (A.EndDate= B.StartDate-1)\n</code></pre>\n\n<p>It should give you what you need, assuming there are never more than two contiguous records at a time. I'm not sure how you'd do it if you had more than two contiguous records (it might involve looking at StartDate-1 compared to EndDate), but this might get you started in the right direction.</p>\n"
},
{
"answer_id": 141585,
"author": "Eric Ness",
"author_id": 18891,
"author_profile": "https://Stackoverflow.com/users/18891",
"pm_score": 0,
"selected": false,
"text": "<p>An alternate final query to the one provided by Tom H. in the accepted answer is</p>\n\n<pre><code>SELECT\n SD.StudentID,\n SD.StartDate,\n MIN(ED.EndDate),\n SD.Field1,\n SD.Field2\nFROM\n dbo.StudentStartDates SD\nINNER JOIN dbo.StudentEndDates ED ON\n ED.StudentID = SD.StudentID AND\n ED.Field1 = SD.Field1 AND\n ED.Field2 = SD.Field2 AND\n ED.EndDate > SD.StartDate\nGROUP BY\n SD.StudentID, SD.Field1, SD.Field2, SD.StartDate\n</code></pre>\n\n<p>This also worked on all test data.</p>\n"
},
{
"answer_id": 148486,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": -1,
"selected": false,
"text": "<p>This is a classic problem in SQL (the language) e.g. covered in Joe Celko's books 'SQL for Smarties\" (chapter 23, Regions, Runs, Gaps, Sequences and Series) and his latest book \"Thinking in Sets\" (chapter 15). </p>\n\n<p>While it's 'fun' to fix the data at run time with a monster query, for me this is one of those situations that can be better fixed off line and procedurally (personally I'd do it with formulas in an Excel spreadsheet). </p>\n\n<p>The important thing is to put in place effective database constraints to prevent the overlapping periods reoccurring. Again, writing sequenced constraints in SQL is a classic: see Snodgrass (<a href=\"http://www.cs.arizona.edu/people/rts/tdbbook.pdf\" rel=\"nofollow noreferrer\">http://www.cs.arizona.edu/people/rts/tdbbook.pdf</a>). Hint for MS Access users: you'll need to use CHECK constraints.</p>\n"
},
{
"answer_id": 2878224,
"author": "Daniel P",
"author_id": 346593,
"author_profile": "https://Stackoverflow.com/users/346593",
"pm_score": 0,
"selected": false,
"text": "<p>Heres an example with test data using SQL Server 2005/2008 syntax.</p>\n\n<pre><code>DECLARE @Data TABLE(\n CalendarDate datetime )\n\nINSERT INTO @Data( CalendarDate )\n-- range start\nSELECT '1 Jan 2010'\nUNION ALL SELECT '2 Jan 2010'\nUNION ALL SELECT '3 Jan 2010'\n-- range start\nUNION ALL SELECT '5 Jan 2010'\n-- range start\nUNION ALL SELECT '7 Jan 2010'\nUNION ALL SELECT '8 Jan 2010'\nUNION ALL SELECT '9 Jan 2010'\nUNION ALL SELECT '10 Jan 2010'\n\nSELECT DateGroup, Min( CalendarDate ) AS StartDate, Max( CalendarDate ) AS EndDate\nFROM( SELECT NextDay.CalendarDate, \n DateDiff( d, RangeStart.CalendarDate, NextDay.CalendarDate ) - ROW_NUMBER() OVER( ORDER BY NextDay.CalendarDate ) AS DateGroup\n FROM( SELECT Min( CalendarDate ) AS CalendarDate\n FROM @data ) AS RangeStart\n JOIN @data AS NextDay\n ON NextDay.CalendarDate >= RangeStart.CalendarDate ) A\nGROUP BY DateGroup\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18891/"
]
| I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like
```
StudentID StartDate EndDate Field1 Field2
1 9/3/2007 10/20/2007 3 True
1 10/21/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
```
The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like
```
StudentID StartDate EndDate Field1 Field2
1 9/3/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
```
What would be the SELECT statement for this query? | The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should point you in the right direction.
You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer.
```
CREATE VIEW dbo.StudentStartDates
AS
SELECT
S.StudentID,
S.StartDate,
S.Field1,
S.Field2
FROM
dbo.Students S
LEFT OUTER JOIN dbo.Students PREV ON
PREV.StudentID = S.StudentID AND
PREV.Field1 = S.Field1 AND
PREV.Field2 = S.Field2 AND
PREV.EndDate = DATEADD(dy, -1, S.StartDate)
WHERE PREV.StudentID IS NULL
GO
CREATE VIEW dbo.StudentEndDates
AS
SELECT
S.StudentID,
S.EndDate,
S.Field1,
S.Field2
FROM
dbo.Students S
LEFT OUTER JOIN dbo.Students NEXT ON
NEXT.StudentID = S.StudentID AND
NEXT.Field1 = S.Field1 AND
NEXT.Field2 = S.Field2 AND
NEXT.StartDate = DATEADD(dy, 1, S.EndDate)
WHERE NEXT.StudentID IS NULL
GO
SELECT
SD.StudentID,
SD.StartDate,
ED.EndDate,
SD.Field1,
SD.Field2
FROM
dbo.StudentStartDates SD
INNER JOIN dbo.StudentEndDates ED ON
ED.StudentID = SD.StudentID AND
ED.Field1 = SD.Field1 AND
ED.Field2 = SD.Field2 AND
ED.EndDate > SD.StartDate AND
NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate)
GO
``` |
140,217 | <p>As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier?</p>
| [
{
"answer_id": 140316,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "<p>In general you find something that isn't how it should be, and work backwards until you understand why.</p>\n\n<p>The most obvious is the most useful: Setting a breakpoint on a function or line number and walking through the code line by line.</p>\n\n<p>Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb:</p>\n\n<pre><code>gdb> p show_my_struct(struct)\n\nMy custom display of Foo:\n ...\n</code></pre>\n\n<p>Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.:</p>\n\n<pre><code>gdb> watch foo\nWatchpoint4: foo\ngdb>\n</code></pre>\n"
},
{
"answer_id": 140448,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 2,
"selected": false,
"text": "<p>Some hints:</p>\n\n<ul>\n<li>use a graphical frontend (kdbg is quite good, ddd is at least better than command-line gdb, kdevelop has a nice gdb frontend but has some bgs, nemiver looks quite nice as well but is still in the works)</li>\n<li>make sure to have debug symbols and source code for all important parts (your own code and also some system libs)\n\n<ul>\n<li>on RedHat, you can install the -debuginfo packages to make both symbols and source code magically appear in the debugger - really cool because you can looks into libc function calls etc.</li>\n<li>on Debian/Ubuntu, you can install the -dbg packages to get symbols; installing appropriate source files for system packages seems to be difficult, though</li>\n</ul></li>\n<li>I tend to add assert() and abort() calls in places that should not be reached, or in places that I want to study (some kind of heavy-weight breakpoint)</li>\n<li>ideally the assert() or abort() calls should be wrapped in some method or macro that only enables them in Debug releases, or even better that only enables them if a certain env var is set</li>\n<li>install a signal handler for SIGSEGV and SIGABRT; personally I check if a certain env var is set before installing the handlers; and in the handler I execute a hardcoded external command which usually lives somewhere in ~/.local/bin/; that command might then start kdbg and attach it to the crashing app. Voila, debugger pops up the moment your app does something bad.</li>\n<li>If you use unit tests, you could similarly attach a debugger whenever a test case fails, to inspect the app then.</li>\n</ul>\n"
},
{
"answer_id": 217038,
"author": "Rob Kam",
"author_id": 25093,
"author_profile": "https://Stackoverflow.com/users/25093",
"pm_score": 0,
"selected": false,
"text": "<p>Use ddd, a visual front-end for gdb. It lets you do things easily with a few mouse clicks and visualise how the code works, plus in the debugger console you have an intercative gdb.</p>\n"
},
{
"answer_id": 236846,
"author": "codeguru",
"author_id": 31476,
"author_profile": "https://Stackoverflow.com/users/31476",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use <a href=\"http://www.geany.org\" rel=\"nofollow noreferrer\">Geany</a>.</p>\n"
},
{
"answer_id": 270911,
"author": "Emerick Rogul",
"author_id": 33837,
"author_profile": "https://Stackoverflow.com/users/33837",
"pm_score": 2,
"selected": false,
"text": "<p>One particularly useful feature of gdb is its ability to inspect the final state of a program that's crashed.</p>\n\n<p>To inspect a crash dump (or core file, as it's more commonly called), start gdb as follows:</p>\n\n<p><kbd>gdb <program-name> <core-file></kbd></p>\n\n<p>For example:</p>\n\n<p><kbd>gdb a.out core</kbd></p>\n\n<p>Upon running this command on a core file, gdb will tell you how the program terminated and display where in the program the error occurred:</p>\n\n<pre><code>Program terminated with signal 11, Segmentation fault.\n#0 0x08048364 in foo () at foo.c:4\n4 *x = 100;\n</code></pre>\n\n<p>In the example above, you can see that the program terminated with a segmentation fault while trying to assign a value to a pointer. By typing <kbd>backtrace</kbd> (or <kbd>bt</kbd> or <kbd>where</kbd>) at gdb's prompt, you can view the program's complete backtrace:</p>\n\n<pre><code>(gdb) backtrace\n#0 0x08048364 in foo () at foo.c:4\n#1 0x0804837f in main () at foo.c:9\n</code></pre>\n\n<p>At this point, you know that <code>main()</code> called <code>foo()</code> and <code>foo()</code> crashed on line 4 while trying to assign a value to <code>*x</code>. Many times, this provides enough information to allow you to fix the bug.</p>\n"
},
{
"answer_id": 270991,
"author": "Jim Keener",
"author_id": 35338,
"author_profile": "https://Stackoverflow.com/users/35338",
"pm_score": 1,
"selected": false,
"text": "<p>I do a lot of parallel-program dev, so I've found that using a simple wrapper in python/ruby that allows me to have gdb attached to all processes on all nodes and communicating back to me is extraordinarily helpful (I haven't found a better way if anyone knows of one, not to hijack the thread, though...)</p>\n\n<p>I'm not sure how experienced the OP is, so:</p>\n\n<p>The GDB docs are pretty nice and all encompassing. The first chapter is a good introduction to all the basics.</p>\n\n<p><a href=\"http://www.gnu.org/software/gdb/documentation/\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/gdb/documentation/</a></p>\n\n<p>Although not gdb, they are related:\nI've personally found that breaking complex lines down to aid in determining which statements are erroring helps.</p>\n\n<p>Also, Valgrind (<a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">http://valgrind.org/</a>) is really nice/usefull for tackling buffer-overflows and the like (I haven't had luck with gdb for doing this.</p>\n"
},
{
"answer_id": 271866,
"author": "John Carter",
"author_id": 8331,
"author_profile": "https://Stackoverflow.com/users/8331",
"pm_score": 1,
"selected": false,
"text": "<p>Basic but very useful - Use the <a href=\"http://davis.lbl.gov/Manuals/GDB/gdb_21.html\" rel=\"nofollow noreferrer\">text gui</a> with the option -tui.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16044/"
]
| As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier? | In general you find something that isn't how it should be, and work backwards until you understand why.
The most obvious is the most useful: Setting a breakpoint on a function or line number and walking through the code line by line.
Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb:
```
gdb> p show_my_struct(struct)
My custom display of Foo:
...
```
Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.:
```
gdb> watch foo
Watchpoint4: foo
gdb>
``` |
140,303 | <p>What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links).</p>
<p>FWIW, I'm not running a web farm.</p>
<h2>Exception</h2>
<blockquote>
<p>Error Message: Unable to validate
data.</p>
<p>Error Source: System.Web</p>
<p>Error Target Site: Byte[]
GetDecodedData(Byte[], Byte[], Int32,
Int32, Int32 ByRef)</p>
</blockquote>
<h2>Post Data</h2>
<blockquote>
<p><em>VIEWSTATE:</em></p>
<p>/wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB</p>
<p><em>EVENTVALIDATION:</em></p>
<p>/wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg=</p>
</blockquote>
<h2>Exception Stack Trace</h2>
<pre><code> at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.default_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code></pre>
<p>~ William Riley-Land</p>
| [
{
"answer_id": 140517,
"author": "Chris Van Opstal",
"author_id": 7264,
"author_profile": "https://Stackoverflow.com/users/7264",
"pm_score": 5,
"selected": true,
"text": "<p>The most likely cause of this error is when a postback is stopped before all the viewstate loads (the user hits the stop or back buttons), the viewstate will fail to validate and throw the error. </p>\n\n<p>Other potential causes:</p>\n\n<ul>\n<li>An application pool recycling between the time the viewstate was generated and the time that the user posts it back to the server (unlikely).</li>\n<li>A web farm where the machineKeys are not synchronized (not your issue).</li>\n</ul>\n\n<p>Update: <a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;555353\" rel=\"noreferrer\">Microsoft article on the issue</a>. In addition to the above they suggest two other potential causes:</p>\n\n<ul>\n<li>Modification of viewstate by firewalls/anti-virus software</li>\n<li>Posting from one aspx page to another.</li>\n</ul>\n"
},
{
"answer_id": 140684,
"author": "Jon Adams",
"author_id": 2291,
"author_profile": "https://Stackoverflow.com/users/2291",
"pm_score": 3,
"selected": false,
"text": "<p>I've experienced the issue with certain specific versions of Safari 3. My solution was to move the ViewState to the top of the form (extended the Page class and overwrote the Render method for pre-3.5 SP1, or .Net 3.5 SP1 and later does this by default), and to split up the ViewState to several different fields instead of one monster file. <em>See <a href=\"http://weblogs.asp.net/lduveau/archive/2007/04/17/viewstate-chunking-in-asp-net-2-0-maxpagestatefieldlength.aspx\" rel=\"noreferrer\">ViewState Chunking in ASP.NET 2.0 (maxPageStateFieldLength)</a></em></p>\n"
},
{
"answer_id": 141419,
"author": "Raelshark",
"author_id": 19678,
"author_profile": "https://Stackoverflow.com/users/19678",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>\"a postback is stopped before all the viewstate loads\"</p>\n</blockquote>\n\n<p>I've had this exact problem before, and this was the cause. </p>\n\n<p>Initially we disabled the ViewStateMac property (<code>enableViewStateMac=\"false\"</code> in the <code>page</code> directive) to solve it, but this is not a true solution to the problem and can threaten data integrity. We ultimately resolved it by disabled our submit button until the page had completely loaded, and trimming the size of our viewstate by disabling it on some controls.</p>\n"
},
{
"answer_id": 254581,
"author": "Jeffrey Harrington",
"author_id": 4307,
"author_profile": "https://Stackoverflow.com/users/4307",
"pm_score": 3,
"selected": false,
"text": "<p>In .NET 3.5 SP1 the <em>RenderAllHiddenFieldsAtTopOfForm</em> property was added to the PagesSection configuration. </p>\n\n<p><strong>Web.config</strong></p>\n\n<pre><code><configuration>\n\n <system.web>\n\n <pages renderAllHiddenFieldsAtTopOfForm=\"true\"></pages>\n\n </system.web>\n\n</configuration>\n</code></pre>\n\n<p>Interestingly, the default value of this is true. So, in essence, if you are using .NET 3.5 SP1 then the ViewState is automatically being rendered at the top of the form (before the rest of the page is loaded) thus eliminating the ViewState error you are getting.</p>\n"
},
{
"answer_id": 711636,
"author": "Techgration",
"author_id": 35130,
"author_profile": "https://Stackoverflow.com/users/35130",
"pm_score": 2,
"selected": false,
"text": "<p>I got this error when I had a form tag setup on my page without an action attribute, and then in the code-behind, I changed the form's action attribute to \"Action.aspx\". </p>\n\n<p>And in JavaScript, I submitted the form (theForm.submit();)</p>\n\n<p>I think in my case it was a security issue, and that you can't change this after it's already been set on the page... ?</p>\n"
},
{
"answer_id": 2963301,
"author": "ileon",
"author_id": 269595,
"author_profile": "https://Stackoverflow.com/users/269595",
"pm_score": 2,
"selected": false,
"text": "<p>I've found the root of this problem in my web site and I finally managed to <strong>solve</strong> it. This is not a direct answer to your question, but I wanted to share this little piece of information. </p>\n\n<p>In the past I tried everything (including the solution proposed by Jeffaxe, above) but with no result, and I didn't want to set <code>enableViewStateMac=\"false\"</code> (as Raelshark mentions above) to my page, because this just hides the problem.</p>\n\n<p>What caused the problem in my case? The problem was caused by the use of the <strong>Intelligencia.UrlRewriter</strong> (Version 2.0 RC 1 build 6) module in certain pages of my web site. I was using some SEO friendly links and that was causing the ViewState validation failure. When I used \"normal\" links (instead of the SEO-friendly links) the problem disappeared! </p>\n\n<p>I reproduced the problem a few times to make sure it was not a false alarm (I use ASP.NET 3.5).</p>\n\n<p>I know that some of you may not use the above module, and still get this error, which implies that the cause is something else. At least, sharing this experience might be helpful to some. </p>\n"
},
{
"answer_id": 4658306,
"author": "MrM",
"author_id": 54197,
"author_profile": "https://Stackoverflow.com/users/54197",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this would help anyone, but my solution was the exclusion of the machineKey in my webconfig for my cookie to get passed.</p>\n"
},
{
"answer_id": 7155976,
"author": "Todd",
"author_id": 830424,
"author_profile": "https://Stackoverflow.com/users/830424",
"pm_score": 2,
"selected": false,
"text": "<p>This free online tool: <a href=\"http://aspnetresources.com/tools/machineKey\" rel=\"nofollow\">http://aspnetresources.com/tools/machineKey</a> generates a machineKey element under the system.web element in the web.config file.\nHere is an example of what it generates:</p>\n\n<pre><code><machineKey validationKey=\"1619AB2FDEE6B943AD5D31DD68B7EBDAB32682A5891481D9403A6A55C4F91A340131CB4F4AD26A686DF5911A6C05CAC89307663656B62BE304EA66605156E9B5\" decryptionKey=\"C9D165260E6A697B2993D45E05BD64386445DE01031B790A60F229F6A2656ECF\" validation=\"SHA1\" decryption=\"AES\" />\n</code></pre>\n\n<hr>\n\n<p>Once you see this in your web.config, the error itself suddenly makes sense.\nThe error you are getting says </p>\n\n<blockquote>\n <p>\"ensure that configuration specifies the same\n validationKey and validation algorithm\".</p>\n</blockquote>\n\n<p>When you look at this machineKey element, suddenly you can see what it is talking about.</p>\n\n<hr>\n\n<p>By \"hard coding\" this value in your web.config, the key that asp.net uses to serialize and deserialize your viewstate stays the same, no matter which server in a server farm picks it up. Your encryption becomes \"portable\", thus your viewstate becomes \"portable\".</p>\n\n<p>I'm just guessing also that maybe the <em>very same server</em> (not in a farm) has this problem if for any reason it \"forgets\" the key it had, due to a reset on any level that wipes it out. That is perhaps why you see this error after an idle period and you try to use a \"stale\" page.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17847/"
]
| What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links).
FWIW, I'm not running a web farm.
Exception
---------
>
> Error Message: Unable to validate
> data.
>
>
> Error Source: System.Web
>
>
> Error Target Site: Byte[]
> GetDecodedData(Byte[], Byte[], Int32,
> Int32, Int32 ByRef)
>
>
>
Post Data
---------
>
> *VIEWSTATE:*
>
>
> /wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB
>
>
> *EVENTVALIDATION:*
>
>
> /wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg=
>
>
>
Exception Stack Trace
---------------------
```
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.default_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
```
~ William Riley-Land | The most likely cause of this error is when a postback is stopped before all the viewstate loads (the user hits the stop or back buttons), the viewstate will fail to validate and throw the error.
Other potential causes:
* An application pool recycling between the time the viewstate was generated and the time that the user posts it back to the server (unlikely).
* A web farm where the machineKeys are not synchronized (not your issue).
Update: [Microsoft article on the issue](http://support.microsoft.com/default.aspx?scid=kb;en-us;555353). In addition to the above they suggest two other potential causes:
* Modification of viewstate by firewalls/anti-virus software
* Posting from one aspx page to another. |
140,329 | <p>I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help.</p>
<p>Thanks!</p>
| [
{
"answer_id": 140398,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 3,
"selected": false,
"text": "<p>I usually add an HtmlMeta control to the Page.Header.Controls collection on the master page when the user has \"logged in\". Set it to Refresh to your SessionExpired.aspx page with an appropriate timeout length, and you're good to go.</p>\n"
},
{
"answer_id": 140413,
"author": "Pablo Marambio",
"author_id": 18552,
"author_profile": "https://Stackoverflow.com/users/18552",
"pm_score": 2,
"selected": false,
"text": "<p>The other way is to tell the browser to redirect itself (via javascript) after a certain amount of time... but that can always be deactivated by the user.</p>\n"
},
{
"answer_id": 140425,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 0,
"selected": false,
"text": "<p>Add or update your Web.Config file to include this or something similar:</p>\n\n<pre><code><customErrors defaultRedirect=\"url\" mode=\"RemoteOnly\">\n <error statusCode=\"408\" redirect=\"~/SessionExpired.aspx\"/>\n</customErrors>\n</code></pre>\n"
},
{
"answer_id": 140435,
"author": "Gabe Sumner",
"author_id": 12689,
"author_profile": "https://Stackoverflow.com/users/12689",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand correctly, \"Session_End\" fires internally and does not have an HTTP context associated with it:</p>\n\n<p><a href=\"http://forums.asp.net/t/1271309.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/t/1271309.aspx</a></p>\n\n<p>Therefore I don't think you could use it to redirect the user. I've seen others suggest using the \"Session_OnStart()\" event in the global.ascx file:</p>\n\n<p><a href=\"http://forums.asp.net/p/1083259/1606991.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1083259/1606991.aspx</a></p>\n\n<p>I have not tried it, but putting the following code in \"global.ascx\" might work for you:</p>\n\n<pre><code>void Session_OnStart() {\n if (Session.IsNewSession == false )\n {\n }\n else \n {\n Server.Transfer(\"SessionExpired.aspx\", False);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 140702,
"author": "Simon Forrest",
"author_id": 4733,
"author_profile": "https://Stackoverflow.com/users/4733",
"pm_score": 1,
"selected": false,
"text": "<p>You can't redirect the user when the session expires because there's no browser request to redirect:</p>\n\n<ul>\n<li>If the user visits your site within the session timeout (20 minutes by default), the session hasn't ended, therefore you don't need to redirect them.</li>\n<li>If the user visits your site after the session has timed out, the session has already ended. This means that they will be in the context of a new session - Session_OnEnd will already have fired for the old session and instead you'll be getting Session_OnStart for the new session.</li>\n</ul>\n\n<p>Other than a client-side feature (eg JavaScript timer etc), you therefore need to handle the redirect in a Session_OnStart instead - but obviously you need to distinguish this from someone coming to the site afresh. One option is to set a session cookie when their session starts (ie a cookie with no expiry so that it only lasts until the browser is closed), then look for that cookie in Session_OnStart - if it's present it is a returning user with an expired session, if not it's a new user.</p>\n\n<p>Obviously you can still use Session_OnEnd to tidy up on the server side - it's just the client interaction that isn't available to you.</p>\n"
},
{
"answer_id": 140703,
"author": "Micky McQuade",
"author_id": 12908,
"author_profile": "https://Stackoverflow.com/users/12908",
"pm_score": 1,
"selected": false,
"text": "<p>Are you putting something in the Session object that should always be there? In other words, if they log in, you may be putting something like UserID in the session</p>\n\n<pre><code>Session(\"UserID\") = 1234\n</code></pre>\n\n<p>So, if that is the case, then you could add something to your codebehind in the master page that checks for that value. Something like this:</p>\n\n<pre><code>Dim UserID As Integer = 0\nInteger.TryParse(Session(\"UserID\"), UserID)\n\nIf UserID = 0 Then\n Response.Redirect(\"/sessionExpired.aspx\")\nEnd If\n</code></pre>\n"
},
{
"answer_id": 140792,
"author": "CSharpAtl",
"author_id": 11907,
"author_profile": "https://Stackoverflow.com/users/11907",
"pm_score": 2,
"selected": false,
"text": "<p>We use Forms Authentication and call this method in the Page_Load method</p>\n\n<pre><code>private bool IsValidSession()\n {\n bool isValidSession = true;\n if (Context.Session != null)\n {\n if (Session.IsNewSession)\n {\n string cookieHeader = Request.Headers[\"Cookie\"];\n if ((null != cookieHeader) && (cookieHeader.IndexOf(\"ASP.NET_SessionId\") >= 0))\n {\n isValidSession = false;\n if (User.Identity.IsAuthenticated)\n FormsAuthentication.SignOut();\n FormsAuthentication.RedirectToLoginPage();\n }\n }\n }\n return isValidSession;\n }\n</code></pre>\n"
},
{
"answer_id": 140801,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 4,
"selected": true,
"text": "<p>You can handle this in global.asax in the Session_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired:</p>\n\n<pre><code> public void Session_OnStart()\n {\n if (HttpContext.Current.Request.Cookies.Contains(\"ASP.NET_SessionId\") != null)\n {\n HttpContext.Current.Response.Redirect(\"SessionTimeout.aspx\")\n }\n\n }\n</code></pre>\n\n<p>Alas I have not found any elegant way of finding out the name of the session cookie.</p>\n"
},
{
"answer_id": 141009,
"author": "Jeremy Frey",
"author_id": 13412,
"author_profile": "https://Stackoverflow.com/users/13412",
"pm_score": 0,
"selected": false,
"text": "<p>Are you looking to redirect on the next request, or redirect immediately, without user intervention? If you're looking to redirect without user intervention, then you can use ClientScript.RegisterStartupScript on your Master Page to inject a bit of javascript that will redirect your clients when their session expires.</p>\n\n<pre><code> System.Text.StringBuilder sb = new System.Text.StringBuilder();\n String timeoutPage = \"SessionExpired.aspx\"; // your page here\n int timeoutPeriod = Session.Timeout * 60 * 1000;\n\n sb.AppendFormat(\"setTimeout(\\\"location.href = {0};\\\",{1});\", timeoutPage, timeoutPeriod);\n Page.ClientScript.RegisterStartupScript(this.GetType(), \"timeourRedirect\", sb.ToString(), true);\n</code></pre>\n"
},
{
"answer_id": 202691,
"author": "TheEmirOfGroofunkistan",
"author_id": 1874,
"author_profile": "https://Stackoverflow.com/users/1874",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.eggheadcafe.com/articles/20051228.asp\" rel=\"nofollow noreferrer\">Code from here</a></p>\n\n<pre><code>namespace PAB.WebControls\n</code></pre>\n\n<p>{\n using System;\n using System.ComponentModel;\n using System.Web;\n using System.Web.Security;\n using System.Web.UI;</p>\n\n<pre><code>[DefaultProperty(\"Text\"),\n\n ToolboxData(\"<{0}:SessionTimeoutControl runat=server></{0}:SessionTimeoutControl>\")]\n\npublic class SessionTimeoutControl : Control\n{\n private string _redirectUrl;\n\n [Bindable(true),\n Category(\"Appearance\"),\n DefaultValue(\"\")]\n public string RedirectUrl\n {\n get { return _redirectUrl; }\n\n set { _redirectUrl = value; }\n }\n\n public override bool Visible\n {\n get { return false; }\n\n }\n\n public override bool EnableViewState\n {\n get { return false; }\n }\n\n protected override void Render(HtmlTextWriter writer)\n {\n if (HttpContext.Current == null)\n\n writer.Write(\"[ *** SessionTimeout: \" + this.ID + \" *** ]\");\n\n base.Render(writer);\n }\n\n\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n\n if (this._redirectUrl == null)\n\n throw new InvalidOperationException(\"RedirectUrl Property Not Set.\");\n\n if (Context.Session != null)\n {\n if (Context.Session.IsNewSession)\n {\n string sCookieHeader = Page.Request.Headers[\"Cookie\"];\n\n if ((null != sCookieHeader) && (sCookieHeader.IndexOf(\"ASP.NET_SessionId\") >= 0))\n {\n if (Page.Request.IsAuthenticated)\n {\n FormsAuthentication.SignOut();\n }\n\n Page.Response.Redirect(this._redirectUrl);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 61451323,
"author": "Avdhoota",
"author_id": 4547325,
"author_profile": "https://Stackoverflow.com/users/4547325",
"pm_score": 1,
"selected": false,
"text": "<p>You can also check the solutions provided in below link</p>\n\n<p><a href=\"http://csharpdotnetfreak.blogspot.com/2008/11/detecting-session-timeout-and-redirect.html\" rel=\"nofollow noreferrer\">Detecting Session Timeout And Redirect To Login Page In ASP.NET</a></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14710/"
]
| I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help.
Thanks! | You can handle this in global.asax in the Session\_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired:
```
public void Session_OnStart()
{
if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null)
{
HttpContext.Current.Response.Redirect("SessionTimeout.aspx")
}
}
```
Alas I have not found any elegant way of finding out the name of the session cookie. |
140,331 | <p>I have a following SQL Server 2005 database schema:</p>
<pre><code>CREATE TABLE Messages (
MessageID int,
Subject varchar(500),
Text varchar(max) NULL,
UserID NULL
)
</code></pre>
<p>The column "UserID" - which can be null - is a foreign key and links to the table</p>
<pre><code>CREATE TABLE Users (
UserID int,
...
)
</code></pre>
<p>Now I have several POCO classes with names Message, User etc. that I use in the following query:</p>
<pre><code>public IList<Message> GetMessages(...) {
var q = (from m in dataContext.Messages.Include("User")
where ...
select m); // could call ToList(), but...
return (from m in q
select new Message {
ID = m.MessageID,
User = new User {
ID = m.User.UserID,
FirstName = m.User.FirstName,
...
}
}).ToList();
}
</code></pre>
<p>Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database. </p>
<p>Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL.</p>
<p>If I change the last couple of lines to</p>
<pre><code>return (from m in q
select new Message {
ID = m.MessageID,
User = m.User == null ? null : new User {
ID = m.User.UserID,
...
}
}).ToList()
</code></pre>
<p>then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported.</p>
<p>Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks.</p>
| [
{
"answer_id": 140385,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": -1,
"selected": false,
"text": "<p>I suspect your relationship is not 1 to 1.</p>\n"
},
{
"answer_id": 140424,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>Since you did an <code>.Include(\"Users\")</code> you should be able to just traverse the <code>User</code> property in the <code>Message</code> object to get the information your want.</p>\n"
},
{
"answer_id": 151953,
"author": "KristoferA",
"author_id": 11241,
"author_profile": "https://Stackoverflow.com/users/11241",
"pm_score": 2,
"selected": false,
"text": "<p>You forgot to include the declaration of your \"Message\" class but I suspect that the UserID property in that class is not declared as a nullable type. If that is the case, change it from \"int\" to \"int?\" (nullable int).</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a following SQL Server 2005 database schema:
```
CREATE TABLE Messages (
MessageID int,
Subject varchar(500),
Text varchar(max) NULL,
UserID NULL
)
```
The column "UserID" - which can be null - is a foreign key and links to the table
```
CREATE TABLE Users (
UserID int,
...
)
```
Now I have several POCO classes with names Message, User etc. that I use in the following query:
```
public IList<Message> GetMessages(...) {
var q = (from m in dataContext.Messages.Include("User")
where ...
select m); // could call ToList(), but...
return (from m in q
select new Message {
ID = m.MessageID,
User = new User {
ID = m.User.UserID,
FirstName = m.User.FirstName,
...
}
}).ToList();
}
```
Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database.
Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL.
If I change the last couple of lines to
```
return (from m in q
select new Message {
ID = m.MessageID,
User = m.User == null ? null : new User {
ID = m.User.UserID,
...
}
}).ToList()
```
then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported.
Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks. | You forgot to include the declaration of your "Message" class but I suspect that the UserID property in that class is not declared as a nullable type. If that is the case, change it from "int" to "int?" (nullable int). |
140,347 | <p>I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!</p>
<p>Does anyone know what it is?</p>
<p>It will do something similar to:</p>
<pre><code>const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowPos(...)
</code></pre>
| [
{
"answer_id": 140373,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>You're probably thinking of <a href=\"http://msdn.microsoft.com/en-us/library/ms632667(VS.85).aspx\" rel=\"noreferrer\"><code>AdjustWindowRectEx()</code></a>. Keep in mind, this is intended for use when <em>creating</em> a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use <a href=\"http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx\" rel=\"noreferrer\"><code>GetWindowRect()</code></a>.</p>\n"
},
{
"answer_id": 140377,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 0,
"selected": false,
"text": "<p>Is this what you are looking for?</p>\n\n<p>ClientToScreen</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms532670(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms532670(VS.85).aspx</a></p>\n"
},
{
"answer_id": 147110,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to map client co-ordinates to window co-ordinates use the <strong>ClientToWindow</strong> API. </p>\n\n<p>If you want to map client co-ordinates to screen co-ordinates use the <strong>ClientToScreen</strong> API.</p>\n"
},
{
"answer_id": 21004956,
"author": "aMarCruz",
"author_id": 3174665,
"author_profile": "https://Stackoverflow.com/users/3174665",
"pm_score": 0,
"selected": false,
"text": "<p>For control reposition use:</p>\n\n<pre><code>RECT client;\n::SetRect(&client, 0, 0, 200, 200);\n::MapWindowPoints(hwndControl, ::GetParent(hwndControl), (POINT*)&client, 2);\n::SetWindowPos(...)\n</code></pre>\n"
},
{
"answer_id": 66902466,
"author": "akovar",
"author_id": 3688137,
"author_profile": "https://Stackoverflow.com/users/3688137",
"pm_score": 0,
"selected": false,
"text": "<p>This will give you window rect in client coordinates, so you can use rect(top,left) as offset</p>\n<pre><code>CRect rectFrame;\nGetWindowRect(&rectFrame);\nScreenToClient(&rectFrame);\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
]
| I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!
Does anyone know what it is?
It will do something similar to:
```
const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowPos(...)
``` | You're probably thinking of [`AdjustWindowRectEx()`](http://msdn.microsoft.com/en-us/library/ms632667(VS.85).aspx). Keep in mind, this is intended for use when *creating* a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use [`GetWindowRect()`](http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx). |
140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>[email protected] password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| [
{
"answer_id": 140495,
"author": "1729",
"author_id": 4319,
"author_profile": "https://Stackoverflow.com/users/4319",
"pm_score": 7,
"selected": true,
"text": "<p>I was missing </p>\n\n<pre><code>l.set_option(ldap.OPT_REFERRALS, 0)\n</code></pre>\n\n<p>From the init.</p>\n"
},
{
"answer_id": 140737,
"author": "Johan Buret",
"author_id": 15366,
"author_profile": "https://Stackoverflow.com/users/15366",
"pm_score": 0,
"selected": false,
"text": "<p>Use a Distinguished Name to log on your system.<code>\"CN=Your user,CN=Users,DC=b2t,DC=local\"</code>\nIt should work on any LDAP system, including AD</p>\n"
},
{
"answer_id": 141729,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 5,
"selected": false,
"text": "<p>If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server:</p>\n\n<pre><code>import win32security\ntoken = win32security.LogonUser(\n username,\n domain,\n password,\n win32security.LOGON32_LOGON_NETWORK,\n win32security.LOGON32_PROVIDER_DEFAULT)\nauthenticated = bool(token)\n</code></pre>\n"
},
{
"answer_id": 153339,
"author": "Daniel Bungert",
"author_id": 21093,
"author_profile": "https://Stackoverflow.com/users/21093",
"pm_score": 2,
"selected": false,
"text": "<p>I see your comment to @Johan Buret about the DN not fixing your problem, but I also believe that is what you should look into.</p>\n\n<p>Given your example, the DN for the default administrator account in AD will be:\ncn=Administrator,cn=Users,dc=mydomain,dc=co,dc=uk - please try that.</p>\n"
},
{
"answer_id": 1126391,
"author": "alfredocambera",
"author_id": 138163,
"author_profile": "https://Stackoverflow.com/users/138163",
"pm_score": 3,
"selected": false,
"text": "<p>That worked for me, <strong>l.set_option(ldap.OPT_REFERRALS, 0)</strong> was the key to access the ActiveDirectory. Moreover, I think that you should add an \"con.unbind()\" in order to close the connection before finishing the script.</p>\n"
},
{
"answer_id": 3920712,
"author": "lanoxx",
"author_id": 474034,
"author_profile": "https://Stackoverflow.com/users/474034",
"pm_score": 1,
"selected": false,
"text": "<p>I tried to add</p>\n\n<blockquote>\n <p>l.set_option(ldap.OPT_REFERRALS, 0)</p>\n</blockquote>\n\n<p>but instead of an error Python just hangs and won't respond to anything any more. Maybe I'm building the search query wrong, what is the Base part of the search? I'm using the same as the DN for the simple bind (oh, and I had to do <code>l.simple_bind</code>, instead of <code>l.simple_bind_s</code>):</p>\n\n<pre><code>import ldap\nlocal = ldap.initialize(\"ldap://127.0.0.1\")\nlocal.simple_bind(\"CN=staff,DC=mydomain,DC=com\")\n#my pc is not actually connected to this domain \nresult_id = local.search(\"CN=staff,DC=mydomain,DC=com\", ldap.SCOPE_SUBTREE, \"cn=foobar\", None)\nlocal.set_option(ldap.OPT_REFERRALS, 0)\nresult_type, result_data = local.result(result_id, 0)\n</code></pre>\n\n<p>I'm using AD LDS and the instance is registered for the current account.</p>\n"
},
{
"answer_id": 6902892,
"author": "Dima Pasechnik",
"author_id": 557937,
"author_profile": "https://Stackoverflow.com/users/557937",
"pm_score": 2,
"selected": false,
"text": "<p>if you have Kerberos installed and talking to AD, as would be the case with, say, Centrify Express installed and running, you might just use python-kerberos. E.g.</p>\n\n<pre><code>import kerberos\nkerberos.checkPassword('joe','pizza','krbtgt/x.pizza.com','X.PIZZA.COM')`\n</code></pre>\n\n<p>would return True a user 'joe' has password 'pizza' in the Kerberos realm X.PIZZA.COM.\n(typically, I think, the latter would be the same as the name of the AD Domain)</p>\n"
},
{
"answer_id": 9943894,
"author": "xcl",
"author_id": 1303347,
"author_profile": "https://Stackoverflow.com/users/1303347",
"pm_score": 0,
"selected": false,
"text": "<p>For me changing from <code>simple_bind_s()</code> to <code>bind()</code> did the trick.</p>\n"
},
{
"answer_id": 18282435,
"author": "JohnMudd",
"author_id": 487992,
"author_profile": "https://Stackoverflow.com/users/487992",
"pm_score": 3,
"selected": false,
"text": "<p>Here's some simple code that works for me.</p>\n\n<pre><code>import ldap # run 'pip install python-ldap' to install ldap module.\nconn = ldap.open(\"ldaphost.company.com\")\nconn.simple_bind_s(\"[email protected]\", \"mypassword\")\n</code></pre>\n\n<p>This is based on a <a href=\"https://stackoverflow.com/a/10743770/487992\">previous answer</a>.</p>\n"
},
{
"answer_id": 38348468,
"author": "Dr.Ü",
"author_id": 2250744,
"author_profile": "https://Stackoverflow.com/users/2250744",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue, but it was regarding the password encoding</p>\n\n<pre><code>.encode('iso-8859-1')\n</code></pre>\n\n<p>Solved the problem.</p>\n"
},
{
"answer_id": 54416600,
"author": "Nagev",
"author_id": 5362795,
"author_profile": "https://Stackoverflow.com/users/5362795",
"pm_score": 2,
"selected": false,
"text": "<p>Based on the excellent <a href=\"https://ldap3.readthedocs.io/tutorial_intro.html\" rel=\"nofollow noreferrer\">ldap3 tutorial</a>:</p>\n<pre><code>from ldap3 import Server, Connection, ALL, NTLM\nserver = Server('server_name_or_ip', get_info=ALL)\nconn = Connection(server, user="user_name", password="password", auto_bind=True)\nconn.extend.standard.who_am_i()\nserver.info\n</code></pre>\n<p>I did the above in Python3 but it's supposed to be compatible with Python 2.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4319/"
]
| How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.
I can't even bind to perform a simple query:
```
import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
```
Running this with `[email protected] password username` gives me one of two errors:
`Invalid Credentials` - When I mistype or intentionally use wrong credentials it fails to authenticate.
>
> ldap.INVALID\_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}
>
>
>
Or
>
> ldap.OPERATIONS\_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}
>
>
>
What am I missing out to bind properly?
I am getting the same errors on fedora and windows. | I was missing
```
l.set_option(ldap.OPT_REFERRALS, 0)
```
From the init. |
140,460 | <p>We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).</p>
<p>I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?</p>
| [
{
"answer_id": 140508,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "<p>One piece of the puzzle:</p>\n\n<pre><code>/**\n * Determines if a form is dirty by comparing the current value of each element\n * with its default value.\n *\n * @param {Form} form the form to be checked.\n * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>\n * otherwise.\n */\nfunction formIsDirty(form)\n{\n for (var i = 0; i < form.elements.length; i++)\n {\n var element = form.elements[i];\n var type = element.type;\n if (type == \"checkbox\" || type == \"radio\")\n {\n if (element.checked != element.defaultChecked)\n {\n return true;\n }\n }\n else if (type == \"hidden\" || type == \"password\" || type == \"text\" ||\n type == \"textarea\")\n {\n if (element.value != element.defaultValue)\n {\n return true;\n }\n }\n else if (type == \"select-one\" || type == \"select-multiple\")\n {\n for (var j = 0; j < element.options.length; j++)\n {\n if (element.options[j].selected !=\n element.options[j].defaultSelected)\n {\n return true;\n }\n }\n }\n }\n return false;\n}\n</code></pre>\n\n<p><a href=\"http://developer.mozilla.org/en/DOM/window.onbeforeunload\" rel=\"noreferrer\">And another</a>:</p>\n\n<pre><code>window.onbeforeunload = function(e)\n{\n e = e || window.event; \n if (formIsDirty(document.forms[\"someFormOfInterest\"]))\n {\n // For IE and Firefox\n if (e)\n {\n e.returnValue = \"You have unsaved changes.\";\n }\n // For Safari\n return \"You have unsaved changes.\";\n }\n};\n</code></pre>\n\n<p>Wrap it all up, and what do you get?</p>\n\n<pre><code>var confirmExitIfModified = (function()\n{\n function formIsDirty(form)\n {\n // ...as above\n }\n\n return function(form, message)\n {\n window.onbeforeunload = function(e)\n {\n e = e || window.event;\n if (formIsDirty(document.forms[form]))\n {\n // For IE and Firefox\n if (e)\n {\n e.returnValue = message;\n }\n // For Safari\n return message;\n }\n };\n };\n})();\n\nconfirmExitIfModified(\"someForm\", \"You have unsaved changes.\");\n</code></pre>\n\n<p>You'll probably also want to change the registration of the <code>beforeunload</code> event handler to use <code>LIBRARY_OF_CHOICE</code>'s event registration.</p>\n"
},
{
"answer_id": 736800,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>If you use jQuery, here's an easy trick:</p>\n\n<pre><code>$('input:text,input:checkbox,input:radio,textarea,select').one('change',function() {\n $('BODY').attr('onbeforeunload',\"return 'Leaving this page will cause any unsaved data to be lost.';\");\n});\n</code></pre>\n\n<p>But just remember, if you have a condition where you redirect from this page, or you want to permit a successful form post, you need to do this before that redirect or submit event like so:</p>\n\n<pre><code>$('BODY').removeAttr('onbeforeunload');\n</code></pre>\n\n<p>...or you'll get yourself in a loop where it keeps asking you the prompt.</p>\n\n<p>In my case, I had a big app and I was doing location.href redirects in Javascript, as well as form posting, and then some AJAX submits that then come back with a success response inline in the page. In any of those conditions, I had to capture that event and use the removeAttr() call.</p>\n"
},
{
"answer_id": 1018862,
"author": "Lance Larsen - Microsoft MVP",
"author_id": 88665,
"author_profile": "https://Stackoverflow.com/users/88665",
"pm_score": 3,
"selected": false,
"text": "<p>Wanted to expand slightly on Volomike excellent jQuery code. </p>\n\n<p>So with this, we have a very very cool and elegant mechanism to accomplish the objective of preventing inadvertent data loss through navigating away from updated data prior to saving – ie. updated field on a page, then click on a button, link or even the back button in the browser before clicking the Save button.</p>\n\n<p>The only thing you need to do is add a “noWarn” class tag to all controls ( especially Save buttons ) that do a post back to the website, that either save or do not remove any updated data. </p>\n\n<p>If the control causes the page to lose data, ie. navigates to the next page or clears the data – you do not need to do anything, as the scripts will automatically show the warning message.</p>\n\n<p>Awesome! Well done Volomike!</p>\n\n<p>Simply have the jQuery code as follows:</p>\n\n<pre><code>$(document).ready(function() {\n\n //----------------------------------------------------------------------\n // Don't allow us to navigate away from a page on which we're changed\n // values on any control without a warning message. Need to class our \n // save buttons, links, etc so they can do a save without the message - \n // ie. CssClass=\"noWarn\"\n //----------------------------------------------------------------------\n $('input:text,input:checkbox,input:radio,textarea,select').one('change', function() {\n $('BODY').attr('onbeforeunload',\n \"return 'Leaving this page will cause any unsaved data to be lost.';\");\n });\n\n $('.noWarn').click(function() { $('BODY').removeAttr('onbeforeunload'); });\n\n});\n</code></pre>\n"
},
{
"answer_id": 2220100,
"author": "Ben McIntyre",
"author_id": 208465,
"author_profile": "https://Stackoverflow.com/users/208465",
"pm_score": 3,
"selected": false,
"text": "<p>Additional to Lance's answer, I just spent an afternoon trying to get this snippet running.\nFirstly, jquery 1.4 seems to have bugs with binding the change event (as of Feb '10). jQuery 1.3 is OK.\nSecondly, I can't get jquery to bind the onbeforeunload/beforeunload (I suspect IE7, which I'm using). I've tried different selectors, (\"body\"), (window). I've tried '.bind', '.attr'.\nReverting to pure js worked (I also saw a few similar posts on SO about this problem):</p>\n\n<pre><code>$(document).ready(function() {\n $(\":input\").one(\"change\", function() {\n window.onbeforeunload = function() { return 'You will lose data changes.'; }\n });\n $('.noWarn').click(function() { window.onbeforeunload = null; });\n});\n</code></pre>\n\n<p>Note I've also used the ':input' selector rather than enumerating all the input types. Strictly overkill, but I thought it was cool :-)</p>\n"
},
{
"answer_id": 2402725,
"author": "Adam Nofsinger",
"author_id": 18524,
"author_profile": "https://Stackoverflow.com/users/18524",
"pm_score": 1,
"selected": false,
"text": "<p>I made one more slight improvement to the jQuery implementations listed on this page. My implementation will handle if you have <strong>client-side ASP.NET page validation</strong> enabled and being used on a page.</p>\n\n<p>It avoids the \"error\" of clearing the <code>onBeforeLeave</code> function when the page doesn't actually post on click due to a validation failure. Simply use the <code>no-warn-validate</code> class on buttons/links that cause validation. It still has the <code>no-warn</code> class to use on controls that have <code>CausesValidation=false</code> (e.g. a \"Save as Draft\" button). This pattern could probably be used for other validation frameworks other than ASP.NET, so I post here for reference.</p>\n\n<pre><code> function removeCheck() { window.onbeforeunload = null; }\n\n$(document).ready(function() {\n //-----------------------------------------------------------------------------------------\n // Don't allow navigating away from page if changes to form are made. Save buttons, links,\n // etc, can be given \"no-warn\" or \"no-warn-validate\" css class to prevent warning on submit.\n // \"no-warn-validate\" inputs/links will only remove warning after successful validation\n //-----------------------------------------------------------------------------------------\n $(':input').one('change', function() {\n window.onbeforeunload = function() {\n return 'Leaving this page will cause edits to be lost.';\n }\n });\n\n $('.no-warn-validate').click(function() {\n if (Page_ClientValidate == null || Page_ClientValidate()) { removeCheck(); }\n });\n\n $('.no-warn').click(function() { removeCheck() });\n});\n</code></pre>\n"
},
{
"answer_id": 2556304,
"author": "Ken Browning",
"author_id": 53162,
"author_profile": "https://Stackoverflow.com/users/53162",
"pm_score": 2,
"selected": false,
"text": "<p>I've created a jQuery <a href=\"http://kenbrowning.blogspot.com/2010/03/how-to-warn-users-of-unsaved-changes.html\" rel=\"nofollow noreferrer\">plug-in</a> which can be used to implement a warn-on-unsaved-changes feature for web applications. It supports postbacks. It also includes a link to information on how to normalize behavior of the <code>onbeforeunload</code> event of Internet Explorer.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22732/"
]
| We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).
I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out? | One piece of the puzzle:
```
/**
* Determines if a form is dirty by comparing the current value of each element
* with its default value.
*
* @param {Form} form the form to be checked.
* @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
* otherwise.
*/
function formIsDirty(form)
{
for (var i = 0; i < form.elements.length; i++)
{
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio")
{
if (element.checked != element.defaultChecked)
{
return true;
}
}
else if (type == "hidden" || type == "password" || type == "text" ||
type == "textarea")
{
if (element.value != element.defaultValue)
{
return true;
}
}
else if (type == "select-one" || type == "select-multiple")
{
for (var j = 0; j < element.options.length; j++)
{
if (element.options[j].selected !=
element.options[j].defaultSelected)
{
return true;
}
}
}
}
return false;
}
```
[And another](http://developer.mozilla.org/en/DOM/window.onbeforeunload):
```
window.onbeforeunload = function(e)
{
e = e || window.event;
if (formIsDirty(document.forms["someFormOfInterest"]))
{
// For IE and Firefox
if (e)
{
e.returnValue = "You have unsaved changes.";
}
// For Safari
return "You have unsaved changes.";
}
};
```
Wrap it all up, and what do you get?
```
var confirmExitIfModified = (function()
{
function formIsDirty(form)
{
// ...as above
}
return function(form, message)
{
window.onbeforeunload = function(e)
{
e = e || window.event;
if (formIsDirty(document.forms[form]))
{
// For IE and Firefox
if (e)
{
e.returnValue = message;
}
// For Safari
return message;
}
};
};
})();
confirmExitIfModified("someForm", "You have unsaved changes.");
```
You'll probably also want to change the registration of the `beforeunload` event handler to use `LIBRARY_OF_CHOICE`'s event registration. |
140,490 | <p>Which gets called first - the base constructor or "other stuff here"?</p>
<pre><code>public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
</code></pre>
| [
{
"answer_id": 140497,
"author": "Mastermind",
"author_id": 22213,
"author_profile": "https://Stackoverflow.com/users/22213",
"pm_score": 3,
"selected": false,
"text": "<p>I'd say base</p>\n\n<p>EDIT see:</p>\n\n<p><a href=\"http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx\" rel=\"noreferrer\">http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx</a></p>\n\n<p>there it says:</p>\n\n<pre><code>using System;\nclass Base\n{\n\npublic Base()\n{\n Console.WriteLine(\"BASE 1\");\n}\npublic Base(int x)\n{\n Console.WriteLine(\"BASE 2\");\n}\n}\n\nclass Derived : Base\n{\npublic Derived():base(10)\n{\n Console.WriteLine(\"DERIVED CLASS\");\n}\n}\n\nclass MyClient\n{\npublic static void Main()\n{\n Derived d1 = new Derived();\n}\n}\n</code></pre>\n\n<blockquote>\n <p>This program outputs </p>\n \n <p>BASE2 </p>\n \n <p>DERIVED CLASS</p>\n</blockquote>\n"
},
{
"answer_id": 140505,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 8,
"selected": true,
"text": "<p>The base constructor will be called first.</p>\n\n<p>try it:</p>\n\n<pre><code>public class MyBase\n{\n public MyBase()\n {\n Console.WriteLine(\"MyBase\");\n }\n}\n\npublic class MyDerived : MyBase\n{\n public MyDerived():base()\n {\n Console.WriteLine(\"MyDerived\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 140526,
"author": "mmcdole",
"author_id": 2635,
"author_profile": "https://Stackoverflow.com/users/2635",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=777\" rel=\"nofollow noreferrer\">http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=777</a></p>\n\n<p>Base Constructor gets called first.</p>\n"
},
{
"answer_id": 140530,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 1,
"selected": false,
"text": "<p>The Exception Constructor will be called, then your Child class constructor will be called.</p>\n\n<p>Simple OO principle</p>\n\n<p>Have a look here\n<a href=\"http://www.dotnet-news.com/lien.aspx?ID=35151\" rel=\"nofollow noreferrer\">http://www.dotnet-news.com/lien.aspx?ID=35151</a></p>\n"
},
{
"answer_id": 140533,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 5,
"selected": false,
"text": "<p>Actually, the derived class constructor is executed first, but the C# compiler inserts a call to the base class constructor as first statement of the derived constructor.</p>\n\n<p>So: the derived is executed first, but it \"looks like\" the base was executed first.</p>\n"
},
{
"answer_id": 140541,
"author": "Sam Meldrum",
"author_id": 16005,
"author_profile": "https://Stackoverflow.com/users/16005",
"pm_score": 7,
"selected": false,
"text": "<p>Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code:</p>\n\n<pre><code>public class BaseClass {\n\n private string sentenceOne = null; // A\n\n public BaseClass() {\n sentenceOne = \"The quick brown fox\"; // B\n }\n}\n\npublic class SubClass : BaseClass {\n\n private string sentenceTwo = null; // C\n\n public SubClass() {\n sentenceTwo = \"jumps over the lazy dog\"; // D\n }\n}\n</code></pre>\n\n<p>Order of execution is: C, A, B, D.</p>\n\n<p>Check out these 2 msdn articles:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx\" rel=\"noreferrer\">Why do initializers run in the opposite order as constructors? Part One</a></li>\n<li><a href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx\" rel=\"noreferrer\">Why do initializers run in the opposite order as constructors? Part Two</a></li>\n</ul>\n"
},
{
"answer_id": 140545,
"author": "kafuchau",
"author_id": 22371,
"author_profile": "https://Stackoverflow.com/users/22371",
"pm_score": 0,
"selected": false,
"text": "<p>The base constructor will be called first, otherwise, in cases where your \"other stuff\" must make use of member variables initialized by your base constructor, you'll get compile time errors because your class members will not have been initialized yet. </p>\n"
},
{
"answer_id": 140551,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "<p>base(?) is called before any work is done in the child constructor.</p>\n\n<p>This is true, even if you leave off the :base() (in which case, the 0-parameter base constructor is called.)</p>\n\n<p>It works similar to java,</p>\n\n<pre><code>public Child()\n{\n super(); // this line is always the first line in a child constructor even if you don't put it there! ***\n}\n</code></pre>\n\n<p>*** Exception: I could put in super(1,2,3) instead. But if I don't put a call to super in explicitly, super() is called.</p>\n"
},
{
"answer_id": 140553,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": false,
"text": "<p>As others have said, the base constructor gets called first. However, constructors are not really the first thing that happens.</p>\n\n<p>Let's say you have classes like this:</p>\n\n<pre><code>class A {}\n\nclass B : A {}\n\nclass C : B {}\n</code></pre>\n\n<p>First, field initializers will be called in order of most-derived to least-derived classes. So first field initializers of <code>C</code>, then <code>B</code>, then <code>A</code>.</p>\n\n<p>The constructors will then be called in the opposite order: First <code>A</code>'s constructor, then <code>B</code>, then <code>C</code>.</p>\n"
},
{
"answer_id": 140583,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Constructor calls are called (fired) from the bottom up, and executed from the top down. Thus, if you had Class C which inherits from Class B which inherits from Class A, when you create an instance of class C the constructor for C is called, which in turn calls the instructor for B, which again in turn calls the constructor for A. Now the constructor for A is executed, then the constructor for B is executed, then the constructor for C is executed.</p>\n"
},
{
"answer_id": 141856,
"author": "David Pokluda",
"author_id": 223,
"author_profile": "https://Stackoverflow.com/users/223",
"pm_score": 6,
"selected": false,
"text": "<p>Don't try to remember it, try to explain to yourself what has to happen. Imagine that you have base class named Animal and a derived class named Dog. The derived class adds some functionality to the base class. Therefore when the constructor of the derived class is executed the base class instance must be available (so that you can add new functionality to it). That's why the constructors are executed from the base to derived but destructors are executed in the opposite way - first the derived destructors and then base destructors. </p>\n\n<p>(This is simplified but it should help you to answer this question in the future without the need to actually memorizing this.)</p>\n"
},
{
"answer_id": 194831,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 2,
"selected": false,
"text": "<p>Eric Lippert had an interesting post on the related issue of object initialization, which explains the reason for the ordering of constructors and field initializers:</p>\n\n<p><a href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx\" rel=\"nofollow noreferrer\">Why Do Initializers Run In The Opposite Order As Constructors? Part One</a>\n<br/>\n<a href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx\" rel=\"nofollow noreferrer\">Why Do Initializers Run In The Opposite Order As Constructors? Part Two</a></p>\n"
},
{
"answer_id": 41008785,
"author": "zwcloud",
"author_id": 3427520,
"author_profile": "https://Stackoverflow.com/users/3427520",
"pm_score": 2,
"selected": false,
"text": "<p>Base Constructor is called first. But the initializer of fields in derived class is called first.</p>\n\n<p>The calling order is</p>\n\n<ol>\n<li>derived class field initializer</li>\n<li>base class field initializer</li>\n<li>base class constructor</li>\n<li>derived class constructor</li>\n</ol>\n\n<p>(You can treat 2 and 3 as a whole to construct the base class.)</p>\n\n<p>Taken from <a href=\"https://www.microsoft.com/en-us/download/details.aspx?id=7029\" rel=\"nofollow noreferrer\"><em>CSharp Language Speification 5.0</em></a>:</p>\n\n<blockquote>\n <p><strong>10.11.3 Constructor execution</strong></p>\n \n <p>Variable initializers are transformed into assignment statements, and these assignment\n statements are executed before the invocation of the base class\n instance constructor. This ordering ensures that all instance fields\n are initialized by their variable initializers before any statements\n that have access to that instance are executed. Given the example</p>\n\n<pre><code>using System;\nclass A\n{\n public A() {\n PrintFields();\n }\n public virtual void PrintFields() {}\n}\nclass B: A\n{\n int x = 1;\n int y;\n public B() {\n y = -1;\n }\n public override void PrintFields() {\n Console.WriteLine(\"x = {0}, y = {1}\", x, y);\n }\n}\n</code></pre>\n \n <p>when <code>new B()</code> is used to create an instance of <code>B</code>, the following\n output is produced:</p>\n\n<pre><code>x = 1, y = 0\n</code></pre>\n \n <p>The value of <code>x</code> is 1 because the variable initializer is executed\n before the base class instance constructor is invoked. However, the\n value of <code>y</code> is 0 (the default value of an <code>int</code>) because the assignment\n to <code>y</code> is not executed until after the base class constructor returns.\n It is useful to think of instance variable initializers and\n constructor initializers as statements that are automatically inserted\n before the constructor-body. The example</p>\n\n<pre><code>using System;\nusing System.Collections;\nclass A\n{\n int x = 1, y = -1, count;\n public A() {\n count = 0;\n }\n public A(int n) {\n count = n;\n }\n}\nclass B: A\n{\n double sqrt2 = Math.Sqrt(2.0);\n ArrayList items = new ArrayList(100);\n int max;\n public B(): this(100) {\n items.Add(\"default\");\n }\n public B(int n): base(n – 1) {\n max = n;\n }\n}\n</code></pre>\n \n <p>contains several variable initializers; it also contains constructor\n initializers of both forms (base and this). The example corresponds to\n the code shown below, where each comment indicates an automatically\n inserted statement (the syntax used for the automatically inserted\n constructor invocations isn’t valid, but merely serves to\n illustrate the mechanism).</p>\n\n<pre><code>using System.Collections;\nclass A\n{\n int x, y, count;\n public A() {\n x = 1; // Variable initializer\n y = -1; // Variable initializer\n object(); // Invoke object() constructor\n count = 0;\n }\n public A(int n) {\n x = 1; // Variable initializer\n y = -1; // Variable initializer\n object(); // Invoke object() constructor\n count = n;\n }\n}\nclass B: A\n{\n double sqrt2;\n ArrayList items;\n int max;\n public B(): this(100) {\n B(100); // Invoke B(int) constructor\n items.Add(\"default\");\n }\n public B(int n): base(n – 1) {\n sqrt2 = Math.Sqrt(2.0); // Variable initializer\n items = new ArrayList(100); // Variable initializer\n A(n – 1); // Invoke A(int) constructor\n max = n;\n }\n}\n</code></pre>\n</blockquote>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16872/"
]
| Which gets called first - the base constructor or "other stuff here"?
```
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
``` | The base constructor will be called first.
try it:
```
public class MyBase
{
public MyBase()
{
Console.WriteLine("MyBase");
}
}
public class MyDerived : MyBase
{
public MyDerived():base()
{
Console.WriteLine("MyDerived");
}
}
``` |
140,602 | <p>I am trying to call a WCF webservice (which I developed) from a Silverlight application. For some reason the Silverlight app does not make the http soap call to the service. I know this because I am sniffing all http traffic with Fiddler (and it is not a localhost call).</p>
<p>This my configuration in the server relevant to WCF:</p>
<pre><code><system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="basicHttpBinding" contract="Service"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
</code></pre>
<p>And the ServiceReferences.ClientConfig file in the silverlight app (i am using the beta 2):</p>
<pre><code><system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Service" maxBufferSize="65536"
maxReceivedMessageSize="65536">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://itlabws2003/Service.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_Service" contract="Silverlight_organigram.DataService.Service"
name="BasicHttpBinding_Service" />
</client>
</system.serviceModel>
</code></pre>
<p>This is the silverlight method that calls the service, I paste the whole method for copleteness, the lambda is to make the call synchronous, I have debugged it and after the line client.GetPersonsAsync(), Fiddler does not show any message travelling to the server.</p>
<pre><code> public static List<Person> GetPersonsFromDatabase()
{
List<Person> persons = new List<Person>();
ServiceClient client = new ServiceClient();
ManualResetEvent eventGetPersons = new ManualResetEvent(false);
client.GetPersonsCompleted += new EventHandler<GetPersonsCompletedEventArgs>(delegate(object sender, GetPersonsCompletedEventArgs e)
{
foreach (DTOperson dtoPerson in e.Result)
{
persons.Add(loadFromDto(dtoPerson));
}
eventGetPersons.Set();
});
client.GetPersonsAsync();
eventGetPersons.WaitOne();
return persons;
}
</code></pre>
<p>Does anyone have any suggestions how I might fix this?</p>
| [
{
"answer_id": 140646,
"author": "Bill Reiss",
"author_id": 18967,
"author_profile": "https://Stackoverflow.com/users/18967",
"pm_score": 0,
"selected": false,
"text": "<p>You wouldn't happen to be running from the filesystem would you? If you are serving up the silverlight application your local machine and not using the VS Web Server or IIS, you won't be able to make HTTP calls for security reasons. Similarly if you're loading from a web server, you can't access local resources.</p>\n\n<p>Also I've found that Nikhil's Web Development Helper <a href=\"http://www.nikhilk.net/ASPNETDevHelperTool.aspx\" rel=\"nofollow noreferrer\">http://www.nikhilk.net/ASPNETDevHelperTool.aspx</a> can be more useful than Fiddler because you will see local traffic as well, although it doesn't look like that is your issue in this case.</p>\n"
},
{
"answer_id": 141678,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 0,
"selected": false,
"text": "<p>I am not 100% certain, but if you are running on Vista or Server 2008 you may have run into the User Access Control issue with http.sys</p>\n\n<p>So in Vista and Win2k8 server, the HttpListener will listen only if you are running under a high privelege account. In fact, from my experience, even if you add yourself to the <em>local</em> administrators group, you might run into this issue.</p>\n\n<p>In any case, try launching Visual Studio on Vista by Right Clicking and runas Administrator. See if that fixes it. If it does, you're good, but....</p>\n\n<p>ideally you should run <a href=\"http://msdn.microsoft.com/en-us/library/aa364478(VS.85).aspx\" rel=\"nofollow noreferrer\">httpcfg</a></p>\n\n<p>like:\nhttpcfg set urlacl -u <a href=\"http://itlabws2003\" rel=\"nofollow noreferrer\">http://itlabws2003</a> -a D:(A;;GX;;;<em>yoursid</em>)</p>\n\n<p>your sid = the security identifier for the account you're running as, you can find it here: \nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList </p>\n\n<p>if you don't know it already, or you could possibly add yourself to BUILTIN\\Administators, find the sid and run the httpcfg via command line again, specifying that sid.</p>\n\n<p>User Access Control, Vista and Http.sys cause all this...if this is indeed the problem you are running into. Not sure but maybe its worth a try</p>\n"
},
{
"answer_id": 186458,
"author": "Larry",
"author_id": 24472,
"author_profile": "https://Stackoverflow.com/users/24472",
"pm_score": 1,
"selected": false,
"text": "<p>If the Silverlight application is not hosted in the same domain that exposes the Web service you want to call, then cross-domain restrictions applies.</p>\n\n<p>If you want the Silverlight application to be hosted in another domain than the web service, you may want to have a look on <a href=\"http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx\" rel=\"nofollow noreferrer\">this post</a> to help you to have a cross domain definition file, or to write a middle \"proxy\" instead.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19010/"
]
| I am trying to call a WCF webservice (which I developed) from a Silverlight application. For some reason the Silverlight app does not make the http soap call to the service. I know this because I am sniffing all http traffic with Fiddler (and it is not a localhost call).
This my configuration in the server relevant to WCF:
```
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="basicHttpBinding" contract="Service"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
```
And the ServiceReferences.ClientConfig file in the silverlight app (i am using the beta 2):
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Service" maxBufferSize="65536"
maxReceivedMessageSize="65536">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://itlabws2003/Service.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_Service" contract="Silverlight_organigram.DataService.Service"
name="BasicHttpBinding_Service" />
</client>
</system.serviceModel>
```
This is the silverlight method that calls the service, I paste the whole method for copleteness, the lambda is to make the call synchronous, I have debugged it and after the line client.GetPersonsAsync(), Fiddler does not show any message travelling to the server.
```
public static List<Person> GetPersonsFromDatabase()
{
List<Person> persons = new List<Person>();
ServiceClient client = new ServiceClient();
ManualResetEvent eventGetPersons = new ManualResetEvent(false);
client.GetPersonsCompleted += new EventHandler<GetPersonsCompletedEventArgs>(delegate(object sender, GetPersonsCompletedEventArgs e)
{
foreach (DTOperson dtoPerson in e.Result)
{
persons.Add(loadFromDto(dtoPerson));
}
eventGetPersons.Set();
});
client.GetPersonsAsync();
eventGetPersons.WaitOne();
return persons;
}
```
Does anyone have any suggestions how I might fix this? | If the Silverlight application is not hosted in the same domain that exposes the Web service you want to call, then cross-domain restrictions applies.
If you want the Silverlight application to be hosted in another domain than the web service, you may want to have a look on [this post](http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx) to help you to have a cross domain definition file, or to write a middle "proxy" instead. |
140,616 | <p>Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant <a href="http://ant.apache.org/manual/Tasks/echoproperties.html" rel="noreferrer">echoproperties</a> task maybe?</p>
| [
{
"answer_id": 140739,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>You can't prove a negative, but I can't find one and haven't seen one. I've traditionally rolled my own property echoes.</p>\n"
},
{
"answer_id": 141174,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 6,
"selected": true,
"text": "<p>Try this snippet:</p>\n\n<pre><code><project>\n <property name=\"foo\" value=\"bar\"/>\n <property name=\"fiz\" value=\"buz\"/>\n\n <script language=\"C#\" prefix=\"util\" >\n <code>\n <![CDATA[\n public static void ScriptMain(Project project) \n {\n foreach (DictionaryEntry entry in project.Properties)\n {\n Console.WriteLine(\"{0}={1}\", entry.Key, entry.Value);\n }\n }\n ]]>\n </code>\n </script>\n</project>\n</code></pre>\n\n<p>You can just save and run with nant.</p>\n\n<p>And no, there isn't a task or function to do this for you already.</p>\n"
},
{
"answer_id": 13772601,
"author": "Brad C",
"author_id": 1886864,
"author_profile": "https://Stackoverflow.com/users/1886864",
"pm_score": 3,
"selected": false,
"text": "<p>I wanted them sorted so I expanded on the other answer. It's not very efficient, but it works:</p>\n\n<pre><code><script language=\"C#\" prefix=\"util\" >\n <references>\n <include name=\"System.dll\" />\n </references> \n <imports>\n <import namespace=\"System.Collections.Generic\" />\n </imports> \n <code>\n <![CDATA[\n public static void ScriptMain(Project project) \n {\n SortedDictionary<string, string> sorted = new SortedDictionary<string, string>();\n foreach (DictionaryEntry entry in project.Properties){\n sorted.Add((string)entry.Key, (string)entry.Value);\n }\n foreach (KeyValuePair<string, string> entry in sorted)\n {\n project.Log(Level.Info, \"{0}={1}\", entry.Key, entry.Value);\n }\n }\n ]]>\n </code>\n</script>\n</code></pre>\n"
},
{
"answer_id": 20248647,
"author": "Ben Corpus",
"author_id": 3042791,
"author_profile": "https://Stackoverflow.com/users/3042791",
"pm_score": 2,
"selected": false,
"text": "<p>I tried the solutions suggested by Brad C, but they did not work for me (running Windows 7 Profession on x64 with NAnt 0.92). However, this works for my local configuration:</p>\n\n<pre><code><target name=\"echo-properties\" verbose=\"false\" description=\"Echo property values\" inheritall=\"true\">\n<script language=\"C#\">\n <code>\n <![CDATA[\n public static void ScriptMain(Project project)\n {\n System.Collections.SortedList sortedByKey = new System.Collections.SortedList();\n foreach(DictionaryEntry de in project.Properties)\n {\n sortedByKey.Add(de.Key, de.Value);\n }\n\n NAnt.Core.Tasks.EchoTask echo = new NAnt.Core.Tasks.EchoTask();\n echo.Project = project;\n\n foreach(DictionaryEntry de in sortedByKey)\n {\n if(de.Key.ToString().StartsWith(\"nant.\"))\n {\n continue;\n }\n echo.Message = String.Format(\"{0}: {1}\", de.Key,de.Value);\n echo.Execute();\n }\n }\n ]]>\n </code>\n</script>\n</target>\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
]
| Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant [echoproperties](http://ant.apache.org/manual/Tasks/echoproperties.html) task maybe? | Try this snippet:
```
<project>
<property name="foo" value="bar"/>
<property name="fiz" value="buz"/>
<script language="C#" prefix="util" >
<code>
<![CDATA[
public static void ScriptMain(Project project)
{
foreach (DictionaryEntry entry in project.Properties)
{
Console.WriteLine("{0}={1}", entry.Key, entry.Value);
}
}
]]>
</code>
</script>
</project>
```
You can just save and run with nant.
And no, there isn't a task or function to do this for you already. |
140,627 | <p>I just wrote my first web service so lets make the assumption that my web service knowlege is non existant. I want to try to call a dbClass function from the web service. However I need some params that are in the session. Is there any way I can get these call these session variables from the webservice??</p>
| [
{
"answer_id": 140644,
"author": "Yitzchok",
"author_id": 5723,
"author_profile": "https://Stackoverflow.com/users/5723",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe this will work HttpContext.Current.Session[\"Name]\nOr else you might have to take in some parameters or store them in a Database</p>\n"
},
{
"answer_id": 140656,
"author": "Metro",
"author_id": 18978,
"author_profile": "https://Stackoverflow.com/users/18978",
"pm_score": 5,
"selected": true,
"text": "<p>If you are using ASP.NET web services and you want to have a session environment maintained for you, you need to embellish your web service method with an attribute that indicates you require a session.</p>\n\n<pre><code>[WebMethod(EnableSession = true)]\npublic void MyWebService()\n{\n Foo foo;\n Session[\"MyObjectName\"] = new Foo();\n foo = Session[\"MyObjectName\"] as Foo;\n}\n</code></pre>\n\n<p>Once you have done this, you may access session objects similar to aspx.</p>\n\n<p>Metro.</p>\n"
},
{
"answer_id": 140659,
"author": "marc",
"author_id": 12260,
"author_profile": "https://Stackoverflow.com/users/12260",
"pm_score": 2,
"selected": false,
"text": "<p>In general web services should not rely on session data. Think of them as ordinary methods: parameters go in and an answer comes out.</p>\n"
},
{
"answer_id": 140660,
"author": "Kyle Trauberman",
"author_id": 21461,
"author_profile": "https://Stackoverflow.com/users/21461",
"pm_score": 0,
"selected": false,
"text": "<p>Your question is a little vague, but I'll try my best to answer.</p>\n\n<p>I'm assuming that your session variables exist on the server that is making the webservice call, and not on the server that hosts the webservice. In that case, you will need to pass the necessary values as parameters of your web service methods.</p>\n"
},
{
"answer_id": 140672,
"author": "Pablo Marambio",
"author_id": 18552,
"author_profile": "https://Stackoverflow.com/users/18552",
"pm_score": 3,
"selected": false,
"text": "<p>You should avoid increasing the complexity of the service layer adding session variables. As someone previously pointed out, think of the web services as isolated methods that take all what is needed to perform the task from their argument list.</p>\n"
},
{
"answer_id": 9582309,
"author": "Prashiddha Raj Joshi",
"author_id": 780505,
"author_profile": "https://Stackoverflow.com/users/780505",
"pm_score": 1,
"selected": false,
"text": "<p>if you have to want Session[\"username\"].ToString(); as in the other C# pages behind aspx then you should simply replace [WebMethod] above the WebService method with [WebMethod(EnableSession = true)]</p>\n\n<p>thanks to :) Metro</p>\n"
},
{
"answer_id": 44005439,
"author": "Debendra Dash",
"author_id": 5418530,
"author_profile": "https://Stackoverflow.com/users/5418530",
"pm_score": 0,
"selected": false,
"text": "<p>To use session in webservice we have to follow 2 steps-</p>\n\n<ol>\n<li>Use [WebMethod(EnableSession = true)] attribute on the method.</li>\n<li>Session[\"Name\"] =50 (what ever you want to save)\nPlease check the following Example.</li>\n</ol>\n\n<pre>\n[WebMethod(EnableSession = true)] \npublic void saveName(string pname) \n{ \n Session[\"Name\"] = pname; \n\n } \n\n</pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16820/"
]
| I just wrote my first web service so lets make the assumption that my web service knowlege is non existant. I want to try to call a dbClass function from the web service. However I need some params that are in the session. Is there any way I can get these call these session variables from the webservice?? | If you are using ASP.NET web services and you want to have a session environment maintained for you, you need to embellish your web service method with an attribute that indicates you require a session.
```
[WebMethod(EnableSession = true)]
public void MyWebService()
{
Foo foo;
Session["MyObjectName"] = new Foo();
foo = Session["MyObjectName"] as Foo;
}
```
Once you have done this, you may access session objects similar to aspx.
Metro. |
140,643 | <p>When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown. These tables have execute permission for the schema where the view was created. If I execute the view's SQL Statement it works. What am I missing?</p>
| [
{
"answer_id": 140665,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 5,
"selected": true,
"text": "<p>As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.</p>\n\n<pre><code>grant SELECT on TABLE_NAME to READ_USERNAME;\n</code></pre>\n"
},
{
"answer_id": 140706,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 1,
"selected": false,
"text": "<p>If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.</p>\n"
},
{
"answer_id": 141219,
"author": "Igor Zelaya",
"author_id": 22769,
"author_profile": "https://Stackoverflow.com/users/22769",
"pm_score": 5,
"selected": false,
"text": "<p>Finally I got it to work. Steve's answer is right but not for all cases. It fails when that view is being executed from a third schema. For that to work you have to add the grant option:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>GRANT SELECT ON [TABLE_NAME] TO [READ_USERNAME] WITH GRANT OPTION;\n</code></pre>\n\n<p>That way, <code>[READ_USERNAME]</code> can also grant select privilege over the view to another schema</p>\n"
},
{
"answer_id": 1133087,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Q. When is the \"with grant option\" required ?</p>\n\n<p>A. when you have a view executed from a third schema.</p>\n\n<p>Example:\n schema DSDSW has a view called view_name</p>\n\n<pre><code>a) that view selects from a table in another schema (FDR.balance)\nb) a third shema X_WORK tries to select from that view\n</code></pre>\n\n<p>Typical grants:\n grant select on dsdw.view_name to dsdw_select_role;\n grant dsdw_select_role to fdr;</p>\n\n<p>But: fdr gets\n select count(*) from dsdw.view_name;\n ERROR at line 1:\n ORA-01031: insufficient privileges</p>\n\n<p>issue the grant: </p>\n\n<pre><code>grant select on fdr.balance to dsdw with grant option;\n</code></pre>\n\n<p>now fdr:\n select count(*) from dsdw.view_name;\n 5 rows </p>\n"
},
{
"answer_id": 2656376,
"author": "Roberto Monterrey",
"author_id": 318925,
"author_profile": "https://Stackoverflow.com/users/318925",
"pm_score": 2,
"selected": false,
"text": "<p>Let me make a recap.</p>\n\n<p>When you build a view containing object of different owners, those other owners have to grant \"with grant option\" to the owner of the view. So, the view owner can grant to other users or schemas....</p>\n\n<p>Example:\nUser_a is the owner of a table called mine_a\nUser_b is the owner of a table called yours_b</p>\n\n<p>Let's say user_b wants to create a view with a join of mine_a and yours_b</p>\n\n<p>For the view to work fine, user_a has to give \"grant select on mine_a to user_b with grant option\"</p>\n\n<p>Then user_b can grant select on that view to everybody.</p>\n"
},
{
"answer_id": 16591957,
"author": "akshay",
"author_id": 2390718,
"author_profile": "https://Stackoverflow.com/users/2390718",
"pm_score": 1,
"selected": false,
"text": "<p>If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.</p>\n\n<p>simply type this</p>\n\n<p>grant all on to public;</p>\n"
},
{
"answer_id": 22535415,
"author": "Van Gogh",
"author_id": 3241616,
"author_profile": "https://Stackoverflow.com/users/3241616",
"pm_score": 1,
"selected": false,
"text": "<p>To use a view, the user must have the appropriate privileges but only for the view itself, not its underlying objects. However, if access privileges for the underlying objects of the view are removed, then the user no longer has access. This behavior occurs because the security domain that is used when a user queries the view is that of the definer of the view. If the privileges on the underlying objects are revoked from the view's definer, then the view becomes invalid, and no one can use the view. Therefore, even if a user has been granted access to the view, the user may not be able to use the view if the definer's rights have been revoked from the view's underlying objects.</p>\n\n<p>Oracle Documentation\n<a href=\"http://docs.oracle.com/cd/B28359_01/network.111/b28531/authorization.htm#DBSEG98017\" rel=\"nofollow\">http://docs.oracle.com/cd/B28359_01/network.111/b28531/authorization.htm#DBSEG98017</a></p>\n"
},
{
"answer_id": 63718765,
"author": "Alisherbek",
"author_id": 13320556,
"author_profile": "https://Stackoverflow.com/users/13320556",
"pm_score": 0,
"selected": false,
"text": "<p>you may also create view with schema name\nfor example <strong>create or replace view schema_name.view_name as select..</strong></p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22769/"
]
| When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown. These tables have execute permission for the schema where the view was created. If I execute the view's SQL Statement it works. What am I missing? | As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.
```
grant SELECT on TABLE_NAME to READ_USERNAME;
``` |
140,728 | <p>It often happens that characters such as <em>é</em> gets transformed to <em>é</em>, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the <em>Content-Type</em> for the page is also set to UTF8.</p>
<p>I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.</p>
<p>I have read the "<a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>" article, but I need some MySQL / PHP specific pointers.</p>
<p>How do I ensure that user entered data containing international characters doesn't get corrupted?</p>
| [
{
"answer_id": 141011,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 5,
"selected": true,
"text": "<p>On the first look at <a href=\"http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet\" rel=\"noreferrer\">http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet</a> I think that one important thing is missing (perhaps I overlooked this one).\nDepending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a</p>\n\n<pre><code>SET NAMES utf8\n</code></pre>\n\n<p>query prior to any other query you send to the MySQL server.</p>\n\n<p>If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using</p>\n\n<pre><code>$db=new PDO($dsn, $user, $pass);\n$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, \"SET NAMES utf8\");\n</code></pre>\n\n<p>when initializing your db connection.</p>\n"
},
{
"answer_id": 141029,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 0,
"selected": false,
"text": "<p>For better unicode correctness, you should use utf8_unicode_ci (though the documentation is a little vague on the differences). You should also make sure the following Mysql flags are set correctly -</p>\n\n<ul>\n<li>default-character-set=utf8</li>\n<li>skip-character-set-client-handshake //Important so the client doesn't enforce another encoding</li>\n</ul>\n\n<p>Those can be set in the mysql configuration file (under the [mysqld] tab) or at run time by sending the appropriate queries.</p>\n"
},
{
"answer_id": 143565,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 2,
"selected": false,
"text": "<p>Things you should do:</p>\n\n<ul>\n<li>Make sure Apache puts out UTF-8 content. Do this in your httpd.conf, or use PHP's <code>header()</code>-function to do it manually.</li>\n<li>Make sure your database connection is UTF8. <code>SET NAMES utf8</code> does the trick.</li>\n<li>Make sure all your tables are set to UTF8.</li>\n<li>Make sure all your PHP and template files are encoded as UTF8 if you store international characters in them.</li>\n</ul>\n\n<p>You usually don't have to do to much using the <code>mb_string</code> or <code>utf8_encode/decode</code>-functions when you do this.</p>\n"
},
{
"answer_id": 143627,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": false,
"text": "<p>Collation and charset are not the same thing. Your collation needs to match the charset, so if your charset is utf-8, so should the collation. Picking the wrong collation won't garble your data though - Just make string-comparison/sorting work wrongly.</p>\n\n<p>That said, there are several places, where you can set charset settings in PHP. I would recommend that you use utf-8 throughout, if possible. Places that needs charset specified are:</p>\n\n<ul>\n<li>The database. This can be set on database, table and field level, and even on a per-query level.</li>\n<li>Connection between PHP and database.</li>\n<li>HTTP output; Make sure that the HTTP-header <code>Content-Type</code> specifies utf-8. You can set default values in PHP and in Apache, or you can use PHP's <a href=\"http://docs.php.net/manual/en/function.header.php\" rel=\"nofollow noreferrer\"><code>header</code></a> function.</li>\n<li>HTTP input. Generally forms will be submitteed in the same charset as the page was served up in, but to make sure, you should specify the <a href=\"http://reference.sitepoint.com/html/form/accept-charset\" rel=\"nofollow noreferrer\"><code>accept-charset</code></a> property. Also make sure that URL's are utf-8 encoded, or avoid using non-ascii characters in url's (And GET parameters).</li>\n</ul>\n\n<p><a href=\"http://docs.php.net/manual/en/function.utf8-encode.php\" rel=\"nofollow noreferrer\"><code>utf8_encode</code></a>/decode functions are a little strangely named. They specifically convert between latin1 (ISO-8859-1) and utf-8. If everything in your application is utf-8, you won't have to use them much.</p>\n\n<p>There are at least two gotchas in regards to utf-8 and PHP. The first is that PHP's builtin string functions expect strings to be single-byte. For a lot of operations, this doesn't matter, but it means than you can't rely on <a href=\"http://docs.php.net/manual/en/function.strlen.php\" rel=\"nofollow noreferrer\"><code>strlen</code></a> and other functions. There is a good run-down of the limitations at <a href=\"http://www.phpwact.org/php/i18n/utf-8\" rel=\"nofollow noreferrer\">this page</a>. Usually, it's not a big problem, but especially when using 3-party libraries, you need to be aware that things could blow up on this. One option is also to use the mb_string extension, which has the option to replace all troublesome functions with utf-8 aware alternatives. It's still not a 100% bulletproof solution, but it'll work for most cases.</p>\n\n<p>Another problem is that some installations of PHP still has the <a href=\"http://docs.php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime\" rel=\"nofollow noreferrer\"><code>magic_quotes</code></a> setting turned on. This problem is orthogonal to utf-8, but can lead to some head scratching. Turn it off, for your own sanity's sake.</p>\n"
},
{
"answer_id": 144279,
"author": "Pete Karl II",
"author_id": 22491,
"author_profile": "https://Stackoverflow.com/users/22491",
"pm_score": 0,
"selected": false,
"text": "<p>Regardless of the language it's written in, if you were to create an app that allows a wide array of encodings, handle it in pieces:</p>\n\n<ul>\n<li>Identify the encoding\n\n<ul>\n<li>somehow you want to find out what kind of encoding you're dealing with, otherwise, it's pretty pointless to consider it further. You'll end up with junk chars.</li>\n</ul></li>\n<li>Handle your bytes\n\n<ul>\n<li>think of these strings less like 'strings' of characters, and more like lists of bytes</li>\n<li>PHP is especially sneaky. Don't let it truncate your data on-the-fly. If you're regexing a UTF-8 string, make sure you identify it as such</li>\n</ul></li>\n<li>Store for the LCD\n\n<ul>\n<li>Again, you don't want to truncate data. If you're storing a sentence in English, can you also store a set of Mandarin glyphps? How about Arabic? Which of these is going to require the most space? Account for it.</li>\n</ul></li>\n</ul>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
]
| It often happens that characters such as *é* gets transformed to *é*, even though the collation for the MySQL DB, table and field is set to utf8\_general\_ci. The encoding in the *Content-Type* for the page is also set to UTF8.
I know about utf8\_encode/decode, but I'm not quite sure about where and how to use it.
I have read the "[The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)" article, but I need some MySQL / PHP specific pointers.
How do I ensure that user entered data containing international characters doesn't get corrupted? | On the first look at <http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet> I think that one important thing is missing (perhaps I overlooked this one).
Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a
```
SET NAMES utf8
```
query prior to any other query you send to the MySQL server.
If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using
```
$db=new PDO($dsn, $user, $pass);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
```
when initializing your db connection. |
140,734 | <p>What would be the best practice way to handle the caching of images using PHP.</p>
<p>The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag.</p>
<p>When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. </p>
<p>The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner,</p>
<p>Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)</p>
| [
{
"answer_id": 140767,
"author": "sgibbons",
"author_id": 2327,
"author_profile": "https://Stackoverflow.com/users/2327",
"pm_score": 0,
"selected": false,
"text": "<p>Your approach seems quite reasonable - I would add that some mechanism should be put into place to check that the date the cached version was generated was after the last modified timestamp of the original (source) image file and if not regenerate the cached/resized version. This will ensure that if an image is changed by the designers the cache will be updated appropriately.</p>\n"
},
{
"answer_id": 140813,
"author": "Pete Karl II",
"author_id": 22491,
"author_profile": "https://Stackoverflow.com/users/22491",
"pm_score": 0,
"selected": false,
"text": "<p>That sounds like a solid way to do it. The next step may be to go beyond PHP/MySQL.</p>\n\n<p>Perhaps, <strong>tweak your headers</strong>:</p>\n\n<p>If you're using PHP to send MIME types, you might also use 'Keep-alive' and 'Cache-control' headers to extend the life of your images on the server and take some of the load off of PHP/MySQL.</p>\n\n<p>Also, consider apache plugin(s) for caching as well. Like <a href=\"http://httpd.apache.org/docs/2.0/mod/mod_expires.html\" rel=\"nofollow noreferrer\">mod_expires</a>.</p>\n\n<p>Oh, one more thing, how much control do you have over your server? Should we limit this conversation to <em>just</em> PHP/MySQL?</p>\n"
},
{
"answer_id": 141164,
"author": "user18334",
"author_id": 18334,
"author_profile": "https://Stackoverflow.com/users/18334",
"pm_score": 0,
"selected": false,
"text": "<p><strong>phpThumb</strong> is a framework that generates resized images/thumbnails on the fly. It also implements caching and it's very easy to implement. </p>\n\n<p>The code to resize an image is:</p>\n\n<pre><code><img src=\"/phpThumb.php?src=/path/to/image.jpg&w=200&amp;h=200\" alt=\"thumbnail\"/>\n</code></pre>\n\n<p>will give you a thumbnail of 200 x 200;</p>\n\n<p>It also supports watermarking.</p>\n\n<p>Check it out at:\n<a href=\"http://phpthumb.sourceforge.net/\" rel=\"nofollow noreferrer\">http://phpthumb.sourceforge.net/</a></p>\n"
},
{
"answer_id": 141224,
"author": "phatduckk",
"author_id": 3896,
"author_profile": "https://Stackoverflow.com/users/3896",
"pm_score": 3,
"selected": false,
"text": "<p>One note worth adding is to make sure you're code does not generate \"unauthorized\" sizes of these images.</p>\n\n<p>So the following URL will create a 200x200 version of image 1234 if one doesn't already exist. I'd <strong>highly</strong> suggest you make sure that the requested URL contains image dimensions you support. </p>\n\n<pre><code>/images/get/200x200/1234.jpg\n</code></pre>\n\n<p>A malicious person could start requesting random URLs, always altering the height & width of the image. This would cause your server some serious issues b/c it will be sitting there, essentially under attack, generating images of sizes you do not support.</p>\n\n<pre><code>/images/get/0x1/1234.jpg\n/images/get/0x2/1234.jpg\n...\n/images/get/0x9999999/1234.jpg\n/images/get/1x1/1234.jpg\n...\netc\n</code></pre>\n\n<p>Here's a random snip of code illustrating this:</p>\n\n<pre><code><?php\n\n $pathOnDisk = getImageDiskPath($_SERVER['REQUEST_URI']);\n\n if(file_exists($pathOnDisk)) {\n // send header with image mime type \n echo file_get_contents($pathOnDisk);\n exit;\n } else {\n $matches = array();\n $ok = preg_match(\n '/\\/images\\/get\\/(\\d+)x(\\d+)\\/(\\w+)\\.jpg/', \n $_SERVER['REQUEST_URI'], $matches);\n\n if(! $ok) {\n // invalid url\n handleInvalidRequest();\n } else {\n list(, $width, $height, $guid) = $matches;\n\n // you should do this!\n if(isSupportedSize($width, $height)) {\n // size is supported. all good\n // generate the resized image, save it & output it\n } else {\n // invalid size requested!!!\n handleInvalidRequest();\n }\n }\n }\n\n // snip\n function handleInvalidRequest() {\n // do something w/ invalid request \n // show a default graphic, log it etc\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 141378,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 5,
"selected": false,
"text": "<p>I would do it in a different manner.</p>\n\n<p>Problems:\n1. Having PHP serve the files out is less efficient than it could be.\n2. PHP has to check the existence of files every time an image is requested\n3. Apache is far better at this than PHP will ever be.</p>\n\n<p>There are a few solutions here.</p>\n\n<p>You can use <code>mod_rewrite</code> on Apache. It's possible to use mod_rewrite to test to see if a file exists, and if so, serve that file instead. This bypasses PHP entirely, and makes things far faster. The real way to do this, though, would be to generate a specific URL schema that should always exist, and then redirect to PHP if not.</p>\n\n<p>For example:</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} ^/images/cached/\nRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f\nRewriteRule (.*) /images/generate.php?$1 [L]\n</code></pre>\n\n<p>So if a client requests <code>/images/cached/<something></code> and that file doesn't exist already, Apache will redirect the request to <code>/images/generate.php?/images/cached/<something></code>. This script can then generate the image, write it to the cache, and then send it to the client. In the future, the PHP script is never called except for new images.</p>\n\n<p>Use caching. As another poster said, use things like <code>mod_expires</code>, Last-Modified headers, etc. to respond to conditional GET requests. If the client doesn't have to re-request images, page loads will speed dramatically, and load on the server will decrease.</p>\n\n<p>For cases where you do have to send an image from PHP, you can use <code>mod_xsendfile</code> to do it with less overhead. See <a href=\"http://blog.adaniels.nl/articles/how-i-php-x-sendfile/\" rel=\"noreferrer\">the excellent blog post from Arnold Daniels</a> on the issue, but note that his example is for downloads. To serve images inline, take out the Content-Disposition header (the third header() call).</p>\n\n<p>Hope this helps - more after my migraine clears up.</p>\n"
},
{
"answer_id": 600859,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Seems great post, but my problem still remains unsolved. I dont have access to htaccess in my host provider, so no question of apache tweaking. Is there really a way to set cace-control header for images?</p>\n"
},
{
"answer_id": 615675,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've managed to do this simply using a redirect header in PHP:</p>\n\n<pre><code>if (!file_exists($filename)) { \n\n // *** Insert code that generates image ***\n\n // Content type\n header('Content-type: image/jpeg'); \n\n // Output\n readfile($filename); \n\n} else {\n // Redirect\n $host = $_SERVER['HTTP_HOST'];\n $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\\\');\n $extra = $filename;\n header(\"Location: http://$host$uri/$extra\");\n}\n</code></pre>\n"
},
{
"answer_id": 1975086,
"author": "Sensi",
"author_id": 240240,
"author_profile": "https://Stackoverflow.com/users/240240",
"pm_score": 4,
"selected": true,
"text": "<p>There is two typos in Dan Udey's rewrite example (and I can't comment on it), it should rather be :</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} ^/images/cached/\nRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f\nRewriteRule (.*) /images/generate.php?$1 [L]\n</code></pre>\n\n<p>Regards.</p>\n"
},
{
"answer_id": 2573122,
"author": "Haluk",
"author_id": 174559,
"author_profile": "https://Stackoverflow.com/users/174559",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of keeping the file address in the db I prefer adding a random number to the file name whenever the user logs in. Something like this for user 1234: image/picture_1234.png?rnd=6534122341</p>\n\n<p>If the user submits a new picture during the session I just refresh the random number.</p>\n\n<p>GUID tackles the cache problem 100%. However it sort of makes it harder to keep track of the picture files. With this method there is a chance the user might see the same picture again at a future login. However the odds are low if you generate your random number from a billion numbers.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22776/"
]
| What would be the best practice way to handle the caching of images using PHP.
The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag.
When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size.
The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner,
Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.) | There is two typos in Dan Udey's rewrite example (and I can't comment on it), it should rather be :
```
RewriteCond %{REQUEST_URI} ^/images/cached/
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule (.*) /images/generate.php?$1 [L]
```
Regards. |
140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| [
{
"answer_id": 140778,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 2,
"selected": false,
"text": "<p>Straight from Python's Refererence Library</p>\n\n<pre><code>>>> import glob\n>>> glob.glob('./[0-9].*')\n['./1.gif', './2.txt']\n>>> glob.glob('*.gif')\n['1.gif', 'card.gif']\n>>> glob.glob('?.gif')\n['1.gif']\n</code></pre>\n"
},
{
"answer_id": 140795,
"author": "Big Dave Diode",
"author_id": 9448,
"author_profile": "https://Stackoverflow.com/users/9448",
"pm_score": 2,
"selected": false,
"text": "<p>Try \"listdir()\" in the os module (<a href=\"http://docs.python.org/lib/os-file-dir.html\" rel=\"nofollow noreferrer\">docs</a>):</p>\n\n<pre><code>import os\nprint os.listdir('.')\n</code></pre>\n"
},
{
"answer_id": 140805,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at <code>os.walk()</code> and the examples <a href=\"http://docs.python.org/lib/os-file-dir.html\" rel=\"nofollow noreferrer\">here</a>. With <code>os.walk()</code> you can easily process a whole directory tree. </p>\n\n<p>An example from the link above...</p>\n\n<pre><code># Delete everything reachable from the directory named in 'top',\n# assuming there are no symbolic links.\n# CAUTION: This is dangerous! For example, if top == '/', it\n# could delete all your disk files.\nimport os\nfor root, dirs, files in os.walk(top, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n</code></pre>\n"
},
{
"answer_id": 140818,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, there is. The Python way is even better.</p>\n\n<p>There are three possibilities:</p>\n\n<p><strong>1) Like File.listFiles():</strong></p>\n\n<p>Python has the function os.listdir(path). It works like the Java method.</p>\n\n<p><strong>2) pathname pattern expansion with glob:</strong></p>\n\n<p>The module glob contains functions to list files on the file system using Unix shell like pattern, e.g.\n<code><pre>\nfiles = glob.glob('/usr/joe/*.gif')\n</pre></code></p>\n\n<p><strong>3) File Traversal with walk:</strong></p>\n\n<p>Really nice is the os.walk function of Python.</p>\n\n<p>The walk method returns a generation function that recursively list all directories and files below a given starting path.</p>\n\n<p>An Example:\n <code><pre>\nimport os\nfrom os.path import join\nfor root, dirs, files in os.walk('/usr'):\n print \"Current directory\", root\n print \"Sub directories\", dirs\n print \"Files\", files\n</pre></code>\nYou can even on the fly remove directories from \"dirs\" to avoid walking to that dir: if \"joe\" in dirs: dirs.remove(\"joe\") to avoid walking into directories called \"joe\".</p>\n\n<p>listdir and walk are documented <a href=\"http://docs.python.org/lib/os-file-dir.html\" rel=\"noreferrer\">here</a>.\nglob is documented <a href=\"http://docs.python.org/lib/module-glob.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 140822,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 2,
"selected": false,
"text": "<p>Use os.path.walk if you want subdirectories as well.</p>\n\n<pre>walk(top, func, arg)\n\n Directory tree walk with callback function.\n\n For each directory in the directory tree rooted at top (including top\n itself, but excluding '.' and '..'), call func(arg, dirname, fnames).\n dirname is the name of the directory, and fnames a list of the names of\n the files and subdirectories in dirname (excluding '.' and '..'). func\n may modify the fnames list in-place (e.g. via del or slice assignment),\n and walk will only recurse into the subdirectories whose names remain in\n fnames; this can be used to implement a filter, or to impose a specific\n order of visiting. No semantics are defined for, or required of, arg,\n beyond that arg is always passed to func. It can be used, e.g., to pass\n a filename pattern, or a mutable object designed to accumulate\n statistics. Passing None for arg is common.\n</pre>\n"
},
{
"answer_id": 141277,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend against <code>os.path.walk</code> as it is being removed in Python 3.0. <code>os.walk</code> is simpler, anyway, or at least <em>I</em> find it simpler.</p>\n"
},
{
"answer_id": 143227,
"author": "Max Maximus",
"author_id": 19627,
"author_profile": "https://Stackoverflow.com/users/19627",
"pm_score": 3,
"selected": false,
"text": "<p>As a long-time Pythonista, I have to say the path/file manipulation functions in the std library are sub-par: they are not object-oriented and they reflect an obsolete, lets-wrap-OS-system-functions-without-thinking philosophy. I'd heartily recommend the 'path' module as a wrapper (around os, os.path, glob and tempfile if you must know): much nicer and OOPy: <a href=\"http://pypi.python.org/pypi/path.py/2.2\" rel=\"nofollow noreferrer\">http://pypi.python.org/pypi/path.py/2.2</a></p>\n\n<p>This is walk() with the path module:</p>\n\n<pre><code>dir = path(os.environ['HOME'])\nfor f in dir.walk():\n if f.isfile() and f.endswith('~'):\n f.remove()\n</code></pre>\n"
},
{
"answer_id": 18465955,
"author": "metakermit",
"author_id": 544059,
"author_profile": "https://Stackoverflow.com/users/544059",
"pm_score": 1,
"selected": false,
"text": "<p>You can also check out <a href=\"https://github.com/mikeorr/Unipath\" rel=\"nofollow\">Unipath</a>, an object-oriented wrapper of Python's <code>os</code>, <code>os.path</code> and <code>shutil</code> modules.</p>\n\n<p>Example:</p>\n\n<pre><code>>>> from unipath import Path\n>>> p = Path('/Users/kermit')\n>>> p.listdir()\nPath(u'/Users/kermit/Applications'),\nPath(u'/Users/kermit/Desktop'),\nPath(u'/Users/kermit/Documents'),\nPath(u'/Users/kermit/Downloads'),\n...\n</code></pre>\n\n<p>Installation through Cheese shop:</p>\n\n<pre><code>$ pip install unipath\n</code></pre>\n"
},
{
"answer_id": 35705659,
"author": "Hazim Sager",
"author_id": 5998003,
"author_profile": "https://Stackoverflow.com/users/5998003",
"pm_score": 0,
"selected": false,
"text": "<p>Seeing as i have programmed in python for a long time, i have many times used the os module and made my own function to print all files in a directory.</p>\n\n<p>The code for the function:</p>\n\n<pre><code>import os\n\ndef PrintFiles(direc):\n files = os.listdir(direc)\n for x in range(len(files)):\n print(\"File no. \"+str(x+1)+\": \"+files[x])\n\nPrintFiles(direc)\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
| In Java you can do `File.listFiles()` and receive all of the files in a directory. You can then easily recurse through directory trees.
Is there an analogous way to do this in Python? | Yes, there is. The Python way is even better.
There are three possibilities:
**1) Like File.listFiles():**
Python has the function os.listdir(path). It works like the Java method.
**2) pathname pattern expansion with glob:**
The module glob contains functions to list files on the file system using Unix shell like pattern, e.g.
````
files = glob.glob('/usr/joe/*.gif')
````
**3) File Traversal with walk:**
Really nice is the os.walk function of Python.
The walk method returns a generation function that recursively list all directories and files below a given starting path.
An Example:
````
import os
from os.path import join
for root, dirs, files in os.walk('/usr'):
print "Current directory", root
print "Sub directories", dirs
print "Files", files
````
You can even on the fly remove directories from "dirs" to avoid walking to that dir: if "joe" in dirs: dirs.remove("joe") to avoid walking into directories called "joe".
listdir and walk are documented [here](http://docs.python.org/lib/os-file-dir.html).
glob is documented [here](http://docs.python.org/lib/module-glob.html). |
140,786 | <p>The code is</p>
<pre><code>return min + static_cast<int>(static_cast<double>(max - min + 1.0) *
(number / (UINT_MAX + 1.0)));
</code></pre>
<p>number is a random number obtained by rand_s. min and max are ints and represent minimum and maximum values (inclusive).</p>
<p>If you provide a solution not using unsigned int as a number, please also explain how to make it be random.</p>
<p>Please do not submit solutions using rand().</p>
| [
{
"answer_id": 140812,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>How about <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/random/index.html\" rel=\"nofollow noreferrer\">Boost:Random</a></p>\n"
},
{
"answer_id": 140826,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": -1,
"selected": false,
"text": "<p>Something like</p>\n\n<pre><code>min + number % (max - min + 1)\n</code></pre>\n\n<p>Check the end-cases</p>\n"
},
{
"answer_id": 140848,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 2,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/140786/how-to-simplify-this-code-generates-a-random-int-between-min-and-max-base-on-un#140826\">Andrew Stein</a></p>\n\n<p>In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following comments are made:</p>\n\n<blockquote>\n <p>\"If you want to generate a random\n integer between 1 and 10, you should\n always do it by using high-order bits,\n as in </p>\n \n <p><code>j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));</code> </p>\n \n <p>and never by\n anything resembling </p>\n \n <p><code>j = 1 + (rand() % 10);</code> </p>\n \n <p>(which uses lower-order bits).\"</p>\n</blockquote>\n\n<p>From <code>man 3 rand</code></p>\n"
},
{
"answer_id": 140865,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>static_cast<double></code> is redundant because the \"+1.0\"s will cause promotion to double anyway.</p>\n"
},
{
"answer_id": 141340,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 0,
"selected": false,
"text": "<p>You could do the arithmetic in an unsigned long long instead of a double, but only if ULONGLONG_MAX >= UINT_MAX*UINT_MAX, which is probably implementation defined. But if you're worried about that, you'd be worried about potential loss of precision in the original code in the case where (max - min) or RAND_MAX is large.</p>\n\n<p>Whether the long long is actually faster might depend how good your platform's hardware float is. But integer arithmetic arguably is inherently simpler than floating-point.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
]
| The code is
```
return min + static_cast<int>(static_cast<double>(max - min + 1.0) *
(number / (UINT_MAX + 1.0)));
```
number is a random number obtained by rand\_s. min and max are ints and represent minimum and maximum values (inclusive).
If you provide a solution not using unsigned int as a number, please also explain how to make it be random.
Please do not submit solutions using rand(). | The `static_cast<double>` is redundant because the "+1.0"s will cause promotion to double anyway. |
140,820 | <p>Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running?</p>
<p>[Update 2]</p>
<p>Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable:</p>
<pre><code>using System.Threading;
[...]
/// <summary>
/// Wait (up to a timeout) for the MSI installer service to become free.
/// </summary>
/// <returns>
/// Returns true for a successful wait, when the installer service has become free.
/// Returns false when waiting for the installer service has exceeded the timeout.
/// </returns>
public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime)
{
// The _MSIExecute mutex is used by the MSI installer service to serialize installations
// and prevent multiple MSI based installations happening at the same time.
// For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx
const string installerServiceMutexName = "Global\\_MSIExecute";
try
{
Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,
System.Security.AccessControl.MutexRights.Synchronize | System.Security.AccessControl.MutexRights.Modify);
bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false);
MSIExecuteMutex.ReleaseMutex();
return waitSuccess;
}
catch (WaitHandleCannotBeOpenedException)
{
// Mutex doesn't exist, do nothing
}
catch (ObjectDisposedException)
{
// Mutex was disposed between opening it and attempting to wait on it, do nothing
}
return true;
}
</code></pre>
| [
{
"answer_id": 140875,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 4,
"selected": true,
"text": "<p>See the description of the <a href=\"http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx\" rel=\"noreferrer\">_MSIExecute Mutex</a> on MSDN.</p>\n"
},
{
"answer_id": 22026461,
"author": "NBPC77",
"author_id": 235100,
"author_profile": "https://Stackoverflow.com/users/235100",
"pm_score": 2,
"selected": false,
"text": "<p>I was getting an unhandled exception using the code above. I cross referenced this article witt this <a href=\"https://stackoverflow.com/questions/17070583/releasing-a-mutex\">one</a></p>\n\n<p>Here's my updated code:</p>\n\n<pre><code> /// <summary>\n/// Wait (up to a timeout) for the MSI installer service to become free.\n/// </summary>\n/// <returns>\n/// Returns true for a successful wait, when the installer service has become free.\n/// Returns false when waiting for the installer service has exceeded the timeout.\n/// </returns>\npublic static bool IsMsiExecFree(TimeSpan maxWaitTime)\n{\n // The _MSIExecute mutex is used by the MSI installer service to serialize installations\n // and prevent multiple MSI based installations happening at the same time.\n // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx\n const string installerServiceMutexName = \"Global\\\\_MSIExecute\";\n Mutex MSIExecuteMutex = null;\n var isMsiExecFree = false;\n try\n {\n MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,\n System.Security.AccessControl.MutexRights.Synchronize);\n isMsiExecFree = MSIExecuteMutex.WaitOne(maxWaitTime, false);\n }\n catch (WaitHandleCannotBeOpenedException)\n {\n // Mutex doesn't exist, do nothing\n isMsiExecFree = true;\n }\n catch (ObjectDisposedException)\n {\n // Mutex was disposed between opening it and attempting to wait on it, do nothing\n isMsiExecFree = true;\n }\n finally\n {\n if(MSIExecuteMutex != null && isMsiExecFree)\n MSIExecuteMutex.ReleaseMutex();\n }\n return isMsiExecFree;\n\n}\n</code></pre>\n"
},
{
"answer_id": 33652559,
"author": "Roadie",
"author_id": 2412770,
"author_profile": "https://Stackoverflow.com/users/2412770",
"pm_score": 2,
"selected": false,
"text": "<p>I have been working on this - for about a week - using your notes (Thank you) and that from other sites - too many to name (Thank you all).</p>\n<p>I stumbled across information revealing that the Service could yield enough information to determine if the MSIEXEC service is already in use. The Service being 'msiserver' - Windows Installer - and it's information being both state and acceptstop.</p>\n<p>The following VBScript code checks this:</p>\n<pre><code>Set objWMIService = GetObject("winmgmts:\\\\.\\root\\cimv2")\nCheck = False\nDo While Not Check\n WScript.Sleep 3000\n Set colServices = objWMIService.ExecQuery("Select * From Win32_Service Where Name="'msiserver'")\n For Each objService In colServices\n If (objService.Started And Not objService.AcceptStop) \n WScript.Echo "Another .MSI is running."\n ElseIf ((objService.Started And objService.AcceptStop) Or Not objService.Started) Then\n WScript.Echo "Ready to install an .MSI application."\n Check = True\n End If\n Next\nLoop\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332/"
]
| Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running?
[Update 2]
Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable:
```
using System.Threading;
[...]
/// <summary>
/// Wait (up to a timeout) for the MSI installer service to become free.
/// </summary>
/// <returns>
/// Returns true for a successful wait, when the installer service has become free.
/// Returns false when waiting for the installer service has exceeded the timeout.
/// </returns>
public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime)
{
// The _MSIExecute mutex is used by the MSI installer service to serialize installations
// and prevent multiple MSI based installations happening at the same time.
// For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx
const string installerServiceMutexName = "Global\\_MSIExecute";
try
{
Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,
System.Security.AccessControl.MutexRights.Synchronize | System.Security.AccessControl.MutexRights.Modify);
bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false);
MSIExecuteMutex.ReleaseMutex();
return waitSuccess;
}
catch (WaitHandleCannotBeOpenedException)
{
// Mutex doesn't exist, do nothing
}
catch (ObjectDisposedException)
{
// Mutex was disposed between opening it and attempting to wait on it, do nothing
}
return true;
}
``` | See the description of the [\_MSIExecute Mutex](http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx) on MSDN. |
140,825 | <p>Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?</p>
<pre><code>struct myobj {
int value;
}
/* This macro does not satisfy the read-only requirement */
#define VALUE(o) (o)->value
/* This macro uses a function, unfortunately */
int getvalue(struct myobj *o) { return o->value; }
#define VALUE(o) getvalue(o)
void dostuff(struct myobj *foo) {
printf("The value of foo is %d.\n", VALUE(foo)); /* OK */
VALUE(foo) = 1; /* We want a compile error here */
foo->value = 1; /* This is ok. */
}
</code></pre>
| [
{
"answer_id": 140853,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 4,
"selected": true,
"text": "<p>If the variable is always numeric, this works:</p>\n\n<pre><code>#define VALUE(x) (x+0)\n</code></pre>\n\n<p>or in the context of your example,</p>\n\n<pre><code>#define VALUE(x) (x->value+0)\n</code></pre>\n"
},
{
"answer_id": 140870,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>#define VALUE(o) (const int)((o)->value)\n</code></pre>\n"
},
{
"answer_id": 140894,
"author": "Joshua Swink",
"author_id": 14732,
"author_profile": "https://Stackoverflow.com/users/14732",
"pm_score": 4,
"selected": false,
"text": "<p>Ok, I came up with one:</p>\n\n<pre><code>#define VALUE(o) (1 ? (o)->value : 0)\n</code></pre>\n"
},
{
"answer_id": 140961,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": -1,
"selected": false,
"text": "<p>Is this a puzzle or is it an engineering task?\nIf it's an engineering task, then there are better ways to get opacity of structures in C. In <a href=\"http://www.atalasoft.com/cs/blogs/stevehawley/archive/2008/07/02/how-to-build-a-managed-unmanaged-library.aspx\" rel=\"nofollow noreferrer\">this blog article</a>, I wrote a decent enough description of how to do that in C.</p>\n"
},
{
"answer_id": 4854735,
"author": "J. C. Salomon",
"author_id": 95580,
"author_profile": "https://Stackoverflow.com/users/95580",
"pm_score": 3,
"selected": false,
"text": "<p>See §6.5.17 in the C standard (C99 & C1x): “A comma operator does not yield an lvalue.”</p>\n\n<pre><code>#define VALUE(x) (0, x)\n</code></pre>\n\n<p>(Not portable to C++.)</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14732/"
]
| Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?
```
struct myobj {
int value;
}
/* This macro does not satisfy the read-only requirement */
#define VALUE(o) (o)->value
/* This macro uses a function, unfortunately */
int getvalue(struct myobj *o) { return o->value; }
#define VALUE(o) getvalue(o)
void dostuff(struct myobj *foo) {
printf("The value of foo is %d.\n", VALUE(foo)); /* OK */
VALUE(foo) = 1; /* We want a compile error here */
foo->value = 1; /* This is ok. */
}
``` | If the variable is always numeric, this works:
```
#define VALUE(x) (x+0)
```
or in the context of your example,
```
#define VALUE(x) (x->value+0)
``` |
140,926 | <p>I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?</p>
<p>So something that would yield this kind of translation table:</p>
<pre><code>\r --> \r\n
\n --> \r\n
\n\n --> \r\n\r\n
\n\r --> \r\n
\r\n --> \r\n
\r\n\n --> \r\n\r\n
</code></pre>
| [
{
"answer_id": 140952,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "<p>A Regex would help.. could do something roughly like this..</p>\n\n<p>(\\r\\n|\\n\\n|\\n\\r|\\r|\\n) replace with \\r\\n</p>\n\n<p>This regex produced these results from the table posted (just testing left side) so a replace should normalize.</p>\n\n<pre><code>\\r => \\r \n\\n => \\n \n\\n\\n => \\n\\n \n\\n\\r => \\n\\r \n\\r\\n => \\r\\n \n\\r\\n => \\r\\n \n\\n => \\n \n</code></pre>\n"
},
{
"answer_id": 141016,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 2,
"selected": false,
"text": "<p>You're thinking too complicated. \nIgnore every \\r and turn every \\n into an \\r\\n.</p>\n\n<p>In Pseudo-C#:</p>\n\n<pre><code>char[] chunk = new char[X];\nStringBuffer output = new StringBuffer();\n\nbuffer.Read(chunk);\nforeach (char c in chunk)\n{\n switch (c)\n {\n case '\\r' : break; // ignore\n case '\\n' : output.Append(\"\\r\\n\");\n default : output.Append(c);\n }\n }\n</code></pre>\n\n<p><strong>EDIT</strong>: \\r alone is no line-terminator so I doubt you really want to expand \\r to \\r\\n.</p>\n"
},
{
"answer_id": 141069,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 6,
"selected": true,
"text": "<p>I believe this will do what you need:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n// ...\nstring normalized = Regex.Replace(originalString, @\"\\r\\n|\\n\\r|\\n|\\r\", \"\\r\\n\");\n</code></pre>\n\n<p>I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct) C#. The only real trick is to match \"\\r\\n\" and \"\\n\\r\" first.</p>\n\n<p>To apply it to an entire stream, just run in on chunks of input. (You could do this with a stream wrapper if you want.)</p>\n\n<hr>\n\n<p>The original perl:</p>\n\n<pre><code>$str =~ s/\\r\\n|\\n\\r|\\n|\\r/\\r\\n/g;\n</code></pre>\n\n<p>The test results:</p>\n\n<pre><code>[bash$] ./test.pl\n\\r -> \\r\\n\n\\n -> \\r\\n\n\\n\\n -> \\r\\n\\r\\n\n\\n\\r -> \\r\\n\n\\r\\n -> \\r\\n\n\\r\\n\\n -> \\r\\n\\r\\n\n</code></pre>\n\n<hr>\n\n<p>Update: Now converts \\n\\r to \\r\\n, though I wouldn't call that normalization.</p>\n"
},
{
"answer_id": 142185,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": false,
"text": "<p>I'm with Jamie Zawinski on RegEx: </p>\n\n<p>\"Some people, when confronted with a problem, think \"I know, I’ll use regular expressions.\" Now they have two problems\"</p>\n\n<p>For those of us who prefer readability:</p>\n\n<ul>\n<li><p>Step 1</p>\n\n<p>Replace \\r\\n by \\n</p>\n\n<p>Replace \\n\\r by \\n (if you really want this, some posters seem to think not)</p>\n\n<p>Replace \\r by \\n</p></li>\n<li><p>Step 2 \nReplace \\n by Environment.NewLine or \\r\\n or whatever.</p></li>\n</ul>\n"
},
{
"answer_id": 41696844,
"author": "Phil",
"author_id": 5048621,
"author_profile": "https://Stackoverflow.com/users/5048621",
"pm_score": 2,
"selected": false,
"text": "<p>Normalise breaks, so that they are all <code>\\r\\n</code></p>\n\n<pre><code>var normalisedString =\n sourceString\n .Replace(\"\\r\\n\", \"\\n\")\n .Replace(\"\\n\\r\", \"\\n\")\n .Replace(\"\\r\", \"\\n\")\n .Replace(\"\\n\", \"\\r\\n\");\n</code></pre>\n"
},
{
"answer_id": 47349387,
"author": "Roberto B",
"author_id": 2641447,
"author_profile": "https://Stackoverflow.com/users/2641447",
"pm_score": 0,
"selected": false,
"text": "<p>This is the answer to the question. The given solution replaces a string by the given translation table.\nIt does not use an expensive regex function.\nIt also does not use multiple replacement functions that each individually did loop over the data with several checks etc.</p>\n\n<p>So the search is done directly in 1 for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops.\nIn some cases, a larger page size might be more efficient.</p>\n\n<pre><code>public static string NormalizeNewLine(this string val)\n{\n if (string.IsNullOrEmpty(val))\n return val;\n\n const int page = 6;\n int a = page;\n int j = 0;\n int len = val.Length;\n char[] res = new char[len];\n\n for (int i = 0; i < len; i++)\n {\n char ch = val[i];\n\n if (ch == '\\r')\n {\n int ni = i + 1;\n if (ni < len && val[ni] == '\\n')\n {\n res[j++] = '\\r';\n res[j++] = '\\n';\n i++;\n }\n else\n {\n if (a == page) //ensure capacity\n {\n char[] nres = new char[res.Length + page];\n Array.Copy(res, 0, nres, 0, res.Length);\n res = nres;\n a = 0;\n }\n\n res[j++] = '\\r';\n res[j++] = '\\n';\n a++;\n }\n }\n else if (ch == '\\n')\n {\n int ni = i + 1;\n if (ni < len && val[ni] == '\\r')\n {\n res[j++] = '\\r';\n res[j++] = '\\n';\n i++;\n }\n else\n {\n if (a == page) //ensure capacity\n {\n char[] nres = new char[res.Length + page];\n Array.Copy(res, 0, nres, 0, res.Length);\n res = nres;\n a = 0;\n }\n\n res[j++] = '\\r';\n res[j++] = '\\n';\n a++;\n }\n }\n else\n {\n res[j++] = ch;\n }\n }\n\n return new string(res, 0, j);\n}\n</code></pre>\n\n<p>The translation table really appeals to me even if '\\n\\r' is not actually used on basic platforms. Who would use two types of linebreaks for indicate 2 linebreaks?\nIf you want to know that, than you need to take a look before to know if the \\n and \\r both are used seperatly in the same document.</p>\n"
},
{
"answer_id": 64300331,
"author": "GDavoli",
"author_id": 5429854,
"author_profile": "https://Stackoverflow.com/users/5429854",
"pm_score": 2,
"selected": false,
"text": "<p>It's a two step process.<br/>\nFirst you convert all the combinations of <code>\\r</code> and <code>\\n</code> into a single one, say <code>\\r</code><br/>\nThen you convert all the <code>\\r</code> into your target <code>\\r\\n</code></p>\n<pre><code>normalized = \n original.Replace("\\r\\n", "\\r").\n Replace("\\n\\r", "\\r").\n Replace("\\n", "\\r").\n Replace("\\r", "\\r\\n"); // last step\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13154/"
]
| I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?
So something that would yield this kind of translation table:
```
\r --> \r\n
\n --> \r\n
\n\n --> \r\n\r\n
\n\r --> \r\n
\r\n --> \r\n
\r\n\n --> \r\n\r\n
``` | I believe this will do what you need:
```
using System.Text.RegularExpressions;
// ...
string normalized = Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n");
```
I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct) C#. The only real trick is to match "\r\n" and "\n\r" first.
To apply it to an entire stream, just run in on chunks of input. (You could do this with a stream wrapper if you want.)
---
The original perl:
```
$str =~ s/\r\n|\n\r|\n|\r/\r\n/g;
```
The test results:
```
[bash$] ./test.pl
\r -> \r\n
\n -> \r\n
\n\n -> \r\n\r\n
\n\r -> \r\n
\r\n -> \r\n
\r\n\n -> \r\n\r\n
```
---
Update: Now converts \n\r to \r\n, though I wouldn't call that normalization. |
140,935 | <p>Anyone knows if is possible to have partial class definition on C++ ?</p>
<p>Something like:</p>
<p>file1.h:</p>
<pre>
class Test {
public:
int test1();
};
</pre>
<p>file2.h: </p>
<pre>
class Test {
public:
int test2();
};
</pre>
<p>For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes.</p>
<p>I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs. </p>
<p>Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class:</p>
<pre>
class genericTest {
public:
int genericMethod();
};
</pre>
<p>Then let's say for win32:</p>
<pre>
class win32Test: public genericTest {
public:
int win32Method();
};
</pre>
<p>And maybe:</p>
<pre>
class macTest: public genericTest {
public:
int macMethod();
};
</pre>
<p>Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this:</p>
<pre>
#ifdef _WIN32
genericTest *test = new win32Test();
#elif MAC
genericTest *test = new macTest();
#endif
test->genericMethod();
</pre>
<p>Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code.</p>
<p>That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.</p>
| [
{
"answer_id": 140942,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 4,
"selected": false,
"text": "<p>Try inheritance</p>\n\n<p>Specifically</p>\n\n<pre><code>class AllPlatforms {\npublic:\n int common();\n};\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>class PlatformA : public AllPlatforms {\npublic:\n int specific();\n};\n</code></pre>\n"
},
{
"answer_id": 140944,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "<p>This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.</p>\n"
},
{
"answer_id": 140958,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 2,
"selected": false,
"text": "<p>As written, it is not possible.</p>\n\n<p>You may want to look into namespaces. You can add a function to a namespace in another file. The problem with a class is that each .cpp needs to see the full layout of the class.</p>\n"
},
{
"answer_id": 140966,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 2,
"selected": false,
"text": "<p>Nope.</p>\n\n<p>But, you may want to look up a technique called \"Policy Classes\". Basically, you make micro-classes (that aren't useful on their own) then glue them together at some later point.</p>\n"
},
{
"answer_id": 140967,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 1,
"selected": false,
"text": "<p>Declaring a class body twice will likely generate a type redefinition error. If you're looking for a work around. I'd suggest #ifdef'ing, or using an <a href=\"http://en.wikipedia.org/wiki/Abstract_base_class\" rel=\"nofollow noreferrer\">Abstract Base Class</a> to hide platform specific details.</p>\n"
},
{
"answer_id": 140969,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 2,
"selected": false,
"text": "<p>Either use inheritance, as Jamie said, or #ifdef to make different parts compile on different platforms.</p>\n"
},
{
"answer_id": 140978,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 2,
"selected": false,
"text": "<p>Since headers are just textually inserted, one of them could omit the \"class Test {\" and \"}\" and be #included in the middle of the other.</p>\n\n<p>I've actually seen this in production code, albeit Delphi not C++. It particularly annoyed me because it broke the IDE's code navigation features.</p>\n"
},
{
"answer_id": 141028,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent.</p>\n</blockquote>\n\n<p>Except developers have been doing this for decades without this 'feature'.</p>\n\n<p>I believe partial was created because Microsoft has had, for decades also, a bad habit of generating code and handing it off to developers to develop and maintain.</p>\n\n<p>Generated code is often a maintenance nightmare. What habits to that entire MFC generated framework when you need to bump your MFC version? Or how do you port all that code in *.designer.cs files when you upgrade Visual Studio?</p>\n\n<p>Most other platforms rely more heavily on generating <strong>configuration files</strong> instead that the user/developer can modify. Those, having a more limited vocabulary and not prone to be mixed with unrelated code. The configuration files can even be inserted in the binary as a resource file if deemed necessary.</p>\n\n<p>I have never seen 'partial' used in a place where inheritance or a configuration resource file wouldn't have done a better job.</p>\n"
},
{
"answer_id": 141043,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can get something like partial classes using <em>template specialization</em> and <em>partial specialization</em>. Before you invest too much time, check your compiler's support for these. Older compilers like MSC++ 6.0 didn't support partial specialization.</p>\n"
},
{
"answer_id": 141085,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": 4,
"selected": false,
"text": "<p>or you could try PIMPL</p>\n\n<p>common header file:</p>\n\n<pre><code>class Test\n{\npublic:\n ...\n void common();\n ...\nprivate:\n class TestImpl;\n TestImpl* m_customImpl;\n};\n</code></pre>\n\n<p>Then create the cpp files doing the custom implementations that are platform specific.</p>\n"
},
{
"answer_id": 141092,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 2,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>class WindowsFuncs { public: int f(); int winf(); };\nclass MacFuncs { public: int f(); int macf(); }\n\nclass Funcs\n#ifdef Windows \n : public WindowsFuncs\n#else\n : public MacFuncs\n#endif\n{\npublic:\n Funcs();\n int g();\n};\n</code></pre>\n\n<p>Now <code>Funcs</code> is a class known at compile-time, so no overheads are caused by abstract base classes or whatever.</p>\n"
},
{
"answer_id": 141482,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#include will work as that is preprocessor stuff.\n\nclass Foo\n{\n#include \"FooFile_Private.h\"\n}\n\n////////\n\nFooFile_Private.h:\n\nprivate:\n void DoSg();\n</code></pre>\n"
},
{
"answer_id": 150018,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 4,
"selected": false,
"text": "<p>You can't partially define classes in C++.</p>\n<p>Here's a way to get the "polymorphism, where there's only one subclass" effect you're after without overhead and with a bare minimum of #define or code duplication. It's called simulated dynamic binding:</p>\n<pre><code>template <typename T>\nclass genericTest {\npublic:\n void genericMethod() {\n // do some generic things\n std::cout << "Could be any platform, I don't know" << std::endl;\n // base class can call a method in the child with static_cast\n (static_cast<T*>(this))->doClassDependentThing();\n }\n};\n\n#ifdef _WIN32\n typedef Win32Test Test;\n#elif MAC\n typedef MacTest Test;\n#endif\n</code></pre>\n<p>Then off in some other headers you'll have:</p>\n<pre><code>class Win32Test : public genericTest<Win32Test> {\npublic:\n void win32Method() {\n // windows-specific stuff:\n std::cout << "I'm in windows" << std::endl;\n // we can call a method in the base class\n genericMethod();\n // more windows-specific stuff...\n }\n void doClassDependentThing() {\n std::cout << "Yep, definitely in windows" << std::endl;\n }\n};\n</code></pre>\n<p>and</p>\n<pre><code>class MacTest : public genericTest<MacTest> {\npublic:\n void macMethod() {\n // mac-specific stuff:\n std::cout << "I'm in MacOS" << std::endl;\n // we can call a method in the base class\n genericMethod();\n // more mac-specific stuff...\n }\n void doClassDependentThing() {\n std::cout << "Yep, definitely in MacOS" << std::endl;\n }\n};\n</code></pre>\n<p>This gives you proper polymorphism at compile time. genericTest can non-virtually call doClassDependentThing in a way that gives it the platform version, (almost like a virtual method), and when win32Method calls genericMethod it of course gets the base class version.</p>\n<p>This creates no overhead associated with virtual calls - you get the same performance as if you'd typed out two big classes with no shared code. It may create a non-virtual call overhead at con(de)struction, but if the con(de)structor for genericTest is inlined you should be fine, and that overhead is in any case no worse than having a genericInit method that's called by both platforms.</p>\n<p>Client code just creates instances of Test, and can call methods on them which are either in genericTest or in the correct version for the platform. To help with type safety in code which doesn't care about the platform and doesn't want to accidentally make use of platform-specific calls, you could additionally do:</p>\n<pre><code>#ifdef _WIN32\n typedef genericTest<Win32Test> BaseTest;\n#elif MAC\n typedef genericTest<MacTest> BaseTest;\n#endif\n</code></pre>\n<p>You have to be a bit careful using BaseTest, but not much more so than is always the case with base classes in C++. For instance, don't slice it with an ill-judged pass-by-value. And don't instantiate it directly, because if you do and call a method that ends up attempting a "fake virtual" call, you're in trouble. The latter can be enforced by ensuring that all of genericTest's constructors are protected.</p>\n"
},
{
"answer_id": 9195739,
"author": "jessn",
"author_id": 1197478,
"author_profile": "https://Stackoverflow.com/users/1197478",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>This is not possible in C++, it will give you an error about redefining already-defined \n classes. If you'd like to share behavior, consider inheritance.</p>\n</blockquote>\n\n<p>I do agree on this. Partial classes is strange construct that makes it very difficult to maintain afterwards. It is difficult to locate on which partial class each member is declared and redefinition or even reimplementation of features are hard to avoid.</p>\n\n<p>Do you want to extend the std::vector, you have to inherit from it. This is because of several reasons. First of all you change the responsibility of the class and (properly?) its class invariants. Secondly, from a security point of view this should be avoided. \nConsider a class that handles user authentication... </p>\n\n<pre><code>partial class UserAuthentication {\n private string user;\n private string password;\n public bool signon(string usr, string pwd);\n}\n\npartial class UserAuthentication {\n private string getPassword() { return password; }\n}\n</code></pre>\n\n<p>A lot of other reasons could be mentioned...</p>\n"
},
{
"answer_id": 15291928,
"author": "Chawathe Vipul S",
"author_id": 1624169,
"author_profile": "https://Stackoverflow.com/users/1624169",
"pm_score": 1,
"selected": false,
"text": "<p>Let platform independent and platform dependent classes/functions be each-others friend classes/functions. :)</p>\n\n<p>And their separate name identifiers permit finer control over instantiation, so coupling is looser. Partial breaks encapsulation foundation of OO far too absolutely, whereas the requisite friend declarations barely relax it just enough to facilitate multi-paradigm Separation of Concerns like Platform Specific aspects from Domain-Specific platform independent ones.</p>\n"
},
{
"answer_id": 21412322,
"author": "SONIC3D",
"author_id": 1758069,
"author_profile": "https://Stackoverflow.com/users/1758069",
"pm_score": 2,
"selected": false,
"text": "<p>Dirty but practical way is using #include preprocessor:</p>\n\n<p>Test.h:</p>\n\n<pre><code>#ifndef TEST_H\n#define TEST_H\n\nclass Test\n{\npublic:\n Test(void);\n virtual ~Test(void);\n\n#include \"Test_Partial_Win32.h\"\n#include \"Test_Partial_OSX.h\"\n\n};\n\n#endif // !TEST_H\n</code></pre>\n\n<p>Test_Partial_OSX.h:</p>\n\n<pre><code>// This file should be included in Test.h only.\n\n#ifdef MAC\n public:\n int macMethod();\n#endif // MAC\n</code></pre>\n\n<p>Test_Partial_WIN32.h:</p>\n\n<pre><code>// This file should be included in Test.h only.\n\n#ifdef _WIN32\n public:\n int win32Method();\n#endif // _WIN32\n</code></pre>\n\n<p>Test.cpp:</p>\n\n<pre><code>// Implement common member function of class Test in this file.\n\n#include \"stdafx.h\"\n#include \"Test.h\"\n\nTest::Test(void)\n{\n}\n\nTest::~Test(void)\n{\n}\n</code></pre>\n\n<p>Test_Partial_OSX.cpp:</p>\n\n<pre><code>// Implement OSX platform specific function of class Test in this file.\n\n#include \"stdafx.h\"\n#include \"Test.h\"\n\n#ifdef MAC\nint Test::macMethod()\n{\n return 0;\n}\n#endif // MAC\n</code></pre>\n\n<p>Test_Partial_WIN32.cpp:</p>\n\n<pre><code>// Implement WIN32 platform specific function of class Test in this file.\n\n#include \"stdafx.h\"\n#include \"Test.h\"\n\n#ifdef _WIN32\nint Test::win32Method()\n{\n return 0;\n}\n#endif // _WIN32\n</code></pre>\n"
},
{
"answer_id": 27894388,
"author": "orfdorf",
"author_id": 3734880,
"author_profile": "https://Stackoverflow.com/users/3734880",
"pm_score": 1,
"selected": false,
"text": "<p>I've been doing something similar in my rendering engine. I have a templated IResource interface class from which a variety of resources inherit (stripped down for brevity):</p>\n\n<pre><code>template <typename TResource, typename TParams, typename TKey>\nclass IResource\n{\npublic:\n virtual TKey GetKey() const = 0;\nprotected:\n static shared_ptr<TResource> Create(const TParams& params)\n {\n return ResourceManager::GetInstance().Load(params);\n }\n virtual Status Initialize(const TParams& params, const TKey key, shared_ptr<Viewer> pViewer) = 0;\n};\n</code></pre>\n\n<p>The <code>Create</code> static function calls back to a templated ResourceManager class that is responsible for loading, unloading, and storing instances of the type of resource it manages with unique keys, ensuring duplicate calls are simply retrieved from the store, rather than reloaded as separate resources.</p>\n\n<pre><code>template <typename TResource, typename TParams, typename TKey>\nclass TResourceManager\n{\n sptr<TResource> Load(const TParams& params) { ... }\n};\n</code></pre>\n\n<p>Concrete resource classes inherit from IResource utilizing the CRTP. ResourceManagers specialized to each resource type are declared as friends to those classes, so that the ResourceManager's <code>Load</code> function can call the concrete resource's <code>Initialize</code> function. One such resource is a texture class, which further uses a pImpl idiom to hide its privates:</p>\n\n<pre><code>class Texture2D : public IResource<Texture2D , Params::Texture2D , Key::Texture2D >\n{\n typedef TResourceManager<Texture2D , Params::Texture2D , Key::Texture2D > ResourceManager;\n friend class ResourceManager;\n\npublic:\n virtual Key::Texture2D GetKey() const override final;\n void GetWidth() const;\nprivate:\n virtual Status Initialize(const Params::Texture2D & params, const Key::Texture2D key, shared_ptr<Texture2D > pTexture) override final;\n\n struct Impl;\n unique_ptr<Impl> m;\n};\n</code></pre>\n\n<p>Much of the implementation of our texture class is platform-independent (such as the <code>GetWidth</code> function if it just returns an int stored in the Impl). However, depending on what graphics API we're targeting (e.g. Direct3D11 vs. OpenGL 4.3), some of the implementation details may differ. One solution could be to inherit from IResource an intermediary Texture2D class that defines the extended public interface for all textures, and then inherit a D3DTexture2D and OGLTexture2D class from that. The first problem with this solution is that it requires users of your API to be constantly mindful of which graphics API they're targeting (they could call <code>Create</code> on both child classes). This could be resolved by restricting the <code>Create</code> to the intermediary Texture2D class, which uses maybe a <code>#ifdef</code> switch to create either a D3D or an OGL child object. But then there is still the second problem with this solution, which is that the platform-independent code would be duplicated across both children, causing extra maintenance efforts. You could attempt to solve this problem by moving the platform-independent code into the intermediary class, but what happens if some of the member data is used by both platform-specific and platform-independent code? The D3D/OGL children won't be able to access those data members in the intermediary's Impl, so you'd have to move them out of the Impl and into the header, along with any dependencies they carry, exposing anyone who includes your header to all that crap they don't need to know about.</p>\n\n<p>API's should be easy to use right and hard to use wrong. Part of being easy to use right is restricting the user's exposure to only the parts of the API they should be using. This solution opens it up to be easily used wrong and adds maintenance overhead. Users should only have to care about the graphics API they're targeting in one spot, not everywhere they use your API, and they shouldn't be exposed to your internal dependencies. This situation screams for partial classes, but they are not available in C++. So instead, you might simply define the Impl structure in separate header files, one for D3D, and one for OGL, and put an <code>#ifdef</code> switch at the top of the Texture2D.cpp file, and define the rest of the public interface universally. This way, the public interface has access to the private data it needs, the only duplicate code is data member declarations (construction can still be done in the Texture2D constructor that creates the Impl), your private dependencies stay private, and users don't have to care about anything except using the limited set of calls in the exposed API surface:</p>\n\n<pre><code>// D3DTexture2DImpl.h\n#include \"Texture2D.h\"\nstruct Texture2D::Impl\n{\n /* insert D3D-specific stuff here */\n};\n\n// OGLTexture2DImpl.h\n#include \"Texture2D.h\"\nstruct Texture2D::Impl\n{\n /* insert OGL-specific stuff here */\n};\n\n// Texture2D.cpp\n#include \"Texture2D.h\"\n\n#ifdef USING_D3D\n#include \"D3DTexture2DImpl.h\"\n#else\n#include \"OGLTexture2DImpl.h\"\n#endif\n\nKey::Texture2D Texture2D::GetKey() const\n{\n return m->key;\n}\n// etc...\n</code></pre>\n"
},
{
"answer_id": 57608411,
"author": "user11962338",
"author_id": 11962338,
"author_profile": "https://Stackoverflow.com/users/11962338",
"pm_score": 2,
"selected": false,
"text": "<p>Suppose that I have:</p>\n\n<p>MyClass_Part1.hpp, MyClass_Part2.hpp and MyClass_Part3.hpp</p>\n\n<p><strong>Theoretically</strong> someone can develop a GUI tool that reads all these hpp files above and creates the following hpp file:</p>\n\n<p>MyClass.hpp</p>\n\n<pre><code>class MyClass\n{\n #include <MyClass_Part1.hpp>\n #include <MyClass_Part2.hpp>\n #include <MyClass_Part3.hpp>\n};\n</code></pre>\n\n<p>The user can <strong>theoretically</strong> tell the GUI tool where is each input hpp file and where to create the output hpp file.</p>\n\n<p>Of course that the developer can <strong>theoretically</strong> program the GUI tool to work with any varying number of hpp files (not necessarily 3 only) whose prefix can be any arbitrary string (not necessarily \"MyClass\" only).</p>\n\n<p>Just don't forget to <code>#include <MyClass.hpp></code> to use the class \"MyClass\" in your projects.</p>\n"
},
{
"answer_id": 65669008,
"author": "db2000",
"author_id": 10389697,
"author_profile": "https://Stackoverflow.com/users/10389697",
"pm_score": 2,
"selected": false,
"text": "<p>As written, it is not possible, and in some cases it is actually annoying.</p>\n<p>There was an official proposal to the ISO, with in mind embedded software, in particular to avoid the RAM ovehead given by both inheritance and pimpl pattern (both approaches require an additional pointer for each object):</p>\n<p><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0309r0.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0309r0.pdf</a></p>\n<p>Unfortunately the proposal was rejected.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
]
| Anyone knows if is possible to have partial class definition on C++ ?
Something like:
file1.h:
```
class Test {
public:
int test1();
};
```
file2.h:
```
class Test {
public:
int test2();
};
```
For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes.
I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs.
Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class:
```
class genericTest {
public:
int genericMethod();
};
```
Then let's say for win32:
```
class win32Test: public genericTest {
public:
int win32Method();
};
```
And maybe:
```
class macTest: public genericTest {
public:
int macMethod();
};
```
Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this:
```
#ifdef _WIN32
genericTest *test = new win32Test();
#elif MAC
genericTest *test = new macTest();
#endif
test->genericMethod();
```
Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code.
That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that. | This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance. |
140,996 | <p>In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:</p>
<pre><code><TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>
</code></pre>
<p>But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:</p>
<pre><code><TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>
</code></pre>
<p>However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).</p>
<p>Any ideas?</p>
| [
{
"answer_id": 141008,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 9,
"selected": true,
"text": "<p>It looks strange, but it works. We do it in about 20 different places in our app. <code>Hyperlink</code> implicitly constructs a <code><Run/></code> if you put text in its \"content\", but in .NET 3.5 <code><Run/></code> won't let you bind to it, so you've got to explicitly use a <code>TextBlock</code>.</p>\n\n<pre><code><TextBlock>\n <Hyperlink Command=\"local:MyCommands.ViewDetails\" CommandParameter=\"{Binding}\">\n <TextBlock Text=\"{Binding Path=Name}\"/>\n </Hyperlink>\n</TextBlock>\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong>: Note that as of .NET 4.0 the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.documents.run.text.aspx?PHPSESSID=o1fb21liejulfgrptbmi9dec92\" rel=\"noreferrer\">Run.Text property</a> can now be bound:</p>\n\n<pre><code><Run Text=\"{Binding Path=Name}\" />\n</code></pre>\n"
},
{
"answer_id": 1801586,
"author": "Jamie Clayton",
"author_id": 219119,
"author_profile": "https://Stackoverflow.com/users/219119",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me in a \"Page\".</p>\n\n<pre><code><TextBlock>\n <Hyperlink NavigateUri=\"{Binding Path}\">\n <TextBlock Text=\"{Binding Path=Path}\" />\n </Hyperlink>\n</TextBlock>\n</code></pre>\n"
},
{
"answer_id": 24580114,
"author": "Ivan Ičin",
"author_id": 202179,
"author_profile": "https://Stackoverflow.com/users/202179",
"pm_score": 2,
"selected": false,
"text": "<p>On Windows Store app (and Windows Phone 8.1 RT app) above example does not work, use HyperlinkButton and bind Content and NavigateUri properties as ususal.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/140996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22789/"
]
| In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:
```
<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>
```
But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:
```
<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>
```
However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).
Any ideas? | It looks strange, but it works. We do it in about 20 different places in our app. `Hyperlink` implicitly constructs a `<Run/>` if you put text in its "content", but in .NET 3.5 `<Run/>` won't let you bind to it, so you've got to explicitly use a `TextBlock`.
```
<TextBlock>
<Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
<TextBlock Text="{Binding Path=Name}"/>
</Hyperlink>
</TextBlock>
```
---
**Update**: Note that as of .NET 4.0 the [Run.Text property](http://msdn.microsoft.com/en-us/library/system.windows.documents.run.text.aspx?PHPSESSID=o1fb21liejulfgrptbmi9dec92) can now be bound:
```
<Run Text="{Binding Path=Name}" />
``` |
141,007 | <p>Is there a way to add a resource to a ResourceDictionary from code without giving it a resource key?</p>
<p>For instance, I have this resource in XAML:</p>
<pre><code><TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type xbap:FieldPropertyInfo}"
ItemsSource="{Binding Path=Value.Values}">
<TextBlock Text="{Binding Path=Name}" />
<HierarchicalDataTemplate>
</TreeView.Resources>
</code></pre>
<p>I need to create this resource dynamically from code and add it to the TreeView ResourceDictionary. However, in XAML having no Key means that it's used, by default, for all FieldPropertyInfo types. Is there a way to add it to the resource in code without having a key or is there a way I can use a key and still have it used on all FieldPropertyInfo types?</p>
<p>Here's what I've done in C# so far:</p>
<pre><code>HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo");
fieldPropertyTemplate.ItemsSource = new Binding("Value.Values");
this.Resources.Add(null, fieldPropertyTemplate);
</code></pre>
<p>Obviously, adding a resource to the ResourceDictionary the key null doesn't work.</p>
| [
{
"answer_id": 141018,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>Use the type that you want the template to apply to as the key:</p>\n\n<pre><code>this.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);\n</code></pre>\n\n<p>As with your template above you provide a type. You have to either have to provide a name or a type.</p>\n"
},
{
"answer_id": 141032,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 4,
"selected": true,
"text": "<p>Use the type that you want the template to apply to as the key:</p>\n\n<pre><code>HierarchicalDataTemplate fieldPropertyTemplate = new \n HierarchicalDataTemplate(\"FieldProperyInfo\");\n\nfieldPropertyTemplate.SetBinding(\n HierarchialDataTemplate.ItemSourceProperty, \n new Binding(\"Value.Values\");\nthis.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);\n</code></pre>\n\n<p>The reason your code wasn't working was your <em>weren't actually setting the binding</em>. You need to call SetBinding, with the property you want the binding bound to.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999/"
]
| Is there a way to add a resource to a ResourceDictionary from code without giving it a resource key?
For instance, I have this resource in XAML:
```
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type xbap:FieldPropertyInfo}"
ItemsSource="{Binding Path=Value.Values}">
<TextBlock Text="{Binding Path=Name}" />
<HierarchicalDataTemplate>
</TreeView.Resources>
```
I need to create this resource dynamically from code and add it to the TreeView ResourceDictionary. However, in XAML having no Key means that it's used, by default, for all FieldPropertyInfo types. Is there a way to add it to the resource in code without having a key or is there a way I can use a key and still have it used on all FieldPropertyInfo types?
Here's what I've done in C# so far:
```
HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo");
fieldPropertyTemplate.ItemsSource = new Binding("Value.Values");
this.Resources.Add(null, fieldPropertyTemplate);
```
Obviously, adding a resource to the ResourceDictionary the key null doesn't work. | Use the type that you want the template to apply to as the key:
```
HierarchicalDataTemplate fieldPropertyTemplate = new
HierarchicalDataTemplate("FieldProperyInfo");
fieldPropertyTemplate.SetBinding(
HierarchialDataTemplate.ItemSourceProperty,
new Binding("Value.Values");
this.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);
```
The reason your code wasn't working was your *weren't actually setting the binding*. You need to call SetBinding, with the property you want the binding bound to. |
141,045 | <p>I want to replace the first occurrence in a given string. </p>
<p>How can I accomplish this in .NET?</p>
| [
{
"answer_id": 141062,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 4,
"selected": false,
"text": "<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx\" rel=\"noreferrer\">Regex.Replace</a>.</p>\n"
},
{
"answer_id": 141076,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 7,
"selected": false,
"text": "<pre><code>string ReplaceFirst(string text, string search, string replace)\n{\n int pos = text.IndexOf(search);\n if (pos < 0)\n {\n return text;\n }\n return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>string str = \"The brown brown fox jumps over the lazy dog\";\n\nstr = ReplaceFirst(str, \"brown\", \"quick\");\n</code></pre>\n\n<p><strong>EDIT</strong>: As @itsmatt <a href=\"https://stackoverflow.com/questions/141045/how-do-i-replace-a-string-in-net#141062\">mentioned</a>, there's also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it's utilizing a full featured parser where my method does one find and three string concatenations.</p>\n\n<p><strong>EDIT2</strong>: If this is a common task, you might want to make the method an extension method:</p>\n\n<pre><code>public static class StringExtension\n{\n public static string ReplaceFirst(this string text, string search, string replace)\n {\n // ...same as above...\n }\n}\n</code></pre>\n\n<p>Using the above example it's now possible to write:</p>\n\n<pre><code>str = str.ReplaceFirst(\"brown\", \"quick\");\n</code></pre>\n"
},
{
"answer_id": 141089,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>In C# syntax:</p>\n\n<pre><code>int loc = original.IndexOf(oldValue);\nif( loc < 0 ) {\n return original;\n}\nreturn original.Remove(loc, oldValue.Length).Insert(loc, newValue);\n</code></pre>\n"
},
{
"answer_id": 141100,
"author": "mortenbpost",
"author_id": 17577,
"author_profile": "https://Stackoverflow.com/users/17577",
"pm_score": 3,
"selected": false,
"text": "<p>C# extension method that will do this:</p>\n<pre><code>public static class StringExt\n{\n public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)\n {\n int i = s.IndexOf(oldValue);\n return s.Remove(i, oldValue.Length).Insert(i, newValue); \n } \n}\n</code></pre>\n"
},
{
"answer_id": 141196,
"author": "Anthony Potts",
"author_id": 22777,
"author_profile": "https://Stackoverflow.com/users/22777",
"pm_score": 2,
"selected": false,
"text": "<p>And because there is also VB.NET to consider, I would like to offer up:</p>\n\n<pre><code>Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String\n Dim pos As Integer = text.IndexOf(search)\n If pos >= 0 Then\n Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n End If\n Return text \nEnd Function\n</code></pre>\n"
},
{
"answer_id": 146747,
"author": "Wes Haggard",
"author_id": 12784,
"author_profile": "https://Stackoverflow.com/users/12784",
"pm_score": 6,
"selected": false,
"text": "<p>As <em>itsmatt</em> said <a href=\"http://msdn.microsoft.com/en-us/library/haekbhys.aspx\" rel=\"noreferrer\">Regex.Replace</a> is a good choice for this however to make his answer more complete I will fill it in with a code sample:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n...\nRegex regex = new Regex(\"foo\");\nstring result = regex.Replace(\"foo1 foo2 foo3 foo4\", \"bar\", 1); \n// result = \"bar1 foo2 foo3 foo4\"\n</code></pre>\n\n<p>The third parameter, set to 1 in this case, is the number of occurrences of the regex pattern that you want to replace in the input string from the beginning of the string.</p>\n\n<p>I was hoping this could be done with a static <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx\" rel=\"noreferrer\">Regex.Replace</a> overload but unfortunately it appears you need a Regex instance to accomplish it.</p>\n"
},
{
"answer_id": 3012392,
"author": "Deenesh",
"author_id": 363194,
"author_profile": "https://Stackoverflow.com/users/363194",
"pm_score": 4,
"selected": false,
"text": "<pre><code>using System.Text.RegularExpressions;\n\nRegEx MyRegEx = new RegEx(\"F\");\nstring result = MyRegex.Replace(InputString, \"R\", 1);\n</code></pre>\n\n<p>will find first <code>F</code> in <code>InputString</code> and replace it with <code>R</code>.</p>\n"
},
{
"answer_id": 4086812,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "<p>Taking the \"first only\" into account, perhaps:</p>\n\n<pre><code>int index = input.IndexOf(\"AA\");\nif (index >= 0) output = input.Substring(0, index) + \"XQ\" +\n input.Substring(index + 2);\n</code></pre>\n\n<p>?</p>\n\n<p>Or more generally:</p>\n\n<pre><code>public static string ReplaceFirstInstance(this string source,\n string find, string replace)\n{\n int index = source.IndexOf(find);\n return index < 0 ? source : source.Substring(0, index) + replace +\n source.Substring(index + find.Length);\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>string output = input.ReplaceFirstInstance(\"AA\", \"XQ\");\n</code></pre>\n"
},
{
"answer_id": 4086818,
"author": "Oded",
"author_id": 1583,
"author_profile": "https://Stackoverflow.com/users/1583",
"pm_score": 3,
"selected": false,
"text": "<p>Assumes that <code>AA</code> only needs to be replaced if it is at the very start of the string:</p>\n\n<pre><code>var newString;\nif(myString.StartsWith(\"AA\"))\n{\n newString =\"XQ\" + myString.Substring(2);\n}\n</code></pre>\n\n<p>If you need to replace the first occurrence of <code>AA</code>, whether the string starts with it or not, go with the solution from Marc.</p>\n"
},
{
"answer_id": 4086855,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>string abc = \"AAAAX1\";\n\n if(abc.IndexOf(\"AA\") == 0)\n {\n abc.Remove(0, 2);\n abc = \"XQ\" + abc;\n }\n</code></pre>\n"
},
{
"answer_id": 4086902,
"author": "AakashM",
"author_id": 71059,
"author_profile": "https://Stackoverflow.com/users/71059",
"pm_score": 2,
"selected": false,
"text": "<p>One of the overloads of <code>Regex.Replace</code> takes an <code>int</code> for \"The maximum number of times the replacement can occur\". Obviously, using <code>Regex.Replace</code> for plain text replacement may seem like overkill, but it's certainly concise:</p>\n\n<pre><code>string output = (new Regex(\"AA\")).Replace(input, \"XQ\", 1);\n</code></pre>\n"
},
{
"answer_id": 37401160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This example abstracts away the substrings (but is slower), but is probably much fast than a RegEx:</p>\n\n<pre><code>var parts = contents.ToString().Split(new string[] { \"needle\" }, 2, StringSplitOptions.None);\nreturn parts[0] + \"replacement\" + parts[1];\n</code></pre>\n"
},
{
"answer_id": 42533240,
"author": "Slai",
"author_id": 1383168,
"author_profile": "https://Stackoverflow.com/users/1383168",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone that doesn't mind a reference to <code>Microsoft.VisualBasic</code>, there is the <a href=\"https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.replace\" rel=\"nofollow noreferrer\"><code>Replace</code> Method</a>:</p>\n\n<pre><code>string result = Microsoft.VisualBasic.Strings.Replace(\"111\", \"1\", \"0\", 2, 1); // \"101\"\n</code></pre>\n"
},
{
"answer_id": 63457947,
"author": "Brad Patton",
"author_id": 27989,
"author_profile": "https://Stackoverflow.com/users/27989",
"pm_score": 0,
"selected": false,
"text": "<p>Updated extension method utilizing <code>Span</code> to minimize new string creation</p>\n<pre><code> public static string ReplaceFirstOccurrence(this string source, string search, string replace) {\n int index = source.IndexOf(search);\n if (index < 0) return source;\n var sourceSpan = source.AsSpan();\n return string.Concat(sourceSpan.Slice(0, index), replace, sourceSpan.Slice(index + search.Length));\n }\n</code></pre>\n"
},
{
"answer_id": 72287953,
"author": "Matěj Štágl",
"author_id": 9250482,
"author_profile": "https://Stackoverflow.com/users/9250482",
"pm_score": 0,
"selected": false,
"text": "<p>With ranges and C# 10 we can do:</p>\n<pre><code>public static string ReplaceFirst(this string text, string search, string replace)\n{\n int pos = text.IndexOf(search, StringComparison.Ordinal);\n return pos < 0 ? text : string.Concat(text[..pos], replace, text.AsSpan(pos + search.Length));\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to replace the first occurrence in a given string.
How can I accomplish this in .NET? | ```
string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
```
Example:
```
string str = "The brown brown fox jumps over the lazy dog";
str = ReplaceFirst(str, "brown", "quick");
```
**EDIT**: As @itsmatt [mentioned](https://stackoverflow.com/questions/141045/how-do-i-replace-a-string-in-net#141062), there's also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it's utilizing a full featured parser where my method does one find and three string concatenations.
**EDIT2**: If this is a common task, you might want to make the method an extension method:
```
public static class StringExtension
{
public static string ReplaceFirst(this string text, string search, string replace)
{
// ...same as above...
}
}
```
Using the above example it's now possible to write:
```
str = str.ReplaceFirst("brown", "quick");
``` |
141,068 | <p>I have an Image column (Allow Null = true) in SQL Server 2005. I am using Crystal Reports designer (ver 10.5) that comes with Visual Studio 2008. Crystal sees the column as blob field and puts an image object for the column.
When I am trying to limit the record selection by using </p>
<pre><code> NOT ISNULL({Employee.Picture})
</code></pre>
<p>as Selection Formula, I get the following error:</p>
<blockquote>
<p>Error in formula .<br>
'NOT (ISNULL({Employee.Picture}))'<br>
This function cannot be used because it must be evaluated later.</p>
</blockquote>
<p>Is there a way to filter out rows with out pictures?</p>
<p>Thanks,<br>
Kishore A</p>
| [
{
"answer_id": 141178,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 0,
"selected": false,
"text": "<p>since no one is jumping in on this I'll try (note: i can't test these possibilities at the moment).</p>\n\n<ul>\n<li><p>if you can get a size out of the\nfield using the formula editor, try\nsize greater than 0 or whatever. </p></li>\n<li><p>if you pull the field on the report,\n does it show a pic?</p></li>\n<li><p>if you look at the database, are the\n empty field actually null or could\n CR be reading them as \"0\"?</p></li>\n</ul>\n"
},
{
"answer_id": 268068,
"author": "David T. Macknet",
"author_id": 6850,
"author_profile": "https://Stackoverflow.com/users/6850",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>ISNULL</code> function is more like the <code>SWITCH</code> function in in VB. What you are looking for is probably something more along the lines of:</p>\n\n<pre><code>WHERE NOT Employee.Picture IS NULL\n</code></pre>\n\n<p>Two separate words for <code>IS NULL</code>.</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18169/"
]
| I have an Image column (Allow Null = true) in SQL Server 2005. I am using Crystal Reports designer (ver 10.5) that comes with Visual Studio 2008. Crystal sees the column as blob field and puts an image object for the column.
When I am trying to limit the record selection by using
```
NOT ISNULL({Employee.Picture})
```
as Selection Formula, I get the following error:
>
> Error in formula .
>
> 'NOT (ISNULL({Employee.Picture}))'
>
> This function cannot be used because it must be evaluated later.
>
>
>
Is there a way to filter out rows with out pictures?
Thanks,
Kishore A | The `ISNULL` function is more like the `SWITCH` function in in VB. What you are looking for is probably something more along the lines of:
```
WHERE NOT Employee.Picture IS NULL
```
Two separate words for `IS NULL`. |
141,088 | <p>I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?</p>
| [
{
"answer_id": 141098,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 13,
"selected": true,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>foreach(KeyValuePair<string, string> entry in myDictionary)\n{\n // do something with entry.Value or entry.Key\n}\n</code></pre>\n"
},
{
"answer_id": 141102,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 6,
"selected": false,
"text": "<p>I would say <code>foreach</code> is the standard way, though it obviously depends on what you're looking for</p>\n<pre><code>foreach(var kvp in my_dictionary) {\n ...\n}\n</code></pre>\n<p>Is that what you're looking for?</p>\n"
},
{
"answer_id": 141105,
"author": "Jacob",
"author_id": 22107,
"author_profile": "https://Stackoverflow.com/users/22107",
"pm_score": 10,
"selected": false,
"text": "<p>If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:</p>\n\n<pre><code>foreach(var item in myDictionary)\n{\n foo(item.Key);\n bar(item.Value);\n}\n</code></pre>\n\n<p>Or, if you only need to iterate over the collection of keys, use</p>\n\n<pre><code>foreach(var item in myDictionary.Keys)\n{\n foo(item);\n}\n</code></pre>\n\n<p>And lastly, if you're only interested in the values:</p>\n\n<pre><code>foreach(var item in myDictionary.Values)\n{\n foo(item);\n}\n</code></pre>\n\n<p>(Take note that the <code>var</code> keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)</p>\n"
},
{
"answer_id": 141106,
"author": "theo",
"author_id": 7870,
"author_profile": "https://Stackoverflow.com/users/7870",
"pm_score": 5,
"selected": false,
"text": "<p>There are plenty of options. My personal favorite is by KeyValuePair</p>\n\n<pre><code>Dictionary<string, object> myDictionary = new Dictionary<string, object>();\n// Populate your dictionary here\n\nforeach (KeyValuePair<string,object> kvp in myDictionary)\n{\n // Do some interesting things\n}\n</code></pre>\n\n<p>You can also use the Keys and Values Collections</p>\n"
},
{
"answer_id": 141132,
"author": "J Healy",
"author_id": 5946,
"author_profile": "https://Stackoverflow.com/users/5946",
"pm_score": 7,
"selected": false,
"text": "<p>Depends on whether you're after the keys or the values...</p>\n\n<p>From the MSDN <a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"noreferrer\"><code>Dictionary(TKey, TValue)</code></a> Class description:</p>\n\n<pre><code>// When you use foreach to enumerate dictionary elements,\n// the elements are retrieved as KeyValuePair objects.\nConsole.WriteLine();\nforeach( KeyValuePair<string, string> kvp in openWith )\n{\n Console.WriteLine(\"Key = {0}, Value = {1}\", \n kvp.Key, kvp.Value);\n}\n\n// To get the values alone, use the Values property.\nDictionary<string, string>.ValueCollection valueColl =\n openWith.Values;\n\n// The elements of the ValueCollection are strongly typed\n// with the type that was specified for dictionary values.\nConsole.WriteLine();\nforeach( string s in valueColl )\n{\n Console.WriteLine(\"Value = {0}\", s);\n}\n\n// To get the keys alone, use the Keys property.\nDictionary<string, string>.KeyCollection keyColl =\n openWith.Keys;\n\n// The elements of the KeyCollection are strongly typed\n// with the type that was specified for dictionary keys.\nConsole.WriteLine();\nforeach( string s in keyColl )\n{\n Console.WriteLine(\"Key = {0}\", s);\n}\n</code></pre>\n"
},
{
"answer_id": 351763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and \"this\" is a Dictionary. </p>\n\n<pre><code>public new IEnumerator<T> GetEnumerator()\n{\n return this.Values.GetEnumerator();\n}\n</code></pre>\n"
},
{
"answer_id": 559263,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I found this method in the documentation for the DictionaryBase class on MSDN:</p>\n\n<pre><code>foreach (DictionaryEntry de in myDictionary)\n{\n //Do some stuff with de.Value or de.Key\n}</code></pre>\n\n<p>This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.</p>\n"
},
{
"answer_id": 5265690,
"author": "Maurício Fedatto",
"author_id": 654288,
"author_profile": "https://Stackoverflow.com/users/654288",
"pm_score": 8,
"selected": false,
"text": "<p>In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides <a href=\"https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx\" rel=\"noreferrer\"><code>ElementAt</code></a> which enables the following:</p>\n\n<pre><code>for (int index = 0; index < dictionary.Count; index++) {\n var item = dictionary.ElementAt(index);\n var itemKey = item.Key;\n var itemValue = item.Value;\n}\n</code></pre>\n"
},
{
"answer_id": 24521742,
"author": "ender",
"author_id": 885175,
"author_profile": "https://Stackoverflow.com/users/885175",
"pm_score": 3,
"selected": false,
"text": "<p>Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:</p>\n\n<pre><code>foreach(var value in dictionary.Values)\n{\n // do something with entry.Value only\n}\n</code></pre>\n\n<p>Reported by this post which states it is the fastest method:\n<a href=\"http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html\" rel=\"noreferrer\">http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html</a></p>\n"
},
{
"answer_id": 25035004,
"author": "Liath",
"author_id": 352176,
"author_profile": "https://Stackoverflow.com/users/352176",
"pm_score": 5,
"selected": false,
"text": "<p>I appreciate this question has already had a lot of responses but I wanted to throw in a little research.</p>\n\n<p>Iterating over a dictionary can be rather slow when compared with iterating over something like an array. In my tests an iteration over an array took 0.015003 seconds whereas an iteration over a dictionary (with the same number of elements) took 0.0365073 seconds that's 2.4 times as long! Although I have seen much bigger differences. For comparison a List was somewhere in between at 0.00215043 seconds.</p>\n\n<p>However, that is like comparing apples and oranges. My point is that iterating over dictionaries is slow.</p>\n\n<p>Dictionaries are optimised for lookups, so with that in mind I've created two methods. One simply does a foreach, the other iterates the keys then looks up.</p>\n\n<pre><code>public static string Normal(Dictionary<string, string> dictionary)\n{\n string value;\n int count = 0;\n foreach (var kvp in dictionary)\n {\n value = kvp.Value;\n count++;\n }\n\n return \"Normal\";\n}\n</code></pre>\n\n<p>This one loads the keys and iterates over them instead (I did also try pulling the keys into a string[] but the difference was negligible.</p>\n\n<pre><code>public static string Keys(Dictionary<string, string> dictionary)\n{\n string value;\n int count = 0;\n foreach (var key in dictionary.Keys)\n {\n value = dictionary[key];\n count++;\n }\n\n return \"Keys\";\n}\n</code></pre>\n\n<p>With this example the normal foreach test took 0.0310062 and the keys version took 0.2205441. Loading all the keys and iterating over all the lookups is clearly a LOT slower!</p>\n\n<p>For a final test I've performed my iteration ten times to see if there are any benefits to using the keys here (by this point I was just curious):</p>\n\n<p>Here's the RunTest method if that helps you visualise what's going on.</p>\n\n<pre><code>private static string RunTest<T>(T dictionary, Func<T, string> function)\n{ \n DateTime start = DateTime.Now;\n string name = null;\n for (int i = 0; i < 10; i++)\n {\n name = function(dictionary);\n }\n DateTime end = DateTime.Now;\n var duration = end.Subtract(start);\n return string.Format(\"{0} took {1} seconds\", name, duration.TotalSeconds);\n}\n</code></pre>\n\n<p>Here the normal foreach run took 0.2820564 seconds (around ten times longer than a single iteration took - as you'd expect). The iteration over the keys took 2.2249449 seconds.</p>\n\n<p><strong>Edited To Add:</strong>\nReading some of the other answers made me question what would happen if I used Dictionary instead of Dictionary. In this example the array took 0.0120024 seconds, the list 0.0185037 seconds and the dictionary 0.0465093 seconds. It's reasonable to expect that the data type makes a difference on how much slower the dictionary is.</p>\n\n<p><strong>What are my Conclusions</strong>?</p>\n\n<ul>\n<li>Avoid iterating over a dictionary if you can, they are substantially slower than iterating over an array with the same data in it.</li>\n<li>If you do choose to iterate over a dictionary don't try to be too clever, although slower you could do a lot worse than using the standard foreach method.</li>\n</ul>\n"
},
{
"answer_id": 26152183,
"author": "yazanpro",
"author_id": 465495,
"author_profile": "https://Stackoverflow.com/users/465495",
"pm_score": 2,
"selected": false,
"text": "<p>I will take the advantage of .NET 4.0+ and provide an updated answer to the originally accepted one:</p>\n\n<pre><code>foreach(var entry in MyDic)\n{\n // do something with entry.Value or entry.Key\n}\n</code></pre>\n"
},
{
"answer_id": 30510215,
"author": "Egor Okhterov",
"author_id": 1509251,
"author_profile": "https://Stackoverflow.com/users/1509251",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var dictionary = new Dictionary<string, int>\n{\n { \"Key\", 12 }\n};\n\nvar aggregateObjectCollection = dictionary.Select(\n entry => new AggregateObject(entry.Key, entry.Value));\n</code></pre>\n"
},
{
"answer_id": 30782291,
"author": "Onur",
"author_id": 2417052,
"author_profile": "https://Stackoverflow.com/users/2417052",
"pm_score": 6,
"selected": false,
"text": "<p>You can also try this on big dictionaries for multithreaded processing.</p>\n\n<pre><code>dictionary\n.AsParallel()\n.ForAll(pair => \n{ \n // Process pair.Key and pair.Value here\n});\n</code></pre>\n"
},
{
"answer_id": 31918117,
"author": "Stéphane Gourichon",
"author_id": 1429390,
"author_profile": "https://Stackoverflow.com/users/1429390",
"pm_score": 7,
"selected": false,
"text": "<p>Generally, asking for \"the best way\" without a specific context is like asking \n<em>what is the best color</em>?</p>\n\n<p>One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.</p>\n\n<p>On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.</p>\n\n<h1>Most straightforward way</h1>\n\n<pre><code>foreach (var kvp in items)\n{\n // key is kvp.Key\n doStuff(kvp.Value)\n}\n</code></pre>\n\n<p>If you need only the value (allows to call it <code>item</code>, more readable than <code>kvp.Value</code>).</p>\n\n<pre><code>foreach (var item in items.Values)\n{\n doStuff(item)\n}\n</code></pre>\n\n<h1>If you need a specific sort order</h1>\n\n<p>Generally, beginners are surprised about order of enumeration of a Dictionary.</p>\n\n<p>LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:</p>\n\n<pre><code>foreach (var kvp in items.OrderBy(kvp => kvp.Key))\n{\n // key is kvp.Key\n doStuff(kvp.Value)\n}\n</code></pre>\n\n<p>Again you might only need the value. LINQ also provides a concise solution to: </p>\n\n<ul>\n<li>iterate directly on the value (allows to call it <code>item</code>, more readable than <code>kvp.Value</code>)</li>\n<li>but sorted by the keys</li>\n</ul>\n\n<p>Here it is:</p>\n\n<pre><code>foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))\n{\n doStuff(item)\n}\n</code></pre>\n\n<p>There are many more real-world use case you can do from these examples.\nIf you don't need a specific order, just stick to the \"most straightforward way\" (see above)!</p>\n"
},
{
"answer_id": 38634404,
"author": "Nick",
"author_id": 1815752,
"author_profile": "https://Stackoverflow.com/users/1815752",
"pm_score": 2,
"selected": false,
"text": "<p>The standard way to iterate over a Dictionary, according to official documentation on MSDN is:</p>\n\n<pre><code>foreach (DictionaryEntry entry in myDictionary)\n{\n //Read entry.Key and entry.Value here\n}\n</code></pre>\n"
},
{
"answer_id": 39535791,
"author": "Alex",
"author_id": 1223276,
"author_profile": "https://Stackoverflow.com/users/1223276",
"pm_score": -1,
"selected": false,
"text": "<p>Just wanted to add my 2 cent, as the most answers relate to foreach-loop.\nPlease, take a look at the following code:</p>\n\n<pre><code>Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();\n\n//Add some entries to the dictionary\n\nmyProductPrices.ToList().ForEach(kvP => \n{\n kvP.Value *= 1.15;\n Console.Writeline(String.Format(\"Product '{0}' has a new price: {1} $\", kvp.Key, kvP.Value));\n});\n</code></pre>\n\n<p>Altought this adds a additional call of '.ToList()', there might be a slight performance-improvement (as pointed out here <a href=\"https://stackoverflow.com/questions/225937/foreach-vs-somelist-foreach\">foreach vs someList.Foreach(){}</a>), \nespacially when working with large Dictionaries and running in parallel is no option / won't have an effect at all.</p>\n\n<p>Also, please note that you wont be able to assign values to the 'Value' property inside a foreach-loop. On the other hand, you will be able to manipulate the 'Key' as well, possibly getting you into trouble at runtime.</p>\n\n<p>When you just want to \"read\" Keys and Values, you might also use IEnumerable.Select().</p>\n\n<pre><code>var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );\n</code></pre>\n"
},
{
"answer_id": 39813726,
"author": "Ron",
"author_id": 672096,
"author_profile": "https://Stackoverflow.com/users/672096",
"pm_score": 4,
"selected": false,
"text": "<p>Simplest form to iterate a dictionary:</p>\n\n<pre><code>foreach(var item in myDictionary)\n{ \n Console.WriteLine(item.Key);\n Console.WriteLine(item.Value);\n}\n</code></pre>\n"
},
{
"answer_id": 46793626,
"author": "Pavel",
"author_id": 6131611,
"author_profile": "https://Stackoverflow.com/users/6131611",
"pm_score": 4,
"selected": false,
"text": "<p>With <code>.NET Framework 4.7</code> one can use <em>decomposition</em></p>\n\n<pre><code>var fruits = new Dictionary<string, int>();\n...\nforeach (var (fruit, number) in fruits)\n{\n Console.WriteLine(fruit + \": \" + number);\n}\n</code></pre>\n\n<p>To make this code work on lower C# versions, add <code>System.ValueTuple NuGet package</code> and write somewhere</p>\n\n<pre><code>public static class MyExtensions\n{\n public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple,\n out T1 key, out T2 value)\n {\n key = tuple.Key;\n value = tuple.Value;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49856111,
"author": "Sheo Dayal Singh",
"author_id": 5736534,
"author_profile": "https://Stackoverflow.com/users/5736534",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Dictionary< TKey, TValue ></strong> It is a generic collection class in c# and it stores the data in the key value format.Key must be unique and it can not be null whereas value can be duplicate and null.As each item in the dictionary is treated as KeyValuePair< TKey, TValue > structure representing a key and its value. and hence we should take the element type KeyValuePair< TKey, TValue> during the iteration of element.<strong>Below is the example.</strong></p>\n\n<pre><code>Dictionary<int, string> dict = new Dictionary<int, string>();\ndict.Add(1,\"One\");\ndict.Add(2,\"Two\");\ndict.Add(3,\"Three\");\n\nforeach (KeyValuePair<int, string> item in dict)\n{\n Console.WriteLine(\"Key: {0}, Value: {1}\", item.Key, item.Value);\n}\n</code></pre>\n"
},
{
"answer_id": 50552122,
"author": "sɐunıɔןɐqɐp",
"author_id": 823321,
"author_profile": "https://Stackoverflow.com/users/823321",
"pm_score": 4,
"selected": false,
"text": "<p>Using <strong>C# 7</strong>, add this <strong>extension method</strong> to any project of your solution:</p>\n\n<pre><code>public static class IDictionaryExtensions\n{\n public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(\n this IDictionary<TKey, TValue> dict)\n {\n foreach (KeyValuePair<TKey, TValue> kvp in dict)\n yield return (kvp.Key, kvp.Value);\n }\n}\n</code></pre>\n\n<p><br>\nAnd use this simple syntax</p>\n\n<pre><code>foreach (var(id, value) in dict.Tuples())\n{\n // your code using 'id' and 'value'\n}\n</code></pre>\n\n<p><br>\nOr this one, if you prefer</p>\n\n<pre><code>foreach ((string id, object value) in dict.Tuples())\n{\n // your code using 'id' and 'value'\n}\n</code></pre>\n\n<p><br>\nIn place of the traditional</p>\n\n<pre><code>foreach (KeyValuePair<string, object> kvp in dict)\n{\n string id = kvp.Key;\n object value = kvp.Value;\n\n // your code using 'id' and 'value'\n}\n</code></pre>\n\n<p><br>\nThe extension method transforms the <code>KeyValuePair</code> of your <code>IDictionary<TKey, TValue></code> into a strongly typed <code>tuple</code>, allowing you to use this new comfortable syntax.</p>\n\n<p>It converts -just- the required dictionary entries to <code>tuples</code>, so it does NOT converts the whole dictionary to <code>tuples</code>, so there are no performance concerns related to that.</p>\n\n<p>There is a only minor cost calling the extension method for creating a <code>tuple</code> in comparison with using the <code>KeyValuePair</code> directly, which should NOT be an issue if you are assigning the <code>KeyValuePair</code>'s properties <code>Key</code> and <code>Value</code> to new loop variables anyway.</p>\n\n<p>In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.</p>\n\n<p>Check this out: <a href=\"https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/\" rel=\"noreferrer\">MSDN Blog - New features in C# 7</a></p>\n"
},
{
"answer_id": 50755179,
"author": "Steven Delrue",
"author_id": 1107617,
"author_profile": "https://Stackoverflow.com/users/1107617",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote an extension to loop over a dictionary. </p>\n\n<pre><code>public static class DictionaryExtension\n{\n public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {\n foreach(KeyValuePair<T1, T2> keyValue in dictionary) {\n action(keyValue.Key, keyValue.Value);\n }\n }\n}\n</code></pre>\n\n<p>Then you can call</p>\n\n<pre><code>myDictionary.ForEach((x,y) => Console.WriteLine(x + \" - \" + y));\n</code></pre>\n"
},
{
"answer_id": 51291784,
"author": "Domn Werner",
"author_id": 4025444,
"author_profile": "https://Stackoverflow.com/users/4025444",
"pm_score": 4,
"selected": false,
"text": "<p>As of C# 7, you can deconstruct objects into variables. I believe this to be the best way to iterate over a dictionary.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>Create an extension method on <code>KeyValuePair<TKey, TVal></code> that deconstructs it:</p>\n\n<pre><code>public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value)\n{\n key = pair.Key;\n value = pair.Value;\n}\n</code></pre>\n\n<p>Iterate over any <code>Dictionary<TKey, TVal></code> in the following manner</p>\n\n<pre><code>// Dictionary can be of any types, just using 'int' and 'string' as examples.\nDictionary<int, string> dict = new Dictionary<int, string>();\n\n// Deconstructor gets called here.\nforeach (var (key, value) in dict)\n{\n Console.WriteLine($\"{key} : {value}\");\n}\n</code></pre>\n"
},
{
"answer_id": 51921755,
"author": "BigChief",
"author_id": 539251,
"author_profile": "https://Stackoverflow.com/users/539251",
"pm_score": -1,
"selected": false,
"text": "<p>in addition to the highest ranking posts where there is a discussion between using</p>\n\n<pre><code>foreach(KeyValuePair<string, string> entry in myDictionary)\n{\n // do something with entry.Value or entry.Key\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>foreach(var entry in myDictionary)\n{\n // do something with entry.Value or entry.Key\n}\n</code></pre>\n\n<p>most complete is the following because you can see the dictionary type from the initialization, kvp is KeyValuePair</p>\n\n<pre><code>var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x\n\nforeach(var kvp in myDictionary)//iterate over dictionary\n{\n // do something with kvp.Value or kvp.Key\n}\n</code></pre>\n"
},
{
"answer_id": 54081425,
"author": "Jaider",
"author_id": 480700,
"author_profile": "https://Stackoverflow.com/users/480700",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"https://msdn.microsoft.com/en-us/magazine/mt790184.aspx\" rel=\"noreferrer\"><em>C# 7.0</em> introduced <strong>Deconstructors</strong></a> and if you are using <em>.NET Core 2.0+</em> Application, the struct <code>KeyValuePair<></code> already include a <code>Deconstruct()</code> for you. So you can do:</p>\n\n<pre><code>var dic = new Dictionary<int, string>() { { 1, \"One\" }, { 2, \"Two\" }, { 3, \"Three\" } };\nforeach (var (key, value) in dic) {\n Console.WriteLine($\"Item [{key}] = {value}\");\n}\n//Or\nforeach (var (_, value) in dic) {\n Console.WriteLine($\"Item [NO_ID] = {value}\");\n}\n//Or\nforeach ((int key, string value) in dic) {\n Console.WriteLine($\"Item [{key}] = {value}\");\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/OdW3m.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OdW3m.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 56601004,
"author": "boca",
"author_id": 251665,
"author_profile": "https://Stackoverflow.com/users/251665",
"pm_score": 3,
"selected": false,
"text": "<p>I know this is a very old question, but I created some extension methods that might be useful:</p>\n\n<pre><code> public static void ForEach<T, U>(this Dictionary<T, U> d, Action<KeyValuePair<T, U>> a)\n {\n foreach (KeyValuePair<T, U> p in d) { a(p); }\n }\n\n public static void ForEach<T, U>(this Dictionary<T, U>.KeyCollection k, Action<T> a)\n {\n foreach (T t in k) { a(t); }\n }\n\n public static void ForEach<T, U>(this Dictionary<T, U>.ValueCollection v, Action<U> a)\n {\n foreach (U u in v) { a(u); }\n }\n</code></pre>\n\n<p>This way I can write code like this:</p>\n\n<pre><code>myDictionary.ForEach(pair => Console.Write($\"key: {pair.Key}, value: {pair.Value}\"));\nmyDictionary.Keys.ForEach(key => Console.Write(key););\nmyDictionary.Values.ForEach(value => Console.Write(value););\n</code></pre>\n"
},
{
"answer_id": 59053661,
"author": "Pixel_95",
"author_id": 4636569,
"author_profile": "https://Stackoverflow.com/users/4636569",
"pm_score": 4,
"selected": false,
"text": "<p><code>foreach</code> is fastest and if you only iterate over <code>___.Values</code>, it is also faster</p>\n\n<p><a href=\"https://i.stack.imgur.com/Nr35i.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Nr35i.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 61797855,
"author": "Seçkin Durgay",
"author_id": 975242,
"author_profile": "https://Stackoverflow.com/users/975242",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use a <code>for</code> loop, you can do as below:</p>\n<pre><code>var keyList=new List<string>(dictionary.Keys);\nfor (int i = 0; i < keyList.Count; i++)\n{\n var key= keyList[i];\n var value = dictionary[key];\n}\n</code></pre>\n"
},
{
"answer_id": 62206867,
"author": "rucamzu",
"author_id": 3059191,
"author_profile": "https://Stackoverflow.com/users/3059191",
"pm_score": 5,
"selected": false,
"text": "<p>As already pointed out on this <a href=\"https://stackoverflow.com/a/55392400/3059191\">answer</a>, <code>KeyValuePair<TKey, TValue></code> implements a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2.deconstruct?view=netcore-2.0\" rel=\"noreferrer\"><code>Deconstruct</code></a> method starting on .NET Core 2.0, .NET Standard 2.1 and .NET Framework 5.0 (preview).</p>\n\n<p>With this, it's possible to iterate through a dictionary in a <code>KeyValuePair</code> agnostic way:</p>\n\n<pre><code>var dictionary = new Dictionary<int, string>();\n\n// ...\n\nforeach (var (key, value) in dictionary)\n{\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 65848494,
"author": "Philm",
"author_id": 1469896,
"author_profile": "https://Stackoverflow.com/users/1469896",
"pm_score": 0,
"selected": false,
"text": "<p>The best answer is of course: <strong>Think, if you could use a more appropriate data structure than a dictionary if you plan to iterate over it</strong>- as Vikas Gupta mentioned already in the (beginning of the) discussion under the question. But that discussion as this whole thread still lacks surprisingly good alternatives. One is:</p>\n<pre><code>SortedList<string, string> x = new SortedList<string, string>();\n\nx.Add("key1", "value1");\nx.Add("key2", "value2");\nx["key3"] = "value3";\nforeach( KeyValuePair<string, string> kvPair in x )\n Console.WriteLine($"{kvPair.Key}, {kvPair.Value}");\n</code></pre>\n<p>Why it could be argued a code smell of iterating over a dictionary (e.g. by foreach(KeyValuePair<,>) ?</p>\n<p>A basic principle of Clean Coding:\n"<strong>Express intent!</strong>"\nRobert C. Martin writes in "Clean Code": "Choosing names that reveal intent". Obviously naming alone is too weak. "<strong>Express (reveal) intent with every coding decision"</strong> expresses it better.</p>\n<p>A related principle is "<a href=\"http://principles-wiki.net/principles:principle_of_least_surprise\" rel=\"nofollow noreferrer\">Principle of least surprise</a>" (=<a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">Principle of Least Astonishment</a>).</p>\n<p>Why this is related to iterating over a dictionary? <strong>Choosing a dictionary expresses the intent of choosing a data structure which was made for primarily finding data by key</strong>. Nowadays there are so much alternatives in .NET, if you want to iterate through key/value pairs that you could choose something else.</p>\n<p>Moreover: If you iterate over something, you have to reveal something about how the items are (to be) ordered and expected to be ordered!\nAlthough the known implementations of Dictionary sort the key collection in the order of the items added-\nAFAIK, Dictionary has no assured specification about ordering (has it?).</p>\n<p>But what are the alternatives?</p>\n<p>TLDR:<br />\n<strong>SortedList</strong>: If your collection is not getting too large, a simple solution would be to use SortedList<,> which gives you also full indexing of key/value pairs.</p>\n<p>Microsoft has a long article about mentioning and explaining fitting collections:<br />\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.keyedcollection-2?view=net-5.0%20AA\" rel=\"nofollow noreferrer\">Keyed collection</a></p>\n<p>To mention the most important: <strong>KeyedCollection</strong><,> and SortedDictionary<,> .\n<strong>SortedDictionary</strong><,> is a bit faster than SortedList for only inserting if it gets large, but lacks indexing and is needed only if O(log n) for inserting is preferenced over other operations. If you really need O(1) for inserting and accept slower iterating in exchange, you have to stay with simple Dictionary<,>.\nObviously there is no data structure which is the fastest for every possible operation..</p>\n<p>Additionally there is <strong>ImmutableSortedDictionary</strong><,>.</p>\n<p>And if one data structure is not exactly what you need, then derivate from Dictionary<,> or even from the new <strong>ConcurrentDictionary</strong><,> and add explicit iteration/sorting functions!</p>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9311/"
]
| I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way? | ```cs
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
``` |
141,108 | <p>Is it possible to find the <code>foreach</code> index?</p>
<p>in a <code>for</code> loop as follows:</p>
<pre><code>for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
</code></pre>
<p><code>$i</code> will give you the index.</p>
<p>Do I have to use the <code>for</code> loop or is there some way to get the index in the <code>foreach</code> loop?</p>
| [
{
"answer_id": 141114,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 11,
"selected": true,
"text": "<pre><code>foreach($array as $key=>$value) {\n // do stuff\n}\n</code></pre>\n\n<p><code>$key</code> is the index of each <code>$array</code> element</p>\n"
},
{
"answer_id": 141117,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 4,
"selected": false,
"text": "<p>You can create <code>$i</code> outside the loop and do <code>$i++</code> at the bottom of the loop.</p>\n"
},
{
"answer_id": 141120,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 8,
"selected": false,
"text": "<p>You can put a hack in your <code>foreach</code>, such as a field incremented on each run-through, which is exactly what the <code>for</code> loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).</p>\n\n<p>A <code>foreach</code> will give you your index in the form of your <code>$key</code> value, so such a hack shouldn't be necessary.</p>\n\n<p>e.g., in a <strong><code>foreach</code></strong></p>\n\n<pre><code>$index = 0;\nforeach($data as $key=>$val) {\n // Use $key as an index, or...\n\n // ... manage the index this way..\n echo \"Index is $index\\n\";\n $index++;\n}\n</code></pre>\n"
},
{
"answer_id": 141220,
"author": "The Brawny Man",
"author_id": 11936,
"author_profile": "https://Stackoverflow.com/users/11936",
"pm_score": 3,
"selected": false,
"text": "<p>Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as </p>\n\n<pre><code>$var = array(2,5);\n\nfor ($i = 0; $i < count($var); $i++) {\n echo $var[$i].\"\\n\";\n}\n</code></pre>\n\n<p>your output will be </p>\n\n<pre><code>2\n5\n</code></pre>\n\n<p>in which case each element in the array has a knowable index, but if you then do something like the following</p>\n\n<pre><code>$var = array_push($var,10);\n\nfor ($i = 0; $i < count($var); $i++) {\n echo $var[$i].\"\\n\";\n}\n</code></pre>\n\n<p>you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.</p>\n"
},
{
"answer_id": 142131,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 5,
"selected": false,
"text": "<p>Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.</p>\n\n<pre><code>foreach(array_keys($array) as $key) {\n// do stuff\n}\n</code></pre>\n"
},
{
"answer_id": 244801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>PHP arrays have internal pointers, so try this:</p>\n\n<pre><code>foreach($array as $key => $value){\n $index = current($array);\n}\n</code></pre>\n\n<p>Works okay for me (only very preliminarily tested though).</p>\n"
},
{
"answer_id": 4822812,
"author": "Trev",
"author_id": 593000,
"author_profile": "https://Stackoverflow.com/users/593000",
"pm_score": 3,
"selected": false,
"text": "<p>These two loops are equivalent (bar the safety railings of course):</p>\n\n<pre><code>for ($i=0; $i<count($things); $i++) { ... }\n\nforeach ($things as $i=>$thing) { ... }\n</code></pre>\n\n<p>eg</p>\n\n<pre><code>for ($i=0; $i<count($things); $i++) {\n echo \"Thing \".$i.\" is \".$things[$i];\n}\n\nforeach ($things as $i=>$thing) {\n echo \"Thing \".$i.\" is \".$thing;\n}\n</code></pre>\n"
},
{
"answer_id": 5193023,
"author": "Bailey Parker",
"author_id": 568785,
"author_profile": "https://Stackoverflow.com/users/568785",
"pm_score": 5,
"selected": false,
"text": "<p>It should be noted that you can call <a href=\"http://www.php.net/manual/en/function.key.php\" rel=\"noreferrer\"><code>key()</code></a> on any array to find the current key its on. As you can guess <code>current()</code> will return the current value and <code>next()</code> will move the array's pointer to the next element. </p>\n"
},
{
"answer_id": 24601593,
"author": "Randy Greencorn",
"author_id": 1925485,
"author_profile": "https://Stackoverflow.com/users/1925485",
"pm_score": 2,
"selected": false,
"text": "<p>I normally do this when working with associative arrays:</p>\n\n<pre><code>foreach ($assoc_array as $key => $value) {\n //do something\n}\n</code></pre>\n\n<p>This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:</p>\n\n<pre><code>foreach ($array as $indx => $value) {\n //do something\n}\n</code></pre>\n"
},
{
"answer_id": 37189216,
"author": "Rai Rz",
"author_id": 6313904,
"author_profile": "https://Stackoverflow.com/users/6313904",
"pm_score": 3,
"selected": false,
"text": "<p>I think best option is like same:</p>\n\n<pre><code>foreach ($lists as $key=>$value) {\n echo $key+1;\n}\n</code></pre>\n\n<p>it is easy and normally </p>\n"
},
{
"answer_id": 37856224,
"author": "Ananda G",
"author_id": 2256217,
"author_profile": "https://Stackoverflow.com/users/2256217",
"pm_score": -1,
"selected": false,
"text": "<pre><code>foreach(array_keys($array) as $key) {\n// do stuff\n}\n</code></pre>\n"
},
{
"answer_id": 55570634,
"author": "Taranis",
"author_id": 10523576,
"author_profile": "https://Stackoverflow.com/users/10523576",
"pm_score": -1,
"selected": false,
"text": "<p>I would like to add this, I used this in laravel to just index my table:</p>\n\n<ul>\n<li>With $loop->index</li>\n<li>I also preincrement it with ++$loop to start at 1</li>\n</ul>\n\n<p>My Code:</p>\n\n<pre><code>@foreach($resultsPerCountry->first()->studies as $result)\n <tr>\n <td>{{ ++$loop->index}}</td> \n </tr>\n@endforeach\n</code></pre>\n"
},
{
"answer_id": 62044349,
"author": "Carlos Cavalchuki",
"author_id": 7011539,
"author_profile": "https://Stackoverflow.com/users/7011539",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this way, when I had to use the foreach index and value in the same context:</p>\n\n<pre><code>$array = array('a', 'b', 'c');\nforeach ($array as $letter=>$index) {\n\n echo $letter; //Here $letter content is the actual index\n echo $array[$letter]; // echoes the array value\n\n}//foreach\n\n</code></pre>\n"
},
{
"answer_id": 67558030,
"author": "jamiryo",
"author_id": 11904361,
"author_profile": "https://Stackoverflow.com/users/11904361",
"pm_score": 3,
"selected": false,
"text": "<p>I use <code>++$key</code> instead of <code>$key++</code> to start from 1. Normally it starts from 0.</p>\n<pre class=\"lang-php prettyprint-override\"><code>@foreach ($quiz->questions as $key => $question)\n <h2> Question: {{++$key}}</h2>\n <p>{{$question->question}}</p>\n@endforeach\n</code></pre>\n<p>Output:</p>\n<pre><code>Question: 1\n......\nQuestion:2\n.....\n.\n.\n.\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18334/"
]
| Is it possible to find the `foreach` index?
in a `for` loop as follows:
```
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
```
`$i` will give you the index.
Do I have to use the `for` loop or is there some way to get the index in the `foreach` loop? | ```
foreach($array as $key=>$value) {
// do stuff
}
```
`$key` is the index of each `$array` element |
141,136 | <p>I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows: </p>
<p>txtStart.Text = 09/19/2008 07:00:00</p>
<p>txtEnd.Text = 09/19/2008 05:00:00</p>
<p>I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page. </p>
| [
{
"answer_id": 141159,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "<p>Once your textbox date formats are known in advance, you can use <a href=\"http://www.mattkruse.com/javascript/date/\" rel=\"noreferrer\">Matt Kruse's Date functions</a> in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.</p>\n\n<p>Equally the <a href=\"http://jonathanleighton.com/projects/date-input#date-formatting\" rel=\"noreferrer\">JQuery Date Input</a> code for <code>stringToDate</code> could be adapted for your purposes - the below takes a string in the format \"YYYY-MM-DD\" and converts it to a date object. The timestamp (<code>getTime()</code>) of these objects could be used for your calculations.</p>\n\n<pre><code>stringToDate: function(string) {\n var matches;\n if (matches = string.match(/^(\\d{4,4})-(\\d{2,2})-(\\d{2,2})$/)) {\n return new Date(matches[1], matches[2] - 1, matches[3]);\n } else {\n return null;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 141387,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>I took what <a href=\"https://stackoverflow.com/questions/141136/calculate-timespan-in-javascript#141159\">@PConroy</a> did and added to it by doing the calculations for you. I also added the regex to make sure the time is part of the string to create the date object.</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\">\n function stringToDate(string) {\n var matches;\n if (matches = string.match(/^(\\d{4,4})-(\\d{2,2})-(\\d{2,2}) (\\d{2,2}):(\\d{2,2}):(\\d{2,2})$/)) {\n return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);\n } else {\n return null;\n };\n }\n\n //Convert duration from milliseconds to 0000:00:00.00 format\n function MillisecondsToDuration(n) {\n var hms = \"\";\n var dtm = new Date();\n dtm.setTime(n);\n var h = \"000\" + Math.floor(n / 3600000);\n var m = \"0\" + dtm.getMinutes();\n var s = \"0\" + dtm.getSeconds();\n var cs = \"0\" + Math.round(dtm.getMilliseconds() / 10);\n hms = h.substr(h.length-4) + \":\" + m.substr(m.length-2) + \":\";\n hms += s.substr(s.length-2) + \".\" + cs.substr(cs.length-2);\n return hms;\n }\n\n var beginDate = stringToDate('2008-09-19 07:14:00');\n var endDate = stringToDate('2008-09-19 17:35:00');\n\n var n = endDate.getTime() - beginDate.getTime();\n\n alert(MillisecondsToDuration(n));\n </script>\n </head>\n <body>\n </body>\n</html>\n</code></pre>\n\n<p>This is pretty rough, since I coded it up pretty fast, but it works. I tested it out. The alert box will display 0010:21:00.00 (HHHH:MM:SS.SS). Basically all you need to do is get the values from your text boxes.</p>\n"
},
{
"answer_id": 1701948,
"author": "Jerod Venema",
"author_id": 25330,
"author_profile": "https://Stackoverflow.com/users/25330",
"pm_score": 2,
"selected": false,
"text": "<p>The answers above all assume string manipulation. Here's a solution that works with pure date objects:</p>\n\n<pre><code>var start = new Date().getTime();\nwindow.setTimeout(function(){\n var diff = new Date(new Date().getTime() - start);\n // this will log 0 hours, 0 minutes, 1 second\n console.log(diff.getHours(), diff.getMinutes(),diff.getSeconds());\n},1000);\n</code></pre>\n"
},
{
"answer_id": 2971130,
"author": "jassey",
"author_id": 306548,
"author_profile": "https://Stackoverflow.com/users/306548",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function stringToDate(string) {\n var matches;\n if (matches = string.match(/^(\\d{4,4})-(\\d{2,2})-(\\d{2,2}) (\\d{2,2}):(\\d{2,2}):(\\d{2,2})$/)) {\n return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);\n } else {\n return null;\n };\n}\n\n function getTimeSpan(ticks) {\n var d = new Date(ticks);\n return {\n hour: d.getUTCHours(), \n minute: d.getMinutes(), \n second: d.getSeconds()\n }\n }\n\n var beginDate = stringToDate('2008-09-19 07:14:00');\n var endDate = stringToDate('2008-09-19 17:35:00');\n\n var sp = getTimeSpan(endDate - beginDate);\n alert(\"timeuse:\" + sp.hour + \" hour \" + sp.minute + \" minute \" + sp.second + \" second \");\n</code></pre>\n\n<p>you can use getUTCHours() instead Math.floor(n / 3600000);</p>\n"
},
{
"answer_id": 3346386,
"author": "KKK",
"author_id": 403703,
"author_profile": "https://Stackoverflow.com/users/403703",
"pm_score": 0,
"selected": false,
"text": "<p>Use Math.floor(n / 3600000) instead of getUTCHours() or else you would lose the number of hours greater than 24.</p>\n\n<p>For example, if you have 126980000 milliseconds, this should translate to 0035:16:20.00</p>\n\n<p>If you use getUTCHours() you get an incorrect string 0011:16:20.00</p>\n\n<p>Better instead, use this (modifications denoted by KK-MOD):</p>\n\n<blockquote>\n <p>function MillisecondsToDuration(n) {<br/>\n var hms = \"\";<br/>\n var dtm = new Date();<br/>\n dtm.setTime(n);<br/>\n var d = Math.floor(n / 3600000 / 24); // KK-MOD<br/>\n var h = \"0\" + (Math.floor(n / 3600000) - (d * 24)); // KK-MOD<br/>\n var m = \"0\" + dtm.getMinutes();<br/>\n var s = \"0\" + dtm.getSeconds();<br/>\n var cs = \"0\" + Math.round(dtm.getMilliseconds() / 10);<br/>\n hms = (d > 0 ? d + \"T\" : \"\") + h.substr(h.length - 2) + \":\" + m.substr(m.length - 2) + \":\"; // KK-MOD<br/>\n hms += s.substr(s.length - 2) + \".\" + cs.substr(cs.length - 2);<br/>\n return hms; }<br/></p>\n</blockquote>\n\n<p>So now, 192680000 gets displayed as 1T11:16:20.00 which is 1 day 11 hours 16 minutes and 20 seconds</p>\n"
},
{
"answer_id": 4972895,
"author": "Louis Kaplan",
"author_id": 613520,
"author_profile": "https://Stackoverflow.com/users/613520",
"pm_score": 0,
"selected": false,
"text": "<p>I like the K3 + KK-MOD approach, but I needed to show negative timespans, so I made the following modifications:</p>\n\n<pre><code>\nfunction MillisecondsToDuration(milliseconds) {\n var n = Math.abs(milliseconds);\n var hms = \"\";\n var dtm = new Date();\n dtm.setTime(n);\n var d = Math.floor(n / 3600000 / 24); // KK-MOD\n var h = \"0\" + (Math.floor(n / 3600000) - (d * 24)); // KK-MOD\n var m = \"0\" + dtm.getMinutes();\n var s = \"0\" + dtm.getSeconds();\n var cs = \"0\" + Math.round(dtm.getMilliseconds() / 10);\n hms = (milliseconds < 0 ? \" - \" : \"\");\n hms += (d > 0 ? d + \".\" : \"\") + h.substr(h.length - 2) + \":\" + m.substr(m.length - 2) + \":\"; // KK-MOD\n hms += s.substr(s.length - 2) + \".\" + cs.substr(cs.length - 2);\n return hms; }\n</code></pre>\n\n<p>I also changed the 'T' separator to a '.' for my own formatting purposes.</p>\n\n<p>Now a negative value passed in, say -360000 (negative six minutes) will produce the following output:</p>\n\n<p>- 00:06:00</p>\n"
},
{
"answer_id": 12684673,
"author": "Paul",
"author_id": 1634810,
"author_profile": "https://Stackoverflow.com/users/1634810",
"pm_score": 1,
"selected": false,
"text": "<p>I googled for calculating a timespan in javascript and found this question on SO; unfortunately the question text and actual question (only needing hours and minutes) are not the same... so I think I arrived here in error.</p>\n\n<p>I did write an answer to the question title, however - so if anyone else wants something that prints out something like \"1 year, and 15 minutes\", then this is for you:</p>\n\n<pre><code>function formatTimespan(from, to) {\n var text = '',\n span = { y: 0, m: 0, d: 0, h: 0, n: 0 };\n\n function calcSpan(n, fnMod) {\n while (from < to) {\n // Modify the date, and check if the from now exceeds the to:\n from = from[fnMod](1);\n if (from <= to) {\n span[n] += 1;\n } else {\n from = from[fnMod](-1);\n return;\n }\n }\n }\n\n function appendText(n, unit) {\n if (n > 0) {\n text += ((text.length > 0) ? ', ' : '') +\n n.toString(10) + ' ' + unit + ((n === 1) ? '' : 's');\n }\n }\n\n calcSpan('y', 'addYears');\n calcSpan('m', 'addMonths');\n calcSpan('d', 'addDays');\n calcSpan('h', 'addHours');\n calcSpan('n', 'addMinutes');\n\n appendText(span.y, 'year');\n appendText(span.m, 'month');\n appendText(span.d, 'day');\n appendText(span.h, 'hour');\n appendText(span.n, 'minute');\n\n if (text.lastIndexOf(',') < 0) {\n return text;\n }\n\n return text.substring(0, text.lastIndexOf(',')) + ', and' + text.substring(text.lastIndexOf(',') + 1);\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4096/"
]
| I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows:
txtStart.Text = 09/19/2008 07:00:00
txtEnd.Text = 09/19/2008 05:00:00
I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page. | Once your textbox date formats are known in advance, you can use [Matt Kruse's Date functions](http://www.mattkruse.com/javascript/date/) in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.
Equally the [JQuery Date Input](http://jonathanleighton.com/projects/date-input#date-formatting) code for `stringToDate` could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (`getTime()`) of these objects could be used for your calculations.
```
stringToDate: function(string) {
var matches;
if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
return new Date(matches[1], matches[2] - 1, matches[3]);
} else {
return null;
};
}
``` |
141,140 | <p>The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:</p>
<pre><code>void methodName() {
int i = 7;
for (int j = 0; j < 10; j++) {
int i = j * 2;
}
}
</code></pre>
<p>Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!</p>
<p>What's the rationale for this design decision for Java?</p>
<p>Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)</p>
| [
{
"answer_id": 141150,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 3,
"selected": false,
"text": "<p>It leads to bugs that are hard to spot, I guess. It's similar in C#.</p>\n\n<p>Pascal does not support this, since you have to declare variables above the function body.</p>\n"
},
{
"answer_id": 141158,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 5,
"selected": true,
"text": "<p>I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw.</p>\n\n<p>in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious.</p>\n\n<p>ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes.</p>\n"
},
{
"answer_id": 141181,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>Because it's not uncommon for writers to do this intentionally and then totally screw it up by forgetting that there are now two variables with the same name. They change the inner variable name, but leave code that uses the variable, which now unintentially uses the previously-shadowed variable. This results in a program that still compiles, but executes buggily.</p>\n\n<p>Similarly, it's not uncommon to accidentally shadow variables and change the program's behavior. Unknowingly shadowing an existing variable can change the program as easily as unshadowing a variable as I mentioned above.</p>\n\n<p>There's so little benefit to allowing this shadowing that they ruled it out as too dangerous. Seriously, just call your new variable something else and the problem goes away.</p>\n"
},
{
"answer_id": 141289,
"author": "Ricardo Massaro",
"author_id": 98102,
"author_profile": "https://Stackoverflow.com/users/98102",
"pm_score": 5,
"selected": false,
"text": "<p>Well, strictly speaking, Java <em>does</em> have block-scoped variable declarations; so this is an error:</p>\n\n<pre><code>void methodName() {\n for (int j = 0; j < 10; j++) {\n int i = j * 2;\n }\n System.out.println(i); // error\n}\n</code></pre>\n\n<p>Because 'i' doesn't exist outside the for block.</p>\n\n<p>The problem is that Java doesn't allow you to create a variable with the same name of another variable that was declared in an outer block of the same method. As other people have said, supposedly this was done to prevent bugs that are hard to identify.</p>\n"
},
{
"answer_id": 141417,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>The underlying assumption in this question is wrong. </p>\n\n<p>Java <strong>does</strong> have block-level scope. But it also has a hierarchy of scope, which is why you can reference <code>i</code> within the <code>for</code> loop, but not <code>j</code> outside of the for loop.</p>\n\n<pre><code>public void methodName() {\n int i = 7;\n for (int j = 0; j < 10; j++) {\n i = j * 2;\n }\n\n //this would cause a compilation error!\n j++;\n}\n</code></pre>\n\n<p>I can't for the life of me figure out why you would want scoping to behave any other way. It'd be impossible to determine which <code>i</code> you were referring to inside the for loop, and I'd bet chances are 99.999% of the time you want to refer to the <code>i</code> inside the method.</p>\n"
},
{
"answer_id": 37202735,
"author": "user3197104",
"author_id": 3197104,
"author_profile": "https://Stackoverflow.com/users/3197104",
"pm_score": 0,
"selected": false,
"text": "<p>another reason: if this kind of variable declaration were allowed, people would want (need?) a way to access outer block variables. may be something like \"outer\" keyword would be added:</p>\n\n<pre><code>void methodName() {\n int i = 7;\n for (int j = 0; j < 10; j++) {\n int i = outer.i * 2;\n if(i > 10) {\n int i = outer.outer.i * 2 + outer.i;\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/26 | [
"https://Stackoverflow.com/questions/141140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
]
| The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:
```
void methodName() {
int i = 7;
for (int j = 0; j < 10; j++) {
int i = j * 2;
}
}
```
Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!
What's the rationale for this design decision for Java?
Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :) | I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw.
in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious.
ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.