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
|
---|---|---|---|---|---|---|
205,522 |
<p>I have image data and i want to get a sub image of that to use as an opengl texture. </p>
<pre><code>glGenTextures(1, &m_name);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldName);
glBindTexture(GL_TEXTURE_2D, m_name);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
</code></pre>
<p>How can i get a sub image of that image loaded as a texture. I think it has something to do with using glTexSubImage2D, but i have no clue how to use it to create a new texture that i can load. Calling: </p>
<pre><code>glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, xWidth, yHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
</code></pre>
<p>does nothing that i can see, and calling glCopyTexSubImage2D just takes part of my framebuffer.
Thanks</p>
|
[
{
"answer_id": 205569,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p><strong>Edit:</strong> Use glPixelStorei. You use it to set <code>GL_UNPACK_ROW_LENGTH</code> to the width (in pixels) of the entire image. Then you call glTexImage2D (or whatever), passing it a pointer to the first pixel of the subimage and the width and height of the subimage.</p>\n\n<p>Don't forget to restore <code>GL_UNPACK_ROW_LENGTH</code> to 0 when you're finished with it.</p>\n\n<p>Ie:</p>\n\n<pre><code>glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );\nchar *subimg = (char*)m_data + (sub_x + sub_y*img_width)*4;\nglTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, subimg );\nglPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );\n</code></pre>\n\n<p>Or, if you're allergic to pointer maths:</p>\n\n<pre><code>glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );\nglPixelStorei( GL_UNPACK_SKIP_PIXELS, sub_x );\nglPixelStorei( GL_UNPACK_SKIP_ROWS, sub_y );\n\nglTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data );\n\nglPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );\nglPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );\nglPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );\n</code></pre>\n\n<p><strong>Edit2:</strong> For the sake of completeness, I should point out that if you're using OpenGL-ES then you don't get <code>GL_UNPACK_ROW_LENGTH</code>. In which case, you could either (a) extract the subimage into a new buffer yourself, or (b)...</p>\n\n<pre><code>glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTES, NULL );\n\nfor( int y = 0; y < sub_height; y++ )\n{\n char *row = m_data + ((y + sub_y)*img_width + sub_x) * 4;\n glTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, sub_width, 1, GL_RGBA, GL_UNSIGNED_BYTE, row );\n}\n</code></pre>\n"
},
{
"answer_id": 48332955,
"author": "vedranm",
"author_id": 1111634,
"author_profile": "https://Stackoverflow.com/users/1111634",
"pm_score": 2,
"selected": false,
"text": "<p>For those stuck with <strong>OpenGL ES 1.1/2.0</strong> in 2018 and later, I did some tests with different methods how to update part of texture from image data (image is of same size as texture).</p>\n\n<p><strong>Method 1:</strong> Copy whole image with <em>glTexImage2D</em>:</p>\n\n<pre><code>glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_Pixels );\n</code></pre>\n\n<p><strong>Method 2:</strong> Copy whole image with <em>glTexSubImage2D</em>:</p>\n\n<pre><code>glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_Pixels );\n</code></pre>\n\n<p><strong>Method 3:</strong> Copy image part, line by line in a loop:</p>\n\n<pre><code>auto *ptr = m_Pixels + (x + y * mWidth) * 4;\nfor( int i = 0; i < h; i++, ptr += mWidth * 4 ) {\n glTexSubImage2D( GL_TEXTURE_2D, 0, x, y+i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, ptr );\n}\n</code></pre>\n\n<p><strong>Method 4:</strong> Copy whole width of the image, but vertically copy only part which has changed:</p>\n\n<pre><code>auto *ptr = m_Pixels + (y * mWidth) * 4;\nglTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, mWidth, h, GL_RGBA, GL_UNSIGNED_BYTE, ptr );\n</code></pre>\n\n<p>And here are the results of test done on PC, by 100000 times updating different parts of the texture which were about 1/5th of size of the whole texture.</p>\n\n<ul>\n<li>Method 1 - 38.17 sec</li>\n<li>Method 2 - 26.09 sec</li>\n<li>Method 3 - 54.83 sec - slowest</li>\n<li>Method 4 - 5.93 sec - <strong>winner</strong></li>\n</ul>\n\n<p>Not surprisingly, method 4 is fastest, as it copies only part of the image, and does it with a single call to glTex...() function.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25893/"
] |
I have image data and i want to get a sub image of that to use as an opengl texture.
```
glGenTextures(1, &m_name);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldName);
glBindTexture(GL_TEXTURE_2D, m_name);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
```
How can i get a sub image of that image loaded as a texture. I think it has something to do with using glTexSubImage2D, but i have no clue how to use it to create a new texture that i can load. Calling:
```
glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, xWidth, yHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
```
does nothing that i can see, and calling glCopyTexSubImage2D just takes part of my framebuffer.
Thanks
|
**Edit:** Use glPixelStorei. You use it to set `GL_UNPACK_ROW_LENGTH` to the width (in pixels) of the entire image. Then you call glTexImage2D (or whatever), passing it a pointer to the first pixel of the subimage and the width and height of the subimage.
Don't forget to restore `GL_UNPACK_ROW_LENGTH` to 0 when you're finished with it.
Ie:
```
glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );
char *subimg = (char*)m_data + (sub_x + sub_y*img_width)*4;
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, subimg );
glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
```
Or, if you're allergic to pointer maths:
```
glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, sub_x );
glPixelStorei( GL_UNPACK_SKIP_ROWS, sub_y );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data );
glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
```
**Edit2:** For the sake of completeness, I should point out that if you're using OpenGL-ES then you don't get `GL_UNPACK_ROW_LENGTH`. In which case, you could either (a) extract the subimage into a new buffer yourself, or (b)...
```
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTES, NULL );
for( int y = 0; y < sub_height; y++ )
{
char *row = m_data + ((y + sub_y)*img_width + sub_x) * 4;
glTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, sub_width, 1, GL_RGBA, GL_UNSIGNED_BYTE, row );
}
```
|
205,526 |
<p>I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.</p>
<p>Can this be done?</p>
|
[
{
"answer_id": 205537,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": -1,
"selected": false,
"text": "<p>My first thought was to write a query something like this...</p>\n\n<pre><code>SELECT EmpId, NameLast, NameMiddle, NameFirst, DepartmentName\n FROM dbo.Employee\n INNER JOIN dbo.Department ON dbo.Employee.DeptId = dbo.Department.Id\n WHERE IdCrq IS NOT NULL\n AND\n (\n @bitSearchFirstName = 0\n OR\n Employee.NameFirst = @vchFirstName\n )\n AND\n (\n @bitSearchMiddleName = 0\n OR\n Employee.NameMiddle = @vchMiddleName\n )\n AND\n (\n @bitSearchFirstName = 0\n OR\n Employee.NameLast = @vchLastName\n )\n AND\n (\n @bitSearchDepartment = 0\n OR\n Department.Id = @intDeptID\n )\n</code></pre>\n\n<p>...which would then have the caller provide a bit flag if they want to search a particular field and then supply the value if they are to search for it, but I don't know if this is creating a sloppy WHERE clause or if I can get away with a CASE statement in the WHERE clause.</p>\n\n<p>As you can see this particular code is in T-SQL, but I'll gladly look at some PL-SQL / MySQL code as well and adapt accordingly.</p>\n"
},
{
"answer_id": 205541,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 3,
"selected": false,
"text": "<p>The most efficient way to implement this type of search is with a stored procedure. The statement shown here creates a procedure that accepts the required parameters. When a parameter value is not supplied it is set to NULL.</p>\n\n<pre><code>CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry\n@Cus_Name varchar(30) = NULL,\n@Cus_City varchar(30) = NULL,\n@Cus_Country varchar(30) =NULL\nAS\nSELECT Cus_Name,\n Cus_City,\n Cus_Country\nFROM Customers\nWHERE Cus_Name = COALESCE(@Cus_Name,Cus_Name) AND\n Cus_City = COALESCE(@Cus_City,Cus_City) AND\n Cus_Country = COALESCE(@Cus_Country,Cus_Country)\n</code></pre>\n\n<p>Taken from this page: <a href=\"http://www.sqlteam.com/article/implementing-a-dynamic-where-clause\" rel=\"noreferrer\">http://www.sqlteam.com/article/implementing-a-dynamic-where-clause</a></p>\n\n<p>I've done it before. It works well.</p>\n"
},
{
"answer_id": 205554,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "<p>It can be done, but usually these kitchen-sink procedures result in some poor query plans. </p>\n\n<p>Having said all that, here is the tactic most commonly used for \"optional\" parameters. The normal approach is to treat NULL as \"ommitted\".</p>\n\n<pre><code>SELECT\n E.EmployeeID,\n E.LastName,\n E.FirstName\nWHERE\n E.FirstName = COALESCE(@FirstName, E.FirstName) AND\n E.LastName = COALESCE(@LastName, E.LastName) AND\n E.DepartmentID = COALESCE(@DepartmentID, E.DepartmentID)\n</code></pre>\n\n<p>EDIT:\nA far better approach would be parameterized queries.\nHere is a blog post from one of the world's foremost authorities in this domain, Frans Bouma from LLBLGen Pro fame:</p>\n\n<p><a href=\"http://weblogs.asp.net/fbouma/archive/2003/05/14/7008.aspx\" rel=\"nofollow noreferrer\">Stored Procedures vs. Dynamic Queries</a></p>\n"
},
{
"answer_id": 205580,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "<p>Erland Sommarskog's article <a href=\"http://www.sommarskog.se/dyn-search-2008.html\" rel=\"noreferrer\">Dynamic Search Conditions in T-SQL</a> is a good reference on how to do this. Erland presents a number of strategies on how to do this without using dynamic SQL (just plain IF blocks, OR, COALESCE, etc) and even lists out the performance characteristics of each technique.</p>\n\n<p>In case you have to bite the bullet and go through the Dynamic SQL path, you should also read Erland's <a href=\"http://www.sommarskog.se/dynamic_sql.html\" rel=\"noreferrer\">Curse and Blessings of Dynamic SQL</a> where he gives out some tips on how to properly write dynamic SQLs</p>\n"
},
{
"answer_id": 205605,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 5,
"selected": true,
"text": "<p>While the <code>COALESCE</code> trick is neat, my preferred method is:</p>\n\n<pre><code>CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry\n @Cus_Name varchar(30) = NULL\n ,@Cus_City varchar(30) = NULL\n ,@Cus_Country varchar(30) = NULL\n ,@Dept_ID int = NULL\n ,@Dept_ID_partial varchar(10) = NULL\nAS\nSELECT Cus_Name\n ,Cus_City\n ,Cus_Country\n ,Dept_ID\nFROM Customers\nWHERE (@Cus_Name IS NULL OR Cus_Name LIKE '%' + @Cus_Name + '%')\n AND (@Cus_City IS NULL OR Cus_City LIKE '%' + @Cus_City + '%')\n AND (@Cus_Country IS NULL OR Cus_Country LIKE '%' + @Cus_Country + '%')\n AND (@Dept_ID IS NULL OR Dept_ID = @DeptID)\n AND (@Dept_ID_partial IS NULL OR CONVERT(varchar, Dept_ID) LIKE '%' + @Dept_ID_partial + '%')\n</code></pre>\n\n<p>These kind of SPs can easily be code generated (and re-generated for table-changes).</p>\n\n<p>You have a few options for handling numbers - depending if you want exact semantics or search semantics.</p>\n"
},
{
"answer_id": 205611,
"author": "Aheho",
"author_id": 21155,
"author_profile": "https://Stackoverflow.com/users/21155",
"pm_score": -1,
"selected": false,
"text": "<p>I would stick with the NULL/COALESCE method over AdHoc Queries, and then test to make sure you don't have performance problems. </p>\n\n<p>If it turns out that you have slow running queries because it's doing a table scan when you're searching on columns that are indexed, you could always supplement the generic search stored procedure with additional specific ones that allow searching on these indexed fields. For instance, you could have a special SP that does searches by CustomerID, or Last/First Name.</p>\n"
},
{
"answer_id": 205820,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 2,
"selected": false,
"text": "<p>Using the COALESCE method has a problem in that if your column has a NULL value, passing in a NULL search condition (meaning ignore the search condition) will not return the row in many databases.</p>\n\n<p>For example, try the following code on SQL Server 2000:</p>\n\n<pre><code>CREATE TABLE dbo.Test_Coalesce (\n my_id INT NOT NULL IDENTITY,\n my_string VARCHAR(20) NULL )\nGO\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES (NULL)\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES ('t')\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES ('x')\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES (NULL)\nGO\nDECLARE @my_string VARCHAR(20)\nSET @my_string = NULL\nSELECT * FROM dbo.Test_Coalesce WHERE my_string = COALESCE(@my_string, my_string)\nGO\n</code></pre>\n\n<p>You will only get back two rows because in the rows where the column my_string is NULL you are effective getting:</p>\n\n<pre><code>my_string = COALESCE(@my_string, my_string) =>\nmy_string = COALESCE(NULL, my_string) =>\nmy_string = my_string =>\nNULL = NULL\n</code></pre>\n\n<p>But of course, NULL does not equal NULL.</p>\n\n<p>I try to stick with:</p>\n\n<pre><code>SELECT\n my_id,\n my_string\nFROM\n dbo.Test_Coalesce\nWHERE\n (@my_string IS NULL OR my_string = @my_string)\n</code></pre>\n\n<p>Of course, you can adjust that to use wild cards or whatever else you want to do.</p>\n"
},
{
"answer_id": 28470325,
"author": "Manoj Pandey",
"author_id": 2443887,
"author_profile": "https://Stackoverflow.com/users/2443887",
"pm_score": 0,
"selected": false,
"text": "<p>Copying this from my blog post:</p>\n\n<pre><code>USE [AdventureWorks]\nGO\n\nCREATE PROCEDURE USP_GET_Contacts_DynSearch\n(\n -- Optional Filters for Dynamic Search\n @ContactID INT = NULL, \n @FirstName NVARCHAR(50) = NULL, \n @LastName NVARCHAR(50) = NULL, \n @EmailAddress NVARCHAR(50) = NULL, \n @EmailPromotion INT = NULL, \n @Phone NVARCHAR(25) = NULL\n)\nAS\nBEGIN\n SET NOCOUNT ON\n\n DECLARE\n @lContactID INT, \n @lFirstName NVARCHAR(50), \n @lLastName NVARCHAR(50), \n @lEmailAddress NVARCHAR(50), \n @lEmailPromotion INT, \n @lPhone NVARCHAR(25)\n\n SET @lContactID = @ContactID\n SET @lFirstName = LTRIM(RTRIM(@FirstName))\n SET @lLastName = LTRIM(RTRIM(@LastName))\n SET @lEmailAddress = LTRIM(RTRIM(@EmailAddress))\n SET @lEmailPromotion = @EmailPromotion\n SET @lPhone = LTRIM(RTRIM(@Phone))\n\n SELECT\n ContactID, \n Title, \n FirstName, \n MiddleName, \n LastName, \n Suffix, \n EmailAddress, \n EmailPromotion, \n Phone\n FROM [Person].[Contact]\n WHERE\n (@lContactID IS NULL OR ContactID = @lContactID)\n AND (@lFirstName IS NULL OR FirstName LIKE '%' + @lFirstName + '%')\n AND (@lLastName IS NULL OR LastName LIKE '%' + @lLastName + '%')\n AND (@lEmailAddress IS NULL OR EmailAddress LIKE '%' + @lEmailAddress + '%')\n AND (@lEmailPromotion IS NULL OR EmailPromotion = @lEmailPromotion)\n AND (@lPhone IS NULL OR Phone = @lPhone)\n ORDER BY ContactID\n\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 35449867,
"author": "Raaj",
"author_id": 5934195,
"author_profile": "https://Stackoverflow.com/users/5934195",
"pm_score": -1,
"selected": false,
"text": "<p>Write a procedure to insert all employee data whose name start with A in table??</p>\n"
},
{
"answer_id": 48301647,
"author": "Ravindra Vairagi",
"author_id": 6656918,
"author_profile": "https://Stackoverflow.com/users/6656918",
"pm_score": 0,
"selected": false,
"text": "<p>We can use Generic @Search Parameter and pass any value to it for searching.</p>\n\n<pre><code>GO\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- =============================================\n-- Author: --\n-- Create date:\n-- Description: --\n-- =============================================\nCREATE PROCEDURE [dbo].[usp_StudentList]\n @PageNumber INT = 1, -- Paging parameter\n @PageSize INT = 10,-- Paging parameter\n @Search VARCHAR(MAX) = NULL, --Generic Search Parameter\n @OrderBy VARCHAR(MAX) = 'FirstName', --Default Column Name 'FirstName' for records ordering\n @SortDir VARCHAR(MAX) = 'asc' --Default ordering 'asc' for records ordering\nAS\nBEGIN\n SET NOCOUNT ON;\n\n --Query required for paging, this query used to show total records\n SELECT COUNT(StudentId) AS RecordsTotal FROM Student\n\n SELECT Student.*, \n --Query required for paging, this query used to show total records filtered\n COUNT(StudentId) OVER (PARTITION BY 1) AS RecordsFiltered \n FROM Student\n WHERE \n --Generic Search \n -- Below is the column list to add in Generic Serach\n (@Search IS NULL OR Student.FirstName LIKE '%'+ @Search +'%')\n OR (@Search IS NULL OR Student.LastName LIKE '%'+ @Search +'%')\n --Order BY\n -- Below is the column list to allow sorting\n ORDER BY \n CASE WHEN @SortDir = 'asc' AND @OrderBy = 'FirstName' THEN Student.FirstName END,\n CASE WHEN @SortDir = 'desc' AND @OrderBy = 'FirstName' THEN Student.FirstName END DESC,\n CASE WHEN @SortDir = 'asc' AND @OrderBy = 'LastName' THEN Student.LastName END,\n CASE WHEN @SortDir = 'desc' AND @OrderBy = 'LastName' THEN Student.LastName END DESC,\n OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;\nEND\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.
Can this be done?
|
While the `COALESCE` trick is neat, my preferred method is:
```
CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry
@Cus_Name varchar(30) = NULL
,@Cus_City varchar(30) = NULL
,@Cus_Country varchar(30) = NULL
,@Dept_ID int = NULL
,@Dept_ID_partial varchar(10) = NULL
AS
SELECT Cus_Name
,Cus_City
,Cus_Country
,Dept_ID
FROM Customers
WHERE (@Cus_Name IS NULL OR Cus_Name LIKE '%' + @Cus_Name + '%')
AND (@Cus_City IS NULL OR Cus_City LIKE '%' + @Cus_City + '%')
AND (@Cus_Country IS NULL OR Cus_Country LIKE '%' + @Cus_Country + '%')
AND (@Dept_ID IS NULL OR Dept_ID = @DeptID)
AND (@Dept_ID_partial IS NULL OR CONVERT(varchar, Dept_ID) LIKE '%' + @Dept_ID_partial + '%')
```
These kind of SPs can easily be code generated (and re-generated for table-changes).
You have a few options for handling numbers - depending if you want exact semantics or search semantics.
|
205,529 |
<p>Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?</p>
<p>Example:</p>
<pre><code>void format_string(char *fmt, ...);
void debug_print(int dbg_lvl, char *fmt, ...) {
format_string(fmt, /* how do I pass all the arguments from '...'? */);
fprintf(stdout, fmt);
}
</code></pre>
|
[
{
"answer_id": 205584,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 9,
"selected": true,
"text": "<p>To pass the ellipses on, you initialize a <code>va_list</code> as usual and simply pass it to your second function. You don't use <code>va_arg()</code>. Specifically;</p>\n<pre><code>void format_string(char *fmt,va_list argptr, char *formatted_string);\n\n\nvoid debug_print(int dbg_lvl, char *fmt, ...) \n{ \n char formatted_string[MAX_FMT_SIZE];\n\n va_list argptr;\n va_start(argptr,fmt);\n format_string(fmt, argptr, formatted_string);\n va_end(argptr);\n fprintf(stdout, "%s",formatted_string);\n}\n</code></pre>\n"
},
{
"answer_id": 205589,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.</p>\n\n<p>The generally used solution is to always provide an alternate form of vararg functions, so <code>printf</code> has <code>vprintf</code> which takes a <code>va_list</code> in place of the <code>...</code>. The <code>...</code> versions are just wrappers around the <code>va_list</code> versions.</p>\n"
},
{
"answer_id": 5426238,
"author": "user2023370",
"author_id": 2023370,
"author_profile": "https://Stackoverflow.com/users/2023370",
"pm_score": 5,
"selected": false,
"text": "<p>In magnificent C++11 you could use variadic templates:</p>\n<pre><code>template <typename... Ts>\nvoid format_string(char *fmt, Ts ... ts) {}\n\ntemplate <typename... Ts>\nvoid debug_print(int dbg_lvl, char *fmt, Ts... ts)\n{\n format_string(fmt, ts...);\n}\n</code></pre>\n"
},
{
"answer_id": 6835569,
"author": "Yoda",
"author_id": 864185,
"author_profile": "https://Stackoverflow.com/users/864185",
"pm_score": 3,
"selected": false,
"text": "<p>You can use inline assembly for the function call. (in this code I assume the arguments are characters).</p>\n\n<pre><code>void format_string(char *fmt, ...);\nvoid debug_print(int dbg_level, int numOfArgs, char *fmt, ...)\n {\n va_list argumentsToPass;\n va_start(argumentsToPass, fmt);\n char *list = new char[numOfArgs];\n for(int n = 0; n < numOfArgs; n++)\n list[n] = va_arg(argumentsToPass, char);\n va_end(argumentsToPass);\n for(int n = numOfArgs - 1; n >= 0; n--)\n {\n char next;\n next = list[n];\n __asm push next;\n }\n __asm push fmt;\n __asm call format_string;\n fprintf(stdout, fmt);\n }\n</code></pre>\n"
},
{
"answer_id": 8283720,
"author": "Rose Perrone",
"author_id": 365298,
"author_profile": "https://Stackoverflow.com/users/365298",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D\" rel=\"noreferrer\">Variadic Functions</a> can be <strong><a href=\"https://stackoverflow.com/questions/3555583/passing-variable-number-of-arguments-with-different-type-c\">dangerous</a></strong>. Here's a safer trick:</p>\n\n<pre><code> void func(type* values) {\n while(*values) {\n x = *values++;\n /* do whatever with x */\n }\n }\n\nfunc((type[]){val1,val2,val3,val4,0});\n</code></pre>\n"
},
{
"answer_id": 12755437,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 2,
"selected": false,
"text": "<p>Ross' solution cleaned-up a bit. Only works if all args are pointers. Also language implementation must support eliding of previous comma if <code>__VA_ARGS__</code> is empty (both Visual Studio C++ and GCC do).</p>\n\n<pre><code>// pass number of arguments version\n #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__}; _actualFunction(args+1,sizeof(args) / sizeof(*args) - 1);}\n\n\n// NULL terminated array version\n #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__, NULL}; _actualFunction(args+1);}\n</code></pre>\n"
},
{
"answer_id": 16450540,
"author": "Jim",
"author_id": 2364065,
"author_profile": "https://Stackoverflow.com/users/2364065",
"pm_score": -1,
"selected": false,
"text": "<p>I'm unsure if this works for all compilers, but it has worked so far for me.</p>\n\n<pre><code>void inner_func(int &i)\n{\n va_list vars;\n va_start(vars, i);\n int j = va_arg(vars);\n va_end(vars); // Generally useless, but should be included.\n}\n\nvoid func(int i, ...)\n{\n inner_func(i);\n}\n</code></pre>\n\n<p>You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.</p>\n\n<p>The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.</p>\n"
},
{
"answer_id": 29731121,
"author": "Jagdish",
"author_id": 2335246,
"author_profile": "https://Stackoverflow.com/users/2335246",
"pm_score": 3,
"selected": false,
"text": "<p>You can try macro also.</p>\n\n<pre><code>#define NONE 0x00\n#define DBG 0x1F\n#define INFO 0x0F\n#define ERR 0x07\n#define EMR 0x03\n#define CRIT 0x01\n\n#define DEBUG_LEVEL ERR\n\n#define WHERESTR \"[FILE : %s, FUNC : %s, LINE : %d]: \"\n#define WHEREARG __FILE__,__func__,__LINE__\n#define DEBUG(...) fprintf(stderr, __VA_ARGS__)\n#define DEBUG_PRINT(X, _fmt, ...) if((DEBUG_LEVEL & X) == X) \\\n DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)\n\nint main()\n{\n int x=10;\n DEBUG_PRINT(DBG, \"i am x %d\\n\", x);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 31675300,
"author": "Engineer",
"author_id": 279738,
"author_profile": "https://Stackoverflow.com/users/279738",
"pm_score": 0,
"selected": false,
"text": "<p>Let's say you have a typical variadic function you've written. Because at least one argument is required before the variadic one <code>...</code>, you have to always write an extra argument in usage.</p>\n\n<p><strong>Or do you?</strong></p>\n\n<p>If you wrap your variadic function in a macro, you need no preceding arg. Consider this example: </p>\n\n<pre><code>#define LOGI(...)\n ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))\n</code></pre>\n\n<p>This is obviously far more convenient, since you needn't specify the initial argument every time.</p>\n"
},
{
"answer_id": 51167684,
"author": "VarunG",
"author_id": 6165026,
"author_profile": "https://Stackoverflow.com/users/6165026",
"pm_score": 3,
"selected": false,
"text": "<p>Though you can solve passing the formatter by storing it in local buffer first, but that needs stack and can sometime be issue to deal with. I tried following and it seems to work fine.</p>\n\n<pre><code>#include <stdarg.h>\n#include <stdio.h>\n\nvoid print(char const* fmt, ...)\n{\n va_list arg;\n va_start(arg, fmt);\n vprintf(fmt, arg);\n va_end(arg);\n}\n\nvoid printFormatted(char const* fmt, va_list arg)\n{\n vprintf(fmt, arg);\n}\n\nvoid showLog(int mdl, char const* type, ...)\n{\n print(\"\\nMDL: %d, TYPE: %s\", mdl, type);\n\n va_list arg;\n va_start(arg, type);\n char const* fmt = va_arg(arg, char const*);\n printFormatted(fmt, arg);\n va_end(arg);\n}\n\nint main() \n{\n int x = 3, y = 6;\n showLog(1, \"INF, \", \"Value = %d, %d Looks Good! %s\", x, y, \"Infact Awesome!!\");\n showLog(1, \"ERR\");\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 64944830,
"author": "Ali80",
"author_id": 1896554,
"author_profile": "https://Stackoverflow.com/users/1896554",
"pm_score": 2,
"selected": false,
"text": "<h1>Short answer</h1>\n<pre class=\"lang-c prettyprint-override\"><code>/// logs all messages below this level, level 0 turns off LOG \n#ifndef LOG_LEVEL\n#define LOG_LEVEL 5 // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose\n#endif\n#define _LOG_FORMAT_SHORT(letter, format) "[" #letter "]: " format "\\n"\n\n/// short log\n#define log_s(level, format, ...) \\ \n if (level <= LOG_LEVEL) \\ \n printf(_LOG_FORMAT_SHORT(level, format), ##__VA_ARGS__)\n\n</code></pre>\n<p>usage</p>\n<pre class=\"lang-c prettyprint-override\"><code>log_s(1, "fatal error occurred");\nlog_s(3, "x=%d and name=%s",2, "ali");\n</code></pre>\n<p>output</p>\n<pre><code>[1]: fatal error occurred\n[3]: x=2 and name=ali\n</code></pre>\n<h1>log with file and line number</h1>\n<pre class=\"lang-c prettyprint-override\"><code>const char* _getFileName(const char* path)\n{\n size_t i = 0;\n size_t pos = 0;\n char* p = (char*)path;\n while (*p) {\n i++;\n if (*p == '/' || *p == '\\\\') {\n pos = i;\n }\n p++;\n }\n return path + pos;\n}\n\n#define _LOG_FORMAT(letter, format) \\ \n "[" #letter "][%s:%u] %s(): " format "\\n", _getFileName(__FILE__), __LINE__, __FUNCTION__\n\n#ifndef LOG_LEVEL\n#define LOG_LEVEL 5 // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose\n#endif\n\n/// long log\n#define log_l(level, format, ...) \\ \n if (level <= LOG_LEVEL) \\ \n printf(_LOG_FORMAT(level, format), ##__VA_ARGS__)\n</code></pre>\n<p>usage</p>\n<pre class=\"lang-c prettyprint-override\"><code>log_s(1, "fatal error occurred");\nlog_s(3, "x=%d and name=%s",2, "ali");\n</code></pre>\n<p>output</p>\n<pre><code>[1][test.cpp:97] main(): fatal error occurred\n[3][test.cpp:98] main(): x=2 and name=ali\n</code></pre>\n<h1>custom print function</h1>\n<p>you can write custom print function and pass <code>...</code> args to it and it is also possible to combine this with methods above. source from <a href=\"https://github.com/espressif/arduino-esp32/blob/dcff2e9774c1a712e601fd62d08a68a5e74dbc62/cores/esp32/esp32-hal-uart.c#L521\" rel=\"nofollow noreferrer\">here</a></p>\n<pre class=\"lang-c prettyprint-override\"><code>int print_custom(const char* format, ...)\n{\n static char loc_buf[64];\n char* temp = loc_buf;\n int len;\n va_list arg;\n va_list copy;\n va_start(arg, format);\n va_copy(copy, arg);\n len = vsnprintf(NULL, 0, format, arg);\n va_end(copy);\n if (len >= sizeof(loc_buf)) {\n temp = (char*)malloc(len + 1);\n if (temp == NULL) {\n return 0;\n }\n }\n vsnprintf(temp, len + 1, format, arg);\n printf(temp); // replace with any print function you want\n va_end(arg);\n if (len >= sizeof(loc_buf)) {\n free(temp);\n }\n return len;\n}\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4381/"
] |
Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?
Example:
```
void format_string(char *fmt, ...);
void debug_print(int dbg_lvl, char *fmt, ...) {
format_string(fmt, /* how do I pass all the arguments from '...'? */);
fprintf(stdout, fmt);
}
```
|
To pass the ellipses on, you initialize a `va_list` as usual and simply pass it to your second function. You don't use `va_arg()`. Specifically;
```
void format_string(char *fmt,va_list argptr, char *formatted_string);
void debug_print(int dbg_lvl, char *fmt, ...)
{
char formatted_string[MAX_FMT_SIZE];
va_list argptr;
va_start(argptr,fmt);
format_string(fmt, argptr, formatted_string);
va_end(argptr);
fprintf(stdout, "%s",formatted_string);
}
```
|
205,555 |
<p>During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:</p>
<pre><code>select * from customer
where customer.id in (34, 26, ..., 2);
</code></pre>
<p>You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.</p>
<p>My approach I have used so far is something like that:</p>
<pre><code>String result = "";
boolean first = true;
for(String string : collectionOfStrings) {
if(first) {
result+=string;
first=false;
} else {
result+=","+string;
}
}
</code></pre>
<p>But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.</p>
<p>What is your (more) elegant way?</p>
|
[
{
"answer_id": 205596,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure how \"sophisticated\" this is, but it's certainly a bit shorter. It will work with various different types of collection e.g. Set<Integer>, List<String>, etc.</p>\n\n<pre><code>public static final String toSqlList(Collection<?> values) {\n\n String collectionString = values.toString();\n\n // Convert the square brackets produced by Collection.toString() to round brackets used by SQL\n return \"(\" + collectionString.substring(1, collectionString.length() - 1) + \")\";\n}\n</code></pre>\n\n<p><strong>Exercise for reader</strong>: modify this method so that it correctly handles a null/empty collection :)</p>\n"
},
{
"answer_id": 205657,
"author": "Denis Fradlin",
"author_id": 28316,
"author_profile": "https://Stackoverflow.com/users/28316",
"pm_score": 2,
"selected": false,
"text": "<p>There are some third-party Java libraries that provide string join method, but you probably don't want to start using a library just for something simple like that. I would just create a helper method like this, which I think is a bit better than your version, It uses StringBuffer, which will be more efficient if you need to join many strings, and it works on a collection of any type.</p>\n\n<pre><code>public static <T> String join(Collection<T> values)\n{\n StringBuffer ret = new StringBuffer();\n for (T value : values)\n {\n if (ret.length() > 0) ret.append(\",\");\n ret.append(value);\n }\n return ret.toString();\n}\n</code></pre>\n\n<p>Another suggestion with using Collection.toString() is shorter, but that relies on Collection.toString() returning a string in a very specific format, which I would personally not want to rely on.</p>\n"
},
{
"answer_id": 205712,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 7,
"selected": true,
"text": "<p>Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.</p>\n\n<hr>\n\n<p>Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.</p>\n\n<p>The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.</p>\n\n<p>The original suggestion in the question can be written even more clearly and efficiently, by taking care of the <em>redundant trailing comma</em>:</p>\n\n<pre><code> StringBuilder result = new StringBuilder();\n for(String string : collectionOfStrings) {\n result.append(string);\n result.append(\",\");\n }\n return result.length() > 0 ? result.substring(0, result.length() - 1): \"\";\n</code></pre>\n"
},
{
"answer_id": 205813,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's not a good idea contruct the sql concatenating the where clause values like you are doing :</p>\n\n<pre><code>SELECT.... FROM.... WHERE ID IN( value1, value2,....valueN)\n</code></pre>\n\n<p>Where <code>valueX</code> comes from a list of Strings. </p>\n\n<p>First, if you are comparing Strings they must be quoted, an this it isn't trivial if the Strings could have a quote inside. </p>\n\n<p>Second, if the values comes from the user,or other system, then a SQL injection attack is possible.</p>\n\n<p>It's a lot more verbose but what you should do is create a String like this:</p>\n\n<pre><code>SELECT.... FROM.... WHERE ID IN( ?, ?,....?)\n</code></pre>\n\n<p>and then bind the variables with <code>Statement.setString(nParameter,parameterValue)</code>.</p>\n"
},
{
"answer_id": 205817,
"author": "Ogre Psalm33",
"author_id": 13140,
"author_profile": "https://Stackoverflow.com/users/13140",
"pm_score": 6,
"selected": false,
"text": "<p>I just looked at code that did this today. This is a variation on AviewAnew's answer.</p>\n\n<pre><code>collectionOfStrings = /* source string collection */;\nString csList = StringUtils.join(collectionOfStrings.toArray(), \",\");\n</code></pre>\n\n<p>The <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html\" rel=\"noreferrer\">StringUtils</a> ( <-- commons.lang 2.x, or <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#join(char[],%20char)\" rel=\"noreferrer\">commons.lang 3.x link</a>) we used is from <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/package-summary.html\" rel=\"noreferrer\">Apache Commons</a>.</p>\n"
},
{
"answer_id": 205976,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": false,
"text": "<p>The way I write that loop is:</p>\n\n<pre><code>StringBuilder buff = new StringBuilder();\nString sep = \"\";\nfor (String str : strs) {\n buff.append(sep);\n buff.append(str);\n sep = \",\";\n}\nreturn buff.toString();\n</code></pre>\n\n<p>Don't worry about the performance of sep. An assignment is <em>very</em> fast. Hotspot tends to peel off the first iteration of a loop anyway (as it often has to deal with oddities such as null and mono/bimorphic inlining checks).</p>\n\n<p>If you use it lots (more than once), put it in a shared method.</p>\n\n<p>There is another question on stackoverflow dealing with how to insert a list of ids into an SQL statement.</p>\n"
},
{
"answer_id": 205996,
"author": "Julie",
"author_id": 8217,
"author_profile": "https://Stackoverflow.com/users/8217",
"pm_score": 7,
"selected": false,
"text": "<p>Use the <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"noreferrer\">Google Guava API</a>'s <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Joiner.html#join%28java.lang.Iterable%29\" rel=\"noreferrer\"><code>join</code></a> method:</p>\n\n<pre><code>Joiner.on(\",\").join(collectionOfStrings);\n</code></pre>\n"
},
{
"answer_id": 206067,
"author": "silverminken",
"author_id": 24777,
"author_profile": "https://Stackoverflow.com/users/24777",
"pm_score": 2,
"selected": false,
"text": "<p>Just another method to deal with this problem. Not the most short, but it is efficient and gets the job done.</p>\n\n<pre><code>/**\n * Creates a comma-separated list of values from given collection.\n * \n * @param <T> Value type.\n * @param values Value collection.\n * @return Comma-separated String of values.\n */\npublic <T> String toParameterList(Collection<T> values) {\n if (values == null || values.isEmpty()) {\n return \"\"; // Depending on how you want to deal with this case...\n }\n StringBuilder result = new StringBuilder();\n Iterator<T> i = values.iterator();\n result.append(i.next().toString());\n while (i.hasNext()) {\n result.append(\",\").append(i.next().toString());\n }\n return result.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 208476,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 4,
"selected": false,
"text": "<p>I found the iterator idiom elegant, because it has a test for more elements (ommited null/empty test for brevity):</p>\n\n<pre><code>public static String convert(List<String> list) {\n String res = \"\";\n for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {\n res += iterator.next() + (iterator.hasNext() ? \",\" : \"\");\n }\n return res;\n}\n</code></pre>\n"
},
{
"answer_id": 212266,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 0,
"selected": false,
"text": "<p>You may be able to use LINQ (to SQL), and you may be able to make use of the Dynamic Query LINQ sample from MS. <a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a></p>\n"
},
{
"answer_id": 936813,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 3,
"selected": false,
"text": "<p>You could try</p>\n\n<pre><code>List collections = Arrays.asList(34, 26, \"...\", 2);\nString asString = collection.toString();\n// justValues = \"34, 26, ..., 2\"\nString justValues = asString.substring(1, asString.length()-1);\n</code></pre>\n"
},
{
"answer_id": 936880,
"author": "Carl Manaster",
"author_id": 82118,
"author_profile": "https://Stackoverflow.com/users/82118",
"pm_score": 1,
"selected": false,
"text": "<p>What makes the code ugly is the special-handling for the first case. Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case. And that's what alternatives like gimel's solve, by moving the special handling outside the loop. There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.</p>\n"
},
{
"answer_id": 1173979,
"author": "case nelson",
"author_id": 111716,
"author_profile": "https://Stackoverflow.com/users/111716",
"pm_score": 3,
"selected": false,
"text": "<p>There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Joiner.html\" rel=\"noreferrer\">google collections Joiner class</a>.</p>\n\n<pre><code>Joiner.on(\", \").join(34, 26, ..., 2)\n</code></pre>\n\n<p>It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.</p>\n"
},
{
"answer_id": 2132934,
"author": "xss",
"author_id": 258496,
"author_profile": "https://Stackoverflow.com/users/258496",
"pm_score": 1,
"selected": false,
"text": "<p>Join 'methods' are available in Arrays and the classes that extend <code>AbstractCollections</code> but doesn't override <code>toString()</code> method (like virtually all collections in <code>java.util</code>).</p>\n\n<p>For instance:</p>\n\n<pre><code>String s= java.util.Arrays.toString(collectionOfStrings.toArray());\ns = s.substing(1, s.length()-1);// [] are guaranteed to be there\n</code></pre>\n\n<hr>\n\n<p>That's quite weird way since it works only for numbers alike data SQL wise.</p>\n"
},
{
"answer_id": 2133160,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 1,
"selected": false,
"text": "<p>I've just checked-in a test for my library <a href=\"http://bitbucket.org/dfa/dollar/\" rel=\"nofollow noreferrer\">dollar</a>:</p>\n\n<pre><code>@Test\npublic void join() {\n List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);\n String string = $(list).join(\",\");\n}\n</code></pre>\n\n<p>it create a fluent wrapper around lists/arrays/strings/etc using <strong>only one static import</strong>: <code>$</code>.</p>\n\n<p><strong>NB</strong>:</p>\n\n<p>using ranges the previous list can be re-writed as <code>$(1, 5).join(\",\")</code></p>\n"
},
{
"answer_id": 7005680,
"author": "VIM",
"author_id": 887135,
"author_profile": "https://Stackoverflow.com/users/887135",
"pm_score": 1,
"selected": false,
"text": "<p>The nice thing about the IN expression is that if you have repeated values, it does not change the result. So, just duplicate the first item and process the entire list. This assumes that there is at least one item in the list. If there are no items, I'd suggest checking for that first and then not executing the SQL at all.</p>\n\n<p>This will do the trick, is obvious in what it is doing and does not rely on any external libraries:</p>\n\n<pre><code>StringBuffer inString = new StringBuffer(listOfIDs.get(0).toString());\nfor (Long currentID : listOfIDs) {\n inString.append(\",\").append(currentID);\n}\n</code></pre>\n"
},
{
"answer_id": 7688450,
"author": "Jeff",
"author_id": 984148,
"author_profile": "https://Stackoverflow.com/users/984148",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an incredibly generic version that I've built from a combination of the previous suggestions:</p>\n\n<pre><code>public static <T> String buildCommaSeparatedString(Collection<T> values) {\n if (values==null || values.isEmpty()) return \"\";\n StringBuilder result = new StringBuilder();\n for (T val : values) {\n result.append(val);\n result.append(\",\");\n }\n return result.substring(0, result.length() - 1);\n}\n</code></pre>\n"
},
{
"answer_id": 7935427,
"author": "Julio César",
"author_id": 1019183,
"author_profile": "https://Stackoverflow.com/users/1019183",
"pm_score": 0,
"selected": false,
"text": "<pre><code>java.util.List<String> lista = new java.util.ArrayList<String>();\nlista.add(\"Hola\");\nlista.add(\"Julio\");\nSystem.out.println(lista.toString().replace('[','(').replace(']',')'));\n\n$~(Hola, Julio)\n</code></pre>\n"
},
{
"answer_id": 9015846,
"author": "weekens",
"author_id": 362738,
"author_profile": "https://Stackoverflow.com/users/362738",
"pm_score": 2,
"selected": false,
"text": "<p>If you use Spring, you can do:</p>\n\n<pre><code>StringUtils.arrayToCommaDelimitedString(\n collectionOfStrings.toArray()\n)\n</code></pre>\n\n<p>(package org.springframework.util)</p>\n"
},
{
"answer_id": 12981729,
"author": "Victor",
"author_id": 3419,
"author_profile": "https://Stackoverflow.com/users/3419",
"pm_score": 1,
"selected": false,
"text": "<p>While I think your best bet is to use Joiner from Guava, if I were to code it by hand I find this approach more elegant that the 'first' flag or chopping the last comma off. </p>\n\n<pre><code>private String commas(Iterable<String> strings) {\n StringBuilder buffer = new StringBuilder();\n Iterator<String> it = strings.iterator();\n if (it.hasNext()) {\n buffer.append(it.next());\n while (it.hasNext()) {\n buffer.append(',');\n buffer.append(it.next());\n }\n }\n\n return buffer.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 15254328,
"author": "iTake",
"author_id": 898776,
"author_profile": "https://Stackoverflow.com/users/898776",
"pm_score": 2,
"selected": false,
"text": "<p>This will be the shortest solution so far, except of using Guava or Apache Commons</p>\n\n<pre><code>String res = \"\";\nfor (String i : values) {\n res += res.isEmpty() ? i : \",\"+i;\n}\n</code></pre>\n\n<p>Good with 0,1 and n element list. But you'll need to check for null list.\nI use this in GWT, so I'm good without StringBuilder there. And for short lists with just couple of elements its ok too elsewhere ;)</p>\n"
},
{
"answer_id": 18399511,
"author": "cloudy_weather",
"author_id": 2028803,
"author_profile": "https://Stackoverflow.com/users/2028803",
"pm_score": 1,
"selected": false,
"text": "<p>if you have an array you can do:</p>\n\n<pre><code>Arrays.asList(parameters).toString()\n</code></pre>\n"
},
{
"answer_id": 19963805,
"author": "Todd Gatts",
"author_id": 2989479,
"author_profile": "https://Stackoverflow.com/users/2989479",
"pm_score": 0,
"selected": false,
"text": "<pre><code>String commaSeparatedNames = namesList.toString().replaceAll( \"[\\\\[|\\\\]| ]\", \"\" ); // replace [ or ] or blank\n</code></pre>\n\n<blockquote>\n <p>The string representation consists of a list of the collection's\n elements in the order they are returned by its iterator, enclosed in\n square brackets (\"[]\"). Adjacent elements are separated by the\n characters \", \" (comma and space).</p>\n \n <p>AbstractCollection javadoc</p>\n</blockquote>\n"
},
{
"answer_id": 27243582,
"author": "Ups",
"author_id": 2493314,
"author_profile": "https://Stackoverflow.com/users/2493314",
"pm_score": 0,
"selected": false,
"text": "<p>List token=new ArrayList(result);\nfinal StringBuilder builder = new StringBuilder();</p>\n\n<pre><code> for (int i =0; i < tokens.size(); i++){\n builder.append(tokens.get(i));\n if(i != tokens.size()-1){\n builder.append(TOKEN_DELIMITER);\n }\n }\n</code></pre>\n\n<p>builder.toString();</p>\n"
},
{
"answer_id": 27510575,
"author": "robjwilkins",
"author_id": 4315049,
"author_profile": "https://Stackoverflow.com/users/4315049",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String.join(\", \", collectionOfStrings)\n</code></pre>\n\n<p>available in the Java8 api.</p>\n\n<p>alternative to (without the need to add a google guava dependency):</p>\n\n<pre><code>Joiner.on(\",\").join(collectionOfStrings);\n</code></pre>\n"
},
{
"answer_id": 27782188,
"author": "elcuco",
"author_id": 78712,
"author_profile": "https://Stackoverflow.com/users/78712",
"pm_score": 1,
"selected": false,
"text": "<p>Another option, based on what I see here (with slight modifications).</p>\n\n<pre><code>public static String toString(int[] numbers) {\n StringBuilder res = new StringBuilder();\n for (int number : numbers) {\n if (res.length() != 0) {\n res.append(',');\n }\n res.append(number);\n }\n return res.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 29234107,
"author": "Christof",
"author_id": 640539,
"author_profile": "https://Stackoverflow.com/users/640539",
"pm_score": 2,
"selected": false,
"text": "<p>In case someone stumbled over this in more recent times, I have added a simple variation using Java 8 <code>reduce()</code>. It also includes some of the already mentioned solutions by others:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.List;\n\nimport org.apache.commons.lang.StringUtils; \n\nimport com.google.common.base.Joiner;\n\npublic class Dummy {\n public static void main(String[] args) {\n\n List<String> strings = Arrays.asList(\"abc\", \"de\", \"fg\");\n String commaSeparated = strings\n .stream()\n .reduce((s1, s2) -> {return s1 + \",\" + s2; })\n .get();\n\n System.out.println(commaSeparated);\n\n System.out.println(Joiner.on(',').join(strings));\n\n System.out.println(StringUtils.join(strings, \",\"));\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29758572,
"author": "Pascalius",
"author_id": 505248,
"author_profile": "https://Stackoverflow.com/users/505248",
"pm_score": 2,
"selected": false,
"text": "<p>In Android you should use this:</p>\n\n<pre><code>TextUtils.join(\",\",collectionOfStrings.toArray());\n</code></pre>\n"
},
{
"answer_id": 30954872,
"author": "Abdull",
"author_id": 923560,
"author_profile": "https://Stackoverflow.com/users/923560",
"pm_score": 6,
"selected": false,
"text": "<p>Since Java 8, you can use:</p>\n\n<ul>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-\"><code>String String.join(CharSequence delimiter, CharSequence... elements)</code></a></li>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-\"><code>String String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)</code></a></li>\n<li><p>If you want to take non-<code>String</code>s and join them to a <code>String</code>, you can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining-java.lang.CharSequence-\"><code>Collectors.joining(CharSequence delimiter)</code></a>, e.g.:</p>\n\n<p><code>String joined = anyCollection.stream().map(Object::toString).collect(Collectors.joining(\",\"));</code></p></li>\n</ul>\n"
},
{
"answer_id": 33164417,
"author": "Fathah Rehman P",
"author_id": 991065,
"author_profile": "https://Stackoverflow.com/users/991065",
"pm_score": 0,
"selected": false,
"text": "<p>There is an easy way. You can get your result in a single line. </p>\n\n<pre><code>String memberIdsModifiedForQuery = memberIds.toString().replace(\"[\", \"(\").replace(\"]\", \")\");\n</code></pre>\n\n<p>To get complete idea check the code below</p>\n\n<pre><code> public static void main(String[] args) { \n List<Integer>memberIds=new ArrayList<Integer>(); //This contain member ids we want to process\n //adding some sample values for example\n memberIds.add(3); \n memberIds.add(4);\n memberIds.add(2);\n String memberIdsModifiedForQuery = memberIds.toString().replace(\"[\", \"(\").replace(\"]\", \")\"); //here you will get (3,4,5) That you can directly use in query\n System.out.println(memberIdsModifiedForQuery);\n String exampleQuery=\"select * from customer where customer.id in \"+memberIdsModifiedForQuery+\" \";\n }\n</code></pre>\n"
},
{
"answer_id": 38301017,
"author": "Jayman Jani",
"author_id": 4993880,
"author_profile": "https://Stackoverflow.com/users/4993880",
"pm_score": 0,
"selected": false,
"text": "<p>The Most easier way in android for convert List to Comma separated String is By useing <code>android.text.TextUtils</code></p>\n\n<pre><code> ArrayList<String>Myli = new ArrayList<String>();\n String ArayCommase=android.text.TextUtils.join(\",\", Myli);\n</code></pre>\n"
},
{
"answer_id": 57900835,
"author": "Sridhar",
"author_id": 8036307,
"author_profile": "https://Stackoverflow.com/users/8036307",
"pm_score": 2,
"selected": false,
"text": "<pre><code>List<String> collectionOfStrings = // List of string to concat\nString csvStrings = StringUtils.collectionToDelimitedString(collectionOfStrings, \",\");\n</code></pre>\n\n<p>StringUtils from springframeowrk:spring-core </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038/"
] |
During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:
```
select * from customer
where customer.id in (34, 26, ..., 2);
```
You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.
My approach I have used so far is something like that:
```
String result = "";
boolean first = true;
for(String string : collectionOfStrings) {
if(first) {
result+=string;
first=false;
} else {
result+=","+string;
}
}
```
But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.
What is your (more) elegant way?
|
Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.
---
Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.
The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.
The original suggestion in the question can be written even more clearly and efficiently, by taking care of the *redundant trailing comma*:
```
StringBuilder result = new StringBuilder();
for(String string : collectionOfStrings) {
result.append(string);
result.append(",");
}
return result.length() > 0 ? result.substring(0, result.length() - 1): "";
```
|
205,557 |
<p>If you develop for ATG Dynamo, how do you structure your modules and dependencies?</p>
<p>How do you structure the projects? source directories, JARs configs etc.</p>
<p>How do you build and deploy? What tools do you use?</p>
|
[
{
"answer_id": 271071,
"author": "talanb",
"author_id": 20103,
"author_profile": "https://Stackoverflow.com/users/20103",
"pm_score": 3,
"selected": false,
"text": "<p>We have a monolithic architecture with a single ATG module. We originally developed this site with JHTML and have since created a (monolithic) J2EE web app within this ATG module and converted all of our JHTML to JSP.</p>\n\n<p>Our project on disk looks like this:</p>\n\n<pre><code>root\n deploy\n class (compile java to here)\n config (primary configpath)\n docroot (JHTML docroot)\n dev (configpath for dev environment)\n test (configpath for QA environment)\n prod (configpath for prod environment)\n j2ee (j2ee web-app)\n WEB-INF\n dir-a (application JSPs)\n dir-b (application JSPs)\n src\n java (java src)\n sql (sql src)\n</code></pre>\n\n<p>We have an Ant build file that compiles the Java source to deploy/class. On dev/test and prod JAR up. We have a single build server that checks out the CVS repository and uses shell scripts and the build.xml to compile and deploy to the requested server using Interwoven OpenDeploy (essentially rsync).</p>\n"
},
{
"answer_id": 610567,
"author": "boyd4715",
"author_id": 8981,
"author_profile": "https://Stackoverflow.com/users/8981",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the layout that we use:</p>\n\n<p>root<br>\n src (java src)<br>\n test/src (unit test)<br>\n build (directory created by ant)<br>\n classes<br>\n config<br>\n javadoc<br>\n lib<br>\n liveconfig<br>\n buildlib (libraries used for building)<br>\n config<br>\n install (holds items used for different IDE)<br>\n j2ee-apps<br>\n lib (libraries used by the application)<br>\n sql<br>\n oracle<br>\n data<br>\n install (tables, indexes etc)<br>\n setup (create tablespace, users etc)<br>\n uninstall<br>\n delta (changes during development) </p>\n"
},
{
"answer_id": 941728,
"author": "bluegene",
"author_id": 1175964,
"author_profile": "https://Stackoverflow.com/users/1175964",
"pm_score": 2,
"selected": false,
"text": "<p>Most structures look like the ones mentioned above with minor changes. \nWe use MAVEN to build and deploy.</p>\n"
},
{
"answer_id": 3065063,
"author": "Miro A.",
"author_id": 369692,
"author_profile": "https://Stackoverflow.com/users/369692",
"pm_score": 1,
"selected": false,
"text": "<p>Very similar to the above (no Maven). Plus the groovy directory - we use lot of groovy scripts for deployment/building related task (Ant in combination with Antbuilder)</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
] |
If you develop for ATG Dynamo, how do you structure your modules and dependencies?
How do you structure the projects? source directories, JARs configs etc.
How do you build and deploy? What tools do you use?
|
We have a monolithic architecture with a single ATG module. We originally developed this site with JHTML and have since created a (monolithic) J2EE web app within this ATG module and converted all of our JHTML to JSP.
Our project on disk looks like this:
```
root
deploy
class (compile java to here)
config (primary configpath)
docroot (JHTML docroot)
dev (configpath for dev environment)
test (configpath for QA environment)
prod (configpath for prod environment)
j2ee (j2ee web-app)
WEB-INF
dir-a (application JSPs)
dir-b (application JSPs)
src
java (java src)
sql (sql src)
```
We have an Ant build file that compiles the Java source to deploy/class. On dev/test and prod JAR up. We have a single build server that checks out the CVS repository and uses shell scripts and the build.xml to compile and deploy to the requested server using Interwoven OpenDeploy (essentially rsync).
|
205,568 |
<p>There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over.</p>
<p>I understand the arguments, but <a href="https://stackoverflow.com/questions/174198/c35-automatic-properties-why-not-access-the-field-directly#205567">I don't think it's good advice in most cases</a>.</p>
<p>Does anyone have an example of a time when it really mattered? When writing a trivial property made something important possible in the future (or when failing to use one got them in to real trouble)?</p>
<p>EDIT: The DataBinding argument is correct, but not very interesting. It's a bug in the DataBinding code that it won't accept public fields. So, we have to write properties to work around that bug, not because properties are a wise class design choice.</p>
<p>EDIT: To be clear, I'm looking for real-world examples, not theory. A time when it really mattered.</p>
<p>EDIT: The ability to set a breakpoint on the setter seems valuable. Designing my code for the debugger is unfortunate: I'd rather the debugger get smarter, but given the debugger we have, I'll take this ability. Good stuff.</p>
|
[
{
"answer_id": 205577,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": false,
"text": "<p>Part of the idea is that those properties may not be trivial in the future - if you bound external code to a field and later wanted to wrap that in a property, all of the dependent code would have to change, and you may not be able to do that, especially in the case where you are a control designer or have libraries that you can't control, etc.</p>\n\n<p>Not to mention there are certain .NET practices that will not allow you to use a field - databinding particularly.</p>\n\n<p>I am sure there are other good reasons as well. Why does it matter to you? Use an automatic property and be done with it. Seems like something not worth being concerned about to me...</p>\n"
},
{
"answer_id": 205610,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>I used to think the same thing, Jay. Why use a property if it's only there to provide <em>direct</em> access to a private member? If you can describe it as an autoproperty, having a property at all rather than a field seemed kind of silly. Even if you ever need to change the implementation, you could always just refactor into a real property later and any dependent code would still work, right?. Well, maybe not.</p>\n\n<p>You see, I've recently seen the light on trivial properties, so maybe now I can help you do the same.</p>\n\n<p>What finally convinced me was the fairly obvious point (in retrospect) that properties in .Net are just syntactic sugar for getter and setter methods, and those methods have a <em>different name</em> from the property itself. Code in the same assembly will still work, because you have to recompile it at the same time anyway. But any code in a different assembly that links to yours will <em>fail</em> if you refactor a field to a property, unless it's recompiled against your new version at the same time. If it's a property from the get-go, everything is still good.</p>\n"
},
{
"answer_id": 205617,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 1,
"selected": false,
"text": "<p>I once had fields that I wanted to expose from a windows from project which allowed the stats for the program (TotalItems and SuccessfulItems).</p>\n\n<p>Later I decided to display the stats on the form and was able to add a call in the setter that updated the display when the property changed.</p>\n"
},
{
"answer_id": 205623,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": false,
"text": "<p>I've had a trivial property save me a couple of times when debugging. .Net doesn't support the concept of a data break point (read or write). Occasionally when debugging a very complex scenario it was important to track read/writes to a particular property. This is easy with a property but impossible with a field. </p>\n\n<p>If you're not working in a production environment, it's simple to refactor a field -> property for the purpose of debugging. Occasionally though you hit bugs that only reproduce in a production environment that is difficult to patch with a new binary. A property can save you here. </p>\n\n<p>It's a fairly constrained scenario though. </p>\n"
},
{
"answer_id": 205626,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 2,
"selected": false,
"text": "<p>It's much easier to debug a problem involving a field if it is wrapped by a property accessor. Placing breakpoints in the accessor can quite quickly help with finding re-entrancy and other issues that otherwise might not be caught. By marshaling all access to the field through an accessor, you can ascertain exactly who is changing what and when.</p>\n"
},
{
"answer_id": 205638,
"author": "John Kraft",
"author_id": 7495,
"author_profile": "https://Stackoverflow.com/users/7495",
"pm_score": 2,
"selected": false,
"text": "<p>In .NET, from my understanding, you cannot databind to public fields; but only to properties. Thus, if you want to do databinding, you have no choice.</p>\n"
},
{
"answer_id": 205667,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "<p>Obviously, if you're not creating a shared class library, and you're not using DataBinding, then using a field will cause you no problems whatsoever.</p>\n\n<p>But if you're creating a shared class library, you'd be foolish IMHO to do otherwise than follow the guidelines, for the usual three reasons:</p>\n\n<ul>\n<li><p>consumers of your shared class library may want to use DataBinding.</p></li>\n<li><p>consumers of your shared class might want binary compatibility, which is not possible if you switch from a field to a property. </p></li>\n<li><p>the principal of least surprise implies you should be consistent with other shared class libraries including the .NET Framework itself.</p></li>\n</ul>\n"
},
{
"answer_id": 205743,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO there is no such thing as a trivial property as people have been calling them. Via the way things such as databinding work, Microsoft has implied that any bit of data that is a part of the public interface of an object should be a property. I don't think they meant it merely to be a convention like it is in some other languages where property syntax is more about convention and convenience. </p>\n\n<p>A more interesting question may be: \"When should I use a public field instead of a property\", or \"When has a public field instead of a public property saved your bacon?\" </p>\n"
},
{
"answer_id": 205876,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>I'll answer your question with another one: have you ever really benefited from not making all your types and members public? I suspect I haven't directly prevented any bugs by doing so. However, I've encapsulated my types properly, only exposing what's meant to be exposed. Properties are similar - good design more than anything else. I think of properties as conceptually different from fields; they're part of the contract rather than being fundamentally part of the implementation. Thinking about them as properties rather than fields helps me to think more clearly about my design, leading to better code.</p>\n\n<p>Oh, and I've benefited occasionally from not breaking source compatibility, being able to set breakpoints, log access etc.</p>\n"
},
{
"answer_id": 207146,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 6,
"selected": true,
"text": "<p>It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming. </p>\n\n<p>Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing a public field. Fast enough that I'll never notice.</p>\n\n<p>Some non-trivial things that come to mind</p>\n\n<ol>\n<li>A public field is totally public, you can not impose read-only or write-only semantics</li>\n<li>A property can have have different <code>get</code> versus <code>set</code> accessibility (e.g. public get, internal set)</li>\n<li>You can not override a field, but you can have virtual properties. </li>\n<li>Your class has no control over the public field</li>\n<li>Your class can control the property. It can limit setting to allowable range of values, flag that the state was changed, and even lazy-load the value.</li>\n<li>Reflection semantics differ. A public field is not a property.</li>\n<li>No databinding, as others point out. (It's only a bug to you. - I can understand Why .net framework designers do not support patterns they are not in favour of.)</li>\n<li>You can not put a field on an interface, but you can put a property on an interface.</li>\n<li>Your property doesn't even need to store data. You can create a facade and dispatch to a contained object.</li>\n</ol>\n\n<p>You only type an extra 13 characters for correctness. That hardly seems like speculative generality. There is a semantic difference, and if nothing else, a property has a different semantic meaning and is far more flexible than a public field.</p>\n\n<pre><code> public string Name { get; set; }\n public string name;\n</code></pre>\n\n<p>I do recall one time when first using .net I coded a few classes as just fields, and then I needed to have them as properties for some reason, and it was a complete waste of time when I could have just done it right the first time.</p>\n\n<p>So what reasons do you have for <em>not</em> following convention? Why do you feel the need to swim upstream? What has it saved you by not doing this?</p>\n"
},
{
"answer_id": 13385502,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>Fields which are of structure types allow direct access to the members thereof, while properties of such types do not. Consequently, if <code>Thing.Boz</code> were a field of type <code>Point</code>, code which wants to modify its <code>X</code> value could simply say <code>Thing.Boz.X += 5;</code>; if <code>Thing.Boz</code> were a mutable property, it would be necessary to use <code>var tmp = Thing.Boz; tmp.X += 5; Thing.Boz = tmp;</code>. The ability to write things more cleanly with the exposed field is often, <i>but not always</i>, a blessing.</p>\n\n<p>If it will always be possible for <code>Boz</code> to be a field, modifying its members directly will be cleaner, faster, and better than copying it to a temporary variable, modifying that, and copying it back. If the type of <code>Boz</code> exposes its mutable fields directly (as structures should) rather than wrapping them in trivial wrappers, it will also be possible to use things like <code>Interlocked</code> methods on them--something that's simply impossible with properties. There's really only one disadvantage to using fields in that way: if it's ever necessary to replace the field with a property, code which relied upon the thing being a field will break, and may be hard to fix.</p>\n\n<p>In short, I would posit that in cases where one isn't concerned about being able to swap in different versions of code without having to recompile any consumers, the biggest effect of using properties rather than fields is to prevent consumers of the code from writing code which would take advantage of (and rely upon) the semantics of exposed fields which are of structure types.</p>\n\n<p>Incidentally, an alternative to exposing a field of a structure type would be to expose an <code>ActOnXXX</code> method. For example:</p>\n\n<pre><code>delegate void ActionByRef<T1>(ref T1 p1);\ndelegate void ActionByRef<T1,T2>(ref T1 p1, ref T2 p2);\ndelegate void ActionByRef<T1,T2,T3>(ref T1 p1, ref T2 p2, ref T3 p3);\n// Method within the type that defines property `Boz`\nvoid ActOnBoz<T1>(ActionByRef<Point, T1> proc, ref T1 p1)\n{\n proc(ref _Boz, ref p1); // _Boz is the private backing field\n}\n</code></pre>\n\n<p>Code which wanted to add some local variable <code>q</code> to <code>Thing.Boz.X</code> could call <code>Thing.ActOnBoz((ref Point pt, ref int x) => {pt.X += x;}, ref q);</code> and have the action performed directly on <code>Thing._Boz</code>, even though the field is not exposed.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5314/"
] |
There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over.
I understand the arguments, but [I don't think it's good advice in most cases](https://stackoverflow.com/questions/174198/c35-automatic-properties-why-not-access-the-field-directly#205567).
Does anyone have an example of a time when it really mattered? When writing a trivial property made something important possible in the future (or when failing to use one got them in to real trouble)?
EDIT: The DataBinding argument is correct, but not very interesting. It's a bug in the DataBinding code that it won't accept public fields. So, we have to write properties to work around that bug, not because properties are a wise class design choice.
EDIT: To be clear, I'm looking for real-world examples, not theory. A time when it really mattered.
EDIT: The ability to set a breakpoint on the setter seems valuable. Designing my code for the debugger is unfortunate: I'd rather the debugger get smarter, but given the debugger we have, I'll take this ability. Good stuff.
|
It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming.
Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing a public field. Fast enough that I'll never notice.
Some non-trivial things that come to mind
1. A public field is totally public, you can not impose read-only or write-only semantics
2. A property can have have different `get` versus `set` accessibility (e.g. public get, internal set)
3. You can not override a field, but you can have virtual properties.
4. Your class has no control over the public field
5. Your class can control the property. It can limit setting to allowable range of values, flag that the state was changed, and even lazy-load the value.
6. Reflection semantics differ. A public field is not a property.
7. No databinding, as others point out. (It's only a bug to you. - I can understand Why .net framework designers do not support patterns they are not in favour of.)
8. You can not put a field on an interface, but you can put a property on an interface.
9. Your property doesn't even need to store data. You can create a facade and dispatch to a contained object.
You only type an extra 13 characters for correctness. That hardly seems like speculative generality. There is a semantic difference, and if nothing else, a property has a different semantic meaning and is far more flexible than a public field.
```
public string Name { get; set; }
public string name;
```
I do recall one time when first using .net I coded a few classes as just fields, and then I needed to have them as properties for some reason, and it was a complete waste of time when I could have just done it right the first time.
So what reasons do you have for *not* following convention? Why do you feel the need to swim upstream? What has it saved you by not doing this?
|
205,573 |
<p>I want to do something like this:</p>
<pre><code>List<Animal> animals = new ArrayList<Animal>();
for( Class c: list_of_all_classes_available_to_my_app() )
if (c is Animal)
animals.add( new c() );
</code></pre>
<p>So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. I can avoid the following:</p>
<pre><code>List<Animal> animals = new ArrayList<Animal>();
animals.add( new Dog() );
animals.add( new Cat() );
animals.add( new Donkey() );
...
</code></pre>
<p>With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically.</p>
<p>UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time:</p>
<p>This question has generated a lot of great responses -- thank you. <s>From the responses and my research, I've found that what I really want to do is just not possible under Java. There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file.</s> <strong>Update 5/10/19</strong> (11 years later!) There are now several libraries that can help with this according to @IvanNik's <a href="https://stackoverflow.com/a/9240969/9648">answer</a> <a href="https://github.com/ronmamo/reflections" rel="noreferrer">org.reflections</a> looks good. Also <a href="https://github.com/classgraph/classgraph" rel="noreferrer">ClassGraph</a> from @Luke Hutchison's <a href="https://stackoverflow.com/a/51625104/9648">answer</a> looks interesting. There are several more possibilities in the answers as well.</p>
<p>Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding. If I have to configure, I might as well just instantiate them in the Animal class anyway. I understand that because a Java program is just a loose federation of .class files that that's just the way it is.</p>
<p>Interestingly, it seems this is <a href="http://my.safaribooksonline.com/0596003390/csharpckbk-CHP-12-SECT-8" rel="noreferrer">fairly trivial</a> in C#.</p>
|
[
{
"answer_id": 205738,
"author": "thoroughly",
"author_id": 8943,
"author_profile": "https://Stackoverflow.com/users/8943",
"pm_score": 2,
"selected": false,
"text": "<p>Java dynamically loads classes, so your universe of classes would be only those that have already been loaded (and not yet unloaded). Perhaps you can do something with a custom class loader that could check the supertypes of each loaded class. I don't think there's an API to query the set of loaded classes.</p>\n"
},
{
"answer_id": 205903,
"author": "jonathan-stafford",
"author_id": 27587,
"author_profile": "https://Stackoverflow.com/users/27587",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately this isn't entirely possible as the ClassLoader won't tell you what classes are available. You can, however, get fairly close doing something like this:</p>\n\n<pre><code>for (String classpathEntry : System.getProperty(\"java.class.path\").split(System.getProperty(\"path.separator\"))) {\n if (classpathEntry.endsWith(\".jar\")) {\n File jar = new File(classpathEntry);\n\n JarInputStream is = new JarInputStream(new FileInputStream(jar));\n\n JarEntry entry;\n while( (entry = is.getNextJarEntry()) != null) {\n if(entry.getName().endsWith(\".class\")) {\n // Class.forName(entry.getName()) and check\n // for implementation of the interface\n }\n }\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> johnstok is correct (in the comments) that this only works for standalone Java applications, and won't work under an application server.</p>\n"
},
{
"answer_id": 205940,
"author": "pdeva",
"author_id": 14316,
"author_profile": "https://Stackoverflow.com/users/14316",
"pm_score": 0,
"selected": false,
"text": "<p>This is a tough problem and you will need to find out this information using static analysis, its not available easily at runtime.\nBasically get the classpath of your app and scan through the available classes and read the bytecode information of a class which class it inherits from. Note that a class Dog may not directly inherit from Animal but might inherit from Pet which is turn inherits from Animal,so you will need to keep track of that hierarchy.</p>\n"
},
{
"answer_id": 205989,
"author": "JohnnyLambada",
"author_id": 9648,
"author_profile": "https://Stackoverflow.com/users/9648",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks all who answered this question. </p>\n\n<p>It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass. </p>\n\n<pre><code>public abstract class Animal{\n private static Animal[] animals= null;\n public static Animal[] getAnimals(){\n if (animals==null){\n animals = new Animal[]{\n new Dog(),\n new Cat(),\n new Lion()\n };\n }\n return animals;\n }\n}\n</code></pre>\n\n<p>It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.</p>\n\n<p>I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.</p>\n\n<p>Thanks again!</p>\n"
},
{
"answer_id": 206083,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):</p>\n\n<pre><code>public class Dog extends Animal{\n\nstatic\n{\n Animal a = new Dog();\n //add a to the List\n}\n</code></pre>\n\n<p>It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.</p>\n"
},
{
"answer_id": 206488,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": 3,
"selected": false,
"text": "<p>Think about this from an aspect-oriented point of view; what you want to do, really, is know all the classes at runtime that HAVE extended the Animal class. (I think that's a slightly more accurate description of your problem than your title; otherwise, I don't think you have a runtime question.)</p>\n\n<p>So what I think you want is to create a constructor of your base class (Animal) which adds to your static array (I prefer ArrayLists, myself, but to each their own) the type of the current Class which is being instantiated.</p>\n\n<p>So, roughly;</p>\n\n<pre><code>public abstract class Animal\n {\n private static ArrayList<Class> instantiatedDerivedTypes;\n public Animal() {\n Class derivedClass = this.getClass();\n if (!instantiatedDerivedClass.contains(derivedClass)) {\n instantiatedDerivedClass.Add(derivedClass);\n }\n }\n</code></pre>\n\n<p>Of course, you'll need a static constructor on Animal to initialize instantiatedDerivedClass... I think this'll do what you probably want. Note that this is execution-path dependent; if you have a Dog class that derives from Animal that never gets invoked, you won't have it in your Animal Class list.</p>\n"
},
{
"answer_id": 206921,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 5,
"selected": false,
"text": "<p>The Java way to do what you want is to use the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html\" rel=\"noreferrer\">ServiceLoader</a> mechanism. </p>\n\n<p>Also many people roll their own by having a file in a well known classpath location (i.e. /META-INF/services/myplugin.properties) and then using <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResources-java.lang.String-\" rel=\"noreferrer\">ClassLoader.getResources()</a> to enumerate all files with this name from all jars. This allows each jar to export its own providers and you can instantiate them by reflection using Class.forName()</p>\n"
},
{
"answer_id": 5831880,
"author": "Adam Gent",
"author_id": 318174,
"author_profile": "https://Stackoverflow.com/users/318174",
"pm_score": 0,
"selected": false,
"text": "<p>I solved this problem pretty elegantly using Package Level Annotations and then making that annotation have as an argument a list of classes.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface/5831808#5831808\">Find Java classes implementing an interface</a></p>\n\n<p>Implementations just have to create a package-info.java and put the magic annotation in with the list of classes they want to support.</p>\n"
},
{
"answer_id": 9240969,
"author": "IvanNik",
"author_id": 1118996,
"author_profile": "https://Stackoverflow.com/users/1118996",
"pm_score": 8,
"selected": true,
"text": "<p>I use <a href=\"https://github.com/ronmamo/reflections\" rel=\"noreferrer\">org.reflections</a>:</p>\n\n<pre><code>Reflections reflections = new Reflections(\"com.mycompany\"); \nSet<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);\n</code></pre>\n\n<p>Another example:</p>\n\n<pre><code>public static void main(String[] args) throws IllegalAccessException, InstantiationException {\n Reflections reflections = new Reflections(\"java.util\");\n Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);\n for (Class<? extends List> aClass : classes) {\n System.out.println(aClass.getName());\n if(aClass == ArrayList.class) {\n List list = aClass.newInstance();\n list.add(\"test\");\n System.out.println(list.getClass().getName() + \": \" + list.size());\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20120607,
"author": "DJDaveMark",
"author_id": 344029,
"author_profile": "https://Stackoverflow.com/users/344029",
"pm_score": 2,
"selected": false,
"text": "<p>You could use <a href=\"http://grepcode.com/file/repo1.maven.org/maven2/net.sourceforge.stripes/stripes/1.5.7/net/sourceforge/stripes/util/ResolverUtil.java\" rel=\"nofollow\">ResolverUtil</a> (<a href=\"http://grepcode.com/file_/repo1.maven.org/maven2/net.sourceforge.stripes/stripes/1.5.7/net/sourceforge/stripes/util/ResolverUtil.java/?v=source\" rel=\"nofollow\">raw source</a>) from the <a href=\"http://www.stripesframework.org/\" rel=\"nofollow\">Stripes Framework</a><br />\nif you need something simple and quick without refactoring any existing code.</p>\n\n<p>Here's a simple example not having loaded any of the classes:</p>\n\n<pre><code>package test;\n\nimport java.util.Set;\nimport net.sourceforge.stripes.util.ResolverUtil;\n\npublic class BaseClassTest {\n public static void main(String[] args) throws Exception {\n ResolverUtil<Animal> resolver = new ResolverUtil<Animal>();\n resolver.findImplementations(Animal.class, \"test\");\n Set<Class<? extends Animal>> classes = resolver.getClasses();\n\n for (Class<? extends Animal> clazz : classes) {\n System.out.println(clazz);\n }\n }\n}\n\nclass Animal {}\nclass Dog extends Animal {}\nclass Cat extends Animal {}\nclass Donkey extends Animal {}\n</code></pre>\n\n<p>This also works in an application server as well since that's where it was designed to work ;)</p>\n\n<p>The code basically does the following:</p>\n\n<ul>\n<li>iterate over all the resources in the package(s) you specify</li>\n<li>keep only the resources ending in .class</li>\n<li>Load those classes using <code>ClassLoader#loadClass(String fullyQualifiedName)</code></li>\n<li>Checks if <code>Animal.class.isAssignableFrom(loadedClass);</code></li>\n</ul>\n"
},
{
"answer_id": 28424686,
"author": "Osman Shoukry",
"author_id": 634553,
"author_profile": "https://Stackoverflow.com/users/634553",
"pm_score": 1,
"selected": false,
"text": "<p>Using <a href=\"http://openpojo.com\" rel=\"nofollow\">OpenPojo</a> you can do the following:</p>\n\n<pre><code>String package = \"com.mycompany\";\nList<Animal> animals = new ArrayList<Animal>();\n\nfor(PojoClass pojoClass : PojoClassFactory.enumerateClassesByExtendingType(package, Animal.class, null) {\n animals.add((Animal) InstanceFactory.getInstance(pojoClass));\n}\n</code></pre>\n"
},
{
"answer_id": 49711316,
"author": "Ali Bagheri",
"author_id": 6893709,
"author_profile": "https://Stackoverflow.com/users/6893709",
"pm_score": 2,
"selected": false,
"text": "<p>use this</p>\n\n<pre><code>public static Set<Class> getExtendedClasses(Class superClass)\n{\n try\n {\n ResolverUtil resolver = new ResolverUtil();\n resolver.findImplementations(superClass, superClass.getPackage().getName());\n return resolver.getClasses(); \n }\n catch(Exception e)\n {Log.d(\"Log:\", \" Err: getExtendedClasses() \");}\n\n return null;\n}\n\ngetExtendedClasses(Animals.class);\n</code></pre>\n\n<p>Edit:</p>\n\n<ul>\n<li>library for (ResolverUtil) : <a href=\"http://www.java2s.com/Code/Jar/s/Downloadstripes155jar.htm\" rel=\"nofollow noreferrer\">Stripes</a></li>\n</ul>\n"
},
{
"answer_id": 51625104,
"author": "Luke Hutchison",
"author_id": 3950982,
"author_profile": "https://Stackoverflow.com/users/3950982",
"pm_score": 3,
"selected": false,
"text": "<p>The most robust mechanism for listing all subclasses of a given class is currently <a href=\"https://github.com/classgraph/classgraph/wiki/Code-examples\" rel=\"nofollow noreferrer\">ClassGraph</a>, because it handles the <a href=\"https://github.com/classgraph/classgraph/wiki/Classpath-Specification-Mechanisms\" rel=\"nofollow noreferrer\">widest possible array of classpath specification mechanisms</a>, including the new JPMS module system. (I am the author.)</p>\n\n<pre><code>List<Class<Animal>> animals;\ntry (ScanResult scanResult = new ClassGraph().whitelistPackages(\"com.zoo.animals\")\n .enableClassInfo().scan()) {\n animals = scanResult\n .getSubclasses(Animal.class.getName())\n .loadClasses(Animal.class);\n}\n</code></pre>\n"
},
{
"answer_id": 67374201,
"author": "AlexIsOK",
"author_id": 13945652,
"author_profile": "https://Stackoverflow.com/users/13945652",
"pm_score": 0,
"selected": false,
"text": "<p>Since directly using <code>newInstance()</code> is deprecated, you can do it this way using <a href=\"https://github.com/ronmamo/reflections\" rel=\"nofollow noreferrer\">Reflections</a>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>Reflections r = new Reflections("com.example.location.of.sub.classes")\nSet<Class<? extends Animal>> classes = r.getSubTypesOf(Animal.class);\n\nclasses.forEach(c -> {\n Animal a = c.getDeclaredConstructor().newInstance();\n //a is your instance of Animal.\n});\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648/"
] |
I want to do something like this:
```
List<Animal> animals = new ArrayList<Animal>();
for( Class c: list_of_all_classes_available_to_my_app() )
if (c is Animal)
animals.add( new c() );
```
So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. I can avoid the following:
```
List<Animal> animals = new ArrayList<Animal>();
animals.add( new Dog() );
animals.add( new Cat() );
animals.add( new Donkey() );
...
```
With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically.
UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time:
This question has generated a lot of great responses -- thank you. ~~From the responses and my research, I've found that what I really want to do is just not possible under Java. There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file.~~ **Update 5/10/19** (11 years later!) There are now several libraries that can help with this according to @IvanNik's [answer](https://stackoverflow.com/a/9240969/9648) [org.reflections](https://github.com/ronmamo/reflections) looks good. Also [ClassGraph](https://github.com/classgraph/classgraph) from @Luke Hutchison's [answer](https://stackoverflow.com/a/51625104/9648) looks interesting. There are several more possibilities in the answers as well.
Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding. If I have to configure, I might as well just instantiate them in the Animal class anyway. I understand that because a Java program is just a loose federation of .class files that that's just the way it is.
Interestingly, it seems this is [fairly trivial](http://my.safaribooksonline.com/0596003390/csharpckbk-CHP-12-SECT-8) in C#.
|
I use [org.reflections](https://github.com/ronmamo/reflections):
```
Reflections reflections = new Reflections("com.mycompany");
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);
```
Another example:
```
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Reflections reflections = new Reflections("java.util");
Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);
for (Class<? extends List> aClass : classes) {
System.out.println(aClass.getName());
if(aClass == ArrayList.class) {
List list = aClass.newInstance();
list.add("test");
System.out.println(list.getClass().getName() + ": " + list.size());
}
}
}
```
|
205,582 |
<p>The new ASP.NET routing is great for simple path style URL's but if you want to use a url such as:</p>
<p><a href="http://example.com/items/search.xhtml?term=Text+to+find&page=2" rel="nofollow noreferrer">http://example.com/items/search.xhtml?term=Text+to+find&page=2</a></p>
<p>Do you have to use a catch all parameter with a validation?</p>
|
[
{
"answer_id": 205620,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 2,
"selected": false,
"text": "<p>You can match querystring parameters with routes as well, if you want to just capture everything you need to add a parameter like so:</p>\n\n<p>{*contentUrl}</p>\n\n<p>Which will populate the rest of the url into that variable.</p>\n"
},
{
"answer_id": 207748,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": true,
"text": "<p>Any view data items that are not listed in the route are automatically mapped to the querystring, so if you map \"items/search.xhtml\" to an action:</p>\n\n<pre><code>Search(string term, int page)\n</code></pre>\n\n<p>Then you should get the results you are looking for.</p>\n"
},
{
"answer_id": 7725561,
"author": "George Filippakos",
"author_id": 961333,
"author_profile": "https://Stackoverflow.com/users/961333",
"pm_score": 0,
"selected": false,
"text": "<p>I was also having trouble passing an encoded URL to a route as a route parameter.</p>\n\n<p>You can't use url encoded chars in a URL, but you can in a query string.</p>\n\n<p>Therefore I needed my route to also have a query string element to it.</p>\n\n<p>Say I have a route:</p>\n\n<pre><code>MapPageRoute(\"myroute\", \"myroute/{x}\", \"~/routehander.aspx\")\n</code></pre>\n\n<p>But I want it in the form of:</p>\n\n<pre><code>http://mywebsite.com/myroute/{x}?url=myurl\n</code></pre>\n\n<p>We can do this:</p>\n\n<pre><code>Dim x as integer = 12\nDim rvd As New Routing.RouteValueDictionary\nrvd.Add(\"x\", x)\nrvd.Add(\"url\", Server.UrlEncode(\"/default.aspx\"))\nHttpContext.Current.ApplicationInstance.Response.RedirectToRoutePermanent(\"myroute\", rvd)\n</code></pre>\n\n<p>This would redirect us to the following url:</p>\n\n<pre><code>http://mywebsite.com/myroute/12?url=%252fdefault.aspx\n</code></pre>\n"
},
{
"answer_id": 9673676,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 0,
"selected": false,
"text": "<p>You can still use <code>Request.QueryString[\"some_value\"];</code></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16340/"
] |
The new ASP.NET routing is great for simple path style URL's but if you want to use a url such as:
<http://example.com/items/search.xhtml?term=Text+to+find&page=2>
Do you have to use a catch all parameter with a validation?
|
Any view data items that are not listed in the route are automatically mapped to the querystring, so if you map "items/search.xhtml" to an action:
```
Search(string term, int page)
```
Then you should get the results you are looking for.
|
205,583 |
<p>I need to reproduce a bug, and a guy from the other team has sent me a .mdf and .ldf files from his sql server 2005 instance. When I attach the database, all I get is empty tables, even though file is 2 mb large. The db contains 2 tables that have, among other thing, a varbinary(max) field. At the same time another database, which has no varbinaries in tables, is attached ok and data are in place. What could be possible reason why data became inaccessible?</p>
|
[
{
"answer_id": 205620,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 2,
"selected": false,
"text": "<p>You can match querystring parameters with routes as well, if you want to just capture everything you need to add a parameter like so:</p>\n\n<p>{*contentUrl}</p>\n\n<p>Which will populate the rest of the url into that variable.</p>\n"
},
{
"answer_id": 207748,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": true,
"text": "<p>Any view data items that are not listed in the route are automatically mapped to the querystring, so if you map \"items/search.xhtml\" to an action:</p>\n\n<pre><code>Search(string term, int page)\n</code></pre>\n\n<p>Then you should get the results you are looking for.</p>\n"
},
{
"answer_id": 7725561,
"author": "George Filippakos",
"author_id": 961333,
"author_profile": "https://Stackoverflow.com/users/961333",
"pm_score": 0,
"selected": false,
"text": "<p>I was also having trouble passing an encoded URL to a route as a route parameter.</p>\n\n<p>You can't use url encoded chars in a URL, but you can in a query string.</p>\n\n<p>Therefore I needed my route to also have a query string element to it.</p>\n\n<p>Say I have a route:</p>\n\n<pre><code>MapPageRoute(\"myroute\", \"myroute/{x}\", \"~/routehander.aspx\")\n</code></pre>\n\n<p>But I want it in the form of:</p>\n\n<pre><code>http://mywebsite.com/myroute/{x}?url=myurl\n</code></pre>\n\n<p>We can do this:</p>\n\n<pre><code>Dim x as integer = 12\nDim rvd As New Routing.RouteValueDictionary\nrvd.Add(\"x\", x)\nrvd.Add(\"url\", Server.UrlEncode(\"/default.aspx\"))\nHttpContext.Current.ApplicationInstance.Response.RedirectToRoutePermanent(\"myroute\", rvd)\n</code></pre>\n\n<p>This would redirect us to the following url:</p>\n\n<pre><code>http://mywebsite.com/myroute/12?url=%252fdefault.aspx\n</code></pre>\n"
},
{
"answer_id": 9673676,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 0,
"selected": false,
"text": "<p>You can still use <code>Request.QueryString[\"some_value\"];</code></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17481/"
] |
I need to reproduce a bug, and a guy from the other team has sent me a .mdf and .ldf files from his sql server 2005 instance. When I attach the database, all I get is empty tables, even though file is 2 mb large. The db contains 2 tables that have, among other thing, a varbinary(max) field. At the same time another database, which has no varbinaries in tables, is attached ok and data are in place. What could be possible reason why data became inaccessible?
|
Any view data items that are not listed in the route are automatically mapped to the querystring, so if you map "items/search.xhtml" to an action:
```
Search(string term, int page)
```
Then you should get the results you are looking for.
|
205,594 |
<p>I use Visual Studio's "Code Snippet" feature pretty heavily while editing c# code. I always wished I could use them while typing out my aspx markup. </p>
<p>Is there a way to enable code snippet use in an aspx file editor window?</p>
<p>Are there any third party tools that perform this?</p>
<p>If you're familiar with code snippet definitions, this is exactly the type of thing I want to do:</p>
<pre><code><asp:TextBox ID="$var$TextBox" Text="$text$" OnClick="$var$_Click" runat="server" />
</code></pre>
<p><em>I could activate the snippet, tab twice, and move on!</em></p>
|
[
{
"answer_id": 205622,
"author": "harriyott",
"author_id": 5744,
"author_profile": "https://Stackoverflow.com/users/5744",
"pm_score": 2,
"selected": false,
"text": "<p>That would be brilliant! I'd recommend the <a href=\"http://secretgeek.net/wscg.htm\" rel=\"nofollow noreferrer\">world's simplest code generato</a>r, or CodeSmith, or maybe <a href=\"http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx\" rel=\"nofollow noreferrer\">T4</a> (although I haven't tried it yet). Doesn't quite do what you'd like, but it does make it a little easier</p>\n"
},
{
"answer_id": 205640,
"author": "Rory Becker",
"author_id": 11356,
"author_profile": "https://Stackoverflow.com/users/11356",
"pm_score": 3,
"selected": true,
"text": "<p>Perhaps you might think of trying <a href=\"http://devexpress.com/coderush\" rel=\"nofollow noreferrer\">Coderush</a> which has a lot more to offer than the basic snippets found in VS. It's template facility can operate in vb, cs, aspx, html, xml and sql files.</p>\n"
},
{
"answer_id": 205687,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 0,
"selected": false,
"text": "<p>@Rory-Becker Coderush is exactly what I've been looking for!!</p>\n\n<p>I had previously posted that Coderush costs $99, but it costs $249.</p>\n\n<p>@harriyott </p>\n\n<p>Codesmith has something called Active Snippets. It only comes with the professional version, which costs $399</p>\n\n<p><a href=\"http://www.codesmithtools.com/features/comparison.aspx\" rel=\"nofollow noreferrer\">http://www.codesmithtools.com/features/comparison.aspx</a></p>\n"
},
{
"answer_id": 259820,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 1,
"selected": false,
"text": "<p>Since I can't afford the $249 for CodeRush, I started trying to build a VisualStudio Add-In. </p>\n\n<p>This guy has allready done this for me: <a href=\"http://ardentdev.com/blog/index.php/aspxedithelper\" rel=\"nofollow noreferrer\">http://ardentdev.com/blog/index.php/aspxedithelper</a></p>\n"
},
{
"answer_id": 259835,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 2,
"selected": false,
"text": "<p><strong>CodeRush Express</strong> is now <strong>free</strong>, you can download it from this <a href=\"http://devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/\" rel=\"nofollow noreferrer\">link</a></p>\n"
},
{
"answer_id": 264089,
"author": "Mehul",
"author_id": 10378,
"author_profile": "https://Stackoverflow.com/users/10378",
"pm_score": 2,
"selected": false,
"text": "<p>At PDC 2008, Jeff King from Microsoft showed a demo of the HTML Snippets feature coming out in the next Visual Studio 2010. However, I put in another vote for CodeRush which is more powerful and you can use it now.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/946/"
] |
I use Visual Studio's "Code Snippet" feature pretty heavily while editing c# code. I always wished I could use them while typing out my aspx markup.
Is there a way to enable code snippet use in an aspx file editor window?
Are there any third party tools that perform this?
If you're familiar with code snippet definitions, this is exactly the type of thing I want to do:
```
<asp:TextBox ID="$var$TextBox" Text="$text$" OnClick="$var$_Click" runat="server" />
```
*I could activate the snippet, tab twice, and move on!*
|
Perhaps you might think of trying [Coderush](http://devexpress.com/coderush) which has a lot more to offer than the basic snippets found in VS. It's template facility can operate in vb, cs, aspx, html, xml and sql files.
|
205,614 |
<p>My initial installation for the <strong>MySQL</strong> had no password for root. I assigned a password for root and everything worked fine. Due to some reason (don't ask why) I had to revert back to the original settings where root didn't have any password.</p>
<p>I changed the root password to <code>'' (empty string)</code>. The problem now is that MySQL doesn't run with <code>'mysql -uroot'</code>, it expects a password. On running <code>'mysql -uroot -p'</code> and hitting enter on the password prompt gets me into the db, but is not same as the default setting.</p>
<p>Is there any other flag/setting that I am missing to set/unset which tells mysql to not expect a password?</p>
<p>Thanks</p>
|
[
{
"answer_id": 205661,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": false,
"text": "<p><strong>How to Reset MySQL root password:</strong></p>\n\n<p>To reset it, see <a href=\"http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html\" rel=\"noreferrer\">How to Reset the Root Password</a> in the MySQL manual. </p>\n\n<p><strong>How to run MySQL without password controlled access</strong></p>\n\n<p>To run MySQL with the password controls disabled, check out the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_skip-grant-tables\" rel=\"noreferrer\">--skip-grant-tables</a> option.</p>\n\n<p><strong>How to avoid typing credentials on the command line</strong></p>\n\n<p>If you simply want to avoid having to type the password on the mysql command line, create a file called .my.cnf (note leading period on that filename!) in your home directory. In your case, for the root user, probably /root</p>\n\n<p>Add the following entries to the file</p>\n\n<pre><code>[client]\nhost=localhost\nuser = root\npassword = mypassword\ndatabase = mydatabase\n</code></pre>\n\n<p>You'd typically chmod 600 this file so that only you can see it, and MySQL will ignore a .my.cnf which is world writable anyway.</p>\n\n<p>See the manual page <a href=\"http://dev.mysql.com/doc/refman/5.0/en/option-files.html\" rel=\"noreferrer\">Using Option Files</a> for more information</p>\n"
},
{
"answer_id": 63053661,
"author": "Stevan Tosic",
"author_id": 6166504,
"author_profile": "https://Stackoverflow.com/users/6166504",
"pm_score": 0,
"selected": false,
"text": "<p>MySql improves security which is good in one hand.</p>\n<p>You can check this link for info on how to reset the password on multiple MySql versions.</p>\n<p><a href=\"https://www.digitalocean.com/community/tutorials/how-to-reset-your-mysql-or-mariadb-root-password\" rel=\"nofollow noreferrer\">https://www.digitalocean.com/community/tutorials/how-to-reset-your-mysql-or-mariadb-root-password</a></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13492/"
] |
My initial installation for the **MySQL** had no password for root. I assigned a password for root and everything worked fine. Due to some reason (don't ask why) I had to revert back to the original settings where root didn't have any password.
I changed the root password to `'' (empty string)`. The problem now is that MySQL doesn't run with `'mysql -uroot'`, it expects a password. On running `'mysql -uroot -p'` and hitting enter on the password prompt gets me into the db, but is not same as the default setting.
Is there any other flag/setting that I am missing to set/unset which tells mysql to not expect a password?
Thanks
|
**How to Reset MySQL root password:**
To reset it, see [How to Reset the Root Password](http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html) in the MySQL manual.
**How to run MySQL without password controlled access**
To run MySQL with the password controls disabled, check out the [--skip-grant-tables](http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_skip-grant-tables) option.
**How to avoid typing credentials on the command line**
If you simply want to avoid having to type the password on the mysql command line, create a file called .my.cnf (note leading period on that filename!) in your home directory. In your case, for the root user, probably /root
Add the following entries to the file
```
[client]
host=localhost
user = root
password = mypassword
database = mydatabase
```
You'd typically chmod 600 this file so that only you can see it, and MySQL will ignore a .my.cnf which is world writable anyway.
See the manual page [Using Option Files](http://dev.mysql.com/doc/refman/5.0/en/option-files.html) for more information
|
205,624 |
<p>I want to iterate through a contacts properties and add those that contain the word "Number" to a list with the value, i tries using reflection but it doesn't work.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Office.Interop.Outlook;
namespace DuplicateNumbers
{
public class ContactService
{
public ContactItem Contact { get; private set; }
private IDictionary<string,string> phoneNumbers = new Dictionary<string, string>();
public ContactService(ContactItem contact)
{
Contact = contact;
}
public IDictionary<string,string> PhoneNumbers
{
get
{
if(phoneNumbers.Count == 0)
{
PopulatePhoneNumbers();
}
return phoneNumbers;
}
}
private void PopulatePhoneNumbers()
{
_ContactItem ci = Contact as _ContactItem;
MemberInfo[] members = ci.GetType().FindMembers(MemberTypes.All, BindingFlags.Instance, (m,criteria) => true, null);
foreach (var info in members)
{
if(info.Name.Contains("Number"))
{
phoneNumbers.Add(info.Name,info.Value);
}
Console.WriteLine(info);
}
}
}
}
</code></pre>
|
[
{
"answer_id": 207432,
"author": "IgorM",
"author_id": 17823,
"author_profile": "https://Stackoverflow.com/users/17823",
"pm_score": 0,
"selected": false,
"text": "<p>Of cause it doesn't work - it's a COM object. You should use the properties from CDO space.</p>\n"
},
{
"answer_id": 231641,
"author": "Paige Watson",
"author_id": 30862,
"author_profile": "https://Stackoverflow.com/users/30862",
"pm_score": 1,
"selected": false,
"text": "<p>Try using MAPI CDO.</p>\n\n<p>Here's a microsoft site that might get you started: <a href=\"http://support.microsoft.com/default.aspx?scid=kb;EN-US;179083\" rel=\"nofollow noreferrer\">How to use CDO to read MAPI Addresses</a></p>\n\n<p>Here's some MAPI Blogs to help as well:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/stephen_griffin/\" rel=\"nofollow noreferrer\">Steven Griffin</a></li>\n<li><a href=\"http://blogs.msdn.com/mstehle/\" rel=\"nofollow noreferrer\">Matt Stehle</a></li>\n</ul>\n"
},
{
"answer_id": 59223844,
"author": "Sanjay Karia",
"author_id": 2204063,
"author_profile": "https://Stackoverflow.com/users/2204063",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to be able to access the Outlook.ContactItem properties.\n<a href=\"https://stackoverflow.com/questions/1323069/enumerating-outlook-contactitem-properties\">Enumerating Outlook ContactItem properties</a></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to iterate through a contacts properties and add those that contain the word "Number" to a list with the value, i tries using reflection but it doesn't work.
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Office.Interop.Outlook;
namespace DuplicateNumbers
{
public class ContactService
{
public ContactItem Contact { get; private set; }
private IDictionary<string,string> phoneNumbers = new Dictionary<string, string>();
public ContactService(ContactItem contact)
{
Contact = contact;
}
public IDictionary<string,string> PhoneNumbers
{
get
{
if(phoneNumbers.Count == 0)
{
PopulatePhoneNumbers();
}
return phoneNumbers;
}
}
private void PopulatePhoneNumbers()
{
_ContactItem ci = Contact as _ContactItem;
MemberInfo[] members = ci.GetType().FindMembers(MemberTypes.All, BindingFlags.Instance, (m,criteria) => true, null);
foreach (var info in members)
{
if(info.Name.Contains("Number"))
{
phoneNumbers.Add(info.Name,info.Value);
}
Console.WriteLine(info);
}
}
}
}
```
|
Try using MAPI CDO.
Here's a microsoft site that might get you started: [How to use CDO to read MAPI Addresses](http://support.microsoft.com/default.aspx?scid=kb;EN-US;179083)
Here's some MAPI Blogs to help as well:
* [Steven Griffin](http://blogs.msdn.com/stephen_griffin/)
* [Matt Stehle](http://blogs.msdn.com/mstehle/)
|
205,631 |
<p>i got a client side javascript function which is triggered on a button click (basically, its a calculator!!). Sometimes, due to enormous data on the page, the javascript calculator function take to long & makes the page appear inactive to the user. I was planning to display a transparent div over entire page, maybe with a busy indicator (in the center) till the calculator function ends, so that user waits till process ends. </p>
<pre>
function CalculateAmountOnClick() {
// Display transparent div
// MY time consuming loop!
{
}
// Remove transparent div
}
</pre>
<p>Any ideas on how to go about this? Should i assign a css class to a div (which surrounds my entire page's content) using javascript when my calculator function starts? I tried that but didnt get desired results. Was facing issues with transparency in IE 6. Also how will i show a loading message + image in such a transparent div?</p>
<p>TIA</p>
|
[
{
"answer_id": 205648,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 2,
"selected": false,
"text": "<p>I would do something like:</p>\n\n<ol>\n<li>unhide a div (<code>display:inline</code>)</li>\n<li>make the <code>position:absolute</code></li>\n<li>give it a <code>z-index:99</code></li>\n<li>make the height and width <code>100%</code></li>\n<li>when the processing is done set <code>display:none</code></li>\n</ol>\n\n<p>To make it transparent you'll have to set the opacity which is different in Firefox, IE, etc.</p>\n\n<p>To show a loading icon you can always create a second div and position it where you want to on the page. When it's done loading, remove it along with the transparent one.</p>\n"
},
{
"answer_id": 205685,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to all of the above, don't forget to put an invisible iframe behind the shim, so that it shows up above select boxes in IE.</p>\n\n<p>Edit:\nThis site, although it provides a solution to a more complex problem, does cover creating a modal background.\n<a href=\"http://www.codeproject.com/KB/aspnet/ModalDialogV2.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/ModalDialogV2.aspx</a></p>\n"
},
{
"answer_id": 205707,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 0,
"selected": false,
"text": "<p>For the loading message, I would use a <code><div></code> with <code>position:absolute</code>, position it using <code>left</code> and <code>top</code>, and set the display to <code>none</code>. </p>\n\n<p>When you want to show the loading indicator, you're going to have to use a timeout otherwise the <code>div</code> won't display until your processing is done. So, you should modify your code to this:</p>\n\n<pre><code>function showLoadingIndicator()\n{\n // Display div by setting display to 'inline'\n setTimeout(CalculateAmountOnClick,0);\n}\n\nfunction CalculateAmountOnClick()\n{\n // MY time consuming loop!\n {\n }\n // Remove transparent div \n}\n</code></pre>\n\n<p>Because you set the timeout, the page will redraw before the time-consuming loop happens.</p>\n"
},
{
"answer_id": 205758,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 5,
"selected": true,
"text": "<p>Javacript to show a curtain:</p>\n\n<pre><code>function CalculateAmountOnClick () {\n var curtain = document.body.appendChild( document.createElement('div') );\n curtain.id = \"curtain\";\n curtain.onkeypress = curtain.onclick = function(){ return false; }\n try {\n // your operations\n }\n finally {\n curtain.parentNode.removeChild( curtain );\n }\n}\n</code></pre>\n\n<p>Your CSS:</p>\n\n<pre><code>#curtain {\n position: fixed;\n _position: absolute;\n z-index: 99;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n _height: expression(document.body.offsetHeight + \"px\");\n background: url(curtain.png);\n _background: url(curtain.gif);\n}\n</code></pre>\n\n<p>(Move MSIE 6 underscore hacks to conditionally included files as desired.)</p>\n\n<p>You could set this up as add/remove functions for the curtain, or as a wrapper:</p>\n\n<pre><code>function modalProcess( callback ) {\n var ret;\n var curtain = document.body.appendChild( document.createElement('div') );\n curtain.id = \"curtain\";\n curtain.onkeypress = curtain.onclick = function(){ return false; }\n try {\n ret = callback();\n }\n finally {\n curtain.parentNode.removeChild( curtain );\n }\n return ret;\n}\n</code></pre>\n\n<p>Which you could then call like this:</p>\n\n<pre><code>var result = modalProcess(function(){\n // your operations here\n});\n</code></pre>\n"
},
{
"answer_id": 210931,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": false,
"text": "<p>I'm going to make some heavy assumptions here, but it sounds to me what is happening is that because you are directly locking the browser up with intense processing immediately after having set up the curtain element, the browser never has a chance to draw the curtain.</p>\n\n<p>The browser doesn't redraw every time you update the DOM. It may woit to see if you're doing something more, and then draw what is needed (browsers vary their method for this). So in this case it may be refreshing the display only after it has removed the curtain, or you have forced a redraw by scrolling.</p>\n\n<p>A fair waring: This kind of intense processing isn't very nice of you because it not only locks up your page. Because browsers generally implement only a single Javascript thread for ALL tabs, your processing will lock up all open tabs (= the browser). Also, you run the risk of the execution timeout and browser simply stopping your script (this can be as low as 5 seconds).</p>\n\n<p>Here is a way around that.</p>\n\n<p>If you can break your processing up into smaller chunks you could run it with a timeout (to allow the browser breathing space). Something like this should work:</p>\n\n<pre><code>function processLoop( actionFunc, numTimes, doneFunc ) {\n var i = 0;\n var f = function () {\n if (i < numTimes) {\n actionFunc( i++ ); // closure on i\n setTimeout( f, 10 )\n } \n else if (doneFunc) { \n doneFunc();\n }\n };\n f();\n}\n\n// add a curtain here\nprocessLoop(function (i){\n // loop code goes in here\n console.log('number: ', i);\n}, \n10, // how many times to run loop\nfunction (){\n // things that happen after the processing is done go here\n console.log('done!');\n // remove curtain here\n});\n</code></pre>\n\n<p>This is essentially a while loop but each iteration of the loop is done in an timed interval so the browser has a bit of time to breathe in between. It will slow down the processing though, and any work done afterwards needs to go into a callback as the loop runs independently of whatwever may follow the call to processLoop.</p>\n\n<p>Another variation on this is to set up the curtain, call your processing function with a setTimeout to allow the browser time to draw the curtain, and then remove it once you're done.</p>\n\n<pre><code>// add a curtain\nvar curtain = document.body.appendChild( document.createElement('div') );\ncurtain.id = \"curtain\";\ncurtain.onkeypress = curtain.onclick = function(){ return false; }\n// delay running processing\nsetTimeout(function(){\n try {\n // here we go...\n myHeavyProcessingFunction();\n }\n finally {\n // remove the curtain\n curtain.parentNode.removeChild( curtain );\n }\n}, 40);\n</code></pre>\n\n<p>If you are using a js-library, you may want to look at a ready made solution for creating curtains. These should exist for most libraries, <a href=\"http://www.malsup.com/jquery/block/\" rel=\"noreferrer\">here is one for jQuery</a>, and they can help with the CSS.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28321/"
] |
i got a client side javascript function which is triggered on a button click (basically, its a calculator!!). Sometimes, due to enormous data on the page, the javascript calculator function take to long & makes the page appear inactive to the user. I was planning to display a transparent div over entire page, maybe with a busy indicator (in the center) till the calculator function ends, so that user waits till process ends.
```
function CalculateAmountOnClick() {
// Display transparent div
// MY time consuming loop!
{
}
// Remove transparent div
}
```
Any ideas on how to go about this? Should i assign a css class to a div (which surrounds my entire page's content) using javascript when my calculator function starts? I tried that but didnt get desired results. Was facing issues with transparency in IE 6. Also how will i show a loading message + image in such a transparent div?
TIA
|
Javacript to show a curtain:
```
function CalculateAmountOnClick () {
var curtain = document.body.appendChild( document.createElement('div') );
curtain.id = "curtain";
curtain.onkeypress = curtain.onclick = function(){ return false; }
try {
// your operations
}
finally {
curtain.parentNode.removeChild( curtain );
}
}
```
Your CSS:
```
#curtain {
position: fixed;
_position: absolute;
z-index: 99;
left: 0;
top: 0;
width: 100%;
height: 100%;
_height: expression(document.body.offsetHeight + "px");
background: url(curtain.png);
_background: url(curtain.gif);
}
```
(Move MSIE 6 underscore hacks to conditionally included files as desired.)
You could set this up as add/remove functions for the curtain, or as a wrapper:
```
function modalProcess( callback ) {
var ret;
var curtain = document.body.appendChild( document.createElement('div') );
curtain.id = "curtain";
curtain.onkeypress = curtain.onclick = function(){ return false; }
try {
ret = callback();
}
finally {
curtain.parentNode.removeChild( curtain );
}
return ret;
}
```
Which you could then call like this:
```
var result = modalProcess(function(){
// your operations here
});
```
|
205,644 |
<p>I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error: </p>
<pre><code>Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'
</code></pre>
<p>When using this simple code:</p>
<pre><code>public static class StringUtils {
static void TestExtension(this String targetString) {
}
}
</code></pre>
<p>The only way to make this compile error go away is to add the following code:</p>
<pre><code>namespace System.Runtime.CompilerServices {
public class ExtensionAttribute : Attribute { }
}
</code></pre>
<p>It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?</p>
|
[
{
"answer_id": 205663,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "<p>Your framework isn't high enough for Extension Methods.<br>\nThat's a <a href=\"http://blogs.msdn.com/jaredpar/archive/2007/11/16/extension-methods-without-3-5-framework.aspx\" rel=\"noreferrer\">hack</a> for making extension methods work without being in 3.5</p>\n"
},
{
"answer_id": 205664,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>What version of .NET are you targetting? The ExtensionAttribute class is shipped in System.Core.dll (.NET 3.5), but you can re-declare it yourself if you want to use extension methods in .NET 2.0/3.0 (with C# 3.0, obviously). In fact, <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"nofollow noreferrer\">LINQBridge</a> does this.</p>\n\n<p>[update] However, I'm slightly confused, because the error you <em>should</em> see is:</p>\n\n<blockquote>\n <p>Error 1 Cannot define a new extension\n method because the compiler required\n type\n 'System.Runtime.CompilerServices.ExtensionAttribute'\n cannot be found. Are you missing a\n reference to\n System.Core.dll? [snipped some path stuff]</p>\n</blockquote>\n"
},
{
"answer_id": 205671,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 0,
"selected": false,
"text": "<p>Extensions are introduced in C# 3.0, which on the other hand was introduced in .NET 3.5 so you can't really use them in .NET 3.0 directly.</p>\n"
},
{
"answer_id": 205717,
"author": "Gabriel Isenberg",
"author_id": 1473493,
"author_profile": "https://Stackoverflow.com/users/1473493",
"pm_score": 0,
"selected": false,
"text": "<p>Is this a web site project, by chance? Try changing the target framework from .NET 3.5 to an earlier version, and then back to .NET 3.5.</p>\n"
},
{
"answer_id": 206657,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 2,
"selected": false,
"text": "<p>A missing System.Core reference will give these symptoms.</p>\n"
},
{
"answer_id": 338452,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 5,
"selected": true,
"text": "<p>I just ran into this problem myself.\nIn my case, it was because I converted a VS 2005/.Net 2.0 project to a VS 2008/.Net 3.5 project. The conversion tool kept references to System.Core 2.0, and I couldn't find an easy way to change the references to System.Core 3.5.</p>\n\n<p>I ended up re-creating the project in VS 2008 from scratch, and it was created with proper references to System.Core 3.5</p>\n"
},
{
"answer_id": 383517,
"author": "Michael Buen",
"author_id": 11432,
"author_profile": "https://Stackoverflow.com/users/11432",
"pm_score": 4,
"selected": false,
"text": "<p>in VS, click Project (next to File,Edit,View), select Properties</p>\n\n<p>then in Application tab (you'll notice you're already in 3.5), select the Target Framework to 2.0, then compile (it will error). then put it back again to 3.5, then compile again, the error will disappear</p>\n\n<p>i think it is just a small glitch in Visual Studio, just fool the IDE :-)</p>\n"
},
{
"answer_id": 393003,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try: Project, Add Reference, find System Core 3.5.0.0 in the list, and OK to add it.</p>\n"
},
{
"answer_id": 577527,
"author": "lexx",
"author_id": 67014,
"author_profile": "https://Stackoverflow.com/users/67014",
"pm_score": 1,
"selected": false,
"text": "<p>This problem is indeed caused by an incorrect reference to version 2 of System.Core . This is normally caused when upgrading from an earlier version of .NET to .NET 3.5 . If it is a website that you are experiencing this problem in then it can be remedied by following the steps below:</p>\n\n<p>1) In web.config add a reference to System.Core v3.5:</p>\n\n<pre><code><assemblies>\n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n</assemblies>\n</code></pre>\n\n<p>2) In web.config add the following as a child of configuration:</p>\n\n<pre><code><configuration>\n <!--Some other config-->\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"System.Core\" publicKeyToken=\"B77A5C561934E089\"/>\n <bindingRedirect oldVersion=\"2.0.0.0-2.1.0.0\" newVersion=\"3.5.0.0\"/>\n </dependentAssembly>\n </assemblyBinding>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 2078904,
"author": "Andrew Myhre",
"author_id": 5152,
"author_profile": "https://Stackoverflow.com/users/5152",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same issue in a class library project that I had upgraded from VS 2008 to VS 2010 Beta 2. I hadn't added any extension methods to the project until after the upgrade, then I started seeing the same error.</p>\n\n<p>Adding a class with the following code to the project solved the problem:</p>\n\n<pre><code>namespace System.Runtime.CompilerServices\n{\n public class ExtensionAttribute : Attribute { }\n}\n</code></pre>\n\n<p>Found the tip on this blog: <a href=\"http://blog.flexforcefive.com/?p=105\" rel=\"noreferrer\">http://blog.flexforcefive.com/?p=105</a></p>\n"
},
{
"answer_id": 2179515,
"author": "7wp",
"author_id": 66803,
"author_profile": "https://Stackoverflow.com/users/66803",
"pm_score": 6,
"selected": false,
"text": "<p>I have the exact same problem. The error <code>System.Runtime.CompilerServices.ExtensionAttribute..ctor</code> is rather cryptic, and could mean a number of different things.</p>\n\n<p>However, for me It boiled down to the fact that I'm using <code>Newtonsoft.Json.Net</code>. I removed the reference to the file <code>Newtonsoft.Json.Net20.dll</code>, and the re-added it. After this my solution builds again.</p>\n\n<p>The strangest thing is that when I tried to find out what was different after this procedure by using Subversion Diff, nothing appears to have changed.</p>\n\n<p>So I really don't know what removing and re-adding this reference really does, but it does fix my build issue with this particular error message mentioned by the asker.</p>\n\n<h2><em>UPDATE 1</em>:</h2>\n\n<p>For those that come across this again, as the comenters pointed out, the proper way to fix this is to <em><a href=\"http://json.codeplex.com/releases/view/50552\" rel=\"nofollow noreferrer\">Download Json.Net's ZIP</a>, and there should be a 3.5 version, re-reference 3.5 every where you are using Json.Net and delete the old reference, as it is likely referencing an assembly that was built for older versions of .net.</em></p>\n\n<h2><em>UPDATE 2</em>:</h2>\n\n<p><a href=\"https://stackoverflow.com/users/80112/charlie-flowers\">Charlie Flowers</a> points out that the DLL NewtonSoft labels as being for 3.5 is actually not going to work with 3.5. You have to use the DLL they label as being for .net 2.0</p>\n"
},
{
"answer_id": 5547334,
"author": "Hash",
"author_id": 52743,
"author_profile": "https://Stackoverflow.com/users/52743",
"pm_score": 0,
"selected": false,
"text": "<p>Just target your VS project to .NET framework 3.5 and above. Most probably you converted your project from a previous version.</p>\n"
},
{
"answer_id": 13157077,
"author": "Gais",
"author_id": 102781,
"author_profile": "https://Stackoverflow.com/users/102781",
"pm_score": 0,
"selected": false,
"text": "<p>I had a version of Elmah.Sandbox that was targetting .net 2.0 in an existing .Net 4.0 project. I added an extension method to my project and the build failed with the \"Missing compiler required member\" error message.</p>\n\n<p>The Elmah.Sandbox dll was included as part of an early version of ElmahR. Once this was removed, it all built again.</p>\n"
},
{
"answer_id": 25815602,
"author": "DJGray",
"author_id": 1243040,
"author_profile": "https://Stackoverflow.com/users/1243040",
"pm_score": 2,
"selected": false,
"text": "<p>For ongoing reference:</p>\n\n<p>I have battled this exact same error message for the last two hours in the .Net 4.0 framework and finally tracked it down to a corrupted reference to the Microsoft.CSharp dll. It was such a frustratingly simple issue. I deleted the offending reference and added a \"new\" reference to that dll which was located at:</p>\n\n<pre><code>C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\Microsoft.CSharp.dll\n</code></pre>\n\n<p>Hopefully this will save someone else the time and aggravation of tracking down a solution to this error message.</p>\n"
},
{
"answer_id": 33926602,
"author": "Denis",
"author_id": 758815,
"author_profile": "https://Stackoverflow.com/users/758815",
"pm_score": 0,
"selected": false,
"text": "<p>In my case the reason was the wrong NET20 version of Microsoft's AntiXSSLibrary.dll. Replaced with NET35 - the error is gone.</p>\n"
},
{
"answer_id": 36422244,
"author": "Elya Livshitz",
"author_id": 802848,
"author_profile": "https://Stackoverflow.com/users/802848",
"pm_score": 0,
"selected": false,
"text": "<p>Edit your csproj and make sure those references are included (it wont work by simple 'add reference'...):</p>\n\n<pre><code><Reference Include=\"System\" />\n<Reference Include=\"System.Core\" />\n<Reference Include=\"System.Xml.Linq\" />\n<Reference Include=\"System.Data.DataSetExtensions\" />\n<Reference Include=\"Microsoft.CSharp\" />\n<Reference Include=\"System.Data\" />\n<Reference Include=\"System.Net.Http\" />\n<Reference Include=\"System.Xml\" />\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902/"
] |
I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error:
```
Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'
```
When using this simple code:
```
public static class StringUtils {
static void TestExtension(this String targetString) {
}
}
```
The only way to make this compile error go away is to add the following code:
```
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute : Attribute { }
}
```
It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?
|
I just ran into this problem myself.
In my case, it was because I converted a VS 2005/.Net 2.0 project to a VS 2008/.Net 3.5 project. The conversion tool kept references to System.Core 2.0, and I couldn't find an easy way to change the references to System.Core 3.5.
I ended up re-creating the project in VS 2008 from scratch, and it was created with proper references to System.Core 3.5
|
205,660 |
<p>It seems that Groovy does not support <code>break</code> and <code>continue</code> from within a closure. What is the best way to simulate this?</p>
<pre><code>revs.eachLine { line ->
if (line ==~ /-{28}/) {
// continue to next line...
}
}
</code></pre>
|
[
{
"answer_id": 205764,
"author": "shemnon",
"author_id": 8020,
"author_profile": "https://Stackoverflow.com/users/8020",
"pm_score": 7,
"selected": true,
"text": "<p>You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --</p>\n\n<p>Best approach (assuming you don't need the resulting value).</p>\n\n<pre><code>revs.eachLine { line -> \n if (line ==~ /-{28}/) {\n return // returns from the closure\n }\n}\n</code></pre>\n\n<p>If your sample really is that simple, this is good for readability.</p>\n\n<pre><code>revs.eachLine { line -> \n if (!(line ==~ /-{28}/)) {\n // do what you would normally do\n }\n}\n</code></pre>\n\n<p>another option, simulates what a continue would normally do at a bytecode level.</p>\n\n<pre><code>revs.eachLine { line -> \n while (true) {\n if (line ==~ /-{28}/) {\n break\n }\n // rest of normal code\n break\n }\n\n}\n</code></pre>\n\n<p>One possible way to support break is via exceptions:</p>\n\n<pre><code>try {\n revs.eachLine { line -> \n if (line ==~ /-{28}/) {\n throw new Exception(\"Break\")\n }\n }\n} catch (Exception e) { } // just drop the exception\n</code></pre>\n\n<p>You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.</p>\n"
},
{
"answer_id": 214443,
"author": "Cliff",
"author_id": 10631,
"author_profile": "https://Stackoverflow.com/users/10631",
"pm_score": 4,
"selected": false,
"text": "<p>Closures cannot break or continue because they are not loop/iteration constructs. Instead they are tools used to process/interpret/handle iterative logic. You can ignore given iterations by simply returning from the closure without processing as in:</p>\n\n<pre><code>revs.eachLine { line -> \n if (line ==~ /-{28}/) {\n return\n }\n\n}\n</code></pre>\n\n<p>Break support does not happen at the closure level but instead is implied by the semantics of the method call accepted the closure. In short that means instead of calling \"each\" on something like a collection which is intended to process the entire collection you should call find which will process until a certain condition is met. Most (all?) times you feel the need to break from a closure what you really want to do is find a specific condition during your iteration which makes the find method match not only your logical needs but also your intention. Sadly some of the API lack support for a find method... File for example. It's possible that all the time spent arguing wether the language should include break/continue could have been well spent adding the find method to these neglected areas. Something like firstDirMatching(Closure c) or findLineMatching(Closure c) would go a long way and answer 99+% of the \"why can't I break from...?\" questions that pop up in the mailing lists. That said, it is trivial to add these methods yourself via MetaClass or Categories.</p>\n\n<pre><code>class FileSupport {\n public static String findLineMatching(File f, Closure c) {\n f.withInputStream {\n def r = new BufferedReader(new InputStreamReader(it))\n for(def l = r.readLine(); null!=l; l = r.readLine())\n if(c.call(l)) return l\n return null\n }\n }\n}\n\nusing(FileSupport) { new File(\"/home/me/some.txt\").findLineMatching { line ==~ /-{28}/ }\n</code></pre>\n\n<p>Other hacks involving exceptions and other magic may work but introduce extra overhead in some situations and convolute the readability in others. The true answer is to look at your code and ask if you are truly iterating or searching instead.</p>\n"
},
{
"answer_id": 2897895,
"author": "Ralph",
"author_id": 96233,
"author_profile": "https://Stackoverflow.com/users/96233",
"pm_score": 4,
"selected": false,
"text": "<p>If you pre-create a static Exception object in Java and then throw the (static) exception from inside a closure, the run-time cost is minimal. The real cost is incurred in creating the exception, not in throwing it. According to Martin Odersky (inventor of Scala), many JVMs can actually optimize throw instructions to single jumps.</p>\n\n<p>This can be used to simulate a break:</p>\n\n<pre><code>final static BREAK = new Exception();\n//...\ntry {\n ... { throw BREAK; }\n} catch (Exception ex) { /* ignored */ }\n</code></pre>\n"
},
{
"answer_id": 9882399,
"author": "0rt",
"author_id": 1294411,
"author_profile": "https://Stackoverflow.com/users/1294411",
"pm_score": 2,
"selected": false,
"text": "<p>In this case, you should probably think of the <code>find()</code> method. It stops after the first time the closure passed to it return true.</p>\n"
},
{
"answer_id": 19413873,
"author": "Michal Zmuda",
"author_id": 1113929,
"author_profile": "https://Stackoverflow.com/users/1113929",
"pm_score": 3,
"selected": false,
"text": "<p>Use <strong>return</strong> to <em>continue</em> and <strong>any</strong> closure to <em>break</em>. </p>\n\n<p><strong>Example</strong></p>\n\n<p>File content:</p>\n\n<pre><code>1\n2\n----------------------------\n3\n4\n5\n</code></pre>\n\n<p>Groovy code:</p>\n\n<pre><code>new FileReader('myfile.txt').any { line ->\n if (line =~ /-+/)\n return // continue\n\n println line\n\n if (line == \"3\")\n true // break\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1\n2\n3\n</code></pre>\n"
},
{
"answer_id": 30592478,
"author": "frhack",
"author_id": 3360759,
"author_profile": "https://Stackoverflow.com/users/3360759",
"pm_score": 2,
"selected": false,
"text": "<p>With <a href=\"https://github.com/ReactiveX/RxJava\" rel=\"nofollow\">rx-java</a> you can transform an iterable in to an observable.</p>\n\n<p>Then you can replace <em>continue</em> with a <em>filter</em> and <em>break</em> with <em>takeWhile</em></p>\n\n<p>Here is an example:</p>\n\n<pre><code>import rx.Observable\n\nObservable.from(1..100000000000000000)\n .filter { it % 2 != 1} \n .takeWhile { it<10 } \n .forEach {println it}\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20103/"
] |
It seems that Groovy does not support `break` and `continue` from within a closure. What is the best way to simulate this?
```
revs.eachLine { line ->
if (line ==~ /-{28}/) {
// continue to next line...
}
}
```
|
You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --
Best approach (assuming you don't need the resulting value).
```
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return // returns from the closure
}
}
```
If your sample really is that simple, this is good for readability.
```
revs.eachLine { line ->
if (!(line ==~ /-{28}/)) {
// do what you would normally do
}
}
```
another option, simulates what a continue would normally do at a bytecode level.
```
revs.eachLine { line ->
while (true) {
if (line ==~ /-{28}/) {
break
}
// rest of normal code
break
}
}
```
One possible way to support break is via exceptions:
```
try {
revs.eachLine { line ->
if (line ==~ /-{28}/) {
throw new Exception("Break")
}
}
} catch (Exception e) { } // just drop the exception
```
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.
|
205,666 |
<p>I have an alert script that I am trying to keep from spamming me so I'd like to place a condition that if an alert has been sent within, say the last hour, to not send another alert. Now I have a cron job that checks the condition every minute because I need to be alerted quickly when the condition is met but I don't need to get the email every munite until I get the issue under control. What is the best way to compare time in bash to accomplish this?</p>
|
[
{
"answer_id": 205681,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": false,
"text": "<p>Use \"test\":</p>\n\n<pre><code>if test file1 -nt file2; then\n # file1 is newer than file2\nfi\n</code></pre>\n\n<p>EDIT: If you want to know when an event occurred, you can use \"touch\" to create a file which you can later compare using \"test\".</p>\n"
},
{
"answer_id": 205694,
"author": "jonathan-stafford",
"author_id": 27587,
"author_profile": "https://Stackoverflow.com/users/27587",
"pm_score": 4,
"selected": false,
"text": "<p>Use the date command to convert the two times into a standard format, and subtract them. You'll probably want to store the previous execution time in a dotfile then do something like:</p>\n\n<pre><code>last = cat /tmp/.lastrun\ncurr = date '+%s'\n\ndiff = $(($curr - $last))\nif [ $diff -gt 3600 ]; then\n # ...\nfi\n\necho \"$curr\" >/tmp/.lastrun\n</code></pre>\n\n<p>(Thanks, Steve.)</p>\n"
},
{
"answer_id": 205710,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 7,
"selected": true,
"text": "<p>By far the easiest is to store time stamps as modification times of dummy files. GNU <code>touch</code> and <code>date</code> commands can set/get these times and perform date calculations. Bash has tests to check whether a file is newer than (<code>-nt</code>) or older than (<code>-ot</code>) another.</p>\n\n<p>For example, to only send a notification if the last notification was more than an hour ago:</p>\n\n<pre><code>touch -d '-1 hour' limit\nif [ limit -nt last_notification ]; then\n #send notification...\n touch last_notification\nfi\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27247/"
] |
I have an alert script that I am trying to keep from spamming me so I'd like to place a condition that if an alert has been sent within, say the last hour, to not send another alert. Now I have a cron job that checks the condition every minute because I need to be alerted quickly when the condition is met but I don't need to get the email every munite until I get the issue under control. What is the best way to compare time in bash to accomplish this?
|
By far the easiest is to store time stamps as modification times of dummy files. GNU `touch` and `date` commands can set/get these times and perform date calculations. Bash has tests to check whether a file is newer than (`-nt`) or older than (`-ot`) another.
For example, to only send a notification if the last notification was more than an hour ago:
```
touch -d '-1 hour' limit
if [ limit -nt last_notification ]; then
#send notification...
touch last_notification
fi
```
|
205,668 |
<p>I'm copying a file from folder A to folder B and then trying to copy the file permissions. Here are the basic steps I'm using:</p>
<ol>
<li>CopyFile(source, target)</li>
<li>GetNamedSecurityInfo(source, GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)</li>
<li>Print source SD using ConvertSecurityDescriptorToStringSecurityDescriptor</li>
<li>SetNamedSecurityInfo(target, GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)</li>
<li>GetNamedSecurityInfo(target, GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)</li>
<li>Print target SD using ConvertSecurityDescriptorToStringSecurityDescriptor</li>
</ol>
<p>At #3 I get this SD:</p>
<pre><code>G:S-1-5-21-1454471165-1482476501-839522115-513D:AI(A;ID;0x1200a9;;;BU)(A;ID;0x1301bf;;;PU)(A;ID;FA;;;BA)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-1454471165-1482476501-839522115-1004)
</code></pre>
<p>At #6 I get</p>
<pre><code>G:S-1-5-21-1454471165-1482476501-839522115-513D:AI(A;ID;0x1301bf;;;PU)(A;ID;FA;;;BA)(A;ID;FA;;;SY)
</code></pre>
<p>The call to SetNamedSecurityInfo returns ERROR_SUCCESS, yet the results are the source and target file do not have the same SDs. Why is that? What am I doing wrong here?</p>
|
[
{
"answer_id": 206671,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 3,
"selected": true,
"text": "<p><code>SHFileOperation</code> can copy files together with their security attributes, but from <a href=\"https://stackoverflow.com/questions/202031/using-shfileoperation-within-a-windows-service\">your other question</a> I see you're concerned that this won't work within a service. Maybe the following newsgroup discussions will provide some useful information for you:</p>\n\n<ul>\n<li><a href=\"http://groups.google.com/group/microsoft.public.platformsdk.security/browse_frm/thread/c0e839addce84150/6a65cec096b4c8ba\" rel=\"nofollow noreferrer\">Copy NTFS files with security</a></li>\n<li><a href=\"http://groups.google.com/group/comp.os.ms-windows.programmer.win32/browse_frm/thread/1687df9d37d7a11c/4debcf8b3cbdf74c\" rel=\"nofollow noreferrer\">How to copy a disk file or directory with ALL attributes?</a></li>\n<li><a href=\"http://groups.google.com/group/comp.os.ms-windows.programmer.win32/browse_frm/thread/451f58b056686c64/9bfdd6f16bca0af3\" rel=\"nofollow noreferrer\">Copying files with security attributes</a></li>\n</ul>\n"
},
{
"answer_id": 206851,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "<p>Robocopy from the server tools kit <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en</a><br>\nWill copy all NTFS settigs and ACLs, it's also more robust and reliable than copy/xcopy</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24898/"
] |
I'm copying a file from folder A to folder B and then trying to copy the file permissions. Here are the basic steps I'm using:
1. CopyFile(source, target)
2. GetNamedSecurityInfo(source, GROUP\_SECURITY\_INFORMATION | DACL\_SECURITY\_INFORMATION)
3. Print source SD using ConvertSecurityDescriptorToStringSecurityDescriptor
4. SetNamedSecurityInfo(target, GROUP\_SECURITY\_INFORMATION | DACL\_SECURITY\_INFORMATION)
5. GetNamedSecurityInfo(target, GROUP\_SECURITY\_INFORMATION | DACL\_SECURITY\_INFORMATION)
6. Print target SD using ConvertSecurityDescriptorToStringSecurityDescriptor
At #3 I get this SD:
```
G:S-1-5-21-1454471165-1482476501-839522115-513D:AI(A;ID;0x1200a9;;;BU)(A;ID;0x1301bf;;;PU)(A;ID;FA;;;BA)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-1454471165-1482476501-839522115-1004)
```
At #6 I get
```
G:S-1-5-21-1454471165-1482476501-839522115-513D:AI(A;ID;0x1301bf;;;PU)(A;ID;FA;;;BA)(A;ID;FA;;;SY)
```
The call to SetNamedSecurityInfo returns ERROR\_SUCCESS, yet the results are the source and target file do not have the same SDs. Why is that? What am I doing wrong here?
|
`SHFileOperation` can copy files together with their security attributes, but from [your other question](https://stackoverflow.com/questions/202031/using-shfileoperation-within-a-windows-service) I see you're concerned that this won't work within a service. Maybe the following newsgroup discussions will provide some useful information for you:
* [Copy NTFS files with security](http://groups.google.com/group/microsoft.public.platformsdk.security/browse_frm/thread/c0e839addce84150/6a65cec096b4c8ba)
* [How to copy a disk file or directory with ALL attributes?](http://groups.google.com/group/comp.os.ms-windows.programmer.win32/browse_frm/thread/1687df9d37d7a11c/4debcf8b3cbdf74c)
* [Copying files with security attributes](http://groups.google.com/group/comp.os.ms-windows.programmer.win32/browse_frm/thread/451f58b056686c64/9bfdd6f16bca0af3)
|
205,688 |
<p>What is the best technique for catching ALL exceptions thrown within JavaScript?</p>
<p>Obviously, the best technique is to use try...catch. But with ansynchronous callbacks and so forth, that can get tricky.</p>
<p>I know IE and Gecko browsers support window.onerror, but what about Opera and Safari?</p>
<p>Here are a bunch of test-cases that I would like to have a central exception handling solution for:</p>
<pre><code>// ErrorHandler-Test1
var test = null;
test.arg = 5;
// ErrorHandler-Test2
throw (new Error("Hello"));
// ErrorHandler-Test3
throw "Hello again";
// ErrorHandler-Test4
throw {
myMessage: "stuff",
customProperty: 5,
anArray: [1, 2, 3]
};
// ErrorHandler-Test5
try {
var test2 = null;
test2.arg = 5;
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test6
try {
throw (new Error("Goodbye"));
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test7
try {
throw "Goodbye again";
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test8
try {
throw {
myMessage: "stuff",
customProperty: 5,
anArray: [1, 2, 3]
};
} catch(e) {
ErrorHandler.handleError(e);
}
</code></pre>
<p>If you think of any other test-cases, please mention them. Several of these cases mention a ErrorHandler.handleError method. This is just a suggested guideline when using try...catch.</p>
|
[
{
"answer_id": 205884,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 4,
"selected": false,
"text": "<p>WebKit (Safari, Chrome, etc) now appears to support <code>onerror</code>.</p>\n\n<p>Original post: As far as I know, WebKit/Safari does not support the <code>onerror</code> event. Which is a damn shame.</p>\n"
},
{
"answer_id": 205982,
"author": "Karl",
"author_id": 2932,
"author_profile": "https://Stackoverflow.com/users/2932",
"pm_score": 5,
"selected": false,
"text": "<p>If you use a library like <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a> for assigning all your event handlers, you can use a combination of <code>window.onerror</code> and wrapping the jQuery event handler code and on ready function with an error handling function (see: <a href=\"http://blogs.cozi.com/tech/2008/04/javascript-error-tracking-why-windowonerror-is-not-enough.html\" rel=\"noreferrer\">JavaScript Error Tracking: Why window.onerror Is Not Enough</a>).</p>\n\n<ul>\n<li><code>window.onerror</code>: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.</li>\n<li>jQuery event handlers: catches jQuery event errors in all browsers.</li>\n<li>jQuery ready function: catches initialisation errors in all browsers.</li>\n</ul>\n"
},
{
"answer_id": 471851,
"author": "adamfisk",
"author_id": 426961,
"author_profile": "https://Stackoverflow.com/users/426961",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, the jquery approach isn't so bad. See:</p>\n\n<p><a href=\"http://docs.jquery.com/Events/error#fn\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events/error#fn</a></p>\n\n<p>and:</p>\n\n<pre><code>$(window).error(function(msg, url, line){\n $.post(\"js_error_log.php\", { msg: msg, url: url, line: line });\n});\n</code></pre>\n"
},
{
"answer_id": 4376524,
"author": "wolfgang",
"author_id": 533639,
"author_profile": "https://Stackoverflow.com/users/533639",
"pm_score": 2,
"selected": false,
"text": "<p><code>try-catch</code> is not always the best solution. For example, in Chrome 7.0 you lose the nice stack trace in the console window. Rethrowing the exception does not help. I don't know of any solution which preserves stack traces <strong>and</strong> letting you react on exception.</p>\n"
},
{
"answer_id": 13285023,
"author": "MyounghoonKim",
"author_id": 1115332,
"author_profile": "https://Stackoverflow.com/users/1115332",
"pm_score": 3,
"selected": false,
"text": "<p>Catch all exceptions with your own exception handler and use instanceof.</p>\n\n<pre><code>$(\"inuput\").live({\n click : function (event) {\n try {\n if (somethingGoesWrong) {\n throw new MyException();\n }\n } catch (Exception) {\n new MyExceptionHandler(Exception);\n }\n\n }\n});\n\nfunction MyExceptionHandler(Exception) {\n if (Exception instanceof TypeError || \n Exception instanceof ReferenceError || \n Exception instanceof RangeError || \n Exception instanceof SyntaxError || \n Exception instanceof URIError ) {\n throw Exception; // native error\n } else {\n // handle exception\n }\n}\n</code></pre>\n\n<p>MyExcetpionHandler will throw native error as there is no try-catch block.</p>\n\n<p>Visit <a href=\"http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/\">http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/</a></p>\n"
},
{
"answer_id": 16894944,
"author": "RamIndani",
"author_id": 734805,
"author_profile": "https://Stackoverflow.com/users/734805",
"pm_score": 0,
"selected": false,
"text": "<p>I was also looking for error handling and stacktrace and logging for user actions this is what i found hope this also helps you \n <a href=\"https://github.com/jefferyto/glitchjs\" rel=\"nofollow\">https://github.com/jefferyto/glitchjs</a></p>\n"
},
{
"answer_id": 31742744,
"author": "Fizer Khan",
"author_id": 1154350,
"author_profile": "https://Stackoverflow.com/users/1154350",
"pm_score": 2,
"selected": false,
"text": "<p>With a little bit of work it's possible to get stacktraces that are reasonably complete in all browsers. </p>\n\n<p>Modern Chrome and Opera (i.e. anything based around the Blink rendering engine) fully support the HTML 5 draft spec for ErrorEvent and <code>window.onerror</code>. In both of these browsers you can either use <code>window.onerror</code>, or (amazingly!) bind to the 'error' event properly:</p>\n\n<pre><code>// Only Chrome & Opera pass the error object.\nwindow.onerror = function (message, file, line, col, error) {\n console.log(message, \"from\", error.stack);\n // You can send data to your server\n // sendData(data);\n};\n// Only Chrome & Opera have an error attribute on the event.\nwindow.addEventListener(\"error\", function (e) {\n console.log(e.error.message, \"from\", e.error.stack);\n // You can send data to your server\n // sendData(data);\n})\n</code></pre>\n\n<p>Unfortunately Firefox, Safari and IE are still around and we have to support them too. As the stacktrace is not available in <code>window.onerror</code> we have to do a little bit more work.</p>\n\n<p>It turns out that the only thing we can do to get stacktraces from errors is to wrap all of our code in a <code>try{ }catch(e){ }</code> block and then look at e.stack. We can make the process somewhat easier with a function called wrap that takes a function and returns a new function with good error handling.</p>\n\n<pre><code>function wrap(func) {\n // Ensure we only wrap the function once.\n if (!func._wrapped) {\n func._wrapped = function () {\n try{\n func.apply(this, arguments);\n } catch(e) {\n console.log(e.message, \"from\", e.stack);\n // You can send data to your server\n // sendData(data);\n throw e;\n }\n }\n }\n return func._wrapped;\n};\n</code></pre>\n\n<p>This works. Any function that you wrap manually will have good error handling.</p>\n\n<p>You can send data using image tag as follows</p>\n\n<pre><code>function sendData(data) {\n var img = newImage(),\n src = http://yourserver.com/jserror + '&data=' + encodeURIComponent(JSON.stringify(data));\n\n img.crossOrigin = 'anonymous';\n img.onload = function success() {\n console.log('success', data);\n };\n img.onerror = img.onabort = function failure() {\n console.error('failure', data);\n };\n img.src = src;\n}\n</code></pre>\n\n<p>However you have to do backend to collect the data and front-end to visualise the data. </p>\n\n<p>At <a href=\"https://www.atatus.com/\" rel=\"nofollow\">Atatus</a>, we are working on solving this problem. More than error tracking, Atatus provides real user monitoring. </p>\n\n<blockquote>\n <p>Give a try <a href=\"https://www.atatus.com/\" rel=\"nofollow\">https://www.atatus.com/</a></p>\n</blockquote>\n\n<p>Disclaimer: I am a web developer at Atatus.</p>\n"
},
{
"answer_id": 32642352,
"author": "K. Craven",
"author_id": 5348220,
"author_profile": "https://Stackoverflow.com/users/5348220",
"pm_score": 1,
"selected": false,
"text": "<p>It is true that with modern browsers, hooking window.onerror for errors that bubble all the way to the top along with adding jQuery event handlers for Ajax errors will catch practically all Error objects thrown in your client code. If you're manually setting up a handler for window.onerror, in modern browsers this is done with <code>window.addEventListener('error', callback)</code>, \nwhile in IE8/9 you need to call \n<code>window.attachEvent('onerror', callback)</code>.</p>\n\n<p>Note that you should then consider the environment in which these errors are being handled, and the reason for doing so. It is one thing to catch as many errors as possible with their stacktraces, but the advent of modern F12 dev tools solves this use case when implementing and debugging locally. Breakpoints etc will give you more data than is available from the handlers, especially for errors thrown by third-party libraries which were loaded from CORS requests. You need to take additional steps to instruct the browser to provide this data.</p>\n\n<p>The key issue is providing this data in production, as your users are guaranteed to run a far wider array of browsers and versions than you can possibly test, and your site/app will break in unexpected ways, no matter how much QA you throw at it.</p>\n\n<p>To handle this, you need a production error tracker which picks up every error thrown in your user's browsers, as they use your code, and sends them to an endpoint where the data can be viewed by you and used to fix the bugs as they happen. At Raygun (disclaimer: I work at Raygun) we've put a bunch of effort into providing a great experience for this, as there's many pitfalls and issues to consider that a naive implementation will miss.</p>\n\n<p>For instance, chances are you'll be bundling and minifying your JS assets, which means that errors thrown from minified code will have junk stacktraces with mangled variable names. For this, you need your build tool to generate source maps (we recommend UglifyJS2 for this part of the pipeline), and your error tracker to accept and process these, turning the mangled stacktraces back into human-readable ones. Raygun does all this out of the box, and includes an API endpoint to accept source maps as they are generated by your build process. This is key as they need to be kept non-public, otherwise anyone could unminify your code, negating its purpose.</p>\n\n<p>The <a href=\"https://github.com/MindscapeHQ/raygun4js\" rel=\"nofollow\">raygun4js</a> client library also comes with <code>window.onerror</code> for both modern and legacy browsers, as well as jQuery hooks out-of-the-box, so to set this up you only need to add:</p>\n\n<p><code><script type=\"text/javascript\" src=\"//cdn.raygun.io/raygun4js/raygun.min.js\" </script>\n<script>\n Raygun.init('yourApiKey').attach();\n</script></code></p>\n\n<p>There's also a bunch of functionality built-in including the ability to mutate the error payload before it is sent, adding tags and custom data, metadata on the user who saw the error. It also takes the pain out of getting good stack traces from the above-mentioned third-party CORS scripts, which solves the dreaded 'Script Error' (which contains no error message, and no stack trace).</p>\n\n<p>A more crucial issue is that due to the huge audience on the web, your site will generate many thousands of duplicate instances of each error. An error tracking service like <a href=\"https://raygun.io\" rel=\"nofollow\">Raygun</a> has smarts to roll these up into error groups so you don't drown in a flood of notifications, and lets you see each actual error ready to be fixed.</p>\n"
},
{
"answer_id": 68584769,
"author": "Rodrigo Alvaro Santo SD 6",
"author_id": 15448375,
"author_profile": "https://Stackoverflow.com/users/15448375",
"pm_score": 0,
"selected": false,
"text": "<p>The best error handler:</p>\n<pre><code>try {\n // something\n} catch(e) {\n window.location.href = "https://stackoverflow.com/search?q=[js] + " + e.message\n}\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26259/"
] |
What is the best technique for catching ALL exceptions thrown within JavaScript?
Obviously, the best technique is to use try...catch. But with ansynchronous callbacks and so forth, that can get tricky.
I know IE and Gecko browsers support window.onerror, but what about Opera and Safari?
Here are a bunch of test-cases that I would like to have a central exception handling solution for:
```
// ErrorHandler-Test1
var test = null;
test.arg = 5;
// ErrorHandler-Test2
throw (new Error("Hello"));
// ErrorHandler-Test3
throw "Hello again";
// ErrorHandler-Test4
throw {
myMessage: "stuff",
customProperty: 5,
anArray: [1, 2, 3]
};
// ErrorHandler-Test5
try {
var test2 = null;
test2.arg = 5;
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test6
try {
throw (new Error("Goodbye"));
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test7
try {
throw "Goodbye again";
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test8
try {
throw {
myMessage: "stuff",
customProperty: 5,
anArray: [1, 2, 3]
};
} catch(e) {
ErrorHandler.handleError(e);
}
```
If you think of any other test-cases, please mention them. Several of these cases mention a ErrorHandler.handleError method. This is just a suggested guideline when using try...catch.
|
If you use a library like [jQuery](http://jquery.com/) for assigning all your event handlers, you can use a combination of `window.onerror` and wrapping the jQuery event handler code and on ready function with an error handling function (see: [JavaScript Error Tracking: Why window.onerror Is Not Enough](http://blogs.cozi.com/tech/2008/04/javascript-error-tracking-why-windowonerror-is-not-enough.html)).
* `window.onerror`: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.
* jQuery event handlers: catches jQuery event errors in all browsers.
* jQuery ready function: catches initialisation errors in all browsers.
|
205,689 |
<p>Say I have a class that's meant to perform a single function. After performing the function, it can be destroyed. Is there any reason to prefer one of these approaches?</p>
<pre><code>// Initialize arguments in constructor
MyClass myObject = new MyClass(arg1, arg2, arg3);
myObject.myMethod();
// Pass arguments to method
MyClass myObject = new MyClass();
myObject.myMethod(arg1, arg2, arg3);
// Pass arguments to static method
MyClass.myMethod(arg1, arg2, arg3);
</code></pre>
<p>I was being intentionally vague about the details, to try to get guidelines for different situations. But I didn't really have in mind simple library functions like Math.random(). I'm thinking more of classes that perform some specific, complex task, but only require one (public) method to do it.</p>
|
[
{
"answer_id": 205698,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 7,
"selected": false,
"text": "<p>I prefer the static way. Since the Class is not representing an object it doesn't make sense to make an instance of it.</p>\n\n<p>Classes that only exist for their methods should be left static.</p>\n"
},
{
"answer_id": 205700,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 2,
"selected": false,
"text": "<p>Can your class be made static?</p>\n\n<p>If so, then I'd make it a 'Utilities' class that I would put all my one-function classes in.</p>\n"
},
{
"answer_id": 205703,
"author": "Ray Jezek",
"author_id": 28309,
"author_profile": "https://Stackoverflow.com/users/28309",
"pm_score": 4,
"selected": false,
"text": "<p>If there is no reason to have an instance of the class created in order to execute the function then use the static implementation. Why make the consumers of this class create an instance when one is not needed.</p>\n"
},
{
"answer_id": 205708,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 3,
"selected": false,
"text": "<p>I really don't know what the situation is here, but I would look at putting it as a method in one of the classes that arg1,arg2 or arg3 belong to -- If you can semantically say that one of those classes would own the method.</p>\n"
},
{
"answer_id": 205709,
"author": "Nathen Silver",
"author_id": 6136,
"author_profile": "https://Stackoverflow.com/users/6136",
"pm_score": 3,
"selected": false,
"text": "<p>I would say the Static Method format would be the better option. And I would make the class static as well, that way you wouldn't have to worry about accidentally creating an instance of the class.</p>\n"
},
{
"answer_id": 205847,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<p>If you don't need to save the <em>state</em> of the object, then there's no need to instantiate it in the first place. I'd go with the single static method that you pass parameters to.</p>\n\n<p>I'd also warn against a giant Utils class that has dozens of unrelated static methods. This can get disorganized and unwieldy in a hurry. It's better to have many classes, each with few, related methods.</p>\n"
},
{
"answer_id": 205859,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I would just do everything in the constructor. like so:</p>\n\n<pre><code>new MyClass(arg1, arg2, arg3);// the constructor does everything.\n</code></pre>\n\n<p>or </p>\n\n<pre><code>MyClass my_object(arg1, arg2, arg3);\n</code></pre>\n"
},
{
"answer_id": 205973,
"author": "Joel Wietelmann",
"author_id": 28340,
"author_profile": "https://Stackoverflow.com/users/28340",
"pm_score": 2,
"selected": false,
"text": "<p>If this method is stateless and you don't need to pass it around, then it makes the most sense to define it as static. If you DO need to pass the method around, you might consider using a <a href=\"http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx\" rel=\"nofollow noreferrer\">delegate</a> rather than one of your other proposed approaches.</p>\n"
},
{
"answer_id": 206481,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 9,
"selected": true,
"text": "<p>I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.</p>\n\n<p><strong>Polymorphism</strong><br/>\nSay we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.</p>\n\n<p><strong>Interface woes</strong><br />\nStatic methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by <a href=\"https://learn.microsoft.com/archive/blogs/kirillosenkov/how-to-override-static-methods\" rel=\"noreferrer\">passing delegates instead of interfaces</a>.</p>\n\n<p><strong>Testing</strong><br />\nThis basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.</p>\n\n<p><strong>Fosters blobs</strong><br />\nAs static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.</p>\n\n<p><strong>Parameter creep</strong><br />\nTo begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyways.</p>\n\n<p><strong>Demanding consumers to create an instance of classes for no reason</strong><br />\nOne of the most common arguments is, why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();</p>\n\n<p><strong>Only a Sith deals in absolutes</strong><br />\nOf course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.</p>\n\n<p><strong>Standards, standards, standards!</strong><br />\nUsing instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.</p>\n"
},
{
"answer_id": 206517,
"author": "Nick",
"author_id": 22407,
"author_profile": "https://Stackoverflow.com/users/22407",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest that its hard to answer based on the information provided.</p>\n\n<p>My gut is that if you are just going to have one method, and that you are going to throw the class away immediately, then make it a static class that takes all the parameters. </p>\n\n<p>Of course, its hard to tell exactly why you need to create a single class just for this one method. Is it the typical \"Utilities class\" situation as most are assuming? Or are you implementing some sort of rule class, of which there might be more in the future.</p>\n\n<p>For instance, have that class be plugable. Then you'd want to create an Interface for your one method, and then you'd want to have all the parameters passed into the interface, rather than into the constructor, but you wouldn't want it to be static.</p>\n"
},
{
"answer_id": 2073743,
"author": "Sam Harwell",
"author_id": 138304,
"author_profile": "https://Stackoverflow.com/users/138304",
"pm_score": 2,
"selected": false,
"text": "<p>For simple applications and <code>internal</code> helpers, I would use a static method. For applications with components, I'm loving the <a href=\"http://mef.codeplex.com\" rel=\"nofollow noreferrer\">Managed Extensibility Framework</a>. Here's an excerpt from a document I'm writing to describe the patterns you'll find across my APIs.</p>\n\n<ul>\n<li>Services\n\n<ul>\n<li>Defined by an <code>I[ServiceName]Service</code> interface.</li>\n<li>Exported and imported by the interface type.</li>\n<li>The single implementation is provided by the host application and consumed internally and/or by extensions.</li>\n<li>The methods on the service interface are thread-safe.</li>\n</ul></li>\n</ul>\n\n<p>As a contrived example:</p>\n\n<pre><code>public interface ISettingsService\n{\n string ReadSetting(string name);\n\n void WriteSetting(string name, string value);\n}\n\n[Export]\npublic class ObjectRequiringSettings\n{\n [Import]\n private ISettingsService SettingsService\n {\n get;\n set;\n }\n\n private void Foo()\n {\n if (SettingsService.ReadSetting(\"PerformFooAction\") == bool.TrueString)\n {\n // whatever\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11683609,
"author": "NZal",
"author_id": 1062738,
"author_profile": "https://Stackoverflow.com/users/1062738",
"pm_score": 0,
"selected": false,
"text": "<p>One more important issue to consider is whether the system would be running at a multithreaded environment, and whether it would be thread-safe to have a static method or variables...</p>\n\n<p>You should pay attention to the system state. </p>\n"
},
{
"answer_id": 14624287,
"author": "Hugo Wood",
"author_id": 1067260,
"author_profile": "https://Stackoverflow.com/users/1067260",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to avoid the situation all together. Try to refactor so that you get <code>arg1.myMethod1(arg2, arg3)</code>.\nSwap arg1 with either arg2 or arg3 if it makes more sense.</p>\n\n<p>If you do not have control over the class of arg1, then decorate it :</p>\n\n<pre><code>class Arg1Decorator\n private final T1 arg1;\n public Arg1Decorator(T1 arg1) {\n this.arg1 = arg1;\n }\n public T myMethod(T2 arg2, T3 arg3) {\n ...\n }\n }\n\n arg1d = new Arg1Decorator(arg1)\n arg1d.myMethod(arg2, arg3)\n</code></pre>\n\n<p>The reasoning is that, in OOP, data and methods processing that data belong together. Plus you get all the advantages that Mark mentionned.</p>\n"
},
{
"answer_id": 42156052,
"author": "user7545070",
"author_id": 7545070,
"author_profile": "https://Stackoverflow.com/users/7545070",
"pm_score": 0,
"selected": false,
"text": "<p>i think, if properties of your class or the instance of class will not be used in constructors or in your methods, methods are not suggested to be designed like 'static' pattern. static method should be always thinked in 'help' way.</p>\n"
},
{
"answer_id": 61806856,
"author": "Mark Walsh",
"author_id": 1890742,
"author_profile": "https://Stackoverflow.com/users/1890742",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on whether you want to only do something or do and return something you could do this:</p>\n\n<pre><code>public abstract class DoSomethingClass<T>\n{\n protected abstract void doSomething(T arg1, T arg2, T arg3);\n}\n\npublic abstract class ReturnSomethingClass<T, V>\n{\n public T value;\n protected abstract void returnSomething(V arg1, V arg2, V arg3);\n}\n\npublic class DoSomethingInt extends DoSomethingClass<Integer>\n{\n public DoSomethingInt(int arg1, int arg2, int arg3)\n {\n doSomething(arg1, arg2, arg3);\n }\n\n @Override\n protected void doSomething(Integer arg1, Integer arg2, Integer arg3)\n {\n // ...\n }\n}\n\npublic class ReturnSomethingString extends ReturnSomethingClass<String, Integer>\n{\n public ReturnSomethingString(int arg1, int arg2, int arg3)\n {\n returnSomething(arg1, arg2, arg3);\n }\n\n @Override\n protected void returnSomething(Integer arg1, Integer arg2, Integer arg3)\n {\n String retValue;\n // ...\n value = retValue;\n }\n}\n\npublic class MainClass\n{\n static void main(String[] args)\n {\n int a = 3, b = 4, c = 5;\n\n Object dummy = new DoSomethingInt(a,b,c); // doSomething was called, dummy is still around though\n String myReturn = (new ReturnSomethingString(a,b,c)).value; // returnSomething was called and immediately destroyed\n }\n}\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4321/"
] |
Say I have a class that's meant to perform a single function. After performing the function, it can be destroyed. Is there any reason to prefer one of these approaches?
```
// Initialize arguments in constructor
MyClass myObject = new MyClass(arg1, arg2, arg3);
myObject.myMethod();
// Pass arguments to method
MyClass myObject = new MyClass();
myObject.myMethod(arg1, arg2, arg3);
// Pass arguments to static method
MyClass.myMethod(arg1, arg2, arg3);
```
I was being intentionally vague about the details, to try to get guidelines for different situations. But I didn't really have in mind simple library functions like Math.random(). I'm thinking more of classes that perform some specific, complex task, but only require one (public) method to do it.
|
I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.
**Polymorphism**
Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.
**Interface woes**
Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by [passing delegates instead of interfaces](https://learn.microsoft.com/archive/blogs/kirillosenkov/how-to-override-static-methods).
**Testing**
This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.
**Fosters blobs**
As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.
**Parameter creep**
To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyways.
**Demanding consumers to create an instance of classes for no reason**
One of the most common arguments is, why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();
**Only a Sith deals in absolutes**
Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.
**Standards, standards, standards!**
Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.
|
205,691 |
<p>Whats the benefit of:</p>
<pre><code>public string User {get; set;}
</code></pre>
<p>over</p>
<pre><code>public string User;
</code></pre>
<p>Since you can't access the private member in the first case, how is it any different that just making your property public?</p>
|
[
{
"answer_id": 205714,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "<p>The second example is making the <em>field</em> public, not a property (your question). This provides a simple way of making simple properties. Properties should be your default, not public fields; the list of reasons is endless, but starts with:</p>\n\n<ul>\n<li>encapsulation</li>\n<li>ability to add notification</li>\n<li>encapsulation</li>\n<li>ability to do validation</li>\n<li>encapsulation</li>\n<li>data binding</li>\n<li>encapsulation</li>\n<li>security checking</li>\n</ul>\n\n<p>oh - and did I mention encapsulation?</p>\n\n<p>Changing from a field to a property after-the-fact is a breaking change - especially if you use a lot of \"ref\" code or mutable structs (yeuch).</p>\n"
},
{
"answer_id": 206047,
"author": "pero",
"author_id": 21645,
"author_profile": "https://Stackoverflow.com/users/21645",
"pm_score": 1,
"selected": false,
"text": "<p>There can be a number of things that you must do when User value changes. Things that you don't know in advance or are not present at the time you design your classes. \nFor example one day you realize that user value should be at least 5 characters long. If you have and property it simple to implement. If you have a public field you must change that to property and recompile all dependent code.</p>\n\n<p>In essence I think it pays to explicitly separate public/API part of the our types and the private implementation details. </p>\n\n<p>Did someone mentioned encapsulation ? ;)</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Whats the benefit of:
```
public string User {get; set;}
```
over
```
public string User;
```
Since you can't access the private member in the first case, how is it any different that just making your property public?
|
The second example is making the *field* public, not a property (your question). This provides a simple way of making simple properties. Properties should be your default, not public fields; the list of reasons is endless, but starts with:
* encapsulation
* ability to add notification
* encapsulation
* ability to do validation
* encapsulation
* data binding
* encapsulation
* security checking
oh - and did I mention encapsulation?
Changing from a field to a property after-the-fact is a breaking change - especially if you use a lot of "ref" code or mutable structs (yeuch).
|
205,697 |
<p>I have a query that has a list of base values and a list of language values. Each value has a key that matches to the other. The base values are stored in one table and the language values in another. My problem is that I need to get all matching base values removed from the QUERY except for one. Then, I export that query into an Excel spreadsheet (I can do this portion fine) and allow the user to edit the language values.</p>
<p>When the user edits and/or inserts new language values, I need to update the database except now writing over any matching values in the database (like those that were removed the first time).</p>
<p>In simplicity, the client pays for translations and if I can generate a sheet that has fewer translations needed (like phrases that reappear often) then they can save money, hence the project to begin with. I realize the downside is that it is not a true linked list, where all matching values all belong to one row in the language table (which would have been easy). Instead, there are multiple values that are identical that need to be updated as described above.</p>
<hr>
<p>Yeah, I'm confused on it which is why it might seem a little vague. Here's a sample:</p>
<pre><code>Table 1
Item Description1
Item Description2
Item Description3
Item Description2
Item Description2
Item Description4
Item Description5
Item Description6
Item Description3
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (blank)
Item Desc in other Language3
Item Desc in other Language4
Item Desc in other Language5
*blank*
</code></pre>
<p>Desired Result (when queried)</p>
<p>Table 1
Item Description1
Item Description2
Item Description3
Item Description4
Item Description5
Item Description6</p>
<pre><code>Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (filled by matching row in Table 2)
Item Desc in other Language4
Item Desc in other Language5
Item Desc in other Language6 (blank, returned as empty string)
</code></pre>
<p>The user makes their modifications, including inserting data into blank rows (like row 6 for the language) then reuploads:</p>
<pre><code>Table 1
Item Description1
Item Description2
Item Description3
Item Description2
Item Description2
Item Description4
Item Description5
Item Description6
Item Description3
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (now matches row below)
Item Desc in other Language3
Item Desc in other Language4
Item Desc in other Language5
Item Desc in other Language6 (new value entered by user)
</code></pre>
<p>There is also a resource key that matches each "Item Description" to a single "Item Desc in other Language". The only time they are ever going to see each other is during this translation process, all other times the values may be different, so the resource keys can't simply be changed to all point at one translation permanently.</p>
<p>I should also add, there should be no alteration of the structure of the tables or removing rows of the table.</p>
<hr>
<p>Ok, here's an updated revisal of what I would LIKE the query to do, but obviously does not do since I actually need the values of the joined table:</p>
<pre><code>SELECT pe.prodtree_element_name_l, rs.resource_value, pe.prodtree_element_name_l_rk
FROM prodtree_element pe
LEFT JOIN resource_shortstrings rs
ON pe.prodtree_element_name_l_rk = rs.resource_key
WHERE rs.language_id = '5'
AND pe.prodtree_element_name_l <> ''
GROUP BY pe.prodtree_element_name_l
</code></pre>
|
[
{
"answer_id": 205798,
"author": "Ben Doom",
"author_id": 12267,
"author_profile": "https://Stackoverflow.com/users/12267",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to remove all matches except for one, why not delete all the matching ... matches ... we need better terms ... and then insert the correct one. EG, if you need to update the matches between items 12 and 13 in the base pair table, do something like</p>\n\n<pre><code>delete from matchtable where (id1 = 12 and id2 = 13) or (id1 = 13 and id2 = 13);\ninsert into matchtable (id1, id2) values (12, 13);\n</code></pre>\n\n<p>I may be oversimplifying, but your description seems vague in places.</p>\n"
},
{
"answer_id": 206294,
"author": "Milner",
"author_id": 16575,
"author_profile": "https://Stackoverflow.com/users/16575",
"pm_score": 1,
"selected": false,
"text": "<p>Hrm, still not real clear on what the issue truly is, but let me give it a go.</p>\n\n<p>Tables:</p>\n\n<pre>\nBASE_VALUES\n------------------\nBASE_VALUE_RK\nBASE_VALUE_NAME\n\nRESOURCE_VALUES (these are the translations, I'm guessing)\n-----------------------\nRESOURCE_KEY\nRESOURCE_LANGUAGE_ID\nRESOURCE_VALUE\n</pre>\n\n<p>You want to retrieve one base value, and all corresponding translation values that match that base value, export them to excel, and then re-load them via an update (I think).</p>\n\n<p>SQL to SELECT out data:</p>\n\n<pre>\nSELECT bv.BASE_VALUE_RK, rv.RESOURVE_VALUE\n FROM BASE_VALUE bv, RESOURCE_VALUE rv\n WHERE bv.BASE_VALUE_RK = rv.RESOURCE_KEY\n AND rv.resource_language_id = '5'\n ORDER BY 1;\n</pre>\n\n<p>That'll give you:</p>\n\n<pre>\n1234 Foo\n1235 Bar\n1236 Baz\n</pre>\n\n<p>Export that to excel, and get it back with updates:</p>\n\n<pre>\n1234 Goo\n1235 Car\n1236 Spaz\n</pre>\n\n<p>You can then say:</p>\n\n<pre>\nUPDATE RESOURCE_VALUES\n SET RESOURCE_VALUE = value_from_spreadsheet\n WHERE RESOURCE_KEY = key_from_spreadsheet\n</pre>\n\n<p>I may be way off base on this guy, so let me know and, if you can provide a little more detail, I may be able to score closer to the mark.</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 206464,
"author": "Organiccat",
"author_id": 16631,
"author_profile": "https://Stackoverflow.com/users/16631",
"pm_score": 1,
"selected": true,
"text": "<p>Hey thanks for that update!</p>\n\n<p>Looking at that and adding it into a previous post I finally came up with this:</p>\n\n<pre><code><cfquery name=\"getRows\" datasource=\"XXXX\">\n SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value\n FROM prodtree_element pe\n LEFT JOIN resource_shortstrings rs\n ON pe.prodtree_element_name_l_rk = rs.resource_key\n WHERE rs.language_id = '5'\n AND pe.prodtree_element_name_l <> ''\n GROUP BY prodtree_element_name_l\n</cfquery>\n</code></pre>\n\n<p>I realized I didn't need a specific resource_value, just any that was in there. I also realized I didn't need the resource key at all outside of the query. The update will be updating ALL the matching base values regardless, so I didn't really need the resource key after all, which allowed me to use the GROUP BY.</p>\n\n<p>Took a while, sorry for the poor explanation, but this is it! :) Thanks for all the help.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16631/"
] |
I have a query that has a list of base values and a list of language values. Each value has a key that matches to the other. The base values are stored in one table and the language values in another. My problem is that I need to get all matching base values removed from the QUERY except for one. Then, I export that query into an Excel spreadsheet (I can do this portion fine) and allow the user to edit the language values.
When the user edits and/or inserts new language values, I need to update the database except now writing over any matching values in the database (like those that were removed the first time).
In simplicity, the client pays for translations and if I can generate a sheet that has fewer translations needed (like phrases that reappear often) then they can save money, hence the project to begin with. I realize the downside is that it is not a true linked list, where all matching values all belong to one row in the language table (which would have been easy). Instead, there are multiple values that are identical that need to be updated as described above.
---
Yeah, I'm confused on it which is why it might seem a little vague. Here's a sample:
```
Table 1
Item Description1
Item Description2
Item Description3
Item Description2
Item Description2
Item Description4
Item Description5
Item Description6
Item Description3
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (blank)
Item Desc in other Language3
Item Desc in other Language4
Item Desc in other Language5
*blank*
```
Desired Result (when queried)
Table 1
Item Description1
Item Description2
Item Description3
Item Description4
Item Description5
Item Description6
```
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (filled by matching row in Table 2)
Item Desc in other Language4
Item Desc in other Language5
Item Desc in other Language6 (blank, returned as empty string)
```
The user makes their modifications, including inserting data into blank rows (like row 6 for the language) then reuploads:
```
Table 1
Item Description1
Item Description2
Item Description3
Item Description2
Item Description2
Item Description4
Item Description5
Item Description6
Item Description3
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (now matches row below)
Item Desc in other Language3
Item Desc in other Language4
Item Desc in other Language5
Item Desc in other Language6 (new value entered by user)
```
There is also a resource key that matches each "Item Description" to a single "Item Desc in other Language". The only time they are ever going to see each other is during this translation process, all other times the values may be different, so the resource keys can't simply be changed to all point at one translation permanently.
I should also add, there should be no alteration of the structure of the tables or removing rows of the table.
---
Ok, here's an updated revisal of what I would LIKE the query to do, but obviously does not do since I actually need the values of the joined table:
```
SELECT pe.prodtree_element_name_l, rs.resource_value, pe.prodtree_element_name_l_rk
FROM prodtree_element pe
LEFT JOIN resource_shortstrings rs
ON pe.prodtree_element_name_l_rk = rs.resource_key
WHERE rs.language_id = '5'
AND pe.prodtree_element_name_l <> ''
GROUP BY pe.prodtree_element_name_l
```
|
Hey thanks for that update!
Looking at that and adding it into a previous post I finally came up with this:
```
<cfquery name="getRows" datasource="XXXX">
SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value
FROM prodtree_element pe
LEFT JOIN resource_shortstrings rs
ON pe.prodtree_element_name_l_rk = rs.resource_key
WHERE rs.language_id = '5'
AND pe.prodtree_element_name_l <> ''
GROUP BY prodtree_element_name_l
</cfquery>
```
I realized I didn't need a specific resource\_value, just any that was in there. I also realized I didn't need the resource key at all outside of the query. The update will be updating ALL the matching base values regardless, so I didn't really need the resource key after all, which allowed me to use the GROUP BY.
Took a while, sorry for the poor explanation, but this is it! :) Thanks for all the help.
|
205,711 |
<p>I've been struggling with a problem for the past couple days and haven't found a solution.</p>
<p>I have an Visual Studio solution with 2 projects, the first one is a DLL with my business objects and logic, the other project is my WinForm application, and a reference dependency on the first project.</p>
<p>I initially wrote the business objects with Attribute LINQ mapping and everything was working fine. Then I thought I would try external mapping. I followed a few different guides on how it should work; however, everytime I ran the code in my solution I would get a <em>InvalidOperationException: Mapping Problem: Cannot find type 'Org.Example.System.Material' from mapping</em>, when the WinForm attempts to create the DataContext object.</p>
<p>After trying different configurations in the XML file I placed a copy of the class into my GUI solution under a different namespace and it worked. My question is, is it not possible to map an object in a class library or if it is how is it accomplished.</p>
<p>Samples</p>
<p><strong>dbmap.xml</strong></p>
<pre><code><Database xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007" Name="Gravel_Dev"><Table Name="dbo.Materials" Member="Material">
<Type Name="Org.Example.System.Material">
<Column Name="MaterialID" Member="MaterialID" Storage="mMaterialID" DbType="UniqueIdentifier NOT NULL" IsDbGenerated="true" IsPrimaryKey="true"/>
<Column Name="Code" Member="Code" Storage="mMaterialCode" DbType="Char(4)"/>
<Column Name="Description" Member="Description" Storage="mDescription" DbType="VarChar(50)"/>
<Column Name="UnitPrice" Member="UnitPrice" Storage="mUnitPrice" DbType="Decimal(5,2)"/>
</Type>
</code></pre>
<p>
</p>
<p><strong>WinForm Loading</strong></p>
<pre><code>XmlMappingSource mapping = XmlMappingSource.FromUrl("dbmap.xml");
mContext = new DataContext(Properties.Settings.Default.dbConn, mapping);
reloadTable();
</code></pre>
|
[
{
"answer_id": 205719,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 2,
"selected": true,
"text": "<p>I think the problem you might be getting is that the assembly/class library containing your classes hasn't been loaded into memory at this stage?</p>\n\n<p>Try accessing a class in the library before instantiating the data context to see if that works.</p>\n"
},
{
"answer_id": 1473739,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same problem. We have a mapping file which maps different assemblies and we get the mapping error since all assemplies are not loaded in memory. What are the different solutions to this problem?</p>\n\n<p>I have read that is is possible to reference a type in a different assembly using the AssemblyQualifiedName of the type. But we did not get it to work. If this is possible can you give an example of what this would look like?</p>\n\n<p>Another solution, I suppose, is to have one mapping file for each assembly and give the datacontext the correct mapping file at runtime.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13616/"
] |
I've been struggling with a problem for the past couple days and haven't found a solution.
I have an Visual Studio solution with 2 projects, the first one is a DLL with my business objects and logic, the other project is my WinForm application, and a reference dependency on the first project.
I initially wrote the business objects with Attribute LINQ mapping and everything was working fine. Then I thought I would try external mapping. I followed a few different guides on how it should work; however, everytime I ran the code in my solution I would get a *InvalidOperationException: Mapping Problem: Cannot find type 'Org.Example.System.Material' from mapping*, when the WinForm attempts to create the DataContext object.
After trying different configurations in the XML file I placed a copy of the class into my GUI solution under a different namespace and it worked. My question is, is it not possible to map an object in a class library or if it is how is it accomplished.
Samples
**dbmap.xml**
```
<Database xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007" Name="Gravel_Dev"><Table Name="dbo.Materials" Member="Material">
<Type Name="Org.Example.System.Material">
<Column Name="MaterialID" Member="MaterialID" Storage="mMaterialID" DbType="UniqueIdentifier NOT NULL" IsDbGenerated="true" IsPrimaryKey="true"/>
<Column Name="Code" Member="Code" Storage="mMaterialCode" DbType="Char(4)"/>
<Column Name="Description" Member="Description" Storage="mDescription" DbType="VarChar(50)"/>
<Column Name="UnitPrice" Member="UnitPrice" Storage="mUnitPrice" DbType="Decimal(5,2)"/>
</Type>
```
**WinForm Loading**
```
XmlMappingSource mapping = XmlMappingSource.FromUrl("dbmap.xml");
mContext = new DataContext(Properties.Settings.Default.dbConn, mapping);
reloadTable();
```
|
I think the problem you might be getting is that the assembly/class library containing your classes hasn't been loaded into memory at this stage?
Try accessing a class in the library before instantiating the data context to see if that works.
|
205,731 |
<p>I need the values of form inputs to be populated by the sql database. My code works great for all text and textarea inputs but I can't figure out how to assign the database value to the drop down lists eg. 'Type of property' below. It revolves around getting the 'option selected' to represent the value held in the database.</p>
<p>Here is my code:</p>
<pre><code>$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");
$row = $db->sql_fetchrow($result);
echo "<center><font class=\"title\">"._CHANGE_MY_INFORMATION."</font></center><br>\n";
echo "<center>".All." ".fields." ".must." ".be." ".filled."
<form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\">
<table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\">
<tr>
<td align=\"right\">".Telephone." :</td>
<td>
<input type=\"text\" name=\"telephone\" size=\"27\" value=\"$row[telephone]\"> Inc. dialing codes
</td>
</tr>
<tr>
<td align=\"right\">".Type." ".of." ".property." ".required." :</td>
<td>Select from list:
<select name=\"req_type\" value=\"$row[req_type]\">
<option>House</option>
<option>Bungalow</option>
<option>Flat/Apartment</option>
<option>Studio</option>
<option>Villa</option>
<option>Any</option>
</select>
</td>
</tr>
....
</code></pre>
|
[
{
"answer_id": 205778,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "<p>using your current code:</p>\n\n<pre><code><?php\n $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n\n foreach($options as $option) {\n if ($option == $row['req_type']) {\n print '<option selected=\"selected\">'.$option.'</option>'.\"\\n\";\n } else {\n print '<option>'.$option.'</option>'.\"\\n\";\n }\n }\n?>\n</code></pre>\n\n<p>assuming <code>$row['req_type']</code> is one of the values in <code>$options</code>. i strongly suggest quoting your array elements (ie <code>$row['req_type']</code> instead of <code>$row[req_type]</code>. the latter method generates errors under <code>error_reporting(E_ALL)</code></p>\n\n<p>you also might want to look at resources such as <a href=\"http://phpbuilder.com\" rel=\"nofollow noreferrer\">phpbuilder.com</a>. some articles are pretty outdated, but will provide you with some basics on how to better structure your code. (for example, separating your HTML from your PHP code woulud help readiability in this sitaution a lot).</p>\n\n<p><strong>edit</strong>: as per the comments, any information displayed should be escaped properly (see <a href=\"http://php.net/htmlentities\" rel=\"nofollow noreferrer\"><code>htmlentities()</code></a> for example).</p>\n"
},
{
"answer_id": 206006,
"author": "Brad",
"author_id": 26130,
"author_profile": "https://Stackoverflow.com/users/26130",
"pm_score": -1,
"selected": false,
"text": "<p>Here is another way of going about it.</p>\n\n<pre><code><?php\n$query = \"SELECT * FROM \".$prefix.\"_users WHERE userid='$userid'\";\n$result = mysql_query($query); ?>\n$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n<select name=\"venue\">\n<?php\n while($row = mysql_fetch_array($result)) {\n print '<option value=\"'.$option.'\"';\n if($row['req_type'] == $option) {\n print 'selected';\n }\n print '>'.$option.'</option>';\n } \n?>\n</select>\n</code></pre>\n"
},
{
"answer_id": 206817,
"author": "user24632",
"author_id": 24632,
"author_profile": "https://Stackoverflow.com/users/24632",
"pm_score": 0,
"selected": false,
"text": "<p>May not be efficient, but it's simple & gets the job done.</p>\n\n<pre><code>$dropdown = str_replace(\"<option value=\\\"\".$row[column].\"\\\">\",\"<option value=\\\"\".$row[column].\"\\\" selected>\",$dropdown);\n</code></pre>\n"
},
{
"answer_id": 207126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Owen. Your code seems perfect but gave lots of php errors. I simplified it to this but just get whitespace as options:</p>\n\n<pre><code><td>Select from list: <select name=\\\"req_type\\\"> \n\n$option = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n\nforeach($option as $option) { \nif ($option == $row[req_type]) { \n <option selected>$option</option>} \nelse { \n<option>$option</option>}};\n</select></td>\n</code></pre>\n"
},
{
"answer_id": 207303,
"author": "andyk",
"author_id": 26721,
"author_profile": "https://Stackoverflow.com/users/26721",
"pm_score": 0,
"selected": false,
"text": "<pre><code> <?php\n $result = $db->sql_query(\"SELECT * FROM \".$prefix.\"_users WHERE userid='$userid'\"); \n $row = $db->sql_fetchrow($result);\n\n // options defined here\n $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n\n ?> \n <center><font class=\"title\"><?php echo _CHANGE_MY_INFORMATION; ?></font></center><br />\n\n <center> All fields must be filled </center> \n <form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\"> \n <table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\"> \n <tr> \n <td align=\"right\">Telephone :</td> \n <td>\n <input type=\"text\" name=\"telephone\" size=\"27\" value=\"<?php echo htmlentities($row['telephone']); ?>\" /> Inc. dialing codes\n </td> \n </tr> \n <tr> \n <td align=\"right\">Type of property required :</td> \n <td>Select from list:\n <select name=\"req_type\">\n <?php foreach($options as $option): ?> \n <option value=\"<?php echo $option; ?>\" <?php if($row['req_type'] == $option) echo 'selected=\"selected\"'; ?>><?php echo $option; ?></option> \n <?php endforeach; ?>\n </select> \n </td> \n </tr>\n\n...\n</code></pre>\n\n<p>oops.. a little too carried away.</p>\n"
},
{
"answer_id": 209169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks everyone for all your help. Although I couldn't get any one answer to work it gave me ideas and I have accomplished the job! I ended up going about it a long-winded way but hey-ho if it's not broke don't fix it.</p>\n\n<pre><code>if ($row[$req_type]=='House'){\n $sel_req_type1='selected';\n}\nelse if ($row[$req_type]=='Bugalow'){\n $sel_req_type2='selected';\n}\n</code></pre>\n\n<p>etc. etc. etc.</p>\n\n<p>And in the table:</p>\n\n<pre><code><option $sel_req_type1>House</option>\n<option $sel_req_type2>Bulgalow</option>\n</code></pre>\n\n<p>etc. etc. etc.</p>\n\n<p>I still have other issues to overcome i.e. htmlentities for the text fields and quoting the array elements (ie <code>$row['req_type']</code> instead of <code>$row[req_type]</code>. But I'll ask that on another question. Thanks again</p>\n"
},
{
"answer_id": 2931535,
"author": "BKCOHEN",
"author_id": 350231,
"author_profile": "https://Stackoverflow.com/users/350231",
"pm_score": 1,
"selected": false,
"text": "<p>Nigel,</p>\n\n<p>See the answer with the check mark next to it. It go me start in solving my problem. First I select my data from the table, then I select the data i want display in my dropdown menu. If the data from the primary table matches the data from the dropdown table selected is echoed.</p>\n\n<pre><code>$query9 = \"SELECT *\n FROM vehicles\n WHERE VID = '\".$VID.\"'\n \";\n\n$result9=mysql_query($query9);\nwhile($row9 = mysql_fetch_array($result9)){\n $vdate=$row9['DateBid'];\n $vmodelid=$row9['ModelID'];\n $vMileage=$row9['Mileage'];\n $vHighBid=$row9['HighBid'];\n $vPurchased=$row9['Purchased'];\n $vDamage=$row9['Damage'];\n $vNotes=$row9['Notes'];\n $vKBBH=$row9['KBBH'];\n $vKBBM=$row9['KBBM'];\n $vKBBL=$row9['KBBL'];\n $vKBBR=$row9['KBBR'];\n $vYID=$row9['YID'];\n $vMID=$row9['MID'];\n $vModelID=$row9['ModelID'];\n $vELID=$row9['ELID'];\n $vECID=$row9['ECID'];\n $vEFID=$row9['EFID'];\n $vColorID=$row9['ColorID'];\n $vRID=$row9['RID'];\n $vFID=$row9['FID'];\n $vDID=$row9['DID'];\n $vTID=$row9['TID'];\n}\n\n$query1 = \"SELECT * FROM year ORDER BY Year ASC\";\n$result1=mysql_query($query1);\necho \"<select name='Year'>\";\nwhile($row1 = mysql_fetch_array($result1)){\n echo \"<option value = '{$row1['YID']}'\";\n if ($vYID == $row1['YID'])\n echo \"selected = 'selected'\";\n echo \">{$row1['Year']}</option>\";\n}\necho \"</select>\";\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need the values of form inputs to be populated by the sql database. My code works great for all text and textarea inputs but I can't figure out how to assign the database value to the drop down lists eg. 'Type of property' below. It revolves around getting the 'option selected' to represent the value held in the database.
Here is my code:
```
$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");
$row = $db->sql_fetchrow($result);
echo "<center><font class=\"title\">"._CHANGE_MY_INFORMATION."</font></center><br>\n";
echo "<center>".All." ".fields." ".must." ".be." ".filled."
<form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\">
<table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\">
<tr>
<td align=\"right\">".Telephone." :</td>
<td>
<input type=\"text\" name=\"telephone\" size=\"27\" value=\"$row[telephone]\"> Inc. dialing codes
</td>
</tr>
<tr>
<td align=\"right\">".Type." ".of." ".property." ".required." :</td>
<td>Select from list:
<select name=\"req_type\" value=\"$row[req_type]\">
<option>House</option>
<option>Bungalow</option>
<option>Flat/Apartment</option>
<option>Studio</option>
<option>Villa</option>
<option>Any</option>
</select>
</td>
</tr>
....
```
|
using your current code:
```
<?php
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
foreach($options as $option) {
if ($option == $row['req_type']) {
print '<option selected="selected">'.$option.'</option>'."\n";
} else {
print '<option>'.$option.'</option>'."\n";
}
}
?>
```
assuming `$row['req_type']` is one of the values in `$options`. i strongly suggest quoting your array elements (ie `$row['req_type']` instead of `$row[req_type]`. the latter method generates errors under `error_reporting(E_ALL)`
you also might want to look at resources such as [phpbuilder.com](http://phpbuilder.com). some articles are pretty outdated, but will provide you with some basics on how to better structure your code. (for example, separating your HTML from your PHP code woulud help readiability in this sitaution a lot).
**edit**: as per the comments, any information displayed should be escaped properly (see [`htmlentities()`](http://php.net/htmlentities) for example).
|
205,733 |
<p>Is it possible to call a class's static property to set the navigateurl property?</p>
<blockquote>
<pre><code><asp:HyperLink ID="hlRegister" NavigateUrl="<%= SomeClass.Property %>" runat="server" />
</code></pre>
</blockquote>
<p><b>without using codebehind ofcourse!</b></p>
|
[
{
"answer_id": 205742,
"author": "craigmoliver",
"author_id": 12252,
"author_profile": "https://Stackoverflow.com/users/12252",
"pm_score": 0,
"selected": false,
"text": "<p>sure, in the code behind:</p>\n\n<pre><code>hl.NavigateUrl = Class.Static().ToString();\n</code></pre>\n"
},
{
"answer_id": 205767,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need code behind. You can just try it, like i just did. I created a simple page with exactly the code you have, and then created a class called SomeClass with a property named Property. It worked fine for me the way that you have it set up above. </p>\n\n<p>Edit: Ok, it didn't compile with an error.. but It's giving me not the result I'm looking for.</p>\n\n<p><a href=\"http://localhost:3061/Sample/%3C%=%20SomeClass.Property.ToString()%20%%3E\" rel=\"nofollow noreferrer\">http://localhost:3061/Sample/%3C%=%20SomeClass.Property.ToString()%20%%3E</a></p>\n\n<p>using:</p>\n\n<pre><code>public static class SomeClass\n{\n public static string Property\n {\n get { return \"http://www.google.com\"; }\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code><asp:HyperLink ID=\"hlRegister\" NavigateUrl='<%= SomeClass.Property.ToString() %>' Text=\"Goooooogle\" runat=\"server\" />\n</code></pre>\n"
},
{
"answer_id": 205865,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this, but to avoid a syntax error you must modify your example to be as follows.</p>\n\n<pre><code> <asp:HyperLink ID=\"hlRegister\" \n NavigateUrl='<%= SomeClass.Property %>' runat=\"server\" />\n</code></pre>\n\n<p>Notice the small difference of using single quotes rather than double around the script.</p>\n\n<p>However, one might really ask why not just do it in the codebehind.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is it possible to call a class's static property to set the navigateurl property?
>
>
> ```
> <asp:HyperLink ID="hlRegister" NavigateUrl="<%= SomeClass.Property %>" runat="server" />
>
> ```
>
>
**without using codebehind ofcourse!**
|
You don't need code behind. You can just try it, like i just did. I created a simple page with exactly the code you have, and then created a class called SomeClass with a property named Property. It worked fine for me the way that you have it set up above.
Edit: Ok, it didn't compile with an error.. but It's giving me not the result I'm looking for.
<http://localhost:3061/Sample/%3C%=%20SomeClass.Property.ToString()%20%%3E>
using:
```
public static class SomeClass
{
public static string Property
{
get { return "http://www.google.com"; }
}
}
```
and
```
<asp:HyperLink ID="hlRegister" NavigateUrl='<%= SomeClass.Property.ToString() %>' Text="Goooooogle" runat="server" />
```
|
205,735 |
<p>My knowledge of matlab is merely on a need to know basis, so this is probably an elementary question. Nevertheless here it comes:</p>
<p>I have got a file containing data (16-bit integers) stored in binary format. How do I read it into a vector /an array in matlab? How do I write this data to a file in matlab? Is there any smart tweak to increase the performance speed when reading/writing a huge amount of data (gigabytes)?</p>
|
[
{
"answer_id": 205777,
"author": "Anthony Potts",
"author_id": 22777,
"author_profile": "https://Stackoverflow.com/users/22777",
"pm_score": 0,
"selected": false,
"text": "<p>I usually hate seeing links in a response, but this looks pretty close:</p>\n\n<p><a href=\"http://www.mathworks.com/support/tech-notes/1400/1403.html\" rel=\"nofollow noreferrer\">http://www.mathworks.com/support/tech-notes/1400/1403.html</a></p>\n\n<p>As to the second part of performance tuning, it's been 6 years since I've used Matlab, so I don't know. </p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 205819,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you know how many values you have stored in the file, you can do something like this to read the data into an array.</p>\n\n<pre><code>fid = fopen('data.bin','rb')\nA = fread(fid, count, 'int16')\n</code></pre>\n\n<p>To write data to a file do this:</p>\n\n<pre><code>fid = fopen('data.bin','w')\ncount = fwrite(fid, A, 'int16')\n</code></pre>\n\n<p>The fwrite function returns the number of <em>elements</em> (not bytes) written to the file.</p>\n\n<p>As far as performance tuning goes, you can read data in chunks to only use as much as you need to process. This is the same in any language, and there's no way to speed it up that's specific to Matlab.</p>\n"
},
{
"answer_id": 206199,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 5,
"selected": true,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819\">Bill the Lizard</a> wrote you can use fread to load the data into a vector. I just want to expand a little on his answer. </p>\n\n<h3>Reading Data</h3>\n\n<pre><code>>> fid=fopen('data.bin','rb') % opens the file for reading\n>> A = fread(fid, count, 'int16') % reads _count_ elements and stores them in A.\n</code></pre>\n\n<p>The commands <em>fopen</em> and <em>fread</em> default to Little-endian[1] encoding for the integers. If your file is Big-endian encoded you will need to change the <em>fread</em> to</p>\n\n<pre><code>>> A = fread(fid, count, 'int16', 'ieee-be');\n</code></pre>\n\n<p>Also, if you want to read the whole file set </p>\n\n<pre><code>>> count=inf;\n</code></pre>\n\n<p>and if you want to read the data into matrix with <em>n</em> columns use</p>\n\n<pre><code>>> count=[n inf];\n</code></pre>\n\n<h3>Writing Data</h3>\n\n<p>As for witting the data to a file. The command, <em>fwrite</em>, in <a href=\"https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819\">Bill's</a> answer will write to a binary file. If you want to write the data to a text file you can use <em>dlmwrite</em></p>\n\n<pre><code>>> dlmwrite('data.csv',A,',');\n</code></pre>\n\n<h3>References</h3>\n\n<p>[1] <a href=\"http://en.wikipedia.org/wiki/Endianness\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Endianness</a></p>\n\n<h3>Update</h3>\n\n<ol>\n<li><p>The machine format (IE, <em>ieee-be</em>,\n<em>ieee-le</em>, <em>vaxd</em> etc.) of the binary data can be specified in either the\n<em>fopen</em> or the <em>fread</em> commands in Matlab. Details of the supported\nmachine format can be found in\nMatlab's documentation of <em>fopen</em>. </p></li>\n<li><p><a href=\"https://stackoverflow.com/users/4928/scott-french\">Scott French's</a> comment to <a href=\"https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819\">Bill's\nanswer</a>\nsuggests reading the data into an\nint16 variable. To do this use</p>\n\n<pre><code>>> A = int16(fread(fid,count,precision,machineFormat));\n</code></pre>\n\n<p>where <em>count</em> is the size/shape of\nthe data to be read, <em>precision</em> is\nthe data format, and <em>machineformat</em>\nis the encoding of each byte.</p></li>\n<li><p>See commands <em>fseek</em> to move around the file. For example, </p>\n\n<pre><code>>> fseek(fid,0,'bof');\n</code></pre>\n\n<p>will rewind the file to the beginning where <em>bof</em> stands for <em>beginning of file</em>.</p></li>\n</ol>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4044/"
] |
My knowledge of matlab is merely on a need to know basis, so this is probably an elementary question. Nevertheless here it comes:
I have got a file containing data (16-bit integers) stored in binary format. How do I read it into a vector /an array in matlab? How do I write this data to a file in matlab? Is there any smart tweak to increase the performance speed when reading/writing a huge amount of data (gigabytes)?
|
As [Bill the Lizard](https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819) wrote you can use fread to load the data into a vector. I just want to expand a little on his answer.
### Reading Data
```
>> fid=fopen('data.bin','rb') % opens the file for reading
>> A = fread(fid, count, 'int16') % reads _count_ elements and stores them in A.
```
The commands *fopen* and *fread* default to Little-endian[1] encoding for the integers. If your file is Big-endian encoded you will need to change the *fread* to
```
>> A = fread(fid, count, 'int16', 'ieee-be');
```
Also, if you want to read the whole file set
```
>> count=inf;
```
and if you want to read the data into matrix with *n* columns use
```
>> count=[n inf];
```
### Writing Data
As for witting the data to a file. The command, *fwrite*, in [Bill's](https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819) answer will write to a binary file. If you want to write the data to a text file you can use *dlmwrite*
```
>> dlmwrite('data.csv',A,',');
```
### References
[1] <http://en.wikipedia.org/wiki/Endianness>
### Update
1. The machine format (IE, *ieee-be*,
*ieee-le*, *vaxd* etc.) of the binary data can be specified in either the
*fopen* or the *fread* commands in Matlab. Details of the supported
machine format can be found in
Matlab's documentation of *fopen*.
2. [Scott French's](https://stackoverflow.com/users/4928/scott-french) comment to [Bill's
answer](https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819)
suggests reading the data into an
int16 variable. To do this use
```
>> A = int16(fread(fid,count,precision,machineFormat));
```
where *count* is the size/shape of
the data to be read, *precision* is
the data format, and *machineformat*
is the encoding of each byte.
3. See commands *fseek* to move around the file. For example,
```
>> fseek(fid,0,'bof');
```
will rewind the file to the beginning where *bof* stands for *beginning of file*.
|
205,736 |
<p>How do I query an Oracle database to display the names of all tables in it?</p>
|
[
{
"answer_id": 205746,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 11,
"selected": true,
"text": "<pre><code>SELECT owner, table_name\n FROM dba_tables\n</code></pre>\n\n<p>This is assuming that you have access to the <code>DBA_TABLES</code> data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the <code>SELECT ANY DICTIONARY</code> privilege or the <code>SELECT_CATALOG_ROLE</code> role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like <code>SYS</code> and <code>SYSTEM</code> which have large numbers of Oracle tables that you probably don't care about.</p>\n\n<p>Alternatively, if you do not have access to <code>DBA_TABLES</code>, you can see all the tables that your account has access to through the <code>ALL_TABLES</code> view:</p>\n\n<pre><code>SELECT owner, table_name\n FROM all_tables\n</code></pre>\n\n<p>Although, that may be a subset of the tables available in the database (<code>ALL_TABLES</code> shows you the information for all the tables that your user has been granted access to). </p>\n\n<p>If you are only concerned with the tables that you own, not those that you have access to, you could use <code>USER_TABLES</code>:</p>\n\n<pre><code>SELECT table_name\n FROM user_tables\n</code></pre>\n\n<p>Since <code>USER_TABLES</code> only has information about the tables that you own, it does not have an <code>OWNER</code> column – the owner, by definition, is you.</p>\n\n<p>Oracle also has a number of legacy data dictionary views-- <code>TAB</code>, <code>DICT</code>, <code>TABS</code>, and <code>CAT</code> for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the <code>TAB</code> and <code>CAT</code> views both show information about tables that are in the user's recycle bin while the <code>[DBA|ALL|USER]_TABLES</code> views all filter those out. <code>CAT</code> also shows information about materialized view logs with a <code>TABLE_TYPE</code> of \"TABLE\" which is unlikely to be what you really want. <code>DICT</code> combines tables and synonyms and doesn't tell you who owns the object.</p>\n"
},
{
"answer_id": 205796,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": 3,
"selected": false,
"text": "<p>Try selecting from <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_5443.htm#REFRN26286\" rel=\"noreferrer\">user_tables</a> which lists the tables owned by the current user.</p>\n"
},
{
"answer_id": 205811,
"author": "vitule",
"author_id": 1287,
"author_profile": "https://Stackoverflow.com/users/1287",
"pm_score": 8,
"selected": false,
"text": "<p>Querying <code>user_tables</code> and <code>dba_tables</code> didn't work.<br>\nThis one did: </p>\n\n<pre><code>select table_name from all_tables \n</code></pre>\n"
},
{
"answer_id": 1377725,
"author": "stealth_angoid",
"author_id": 167171,
"author_profile": "https://Stackoverflow.com/users/167171",
"pm_score": 6,
"selected": false,
"text": "<p>Going one step further, there is another view called cols (all_tab_columns) which can be used to ascertain which tables contain a given column name.</p>\n\n<p>For example:</p>\n\n<pre><code>SELECT table_name, column_name\nFROM cols\nWHERE table_name LIKE 'EST%'\nAND column_name LIKE '%CALLREF%';\n</code></pre>\n\n<p>to find all tables having a name beginning with EST and columns containing CALLREF anywhere in their names.</p>\n\n<p>This can help when working out what columns you want to join on, for example, depending on your table and column naming conventions.</p>\n"
},
{
"answer_id": 10320765,
"author": "Mahmoud Ahmed El-Sayed",
"author_id": 1323891,
"author_profile": "https://Stackoverflow.com/users/1323891",
"pm_score": 4,
"selected": false,
"text": "<p>Try the below data dictionary views.</p>\n\n<pre><code>tabs\ndba_tables\nall_tables\nuser_tables\n</code></pre>\n"
},
{
"answer_id": 11946866,
"author": "praveen2609",
"author_id": 1479168,
"author_profile": "https://Stackoverflow.com/users/1479168",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select * from dba_tables\n</code></pre>\n\n<p>gives all the tables of all the users only if the user with which you logged in is having the <code>sysdba</code> privileges.</p>\n"
},
{
"answer_id": 13993788,
"author": "Israel Margulies",
"author_id": 1346806,
"author_profile": "https://Stackoverflow.com/users/1346806",
"pm_score": 5,
"selected": false,
"text": "<p>Simple query to select the tables for the current user:</p>\n\n<pre><code> SELECT table_name FROM user_tables;\n</code></pre>\n"
},
{
"answer_id": 22257585,
"author": "Van Gogh",
"author_id": 3241616,
"author_profile": "https://Stackoverflow.com/users/3241616",
"pm_score": 3,
"selected": false,
"text": "<p>With any of those, you can select:</p>\n\n<pre><code>SELECT DISTINCT OWNER, OBJECT_NAME \n FROM DBA_OBJECTS \n WHERE OBJECT_TYPE = 'TABLE' AND OWNER='SOME_SCHEMA_NAME';\n\nSELECT DISTINCT OWNER, OBJECT_NAME \n FROM ALL_OBJECTS \n WHERE OBJECT_TYPE = 'TABLE' AND OWNER='SOME_SCHEMA_NAME';\n</code></pre>\n"
},
{
"answer_id": 24808745,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 6,
"selected": false,
"text": "<h2>For better viewing with <code>sqlplus</code></h2>\n\n<p>If you're using <code>sqlplus</code> you may want to first set up a few parameters for nicer viewing if your columns are getting mangled (these variables should not persist after you exit your <code>sqlplus</code> session ):</p>\n\n<pre><code>set colsep '|'\nset linesize 167\nset pagesize 30\nset pagesize 1000\n</code></pre>\n\n<h2>Show All Tables</h2>\n\n<p>You can then use something like this to see all table names:</p>\n\n<pre><code>SELECT table_name, owner, tablespace_name FROM all_tables;\n</code></pre>\n\n<h2>Show Tables You Own</h2>\n\n<p>As @Justin Cave mentions, you can use this to show only tables that you own:</p>\n\n<pre><code>SELECT table_name FROM user_tables;\n</code></pre>\n\n<h2>Don't Forget about Views</h2>\n\n<p>Keep in mind that some \"tables\" may actually be \"views\" so you can also try running something like:</p>\n\n<pre><code>SELECT view_name FROM all_views;\n</code></pre>\n\n<h2>The Results</h2>\n\n<p>This should yield something that looks fairly acceptable like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/s0Hb5.png\" alt=\"result\"></p>\n"
},
{
"answer_id": 26253523,
"author": "Harshil",
"author_id": 1636874,
"author_profile": "https://Stackoverflow.com/users/1636874",
"pm_score": 4,
"selected": false,
"text": "<pre><code> select object_name from user_objects where object_type='TABLE';\n</code></pre>\n\n<p>----------------OR------------------</p>\n\n<pre><code> select * from tab;\n</code></pre>\n\n<p>----------------OR------------------</p>\n\n<pre><code> select table_name from user_tables;\n</code></pre>\n"
},
{
"answer_id": 26828225,
"author": "Mateen",
"author_id": 3156006,
"author_profile": "https://Stackoverflow.com/users/3156006",
"pm_score": 2,
"selected": false,
"text": "<p>The following query only list the required data, whereas the other answers gave me the extra data which only confused me.</p>\n\n<pre><code>select table_name from user_tables;\n</code></pre>\n"
},
{
"answer_id": 37936871,
"author": "Prashant Mishra",
"author_id": 4534585,
"author_profile": "https://Stackoverflow.com/users/4534585",
"pm_score": 2,
"selected": false,
"text": "<p>Below is a commented snippet of SQL queries describing how options you can make use of:</p>\n\n<pre><code>-- need to have select catalog role\nSELECT * FROM dba_tables;\n\n-- to see tables of your schema\nSELECT * FROM user_tables;\n\n-- tables inside your schema and tables of other schema which you possess select grants on\nSELECT * FROM all_tables;\n</code></pre>\n"
},
{
"answer_id": 38994090,
"author": "Brahmareddy K",
"author_id": 5721161,
"author_profile": "https://Stackoverflow.com/users/5721161",
"pm_score": 4,
"selected": false,
"text": "<p>Oracle database to display the names of all tables using below query</p>\n\n<pre>\nSELECT owner, table_name FROM dba_tables;\n\nSELECT owner, table_name FROM all_tables;\n\nSELECT table_name FROM user_tables;</pre>\n\n<p>vist more : <a href=\"http://www.plsqlinformation.com/2016/08/get-list-of-all-tables-in-oracle.html\" rel=\"noreferrer\">http://www.plsqlinformation.com/2016/08/get-list-of-all-tables-in-oracle.html</a></p>\n"
},
{
"answer_id": 39945684,
"author": "Slava Babin",
"author_id": 3001523,
"author_profile": "https://Stackoverflow.com/users/3001523",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"https://docs.oracle.com/cd/B10501_01/server.920/a96524/c05dicti.htm\" rel=\"nofollow noreferrer\">Oracle Data Dictionary</a> to get information about oracle objects.</p>\n\n<p>You can get list of tables in different ways:</p>\n\n<pre><code>select * \nfrom dba_tables\n</code></pre>\n\n<p>or for example:</p>\n\n<pre><code>select * \nfrom dba_objects \nwhere object_type = 'TABLE' \n</code></pre>\n\n<p>Then you can get table columns using table name:</p>\n\n<pre><code>select * \nfrom dba_tab_columns\n</code></pre>\n\n<p>Then you can get list of dependencies (triggers, views and etc.):</p>\n\n<pre><code>select * \nfrom dba_dependencies\nwhere referenced_type='TABLE' and referenced_name=:t_name \n</code></pre>\n\n<p>Then you can get text source of this objects:</p>\n\n<pre><code>select * from dba_source\n</code></pre>\n\n<p>And you can use <code>USER</code> or <code>ALL</code> views instead of <code>DBA</code> if you want.</p>\n"
},
{
"answer_id": 40551167,
"author": "Rusty",
"author_id": 2235483,
"author_profile": "https://Stackoverflow.com/users/2235483",
"pm_score": 3,
"selected": false,
"text": "<p>I did not find answer which would point to use </p>\n\n<pre><code>DBA_ALL_TABLES (ALL_ALL_TABLES/USER_ALL_TABLES)\n</code></pre>\n\n<p>so decided to add my version as well.\nThis view actually returns more that DBA_TABLES as it returns object tables as well (<a href=\"http://docs.oracle.com/cd/E11882_01/server.112/e40402/statviews_1003.htm\" rel=\"noreferrer\">http://docs.oracle.com/cd/E11882_01/server.112/e40402/statviews_1003.htm</a>).</p>\n"
},
{
"answer_id": 46931566,
"author": "Punnerud",
"author_id": 2326672,
"author_profile": "https://Stackoverflow.com/users/2326672",
"pm_score": 2,
"selected": false,
"text": "<p>Including views:</p>\n\n<pre><code>SELECT owner, table_name as table_view\n FROM dba_tables\nUNION ALL\nSELECT owner, view_name as table_view\n FROM DBA_VIEWS\n</code></pre>\n"
},
{
"answer_id": 47395677,
"author": "aim_thebest",
"author_id": 1515049,
"author_profile": "https://Stackoverflow.com/users/1515049",
"pm_score": 2,
"selected": false,
"text": "<p>We can get all tables including column details from below query:</p>\n\n<pre><code>SELECT * FROM user_tab_columns;\n</code></pre>\n"
},
{
"answer_id": 49891879,
"author": "Rakesh Narang",
"author_id": 5140709,
"author_profile": "https://Stackoverflow.com/users/5140709",
"pm_score": 1,
"selected": false,
"text": "<p>I was looking to get a list of all columns names belonging to a table of a schema sorted by the order of column id.</p>\n\n<p>Here's the query I am using: -</p>\n\n<pre><code>SELECT COLUMN_NAME\nFROM ALL_TAB_COLUMNS\nWHERE OWNER = 'schema_owner_username' AND TABLE_NAME='table_name'\nORDER BY COLUMN_ID ASC;\n</code></pre>\n"
},
{
"answer_id": 55442651,
"author": "Kaushik Nayak",
"author_id": 7998591,
"author_profile": "https://Stackoverflow.com/users/7998591",
"pm_score": 3,
"selected": false,
"text": "<p>A new feature available in <a href=\"https://www.oracle.com/in/database/technologies/appdev/sqlcl.html\" rel=\"noreferrer\"><strong>SQLcl</strong></a>( which is a free command line interface for Oracle Database) is</p>\n\n<p><strong><code>Tables</code></strong> alias.</p>\n\n<p>Here are few examples showing the usage and additional aspects of the feature. First, connect to a <code>sql</code> command line (<code>sql.exe</code> in windows) session. It is recommended to enter this sqlcl specific command before running any other commands or queries which display data.</p>\n\n<pre><code>SQL> set sqlformat ansiconsole -- resizes the columns to the width of the \n -- data to save space \n</code></pre>\n\n<p><strong><code>SQL> tables</code></strong></p>\n\n<pre><code>TABLES\n-----------\nREGIONS\nLOCATIONS\nDEPARTMENTS\nJOBS\nEMPLOYEES\nJOB_HISTORY\n..\n</code></pre>\n\n<p>To know what the <code>tables</code> alias is referring to, you may simply use <code>alias list <alias></code></p>\n\n<pre><code>SQL> alias list tables\ntables - tables <schema> - show tables from schema\n--------------------------------------------------\n\n select table_name \"TABLES\" from user_tables\n</code></pre>\n\n<p>You don't have to define this alias as it comes by default under SQLcl. If you want to list tables from a specific schema, using a new user-defined alias and passing schema name as a bind argument with only a set of columns being displayed, you may do so using</p>\n\n<p><strong><code>SQL> alias tables_schema = select owner, table_name, last_analyzed from all_tables where owner = :ownr;</code></strong></p>\n\n<p>Thereafter you may simply pass schema name as an argument</p>\n\n<p><strong><code>SQL> tables_schema HR</code></strong></p>\n\n<pre><code>OWNER TABLE_NAME LAST_ANALYZED\nHR DUMMY1 18-10-18\nHR YOURTAB2 16-11-18\nHR YOURTABLE 01-12-18\nHR ID_TABLE 05-12-18\nHR REGIONS 26-05-18\nHR LOCATIONS 26-05-18\nHR DEPARTMENTS 26-05-18\nHR JOBS 26-05-18\nHR EMPLOYEES 12-10-18\n..\n..\n</code></pre>\n\n<p>A more sophisticated pre-defined alias is known as <strong><code>Tables2</code></strong>, which displays several other columns.</p>\n\n<pre><code>SQL> tables2\n\nTables\n======\nTABLE_NAME NUM_ROWS BLOCKS UNFORMATTED_SIZE COMPRESSION INDEX_COUNT CONSTRAINT_COUNT PART_COUNT LAST_ANALYZED\nAN_IP_TABLE 0 0 0 Disabled 0 0 0 > Month\nPARTTABLE 0 0 0 1 0 1 > Month\nTST2 0 0 0 Disabled 0 0 0 > Month\nTST3 0 0 0 Disabled 0 0 0 > Month\nMANAGE_EMPLYEE 0 0 0 Disabled 0 0 0 > Month\nPRODUCT 0 0 0 Disabled 0 0 0 > Month\nALL_TAB_X78EHRYFK 0 0 0 Disabled 0 0 0 > Month\nTBW 0 0 0 Disabled 0 0 0 > Month\nDEPT 0 0 0 Disabled 0 0 0 > Month\n</code></pre>\n\n<p>To know what query it runs in the background, enter</p>\n\n<pre><code>alias list tables2\n</code></pre>\n\n<p>This will show you a slightly more complex query along with predefined <code>column</code> definitions commonly used in SQL*Plus.</p>\n\n<p><em>Jeff Smith</em> explains more about aliases <a href=\"https://www.thatjeffsmith.com/archive/2015/11/object-search-in-sqlcl/\" rel=\"noreferrer\"><strong>here</strong></a> </p>\n"
},
{
"answer_id": 56953868,
"author": "parash",
"author_id": 11701910,
"author_profile": "https://Stackoverflow.com/users/11701910",
"pm_score": 1,
"selected": false,
"text": "<p>Indeed, it is possible to have the list of tables via SQL queries.it is possible to do that also via tools that allow the generation of data dictionaries, such as <a href=\"https://erwin.com/products/erwin-data-modeler/\" rel=\"nofollow noreferrer\">ERWIN</a>, <a href=\"https://www.quest.com/fr-fr/products/toad-data-modeler/#\" rel=\"nofollow noreferrer\">Toad Data Modeler</a> or <a href=\"https://soft-builder.com/en/erbuilder-data-modeler/\" rel=\"nofollow noreferrer\">ERBuilder</a>. With these tools, in addition to table names, you will have fields, their types, objects like(triggers, sequences, domain, views...)</p>\n\n<p>Below steps to follow to generate your tables definition:</p>\n\n<ol>\n<li>You have to reverse engineer your database \n\n<ul>\n<li>In Toad data modeler: Menu -> File -> reverse engineer -> reverse engineering wizard</li>\n<li>In ERBuilder data modeler: Menu -> File -> reverse engineer</li>\n</ul></li>\n</ol>\n\n<p>Your database will be displayed in the software as an Entity Relationship diagram.</p>\n\n<ol start=\"2\">\n<li>Generate your data dictionary that will contain your Tables definition\n\n<ul>\n<li>In Toad data modeler: Menu -> Model -> Generate report -> Run</li>\n<li>In ERBuilder data modeler: Menu -> Tool -> generate model documentation </li>\n</ul></li>\n</ol>\n"
},
{
"answer_id": 59158938,
"author": "dealwithit",
"author_id": 12189197,
"author_profile": "https://Stackoverflow.com/users/12189197",
"pm_score": -1,
"selected": false,
"text": "<pre><code>select * from all_all_tables\n</code></pre>\n\n<p>this additional 'all' at the beginning gives extra 3 columns which are:</p>\n\n<pre><code>OBJECT_ID_TYPE\nTABLE_TYPE_OWNER\nTABLE_TYPE\n</code></pre>\n"
},
{
"answer_id": 62666104,
"author": "The AG",
"author_id": 8692957,
"author_profile": "https://Stackoverflow.com/users/8692957",
"pm_score": 0,
"selected": false,
"text": "<p>To get all the table names, we can use:</p>\n<pre><code>Select owner, table_name from all_tables;\n</code></pre>\n<p>if you have dba permission, you can use:</p>\n<pre><code>Select owner, table_name from dba_tables;\n</code></pre>\n"
},
{
"answer_id": 63919871,
"author": "Prasenjit Mahato",
"author_id": 10282780,
"author_profile": "https://Stackoverflow.com/users/10282780",
"pm_score": 3,
"selected": false,
"text": "<p><b>Execute the below commands:</b></p>\n<p><b>Show all tables in the Oracle Database</b></p>\n<p><code>sql> SELECT table_name FROM dba_tables;</code></p>\n<p><b>Show tables owned by the current user</b></p>\n<p><code>sql> SELECT table_name FROM user_tables;</code></p>\n<p><b>Show tables that are accessible by the current user</b></p>\n<p><code>sql> SELECT table_name FROM all_tables ORDER BY table_name;</code>\n<a href=\"https://i.stack.imgur.com/10au5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/10au5.png\" alt=\"The following picture illustrates the tables that can be returned from the user_tables, all_tables, and dba_tables views:\" /></a></p>\n"
},
{
"answer_id": 64717930,
"author": "Ejrr1085",
"author_id": 2825284,
"author_profile": "https://Stackoverflow.com/users/2825284",
"pm_score": -1,
"selected": false,
"text": "<p>Tables in the current user - logon schema</p>\n<pre><code>select * from tabs;\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1287/"
] |
How do I query an Oracle database to display the names of all tables in it?
|
```
SELECT owner, table_name
FROM dba_tables
```
This is assuming that you have access to the `DBA_TABLES` data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the `SELECT ANY DICTIONARY` privilege or the `SELECT_CATALOG_ROLE` role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like `SYS` and `SYSTEM` which have large numbers of Oracle tables that you probably don't care about.
Alternatively, if you do not have access to `DBA_TABLES`, you can see all the tables that your account has access to through the `ALL_TABLES` view:
```
SELECT owner, table_name
FROM all_tables
```
Although, that may be a subset of the tables available in the database (`ALL_TABLES` shows you the information for all the tables that your user has been granted access to).
If you are only concerned with the tables that you own, not those that you have access to, you could use `USER_TABLES`:
```
SELECT table_name
FROM user_tables
```
Since `USER_TABLES` only has information about the tables that you own, it does not have an `OWNER` column – the owner, by definition, is you.
Oracle also has a number of legacy data dictionary views-- `TAB`, `DICT`, `TABS`, and `CAT` for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the `TAB` and `CAT` views both show information about tables that are in the user's recycle bin while the `[DBA|ALL|USER]_TABLES` views all filter those out. `CAT` also shows information about materialized view logs with a `TABLE_TYPE` of "TABLE" which is unlikely to be what you really want. `DICT` combines tables and synonyms and doesn't tell you who owns the object.
|
205,793 |
<p>I need to make changes to an in-use production database. Just adding a few columns. I've made the changes to the dev database with migrations. What is the best way to update the production database while preserving the existing data and not disrupting operation too much?</p>
<p>It's MYSQL and I will be needing to add data to the columns as well for already existing records. One column can have a default value (it's boolean) but the other is a timestamp and should have an arbitrary backdated value. The row counts are not huge.</p>
<p>So if I use migrations how do I add data and how do I get it to just do the two (or three - I add data -latest migrations on the production db when it wasn't initially built via migrations (I believe they used the schema instead)?</p>
|
[
{
"answer_id": 205823,
"author": "Matt",
"author_id": 17803,
"author_profile": "https://Stackoverflow.com/users/17803",
"pm_score": 2,
"selected": false,
"text": "<p>Is there a reason you are not using the same migrations you used in your dev environment?</p>\n"
},
{
"answer_id": 206330,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 2,
"selected": false,
"text": "<p>Adding a column with <code>add_column</code> in a migration should be non-destructive: it will generate a \"ALTER TABLE\" statement. If you know what you're going to put into the columns once created, you can fill in the values within the migration (you may choose a less time-consuming alternative if the row counts are large).</p>\n\n<p>Removing or altering the definition of a column is, I think, platform-dependent: some will allow deletion of a column in place, others will perform a rename-create-select-drop sequence of commands.</p>\n\n<p>To get more specific, we need more information: what kind of migration are you looking at, what platform are you running on, do you need to set values as part of the migration? Stuff like that would help a lot - just edit the question, which will push it back up the list.</p>\n"
},
{
"answer_id": 207518,
"author": "RichH",
"author_id": 16779,
"author_profile": "https://Stackoverflow.com/users/16779",
"pm_score": 4,
"selected": false,
"text": "<p>I always follow this procedure:</p>\n\n<ul>\n<li>Dump prod database with mysqldump command</li>\n<li>Populate dev / test database with dump using mysql command</li>\n<li>Run migrations in dev / test</li>\n<li>Check migration worked</li>\n<li>Dump prod database with mysqldump command (as it may have changed) keeping backup on server</li>\n<li>Run migrations on prod (using capristano)</li>\n<li>Test migration has worked on prod</li>\n<li>Drink beer (while watching error logs)</li>\n</ul>\n"
},
{
"answer_id": 272673,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 4,
"selected": true,
"text": "<p>It sounds like you're in a state where the production db schema doesn't exactly match what you're using in dev (although it's not totally clear). I would draw a line in the sand, and get that prod db in a better state. Essentially what you want to do is make sure that the prod db has a \"schema_info\" table that lists any migrations that you >don't< ever want to run in production. Then you can add migrations to your hearts content and they'll work against the production db.</p>\n\n<p>Once you've done that you can write migrations that add schema changes or add data, but one thing you need to be really careful about is that if you add data using a migration, you must define the model within the migration itself, like this:</p>\n\n<pre><code>class AddSomeColumnsToUserTable < ActiveRecord::Migration\n class User < ActiveRecord::Base; end\n def self.up\n add_column :users, :super_cool, :boolean, :default => :false\n u = User.find_by_login('cameron')\n u.super_cool = true\n u.save\n end\n\n def self.down\n remove_column :users, :super_cool\n end\nend\n</code></pre>\n\n<p>The reason for this is that in the future, you might remove the model altogether, during some refactoring or other. If you don't define the user class on line \"User.find_by_login...\" the migration will throw an exception which is a big pain.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6805/"
] |
I need to make changes to an in-use production database. Just adding a few columns. I've made the changes to the dev database with migrations. What is the best way to update the production database while preserving the existing data and not disrupting operation too much?
It's MYSQL and I will be needing to add data to the columns as well for already existing records. One column can have a default value (it's boolean) but the other is a timestamp and should have an arbitrary backdated value. The row counts are not huge.
So if I use migrations how do I add data and how do I get it to just do the two (or three - I add data -latest migrations on the production db when it wasn't initially built via migrations (I believe they used the schema instead)?
|
It sounds like you're in a state where the production db schema doesn't exactly match what you're using in dev (although it's not totally clear). I would draw a line in the sand, and get that prod db in a better state. Essentially what you want to do is make sure that the prod db has a "schema\_info" table that lists any migrations that you >don't< ever want to run in production. Then you can add migrations to your hearts content and they'll work against the production db.
Once you've done that you can write migrations that add schema changes or add data, but one thing you need to be really careful about is that if you add data using a migration, you must define the model within the migration itself, like this:
```
class AddSomeColumnsToUserTable < ActiveRecord::Migration
class User < ActiveRecord::Base; end
def self.up
add_column :users, :super_cool, :boolean, :default => :false
u = User.find_by_login('cameron')
u.super_cool = true
u.save
end
def self.down
remove_column :users, :super_cool
end
end
```
The reason for this is that in the future, you might remove the model altogether, during some refactoring or other. If you don't define the user class on line "User.find\_by\_login..." the migration will throw an exception which is a big pain.
|
205,794 |
<p>For my C# RichTextBox, I want to programmatically do the same thing as clicking the up arrow at the top of a vertical scroll bar, which moves the RichTextBox display up by one line. What is the code for this? Thanks!</p>
|
[
{
"answer_id": 205832,
"author": "Ray Jezek",
"author_id": 28309,
"author_profile": "https://Stackoverflow.com/users/28309",
"pm_score": 0,
"selected": false,
"text": "<p>window.scrollBy(0,20); </p>\n\n<p>This will scroll the window. 20 is an approximate value I have used in the past that typically equals one line... but of course font size may impact how far one line really is.</p>\n"
},
{
"answer_id": 205861,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "<p>If you can get the scroll control for the rich text box, you should be able to get its SmallChange property and use that to scroll the text.</p>\n"
},
{
"answer_id": 205904,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 5,
"selected": true,
"text": "<p>Here's what I do:</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern int SendMessage(IntPtr hWnd, uint wMsg, \n UIntPtr wParam, IntPtr lParam);\n</code></pre>\n\n<p>then call:</p>\n\n<pre><code>SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));\n</code></pre>\n\n<p>Seems to work OK - you might need to tweak things a bit, though.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 206216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>For future reference the EM_LINESCROLL message is what you send to any multi-line edit control to set the scroll position. You can scroll vertically or horizontally.\nSee <a href=\"http://msdn.microsoft.com/en-us/library/bb761615(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a> for details.</p>\n\n<p>You can also use the Rich Edit Selection method, where you set the character index (which you can get with EM_LINEINDEX) then call RichEdit.ScrollToCaret ie:</p>\n\n<pre><code>RichEdit.SelectionStart = SendMessage(RichEdit.Handle, EM_LINEINDEX, ScrollTo, 0);\nRichEdit.ScrollToCaret();\n</code></pre>\n\n<p>This will scroll that line to the top of the edit control.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
For my C# RichTextBox, I want to programmatically do the same thing as clicking the up arrow at the top of a vertical scroll bar, which moves the RichTextBox display up by one line. What is the code for this? Thanks!
|
Here's what I do:
```
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,
UIntPtr wParam, IntPtr lParam);
```
then call:
```
SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
```
Seems to work OK - you might need to tweak things a bit, though.
Hope that helps.
|
205,797 |
<p>I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to universal time so I only need an update script. To be accurate, the conversion would need to account for Daylight savings time fluctuations, etc.</p>
|
[
{
"answer_id": 205832,
"author": "Ray Jezek",
"author_id": 28309,
"author_profile": "https://Stackoverflow.com/users/28309",
"pm_score": 0,
"selected": false,
"text": "<p>window.scrollBy(0,20); </p>\n\n<p>This will scroll the window. 20 is an approximate value I have used in the past that typically equals one line... but of course font size may impact how far one line really is.</p>\n"
},
{
"answer_id": 205861,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "<p>If you can get the scroll control for the rich text box, you should be able to get its SmallChange property and use that to scroll the text.</p>\n"
},
{
"answer_id": 205904,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 5,
"selected": true,
"text": "<p>Here's what I do:</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern int SendMessage(IntPtr hWnd, uint wMsg, \n UIntPtr wParam, IntPtr lParam);\n</code></pre>\n\n<p>then call:</p>\n\n<pre><code>SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));\n</code></pre>\n\n<p>Seems to work OK - you might need to tweak things a bit, though.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 206216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>For future reference the EM_LINESCROLL message is what you send to any multi-line edit control to set the scroll position. You can scroll vertically or horizontally.\nSee <a href=\"http://msdn.microsoft.com/en-us/library/bb761615(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a> for details.</p>\n\n<p>You can also use the Rich Edit Selection method, where you set the character index (which you can get with EM_LINEINDEX) then call RichEdit.ScrollToCaret ie:</p>\n\n<pre><code>RichEdit.SelectionStart = SendMessage(RichEdit.Handle, EM_LINEINDEX, ScrollTo, 0);\nRichEdit.ScrollToCaret();\n</code></pre>\n\n<p>This will scroll that line to the top of the edit control.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18313/"
] |
I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to universal time so I only need an update script. To be accurate, the conversion would need to account for Daylight savings time fluctuations, etc.
|
Here's what I do:
```
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,
UIntPtr wParam, IntPtr lParam);
```
then call:
```
SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
```
Seems to work OK - you might need to tweak things a bit, though.
Hope that helps.
|
205,853 |
<p>I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?</p>
<p>(I'm not asking about <code>$('p.foo')</code> syntax that you see in jQuery and others, but normal variables like <code>$name</code> and <code>$order</code>)</p>
|
[
{
"answer_id": 205881,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 0,
"selected": false,
"text": "<p>While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.</p>\n"
},
{
"answer_id": 205974,
"author": "cic",
"author_id": 4771,
"author_profile": "https://Stackoverflow.com/users/4771",
"pm_score": 8,
"selected": false,
"text": "<p>In the 1st, 2nd, and <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf\" rel=\"noreferrer\">3rd Edition of ECMAScript</a>, using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:</p>\n\n<blockquote>\n <p>The dollar sign (<code>$</code>) and the underscore (<code>_</code>) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.</p>\n</blockquote>\n\n<p>However, in the next version (the <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262%205th%20edition%20December%202009.pdf\" rel=\"noreferrer\">5th Edition</a>, which is current), this restriction was dropped, and the above passage replaced with</p>\n\n<blockquote>\n <p>The dollar sign (<code>$</code>) and the underscore (<code>_</code>) are permitted anywhere in an <em>IdentifierName</em>.</p>\n</blockquote>\n\n<p>As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.</p>\n"
},
{
"answer_id": 206843,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 6,
"selected": false,
"text": "<p>As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).</p>\n\n<p>In short you can use the <code>$</code> whenever you want. (The interpreter won't complain.) The question is when do you <i>want</i> to use it?</p>\n\n<p>I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.</p>\n\n<p>For example:</p>\n\n<pre><code>var $get = function(id) { return document.getElementById(id); }\n</code></pre>\n\n<p>That seems like a reasonable convention.</p>\n"
},
{
"answer_id": 553734,
"author": "jonstjohn",
"author_id": 67009,
"author_profile": "https://Stackoverflow.com/users/67009",
"pm_score": 12,
"selected": true,
"text": "<p>Very common use in <strong>jQuery</strong> is to distinguish <strong>jQuery</strong> objects stored in variables from other variables. </p>\n\n<p>For example, I would define:</p>\n\n<pre><code>var $email = $(\"#email\"); // refers to the jQuery object representation of the dom object\nvar email_field = $(\"#email\").get(0); // refers to the dom object itself\n</code></pre>\n\n<p>I find this to be very helpful in writing <strong>jQuery</strong> code and makes it easy to see <strong>jQuery</strong> objects which have a different set of properties.</p>\n"
},
{
"answer_id": 1194902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...</p>\n"
},
{
"answer_id": 1247605,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Stevo is right, the meaning and usage of the dollar script sign (in Javascript and the jQuery platform, but not in PHP) is completely semantic. $ is a character that can be used as part of an identifier name. In addition, the dollar sign is perhaps not the most \"weird\" thing you can encounter in Javascript. Here are some examples of valid identifier names:</p>\n\n<pre><code>var _ = function() { alert(\"hello from _\"); }\nvar \\u0024 = function() { alert(\"hello from $ defined as u0024\"); }\nvar Ø = function() { alert(\"hello from Ø\"); }\nvar $$$$$ = function() { alert(\"hello from $$$$$\"); }\n</code></pre>\n\n<p>All of the examples above will work.</p>\n\n<p>Try them.</p>\n"
},
{
"answer_id": 5066156,
"author": "not-just-yeti",
"author_id": 320830,
"author_profile": "https://Stackoverflow.com/users/320830",
"pm_score": -1,
"selected": false,
"text": "<p>The reason I sometimes use php name-conventions with javascript variables:\nWhen doing input validation, I want to run the exact same algorithms both client-side,\nand server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.</p>\n\n<p>(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)</p>\n"
},
{
"answer_id": 6769114,
"author": "RussellW",
"author_id": 321739,
"author_profile": "https://Stackoverflow.com/users/321739",
"pm_score": -1,
"selected": false,
"text": "<p>If you see the dollar sign ($) or double dollar sign ($$), and are curious as to what this means in the Prototype framework, here is your answer:</p>\n\n<pre><code>$$('div');\n// -> all DIVs in the document. Same as document.getElementsByTagName('div')!\n\n$$('#contents');\n// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).\n\n$$('li.faux');\n// -> all LI elements with class 'faux'\n</code></pre>\n\n<p>Source:<br>\n<a href=\"http://www.prototypejs.org/api/utility/dollar-dollar\" rel=\"nofollow\">http://www.prototypejs.org/api/utility/dollar-dollar</a></p>\n"
},
{
"answer_id": 10211120,
"author": "Manish Jhawar",
"author_id": 1237732,
"author_profile": "https://Stackoverflow.com/users/1237732",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://angularjs.org\" rel=\"nofollow\" title=\"AngularJS\">Angular</a> uses is for properties generated by the framework. Guess, they are going by the (now defunct) hint provided by the ECMA-262 3.0.</p>\n"
},
{
"answer_id": 12206716,
"author": "Travis Watson",
"author_id": 897559,
"author_profile": "https://Stackoverflow.com/users/897559",
"pm_score": 6,
"selected": false,
"text": "<p>In the context of AngularJS, the <code>$</code> prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:</p>\n\n<blockquote>\n <h2>Angular Namespaces <code>$</code> and <code>$$</code></h2>\n \n <p>To prevent accidental name collisions with your code, Angular prefixes names of public objects with <code>$</code> and names of private objects with <code>$$</code>. Please do not use the <code>$</code> or <code>$$</code> prefix in your code.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://docs.angularjs.org/api\">https://docs.angularjs.org/api</a></p>\n"
},
{
"answer_id": 16373014,
"author": "Saurabh Saluja",
"author_id": 1743277,
"author_profile": "https://Stackoverflow.com/users/1743277",
"pm_score": -1,
"selected": false,
"text": "<p>$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables.\nlet you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as \"order\" but if we click on place order then an object is returned that object will be denoted by $ as \"$order\" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.</p>\n"
},
{
"answer_id": 23457623,
"author": "Brett Zamir",
"author_id": 271577,
"author_profile": "https://Stackoverflow.com/users/271577",
"pm_score": 2,
"selected": false,
"text": "<p>Since <code>_</code> at the beginning of a variable name is often used to indicate a private variable (or at least one intended to remain private), I find <code>$</code> convenient for adding in front of my own brief aliases to generic code libraries.</p>\n\n<p>For example, when using jQuery, I prefer to use the variable <code>$J</code> (instead of just <code>$</code>) and use <code>$P</code> when using php.js, etc.</p>\n\n<p>The prefix makes it visually distinct from other variables such as my own static variables, cluing me into the fact that the code is part of some library or other, and is less likely to conflict or confuse others once they know the convention.</p>\n\n<p>It also doesn't clutter the code (or require extra typing) as does a fully specified name repeated for each library call.</p>\n\n<p>I like to think of it as being similar to what modifier keys do for expanding the possibilities of single keys.</p>\n\n<p>But this is just my own convention.</p>\n"
},
{
"answer_id": 28063827,
"author": "Satyabrata Mishra",
"author_id": 4477545,
"author_profile": "https://Stackoverflow.com/users/4477545",
"pm_score": 2,
"selected": false,
"text": "<p><code>${varname}</code> is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.</p>\n\n<p>Plain <code>{varname}</code> is used to store general stuffs like texts and strings.\n<code>${varname}</code> holds elements returned from jQuery.</p>\n\n<p>You can use plain <code>{varname}</code> to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds). </p>\n\n<p>For example :</p>\n\n<pre><code>var $blah = $(this).parents('.blahblah');\n</code></pre>\n\n<p>Here, blah is storing a returned jQuery element.</p>\n\n<p>So, when someone else see the <code>$blah</code> in the code, they'll understand it's not just a string or a number, it's a jQuery element.</p>\n"
},
{
"answer_id": 32416910,
"author": "Naga Srinu Kapusetti",
"author_id": 1676634,
"author_profile": "https://Stackoverflow.com/users/1676634",
"pm_score": 2,
"selected": false,
"text": "<p>As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Ex:\r\nvar name = 'jQuery';\r\nvar lib = {name:'jQuery',version:1.6};\r\n\r\nvar $dataDiv = $('#myDataDiv');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>in the above example when I see the variable \"$dataDiv\" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().</p>\n\n<p>Hope it may helped.\nso finally want to say that it will be a good practice to follow this but not mandatory. </p>\n"
},
{
"answer_id": 33256614,
"author": "Harikesh Yadav",
"author_id": 3690208,
"author_profile": "https://Stackoverflow.com/users/3690208",
"pm_score": -1,
"selected": false,
"text": "<p>A valid JavaScript identifier shuold must start with a letter,\n underscore (_), or dollar sign ($); \n subsequent characters can also\n be digits (0-9). Because JavaScript is case sensitive, \n letters\n include the characters \"A\" through \"Z\" (uppercase) and the\n characters \"a\" through \"z\" (lowercase).</p>\n\n<p>Details:<br>\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables</a></p>\n"
},
{
"answer_id": 48558883,
"author": "Michael Geary",
"author_id": 1202830,
"author_profile": "https://Stackoverflow.com/users/1202830",
"pm_score": 6,
"selected": false,
"text": "<p>I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.</p>\n\n<p>The accepted answer gives this example:</p>\n\n<pre><code>var $email = $(\"#email\"); // refers to the jQuery object representation of the dom object\nvar email_field = $(\"#email\").get(0); // refers to the dom object itself\n</code></pre>\n\n<p>But that doesn't really illustrate it well. Even without the <code>$</code>, we would still have two different variable names here, <code>email</code> and <code>email_field</code>. That's plenty good right there. Why would we need to throw a <code>$</code> into one of the names when we already have two different names?</p>\n\n<p>Actually, I wouldn't have used <code>email_field</code> here for two reasons: <code>names_with_underscores</code> are not idiomatic JavaScript, and <code>field</code> doesn't really make sense for a DOM element. But I did follow the same idea.</p>\n\n<p>I tried a few different things, among them something very similar to the example:</p>\n\n<pre><code>var email = $(\"#email\"), emailElement = $(\"#email\")[0];\n// Now email is a jQuery object and emailElement is the first/only DOM element in it\n</code></pre>\n\n<p>(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of <code>id</code> selectors, so in those cases there was a 1:1 correspondence.)</p>\n\n<p>I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:</p>\n\n<pre><code>// email is a DOM element passed into this function\nfunction doSomethingWithEmail( email ) {\n var emailJQ = $(email);\n // Now email is the DOM element and emailJQ is a jQuery object for it\n}\n</code></pre>\n\n<p>Well that's a little confusing! In one of my bits of code, <code>email</code> is the jQuery object and <code>emailElement</code> is the DOM element, but in the other, <code>email</code> is the DOM element and <code>emailJQ</code> is the jQuery object.</p>\n\n<p>There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides <code>email</code>, <code>emailElement</code>, and <code>emailJQ</code>, I kept trying other variations too.</p>\n\n<p>Then I noticed a common pattern:</p>\n\n<pre><code>var email = $(\"#email\");\nvar emailJQ = $(email);\n</code></pre>\n\n<p>Since JavaScript treats <code>$</code> as simply another letter for names, and since I always got a jQuery object back from a <code>$(whatever)</code> call, the pattern finally dawned on me. I could take a <code>$(...)</code> call and just remove some characters, and it would come up with a pretty nice name:</p>\n\n<pre>\n<code>$<del>(\"#</del>email<del>\")</del></code>\n<code>$<del>(</del>email<del>)</del></code>\n</pre>\n\n<p>Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:</p>\n\n<pre><code>$email\n</code></pre>\n\n<p>That's when I realized I didn't need to make up a convention like <code>emailElement</code> or <code>emailJQ</code>. There was already a nice convention staring at me: take some characters out of a <code>$(whatever)</code> call and it turns into <code>$whatever</code>.</p>\n\n<pre><code>var $email = $(\"#email\"), email = $email[0];\n// $email is the jQuery object and email is the DOM object\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>// email is a DOM element passed into this function\nfunction doSomethingWithEmail( email ) {\n var $email = $(email);\n // $email is the jQuery object and email is the DOM object\n // Same names as in the code above. Yay!\n}\n</code></pre>\n\n<p>So I didn't have to make up two different names all the time but could just use the same name with or without a <code>$</code> prefix. And the <code>$</code> prefix was a nice reminder that I was dealing with a jQuery object:</p>\n\n<pre><code>$('#email').click( ... );\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>var $email = $('#email');\n// Maybe do some other stuff with $email here\n$email.click( ... );\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about `$('p.foo')` syntax that you see in jQuery and others, but normal variables like `$name` and `$order`)
|
Very common use in **jQuery** is to distinguish **jQuery** objects stored in variables from other variables.
For example, I would define:
```
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
```
I find this to be very helpful in writing **jQuery** code and makes it easy to see **jQuery** objects which have a different set of properties.
|
205,911 |
<p>I had a nasty typo that wasted my time and my colleague's time, it was something like this:</p>
<pre><code>for (i = 0; i < blah; i++); // <- I had a semi-colon here, that's the bug!
{
// Some awesome logic here
}
</code></pre>
<p>First of all, it's very embarrassing, second thing, I should never repeat this. I'm relatively new to C. In Java, I guess I can use <a href="http://findbugs.sourceforge.net/" rel="noreferrer">FindBugs</a> to catch errors like these, what tool should I use for C code? Lint?</p>
|
[
{
"answer_id": 205919,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, <a href=\"http://www.gimpel.com/\" rel=\"nofollow noreferrer\">PC-Lint</a> is probably the best tool available.</p>\n"
},
{
"answer_id": 205928,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 2,
"selected": false,
"text": "<p>I would start by learning about <a href=\"http://en.wikipedia.org/wiki/Splint_(programming_tool)\" rel=\"nofollow noreferrer\">splint</a> and <a href=\"http://en.wikipedia.org/wiki/Gdb\" rel=\"nofollow noreferrer\">gdb</a>. If you need more advanced, build on these two tools. But they are a good start.</p>\n"
},
{
"answer_id": 205930,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to <a href=\"https://stackoverflow.com/questions/205911/any-tools-to-catch-silly-mistakes-in-c-code#205919\">Lykathea's PC-Lint suggestion</a>, you can also get better (or at least more) diagnostics if you bump up the warning level of the compiler. Something like <code>/W4</code> or <code>-Wall</code></p>\n\n<p>Though I'm not sure if your particular problem would have been caught with this (MS VC doesn't seem to flag it even with all warnings enabled). I think that's because it's not an uncommon idiom for <code>for</code> loops to be empty when the work is done as side effects of the loop control expressions.</p>\n"
},
{
"answer_id": 205932,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": 0,
"selected": false,
"text": "<p>Any good GUI programming environment (\"IDE\" - Integrated Development Environment) like Eclipse would generate a warning in a case like that.</p>\n"
},
{
"answer_id": 205946,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 2,
"selected": false,
"text": "<p>A few things that have saved me in the past, from the top of my head:</p>\n\n<ul>\n<li><p>Use if <strong>(3 == bla) rather than (bla == 3)</strong>, because if you misspell and type (3 = bla) the compiler will complain.</p></li>\n<li><p>Use the <strong>all-warnings</strong> switch. Your compiler should warn you about empty statements like that.</p></li>\n<li><p>Use <strong>assertions</strong> when you can and program defensively. Put good effort into making your program fail early, you will see the weaknesses that way.</p></li>\n<li><p>Don't try to circumvent any safeguards the compiler or the OS have put in place. They are there for your ease of programming aswell.</p></li>\n</ul>\n"
},
{
"answer_id": 205965,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": -1,
"selected": false,
"text": "<p>In this (old) version of <a href=\"http://www-users.cs.york.ac.uk/susan/joke/foot.htm\" rel=\"nofollow noreferrer\">How to Shoot Yourself In the Foot</a>, and in many other versions around the web, <em>C</em> is always the language that allows for the simplest procedure. When programming in <em>C</em>, you have to remember this and be careful. If you want protection, choose another language.</p>\n\n<p>This saying is <a href=\"http://www.research.att.com/~bs/bs_faq.html#really-say-that\" rel=\"nofollow noreferrer\">attributed</a> to Bjarne Stroustrup (C++) himself. To (mis)quote: </p>\n\n<blockquote>\n <p>\"C makes it easy to shoot yourself in the foot\"</p>\n</blockquote>\n"
},
{
"answer_id": 206072,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 0,
"selected": false,
"text": "<p>A good syntax highlighter will make some cases like this more visible.</p>\n"
},
{
"answer_id": 207247,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 2,
"selected": false,
"text": "<p>GCC has most of the functionality that Lint has had built in via the <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html\" rel=\"nofollow noreferrer\">warning flags</a>.</p>\n"
},
{
"answer_id": 3282490,
"author": "Kortuk",
"author_id": 354753,
"author_profile": "https://Stackoverflow.com/users/354753",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest seeing if you have the ability to <a href=\"http://en.wikipedia.org/wiki/MISRA_C\" rel=\"nofollow noreferrer\">enforce MISRA standards</a>. They were written with great thought and many rules that are simple for a compiler to check. For example, A rule I use requires all NOP commands have their own line. This means when you put a ; on the end of a loop statement it will through an error saying that it is not on it's own line.</p>\n"
},
{
"answer_id": 3997651,
"author": "arsenm",
"author_id": 353253,
"author_profile": "https://Stackoverflow.com/users/353253",
"pm_score": 2,
"selected": false,
"text": "<p>Also look at <a href=\"http://clang-analyzer.llvm.org/\" rel=\"nofollow\">clang static analysis</a></p>\n"
},
{
"answer_id": 6878736,
"author": "Jace Browning",
"author_id": 429533,
"author_profile": "https://Stackoverflow.com/users/429533",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.programmingresearch.com/qac_main.html\" rel=\"nofollow\">QA·C</a> by Programming Research is another good static analysis tool for C.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
] |
I had a nasty typo that wasted my time and my colleague's time, it was something like this:
```
for (i = 0; i < blah; i++); // <- I had a semi-colon here, that's the bug!
{
// Some awesome logic here
}
```
First of all, it's very embarrassing, second thing, I should never repeat this. I'm relatively new to C. In Java, I guess I can use [FindBugs](http://findbugs.sourceforge.net/) to catch errors like these, what tool should I use for C code? Lint?
|
Yes, [PC-Lint](http://www.gimpel.com/) is probably the best tool available.
|
205,923 |
<p>We have a high security application and we want to allow users to enter URLs that other users will see.</p>
<p>This introduces a high risk of XSS hacks - a user could potentially enter javascript that another user ends up executing. Since we hold sensitive data it's essential that this never happens.</p>
<p>What are the best practices in dealing with this? Is any security whitelist or escape pattern alone good enough? </p>
<p>Any advice on dealing with redirections ("this link goes outside our site" message on a warning page before following the link, for instance)</p>
<p>Is there an argument for not supporting user entered links at all?</p>
<hr>
<p>Clarification:</p>
<p>Basically our users want to input: </p>
<blockquote>
<p>stackoverflow.com</p>
</blockquote>
<p>And have it output to another user:</p>
<pre><code><a href="http://stackoverflow.com">stackoverflow.com</a>
</code></pre>
<p>What I really worry about is them using this in a XSS hack. I.e. they input:</p>
<blockquote>
<p>alert('hacked!');</p>
</blockquote>
<p>So other users get this link:</p>
<pre><code><a href="javascript:alert('hacked!');">stackoverflow.com</a>
</code></pre>
<p>My example is just to explain the risk - I'm well aware that javascript and URLs are different things, but by letting them input the latter they may be able to execute the former.</p>
<p>You'd be amazed how many sites you can break with this trick - HTML is even worse. If they know to deal with links do they also know to sanitise <code><iframe></code>, <code><img></code> and clever CSS references?</p>
<p>I'm working in a high security environment - a single XSS hack could result in very high losses for us. I'm happy that I could produce a Regex (or use one of the excellent suggestions so far) that could exclude everything that I could think of, but would that be enough?</p>
|
[
{
"answer_id": 205924,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": -1,
"selected": false,
"text": "<p>Allowing a URL and allowing JavaScript are 2 different things.</p>\n"
},
{
"answer_id": 205929,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>How about not displaying them as a link? Just use the text.</p>\n\n<p>Combined with a warning to proceed at your own risk may be enough.</p>\n\n<p><strong>addition</strong> - see also <a href=\"https://stackoverflow.com/questions/176195/for-hosted-applications-should-i-be-sanitizing\">Should I sanitize HTML markup for a hosted CMS?</a> for a discussion on sanitizing user input</p>\n"
},
{
"answer_id": 205938,
"author": "balexandre",
"author_id": 28004,
"author_profile": "https://Stackoverflow.com/users/28004",
"pm_score": 2,
"selected": false,
"text": "<p>You don't specify the language of your application, I will then presume ASP.NET, and for this you can use the <a href=\"http://msdn.microsoft.com/en-us/security/aa973814.aspx\" rel=\"nofollow noreferrer\">Microsoft Anti-Cross Site Scripting Library</a></p>\n\n<p>It is very easy to use, all you need is an include and that is it :)</p>\n\n<p>While you're on the topic, why not given a read on <a href=\"http://msdn.microsoft.com/en-us/library/aa302420.aspx\" rel=\"nofollow noreferrer\">Design Guidelines for Secure Web Applications</a></p>\n\n<p>If any other language.... if there is a library for ASP.NET, has to be available as well for other kind of language (PHP, Python, ROR, etc)</p>\n"
},
{
"answer_id": 205967,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 7,
"selected": true,
"text": "<p>If you think URLs can't contain code, think again!</p>\n<p><a href=\"https://owasp.org/www-community/xss-filter-evasion-cheatsheet\" rel=\"noreferrer\">https://owasp.org/www-community/xss-filter-evasion-cheatsheet</a></p>\n<p>Read that, and weep.</p>\n<p>Here's how we do it on Stack Overflow:</p>\n<pre><code>/// <summary>\n/// returns "safe" URL, stripping anything outside normal charsets for URL\n/// </summary>\npublic static string SanitizeUrl(string url)\n{\n return Regex.Replace(url, @"[^-A-Za-z0-9+&@#/%?=~_|!:,.;\\(\\)]", "");\n}\n</code></pre>\n"
},
{
"answer_id": 205968,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 2,
"selected": false,
"text": "<p>Just HTMLEncode the links when you output them. Make sure you don't allow <code>javascript:</code> links. (It's best to have a whitelist of protocols that are accepted, e.g., http, https, and mailto.)</p>\n"
},
{
"answer_id": 210083,
"author": "Bell",
"author_id": 28158,
"author_profile": "https://Stackoverflow.com/users/28158",
"pm_score": 4,
"selected": false,
"text": "<p>The process of rendering a link \"safe\" should go through three or four steps:</p>\n\n<ul>\n<li>Unescape/re-encode the string you've been given (RSnake has documented a number of tricks at <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\"><a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">http://ha.ckers.org/xss.html</a></a> that use escaping and UTF encodings).</li>\n<li>Clean the link up: Regexes are a good start - make sure to truncate the string or throw it away if it contains a \" (or whatever you use to close the attributes in your output); If you're doing the links only as references to other information you can also force the protocol at the end of this process - if the portion before the first colon is not 'http' or 'https' then append 'http://' to the start. This allows you to create usable links from incomplete input as a user would type into a browser and gives you a last shot at tripping up whatever mischief someone has tried to sneak in.</li>\n<li>Check that the result is a well formed URL (protocol://host.domain[:port][/path][/[file]][?queryField=queryValue][#anchor]).</li>\n<li>Possibly check the result against a site blacklist or try to fetch it through some sort of malware checker.</li>\n</ul>\n\n<p>If security is a priority I would hope that the users would forgive a bit of paranoia in this process, even if it does end up throwing away some safe links.</p>\n"
},
{
"answer_id": 15825812,
"author": "Dave Jarvis",
"author_id": 59087,
"author_profile": "https://Stackoverflow.com/users/59087",
"pm_score": 4,
"selected": false,
"text": "<p>Use a library, such as OWASP-ESAPI API:</p>\n\n<ul>\n<li>PHP - <a href=\"http://code.google.com/p/owasp-esapi-php/\" rel=\"noreferrer\">http://code.google.com/p/owasp-esapi-php/</a></li>\n<li>Java - <a href=\"http://code.google.com/p/owasp-esapi-java/\" rel=\"noreferrer\">http://code.google.com/p/owasp-esapi-java/</a></li>\n<li>.NET - <a href=\"http://code.google.com/p/owasp-esapi-dotnet/\" rel=\"noreferrer\">http://code.google.com/p/owasp-esapi-dotnet/</a></li>\n<li>Python - <a href=\"http://code.google.com/p/owasp-esapi-python/\" rel=\"noreferrer\">http://code.google.com/p/owasp-esapi-python/</a></li>\n</ul>\n\n<p>Read the following:</p>\n\n<ul>\n<li><a href=\"https://www.golemtechnologies.com/articles/prevent-xss#how-to-prevent-cross-site-scripting\" rel=\"noreferrer\">https://www.golemtechnologies.com/articles/prevent-xss#how-to-prevent-cross-site-scripting</a></li>\n<li><a href=\"https://www.owasp.org/\" rel=\"noreferrer\">https://www.owasp.org/</a></li>\n<li><a href=\"http://www.secbytes.com/blog/?p=253\" rel=\"noreferrer\">http://www.secbytes.com/blog/?p=253</a></li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>$url = \"http://stackoverflow.com\"; // e.g., $_GET[\"user-homepage\"];\n$esapi = new ESAPI( \"/etc/php5/esapi/ESAPI.xml\" ); // Modified copy of ESAPI.xml\n$sanitizer = ESAPI::getSanitizer();\n$sanitized_url = $sanitizer->getSanitizedURL( \"user-homepage\", $url );\n</code></pre>\n\n<p>Another example is to use a built-in function. PHP's <a href=\"http://svn.php.net/viewvc/php/php-src/trunk/ext/filter/logical_filters.c?view=markup\" rel=\"noreferrer\">filter_var</a> function is an example:</p>\n\n<pre><code>$url = \"http://stackoverflow.com\"; // e.g., $_GET[\"user-homepage\"];\n$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);\n</code></pre>\n\n<p>Using <code>filter_var</code> <a href=\"http://www.hashbangcode.com/examples/filter_var_url_validate/\" rel=\"noreferrer\">allows</a> javascript calls, and filters out schemes that are neither <code>http</code> nor <code>https</code>. Using the <a href=\"https://code.google.com/p/owasp-esapi-php/source/browse/trunk/src/Sanitizer.php\" rel=\"noreferrer\">OWASP ESAPI Sanitizer</a> is probably the best option.</p>\n\n<p>Still another example is the code from <a href=\"http://codex.wordpress.org/Function_Reference/esc_url\" rel=\"noreferrer\">WordPress</a>:</p>\n\n<ul>\n<li><a href=\"http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/formatting.php#L2561\" rel=\"noreferrer\">http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/formatting.php#L2561</a></li>\n</ul>\n\n<p>Additionally, since there is no way of knowing where the URL links (i.e., it might be a valid URL, but the contents of the URL could be mischievous), Google has a <a href=\"https://developers.google.com/safe-browsing/\" rel=\"noreferrer\">safe browsing</a> API you can call:</p>\n\n<ul>\n<li><a href=\"https://developers.google.com/safe-browsing/lookup_guide\" rel=\"noreferrer\">https://developers.google.com/safe-browsing/lookup_guide</a></li>\n</ul>\n\n<p>Rolling your own regex for sanitation is problematic for several reasons:</p>\n\n<ul>\n<li>Unless you are Jon Skeet, the code will have errors.</li>\n<li>Existing APIs have many hours of review and testing behind them.</li>\n<li>Existing URL-validation APIs consider internationalization.</li>\n<li>Existing APIs will be kept up-to-date with emerging standards.</li>\n</ul>\n\n<p>Other issues to consider:</p>\n\n<ul>\n<li>What schemes do you permit (are <code>file:///</code> and <code>telnet://</code> acceptable)?</li>\n<li>What restrictions do you want to place on the content of the URL (are malware URLs acceptable)?</li>\n</ul>\n"
},
{
"answer_id": 17876271,
"author": "Shashi",
"author_id": 2075365,
"author_profile": "https://Stackoverflow.com/users/2075365",
"pm_score": -1,
"selected": false,
"text": "<p>You could use a hex code to convert the entire URL and send it to your server. That way the client would not understand the content in the first glance. After reading the content, you could decode the content URL = ? and send it to the browser.</p>\n"
},
{
"answer_id": 52804099,
"author": "jcubic",
"author_id": 387194,
"author_profile": "https://Stackoverflow.com/users/387194",
"pm_score": 0,
"selected": false,
"text": "<p>In my project written in JavaScript I use this regex as white list:</p>\n\n<pre><code> url.match(/^((https?|ftp):\\/\\/|\\.{0,2}\\/)/)\n</code></pre>\n\n<p>the only limitation is that you need to put ./ in front for files in same directory but I think I can live with that.</p>\n"
},
{
"answer_id": 55206109,
"author": "Zach Valenta",
"author_id": 6813490,
"author_profile": "https://Stackoverflow.com/users/6813490",
"pm_score": 2,
"selected": false,
"text": "<p>For Pythonistas, try Scrapy's <a href=\"https://github.com/scrapy/w3lib\" rel=\"nofollow noreferrer\">w3lib</a>.</p>\n\n<p><a href=\"https://www.owasp.org/index.php/ESAPI_Python_Readme\" rel=\"nofollow noreferrer\">OWASP ESAPI pre-dates Python 2.7</a> and is archived on the <a href=\"https://en.wikipedia.org/wiki/Google_Developers#Google_Code\" rel=\"nofollow noreferrer\">now-defunct Google Code</a>.</p>\n"
},
{
"answer_id": 69307257,
"author": "babakansari",
"author_id": 3621442,
"author_profile": "https://Stackoverflow.com/users/3621442",
"pm_score": 0,
"selected": false,
"text": "<p>Using Regular Expression to prevent XSS vulnerability is becoming complicated thus hard to maintain over time while it could leave some vulnerabilities behind. Having URL validation using regular expression is helpful in some scenarios but better not be mixed with vulnerability checks.</p>\n<p>Solution probably is to use combination of an encoder like <code>AntiXssEncoder.UrlEncode</code> for encoding Query portion of the URL and <code>QueryBuilder</code> for the rest:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code> public sealed class AntiXssUrlEncoder\n {\n public string EncodeUri(Uri uri, bool isEncoded = false)\n {\n // Encode the Query portion of URL to prevent XSS attack if is not already encoded. Otherwise let UriBuilder take care code it.\n var encodedQuery = isEncoded ? uri.Query.TrimStart('?') : AntiXssEncoder.UrlEncode(uri.Query.TrimStart('?'));\n var encodedUri = new UriBuilder\n {\n Scheme = uri.Scheme,\n Host = uri.Host,\n Path = uri.AbsolutePath,\n Query = encodedQuery.Trim(),\n Fragment = uri.Fragment\n };\n if (uri.Port != 80 && uri.Port != 443)\n {\n encodedUri.Port = uri.Port;\n }\n\n return encodedUri.ToString();\n }\n\n public static string Encode(string uri)\n {\n var baseUri = new Uri(uri);\n var antiXssUrlEncoder = new AntiXssUrlEncoder();\n return antiXssUrlEncoder.EncodeUri(baseUri);\n }\n }\n</code></pre>\n<p>You may need to include white listing to exclude some characters from encoding. That could become helpful for particular sites.\nHTML Encoding the page that render the URL is another thing you may need to consider too.</p>\n<p><strong>BTW</strong>. Please note that encoding URL may break <a href=\"https://owasp.org/www-community/attacks/Web_Parameter_Tampering\" rel=\"nofollow noreferrer\">Web Parameter Tampering</a> so the encoded link may appear not working as expected.\nAlso, you need to be careful about double encoding</p>\n<p><em>P.S. <code>AntiXssEncoder.UrlEncode</code> was better be named <code>AntiXssEncoder.EncodeForUrl</code> to be more descriptive. Basically, It encodes a string for URL not encode a given URL and return usable URL.</em></p>\n"
},
{
"answer_id": 69492063,
"author": "happy_cutman",
"author_id": 10933150,
"author_profile": "https://Stackoverflow.com/users/10933150",
"pm_score": 1,
"selected": false,
"text": "<p>There is a library for javascript that solves this problem\n<a href=\"https://github.com/braintree/sanitize-url\" rel=\"nofollow noreferrer\">https://github.com/braintree/sanitize-url</a>\nTry it =)</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
We have a high security application and we want to allow users to enter URLs that other users will see.
This introduces a high risk of XSS hacks - a user could potentially enter javascript that another user ends up executing. Since we hold sensitive data it's essential that this never happens.
What are the best practices in dealing with this? Is any security whitelist or escape pattern alone good enough?
Any advice on dealing with redirections ("this link goes outside our site" message on a warning page before following the link, for instance)
Is there an argument for not supporting user entered links at all?
---
Clarification:
Basically our users want to input:
>
> stackoverflow.com
>
>
>
And have it output to another user:
```
<a href="http://stackoverflow.com">stackoverflow.com</a>
```
What I really worry about is them using this in a XSS hack. I.e. they input:
>
> alert('hacked!');
>
>
>
So other users get this link:
```
<a href="javascript:alert('hacked!');">stackoverflow.com</a>
```
My example is just to explain the risk - I'm well aware that javascript and URLs are different things, but by letting them input the latter they may be able to execute the former.
You'd be amazed how many sites you can break with this trick - HTML is even worse. If they know to deal with links do they also know to sanitise `<iframe>`, `<img>` and clever CSS references?
I'm working in a high security environment - a single XSS hack could result in very high losses for us. I'm happy that I could produce a Regex (or use one of the excellent suggestions so far) that could exclude everything that I could think of, but would that be enough?
|
If you think URLs can't contain code, think again!
<https://owasp.org/www-community/xss-filter-evasion-cheatsheet>
Read that, and weep.
Here's how we do it on Stack Overflow:
```
/// <summary>
/// returns "safe" URL, stripping anything outside normal charsets for URL
/// </summary>
public static string SanitizeUrl(string url)
{
return Regex.Replace(url, @"[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]", "");
}
```
|
205,950 |
<p>I'm writing SQL (for Oracle) like:</p>
<pre>
INSERT INTO Schema1.tableA SELECT * FROM Schema2.tableA;
</pre>
<p>where Schema1.tableA and Schema2.tableA have the same columns. However, it seems like this is unsafe, since the order of the columns coming back in the SELECT is undefined. What I should be doing is:</p>
<pre>
INSERT INTO Schema1.tableA (col1, col2, ... colN)
SELECT (col1, col2, ... colN) FROM Schema2.tableA;
</pre>
<p>I'm doing this for lots of tables using some scripts, so what I'd like to do is write something like:</p>
<pre>
INSERT INTO Schema1.tableA (foo(Schema1.tableA))
SELECT (foo(Schema1.tableA)) FROM Schema2.tableA;
</pre>
<p>Where foo is some nifty magic that extracts the column names from table one and packages them in the appropriate syntax. Thoughts?</p>
|
[
{
"answer_id": 205971,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": 1,
"selected": false,
"text": "<p>You may need to construct the insert statements dynamically using <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_5429.htm#REFRN26277\" rel=\"nofollow noreferrer\">USER_TAB_COLUMNS</a> and execute them using <a href=\"http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/executeimmediate_statement.htm#LNPLS01317\" rel=\"nofollow noreferrer\">EXECUTE IMMEDIATE</a>.</p>\n"
},
{
"answer_id": 206102,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "<p>This PL/SQL should do it:</p>\n\n<pre><code>declare\n l_cols long;\n l_sql long;\nbegin\n for r in (select column_name from all_tab_columns\n where table_name = 'TABLEA'\n and owner = 'SCHEMA1'\n )\n loop\n l_cols := l_cols || ',' || r.column_name;\n end loop;\n\n -- Remove leading comma\n l_cols := substr(l_cols, 2);\n\n l_sql := 'insert into schema1.tableA (' || l_cols || ') select ' \n || l_cols || ' from schema2.tableA';\n\n execute immediate l_sql;\n\nend;\n/\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25915/"
] |
I'm writing SQL (for Oracle) like:
```
INSERT INTO Schema1.tableA SELECT * FROM Schema2.tableA;
```
where Schema1.tableA and Schema2.tableA have the same columns. However, it seems like this is unsafe, since the order of the columns coming back in the SELECT is undefined. What I should be doing is:
```
INSERT INTO Schema1.tableA (col1, col2, ... colN)
SELECT (col1, col2, ... colN) FROM Schema2.tableA;
```
I'm doing this for lots of tables using some scripts, so what I'd like to do is write something like:
```
INSERT INTO Schema1.tableA (foo(Schema1.tableA))
SELECT (foo(Schema1.tableA)) FROM Schema2.tableA;
```
Where foo is some nifty magic that extracts the column names from table one and packages them in the appropriate syntax. Thoughts?
|
This PL/SQL should do it:
```
declare
l_cols long;
l_sql long;
begin
for r in (select column_name from all_tab_columns
where table_name = 'TABLEA'
and owner = 'SCHEMA1'
)
loop
l_cols := l_cols || ',' || r.column_name;
end loop;
-- Remove leading comma
l_cols := substr(l_cols, 2);
l_sql := 'insert into schema1.tableA (' || l_cols || ') select '
|| l_cols || ' from schema2.tableA';
execute immediate l_sql;
end;
/
```
|
205,977 |
<p><a href="https://stackoverflow.com/questions/205887/postback-security">Related Article</a></p>
<p>On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?</p>
|
[
{
"answer_id": 206101,
"author": "balexandre",
"author_id": 28004,
"author_profile": "https://Stackoverflow.com/users/28004",
"pm_score": 0,
"selected": false,
"text": "<p>why not validating onChange even in the dropdownlist?</p>\n\n<p>just add the script manager and add that property to the onchange in the Page_Load event</p>\n\n<pre>\n' Creating the javascript function to validate\nDim js As String\njs = \"function validateDDL1(ddl) { alert(ddl.value); }\"\n\n' Adding onChange javascript method\nDropDownList1.Attributes.Add(\"onchange\", \"validateDDL1(this);\")\n\n' Registering the javascript\nScriptManager.RegisterClientScriptBlock(Me, GetType(String), \"validateDDL1(ddl)\", js, True)\n</pre>\n"
},
{
"answer_id": 206471,
"author": "bashmohandes",
"author_id": 28120,
"author_profile": "https://Stackoverflow.com/users/28120",
"pm_score": 1,
"selected": false,
"text": "<p>You can call the Page_Validate() function from your javascript code, it will trigger the asp.net validators on the page, it is basically similar to Page.Validate() in server code</p>\n"
},
{
"answer_id": 206503,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": true,
"text": "<p>You're not validating the dropdown list are you? You're validating the value a user selected. It's pretty much the same advice as the other post, since javascript or other tools can alter the html or create their own POST's, you <em>must always</em> validate on the server side. Assume all client requests can be tampered with, and assume that no client-side validation has occurred.</p>\n\n<hr>\n\n<p>If you're using the web forms model ....</p>\n\n<p>If you just want to check a value was selected in the dropdown <code>myAjaxDropDown</code>, use the </p>\n\n<pre><code><asp:RequiredFieldValidator id=\"dropdownRequiredFieldValidator\"\n ControlToValidate=\"myAjaxDropDown\"\n Display=\"Static\"\n InitialValue=\"\" runat=server>\n *\n </asp:RequiredFieldValidator>\n</code></pre>\n\n<p>You could also want to look at the asp:CustomValidator - for server side validation:</p>\n\n<pre><code><asp:CustomValidator ID=\"myCustomValidator\" runat=\"server\" \n onservervalidate=\"myCustomValidator_ServerValidate\" \n ErrorMessage=\"Bad Value\" />\n</code></pre>\n\n<p>Both plug into the validation framework of asp.net. e.g. when you click a button called <code>SumbitButton</code></p>\n\n<pre><code>protected void myCustomValidator_ServerValidate(object source, ServerValidateEventArgs e)\n{\n // determine validity for this custom validator\n e.IsValid = DropdownValueInRange(myAjaxDropDown.SelectedItem.Value); \n}\n\nprotected void SubmitButton_Click( object source, EventArgs e )\n{\n Validate(); \n if( !IsValid )\n return;\n\n // validators pass. Continue processing.\n}\n</code></pre>\n\n<p>Some links for further reading:</p>\n\n<ul>\n<li><a href=\"http://quickstart.developerfusion.co.uk/QuickStart/aspnet/doc/validation/default.aspx\" rel=\"nofollow noreferrer\">ASP.Net 2.0 Quickstart - Validating Form Input Controls</a></li>\n<li><a href=\"http://www.dotnetcurry.com/ShowArticle.aspx?ID=121&AspxAutoDetectCookieSupport=1\" rel=\"nofollow noreferrer\">ASP.NET Validation Controls – Important Points, Tips and Tricks</a></li>\n</ul>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8873/"
] |
[Related Article](https://stackoverflow.com/questions/205887/postback-security)
On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?
|
You're not validating the dropdown list are you? You're validating the value a user selected. It's pretty much the same advice as the other post, since javascript or other tools can alter the html or create their own POST's, you *must always* validate on the server side. Assume all client requests can be tampered with, and assume that no client-side validation has occurred.
---
If you're using the web forms model ....
If you just want to check a value was selected in the dropdown `myAjaxDropDown`, use the
```
<asp:RequiredFieldValidator id="dropdownRequiredFieldValidator"
ControlToValidate="myAjaxDropDown"
Display="Static"
InitialValue="" runat=server>
*
</asp:RequiredFieldValidator>
```
You could also want to look at the asp:CustomValidator - for server side validation:
```
<asp:CustomValidator ID="myCustomValidator" runat="server"
onservervalidate="myCustomValidator_ServerValidate"
ErrorMessage="Bad Value" />
```
Both plug into the validation framework of asp.net. e.g. when you click a button called `SumbitButton`
```
protected void myCustomValidator_ServerValidate(object source, ServerValidateEventArgs e)
{
// determine validity for this custom validator
e.IsValid = DropdownValueInRange(myAjaxDropDown.SelectedItem.Value);
}
protected void SubmitButton_Click( object source, EventArgs e )
{
Validate();
if( !IsValid )
return;
// validators pass. Continue processing.
}
```
Some links for further reading:
* [ASP.Net 2.0 Quickstart - Validating Form Input Controls](http://quickstart.developerfusion.co.uk/QuickStart/aspnet/doc/validation/default.aspx)
* [ASP.NET Validation Controls – Important Points, Tips and Tricks](http://www.dotnetcurry.com/ShowArticle.aspx?ID=121&AspxAutoDetectCookieSupport=1)
|
205,986 |
<p>I'm using the following syntax to loop through a list collection:</p>
<pre><code>For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors
i = IndexOf(PropertyActor)
Next
</code></pre>
<p>How do I get the index of the current object within the loop? I'm using IndexOf(PropertyActor) but this seems inefficient as it searches the collection when I already have the object available!</p>
|
[
{
"answer_id": 205994,
"author": "sebagomez",
"author_id": 23893,
"author_profile": "https://Stackoverflow.com/users/23893",
"pm_score": 2,
"selected": false,
"text": "<p>just initialize an integer variable before entering the loop and iterate it...</p>\n\n<pre><code>Dim i as Integer \nFor Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors\n i++\nNext\n</code></pre>\n"
},
{
"answer_id": 205995,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 1,
"selected": false,
"text": "<p>Add an index variable that you increase yourself for each iteration?</p>\n"
},
{
"answer_id": 205997,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": false,
"text": "<p>AFAIK since this pulls the object out of the collection, you would have to go back to the collection to find it.</p>\n\n<p>If you need the index, rather than using a for each loop, I would just use a for loop that went through the indices so you know what you have.</p>\n"
},
{
"answer_id": 206000,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>It might be easiest to just keep a separate counter:</p>\n\n<pre><code>i = 0\nFor Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors\n ...\n i = i + 1\nNext\n</code></pre>\n\n<p>As an aside, Python has a convenient way of doing this:</p>\n\n<pre><code>for i, x in enumerate(a):\n print \"object at index \", i, \" is \", x\n</code></pre>\n"
},
{
"answer_id": 206007,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>An index doesn't have any meaning to an IEnumerable, which is what the foreach construct uses. That's important because <code>foreach</code> may not enumerate in index order, if your particular collection type implements IEnumerable in an odd way. If you have an object that can be accessed by index <em>and</em> you care about the index during an iteration, then you're better off just using a traditional for loop:</p>\n\n<pre><code>for (int i=0;i<MyProperty.PropertyActors.Length;i++)\n{\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 206069,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 1,
"selected": false,
"text": "<p>You could use the \"FindIndex\" method.</p>\n\n<pre><code>MyProperty.PropertyActors.FindIndex(Function(propActor As JCPropertyActor) propActor = JCPropertyActor)\n</code></pre>\n\n<p>But inside of a for each loop that seems like alot of extra overhead, and seems like the same resulting problem as the \"IndexOf\" method. I suggest using old fashioned index iteration. This way you have your index and your item.</p>\n\n<pre><code>Dim PropertyActor As JCPropertyActor\nFor i As Integer = 0 To MyProperty.PropertyActors.Count - 1\n PropertyActor = MyProperty.PropertyActors.Item(i)\nNext\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20048/"
] |
I'm using the following syntax to loop through a list collection:
```
For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors
i = IndexOf(PropertyActor)
Next
```
How do I get the index of the current object within the loop? I'm using IndexOf(PropertyActor) but this seems inefficient as it searches the collection when I already have the object available!
|
An index doesn't have any meaning to an IEnumerable, which is what the foreach construct uses. That's important because `foreach` may not enumerate in index order, if your particular collection type implements IEnumerable in an odd way. If you have an object that can be accessed by index *and* you care about the index during an iteration, then you're better off just using a traditional for loop:
```
for (int i=0;i<MyProperty.PropertyActors.Length;i++)
{
//...
}
```
|
206,009 |
<p>I have SQL data that looks like this:</p>
<pre><code>events
id name capacity
1 Cooking 10
2 Swimming 20
3 Archery 15
registrants
id name
1 Jimmy
2 Billy
3 Sally
registrant_event
registrant_id event_id
1 3
2 3
3 2
</code></pre>
<p>I would like to select all of the fields in 'events' as well as an additional field that is the number of people who are currently registered for that event. In this case Archery would have 2 registrants, Swimming would have 1, and Cooking would have 0.</p>
<p>I imagine this could be accomplished in a single query but I'm not sure of the correct syntax. <strong>How would a query be written to get that data?</strong></p>
|
[
{
"answer_id": 206017,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT e.*, ISNULL(ec.TotalRegistrants, 0) FROM events e LEFT OUTER JOIN\n(\n SELECT event_id, Count(registrant_id) AS TotalRegistrants\n FROM registrant_event\n GROUP BY event_id\n) ec ON e.id = ec.event_id\n</code></pre>\n"
},
{
"answer_id": 206028,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT Events.ID, Events.Name, Events.Capacity, \n ISNULL(COUNT(Registrant_Event.Registrant_ID), 0)\nFROM Events\nLEFT OUTER JOIN Registrant_Event ON Events.ID = Registrant_Event.Event_ID\nGROUP BY Events.ID, Events.Name, Events.Capacity\n</code></pre>\n"
},
{
"answer_id": 206029,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select e.id, e.name, e.capacity, IsNull(re.eventCount,0) from events e\nleft join (\n select count(event_id) as eventCount, event_id from registrant_event group by event_id\n ) re \non e.id = re.event_id</code></pre>\n"
},
{
"answer_id": 206030,
"author": "Jacco",
"author_id": 22674,
"author_profile": "https://Stackoverflow.com/users/22674",
"pm_score": -1,
"selected": false,
"text": "<pre><code>SELECT\n events.*\n, COUNT(registrant_event.registrant_id) AS registrantsCount\nFROM events\nLEFT JOIN registrant_event ON events.id = registrant_event.event_id\nGROUP BY events.id\n</code></pre>\n"
},
{
"answer_id": 206033,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<pre><code>SELECT e.id, count(*) AS NumRegistrants\nFROM events e\nLEFT JOIN registrant_event re ON re.event_id=e.id\nGROUP BY e.id\n</code></pre>\n\n<p>Note that this will return 1 instead of 0 for events with no registrants. To get it to show 0 instead, you have to get a little more complicated:</p>\n\n<pre><code>SELECT *,\n (SELECT COUNT(*) FROM registrant_event WHERE event_id=id) AS NumRegistrants\nFROM events\n</code></pre>\n"
},
{
"answer_id": 206090,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<p>I tested this in Oracle 11g, and it seems to work</p>\n\n<pre><code>SELECT e.id, e.name, e.capacity, COUNT(re.event_id)\nFROM events e\nLEFT JOIN registrant_event re\n ON e.id = re.event_id\nGROUP BY e.id, e.name, e.capacity\n</code></pre>\n"
},
{
"answer_id": 5074928,
"author": "majesty",
"author_id": 627836,
"author_profile": "https://Stackoverflow.com/users/627836",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select d.id1, d.name, d.cappacity, count(d.b_id) as number_of_people\nfrom (select eve.id1,eve.name,eve.cappacity,re_eve.b_id\n from eve left join re_eve on eve.id1 = re_eve.b_id) d\ngroup by d.id1, d.name, d.cappacity\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
] |
I have SQL data that looks like this:
```
events
id name capacity
1 Cooking 10
2 Swimming 20
3 Archery 15
registrants
id name
1 Jimmy
2 Billy
3 Sally
registrant_event
registrant_id event_id
1 3
2 3
3 2
```
I would like to select all of the fields in 'events' as well as an additional field that is the number of people who are currently registered for that event. In this case Archery would have 2 registrants, Swimming would have 1, and Cooking would have 0.
I imagine this could be accomplished in a single query but I'm not sure of the correct syntax. **How would a query be written to get that data?**
|
```
SELECT e.*, ISNULL(ec.TotalRegistrants, 0) FROM events e LEFT OUTER JOIN
(
SELECT event_id, Count(registrant_id) AS TotalRegistrants
FROM registrant_event
GROUP BY event_id
) ec ON e.id = ec.event_id
```
|
206,024 |
<p>I have an ASP.Net 2.0 page that contains two UpdatePanels. The first panel contains a TreeView. The second panel contains a label and is triggered by a selection in the tree. When I select a node the label gets updated as expected and the <code>TreeNode</code> that I clicked on becomes highlighted and the previously selected node is no longer highlighted. However if a node is original highlighted(selected) in the code-behind the highlight is not removed when selecting another node.</p>
<p>The markup</p>
<pre><code><asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:TreeView ID="TreeView1" runat="server" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged">
<SelectedNodeStyle BackColor="Pink" />
</asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text=" - "></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="SelectedNodeChanged" />
</Triggers>
</asp:UpdatePanel>
</code></pre>
<p>The code behind</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeView1.Nodes.Add(new TreeNode("Test 1", "Test One"));
TreeView1.Nodes.Add(new TreeNode("Test 2", "Test Two"));
TreeView1.Nodes.Add(new TreeNode("Test 3", "Test Three"));
TreeView1.Nodes.Add(new TreeNode("Test 4", "Test Four"));
TreeView1.Nodes[0].Selected = true;
}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Label1.Text = TreeView1.SelectedValue;
}
</code></pre>
<p>The at the start the first node is selected. Why is its highlight not removed when selecting another node?</p>
<p>Also, I asked a different <a href="https://stackoverflow.com/questions/205114/why-is-my-asptreeview-selected-node-reset-when-in-an-updatepanel">question about the same setup</a> that I haven't got an answer for. Any help would appreciated. </p>
<p><strong>Edit</strong> I know that setting <code>ChildrenAsTriggers="false"</code> will work but I want to avoid rendering the tree again as it can be very large.</p>
|
[
{
"answer_id": 207382,
"author": "Jason Kealey",
"author_id": 20893,
"author_profile": "https://Stackoverflow.com/users/20893",
"pm_score": 1,
"selected": false,
"text": "<p>You need to set the selection to false for all nodes. </p>\n\n<p>I use something like this for one of my applications (with my treeview tvCategories):</p>\n\n<pre><code>public void RefreshSelection(string guid)\n{\n if (guid == string.Empty)\n ClearNodes(tvCategories.Nodes);\n else\n SelectNode(guid, tvCategories.Nodes);\n\n}\n\nprivate void ClearNodes(TreeNodeCollection tnc)\n{\n foreach (TreeNode n in tnc)\n {\n n.Selected = false;\n ClearNodes(n.ChildNodes);\n }\n}\nprivate bool SelectNode(string guid, TreeNodeCollection tnc)\n{\n foreach (TreeNode n in tnc)\n {\n if (n.Value == guid)\n {\n n.Selected = true;\n return true;\n }\n else\n {\n SelectNode(guid, n.ChildNodes);\n }\n }\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 208013,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 1,
"selected": true,
"text": "<p>This may be a bit of a hack but this will clear the selection on the client and avoid updating the panel.</p>\n\n<pre><code>Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function BeginRequestHandler(sender, args)\n {\n var elem = args.get_postBackElement();\n var selectedClassName = elem.id + '_1';\n\n var arrAllElements = GetElementsByClassName(selectedClassName, elem);\n var selectedNode = $get(elem.id + '_SelectedNode').value;\n\n for(var i = 0; i < arrAllElements.length; i++)\n {\n if(arrAllElements[i].childNodes[0].id != selectedNode)\n RemoveClassName(arrAllElements[i], selectedClassName );\n }\n }\n);\n</code></pre>\n\n<p>It removes the selected style/class from all tree nodes unless its value is contained in the '_SelectedNode' hidden field.\n<code>GetElementsByClassName</code> and <code>RemoveClassName</code> are in my own js library but are obvious enough.</p>\n"
},
{
"answer_id": 4544137,
"author": "Newborn",
"author_id": 555702,
"author_profile": "https://Stackoverflow.com/users/555702",
"pm_score": 2,
"selected": false,
"text": "<pre><code> /// <summary>\n /// Remove selection from TreeView\n /// </summary>\n /// <param name=\"tree\"></param>\n public static void ClearTreeView(TreeView tree)\n {\n\n if (tree.SelectedNode != null)\n {\n tree.SelectedNode.Selected = false;\n }\n }\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
I have an ASP.Net 2.0 page that contains two UpdatePanels. The first panel contains a TreeView. The second panel contains a label and is triggered by a selection in the tree. When I select a node the label gets updated as expected and the `TreeNode` that I clicked on becomes highlighted and the previously selected node is no longer highlighted. However if a node is original highlighted(selected) in the code-behind the highlight is not removed when selecting another node.
The markup
```
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:TreeView ID="TreeView1" runat="server" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged">
<SelectedNodeStyle BackColor="Pink" />
</asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text=" - "></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="SelectedNodeChanged" />
</Triggers>
</asp:UpdatePanel>
```
The code behind
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeView1.Nodes.Add(new TreeNode("Test 1", "Test One"));
TreeView1.Nodes.Add(new TreeNode("Test 2", "Test Two"));
TreeView1.Nodes.Add(new TreeNode("Test 3", "Test Three"));
TreeView1.Nodes.Add(new TreeNode("Test 4", "Test Four"));
TreeView1.Nodes[0].Selected = true;
}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Label1.Text = TreeView1.SelectedValue;
}
```
The at the start the first node is selected. Why is its highlight not removed when selecting another node?
Also, I asked a different [question about the same setup](https://stackoverflow.com/questions/205114/why-is-my-asptreeview-selected-node-reset-when-in-an-updatepanel) that I haven't got an answer for. Any help would appreciated.
**Edit** I know that setting `ChildrenAsTriggers="false"` will work but I want to avoid rendering the tree again as it can be very large.
|
This may be a bit of a hack but this will clear the selection on the client and avoid updating the panel.
```
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function BeginRequestHandler(sender, args)
{
var elem = args.get_postBackElement();
var selectedClassName = elem.id + '_1';
var arrAllElements = GetElementsByClassName(selectedClassName, elem);
var selectedNode = $get(elem.id + '_SelectedNode').value;
for(var i = 0; i < arrAllElements.length; i++)
{
if(arrAllElements[i].childNodes[0].id != selectedNode)
RemoveClassName(arrAllElements[i], selectedClassName );
}
}
);
```
It removes the selected style/class from all tree nodes unless its value is contained in the '\_SelectedNode' hidden field.
`GetElementsByClassName` and `RemoveClassName` are in my own js library but are obvious enough.
|
206,045 |
<p>I have code like this:</p>
<pre><code>template <typename T, typename U> struct MyStruct {
T aType;
U anotherType;
};
class IWantToBeFriendsWithMyStruct
{
friend struct MyStruct; //what is the correct syntax here ?
};
</code></pre>
<p>What is the correct syntax to give friendship to the template ?</p>
|
[
{
"answer_id": 206054,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 5,
"selected": true,
"text": "<pre><code>class IWantToBeFriendsWithMyStruct\n{\n template <typename T, typename U>\n friend struct MyStruct;\n};\n</code></pre>\n\n<p>Works in VS2008, and allows MyStruct to access the class.</p>\n"
},
{
"answer_id": 206073,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"http://www.devx.com/cplus/10MinuteSolution/30302/0/page/2\" rel=\"noreferrer\">this site</a>, the correct syntax would be</p>\n\n<pre><code>class IWantToBeFriendsWithMyStruct\n{\n template <typename T, typename U> friend struct MyStruct; \n}\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28275/"
] |
I have code like this:
```
template <typename T, typename U> struct MyStruct {
T aType;
U anotherType;
};
class IWantToBeFriendsWithMyStruct
{
friend struct MyStruct; //what is the correct syntax here ?
};
```
What is the correct syntax to give friendship to the template ?
|
```
class IWantToBeFriendsWithMyStruct
{
template <typename T, typename U>
friend struct MyStruct;
};
```
Works in VS2008, and allows MyStruct to access the class.
|
206,055 |
<p>I am a SQL Server user .</p>
<p>I am on a project that is using oracle (which I rarely use)
I need to create an ODBC connection so I can access the some data via MS Access
I have a application on my machine called oraHome90. It seems to allow a configuration of something called a listener in a “net configuration utility”, I think that a “Local Net Service Name Configuration” needs to also be done. The IT support gave me this information to set up the ODBC connection . I have tried every combination that I can think of. I can get past a test that successfully passes a test to “login“ to the oracle server database. When I try to create the ODBC connection I get the following error: ORA-12154: TNS: Could not resolve service name.</p>
<p>Assuming that I want to start from scratch and the following information is supposed to allow for me to connect to the database….. Any suggestions or comment ? Note: ultimately the project will have a website .ASP page query the data, but I have to first prove that I can see the data using the ODBC connection via MS Access</p>
<pre><code>Service name: SERVICENAME
HOST = HOST.XYZi.com
User Id: MYUSERID
Password: MYPASSWORD
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'Oracle Connection
Dim ocst
Dim oconn
ocst = "Provider=OraOLEDB.Oracle;" & _
"Data Source=DATASOURCE;" & _
"User ID=CHIJXL;" & _
"Password=password;"
set oconn = CreateObject("ADODB.Connection")
</code></pre>
|
[
{
"answer_id": 206066,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 3,
"selected": false,
"text": "<p>from <a href=\"http://ora-12154.ora-code.com\" rel=\"noreferrer\">http://ora-12154.ora-code.com</a></p>\n\n<p><strong>ORA-12154</strong>: TNS:could not resolve the connect identifier specified<br>\n<em>Cause</em>: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.<br>\n<em>Action</em>: </p>\n\n<ul>\n<li><p>If you are using local naming (TNSNAMES.ORA file):</p></li>\n<li><p>Make sure that \"TNSNAMES\" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)</p></li>\n<li><p>Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.</p></li>\n<li><p>Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.</p></li>\n<li><p>Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.</p></li>\n<li><p>If you are using directory naming:</p></li>\n<li><p>Verify that \"LDAP\" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).</p></li>\n<li><p>Verify that the LDAP directory server is up and that it is accessible.</p></li>\n<li><p>Verify that the net service name or database name used as the connect identifier is configured in the directory.</p></li>\n<li><p>Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier</p></li>\n<li><p>If you are using easy connect naming:</p></li>\n<li><p>Verify that \"EZCONNECT\" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).</p></li>\n<li><p>Make sure the host, port and service name specified are correct.</p></li>\n<li><p>Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.</p></li>\n</ul>\n"
},
{
"answer_id": 206883,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 3,
"selected": false,
"text": "<p>Going on the assumption you're using TNSNAMES naming, here's a couple of things to do:</p>\n\n<ul>\n<li>Create/modify the tnsnames.ora file in the network/admin subdirectory associated with OraHome90 to include an entry for your oracle database:</li>\n</ul>\n\n<blockquote>\n<pre><code>> SERVICENAME_alias =\n> (DESCRIPTION =\n> (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.XYZi.com)(PORT = 1521))\n> (CONNECT_DATA = (SERVICE_NAME = SERVICENAME))\n</code></pre>\n</blockquote>\n\n<p>This is assuming you're using the standard Oracle port of 1521. Note that servicename_alias can be any name you want to use on the local system. You may also find that you need to specify (SID = SERVICENAME) instead of (SERVICENAME=SERVICENAME).</p>\n\n<ul>\n<li>Execute tnsping servicename_alias to verify connectivity. Get this working before going any further. This will tell you if you're past the 12154 error.</li>\n<li>Assuming a good connection, create an ODBC DSN using the control panel, specifying the ODBC driver for Oracle of your choice (generally there's a Microsoft ODBC driver at least, and it should work adequately as a proof of concept). I'll assume the name you gave of DATASOURCE. Use the servicename_alias as the Server name in the ODBC configuration.</li>\n<li>At this point you should be able to connect to your database via Access. I am not a VB programmer, but I know you should be able to go to File->Get External Data->Link Tables and connect to your ODBC source. I would assume your code would work as well.</li>\n</ul>\n"
},
{
"answer_id": 206930,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 2,
"selected": false,
"text": "<p>@Warren and @DCookie have covered the solution, one thing to emphasise is the use of <code>tnsping</code>. You can use this to prove your TNSNames is correct before attempting to connect.</p>\n\n<p>Once you have set up tnsnames correctly you could use ODBC or try <a href=\"http://tora.sourceforge.net/\" rel=\"nofollow noreferrer\">TOra</a> which will use your native oracle connection. TOra or something similar (TOAD, SQL*Plus etc) will prove invaluable in debugging and improving your SQL.</p>\n\n<p>Last but not least when you eventually connect with ASP.net remember that you can use the Oracle data connection libraries. See <a href=\"http://www.oracle.com/technology/tech/dotnet/index.html\" rel=\"nofollow noreferrer\">Oracle.com</a> for a host of resources.</p>\n"
},
{
"answer_id": 5633967,
"author": "khizer jalal",
"author_id": 703891,
"author_profile": "https://Stackoverflow.com/users/703891",
"pm_score": 1,
"selected": false,
"text": "<p>I had a same problem and the same error was showing up. my TNSNAMES:ORA file was also good to go but apparently there was a problem due to firewall blocking the access. SO a good tip would be to make sure that firewall is not blocking the access to the datasource. </p>\n"
},
{
"answer_id": 6296895,
"author": "Tom Stickel",
"author_id": 756246,
"author_profile": "https://Stackoverflow.com/users/756246",
"pm_score": 0,
"selected": false,
"text": "<p>Hours of problems SOLVED. I had installed the Beta Entity Framework for Oracle and in in visual studio 2010 MVC 3 project I was referencing under the tab .NET the Oracle.DataAccess ... This kept giving me the \"Oracle ORA-12154: TNS: Could not...\" error. I finally just browsed to the previous Oracle install under c:\\Oracle\\product.... using the old 10.2.0.100 version of the dll. Finally it works now. Hope it helps someone else.</p>\n"
},
{
"answer_id": 8818766,
"author": "Sertan",
"author_id": 1143102,
"author_profile": "https://Stackoverflow.com/users/1143102",
"pm_score": 2,
"selected": false,
"text": "<p>If there is a space in the beginning of the tns name define in file <code>tnsnames.ora</code>, then some of the the connectors like odbc may give this error. Remove space character in the beginning.</p>\n"
},
{
"answer_id": 9375400,
"author": "Anto",
"author_id": 1223042,
"author_profile": "https://Stackoverflow.com/users/1223042",
"pm_score": 2,
"selected": false,
"text": "<p>I struggled to resolve this problem for hours until I found an Environment variable called TNS_ADMIN set in My Computer => Properties => Advanced => Environment Variables => look in System variables for an entry called TNS_ADMIN. \nTNS_ADMIN is added to change the default path for Tnsnames.ora entry.\nThis is useful when its used in a network environment where a generic tnsnames.ora entry can be setup for all the network computers.\nTo look at the default path of tnsnames.ora add the default path in TNS_ADMIN.</p>\n"
},
{
"answer_id": 14249519,
"author": "hanzolo",
"author_id": 574952,
"author_profile": "https://Stackoverflow.com/users/574952",
"pm_score": 0,
"selected": false,
"text": "<p>I just spend an hour on this, I'm new to Oracle so i was thoroughly confused.. </p>\n\n<p>the situation:</p>\n\n<p>just installed visual studio 2012 Oracle developer tools. When i did this I lost the items in my drop down which contained my TNS entries in TOAD. I was getting this error from Visual studio AND TOAD!! WTH! so i added the environmental Variable TNS_ADMIN under \"ALL USERS\" with the path to my .ora file (which i now worked fine because it worked until I broke it). Toad picked up that change. Still Visual Studio wouldn't give me any love... still getting same error. THEN, i added the environmental Variable TO MY USER VARIABLES.. VIOLA!! </p>\n\n<p><strong>ENSURE THE ENVIRONMENTAL VARIABLES ARE SET FOR THE SYSTEM AND THE USER</strong></p>\n"
},
{
"answer_id": 16818428,
"author": "guiomie",
"author_id": 540585,
"author_profile": "https://Stackoverflow.com/users/540585",
"pm_score": 3,
"selected": false,
"text": "<p>In reference to #7 in this <a href=\"http://blogs.msdn.com/b/dataaccesstechnologies/archive/2010/06/30/ora-12154-tns-could-not-resolve-the-connect-identifier-specified-error-while-creating-a-linked-server-to-oracle.aspx\" rel=\"noreferrer\">MSDN POST</a> , adding a registry entry worked for me. I had Vs2010, et oracle 11.0 installed.</p>\n\n<blockquote>\n <p>Check for the registry key “TNS_ADMIN” at HKEY_LOCAL_MACHINE\\SOFTWARE\\ORACLE. If it exists then make sure it has\n the right value as “Dir:\\app\\product\\11.1.0\\client_1\\network\\admin”.\n If you don’t see the key then create the key and set appropriate value\n as below. Regedit->HKEY_LOCAL_MACHINE->Software->Oracle->RightClick\n NEW->StringValue and name it TNS_ADMIN and give the value \n “X:\\app\\product\\11.1.0\\client_1\\network\\admin”</p>\n</blockquote>\n"
},
{
"answer_id": 21131961,
"author": "Law",
"author_id": 3197190,
"author_profile": "https://Stackoverflow.com/users/3197190",
"pm_score": 1,
"selected": false,
"text": "<p>I experienced this problem too. I discovered the problem is because Oracle DB does not like the space in C:program files (x86)\\Toad...... so I created a new directory named C:App\\Toad then reinstalled in it to connect Toad to Oracle. It worked.</p>\n"
},
{
"answer_id": 21602370,
"author": "user2689022",
"author_id": 2689022,
"author_profile": "https://Stackoverflow.com/users/2689022",
"pm_score": 0,
"selected": false,
"text": "<p>Only restart the SID services. For example you SID name = orcl then all the services which related to orcl should be restart then you problem will be solved</p>\n"
},
{
"answer_id": 22823282,
"author": "Venki",
"author_id": 3491318,
"author_profile": "https://Stackoverflow.com/users/3491318",
"pm_score": 2,
"selected": false,
"text": "<p>It has nothing to do with a space embedded in the folder structure.</p>\n\n<p>I had the same problem. But when I created an environmental variable (defined both at the system- and user-level) called TNS_HOME and made it to point to the folder where TNSNAMES.ORA existed, the problem was resolved. Voila!</p>\n\n<p>venki</p>\n"
},
{
"answer_id": 25040128,
"author": "Austin",
"author_id": 3892057,
"author_profile": "https://Stackoverflow.com/users/3892057",
"pm_score": 0,
"selected": false,
"text": "<p>We resolved our issues by re-installing the Oracle Database Client. Somehow the installation wasn't successful on 1 of the workstations (even though there was no logging), however when comparing size/files/folders of the Oracle directory to a working client workstation, there was a significant amount of files that were missing. Once we performed a clean install, everything worked perfectly. </p>\n"
},
{
"answer_id": 26161675,
"author": "Hernaldo Gonzalez",
"author_id": 1536197,
"author_profile": "https://Stackoverflow.com/users/1536197",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, the error are because I have 2 Oracle clients, It's the solution:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/7176252/oracle-ora-12154-error-on-local-iis-but-not-with-visual-studio-development-serv/26161650#26161650\">Oracle ORA-12154 error on local IIS, but not with Visual Studio Development Server</a></p>\n"
},
{
"answer_id": 32123008,
"author": "stantont",
"author_id": 28810,
"author_profile": "https://Stackoverflow.com/users/28810",
"pm_score": 1,
"selected": false,
"text": "<p>This was mentioned in a <a href=\"https://stackoverflow.com/questions/206055/oracle-ora-12154-tns-could-not-resolve-service-name-error#comment49703662_206066\">comment</a> to another answer, but I wanted to move it to an actual answer since this was also the problem in my case and I would have upvoted it if it had been an answer.</p>\n\n<p>I'm on Linux and the tnsnames.ora file was not set to readable by everyone. After making it readable connecting via tns locally worked.</p>\n\n<pre><code>$ chmod +r tnsnames.ora\n</code></pre>\n"
},
{
"answer_id": 32256968,
"author": "JavaTec",
"author_id": 3965524,
"author_profile": "https://Stackoverflow.com/users/3965524",
"pm_score": 0,
"selected": false,
"text": "<p>We also had the similar issue. What we found out that we had provided multiple aliases for our connection string in tnsnames.ora, something like:</p>\n\n<p>svc01, svc02=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxx)(port=50))(CONNECT_DATA=(SERVER=DEDICATED)(service_name=yyyysvc.world)))</p>\n\n<p>so when creating a connection using ODBC, when we selected the value for TNS service name, the auto populate was showing 'svc01,' (please note the extra comma there). As soon as we removed the comma, it started working for us.</p>\n"
},
{
"answer_id": 33007863,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 2,
"selected": false,
"text": "<p>Arrhhh!! I RAN INTO THIS AGAIN!!!</p>\n\n<p>Just install ToadForOracle in C:\\ or any directory without parenthesis in the path.</p>\n\n<hr>\n\n<p>In my case its because I was on a x64 PC and still using the old Oracle 9i with the 32bit drivers!</p>\n\n<p>I am using SQL Reporting Services with an Oracle Database. The problem is the brackets in the path to Visual Studio (BIDS). Oracle doesn't like apps that start in a path with brackets:</p>\n\n<p><a href=\"https://community.oracle.com/thread/2377520?tstart=0\" rel=\"nofollow noreferrer\">RDBMS 10g XE problem with parenthesis in path</a></p>\n\n<p>So I made a BAT file to open Visual Studio with Progra~2 as the short path name for \"Program Files (x86)\".</p>\n\n<p>Here is the contents of the BAT file:</p>\n\n<pre><code>rem Progra~2 is short path name for \"Program Files (x86)\" and works around an Oracle client bug that doesn't like the ()'s in the path\nstart /B \"C:\\Progra~2\\Microsoft Visual Studio 9.0\\Common7\\IDE\" \"C:\\Progra~2\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe\"\n</code></pre>\n\n<p>I name this BAT file StartBIDS.BAT and put it in the directory: </p>\n\n<blockquote>\n <p>\"C:\\Program Files\\Microsoft SQL Server\\Start BIDS.bat\"</p>\n</blockquote>\n\n<p>Then I make a short cut to the BAT file on my Desktop and also my Start Menu and change the ShortCuts icon. This allows me to open TOAD, Visual Studio, BIDS and etc apps that I use to work with Oracle.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Alternatively make a Junction: </p>\n\n<pre><code>mklink /J \"C:\\Program Files (x86)\\\" \"C:\\Program Files x86\\\"\n</code></pre>\n\n<p>Then remove the brackets in the shortcut:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9q5Rb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9q5Rb.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 33668354,
"author": "Muhamed Krlić",
"author_id": 1951115,
"author_profile": "https://Stackoverflow.com/users/1951115",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a 32bit DSN and a 64bit DSN with same names, Windows will automatically choose the 64bit one and If your application is 32bit it shows this error. Just watch out for that.</p>\n"
},
{
"answer_id": 34292571,
"author": "Ken",
"author_id": 180615,
"author_profile": "https://Stackoverflow.com/users/180615",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem because of a typo in the filename tsnames.ora instead of tnsnames.ora</p>\n"
},
{
"answer_id": 43323947,
"author": "aemre",
"author_id": 4582867,
"author_profile": "https://Stackoverflow.com/users/4582867",
"pm_score": 1,
"selected": false,
"text": "<p>I fixed this problem using this steps. </p>\n\n<p>First of all, this error occured , if you didn't install same directory or drive. </p>\n\n<p>But the answer is here. </p>\n\n<ol>\n<li>Login windows as a Adminstrator.</li>\n<li>Go to Control Panel.</li>\n<li>System Properties and click Enviroment</li>\n<li><p>Find the OS variable and change name as a \"TNS_ADMIN\"<br><br>\n<a href=\"https://i.stack.imgur.com/SazDD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SazDD.png\" alt=\"enter image description here\"></a></p></li>\n<li><p>And change the value as a \"tnsnames's directory address\"\n<a href=\"https://i.stack.imgur.com/myxxy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/myxxy.png\" alt=\"enter image description here\"></a></p></li>\n<li><p>Restart the system. </p></li>\n<li>Congrulations. </li>\n</ol>\n"
},
{
"answer_id": 51022907,
"author": "Nalluswamy K",
"author_id": 8718400,
"author_profile": "https://Stackoverflow.com/users/8718400",
"pm_score": 1,
"selected": false,
"text": "<p>I have resolved this issue by removing sqlnet.ora from the C:\\oracle\\ora92\\network\\ADMIN path </p>\n\n<ul>\n<li>Make sure TNSNAMES.ORA file exists in the right directory</li>\n<li>Make sure PATH environment variable is having entry for oracle</li>\n<li>Make sure no syntax issues in the TNSNAMES.ORA</li>\n<li>Try removing sqlnet.ora file</li>\n</ul>\n"
},
{
"answer_id": 65305352,
"author": "Miroslav Kovarik",
"author_id": 4655974,
"author_profile": "https://Stackoverflow.com/users/4655974",
"pm_score": 0,
"selected": false,
"text": "<p>This error message can be very confusing and the solution can be surprisingly primitive.</p>\n<p>In my case: Oracle stored procedure sends recordset to MS Excel via "Provider=OraOLEDB.Oracle;Data Source= ...etc" .</p>\n<p>The problem was a number of decimal numbers in the Oracle data column sent to Excel 2010.\nWhen I used Oracle SQL query ROUND(grosssales_eur,2) AS grosssales_eur, it worked fine.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26883/"
] |
I am a SQL Server user .
I am on a project that is using oracle (which I rarely use)
I need to create an ODBC connection so I can access the some data via MS Access
I have a application on my machine called oraHome90. It seems to allow a configuration of something called a listener in a “net configuration utility”, I think that a “Local Net Service Name Configuration” needs to also be done. The IT support gave me this information to set up the ODBC connection . I have tried every combination that I can think of. I can get past a test that successfully passes a test to “login“ to the oracle server database. When I try to create the ODBC connection I get the following error: ORA-12154: TNS: Could not resolve service name.
Assuming that I want to start from scratch and the following information is supposed to allow for me to connect to the database….. Any suggestions or comment ? Note: ultimately the project will have a website .ASP page query the data, but I have to first prove that I can see the data using the ODBC connection via MS Access
```
Service name: SERVICENAME
HOST = HOST.XYZi.com
User Id: MYUSERID
Password: MYPASSWORD
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'Oracle Connection
Dim ocst
Dim oconn
ocst = "Provider=OraOLEDB.Oracle;" & _
"Data Source=DATASOURCE;" & _
"User ID=CHIJXL;" & _
"Password=password;"
set oconn = CreateObject("ADODB.Connection")
```
|
from <http://ora-12154.ora-code.com>
**ORA-12154**: TNS:could not resolve the connect identifier specified
*Cause*: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.
*Action*:
* If you are using local naming (TNSNAMES.ORA file):
* Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY\_PATH parameter in the Oracle Net profile (SQLNET.ORA)
* Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.
* Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.
* Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.
* If you are using directory naming:
* Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY\_PATH parameter in the Oracle Net profile (SQLNET.ORA).
* Verify that the LDAP directory server is up and that it is accessible.
* Verify that the net service name or database name used as the connect identifier is configured in the directory.
* Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier
* If you are using easy connect naming:
* Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY\_PATH parameter in the Oracle Net profile (SQLNET.ORA).
* Make sure the host, port and service name specified are correct.
* Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.
|
206,059 |
<p>I've been looking for a simple regex for URLs, does anybody have one handy that works well? I didn't find one with the zend framework validation classes and have seen several implementations.</p>
|
[
{
"answer_id": 206087,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 7,
"selected": true,
"text": "<p>I used this on a few projects, I don't believe I've run into issues, but I'm sure it's not exhaustive:</p>\n<pre><code>$text = preg_replace(\n '#((https?|ftp)://(\\S*?\\.\\S*?))([\\s)\\[\\]{},;"\\':<]|\\.\\s|$)#i',\n "'<a href=\\"$1\\" target=\\"_blank\\">$3</a>$4'",\n $text\n);\n</code></pre>\n<p>Most of the random junk at the end is to deal with situations like <code>http://domain.example.</code> in a sentence (to avoid matching the trailing period). I'm sure it could be cleaned up but since it worked. I've more or less just copied it over from project to project.</p>\n"
},
{
"answer_id": 206107,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 3,
"selected": false,
"text": "<p>I've used this one with good success - I don't remember where I got it from</p>\n\n<pre><code>$pattern = \"/\\b(?:(?:https?|ftp):\\/\\/|www\\.)[-a-z0-9+&@#\\/%?=~_|!:,.;]*[-a-z0-9+&@#\\/%=~_|]/i\";\n</code></pre>\n"
},
{
"answer_id": 207627,
"author": "Stanislav",
"author_id": 21504,
"author_profile": "https://Stackoverflow.com/users/21504",
"pm_score": 8,
"selected": false,
"text": "<p>Use the <code>filter_var()</code> function to validate whether a string is URL or not:</p>\n\n<pre><code>var_dump(filter_var('example.com', FILTER_VALIDATE_URL));\n</code></pre>\n\n<p>It is bad practice to use regular expressions when not necessary.</p>\n\n<p><strong>EDIT</strong>: Be careful, this solution is not unicode-safe and not XSS-safe. If you need a complex validation, maybe it's better to look somewhere else.</p>\n"
},
{
"answer_id": 395032,
"author": "catchdave",
"author_id": 49366,
"author_profile": "https://Stackoverflow.com/users/49366",
"pm_score": 5,
"selected": false,
"text": "<p>As per the PHP manual - parse_url should <strong>not</strong> be used to validate a URL.</p>\n\n<p>Unfortunately, it seems that <code>filter_var('example.com', FILTER_VALIDATE_URL)</code> does not perform any better.</p>\n\n<p>Both <code>parse_url()</code> and <code>filter_var()</code> will pass malformed URLs such as <code>http://...</code></p>\n\n<p>Therefore in this case - regex <strong>is</strong> the better method.</p>\n"
},
{
"answer_id": 639598,
"author": "Frankie",
"author_id": 67945,
"author_profile": "https://Stackoverflow.com/users/67945",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit:</strong>\n<br />\nAs <a href=\"https://stackoverflow.com/users/138016/incidence\">incidence</a> pointed out this code has been DEPRECATED with the release of PHP 5.3.0 (2009-06-30) and should be used accordingly.</p>\n\n<hr>\n\n<p>Just my two cents but I've developed this function and have been using it for a while with success. It's well documented and separated so you can easily change it.</p>\n\n<pre><code>// Checks if string is a URL\n// @param string $url\n// @return bool\nfunction isURL($url = NULL) {\n if($url==NULL) return false;\n\n $protocol = '(http://|https://)';\n $allowed = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';\n\n $regex = \"^\". $protocol . // must include the protocol\n '(' . $allowed . '{1,63}\\.)+'. // 1 or several sub domains with a max of 63 chars\n '[a-z]' . '{2,6}'; // followed by a TLD\n if(eregi($regex, $url)==true) return true;\n else return false;\n}\n</code></pre>\n"
},
{
"answer_id": 929053,
"author": "joedevon",
"author_id": 110337,
"author_profile": "https://Stackoverflow.com/users/110337",
"pm_score": 0,
"selected": false,
"text": "<p>Peter's Regex doesn't look right to me for many reasons. It allows all kinds of special characters in the domain name and doesn't test for much.</p>\n\n<p>Frankie's function looks good to me and you can build a good regex from the components if you don't want a function, like so:</p>\n\n<pre><code>^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\\.)+[a-z]{2,6}\n</code></pre>\n\n<p>Untested but I think that should work.</p>\n\n<p>Also, Owen's answer doesn't look 100% either. I took the domain part of the regex and tested it on a Regex tester tool <a href=\"http://erik.eae.net/playground/regexp/regexp.html\" rel=\"nofollow noreferrer\">http://erik.eae.net/playground/regexp/regexp.html</a> </p>\n\n<p>I put the following line:</p>\n\n<pre><code>(\\S*?\\.\\S*?)\n</code></pre>\n\n<p>in the \"regexp\" section\nand the following line:</p>\n\n<blockquote>\n <p>-hello.com</p>\n</blockquote>\n\n<p>under the \"sample text\" section.</p>\n\n<p>The result allowed the minus character through. Because \\S means any non-space character. </p>\n\n<p>Note the regex from Frankie handles the minus because it has this part for the first character:</p>\n\n<pre><code>[a-z0-9]\n</code></pre>\n\n<p>Which won't allow the minus or any other special character.</p>\n"
},
{
"answer_id": 4969311,
"author": "Roger",
"author_id": 559742,
"author_profile": "https://Stackoverflow.com/users/559742",
"pm_score": 4,
"selected": false,
"text": "<p>Just in case you want to know if the url really exists:</p>\n\n<pre><code>function url_exist($url){//se passar a URL existe\n $c=curl_init();\n curl_setopt($c,CURLOPT_URL,$url);\n curl_setopt($c,CURLOPT_HEADER,1);//get the header\n curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header\n curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it\n curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url\n if(!curl_exec($c)){\n //echo $url.' inexists';\n return false;\n }else{\n //echo $url.' exists';\n return true;\n }\n //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);\n //return ($httpcode<400);\n}\n</code></pre>\n"
},
{
"answer_id": 5289151,
"author": "abhiomkar",
"author_id": 235453,
"author_profile": "https://Stackoverflow.com/users/235453",
"pm_score": 4,
"selected": false,
"text": "<p>As per <strong>John Gruber</strong> (Daring Fireball):</p>\n\n<p>Regex:</p>\n\n<pre><code>(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))\n</code></pre>\n\n<p>using in preg_match():</p>\n\n<pre><code>preg_match(\"/(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))/\", $url)\n</code></pre>\n\n<p>Here is the extended regex pattern (with comments):</p>\n\n<pre><code>(?xi)\n\\b\n( # Capture 1: entire matched URL\n (?:\n https?:// # http or https protocol\n | # or\n www\\d{0,3}[.] # \"www.\", \"www1.\", \"www2.\" … \"www999.\"\n | # or\n [a-z0-9.\\-]+[.][a-z]{2,4}/ # looks like domain name followed by a slash\n )\n (?: # One or more:\n [^\\s()<>]+ # Run of non-space, non-()<>\n | # or\n \\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\) # balanced parens, up to 2 levels\n )+\n (?: # End with:\n \\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\) # balanced parens, up to 2 levels\n | # or\n [^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’] # not a space or one of these punct chars\n )\n)\n</code></pre>\n\n<p>For more details please look at:\n<a href=\"http://daringfireball.net/2010/07/improved_regex_for_matching_urls\" rel=\"noreferrer\">http://daringfireball.net/2010/07/improved_regex_for_matching_urls</a></p>\n"
},
{
"answer_id": 5492163,
"author": "jini",
"author_id": 323698,
"author_profile": "https://Stackoverflow.com/users/323698",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function is_valid_url ($url=\"\") {\n\n if ($url==\"\") {\n $url=$this->url;\n }\n\n $url = @parse_url($url);\n\n if ( ! $url) {\n\n\n return false;\n }\n\n $url = array_map('trim', $url);\n $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];\n $path = (isset($url['path'])) ? $url['path'] : '';\n\n if ($path == '') {\n $path = '/';\n }\n\n $path .= ( isset ( $url['query'] ) ) ? \"?$url[query]\" : '';\n\n\n\n if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) ) {\n if ( PHP_VERSION >= 5 ) {\n $headers = get_headers(\"$url[scheme]://$url[host]:$url[port]$path\");\n }\n else {\n $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);\n\n if ( ! $fp ) {\n return false;\n }\n fputs($fp, \"HEAD $path HTTP/1.1\\r\\nHost: $url[host]\\r\\n\\r\\n\");\n $headers = fread ( $fp, 128 );\n fclose ( $fp );\n }\n $headers = ( is_array ( $headers ) ) ? implode ( \"\\n\", $headers ) : $headers;\n return ( bool ) preg_match ( '#^HTTP/.*\\s+[(200|301|302)]+\\s#i', $headers );\n }\n\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 5968861,
"author": "promaty",
"author_id": 748745,
"author_profile": "https://Stackoverflow.com/users/748745",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think that using regular expressions is a smart thing to do in this case. It is impossible to match all of the possibilities and even if you did, there is still a chance that url simply doesn't exist.</p>\n\n<p>Here is a very simple way to test if url actually exists and is readable :</p>\n\n<pre><code>if (preg_match(\"#^https?://.+#\", $link) and @fopen($link,\"r\")) echo \"OK\";\n</code></pre>\n\n<p>(if there is no <code>preg_match</code> then this would also validate all filenames on your server)</p>\n"
},
{
"answer_id": 11820924,
"author": "Jeremy Moore",
"author_id": 1522312,
"author_profile": "https://Stackoverflow.com/users/1522312",
"pm_score": -1,
"selected": false,
"text": "<p>I've found this to be the most useful for matching a URL..</p>\n\n<pre><code>^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$\n</code></pre>\n"
},
{
"answer_id": 12910990,
"author": "Vikash Kumar",
"author_id": 1749440,
"author_profile": "https://Stackoverflow.com/users/1749440",
"pm_score": 3,
"selected": false,
"text": "<pre><code> function validateURL($URL) {\n $pattern_1 = \"/^(http|https|ftp):\\/\\/(([A-Z0-9][A-Z0-9_-]*)(\\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\\d+))?\\/?/i\";\n $pattern_2 = \"/^(www)((\\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\\d+))?\\/?/i\"; \n if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){\n return true;\n } else{\n return false;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 13756384,
"author": "George Milonas",
"author_id": 1172788,
"author_profile": "https://Stackoverflow.com/users/1172788",
"pm_score": 3,
"selected": false,
"text": "<p>And there is your answer =) Try to break it, you can't!!!</p>\n\n<pre><code>function link_validate_url($text) {\n$LINK_DOMAINS = 'aero|arpa|asia|biz|com|cat|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|mobi|local';\n $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode(\"\", array( // @TODO completing letters ...\n \"&#x00E6;\", // æ\n \"&#x00C6;\", // Æ\n \"&#x00C0;\", // À\n \"&#x00E0;\", // à\n \"&#x00C1;\", // Á\n \"&#x00E1;\", // á\n \"&#x00C2;\", // Â\n \"&#x00E2;\", // â\n \"&#x00E5;\", // å\n \"&#x00C5;\", // Å\n \"&#x00E4;\", // ä\n \"&#x00C4;\", // Ä\n \"&#x00C7;\", // Ç\n \"&#x00E7;\", // ç\n \"&#x00D0;\", // Ð\n \"&#x00F0;\", // ð\n \"&#x00C8;\", // È\n \"&#x00E8;\", // è\n \"&#x00C9;\", // É\n \"&#x00E9;\", // é\n \"&#x00CA;\", // Ê\n \"&#x00EA;\", // ê\n \"&#x00CB;\", // Ë\n \"&#x00EB;\", // ë\n \"&#x00CE;\", // Î\n \"&#x00EE;\", // î\n \"&#x00CF;\", // Ï\n \"&#x00EF;\", // ï\n \"&#x00F8;\", // ø\n \"&#x00D8;\", // Ø\n \"&#x00F6;\", // ö\n \"&#x00D6;\", // Ö\n \"&#x00D4;\", // Ô\n \"&#x00F4;\", // ô\n \"&#x00D5;\", // Õ\n \"&#x00F5;\", // õ\n \"&#x0152;\", // Œ\n \"&#x0153;\", // œ\n \"&#x00FC;\", // ü\n \"&#x00DC;\", // Ü\n \"&#x00D9;\", // Ù\n \"&#x00F9;\", // ù\n \"&#x00DB;\", // Û\n \"&#x00FB;\", // û\n \"&#x0178;\", // Ÿ\n \"&#x00FF;\", // ÿ \n \"&#x00D1;\", // Ñ\n \"&#x00F1;\", // ñ\n \"&#x00FE;\", // þ\n \"&#x00DE;\", // Þ\n \"&#x00FD;\", // ý\n \"&#x00DD;\", // Ý\n \"&#x00BF;\", // ¿\n )), ENT_QUOTES, 'UTF-8');\n\n $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode(\"\", array(\n \"&#x00DF;\", // ß\n )), ENT_QUOTES, 'UTF-8');\n $allowed_protocols = array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal');\n\n // Starting a parenthesis group with (?: means that it is grouped, but is not captured\n $protocol = '((?:'. implode(\"|\", $allowed_protocols) .'):\\/\\/)';\n $authentication = \"(?:(?:(?:[\\w\\.\\-\\+!$&'\\(\\)*\\+,;=\" . $LINK_ICHARS . \"]|%[0-9a-f]{2})+(?::(?:[\\w\". $LINK_ICHARS .\"\\.\\-\\+%!$&'\\(\\)*\\+,;=]|%[0-9a-f]{2})*)?)?@)\";\n $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9'. $LINK_ICHARS_DOMAIN . '\\-_\\[\\]])*)(\\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\\-_\\[\\]])+\\.)*('. $LINK_DOMAINS .'|[a-z]{2}))?)';\n $ipv4 = '(?:[0-9]{1,3}(\\.[0-9]{1,3}){3})';\n $ipv6 = '(?:[0-9a-fA-F]{1,4}(\\:[0-9a-fA-F]{1,4}){7})';\n $port = '(?::([0-9]{1,5}))';\n\n // Pattern specific to external links.\n $external_pattern = '/^'. $protocol .'?'. $authentication .'?('. $domain .'|'. $ipv4 .'|'. $ipv6 .' |localhost)'. $port .'?';\n\n // Pattern specific to internal links.\n $internal_pattern = \"/^(?:[a-z0-9\". $LINK_ICHARS .\"_\\-+\\[\\]]+)\";\n $internal_pattern_file = \"/^(?:[a-z0-9\". $LINK_ICHARS .\"_\\-+\\[\\]\\.]+)$/i\";\n\n $directories = \"(?:\\/[a-z0-9\". $LINK_ICHARS .\"_\\-\\.~+%=&,$'#!():;*@\\[\\]]*)*\";\n // Yes, four backslashes == a single backslash.\n $query = \"(?:\\/?\\?([?a-z0-9\". $LINK_ICHARS .\"+_|\\-\\.~\\/\\\\\\\\%=&,$'():;*@\\[\\]{} ]*))\";\n $anchor = \"(?:#[a-z0-9\". $LINK_ICHARS .\"_\\-\\.~+%=&,$'():;*@\\[\\]\\/\\?]*)\";\n\n // The rest of the path for a standard URL.\n $end = $directories .'?'. $query .'?'. $anchor .'?'.'$/i';\n\n $message_id = '[^@].*@'. $domain;\n $newsgroup_name = '(?:[0-9a-z+-]*\\.)*[0-9a-z+-]*';\n $news_pattern = '/^news:('. $newsgroup_name .'|'. $message_id .')$/i';\n\n $user = '[a-zA-Z0-9'. $LINK_ICHARS .'_\\-\\.\\+\\^!#\\$%&*+\\/\\=\\?\\`\\|\\{\\}~\\'\\[\\]]+';\n $email_pattern = '/^mailto:'. $user .'@'.'(?:'. $domain .'|'. $ipv4 .'|'. $ipv6 .'|localhost)'. $query .'?$/';\n\n if (strpos($text, '<front>') === 0) {\n return false;\n }\n if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {\n return false;\n }\n if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {\n return false;\n }\n if (preg_match($internal_pattern . $end, $text)) {\n return false;\n }\n if (preg_match($external_pattern . $end, $text)) {\n return false;\n }\n if (preg_match($internal_pattern_file, $text)) {\n return false;\n }\n\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 21872143,
"author": "Tim Groeneveld",
"author_id": 2143004,
"author_profile": "https://Stackoverflow.com/users/2143004",
"pm_score": 1,
"selected": false,
"text": "<p>OK, so this is a little bit more complex then a simple regex, but it allows for different types of urls.</p>\n\n<p>Examples:</p>\n\n<ul>\n<li>google.com</li>\n<li>www.microsoft.com/</li>\n<li><a href=\"http://www.yahoo.com/\" rel=\"nofollow noreferrer\">http://www.yahoo.com/</a></li>\n<li><a href=\"https://www.bandcamp.com/artist/#!someone-special\" rel=\"nofollow noreferrer\">https://www.bandcamp.com/artist/#!someone-special</a>!</li>\n</ul>\n\n<p>All which should be marked as valid.</p>\n\n<pre><code>function is_valid_url($url) {\n // First check: is the url just a domain name? (allow a slash at the end)\n $_domain_regex = \"|^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})/?$|\";\n if (preg_match($_domain_regex, $url)) {\n return true;\n }\n\n // Second: Check if it's a url with a scheme and all\n $_regex = '#^([a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))$#';\n if (preg_match($_regex, $url, $matches)) {\n // pull out the domain name, and make sure that the domain is valid.\n $_parts = parse_url($url);\n if (!in_array($_parts['scheme'], array( 'http', 'https' )))\n return false;\n\n // Check the domain using the regex, stops domains like \"-example.com\" passing through\n if (!preg_match($_domain_regex, $_parts['host']))\n return false;\n\n // This domain looks pretty valid. Only way to check it now is to download it!\n return true;\n }\n\n return false;\n}\n</code></pre>\n\n<p>Note that there is a in_array check for the protocols that you want to allow (currently only http and https are in that list).</p>\n\n<pre><code>var_dump(is_valid_url('google.com')); // true\nvar_dump(is_valid_url('google.com/')); // true\nvar_dump(is_valid_url('http://google.com')); // true\nvar_dump(is_valid_url('http://google.com/')); // true\nvar_dump(is_valid_url('https://google.com')); // true\n</code></pre>\n"
},
{
"answer_id": 25422556,
"author": "Thomas Venturini",
"author_id": 1401296,
"author_profile": "https://Stackoverflow.com/users/1401296",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the way I did it. But I want to mentoin that I am not so shure about the regex. But It should work thou :)</p>\n\n<pre><code>$pattern = \"#((http|https)://(\\S*?\\.\\S*?))(\\s|\\;|\\)|\\]|\\[|\\{|\\}|,|”|\\\"|'|:|\\<|$|\\.\\s)#i\";\n $text = preg_replace_callback($pattern,function($m){\n return \"<a href=\\\"$m[1]\\\" target=\\\"_blank\\\">$m[1]</a>$m[4]\";\n },\n $text);\n</code></pre>\n\n<p>This way you won't need the eval marker on your pattern.</p>\n\n<p>Hope it helps :)</p>\n"
},
{
"answer_id": 30238322,
"author": "Fredmat",
"author_id": 1466704,
"author_profile": "https://Stackoverflow.com/users/1466704",
"pm_score": -1,
"selected": false,
"text": "<p>There is a PHP native function for that:</p>\n\n<pre><code>$url = 'http://www.yoururl.co.uk/sub1/sub2/?param=1&param2/';\n\nif ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {\n // Wrong\n}\nelse {\n // Valid\n}\n</code></pre>\n\n<p>Returns the filtered data, or FALSE if the filter fails.</p>\n\n<p><a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow\">Check it here</a></p>\n"
},
{
"answer_id": 41132408,
"author": "Xavi Montero",
"author_id": 1315009,
"author_profile": "https://Stackoverflow.com/users/1315009",
"pm_score": 2,
"selected": false,
"text": "<p>Inspired <a href=\"https://stackoverflow.com/questions/30847/regex-to-validate-uris\">in this .NET StackOverflow question</a> and <a href=\"http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/\" rel=\"nofollow noreferrer\">in this referenced article from that question</a> there is this URI validator (URI means it validates both URL and URN).</p>\n\n<pre><code>if( ! preg_match( \"/^([a-z][a-z0-9+.-]*):(?:\\\\/\\\\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\\\\3)@)?(?=(\\\\[[0-9A-F:.]{2,}\\\\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\\\\5(?::(?=(\\\\d*))\\\\6)?)(\\\\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\8)?|(\\\\/?(?!\\\\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\10)?)(?:\\\\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\12)?$/i\", $uri ) )\n{\n throw new \\RuntimeException( \"URI has not a valid format.\" );\n}\n</code></pre>\n\n<p>I have successfully unit-tested this function inside a ValueObject I made named <code>Uri</code> and tested by <code>UriTest</code>.</p>\n\n<h1>UriTest.php (Contains valid and invalid cases for both URLs and URNs)</h1>\n\n<pre><code><?php\n\ndeclare( strict_types = 1 );\n\nnamespace XaviMontero\\ThrasherPortage\\Tests\\Tour;\n\nuse XaviMontero\\ThrasherPortage\\Tour\\Uri;\n\nclass UriTest extends \\PHPUnit_Framework_TestCase\n{\n private $sut;\n\n public function testCreationIsOfProperClassWhenUriIsValid()\n {\n $sut = new Uri( 'http://example.com' );\n $this->assertInstanceOf( 'XaviMontero\\\\ThrasherPortage\\\\Tour\\\\Uri', $sut );\n }\n\n /**\n * @dataProvider urlIsValidProvider\n * @dataProvider urnIsValidProvider\n */\n public function testGetUriAsStringWhenUriIsValid( string $uri )\n {\n $sut = new Uri( $uri );\n $actual = $sut->getUriAsString();\n\n $this->assertInternalType( 'string', $actual );\n $this->assertEquals( $uri, $actual );\n }\n\n public function urlIsValidProvider()\n {\n return\n [\n [ 'http://example-server' ],\n [ 'http://example.com' ],\n [ 'http://example.com/' ],\n [ 'http://subdomain.example.com/path/?parameter1=value1&parameter2=value2' ],\n [ 'random-protocol://example.com' ],\n [ 'http://example.com:80' ],\n [ 'http://example.com?no-path-separator' ],\n [ 'http://example.com/pa%20th/' ],\n [ 'ftp://example.org/resource.txt' ],\n [ 'file://../../../relative/path/needs/protocol/resource.txt' ],\n [ 'http://example.com/#one-fragment' ],\n [ 'http://example.edu:8080#one-fragment' ],\n ];\n }\n\n public function urnIsValidProvider()\n {\n return\n [\n [ 'urn:isbn:0-486-27557-4' ],\n [ 'urn:example:mammal:monotreme:echidna' ],\n [ 'urn:mpeg:mpeg7:schema:2001' ],\n [ 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66' ],\n [ 'rare-urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66' ],\n [ 'urn:FOO:a123,456' ]\n ];\n }\n\n /**\n * @dataProvider urlIsNotValidProvider\n * @dataProvider urnIsNotValidProvider\n */\n public function testCreationThrowsExceptionWhenUriIsNotValid( string $uri )\n {\n $this->expectException( 'RuntimeException' );\n $this->sut = new Uri( $uri );\n }\n\n public function urlIsNotValidProvider()\n {\n return\n [\n [ 'only-text' ],\n [ 'http//missing.colon.example.com/path/?parameter1=value1&parameter2=value2' ],\n [ 'missing.protocol.example.com/path/' ],\n [ 'http://example.com\\\\bad-separator' ],\n [ 'http://example.com|bad-separator' ],\n [ 'ht tp://example.com' ],\n [ 'http://exampl e.com' ],\n [ 'http://example.com/pa th/' ],\n [ '../../../relative/path/needs/protocol/resource.txt' ],\n [ 'http://example.com/#two-fragments#not-allowed' ],\n [ 'http://example.edu:portMustBeANumber#one-fragment' ],\n ];\n }\n\n public function urnIsNotValidProvider()\n {\n return\n [\n [ 'urn:mpeg:mpeg7:sch ema:2001' ],\n [ 'urn|mpeg:mpeg7:schema:2001' ],\n [ 'urn?mpeg:mpeg7:schema:2001' ],\n [ 'urn%mpeg:mpeg7:schema:2001' ],\n [ 'urn#mpeg:mpeg7:schema:2001' ],\n ];\n }\n}\n</code></pre>\n\n<h1>Uri.php (Value Object)</h1>\n\n<pre><code><?php\n\ndeclare( strict_types = 1 );\n\nnamespace XaviMontero\\ThrasherPortage\\Tour;\n\nclass Uri\n{\n /** @var string */\n private $uri;\n\n public function __construct( string $uri )\n {\n $this->assertUriIsCorrect( $uri );\n $this->uri = $uri;\n }\n\n public function getUriAsString()\n {\n return $this->uri;\n }\n\n private function assertUriIsCorrect( string $uri )\n {\n // https://stackoverflow.com/questions/30847/regex-to-validate-uris\n // http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/\n\n if( ! preg_match( \"/^([a-z][a-z0-9+.-]*):(?:\\\\/\\\\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\\\\3)@)?(?=(\\\\[[0-9A-F:.]{2,}\\\\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\\\\5(?::(?=(\\\\d*))\\\\6)?)(\\\\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\8)?|(\\\\/?(?!\\\\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\10)?)(?:\\\\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\12)?$/i\", $uri ) )\n {\n throw new \\RuntimeException( \"URI has not a valid format.\" );\n }\n }\n}\n</code></pre>\n\n<h1>Running UnitTests</h1>\n\n<p>There are 65 assertions in 46 tests. <strong>Caution:</strong> there are 2 data-providers for valid and 2 more for invalid expressions. One is for URLs and the other for URNs. If you are using a version of PhpUnit of v5.6* or earlier then you need to join the two data providers into a single one.</p>\n\n<pre><code>xavi@bromo:~/custom_www/hello-trip/mutant-migrant$ vendor/bin/phpunit\nPHPUnit 5.7.3 by Sebastian Bergmann and contributors.\n\n.............................................. 46 / 46 (100%)\n\nTime: 82 ms, Memory: 4.00MB\n\nOK (46 tests, 65 assertions)\n</code></pre>\n\n<h1>Code coverage</h1>\n\n<p>There's is 100% of code-coverage in this sample URI checker.</p>\n"
},
{
"answer_id": 42117926,
"author": "Kitson88",
"author_id": 6574422,
"author_profile": "https://Stackoverflow.com/users/6574422",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a simple class for <a href=\"https://github.com/K1tson/URLValidation\" rel=\"nofollow noreferrer\">URL Validation</a> using RegEx and then cross-references the domain against popular RBL (Realtime Blackhole Lists) servers: </p>\n\n<p><strong>Install:</strong> </p>\n\n<pre><code>require 'URLValidation.php';\n</code></pre>\n\n<p><strong>Usage:</strong> </p>\n\n<pre><code>require 'URLValidation.php';\n$urlVal = new UrlValidation(); //Create Object Instance\n</code></pre>\n\n<p>Add a URL as the parameter of the <code>domain()</code> method and check the the return. </p>\n\n<pre><code>$urlArray = ['http://www.bokranzr.com/test.php?test=foo&test=dfdf', 'https://en-gb.facebook.com', 'https://www.google.com'];\nforeach ($urlArray as $k=>$v) {\n\n echo var_dump($urlVal->domain($v)) . ' URL: ' . $v . '<br>';\n\n}\n</code></pre>\n\n<p><strong>Output:</strong> </p>\n\n<pre><code>bool(false) URL: http://www.bokranzr.com/test.php?test=foo&test=dfdf\nbool(true) URL: https://en-gb.facebook.com\nbool(true) URL: https://www.google.com\n</code></pre>\n\n<p>As you can see above, www.bokranzr.com is listed as malicious website via an RBL so the domain was returned as false. </p>\n"
},
{
"answer_id": 51441301,
"author": "Some_North_korea_kid",
"author_id": 9994228,
"author_profile": "https://Stackoverflow.com/users/9994228",
"pm_score": 2,
"selected": false,
"text": "<pre><code>\"/(http(s?):\\/\\/)([a-z0-9\\-]+\\.)+[a-z]{2,4}(\\.[a-z]{2,4})*(\\/[^ ]+)*/i\"\n</code></pre>\n\n<ol>\n<li><p>(http(s?)://) means http:// or https://</p></li>\n<li><p>([a-z0-9-]+.)+ =>\n 2.0[a-z0-9-] means any a-z character or any 0-9 or (-)sign)</p>\n\n<pre><code> 2.1 (+) means the character can be one or more ex: a1w, \n a9-,c559s, f)\n\n 2.2 \\. is (.)sign\n\n 2.3. the (+) sign after ([a-z0-9\\-]+\\.) mean do 2.1,2.2,2.3 \n at least 1 time \n ex: abc.defgh0.ig, aa.b.ced.f.gh. also in case www.yyy.com\n\n 3.[a-z]{2,4} mean a-z at least 2 character but not more than \n 4 characters for check that there will not be \n the case \n ex: https://www.google.co.kr.asdsdagfsdfsf\n\n 4.(\\.[a-z]{2,4})*(\\/[^ ]+)* mean \n\n 4.1 \\.[a-z]{2,4} means like number 3 but start with \n (.)sign \n\n 4.2 * means (\\.[a-z]{2,4})can be use or not use never mind\n\n 4.3 \\/ means \\\n 4.4 [^ ] means any character except blank\n 4.5 (+) means do 4.3,4.4,4.5 at least 1 times\n 4.6 (*) after (\\/[^ ]+) mean use 4.3 - 4.5 or not use \n no problem\n\n use for case https://stackoverflow.com/posts/51441301/edit\n\n 5. when you use regex write in \"/ /\" so it come\n</code></pre>\n\n<p>\"/(http(s?)://)([a-z0-9-]+.)+[a-z]{2,4}(.[a-z]{2,4})<em>(/[^ ]+)</em>/i\"</p>\n\n<pre><code> 6. almost forgot: letter i on the back mean ignore case of \n Big letter or small letter ex: A same as a, SoRRy same \n as sorry.\n</code></pre></li>\n</ol>\n\n<p>Note : Sorry for bad English. My country not use it well.</p>\n"
},
{
"answer_id": 52120682,
"author": "thespacecamel",
"author_id": 1493883,
"author_profile": "https://Stackoverflow.com/users/1493883",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone developing with WordPress, just use </p>\n\n<pre><code>esc_url_raw($url) === $url\n</code></pre>\n\n<p>to validate a URL (<a href=\"https://developer.wordpress.org/reference/functions/esc_url_raw/\" rel=\"nofollow noreferrer\">here's WordPress' documentation on <code>esc_url_raw</code></a>). It handles URLs much better than <code>filter_var($url, FILTER_VALIDATE_URL)</code> because it <em>is</em> unicode and XSS-safe. (<a href=\"https://d-mueller.de/blog/why-url-validation-with-filter_var-might-not-be-a-good-idea/\" rel=\"nofollow noreferrer\">Here is a good article mentioning all the problems with <code>filter_var</code></a>).</p>\n"
},
{
"answer_id": 56791522,
"author": "Fred Vanelli",
"author_id": 3335893,
"author_profile": "https://Stackoverflow.com/users/3335893",
"pm_score": 3,
"selected": false,
"text": "<p>The best URL Regex that worked for me:</p>\n\n<pre><code>function valid_URL($url){\n return preg_match('%^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@|\\d{1,3}(?:\\.\\d{1,3}){3}|(?:(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)(?:\\.(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)*(?:\\.[a-z\\x{00a1}-\\x{ffff}]{2,6}))(?::\\d+)?(?:[^\\s]*)?$%iu', $url);\n}\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>valid_URL('https://twitter.com'); // true\nvalid_URL('http://twitter.com'); // true\nvalid_URL('http://twitter.co'); // true\nvalid_URL('http://t.co'); // true\nvalid_URL('http://twitter.c'); // false\nvalid_URL('htt://twitter.com'); // false\n\nvalid_URL('http://example.com/?a=1&b=2&c=3'); // true\nvalid_URL('http://127.0.0.1'); // true\nvalid_URL(''); // false\nvalid_URL(1); // false\n</code></pre>\n\n<p>Source: <a href=\"http://urlregex.com/\" rel=\"noreferrer\">http://urlregex.com/</a></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26577/"
] |
I've been looking for a simple regex for URLs, does anybody have one handy that works well? I didn't find one with the zend framework validation classes and have seen several implementations.
|
I used this on a few projects, I don't believe I've run into issues, but I'm sure it's not exhaustive:
```
$text = preg_replace(
'#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',
"'<a href=\"$1\" target=\"_blank\">$3</a>$4'",
$text
);
```
Most of the random junk at the end is to deal with situations like `http://domain.example.` in a sentence (to avoid matching the trailing period). I'm sure it could be cleaned up but since it worked. I've more or less just copied it over from project to project.
|
206,062 |
<p>In MySQL 5.0 why does the following error occur when trying to create a view with a subquery in the FROM clause?</p>
<blockquote>
<p>ERROR 1349 (HY000): View's SELECT contains a subquery in the FROM clause</p>
</blockquote>
<p>If this is a limitation of the MySQL engine, then why haven't they implemented this feature yet?</p>
<p>Also, what are some good workarounds for this limitation?</p>
<p>Are there any workarounds that work for any subquery in the FROM clause or are there some queries that can not be expressed without using a subquery in the FROM clause?</p>
<hr>
<p>An example query (was buried in a comment):</p>
<pre><code>SELECT temp.UserName
FROM (SELECT u1.name as UserName, COUNT(m1.UserFromId) as SentCount
FROM Message m1, User u1
WHERE u1.uid = m1.UserFromId
Group BY u1.name HAVING SentCount > 3 ) as temp
</code></pre>
|
[
{
"answer_id": 206118,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 3,
"selected": false,
"text": "<p>It appears to be a known issue.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html</a></p>\n\n<p><a href=\"http://bugs.mysql.com/bug.php?id=16757\" rel=\"noreferrer\">http://bugs.mysql.com/bug.php?id=16757</a></p>\n\n<p>Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example</p>\n\n<pre><code>SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)\n</code></pre>\n\n<p>can be re-written as</p>\n\n<pre><code>SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>SELECT FOO.* FROM FOO \nLEFT OUTER JOIN FOO2 \nON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL\n</code></pre>\n"
},
{
"answer_id": 206164,
"author": "Grant Limberg",
"author_id": 27314,
"author_profile": "https://Stackoverflow.com/users/27314",
"pm_score": 5,
"selected": true,
"text": "<p>Couldn't your query just be written as:</p>\n\n<pre><code>SELECT u1.name as UserName from Message m1, User u1 \n WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3\n</code></pre>\n\n<p>That should also help with the known speed issues with subqueries in MySQL</p>\n"
},
{
"answer_id": 3520552,
"author": "Json on Linux Apache MySQL",
"author_id": 425039,
"author_profile": "https://Stackoverflow.com/users/425039",
"pm_score": 6,
"selected": false,
"text": "<p>I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:</p>\n\n<pre><code>SELECT a.* \nFROM a \nJOIN ( \n SELECT a.alias, MAX(a.year) as max_year \n FROM a \n GROUP BY a.alias\n) b \nON a.alias=b.alias and a.year=b.max_year\n</code></pre>\n\n<p>Outline of solution:</p>\n\n<ol>\n<li>create a view for each subquery</li>\n<li>replace subqueries with those views</li>\n</ol>\n\n<p>Here's the solution query:</p>\n\n<pre><code>CREATE VIEW v_max_year AS \n SELECT alias, MAX(year) as max_year \n FROM a \n GROUP BY a.alias;\n\nCREATE VIEW v_latest_info AS \n SELECT a.* \n FROM a \n JOIN v_max_year b \n ON a.alias=b.alias and a.year=b.max_year;\n</code></pre>\n\n<p>It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing\nthe original sub-query select without any views).</p>\n"
},
{
"answer_id": 15959832,
"author": "Dexin Wang",
"author_id": 1174655,
"author_profile": "https://Stackoverflow.com/users/1174655",
"pm_score": 2,
"selected": false,
"text": "<p>create a view for each subquery is the way to go. Got it working like a charm.</p>\n"
},
{
"answer_id": 28167358,
"author": "Gruff",
"author_id": 375980,
"author_profile": "https://Stackoverflow.com/users/375980",
"pm_score": 3,
"selected": false,
"text": "<p>You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating.\nHere's an example:\n<a href=\"http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/\" rel=\"noreferrer\">http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/</a></p>\n\n<p>This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8784/"
] |
In MySQL 5.0 why does the following error occur when trying to create a view with a subquery in the FROM clause?
>
> ERROR 1349 (HY000): View's SELECT contains a subquery in the FROM clause
>
>
>
If this is a limitation of the MySQL engine, then why haven't they implemented this feature yet?
Also, what are some good workarounds for this limitation?
Are there any workarounds that work for any subquery in the FROM clause or are there some queries that can not be expressed without using a subquery in the FROM clause?
---
An example query (was buried in a comment):
```
SELECT temp.UserName
FROM (SELECT u1.name as UserName, COUNT(m1.UserFromId) as SentCount
FROM Message m1, User u1
WHERE u1.uid = m1.UserFromId
Group BY u1.name HAVING SentCount > 3 ) as temp
```
|
Couldn't your query just be written as:
```
SELECT u1.name as UserName from Message m1, User u1
WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3
```
That should also help with the known speed issues with subqueries in MySQL
|
206,106 |
<p><em>[This question is related to but not the same as <a href="https://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c">this one</a>.]</em></p>
<p>If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (<code>?:</code>) to convert to a bool. Using two not operators (<code>!!</code>) seems to do the same thing.</p>
<p>Here's what I mean:</p>
<pre><code>typedef long T; // similar warning with void * or double
T t = 0;
bool b = t; // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t; // any different?
</code></pre>
<p>So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with <code>void *</code> or <code>double</code> for <code>T</code>)?</p>
<p>I'm not asking if <code>!!t</code> is good style. I am asking if it is semantically different than <code>t ? true : false</code>.</p>
|
[
{
"answer_id": 206120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>All valid techniques, all will generate the same code.</p>\n\n<p>Personally, I just disable the warning so I can use the cleanest syntax. Casting to a bool is not something I'm worried about doing accidentally.</p>\n"
},
{
"answer_id": 206122,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 5,
"selected": false,
"text": "<p>Alternatively, you can do this: <code>bool b = (t != 0)</code></p>\n"
},
{
"answer_id": 206127,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 2,
"selected": false,
"text": "<p>If you're worried about the warning, you can also force the cast: <code>bool b = (bool)t;</code></p>\n"
},
{
"answer_id": 206131,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 3,
"selected": false,
"text": "<p><br>Yes it is safe.</p>\n\n<p><br>0 is interpreted as false, everthing else is true,\n<br>hence !5 comes out as a false\n<br>!0 comes out as true\n<br>so !!5 comes out as true</p>\n"
},
{
"answer_id": 206136,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 1,
"selected": false,
"text": "<p>!! may be compact, but I think it is unnecessarily complicated. Better to disable the warning or use the ternary operator, in my opinion.</p>\n"
},
{
"answer_id": 206139,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": -1,
"selected": false,
"text": "<p>The double not feels funny to me and in debug code will be very different than in optimized code.</p>\n\n<p>If you're in love with !! you could always Macro it.</p>\n\n<pre><code>#define LONGTOBOOL(x) (!!(x))\n</code></pre>\n\n<p>(as an aside, the ternary operator is what I favor in these cases)</p>\n"
},
{
"answer_id": 206140,
"author": "tabdamage",
"author_id": 28022,
"author_profile": "https://Stackoverflow.com/users/28022",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend never suppressing that warning, and never using a c cast (bool) to suppress it. The conversions may not always be called as you assume.</p>\n\n<p>There is a difference between an expression that evaluates to true and a boolean of that value.</p>\n\n<p>Both !! and ternary take getting used to, but will do the job similarly, if you do not want to define internal types with overloaded casts to bool.</p>\n\n<p>Dima's approach is fine too, since it assigns the value of an expression to a bool.</p>\n"
},
{
"answer_id": 206156,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I would use b = (0 != t) -- at least any sane person can read it easily. If I would see double dang in the code, I would be pretty much surprised.</p>\n"
},
{
"answer_id": 206200,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 7,
"selected": true,
"text": "<p>The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for </p>\n\n<pre><code>b = (t != 0);\n</code></pre>\n\n<p>No implicit conversions.</p>\n"
},
{
"answer_id": 206219,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": "<p>I would not use:</p>\n\n<pre><code>bool b = !!t;\n</code></pre>\n\n<p>That is the least readable way (and thus the hardest to maintain)</p>\n\n<p>The others depend on the situation.<br>\nIf you are converting to use in a bool expression only.</p>\n\n<pre><code>bool b = t ? true : false;\nif (b)\n{\n doSomething();\n}\n</code></pre>\n\n<p>Then I would let the language do it for you:<br></p>\n\n<pre><code>if (t)\n{\n doSomething();\n}\n</code></pre>\n\n<p>If you are actually storing a boolean value. Then first I would wonder why you have a long in the first places that requires the cast. Assuming you need the long and the bool value I would consider all the following depending on the situation.</p>\n\n<pre><code>bool b = t ? true : false; // Short and too the point.\n // But not everybody groks this especially beginners.\nbool b = (t != 0); // Gives the exact meaning of what you want to do.\nbool b = static_cast<bool>(t); // Implies that t has no semantic meaning\n // except as a bool in this context.\n</code></pre>\n\n<p>Summary:\nUse what provides the most meaning for the context you are in.<br>\nTry and make it obvious what you are doing<br></p>\n"
},
{
"answer_id": 206287,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": -1,
"selected": false,
"text": "<p>I would use bool b = t and leave the compile warning in, commenting on this particular line's safety. Disabling the warning may bite you in the butt in another part of the code.</p>\n"
},
{
"answer_id": 206317,
"author": "Marco M.",
"author_id": 28375,
"author_profile": "https://Stackoverflow.com/users/28375",
"pm_score": -1,
"selected": false,
"text": "<p>I recommend to use</p>\n\n<p>if (x != 0)</p>\n\n<p>or </p>\n\n<p>if (x != NULL)</p>\n\n<p>instead of if(x); it's more understandable and readable.</p>\n"
},
{
"answer_id": 206345,
"author": "edgar.holleis",
"author_id": 24937,
"author_profile": "https://Stackoverflow.com/users/24937",
"pm_score": 5,
"selected": false,
"text": "<p>Careful!</p>\n\n<ul>\n<li>A boolean is about truth and falseness.</li>\n<li>An integer is about whole numbers.</li>\n</ul>\n\n<p>Those are very distinct concepts:</p>\n\n<ul>\n<li>Truth and falseness is about deciding stuff.</li>\n<li>Numbers are about counting stuff.</li>\n</ul>\n\n<p>When bridging those concepts, it should be done explicitly. I like Dima's version best:</p>\n\n<p><code>b = (t != 0);</code></p>\n\n<p>That code clearly says: Compare two numbers and store the truth-value in a boolean.</p>\n"
},
{
"answer_id": 206493,
"author": "Jim In Texas",
"author_id": 15079,
"author_profile": "https://Stackoverflow.com/users/15079",
"pm_score": 2,
"selected": false,
"text": "<p>I really hate !!t!!!!!!. It smacks of the worst thing about C and C++, the temptation to be too clever by half with your syntax.</p>\n\n<p>bool b(t != 0); // Is the best way IMHO, it explicitly shows what is happening.</p>\n"
},
{
"answer_id": 206742,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>Disable the warning.</p>\n\n<p>Write for clarity first; then profile; then optimize for speed, where required.</p>\n"
},
{
"answer_id": 206947,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 0,
"selected": false,
"text": "<p>!! is only useful when you're using a boolean expression in arithmetic fashion, e.g.:</p>\n\n<pre><code>c = 3 + !!extra; //3 or 4\n</code></pre>\n\n<p>(Whose style is a different discussion.) When all you need is a boolean expression, the !! is redundant. Writing</p>\n\n<pre><code>bool b = !!extra;\n</code></pre>\n\n<p>makes as much sense as:</p>\n\n<pre><code>if (!!extra) { ... }\n</code></pre>\n"
},
{
"answer_id": 50522954,
"author": "Jay K",
"author_id": 5751393,
"author_profile": "https://Stackoverflow.com/users/5751393",
"pm_score": 2,
"selected": false,
"text": "<p>Comparison to 0 doesn't work so well.\nWhich comes back -- why !! vs. ternary?</p>\n\n<pre><code>class foo { public: explicit operator bool () ; };\n\nfoo f;\n\nauto a = f != 0; // invalid operands to binary expression ('foo' and 'int')\nauto b = f ? true : false; // ok\nauto c = !!f; // ok\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
*[This question is related to but not the same as [this one](https://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c).]*
If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (`?:`) to convert to a bool. Using two not operators (`!!`) seems to do the same thing.
Here's what I mean:
```
typedef long T; // similar warning with void * or double
T t = 0;
bool b = t; // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t; // any different?
```
So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with `void *` or `double` for `T`)?
I'm not asking if `!!t` is good style. I am asking if it is semantically different than `t ? true : false`.
|
The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for
```
b = (t != 0);
```
No implicit conversions.
|
206,114 |
<p>How you can read a file (text or binary) from a batch file? There is a way to read it in a binary mode or text mode?</p>
|
[
{
"answer_id": 206137,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 6,
"selected": false,
"text": "<p>Under NT-style cmd.exe, you can loop through the lines of a text file with</p>\n<pre><code>FOR /F %%i IN (file.txt) DO @echo %%i\n</code></pre>\n<p>Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)</p>\n"
},
{
"answer_id": 206145,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 6,
"selected": true,
"text": "<p>You can use the for command:</p>\n\n<pre><code>FOR /F \"eol=; tokens=2,3* delims=, \" %i in (myfile.txt) do @echo %i %j %k\n</code></pre>\n\n<p>Type</p>\n\n<pre><code>for /?\n</code></pre>\n\n<p>at the command prompt. Also, you can <a href=\"http://www.ericphelps.com/batch/samples/getini.txt\" rel=\"noreferrer\">parse ini files</a>!</p>\n"
},
{
"answer_id": 4531090,
"author": "jeb",
"author_id": 463115,
"author_profile": "https://Stackoverflow.com/users/463115",
"pm_score": 6,
"selected": false,
"text": "<p>The FOR-LOOP generally works, but there are some issues.\nThe FOR doesn't accept empty lines and lines with more than ~8190 are problematic.\nThe expansion works only reliable, if the delayed expansion is disabled.</p>\n\n<p>Detection of CR/LF versus single LF seems also a little bit complicated.<br>\nAlso NUL characters are problematic, as a FOR-Loop immediatly cancels the reading.</p>\n\n<p><em>Direct</em> binary reading seems therefore nearly impossible.</p>\n\n<p>The problem with empty lines can be solved with a trick. Prefix each line with a line number, using the findstr command, and after reading, remove the prefix.</p>\n\n<pre><code>@echo off\nSETLOCAL DisableDelayedExpansion\nFOR /F \"usebackq delims=\" %%a in (`\"findstr /n ^^ t.txt\"`) do (\n set \"var=%%a\"\n SETLOCAL EnableDelayedExpansion\n set \"var=!var:*:=!\"\n echo(!var!\n ENDLOCAL\n)\n</code></pre>\n\n<p><strong>Toggling between enable and disabled delayed expansion is neccessary</strong> for the safe working with strings, like <code>!</code> or <code>^^^xy!z</code>.<br>\nThat's because the line <code>set \"var=%%a\"</code> is only safe with <em>DisabledDelayedExpansion</em>, else exclamation marks are removed and the carets are used as (secondary) escape characters and they are removed too.<br>\nBut using the variable <code>var</code> is only safe with <em>EnabledDelayedExpansion</em>, as even a <code>call %%var%%</code> will fail with content like <code>\"&\"&</code>.</p>\n\n<p><strong>EDIT: Added set/p variant</strong><br>\nThere is a second way of reading a file with <code>set /p</code>, the only disadvantages are that it is limited to ~1024 characters per line and it removes control characters at the line end.<br>\nBut the advantage is, you didn't need the delayed toggling and it's easier to store values in variables</p>\n\n<pre><code>@echo off\nsetlocal EnableDelayedExpansion\nset \"file=%~1\"\n\nfor /f \"delims=\" %%n in ('find /c /v \"\" %file%') do set \"len=%%n\"\nset \"len=!len:*: =!\"\n\n<%file% (\n for /l %%l in (1 1 !len!) do (\n set \"line=\"\n set /p \"line=\"\n echo(!line!\n )\n)\n</code></pre>\n\n<p><strong>For reading it \"binary\" into a hex-representation</strong><br>\nYou could look at <a href=\"https://stackoverflow.com/a/4648636/463115\">SO: converting a binary file to HEX representation using batch file</a></p>\n"
},
{
"answer_id": 39479326,
"author": "NetvorMcWolf",
"author_id": 6828401,
"author_profile": "https://Stackoverflow.com/users/6828401",
"pm_score": 1,
"selected": false,
"text": "<p>Well theres a lot of different ways but if you only want to DISPLAY the text and not STORE it anywhere then you just use: <code>findstr /v \"randomtextthatnoonewilluse\" filename.txt</code></p>\n"
},
{
"answer_id": 45624844,
"author": "J. Bond",
"author_id": 7811378,
"author_profile": "https://Stackoverflow.com/users/7811378",
"pm_score": 4,
"selected": false,
"text": "<p>One very easy way to do it is use the following command:</p>\n\n<pre><code>set /p mytextfile=< %pathtotextfile%\\textfile.txt\necho %mytextfile%\n</code></pre>\n\n<p>This will only display the first line of text in a text file. The other way you can do it is use the following command:</p>\n\n<pre><code>type %pathtotextfile%\\textfile.txt\n</code></pre>\n\n<p>This will put all the data in the text file on the screen. Hope this helps!</p>\n"
},
{
"answer_id": 56600202,
"author": "Celes",
"author_id": 9086531,
"author_profile": "https://Stackoverflow.com/users/9086531",
"pm_score": 0,
"selected": false,
"text": "<p>Corrected code :</p>\n\n<pre><code>setlocal enabledelayedexpansion\nfor /f \"usebackq eol= tokens=* delims= \" %%a in (`findstr /n ^^^^ \"name with spaces.txt\"`) do (\n set line=%%a\n set \"line=!line:*:=!\"\n echo(!line!\n)\nendlocal\npause\n</code></pre>\n"
},
{
"answer_id": 72460077,
"author": "Kuza Grave",
"author_id": 7806306,
"author_profile": "https://Stackoverflow.com/users/7806306",
"pm_score": 1,
"selected": false,
"text": "<p><strong>settings.ini</strong></p>\n<pre><code>name="John"\nlastName="Doe"\n</code></pre>\n<p><strong>script.bat</strong></p>\n<pre><code>@echo off\nfor /f "tokens=1,2 delims==" %%a in (settings.ini) do (\n if %%a==name set %%a=%%b\n if %%a==lastName set %%a=%%b\n)\n\necho %name% %lastName%\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] |
How you can read a file (text or binary) from a batch file? There is a way to read it in a binary mode or text mode?
|
You can use the for command:
```
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
```
Type
```
for /?
```
at the command prompt. Also, you can [parse ini files](http://www.ericphelps.com/batch/samples/getini.txt)!
|
206,132 |
<p>Platform: IIS 6, ASP.Net 2.0 (.Net 3.5), Server 2003.</p>
<p>I'm building an application that accepts files from a user, processes them, and returns a result. The file is uploaded using HTTP POST to an ASP.Net web form. The application is expecting some large files (hundreds of MB).</p>
<p>I'm using SWFUpload to accomplish the upload with a nice progress bar, but that's not contributing to the issue, because when I bypass it using a standard HTML form pointing at my upload accepter page, I get the exact same error. When using the progress bar, the upload continues to 100%, then fails. With a standard form, the behavior appears to be the same. </p>
<p>I'm having a problem right now uploading a file that's about 150MB. I've changed every settings I can find, but still no luck. </p>
<p>Here's a summary of what I've changed so far:</p>
<p>In Web.config:
Added this inside system.web:</p>
<pre><code><httpRuntime executionTimeout="3600" maxRequestLength="1536000"/>
</code></pre>
<p>In machine.config:
Inside system.web, changed:</p>
<pre><code><processModel autoConfig="true" />
</code></pre>
<p>to: </p>
<pre><code><processModel autoConfig="true" responseDeadlockInterval="00:30:00" responseRestartDeadlockInterval="00:30:00" />
</code></pre>
<p>and in MetaBase.xml:
Changed:</p>
<pre><code>AspMaxRequestEntityAllowed="204800"
</code></pre>
<p>to:</p>
<pre><code>AspMaxRequestEntityAllowed="200000000"
</code></pre>
<p>When the upload fails, I get a 404 error from IIS. My web form does not begin processing, or at least, it doesn't make it to the Page_Load event. I threw an exception at the beginning of that handler, and it doesn't execute at all on large files. </p>
<p>Everything works fine with smaller files (I've tested up to about 5.5MB). I'm not exactly sure what file size is the limit, but I know that my limit needs to be higher than 150MB, since this is not the largest file that the client will need to upload. </p>
<p>Can anyone help?</p>
|
[
{
"answer_id": 206141,
"author": "Chris Roland",
"author_id": 27975,
"author_profile": "https://Stackoverflow.com/users/27975",
"pm_score": 2,
"selected": false,
"text": "<p>When we ran into this issue we had to increase the buffer size limit according to this KB article:\n<a href=\"http://support.microsoft.com/kb/944886/en-us\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/944886/en-us</a></p>\n\n<p>I know this mentions ASP, but I believe it worked for ASP.NET as well.</p>\n\n<p>Edit: Here is a link that might be more relevant to your issue and provide other options:<br>\n<a href=\"http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx</a></p>\n"
},
{
"answer_id": 206176,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 1,
"selected": false,
"text": "<p>404 and missing Page_Load: IIS can only process the request once the complete POST is on the server. Therefore, if the POST fails (due to its size), it cannot fire the page's events.</p>\n\n<p>You might try NeatUpload <a href=\"http://www.brettle.com/neatupload\" rel=\"nofollow noreferrer\">http://www.brettle.com/neatupload</a>.\nFrom the Manual: \"By default, NeatUpload does not directly limit the size of uploads.\"</p>\n"
},
{
"answer_id": 206796,
"author": "Chris Weisel",
"author_id": 28358,
"author_profile": "https://Stackoverflow.com/users/28358",
"pm_score": 4,
"selected": true,
"text": "<p>Urlscan was active on all websites, and has it's own request entity length limit. I wasn't aware that Urlscan was running on our server because it was a global ISAPI filter, not running on my individual website. </p>\n\n<p>Note: to locate global ISAPI filters, right click on the Web Sites folder in IIS Admin and click Properties, then on the ISAPI Filters tab. </p>\n"
},
{
"answer_id": 323812,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can also try <a href=\"http://www.codeplex.com/velodocxp\" rel=\"nofollow noreferrer\">Velodoc XP Edition</a> which has several advantages over NeatUpload including the fact that it uses ASP.NET Ajax extensions. See also <a href=\"http://www.velodoc.com\" rel=\"nofollow noreferrer\">the Velodoc web site</a> for more information.</p>\n"
},
{
"answer_id": 1191943,
"author": "Ewan Makepeace",
"author_id": 9731,
"author_profile": "https://Stackoverflow.com/users/9731",
"pm_score": 0,
"selected": false,
"text": "<p>You say:</p>\n\n<p></p>\n\n<p>But 1536000 is only 1.5MB?</p>\n"
},
{
"answer_id": 8568011,
"author": "Manish Jain",
"author_id": 486867,
"author_profile": "https://Stackoverflow.com/users/486867",
"pm_score": 2,
"selected": false,
"text": "<p>(A note for googlers):</p>\n\n<p>For IIS7 add below to web.config (I added above <code><system.serviceModel></code>):</p>\n\n<pre><code><system.webServer>\n <security>\n <requestFiltering><requestLimits maxAllowedContentLength=\"262144000\" /></requestFiltering> <!-- maxAllowedContentLength is in bytes. Defaults to 30,000,000 -->\n </security>\n</system.webServer>\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28358/"
] |
Platform: IIS 6, ASP.Net 2.0 (.Net 3.5), Server 2003.
I'm building an application that accepts files from a user, processes them, and returns a result. The file is uploaded using HTTP POST to an ASP.Net web form. The application is expecting some large files (hundreds of MB).
I'm using SWFUpload to accomplish the upload with a nice progress bar, but that's not contributing to the issue, because when I bypass it using a standard HTML form pointing at my upload accepter page, I get the exact same error. When using the progress bar, the upload continues to 100%, then fails. With a standard form, the behavior appears to be the same.
I'm having a problem right now uploading a file that's about 150MB. I've changed every settings I can find, but still no luck.
Here's a summary of what I've changed so far:
In Web.config:
Added this inside system.web:
```
<httpRuntime executionTimeout="3600" maxRequestLength="1536000"/>
```
In machine.config:
Inside system.web, changed:
```
<processModel autoConfig="true" />
```
to:
```
<processModel autoConfig="true" responseDeadlockInterval="00:30:00" responseRestartDeadlockInterval="00:30:00" />
```
and in MetaBase.xml:
Changed:
```
AspMaxRequestEntityAllowed="204800"
```
to:
```
AspMaxRequestEntityAllowed="200000000"
```
When the upload fails, I get a 404 error from IIS. My web form does not begin processing, or at least, it doesn't make it to the Page\_Load event. I threw an exception at the beginning of that handler, and it doesn't execute at all on large files.
Everything works fine with smaller files (I've tested up to about 5.5MB). I'm not exactly sure what file size is the limit, but I know that my limit needs to be higher than 150MB, since this is not the largest file that the client will need to upload.
Can anyone help?
|
Urlscan was active on all websites, and has it's own request entity length limit. I wasn't aware that Urlscan was running on our server because it was a global ISAPI filter, not running on my individual website.
Note: to locate global ISAPI filters, right click on the Web Sites folder in IIS Admin and click Properties, then on the ISAPI Filters tab.
|
206,142 |
<p>I have a full text catalog with two tables in it.</p>
<p>tableA has 4 columns (a1, a2, a3, a4) of which 3 are indexed in the catalog, a2,a3,a4.
a1 is the primary key.</p>
<p>tableB has 3 columns (b1, b2, b3, b4), two of which are indexed in the catalog, b3 and b4. b1 is the PK of this table, b2 is the FK to tableA.</p>
<p>I want to do something like</p>
<pre><code>SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank
FROM tableA
INNER JOIN tableB ON tableA.a1=tableB.b2
INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY]
INNER JOIN FREETEXTTABLE(tableB, (b3,b4), 'search term') as ftTableB ON tableB.11=ftTableB.[KEY]
</code></pre>
<p>But this does not work...
I can get a single table to work, eg.</p>
<pre><code>SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank
FROM tableA
INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY]
</code></pre>
<p>but never more than one table.</p>
<p>Could someone give an explanation and/or example of the steps required to full-text search over multiple tables.</p>
|
[
{
"answer_id": 209763,
"author": "Dave_H",
"author_id": 17109,
"author_profile": "https://Stackoverflow.com/users/17109",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not positive that I understood what you were trying to do. I interpreted your question as you want to return all items in Table A that matched the search term. Furthermore you wanted to sum the rank from the item in TableA plus the matching items in TableB.</p>\n\n<p>The best way I can think to do this is to use a table variable with 3 queries.</p>\n\n<pre>DECLARE @Results Table (a1 Int UNIQUE, Rank Int)\n\n--Insert into @Results all matching items from TableA\nINSERT INTO @Results\n(a1, Rank)\n( SELECT TableA.a1, FT.Rank\nFROM TableA INNER JOIN FreeTextTable(TableA, *, 'search term') FT\nON TableA.A1 = FT.[Key]\n)\n\n--Update all of the ranks in @Results with a sum of current value plus the sum of\n--all sub items (in TableB)\nUPDATE @Results\nSET Rank = RS.Rank + FT.Rank\nFROM @Results RS INNER JOIN TableB\nON RS.A1 = TableB.b2\nINNER JOIN FreeTextTable(TableB, *, 'search term') FT\nON TableB.b1 = FT.[Key]\n\n--Now insert into @Results any items that has a match in TableB but not in TableA\n--This query may/may not be desired based on your business rules.\nINSERT INTO @Results\n(SkillKeyId, Rank)\n( SELECT TableB.b2, Sum(FT.Rank)\nFROM TableB INNER JOIN FreeTextTable(TableB, *, 'search term') FT\nON TableB.b1 = FT.[key]\nLEFT JOIN @Results RS\nON RS.a1 = TableB.b2\nWHERE RS.a1 IS NULL\nGROUP BY TableB.b2\n)\n\n--All that's left is to return the results\nSELECT TableA.*, RS.Rank AS Total_Rank\nFROM TableA INNER JOIN @Results RS\nON TableA.a1 = RS.a1\nORDER BY RS.Rank DESC\n\n</pre>\n\n<p>This isn't as elegant as using one query, but it should be easy to follow and allows you to decide whether or not to include records in the 3rd query.</p>\n"
},
{
"answer_id": 209809,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": false,
"text": "<p>Your query only returns records, if both A and related B contains the search text.</p>\n\n<p>You do not state what does not work, though.</p>\n\n<p>Why not LEFT OUTER JOIN the fulltext searches, and replace:</p>\n\n<pre><code>SELECT *, (ISNULL(ftTableA.[RANK], 0) + ISNULL(ftTableB.[RANK], 0)) AS total_rank \n</code></pre>\n\n<p>and</p>\n\n<pre><code>WHERE ftTableA.Key IS NOT NULL OR ftTableB.Key IS NOT NULL\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1741868/"
] |
I have a full text catalog with two tables in it.
tableA has 4 columns (a1, a2, a3, a4) of which 3 are indexed in the catalog, a2,a3,a4.
a1 is the primary key.
tableB has 3 columns (b1, b2, b3, b4), two of which are indexed in the catalog, b3 and b4. b1 is the PK of this table, b2 is the FK to tableA.
I want to do something like
```
SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank
FROM tableA
INNER JOIN tableB ON tableA.a1=tableB.b2
INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY]
INNER JOIN FREETEXTTABLE(tableB, (b3,b4), 'search term') as ftTableB ON tableB.11=ftTableB.[KEY]
```
But this does not work...
I can get a single table to work, eg.
```
SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank
FROM tableA
INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY]
```
but never more than one table.
Could someone give an explanation and/or example of the steps required to full-text search over multiple tables.
|
I'm not positive that I understood what you were trying to do. I interpreted your question as you want to return all items in Table A that matched the search term. Furthermore you wanted to sum the rank from the item in TableA plus the matching items in TableB.
The best way I can think to do this is to use a table variable with 3 queries.
```
DECLARE @Results Table (a1 Int UNIQUE, Rank Int)
--Insert into @Results all matching items from TableA
INSERT INTO @Results
(a1, Rank)
( SELECT TableA.a1, FT.Rank
FROM TableA INNER JOIN FreeTextTable(TableA, *, 'search term') FT
ON TableA.A1 = FT.[Key]
)
--Update all of the ranks in @Results with a sum of current value plus the sum of
--all sub items (in TableB)
UPDATE @Results
SET Rank = RS.Rank + FT.Rank
FROM @Results RS INNER JOIN TableB
ON RS.A1 = TableB.b2
INNER JOIN FreeTextTable(TableB, *, 'search term') FT
ON TableB.b1 = FT.[Key]
--Now insert into @Results any items that has a match in TableB but not in TableA
--This query may/may not be desired based on your business rules.
INSERT INTO @Results
(SkillKeyId, Rank)
( SELECT TableB.b2, Sum(FT.Rank)
FROM TableB INNER JOIN FreeTextTable(TableB, *, 'search term') FT
ON TableB.b1 = FT.[key]
LEFT JOIN @Results RS
ON RS.a1 = TableB.b2
WHERE RS.a1 IS NULL
GROUP BY TableB.b2
)
--All that's left is to return the results
SELECT TableA.*, RS.Rank AS Total_Rank
FROM TableA INNER JOIN @Results RS
ON TableA.a1 = RS.a1
ORDER BY RS.Rank DESC
```
This isn't as elegant as using one query, but it should be easy to follow and allows you to decide whether or not to include records in the 3rd query.
|
206,161 |
<p>How would I get the length of an <code>ArrayList</code> using a JSF EL expression? </p>
<pre><code>#{MyBean.somelist.length}
</code></pre>
<p>does not work.</p>
|
[
{
"answer_id": 206252,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 8,
"selected": true,
"text": "<p>Yes, since some genius in the Java API creation committee decided that, even though certain classes have <code>size()</code> members or <code>length</code> attributes, they won't implement <code>getSize()</code> or <code>getLength()</code> which JSF and most other standards require, you can't do what you want.</p>\n\n<p>There's a couple ways to do this.</p>\n\n<p>One: add a function to your Bean that returns the length:</p>\n\n<pre>\nIn class MyBean:\npublic int getSomelistLength() { return this.somelist.length; }\n\nIn your JSF page:\n#{MyBean.somelistLength}\n</pre>\n\n<p>Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function</p>\n\n<pre>\nIn JSF page:\n#{ fn:length(MyBean.somelist) }\n</pre>\n"
},
{
"answer_id": 208093,
"author": "Damo",
"author_id": 2955,
"author_profile": "https://Stackoverflow.com/users/2955",
"pm_score": 6,
"selected": false,
"text": "<p>You mean size() don't you?</p>\n\n<pre><code>#{MyBean.somelist.size()}\n</code></pre>\n\n<p>works for me (using JBoss Seam which has the Jboss EL extensions)</p>\n"
},
{
"answer_id": 212026,
"author": "Romain Linsolas",
"author_id": 26457,
"author_profile": "https://Stackoverflow.com/users/26457",
"pm_score": 0,
"selected": false,
"text": "<p>You can eventually extend the EL language by using the <a href=\"http://el-functors.sourceforge.net\" rel=\"nofollow noreferrer\">EL Functor</a>, which will allow you to call any Java beans methods, even with parameters...</p>\n"
},
{
"answer_id": 1361935,
"author": "James McMahon",
"author_id": 20774,
"author_profile": "https://Stackoverflow.com/users/20774",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Note:</strong> This solution is better for older versions of JSTL. For versions greater then 1.1 I recommend using <code>fn:length(MyBean.somelist)</code> as suggested by <a href=\"https://stackoverflow.com/questions/206161/how-do-you-get-the-length-of-a-list-in-the-jsf-expression-language/206252#206252\">Bill James</a>.</p>\n<hr>\n<p><a href=\"http://www.informit.com/articles/article.aspx?p=30946&seqNum=8\" rel=\"noreferrer\">This article</a> has some more detailed information, including another possible solution;</p>\n<blockquote>\n<p>The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.</p>\n<p>There are two ways to address this dilemma. First, you can use the RT Core library, like this:</p>\n</blockquote>\n<pre><code><c_rt:out value='<%= list[list.size()-1] %>'/>\n</code></pre>\n<blockquote>\n<p>Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.</p>\n</blockquote>\n<p>The problem with c_rt method is that you need to get the variable from request manually, because it doesn't recognize it otherwise. At this point you are putting in a lot of code for what should be built in functionality. This is a <strong>GIANT</strong> flaw in the EL.</p>\n<p>I ended up using the "wrapper" method, here is the class for it;</p>\n<pre><code>public class CollectionWrapper {\n\n Collection collection;\n\n public CollectionWrapper(Collection collection) {\n this.collection = collection;\n }\n\n public Collection getCollection() {\n return collection;\n }\n\n public int getSize() {\n return collection.size();\n }\n}\n</code></pre>\n<p>A third option that no one has mentioned yet is to put your list size into the model (assuming you are using MVC) as a separate attribute. So in your model you would have "someList" and then "someListSize". That may be simplest way to solve this issue.</p>\n"
},
{
"answer_id": 15131294,
"author": "UdayKiran Pulipati",
"author_id": 1624035,
"author_profile": "https://Stackoverflow.com/users/1624035",
"pm_score": 3,
"selected": false,
"text": "<pre><code><%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\"%>\n\n<h:outputText value=\"Table Size = #{fn:length(SystemBean.list)}\"/>\n</code></pre>\n\n<p>On screen it displays the Table size</p>\n\n<p>Example: <code>Table Size = 5</code></p>\n"
},
{
"answer_id": 25023603,
"author": "Soujanya",
"author_id": 1204688,
"author_profile": "https://Stackoverflow.com/users/1204688",
"pm_score": -1,
"selected": false,
"text": "<p>You can get the length using the following EL:</p>\n\n<p><strong>#{Bean.list.size()}</strong></p>\n"
},
{
"answer_id": 43083011,
"author": "Arry",
"author_id": 3204788,
"author_profile": "https://Stackoverflow.com/users/3204788",
"pm_score": 2,
"selected": false,
"text": "<p>After 7 years... the facelets solution still works fine for me as a jsf user</p>\n\n<p>include the namespace as \n<code>xmlns:fn=\"http://java.sun.com/jsp/jstl/functions\"</code></p>\n\n<p>and use the EL as \n<code>#{fn:length(myBean.someList)}</code> for example if using in jsf ui:fragment below example works fine</p>\n\n<pre><code><ui:fragment rendered=\"#{fn:length(myBean.someList) gt 0}\">\n <!-- Do something here-->\n</ui:fragment>\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17614/"
] |
How would I get the length of an `ArrayList` using a JSF EL expression?
```
#{MyBean.somelist.length}
```
does not work.
|
Yes, since some genius in the Java API creation committee decided that, even though certain classes have `size()` members or `length` attributes, they won't implement `getSize()` or `getLength()` which JSF and most other standards require, you can't do what you want.
There's a couple ways to do this.
One: add a function to your Bean that returns the length:
```
In class MyBean:
public int getSomelistLength() { return this.somelist.length; }
In your JSF page:
#{MyBean.somelistLength}
```
Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function
```
In JSF page:
#{ fn:length(MyBean.somelist) }
```
|
206,183 |
<p>I want subversion to commit a file even if it's unchanged. Is there a way to do this?</p>
|
[
{
"answer_id": 206196,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that's possible, but first of all why do you need to do that? If a file is unchanged it shouldn't be commited.</p>\n\n<p>If you really want that file grouped with other files in a commit you could change something minor inside (add a space for example).</p>\n"
},
{
"answer_id": 206218,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 2,
"selected": false,
"text": "<p>If it's a text file just add some whitespace, such as a line feed.</p>\n"
},
{
"answer_id": 206856,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 7,
"selected": true,
"text": "<p>If you want the file contents to remain unchanged (meaning that you can't merely change whitespace as johnstok suggested) you can always change one of the properties on the file.</p>\n\n<p>eg.</p>\n\n<pre>\nsvn propset dummyproperty 1 yourfile\nsvn commit yourfile\n</pre>\n\n<p>That will perform a commit without having to change the file.</p>\n\n<p>Just make sure that you don't use one of the special <code>svn:</code> properties. Anything else should be ok.</p>\n\n<hr>\n\n<p>Edit:\nA number of other posters have asked why someone would want to do this - presumably the people who have marked this answer down have also had the same concerns.</p>\n\n<p>I can't speak for the original poster, but one scenario where I have seen this used is when attempting to automatically synchronise activities on a Visual Sourcesafe repository with a subversion repository.</p>\n"
},
{
"answer_id": 253086,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": -1,
"selected": false,
"text": "<p>I thought you could do it from the command line?</p>\n\n<pre><code>svn ci -force <filename>\n</code></pre>\n\n<p>I don't have a repository here to check that on, so I might be wrong.</p>\n"
},
{
"answer_id": 384433,
"author": "Mat",
"author_id": 42974,
"author_profile": "https://Stackoverflow.com/users/42974",
"pm_score": 2,
"selected": false,
"text": "<p>I frigged this by deleting then re-adding the offending file. Not the nicest way to do it, and it probably broke the revision history, but it suited my purposes.</p>\n\n<p>Reason for wanting to do it: File was one of two executables built from the same source (with different #defines set). Minor change to source meant one had changed, one didn't. I wanted to record in the revision history that I had actually updated it to the latest version (even though there was no change).</p>\n\n<p>Maybe Morten Holdflod Møller's point that \"the file will still be a part of the new revision\" would cover this indication, but I think a log of the unchanged file did not show comments for that revision.</p>\n"
},
{
"answer_id": 813579,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Actually, I have come across a reason to do a force commit. This probably isn't best practice but we put Truecrypt (<a href=\"http://www.truecrypt.org/\" rel=\"nofollow noreferrer\">http://www.truecrypt.org/</a>) volumes in SVN because we need to keep a tight security on some shell script as it contains sensitive information. When a Truecrypt volume is created, it's binary data stays the same no matter what you do with it. So in effect, I can change the contents of the volume but the volume never appears changed.</p>\n"
},
{
"answer_id": 813595,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Changing the property will NOT force the commit.</p>\n\n<p>TortoiseSVN 1.4.5, Build 10425 - 32 Bit , 2007/08/26 11:14:13</p>\n"
},
{
"answer_id": 1044792,
"author": "user41806",
"author_id": 41806,
"author_profile": "https://Stackoverflow.com/users/41806",
"pm_score": -1,
"selected": false,
"text": "<p>I have the same problem with a trueCrypt volume.</p>\n\n<p>I added a new property (as suggested above) \"forceCommit1\" and them I was able to commit the volume file. but only the property was commited not the contents of the file.</p>\n\n<p>I removed the file and added it again to the svn</p>\n"
},
{
"answer_id": 2086317,
"author": "user253217",
"author_id": 253217,
"author_profile": "https://Stackoverflow.com/users/253217",
"pm_score": 3,
"selected": false,
"text": "<p>As to answer why one would like to do forced commits. I've seen cases where someone used a commit message that was wrong or unclear. It's nice if you can perform a forced commit, where you can correct this mistake. That way the updated commit message goes into the repository, so it won't get lost.</p>\n"
},
{
"answer_id": 2379551,
"author": "agata",
"author_id": 286278,
"author_profile": "https://Stackoverflow.com/users/286278",
"pm_score": 2,
"selected": false,
"text": "<p>Answering some people questioning this should be possible: for some reason svn doesn't recognizes differences between doc files, so I would like to force commit as well!</p>\n\n<p>I am now moving documentation from static dirs, to svn. files are like UG_v1.2, UG_v1.3 etc.\nSo just to keep history, I take 1.2, remove version from the filename and add and commit it to svn.\nThen I take the ver from the second one, copy it over the first one and want to commit it and newer version. File size and creation date changes (not mentioning what's inside the doc), but svn claims it's perfectly the same file and disallows me to commit.\nWhen I manually change the doc, svn sees the different.\nThe heck? :></p>\n"
},
{
"answer_id": 4334768,
"author": "Sergiy Sokolenko",
"author_id": 131337,
"author_profile": "https://Stackoverflow.com/users/131337",
"pm_score": 0,
"selected": false,
"text": "<p>The reason why someone wants to commit unchanged file is misunderstanding of how to revert to a previous version of a file.</p>\n\n<p>For example, one may revert the file <code>index.html</code> in the revision <strong>680</strong> by just updating it to a revision in the past, e.g. <strong>650</strong>:</p>\n\n<p><code>svn update index.html -r 650</code></p>\n\n<p>but it does not solve the problem, because:</p>\n\n<pre>\nsvn status -u index.html\n * 650 index.html\nStatus against revision: 680\n</pre>\n\n<p>svn clearly says that index.html is <em>modified remotely</em> and you can't commit it, i.e. it \"thinks\" that index.html is old and should be updated to a newer revision. So the next <code>svn update</code> will bring index.html back to the revision <strong>680</strong>.</p>\n\n<p>To really revert a file you should merge it in reverse order:</p>\n\n<p><code>svn merge -r 680:650 index.html</code></p>\n\n<p>and then commit it <code>svn ci -m \"Reverted to r650\" index.html</code></p>\n"
},
{
"answer_id": 70679110,
"author": "endangered",
"author_id": 10473703,
"author_profile": "https://Stackoverflow.com/users/10473703",
"pm_score": 0,
"selected": false,
"text": "<p>Ancient question, but here's one reason why someone would want to do this:</p>\n<p>We use an svn "commit" to document the successful outcome of a code review. During the code review, a certain subset of files is examined (and potentially modified). But files that are found to pass the review as-is will remain unmodified.</p>\n<p>The idea is to use the commit to document which files were reviewed. That should include the ones that were found to pass the review without any modifications. Hence the need to "re-commit" ("force-commit") them unmodified.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15992/"
] |
I want subversion to commit a file even if it's unchanged. Is there a way to do this?
|
If you want the file contents to remain unchanged (meaning that you can't merely change whitespace as johnstok suggested) you can always change one of the properties on the file.
eg.
```
svn propset dummyproperty 1 yourfile
svn commit yourfile
```
That will perform a commit without having to change the file.
Just make sure that you don't use one of the special `svn:` properties. Anything else should be ok.
---
Edit:
A number of other posters have asked why someone would want to do this - presumably the people who have marked this answer down have also had the same concerns.
I can't speak for the original poster, but one scenario where I have seen this used is when attempting to automatically synchronise activities on a Visual Sourcesafe repository with a subversion repository.
|
206,198 |
<p>i have a class with a static public property called "Info".
via reflection i want to get this properties value, so i call:</p>
<pre><code>PropertyInfo pi myType.GetProperty("Info");
string info = (string) pi.GetValue(null, null);
</code></pre>
<p>this works fine as long as the property is of type string. but actually my property is of type IPluginInfo and a PluginInfo type (implementing IPluginInfo) is instatiated and returned in the Info properties get accessor, like this:</p>
<pre><code>public static IPluginInfo PluginInfo
{
get
{
IPluginInfo Info = new PluginInfo();
Info.Name = "PluginName";
Info.Version = "PluginVersion";
return Info;
}
}
</code></pre>
<p>like this when i call:</p>
<pre><code>IPluginInfo info = pi.GetValue(null, null) as IPluginInfo;
</code></pre>
<p>info is always null, whiel PropertyInfo pi is still valid. am i missing something obvious here?</p>
|
[
{
"answer_id": 206227,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>Could you create a short but complete program that demonstrates the problem?</p>\n\n<p>Given that you're talking about plugins, my <em>guess</em> is that you've got the problem of having IPluginInfo defined in two different assemblies. See if <a href=\"http://pobox.com/~skeet/csharp/plugin.html\" rel=\"nofollow noreferrer\">this article</a> helps at all.</p>\n\n<p>The easiest way to verify it is to call <code>pi.GetValue</code> and store the result in an <code>object</code> variable first, then do the cast or \"as\" in another line. That way you can break the debugger and look at the return value before it's lost.</p>\n"
},
{
"answer_id": 206237,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>My first guess would be that you have re-declared the IPluginInfo interface. All .NET types are scoped by their assembly; if you have the same class file in 2 assemblies, you have 2 different interfaces that happen to have the same name.</p>\n"
},
{
"answer_id": 206253,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Um, first of all I'd implement that property a little differently:</p>\n\n<pre><code>private static PluginInfo _PluginInfo = null;\npublic static IPluginInfo PluginInfo\n{\n get\n {\n if (_PluginInfo == null)\n {\n _PluginInfo = new PluginInfo();\n _PluginInfo.Name = \"PluginName\";\n _PluginInfo.Version = \"PluginVersion\";\n }\n return _PluginInfo;\n }\n}\n</code></pre>\n\n<p>Note that this needs a little more work because it isn't threadsafe, but hopefully you get the idea: build it one time rather than repeatedly.</p>\n\n<p>I'll stop here now, since it looks like two others already finished the rest of my answer while putting together the first part.</p>\n"
},
{
"answer_id": 206254,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "<p>In C#, AS returns null if the value does not match the type.\nIf you write:</p>\n\n<pre><code>object info = pi.GetValue(null, null);\nConsole.WriteLine(info.GetType().ToString());\n</code></pre>\n\n<p>what type do you receive?</p>\n"
},
{
"answer_id": 206618,
"author": "joreg",
"author_id": 6368,
"author_profile": "https://Stackoverflow.com/users/6368",
"pm_score": 1,
"selected": false,
"text": "<p>ok, thanks for all the answers.</p>\n\n<p>i indeed already had the plugininterface in a separate .dll but had placed this .dll in the pluginhosts directory as well as in the directory with all the plugins. </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6368/"
] |
i have a class with a static public property called "Info".
via reflection i want to get this properties value, so i call:
```
PropertyInfo pi myType.GetProperty("Info");
string info = (string) pi.GetValue(null, null);
```
this works fine as long as the property is of type string. but actually my property is of type IPluginInfo and a PluginInfo type (implementing IPluginInfo) is instatiated and returned in the Info properties get accessor, like this:
```
public static IPluginInfo PluginInfo
{
get
{
IPluginInfo Info = new PluginInfo();
Info.Name = "PluginName";
Info.Version = "PluginVersion";
return Info;
}
}
```
like this when i call:
```
IPluginInfo info = pi.GetValue(null, null) as IPluginInfo;
```
info is always null, whiel PropertyInfo pi is still valid. am i missing something obvious here?
|
Could you create a short but complete program that demonstrates the problem?
Given that you're talking about plugins, my *guess* is that you've got the problem of having IPluginInfo defined in two different assemblies. See if [this article](http://pobox.com/~skeet/csharp/plugin.html) helps at all.
The easiest way to verify it is to call `pi.GetValue` and store the result in an `object` variable first, then do the cast or "as" in another line. That way you can break the debugger and look at the return value before it's lost.
|
206,221 |
<p>I've successfully used the Windows SendMessage method to help me do various things in my text editor, but each time I am just copying and pasting code suggested by others, and I don't really know what it means. There is always a cryptic message number that is a parameter. How do I know what these code numbers mean so that I can actually understand what is happening and (hopefully) be a little more self-sufficient in the future? Thanks.</p>
<p>Recent example:</p>
<pre><code>using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam);
SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
</code></pre>
|
[
{
"answer_id": 206260,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 3,
"selected": true,
"text": "<p>This is the windows message code.<br>\nThey are defined in the header files, and generally available translated as an include of some sort with different languages. </p>\n\n<p>example:<br>\nWM_MOUSEMOVE = &H200<br>\nMK_CONTROL = &H8<br>\nMK_LBUTTON = &H1<br>\nMK_MBUTTON = &H10<br>\nMK_RBUTTON = &H2<br>\nMK_SHIFT = &H4<br>\nMK_XBUTTON1 = &H20<br>\nMK_XBUTTON2 = &H40 </p>\n\n<p>see <a href=\"http://msdn.microsoft.com/en-us/library/ms644927(VS.85).aspx#windows_messages\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms644927(VS.85).aspx#windows_messages</a>. </p>\n"
},
{
"answer_id": 206261,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 2,
"selected": false,
"text": "<p>Each message in Windows is signified by a number. When coding using the Windows SDK in native code, these are provided by defines such as WM_CHAR, WM_PAINT, or LVM_GETCOUNT, but these defines are not carried over to the .NET framework because in the most part, the messages are wrapped by .NET events like OnKeyPressed and OnPaint, or methods and properties like ListView.Items.Count.</p>\n\n<p>On the occasion where there is no wrapped event, property or method, or you need to do something that isn't supported at the higher level, you need the message numbers that Windows uses underneath the .NET framework.</p>\n\n<p>The best way to find out what a particular number actually means is to look in the Windows SDK headers and find the definition for that number.</p>\n"
},
{
"answer_id": 209517,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 0,
"selected": false,
"text": "<p>Try out the <a href=\"http://codeplex.com/clrinterop\" rel=\"nofollow noreferrer\">PInvoke interop Assistant</a>. This tool has a search functionality that allows you to browse through all of the defined windows messages. It will then generate the correct C#/VB.Net code for those values.</p>\n\n<p>It's also not limited to just constant values. It can also generated structs, functions, function pointers and enums. </p>\n"
},
{
"answer_id": 2114829,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you'll find the code at <a href=\"http://www.codeproject.com/KB/cs/cswindowsmessages.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/cswindowsmessages.aspx</a> useful. It provides a C# enumeration of many common windows messages.</p>\n"
},
{
"answer_id": 2494625,
"author": "Pedro",
"author_id": 299266,
"author_profile": "https://Stackoverflow.com/users/299266",
"pm_score": 1,
"selected": false,
"text": "<p>Among all the examples I found on the internet, this one is the best because it is the only one that takes care of showing the <code>using System.Runtime.InteropServices</code>. Without this directive I could not have SendMessage working in c#. Also very helpful is the list of Windows Messages this page offer. Here I repeat the example:</p>\n\n<pre><code>using System.Runtime.InteropServices; \n\n[DllImport(\"user32.dll\")] \nstatic extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam); \n\nSendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1)); \n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
I've successfully used the Windows SendMessage method to help me do various things in my text editor, but each time I am just copying and pasting code suggested by others, and I don't really know what it means. There is always a cryptic message number that is a parameter. How do I know what these code numbers mean so that I can actually understand what is happening and (hopefully) be a little more self-sufficient in the future? Thanks.
Recent example:
```
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam);
SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
```
|
This is the windows message code.
They are defined in the header files, and generally available translated as an include of some sort with different languages.
example:
WM\_MOUSEMOVE = &H200
MK\_CONTROL = &H8
MK\_LBUTTON = &H1
MK\_MBUTTON = &H10
MK\_RBUTTON = &H2
MK\_SHIFT = &H4
MK\_XBUTTON1 = &H20
MK\_XBUTTON2 = &H40
see <http://msdn.microsoft.com/en-us/library/ms644927(VS.85).aspx#windows_messages>.
|
206,222 |
<p>I'm attempting to fulfill a rather difficult reporting request from a client, and I need to find away to get the difference between two DateTime columns in minutes. I've attempted to use trunc and round with various <a href="http://www.ss64.com/orasyntax/fmt.html" rel="noreferrer">formats</a> and can't seem to come up with a combination that makes sense. Is there an elegant way to do this? If not, is there <b>any</b> way to do this?</p>
|
[
{
"answer_id": 206229,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://asktom.oracle.com/tkyte/Misc/DateDiff.html\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/tkyte/Misc/DateDiff.html</a> - link dead as of 2012-01-30</p>\n\n<p>Looks like this is the resource:</p>\n\n<p><a href=\"http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129</a></p>\n"
},
{
"answer_id": 206232,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 7,
"selected": true,
"text": "<pre><code>SELECT date1 - date2\n FROM some_table\n</code></pre>\n\n<p>returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So</p>\n\n<pre><code>SELECT (date1 - date2) * 24 * 60 difference_in_minutes\n FROM some_table\n</code></pre>\n\n<p>should be what you're looking for</p>\n"
},
{
"answer_id": 206243,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 4,
"selected": false,
"text": "<p>By default, oracle date subtraction returns a result in # of days.</p>\n\n<p>So just multiply by 24 to get # of hours, and again by 60 for # of minutes.</p>\n\n<p>Example:</p>\n\n<pre><code>select\n round((second_date - first_date) * (60 * 24),2) as time_in_minutes\nfrom\n (\n select\n to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date\n ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date\n from\n dual\n ) test_data\n</code></pre>\n"
},
{
"answer_id": 67058433,
"author": "Raghavendra",
"author_id": 15611654,
"author_profile": "https://Stackoverflow.com/users/15611654",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>timestampdiff</code> at <code>where</code> clause.</p>\n<p>Example:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>Select * from tavle1,table2 where timestampdiff(mi,col1,col2).\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27457/"
] |
I'm attempting to fulfill a rather difficult reporting request from a client, and I need to find away to get the difference between two DateTime columns in minutes. I've attempted to use trunc and round with various [formats](http://www.ss64.com/orasyntax/fmt.html) and can't seem to come up with a combination that makes sense. Is there an elegant way to do this? If not, is there **any** way to do this?
|
```
SELECT date1 - date2
FROM some_table
```
returns a difference in days. Multiply by 24 to get a difference in hours and 24\*60 to get minutes. So
```
SELECT (date1 - date2) * 24 * 60 difference_in_minutes
FROM some_table
```
should be what you're looking for
|
206,224 |
<p>I'm trying to emulate the file upload code from the grails website, and I'm running into some problems. I'm using the same code as found <a href="http://grails.org/Controllers+-+File+Uploads" rel="nofollow noreferrer">here</a>. Here is my code:</p>
<pre><code> <g:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" value="Upload" />
</g:form>
</code></pre>
<p>and</p>
<pre><code>def upload = {
def f = request.getFile('myFile')
if(!f.empty) {
flash.message = 'success'
}
else {
flash.message = 'file cannot be empty'
}
}
</code></pre>
<p>I'm receiving the following error at runtime:</p>
<pre><code>Message: No signature of method: org.mortbay.jetty.Request.getFile() is applicable for argument types: (java.lang.String) values: {"myFile"}
Caused by: groovy.lang.MissingMethodException: No signature of method: org.mortbay.jetty.Request.getFile() is applicable for argument types: (java.lang.String) values: {"myFile"}
</code></pre>
<p>It appears to be related to some Spring configuration. Spring does not appear to be injecting <code>MultipartHttpServletRequest</code>, so my request doesn't have the appropriate method. I just created this applications using <code>grails create-app</code>. I have not modified the resources.groovy file. I'm using grails 1.0.3.</p>
<p>Any help is much appreciated. The grails website makes this look so easy.</p>
|
[
{
"answer_id": 206259,
"author": "codeLes",
"author_id": 3030,
"author_profile": "https://Stackoverflow.com/users/3030",
"pm_score": 2,
"selected": false,
"text": "<p>make sure you update the html (your gsp with the form to upload from) to have the <strong>enctype</strong> as they show:</p>\n\n<pre><code><g:form action=\"upload\" method=\"post\" enctype=\"multipart/form-data\">\n</code></pre>\n\n<p>Hope that is helpful, seems too obvious but it's my first thought after seeing your error message.</p>\n"
},
{
"answer_id": 206357,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 2,
"selected": false,
"text": "<p>Someone <a href=\"http://docs.codehaus.org/display/GRAILS/File+Upload\" rel=\"nofollow noreferrer\">here</a> seems to be having the same troubles you had. He says he \"fixed\" it:</p>\n\n<blockquote>\n <p>Solved. It was my mistake, I was going in action save before submitting the form, so I suppose there was no file.</p>\n</blockquote>\n\n<p>Not sure how to take what he said, but maybe it'll help you.</p>\n"
},
{
"answer_id": 206513,
"author": "anschoewe",
"author_id": 21832,
"author_profile": "https://Stackoverflow.com/users/21832",
"pm_score": 5,
"selected": true,
"text": "<p>Problem solved!</p>\n\n<p>I was using the example code for uploading files to Grails differently than the original author probably intended. The problem is that when the <em>upload</em> method of the controller was called, it was sometimes for the original render of the Upload page. The request in that method was was not of type MultipartHttpServletRequest. When I did a POST with my file to upload, then Spring did the correct thing and changed my requestion to MultipartHttpServletRequest. So, I needed to do a simple check in my <em>update</em> controller method before using my request like a MultipartHttpServletRequest.</p>\n\n<pre><code>if(request instanceof MultipartHttpServletRequest)\n{\n MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request; \n CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile(\"myFile\");\n if(!f.empty)\n flash.message = 'success'\n else\n flash.message = 'file cannot be empty'\n} \nelse\n flash.message = 'request is not of type MultipartHttpServletRequest'\n</code></pre>\n"
},
{
"answer_id": 17109379,
"author": "Carleto",
"author_id": 2347491,
"author_profile": "https://Stackoverflow.com/users/2347491",
"pm_score": 3,
"selected": false,
"text": "<p>Now with the Grails 2.x use:</p>\n\n<pre><code><g:uploadForm name=\"upload\" action=\"upload\" method=\"POST\">\n <input type=\"file\" name=\"file\" />\n</g:uploadForm>\n\ndef upload = {\n def file = request.getFile('file')\n assert file instanceof CommonsMultipartFile\n\n if(!file.empty){ //do something }\n else { //do something }\n}\n</code></pre>\n\n<p>More clean, more simple.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21832/"
] |
I'm trying to emulate the file upload code from the grails website, and I'm running into some problems. I'm using the same code as found [here](http://grails.org/Controllers+-+File+Uploads). Here is my code:
```
<g:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" value="Upload" />
</g:form>
```
and
```
def upload = {
def f = request.getFile('myFile')
if(!f.empty) {
flash.message = 'success'
}
else {
flash.message = 'file cannot be empty'
}
}
```
I'm receiving the following error at runtime:
```
Message: No signature of method: org.mortbay.jetty.Request.getFile() is applicable for argument types: (java.lang.String) values: {"myFile"}
Caused by: groovy.lang.MissingMethodException: No signature of method: org.mortbay.jetty.Request.getFile() is applicable for argument types: (java.lang.String) values: {"myFile"}
```
It appears to be related to some Spring configuration. Spring does not appear to be injecting `MultipartHttpServletRequest`, so my request doesn't have the appropriate method. I just created this applications using `grails create-app`. I have not modified the resources.groovy file. I'm using grails 1.0.3.
Any help is much appreciated. The grails website makes this look so easy.
|
Problem solved!
I was using the example code for uploading files to Grails differently than the original author probably intended. The problem is that when the *upload* method of the controller was called, it was sometimes for the original render of the Upload page. The request in that method was was not of type MultipartHttpServletRequest. When I did a POST with my file to upload, then Spring did the correct thing and changed my requestion to MultipartHttpServletRequest. So, I needed to do a simple check in my *update* controller method before using my request like a MultipartHttpServletRequest.
```
if(request instanceof MultipartHttpServletRequest)
{
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("myFile");
if(!f.empty)
flash.message = 'success'
else
flash.message = 'file cannot be empty'
}
else
flash.message = 'request is not of type MultipartHttpServletRequest'
```
|
206,257 |
<p>I am declaring an array of void pointers. Each of which points to a value of arbitary type.<br>
<code>void **values; // Array of void pointers to each value of arbitary type</code></p>
<p>Initializing values as follows:</p>
<pre><code>
values = (void**)calloc(3,sizeof(void*));
//can initialize values as: values = new void* [3];
int ival = 1;
float fval = 2.0;
char* str = "word";
values[0] = (void*)new int(ival);
values[1] = (void*)new float(fval);
values[2] = (void*)str;
//Trying to Clear the memory allocated
free(*values);
//Error: *** glibc detected *** simpleSQL: free(): invalid pointer: 0x080611b4
//Core dumped
delete[] values*;
//warning: deleting 'void*' is undefined
//Similar Error.
</code></pre>
<p>Now how do I free/delete the memory allocated for values ( the array of void pointers)?</p>
|
[
{
"answer_id": 206289,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 0,
"selected": false,
"text": "<p>You'd have to keep track of how many void* were originally calloc'd, and iterate over them, free-ing each one, then free the original values variable.</p>\n\n<p>darn formatting... (the preview is working fine).</p>\n\n<pre><code>int ct = 3;\nvalues = (void*)calloc(ct,sizeof(void));\n//can initialize values as: values = new void* [3];\nint ival = 1;\nfloat fval = 2.0;\nchar* str = \"word\";\nvalues[0] = (void*)new int(ival);\nvalues[1] = (void*)new float(fval);\nvalues[2] = (void*)str;\n\nfor ( int i = 0; i < ct; i++ ) [\n delete( values[i] );\n}\nfree( values );\n</code></pre>\n"
},
{
"answer_id": 206296,
"author": "Jon",
"author_id": 12261,
"author_profile": "https://Stackoverflow.com/users/12261",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure why you are using new if you're doing things in C (referencing the tag here).</p>\n\n<p>I would malloc the individual pieces of the array I need and then free them when I'm done I suppose. You can't free something you didn't first malloc. You also can't delete a void pointer.</p>\n"
},
{
"answer_id": 206299,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>I suspect the issue is with the way that you allocated <code>values</code>: <code>values = (void*)calloc(3,sizeof(</code><b><code>void</code></b><code>))</code>. That should be <code>sizeof(void *)</code> rather than just <code>sizeof(void)</code>.</p>\n\n<p>sizeof(void) may be zero or something else that makes no sense, so you're not really allocating any memory to begin with... it's just dumb luck that the assignments work, and then the error pops up when you try to deallocate the memory.</p>\n\n<p>EDIT: You're also asking for trouble by alternating between C++-style <code>new</code>/<code>delete</code> with C-style <code>malloc</code>/<code>free</code>. It is okay to use them both as long as you don't <code>delete</code> something you <code>malloc</code>'ed or <code>free</code> something you <code>new</code>'ed, but you're going to mix them up in your head if you go like this.</p>\n"
},
{
"answer_id": 206308,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "<p>You have 3 things that are dynamically allocated that need to be freed in 2 different ways:</p>\n\n<pre><code>delete reinterpret_cast<int*>( values[0]); \ndelete reinterpret_cast<float*>( values[1]);\n\nfree( values); // I'm not sure why this would have failed in your example, \n // but it would have leaked the 2 items that you allocated \n // with new\n</code></pre>\n\n<p>Note that since <code>str</code> is not dynamically allocated it should not (actually <strong>cannot</strong>) be freed.</p>\n\n<p>A couple of notes:</p>\n\n<ul>\n<li>I'm assuming that the <code>sizeof(void)</code>\nwas meant to be <code>sizeof(void*)</code>\nsince what you have won't compile</li>\n<li>I'm not going to say anything about\nyour seemingly random casting except\nthat it looks like code that ready\nfor disaster in general</li>\n</ul>\n"
},
{
"answer_id": 206393,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 1,
"selected": false,
"text": "<p>You're mixing new and *alloc(). That's a no-no, and can lead to undefined results.</p>\n"
},
{
"answer_id": 206410,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": 0,
"selected": false,
"text": "<p>Note that you're also not deleting values[0] and values[1] which is a memory leak, Yet by your design you can't free values[2] since its a pointer into you .data section.</p>\n"
},
{
"answer_id": 206496,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>This is the perfect situation for the boost::any class<br>\nAlso you may want to consider using a vector rather than allocating your own memory.</p>\n\n<pre><code>std::vector<boost::any> data;\nboost::any i1 = 1; // add integer\ndata.push_back(i1);\n\nboost::any f1 = 1.0; // add double\ndata.push_back(f1);\n\ndata.push_back(\"PLOP\"); // add a char *\n\nstd:: cout << boost::any_cast<int>(data[0]) + boost::any_cast<double>(data[1])\n << std::endl;\n</code></pre>\n\n<p>Going back to your original code the main problem was:</p>\n\n<pre><code>values = (void*)calloc(3,sizeof(void));\n\n// This should have been\nvoid** values = (void**)calloc(3,sizeof(void*));\n\n// Freeing the members needs care as you need to cast them\n// back to the correct type before you release the memory.\n\n// now you can free the array with\nfree(values);\n</code></pre>\n\n<p>Also note: Though it is not illegal to use both new/delete and calloc/free in the same piece of code it is frowned upon. Mainly because it is easy to get things mixed up and that could potentially be fatal.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27221/"
] |
I am declaring an array of void pointers. Each of which points to a value of arbitary type.
`void **values; // Array of void pointers to each value of arbitary type`
Initializing values as follows:
```
values = (void**)calloc(3,sizeof(void*));
//can initialize values as: values = new void* [3];
int ival = 1;
float fval = 2.0;
char* str = "word";
values[0] = (void*)new int(ival);
values[1] = (void*)new float(fval);
values[2] = (void*)str;
//Trying to Clear the memory allocated
free(*values);
//Error: *** glibc detected *** simpleSQL: free(): invalid pointer: 0x080611b4
//Core dumped
delete[] values*;
//warning: deleting 'void*' is undefined
//Similar Error.
```
Now how do I free/delete the memory allocated for values ( the array of void pointers)?
|
You have 3 things that are dynamically allocated that need to be freed in 2 different ways:
```
delete reinterpret_cast<int*>( values[0]);
delete reinterpret_cast<float*>( values[1]);
free( values); // I'm not sure why this would have failed in your example,
// but it would have leaked the 2 items that you allocated
// with new
```
Note that since `str` is not dynamically allocated it should not (actually **cannot**) be freed.
A couple of notes:
* I'm assuming that the `sizeof(void)`
was meant to be `sizeof(void*)`
since what you have won't compile
* I'm not going to say anything about
your seemingly random casting except
that it looks like code that ready
for disaster in general
|
206,320 |
<p>I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention. </p>
<p>How can I tell the difference? </p>
|
[
{
"answer_id": 206339,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": false,
"text": "<pre><code>print \"$file is a directory\\n\" if ( -d $file );\n</code></pre>\n"
},
{
"answer_id": 206351,
"author": "jonathan-stafford",
"author_id": 27587,
"author_profile": "https://Stackoverflow.com/users/27587",
"pm_score": 3,
"selected": false,
"text": "<pre>\nmy $dh = opendir(\".\");\nmy @entries = grep !/^\\.\\.?$/, readdir($dh);\nclosedir $dh;\n\nforeach my $entry (@entries) {\n if(-f $entry) {\n # $entry is a file\n } elsif (-d $entry) {\n # $entry is a directory\n }\n}\n</pre>\n"
},
{
"answer_id": 206354,
"author": "catfood",
"author_id": 12802,
"author_profile": "https://Stackoverflow.com/users/12802",
"pm_score": 2,
"selected": false,
"text": "<p>It would be easier to use <code>File::Find</code>.</p>\n"
},
{
"answer_id": 206364,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 3,
"selected": false,
"text": "<p>Look at the -X operators:</p>\n\n<pre><code>perldoc -f -X\n</code></pre>\n\n<p>For directory traversal, use File::Find, or, if you're not a masochist, use my File::Next module which makes an iterator for you and doesn't require crazy callbacks. In fact, you can have File::Next ONLY return files, and ignore directories.</p>\n\n<pre><code>use File::Next;\n\nmy $iterator = File::Next::files( '/tmp' );\n\nwhile ( defined ( my $file = $iterator->() ) ) {\n print $file, \"\\n\";\n}\n\n# Prints...\n/tmp/foo.txt\n/tmp/bar.pl\n/tmp/baz/1\n/tmp/baz/2.txt\n/tmp/baz/wango/tango/purple.txt\n</code></pre>\n\n<p>It's at <a href=\"http://metacpan.org/pod/File::Next\" rel=\"nofollow noreferrer\">http://metacpan.org/pod/File::Next</a></p>\n"
},
{
"answer_id": 206399,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 6,
"selected": true,
"text": "<p>You can use a <code>-d</code> file test operator to check if something is a directory. Here's some of the commonly useful file test operators</p>\n<pre>\n -e File exists.\n -z File has zero size (is empty).\n -s File has nonzero size (returns size in bytes).\n -f File is a plain file.\n -d File is a directory.\n -l File is a symbolic link.\n</pre>\n<p>See <a href=\"http://perldoc.perl.org/perlfunc.html#-X-FILEHANDLE\" rel=\"nofollow noreferrer\">perlfunc manual page for more</a></p>\n<p>Also, try using <a href=\"https://metacpan.org/pod/File::Find\" rel=\"nofollow noreferrer\">File::Find</a> which can recurse directories for you. Here's a sample which looks for directories....</p>\n<pre><code>sub wanted {\n if (-d) { \n print $File::Find::name." is a directory\\n";\n }\n}\n\nfind(\\&wanted, $mydir);\n</code></pre>\n"
},
{
"answer_id": 223245,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 3,
"selected": false,
"text": "<pre><code>my @files = grep { -f } @all;\nmy @dirs = grep { -d } @all;\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21539/"
] |
I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention.
How can I tell the difference?
|
You can use a `-d` file test operator to check if something is a directory. Here's some of the commonly useful file test operators
```
-e File exists.
-z File has zero size (is empty).
-s File has nonzero size (returns size in bytes).
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
```
See [perlfunc manual page for more](http://perldoc.perl.org/perlfunc.html#-X-FILEHANDLE)
Also, try using [File::Find](https://metacpan.org/pod/File::Find) which can recurse directories for you. Here's a sample which looks for directories....
```
sub wanted {
if (-d) {
print $File::Find::name." is a directory\n";
}
}
find(\&wanted, $mydir);
```
|
206,323 |
<p>How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and write the results to a text box.</p>
|
[
{
"answer_id": 206340,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": false,
"text": "<p>This may not be the best/easiest way, but may be an option:</p>\n\n<p>When you execute from your code, add \" > output.txt\" and then read in the output.txt file.</p>\n"
},
{
"answer_id": 206347,
"author": "Ray Jezek",
"author_id": 28309,
"author_profile": "https://Stackoverflow.com/users/28309",
"pm_score": 10,
"selected": true,
"text": "<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 = \"YOURBATCHFILE.bat\";\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\n<p>Code is from <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx\" rel=\"noreferrer\">MSDN</a>.</p>\n"
},
{
"answer_id": 206348,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "<p>You will need to use <code>ProcessStartInfo</code> with <code>RedirectStandardOutput</code> enabled - then you can read the output stream. You might find it easier to use \">\" to redirect the output to a file (via the OS), and then simply read the file.</p>\n\n<p>[edit: like what Ray did: +1]</p>\n"
},
{
"answer_id": 206353,
"author": "Nick",
"author_id": 22407,
"author_profile": "https://Stackoverflow.com/users/22407",
"pm_score": 2,
"selected": false,
"text": "<p>You can launch any command line program using the Process class, and set the StandardOutput property of the Process instance with a stream reader you create (either based on a string or a memory location). After the process completes, you can then do whatever diff you need to on that stream.</p>\n"
},
{
"answer_id": 206361,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": 4,
"selected": false,
"text": "<pre><code> System.Diagnostics.ProcessStartInfo psi =\n new System.Diagnostics.ProcessStartInfo(@\"program_to_call.exe\");\n psi.RedirectStandardOutput = true;\n psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n psi.UseShellExecute = false;\n System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////\n System.IO.StreamReader myOutput = proc.StandardOutput;\n proc.WaitForExit(2000);\n if (proc.HasExited)\n {\n string output = myOutput.ReadToEnd();\n }\n</code></pre>\n"
},
{
"answer_id": 206366,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a quick sample:</p>\n\n<pre><code>//Create process\nSystem.Diagnostics.Process pProcess = new System.Diagnostics.Process();\n\n//strCommand is path and file name of command to run\npProcess.StartInfo.FileName = strCommand;\n\n//strCommandParameters are parameters to pass to program\npProcess.StartInfo.Arguments = strCommandParameters;\n\npProcess.StartInfo.UseShellExecute = false;\n\n//Set output of program to be written to process output stream\npProcess.StartInfo.RedirectStandardOutput = true; \n\n//Optional\npProcess.StartInfo.WorkingDirectory = strWorkingDirectory;\n\n//Start the process\npProcess.Start();\n\n//Get program output\nstring strOutput = pProcess.StandardOutput.ReadToEnd();\n\n//Wait for process to finish\npProcess.WaitForExit();\n</code></pre>\n"
},
{
"answer_id": 1266108,
"author": "Shaik",
"author_id": 7637,
"author_profile": "https://Stackoverflow.com/users/7637",
"pm_score": 2,
"selected": false,
"text": "<p>There is a ProcessHelper Class in <a href=\"http://www.codeplex.com/publicdomain\" rel=\"nofollow noreferrer\">PublicDomain</a> open source code which might interest you.</p>\n"
},
{
"answer_id": 1488639,
"author": "Peter Du",
"author_id": 162429,
"author_profile": "https://Stackoverflow.com/users/162429",
"pm_score": 7,
"selected": false,
"text": "<p>There one other parameter I found useful, which I use to eliminate the process window</p>\n\n<pre><code>pProcess.StartInfo.CreateNoWindow = true;\n</code></pre>\n\n<p>this helps to hide the black console window from user completely, if that is what you desire.</p>\n"
},
{
"answer_id": 10072082,
"author": "Ilya Serbis",
"author_id": 355438,
"author_profile": "https://Stackoverflow.com/users/355438",
"pm_score": 7,
"selected": false,
"text": "<pre><code>// usage\nconst string ToolFileName = \"example.exe\";\nstring output = RunExternalExe(ToolFileName);\n\npublic string RunExternalExe(string filename, string arguments = null)\n{\n var process = new Process();\n\n process.StartInfo.FileName = filename;\n if (!string.IsNullOrEmpty(arguments))\n {\n process.StartInfo.Arguments = arguments;\n }\n\n process.StartInfo.CreateNoWindow = true;\n process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n process.StartInfo.UseShellExecute = false;\n\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n var stdOutput = new StringBuilder();\n process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.\n\n string stdError = null;\n try\n {\n process.Start();\n process.BeginOutputReadLine();\n stdError = process.StandardError.ReadToEnd();\n process.WaitForExit();\n }\n catch (Exception e)\n {\n throw new Exception(\"OS error while executing \" + Format(filename, arguments)+ \": \" + e.Message, e);\n }\n\n if (process.ExitCode == 0)\n {\n return stdOutput.ToString();\n }\n else\n {\n var message = new StringBuilder();\n\n if (!string.IsNullOrEmpty(stdError))\n {\n message.AppendLine(stdError);\n }\n\n if (stdOutput.Length != 0)\n {\n message.AppendLine(\"Std output:\");\n message.AppendLine(stdOutput.ToString());\n }\n\n throw new Exception(Format(filename, arguments) + \" finished with exit code = \" + process.ExitCode + \": \" + message);\n }\n}\n\nprivate string Format(string filename, string arguments)\n{\n return \"'\" + filename + \n ((string.IsNullOrEmpty(arguments)) ? string.Empty : \" \" + arguments) +\n \"'\";\n}\n</code></pre>\n"
},
{
"answer_id": 45817364,
"author": "Kitson88",
"author_id": 6574422,
"author_profile": "https://Stackoverflow.com/users/6574422",
"pm_score": 2,
"selected": false,
"text": "<p>This might be useful for someone if your attempting to query the local ARP cache on a PC/Server. </p>\n\n<pre><code>List<string[]> results = new List<string[]>();\n\n using (Process p = new Process())\n {\n p.StartInfo.CreateNoWindow = true;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.Arguments = \"/c arp -a\";\n p.StartInfo.FileName = @\"C:\\Windows\\System32\\cmd.exe\";\n p.Start();\n\n string line;\n\n while ((line = p.StandardOutput.ReadLine()) != null)\n {\n if (line != \"\" && !line.Contains(\"Interface\") && !line.Contains(\"Physical Address\"))\n {\n var lineArr = line.Trim().Split(' ').Select(n => n).Where(n => !string.IsNullOrEmpty(n)).ToArray();\n var arrResult = new string[]\n {\n lineArr[0],\n lineArr[1],\n lineArr[2]\n };\n results.Add(arrResult);\n }\n }\n\n p.WaitForExit();\n }\n</code></pre>\n"
},
{
"answer_id": 47003136,
"author": "Tyrrrz",
"author_id": 2205454,
"author_profile": "https://Stackoverflow.com/users/2205454",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't mind introducing a dependency, <a href=\"https://github.com/Tyrrrz/CliWrap\" rel=\"nofollow noreferrer\">CliWrap</a> can simplify this for you:</p>\n<pre><code>using CliWrap;\nusing CliWrap.Buffered;\n\nvar result = await Cli.Wrap("target.exe")\n .WithArguments("arguments")\n .ExecuteBufferedAsync();\n\nvar stdout = result.StandardOutput;\n</code></pre>\n"
},
{
"answer_id": 47382540,
"author": "Cameron",
"author_id": 86375,
"author_profile": "https://Stackoverflow.com/users/86375",
"pm_score": 5,
"selected": false,
"text": "<p>The accepted answer on this page has a weakness that is troublesome in rare situations. There are two file handles which programs write to by convention, stdout, and stderr.\nIf you just read a single file handle such as the answer from Ray, and the program you are starting writes enough output to stderr, it will fill up the output stderr buffer and block. Then your two processes are deadlocked. The buffer size may be 4K.\nThis is extremely rare on short-lived programs, but if you have a long running program which repeatedly outputs to stderr, it will happen eventually. This is tricky to debug and track down.</p>\n\n<p>There are a couple good ways to deal with this.</p>\n\n<ol>\n<li><p>One way is to execute cmd.exe instead of your program and use the /c argument to cmd.exe to invoke your program along with the \"2>&1\" argument to cmd.exe to tell it to merge stdout and stderr.</p>\n\n<pre><code> var p = new Process();\n p.StartInfo.FileName = \"cmd.exe\";\n p.StartInfo.Arguments = \"/c mycmd.exe 2>&1\";\n</code></pre></li>\n<li><p>Another way is to use a programming model which reads both handles at the same time. </p>\n\n<pre><code> var p = new Process();\n p.StartInfo.FileName = \"cmd.exe\";\n p.StartInfo.Arguments = @\"/c dir \\windows\";\n p.StartInfo.CreateNoWindow = true;\n p.StartInfo.RedirectStandardError = true;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.RedirectStandardInput = false;\n p.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);\n p.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);\n p.Start();\n p.BeginErrorReadLine();\n p.BeginOutputReadLine();\n p.WaitForExit();\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 49048917,
"author": "Dave",
"author_id": 1451197,
"author_profile": "https://Stackoverflow.com/users/1451197",
"pm_score": 0,
"selected": false,
"text": "<p>Just for fun, here's my completed solution for getting PYTHON output - under a button click - with error reporting. Just add a button called \"butPython\" and a label called \"llHello\"...</p>\n\n<pre><code> private void butPython(object sender, EventArgs e)\n {\n llHello.Text = \"Calling Python...\";\n this.Refresh();\n Tuple<String,String> python = GoPython(@\"C:\\Users\\BLAH\\Desktop\\Code\\Python\\BLAH.py\");\n llHello.Text = python.Item1; // Show result.\n if (python.Item2.Length > 0) MessageBox.Show(\"Sorry, there was an error:\" + Environment.NewLine + python.Item2);\n }\n\n public Tuple<String,String> GoPython(string pythonFile, string moreArgs = \"\")\n {\n ProcessStartInfo PSI = new ProcessStartInfo();\n PSI.FileName = \"py.exe\";\n PSI.Arguments = string.Format(\"\\\"{0}\\\" {1}\", pythonFile, moreArgs);\n PSI.CreateNoWindow = true;\n PSI.UseShellExecute = false;\n PSI.RedirectStandardError = true;\n PSI.RedirectStandardOutput = true;\n using (Process process = Process.Start(PSI))\n using (StreamReader reader = process.StandardOutput)\n {\n string stderr = process.StandardError.ReadToEnd(); // Error(s)!!\n string result = reader.ReadToEnd(); // What we want.\n return new Tuple<String,String> (result,stderr); \n }\n }\n</code></pre>\n"
},
{
"answer_id": 58286629,
"author": "Dan Stevens",
"author_id": 660896,
"author_profile": "https://Stackoverflow.com/users/660896",
"pm_score": 3,
"selected": false,
"text": "<p>One-liner run command:</p>\n\n<pre><code>new Process() { StartInfo = new ProcessStartInfo(\"echo\", \"Hello, World\") }.Start();\n</code></pre>\n\n<p>Read output of command in shortest amount of reable code:</p>\n\n<pre><code> var cliProcess = new Process() {\n StartInfo = new ProcessStartInfo(\"echo\", \"Hello, World\") {\n UseShellExecute = false,\n RedirectStandardOutput = true\n }\n };\n cliProcess.Start();\n string cliOut = cliProcess.StandardOutput.ReadToEnd();\n cliProcess.WaitForExit();\n cliProcess.Close();\n</code></pre>\n"
},
{
"answer_id": 59987509,
"author": "Konard",
"author_id": 710069,
"author_profile": "https://Stackoverflow.com/users/710069",
"pm_score": 3,
"selected": false,
"text": "<p>In case you also need to execute some command in the cmd.exe, you can do the following:</p>\n\n<pre><code>// Start the child process.\nProcess p = new Process();\n// Redirect the output stream of the child process.\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = \"cmd.exe\";\np.StartInfo.Arguments = \"/C vol\";\np.Start();\n// Read the output stream first and then wait.\nstring output = p.StandardOutput.ReadToEnd();\np.WaitForExit();\nConsole.WriteLine(output);\n</code></pre>\n\n<p>This returns just the output of the command itself:</p>\n\n<p><a href=\"https://i.stack.imgur.com/O545N.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/O545N.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can also use <code>StandardInput</code> instead of <code>StartInfo.Arguments</code>:</p>\n\n<pre><code>// Start the child process.\nProcess p = new Process();\n// Redirect the output stream of the child process.\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardInput = true;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = \"cmd.exe\";\np.Start();\n// Read the output stream first and then wait.\np.StandardInput.WriteLine(\"vol\");\np.StandardInput.WriteLine(\"exit\");\nstring output = p.StandardOutput.ReadToEnd();\np.WaitForExit();\nConsole.WriteLine(output);\n</code></pre>\n\n<p>The result looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/d6uj8.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/d6uj8.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 61867172,
"author": "Julian",
"author_id": 9479890,
"author_profile": "https://Stackoverflow.com/users/9479890",
"pm_score": 2,
"selected": false,
"text": "<p>Since the most answers here dont implement the <code>using</code> statemant for <code>IDisposable</code> and some other stuff wich I think could be nessecary I will add this answer.</p>\n\n<p>For C# 8.0</p>\n\n<pre><code>// Start a process with the filename or path with filename e.g. \"cmd\". Please note the \n//using statemant\nusing myProcess.StartInfo.FileName = \"cmd\";\n// add the arguments - Note add \"/c\" if you want to carry out tge argument in cmd and \n// terminate\nmyProcess.StartInfo.Arguments = \"/c dir\";\n// Allows to raise events\nmyProcess.EnableRaisingEvents = true;\n//hosted by the application itself to not open a black cmd window\nmyProcess.StartInfo.UseShellExecute = false;\nmyProcess.StartInfo.CreateNoWindow = true;\n// Eventhander for data\nmyProcess.Exited += OnOutputDataRecived;\n// Eventhandler for error\nmyProcess.ErrorDataReceived += OnErrorDataReceived;\n// Eventhandler wich fires when exited\nmyProcess.Exited += OnExited;\n// Starts the process\nmyProcess.Start();\n//read the output before you wait for exit\nmyProcess.BeginOutputReadLine();\n// wait for the finish - this will block (leave this out if you dont want to wait for \n// it, so it runs without blocking)\nprocess.WaitForExit();\n\n// Handle the dataevent\nprivate void OnOutputDataRecived(object sender, DataReceivedEventArgs e)\n{\n //do something with your data\n Trace.WriteLine(e.Data);\n}\n\n//Handle the error\nprivate void OnErrorDataReceived(object sender, DataReceivedEventArgs e)\n{ \n Trace.WriteLine(e.Data);\n //do something with your exception\n throw new Exception();\n} \n\n// Handle Exited event and display process information.\nprivate void OnExited(object sender, System.EventArgs e)\n{\n Trace.WriteLine(\"Process exited\");\n}\n</code></pre>\n"
},
{
"answer_id": 62823078,
"author": "Frank",
"author_id": 2324547,
"author_profile": "https://Stackoverflow.com/users/2324547",
"pm_score": 1,
"selected": false,
"text": "<p>Julian's solution is tested working with some minor corrections. The following is an example that also used <a href=\"https://sourceforge.net/projects/bat-to-exe/\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/bat-to-exe/</a> GenericConsole.cs and <a href=\"https://www.codeproject.com/Articles/19225/Bat-file-compiler\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/19225/Bat-file-compiler</a> program.txt for args part:</p>\n<pre><code>using System;\nusing System.Text; //StringBuilder\nusing System.Diagnostics;\nusing System.IO;\n\n\nclass Program\n{\n private static bool redirectStandardOutput = true;\n\n private static string buildargument(string[] args)\n {\n StringBuilder arg = new StringBuilder();\n for (int i = 0; i < args.Length; i++)\n {\n arg.Append("\\"" + args[i] + "\\" ");\n }\n\n return arg.ToString();\n }\n\n static void Main(string[] args)\n {\n Process prc = new Process();\n prc.StartInfo = //new ProcessStartInfo("cmd.exe", String.Format("/c \\"\\"{0}\\" {1}", Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args)));\n //new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args));\n new ProcessStartInfo("mapTargetIDToTargetNameA3.bat");\n prc.StartInfo.Arguments = buildargument(args);\n\n prc.EnableRaisingEvents = true;\n\n if (redirectStandardOutput == true)\n {\n prc.StartInfo.UseShellExecute = false;\n }\n else\n {\n prc.StartInfo.UseShellExecute = true;\n }\n\n prc.StartInfo.CreateNoWindow = true;\n\n prc.OutputDataReceived += OnOutputDataRecived;\n prc.ErrorDataReceived += OnErrorDataReceived;\n //prc.Exited += OnExited;\n\n prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;\n prc.StartInfo.RedirectStandardError = redirectStandardOutput;\n\n try\n {\n prc.Start();\n prc.BeginOutputReadLine();\n prc.BeginErrorReadLine();\n prc.WaitForExit();\n }\n catch (Exception e)\n {\n Console.WriteLine("OS error: " + e.Message);\n }\n\n prc.Close();\n }\n\n // Handle the dataevent\n private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)\n {\n //do something with your data\n Console.WriteLine(e.Data);\n }\n\n //Handle the error\n private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)\n {\n Console.WriteLine(e.Data);\n }\n\n // Handle Exited event and display process information.\n //private static void OnExited(object sender, System.EventArgs e)\n //{\n // var process = sender as Process;\n // if (process != null)\n // {\n // Console.WriteLine("ExitCode: " + process.ExitCode);\n // }\n // else\n // {\n // Console.WriteLine("Process exited");\n // }\n //}\n}\n</code></pre>\n<p>The code need to compile inside VS2007, using commandline csc.exe generated executable will not show console output correctly, or even crash with CLR20r3 error. Comment out the OnExited event process, the console output of the bat to exe will be more like the original bat console output.</p>\n"
},
{
"answer_id": 66798326,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 2,
"selected": false,
"text": "<p>Here is small example:</p>\n<pre><code>using System;\nusing System.Diagnostics;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var p = Process.Start(\n new ProcessStartInfo("git", "branch --show-current")\n {\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardError = true,\n RedirectStandardOutput = true,\n WorkingDirectory = Environment.CurrentDirectory\n }\n );\n\n p.WaitForExit();\n string branchName =p.StandardOutput.ReadToEnd().TrimEnd();\n string errorInfoIfAny =p.StandardError.ReadToEnd().TrimEnd();\n\n if (errorInfoIfAny.Length != 0)\n {\n Console.WriteLine($"error: {errorInfoIfAny}");\n }\n else { \n Console.WriteLine($"branch: {branchName}");\n }\n\n }\n}\n</code></pre>\n<p>I believe this is shortest form.</p>\n<p>Please notice that most of command line tools easily confuse standard output and standard error, sometimes it makes sense just to clue those together into single string.</p>\n<p>Also <code>p.ExitCode</code> might be sometimes useful.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/958/"
] |
How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and write the results to a text box.
|
```
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "YOURBATCHFILE.bat";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
```
Code is from [MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx).
|
206,324 |
<p>I want to check for empty arrays. Google gave me varied solutions but nothing worked. Maybe I am not applying them correctly.</p>
<pre><code>Function GetBoiler(ByVal sFile As String) As String
'Email Signature
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.ReadAll
ts.Close
End Function
Dim FileNamesList As Variant, i As Integer
' activate the desired startfolder for the filesearch
FileNamesList = CreateFileList("*.*", False) ' Returns File names
' performs the filesearch, includes any subfolders
' present the result
' If there are Signatures then populate SigString
Range("A:A").ClearContents
For i = 1 To UBound(FileNamesList)
Cells(i + 1, 1).Formula = FileNamesList(i)
Next i
SigString = FileNamesList(3)
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
</code></pre>
<p>Here if <code>FileNamesList</code> array is empty, <code>GetBoiler(SigString)</code> should not get called at all. When <code>FileNamesList</code> array is empty, <code>SigString</code> is also empty and this calls <code>GetBoiler()</code> function with empty string. I get an error at line </p>
<pre><code>Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
</code></pre>
<p>since <code>sFile</code> is empty. Any way to avoid that?</p>
|
[
{
"answer_id": 206523,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 2,
"selected": false,
"text": "<p>This code doesn't do what you expect:</p>\n\n<pre><code>If Dir(SigString) <> \"\" Then\n Signature = GetBoiler(SigString) \nElse\n Signature = \"\" \nEnd If\n</code></pre>\n\n<p>If you pass an empty string (<code>\"\"</code>) or <code>vbNullString</code> to <code>Dir</code>, it will return the name of the first file in the current directory path (the path returned by <code>CurDir$</code>). So, if <code>SigString</code> is empty, your <code>If</code> condition will evaluate to <code>True</code> because <code>Dir</code> will return a non-empty string (the name of the first file in the current directory), and <code>GetBoiler</code> will be called. And if <code>SigString</code> is empty, the call to <code>fso.GetFile</code> will fail.</p>\n\n<p>You should either change your condition to check that <code>SigString</code> isn't empty, or use the <code>FileSystemObject.FileExists</code> method instead of <code>Dir</code> for checking if the file exists. <code>Dir</code> is tricky to use precisely because it does things you might not expect it to do. Personally, I would use <code>Scripting.FileSystemObject</code> over <code>Dir</code> because there's no funny business (<code>FileExists</code> returns <code>True</code> if the file exists, and, well, <code>False</code> if it doesn't). What's more, <code>FileExists</code> expresses the <em>intent</em> of your code much clearly than <code>Dir</code>.</p>\n\n<p><strong>Method 1: Check that <code>SigString</code> is non-empty first</strong></p>\n\n<pre><code>If SigString <> \"\" And Dir(SigString) <> \"\" Then\n Signature = GetBoiler(SigString) \nElse\n Signature = \"\" \nEnd If\n</code></pre>\n\n<p><strong>Method 2: Use the <code>FileSystemObject.FileExists</code> method</strong></p>\n\n<pre><code>Dim fso As Object\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\nIf fso.FileExists(SigString) Then\n Signature = GetBoiler(SigString) \nElse\n Signature = \"\" \nEnd If\n</code></pre>\n"
},
{
"answer_id": 206526,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 6,
"selected": false,
"text": "<p>As you are dealing with a string array, have you considered Join?</p>\n\n<pre><code>If Len(Join(FileNamesList)) > 0 Then\n</code></pre>\n"
},
{
"answer_id": 284967,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": 0,
"selected": false,
"text": "<p>I'll generalize the problem and the Question as intended.\nTest assingment on the array, and catch the eventual error</p>\n\n<pre><code>Function IsVarArrayEmpty(anArray as Variant)\nDim aVar as Variant\n\nIsVarArrayEmpty=False\nOn error resume next\naVar=anArray(1)\nIf Err.number then '...still, it might not start at this index\n aVar=anArray(0)\n If Err.number then IsVarArrayEmpty=True ' neither 0 or 1 yields good assignment\nEndIF\nEnd Function\n</code></pre>\n\n<p>Sure it misses arrays with all negative indexes or all > 1... is that likely? in weirdland, yes.</p>\n"
},
{
"answer_id": 620052,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 5,
"selected": false,
"text": "<p>If you test on an array function it'll work for all bounds:</p>\n\n<pre><code>Function IsVarArrayEmpty(anArray As Variant)\n\nDim i As Integer\n\nOn Error Resume Next\n i = UBound(anArray,1)\nIf Err.number = 0 Then\n IsVarArrayEmpty = False\nElse\n IsVarArrayEmpty = True\nEnd If\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 5511769,
"author": "BBQ Chef",
"author_id": 684098,
"author_profile": "https://Stackoverflow.com/users/684098",
"pm_score": 3,
"selected": false,
"text": "<p>When writing VBA there is this sentence in my head: \"Could be so easy, but...\"</p>\n\n<p>Here is what I adopted it to:</p>\n\n<pre><code>Private Function IsArrayEmpty(arr As Variant)\n ' This function returns true if array is empty\n Dim l As Long\n\n On Error Resume Next\n l = Len(Join(arr))\n If l = 0 Then\n IsArrayEmpty = True\n Else\n IsArrayEmpty = False\n End If\n\n If Err.Number > 0 Then\n IsArrayEmpty = True\n End If\n\n On Error GoTo 0\nEnd Function\n\nPrivate Sub IsArrayEmptyTest()\n Dim a As Variant\n a = Array()\n Debug.Print \"Array is Empty is \" & IsArrayEmpty(a)\n If IsArrayEmpty(a) = False Then\n Debug.Print \" \" & Join(a)\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 11491235,
"author": "irm",
"author_id": 1526761,
"author_profile": "https://Stackoverflow.com/users/1526761",
"pm_score": -1,
"selected": false,
"text": "<p>Another solution to test for empty array</p>\n\n<pre><code>if UBound(ar) < LBound(ar) then msgbox \"Your array is empty!\"\n</code></pre>\n\n<p>Or, if you already know that LBound is 0</p>\n\n<pre><code>if -1 = UBound(ar) then msgbox \"Your array is empty!\"\n</code></pre>\n\n<p>This may be faster than join(). (And I didn't check with negative indexes)</p>\n\n<p>Here is my sample to filter 2 string arrays so they do not share same strings.</p>\n\n<pre><code>' Filtering ar2 out of strings that exists in ar1\n\nFor i = 0 To UBound(ar1)\n\n ' filter out any ar2.string that exists in ar1\n ar2 = Filter(ar2 , ar1(i), False) \n\n If UBound(ar2) < LBound(ar2) Then\n MsgBox \"All strings are the same.\", vbExclamation, \"Operation ignored\":\n Exit Sub\n\n End If\n\nNext\n\n' At this point, we know that ar2 is not empty and it is filtered \n'\n</code></pre>\n"
},
{
"answer_id": 13211736,
"author": "Stefanos Kargas",
"author_id": 350061,
"author_profile": "https://Stackoverflow.com/users/350061",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Public Function arrayIsEmpty(arrayToCheck() As Variant) As Boolean\n On Error GoTo Err:\n Dim forCheck\n forCheck = arrayToCheck(0)\n arrayIsEmpty = False\n Exit Function\nErr:\n arrayIsEmpty = True\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 14382846,
"author": "ahuth",
"author_id": 1430871,
"author_profile": "https://Stackoverflow.com/users/1430871",
"pm_score": 6,
"selected": false,
"text": "<p>Go with a triple negative:</p>\n\n<pre><code>If (Not Not FileNamesList) <> 0 Then\n ' Array has been initialized, so you're good to go.\nElse\n ' Array has NOT been initialized\nEnd If\n</code></pre>\n\n<p>Or just:</p>\n\n<pre><code>If (Not FileNamesList) = -1 Then\n ' Array has NOT been initialized\nElse\n ' Array has been initialized, so you're good to go.\nEnd If\n</code></pre>\n\n<p>In VB, for whatever reason, <code>Not myArray</code> returns the SafeArray pointer. For uninitialized arrays, this returns -1. You can <code>Not</code> this to XOR it with -1, thus returning zero, if you prefer. </p>\n\n<pre><code> (Not myArray) (Not Not myArray)\nUninitialized -1 0\nInitialized -someBigNumber someOtherBigNumber\n</code></pre>\n\n<p><a href=\"http://www.vbforums.com/showthread.php?654880-How-do-I-tell-if-an-array-is-quot-empty-quot&p=4040234&viewfull=1#post4040234\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 15668372,
"author": "Jim Snyder",
"author_id": 2047486,
"author_profile": "https://Stackoverflow.com/users/2047486",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, I think one of the answers above can be modified to check if the array has contents:</p>\n\n<pre><code>if UBound(ar) > LBound(ar) Then\n</code></pre>\n\n<p>This handles negative number references and takes less time than some of the other options.</p>\n"
},
{
"answer_id": 19096020,
"author": "sancho.s ReinstateMonicaCellio",
"author_id": 2707864,
"author_profile": "https://Stackoverflow.com/users/2707864",
"pm_score": 2,
"selected": false,
"text": "<p>I am simply pasting below the code by the great Chip Pearson. It works a charm.<br>\nHere's his <a href=\"http://www.cpearson.com/excel/vbaarrays.htm\" rel=\"nofollow noreferrer\">page on array functions</a>.</p>\n\n<p>I hope this helps.</p>\n\n<pre><code>Public Function IsArrayEmpty(Arr As Variant) As Boolean\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' IsArrayEmpty\n' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.\n'\n' The VBA IsArray function indicates whether a variable is an array, but it does not\n' distinguish between allocated and unallocated arrays. It will return TRUE for both\n' allocated and unallocated arrays. This function tests whether the array has actually\n' been allocated.\n'\n' This function is really the reverse of IsArrayAllocated.\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\n Dim LB As Long\n Dim UB As Long\n\n err.Clear\n On Error Resume Next\n If IsArray(Arr) = False Then\n ' we weren't passed an array, return True\n IsArrayEmpty = True\n End If\n\n ' Attempt to get the UBound of the array. If the array is\n ' unallocated, an error will occur.\n UB = UBound(Arr, 1)\n If (err.Number <> 0) Then\n IsArrayEmpty = True\n Else\n ''''''''''''''''''''''''''''''''''''''''''\n ' On rare occasion, under circumstances I\n ' cannot reliably replicate, Err.Number\n ' will be 0 for an unallocated, empty array.\n ' On these occasions, LBound is 0 and\n ' UBound is -1.\n ' To accommodate the weird behavior, test to\n ' see if LB > UB. If so, the array is not\n ' allocated.\n ''''''''''''''''''''''''''''''''''''''''''\n err.Clear\n LB = LBound(Arr)\n If LB > UB Then\n IsArrayEmpty = True\n Else\n IsArrayEmpty = False\n End If\n End If\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 21150293,
"author": "Zhenya",
"author_id": 1916997,
"author_profile": "https://Stackoverflow.com/users/1916997",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Public Function IsEmptyArray(InputArray As Variant) As Boolean\n\n On Error GoTo ErrHandler:\n IsEmptyArray = Not (UBound(InputArray) >= 0)\n Exit Function\n\n ErrHandler:\n IsEmptyArray = True\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 22941963,
"author": "Mike Bethany",
"author_id": 2611793,
"author_profile": "https://Stackoverflow.com/users/2611793",
"pm_score": 2,
"selected": false,
"text": "<p>Auth was closest but his answer throws a type mismatch error.</p>\n\n<p>As for the other answers you should avoid using an error to test for a condition, if you can, because at the very least it complicates debugging (what if something else is causing that error).</p>\n\n<p>Here's a simple, complete solution:</p>\n\n<pre><code>option explicit\nFunction foo() As Variant\n\n Dim bar() As String\n\n If (Not Not bar) Then\n ReDim Preserve bar(0 To UBound(bar) + 1)\n Else\n ReDim Preserve bar(0 To 0)\n End If\n\n bar(UBound(bar)) = \"it works!\"\n\n foo = bar\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 26490424,
"author": "Robert S.",
"author_id": 4166543,
"author_profile": "https://Stackoverflow.com/users/4166543",
"pm_score": 2,
"selected": false,
"text": "<p>Simplified check for Empty Array: </p>\n\n<pre><code>Dim exampleArray() As Variant 'Any Type\n\nIf ((Not Not exampleArray) = 0) Then\n 'Array is Empty\nElse\n 'Array is Not Empty\nEnd If\n</code></pre>\n"
},
{
"answer_id": 30025972,
"author": "Vignesh Subramanian",
"author_id": 848841,
"author_profile": "https://Stackoverflow.com/users/848841",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the below function to check if variant or string array is empty in vba</p>\n\n<pre><code>Function IsArrayAllocated(Arr As Variant) As Boolean\n On Error Resume Next\n IsArrayAllocated = IsArray(Arr) And _\n Not IsError(LBound(Arr, 1)) And _\n LBound(Arr, 1) <= UBound(Arr, 1)\nEnd Function\n</code></pre>\n\n<p>Sample usage</p>\n\n<pre><code>Public Function test()\nDim Arr(1) As String\nArr(0) = \"d\"\nDim x As Boolean\nx = IsArrayAllocated(Arr)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 31082392,
"author": "Perposterer",
"author_id": 3246731,
"author_profile": "https://Stackoverflow.com/users/3246731",
"pm_score": 3,
"selected": false,
"text": "<p>I see similar answers on here... but not mine...</p>\n\n<p>This is how I am unfortunatley going to deal with it... I like the len(join(arr)) > 0 approach, but it wouldn't work if the array was an array of emptystrings...</p>\n\n<pre><code>Public Function arrayLength(arr As Variant) As Long\n On Error GoTo handler\n\n Dim lngLower As Long\n Dim lngUpper As Long\n\n lngLower = LBound(arr)\n lngUpper = UBound(arr)\n\n arrayLength = (lngUpper - lngLower) + 1\n Exit Function\n\nhandler:\n arrayLength = 0 'error occured. must be zero length\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 35341875,
"author": "Tim Boutchia",
"author_id": 5914019,
"author_profile": "https://Stackoverflow.com/users/5914019",
"pm_score": 1,
"selected": false,
"text": "<p>Another method would be to do it sooner. You can create a Boolean variable and set it to true once you load data to the array. so all you really need is a simple if statement of when you load data into the array.</p>\n"
},
{
"answer_id": 37191574,
"author": "Surya",
"author_id": 6326466,
"author_profile": "https://Stackoverflow.com/users/6326466",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another way to do it. I have used it in some cases and it's working.</p>\n\n<pre><code>Function IsArrayEmpty(arr As Variant) As Boolean\n\nDim index As Integer\n\nindex = -1\n On Error Resume Next\n index = UBound(arr)\n On Error GoTo 0\n\nIf (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 38787339,
"author": "omegastripes",
"author_id": 2165759,
"author_profile": "https://Stackoverflow.com/users/2165759",
"pm_score": 0,
"selected": false,
"text": "<p>You can check if the array is empty by retrieving total elements count using JScript's <code>VBArray()</code> object (works with arrays of variant type, single or multidimensional):</p>\n\n<pre><code>Sub Test()\n\n Dim a() As Variant\n Dim b As Variant\n Dim c As Long\n\n ' Uninitialized array of variant\n ' MsgBox UBound(a) ' gives 'Subscript out of range' error\n MsgBox GetElementsCount(a) ' 0\n\n ' Variant containing an empty array\n b = Array()\n MsgBox GetElementsCount(b) ' 0\n\n ' Any other types, eg Long or not Variant type arrays\n MsgBox GetElementsCount(c) ' -1\n\nEnd Sub\n\nFunction GetElementsCount(aSample) As Long\n\n Static oHtmlfile As Object ' instantiate once\n\n If oHtmlfile Is Nothing Then\n Set oHtmlfile = CreateObject(\"htmlfile\")\n oHtmlfile.parentWindow.execScript (\"function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}\"), \"jscript\"\n End If\n GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)\n\nEnd Function\n</code></pre>\n\n<p>For me it takes about 0.3 mksec for each element + 15 msec initialization, so the array of 10M elements takes about 3 sec. The same functionality could be implemented via <code>ScriptControl</code> ActiveX (it is not available in 64-bit MS Office versions, so you can use workaround like <a href=\"https://stackoverflow.com/a/38134477/2165759\">this</a>).</p>\n"
},
{
"answer_id": 39795399,
"author": "Pierre",
"author_id": 6903657,
"author_profile": "https://Stackoverflow.com/users/6903657",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Function IsVarArrayEmpty(anArray As Variant) as boolean\n On Error Resume Next\n IsVarArrayEmpty = true\n IsVarArrayEmpty = UBound(anArray) < LBound(anArray)\nEnd Function\n</code></pre>\n\n<p>Maybe <code>ubound</code> crashes and it remains at true, and if <code>ubound < lbound</code>, it's empty</p>\n"
},
{
"answer_id": 40326677,
"author": "Fuzzier",
"author_id": 2597989,
"author_profile": "https://Stackoverflow.com/users/2597989",
"pm_score": 1,
"selected": false,
"text": "<p>To check whether a Byte array is empty, the simplest way is to use the VBA function <code>StrPtr()</code>.</p>\n\n<p>If the Byte array is empty, <code>StrPtr()</code> returns <code>0</code>; otherwise, it returns a non-zero value (however, it's <b>not</b> the address to the first element).</p>\n\n<pre><code>Dim ar() As Byte\nDebug.Assert StrPtr(ar) = 0\n\nReDim ar(0 to 3) As Byte\nDebug.Assert StrPtr(ar) <> 0\n</code></pre>\n\n<p>However, it only works with Byte array.</p>\n"
},
{
"answer_id": 40909581,
"author": "Dave Poole",
"author_id": 987776,
"author_profile": "https://Stackoverflow.com/users/987776",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if Ubound(yourArray)>-1 then\n debug.print \"The array is not empty\"\nelse\n debug.print \"EMPTY\"\nend if\n</code></pre>\n"
},
{
"answer_id": 45123278,
"author": "user425678",
"author_id": 425678,
"author_profile": "https://Stackoverflow.com/users/425678",
"pm_score": 2,
"selected": false,
"text": "<p>Based on ahuth's <a href=\"https://stackoverflow.com/a/14382846/425678\">answer</a>;</p>\n\n<pre><code>Function AryLen(ary() As Variant, Optional idx_dim As Long = 1) As Long\n If (Not ary) = -1 Then\n AryLen = 0\n Else\n AryLen = UBound(ary, idx_dim) - LBound(ary, idx_dim) + 1\n End If\nEnd Function\n</code></pre>\n\n<p>Check for an empty array; <code>is_empty = AryLen(some_array)=0</code></p>\n"
},
{
"answer_id": 50933250,
"author": "Mantej Singh",
"author_id": 2304478,
"author_profile": "https://Stackoverflow.com/users/2304478",
"pm_score": 0,
"selected": false,
"text": "<p>You can check its count.</p>\n\n<p>Here <strong>cid</strong> is an array.</p>\n\n<pre><code>if (jsonObject(\"result\")(\"cid\").Count) = 0 them\nMsgBox \"Empty Array\"\n</code></pre>\n\n<p>I hope this helps.\nHave a nice day!</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26927/"
] |
I want to check for empty arrays. Google gave me varied solutions but nothing worked. Maybe I am not applying them correctly.
```
Function GetBoiler(ByVal sFile As String) As String
'Email Signature
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.ReadAll
ts.Close
End Function
Dim FileNamesList As Variant, i As Integer
' activate the desired startfolder for the filesearch
FileNamesList = CreateFileList("*.*", False) ' Returns File names
' performs the filesearch, includes any subfolders
' present the result
' If there are Signatures then populate SigString
Range("A:A").ClearContents
For i = 1 To UBound(FileNamesList)
Cells(i + 1, 1).Formula = FileNamesList(i)
Next i
SigString = FileNamesList(3)
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
```
Here if `FileNamesList` array is empty, `GetBoiler(SigString)` should not get called at all. When `FileNamesList` array is empty, `SigString` is also empty and this calls `GetBoiler()` function with empty string. I get an error at line
```
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
```
since `sFile` is empty. Any way to avoid that?
|
As you are dealing with a string array, have you considered Join?
```
If Len(Join(FileNamesList)) > 0 Then
```
|
206,384 |
<p>I'm taking my first crack at <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:</p>
<pre><code>/Date(1224043200000)/
</code></pre>
<p>From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the <code>jQuery.UI.datepicker</code> plugin using <code>$.datepicker.formatDate()</code> without any success.</p>
<p>FYI: Here's the solution I came up with using a combination of the answers here:</p>
<pre><code>function getMismatch(id) {
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function (result) {
$("#AuthMerchId").text(result.AuthorizationMerchantId);
$("#SttlMerchId").text(result.SettlementMerchantId);
$("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
$("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
$("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
$("#LastUpdatedBy").text(result.LastUpdateNt);
$("#ProcessIn").text(result.ProcessIn);
}
);
return false;
}
function formatJSONDate(jsonDate) {
var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
return newDate;
}
</code></pre>
<p>This solution got my object from the callback method and displayed the dates on the page properly using the date format library.</p>
|
[
{
"answer_id": 206398,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 5,
"selected": false,
"text": "<p>There is no built in date type in <a href=\"http://www.json.org/\" rel=\"noreferrer\">JSON</a>. This looks like the number of seconds / milliseconds from some epoch. If you know the epoch you can create the date by adding on the right amount of time.</p>\n"
},
{
"answer_id": 206416,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 6,
"selected": false,
"text": "<p>If you say in JavaScript,</p>\n\n<pre><code>var thedate = new Date(1224043200000);\nalert(thedate);\n</code></pre>\n\n<p>you will see that it's the correct date, and you can use that anywhere in JavaScript code with any framework.</p>\n"
},
{
"answer_id": 206527,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 7,
"selected": false,
"text": "<p>You can use this to get a date from JSON:</p>\n\n<pre><code>var date = eval(jsonDate.replace(/\\/Date\\((\\d+)\\)\\//gi, \"new Date($1)\"));\n</code></pre>\n\n<p>And then you can use <a href=\"http://blog.stevenlevithan.com/archives/date-time-format\" rel=\"noreferrer\">a JavaScript Date Format</a> script (1.2 KB when minified and gzipped) to display it as you want.</p>\n"
},
{
"answer_id": 207370,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": -1,
"selected": false,
"text": "<p>Your JSON should probably be returning an object of some sort (well, a string representation thereof).</p>\n\n<pre><code>\"{ myDate : Date(1224043200000) }\"\n</code></pre>\n\n<p>Using jQuery, you can access your data object this way:</p>\n\n<pre><code>$.get(\n \"myJSONFile.php\",\n function (data) {\n // data.myDate will be a date object.\n\n // to show in a short date format (eg: dd/mm/yyyy)\n alert (\n data.myDate.getDate() + \"/\"\n + (data.myDate.getMonth() + 1) + \"/\"\n + data.myDate.getFullYear()\n ); // alerts: \"15/10/2008\"\n }\n);\n</code></pre>\n"
},
{
"answer_id": 304747,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 3,
"selected": false,
"text": "<p>Check up the date ISO standard; kind of like this:</p>\n\n<pre><code>yyyy.MM.ddThh:mm\n</code></pre>\n\n<p>It becomes <code>2008.11.20T22:18</code>.</p>\n"
},
{
"answer_id": 1471134,
"author": "Bilgin Kılıç",
"author_id": 173718,
"author_profile": "https://Stackoverflow.com/users/173718",
"pm_score": 4,
"selected": false,
"text": "<pre><code>var newDate = dateFormat(jsonDate, \"mm/dd/yyyy\"); \n</code></pre>\n\n<p>Is there another option without using the jQuery library?</p>\n"
},
{
"answer_id": 1541350,
"author": "Chris Woodward",
"author_id": 177527,
"author_profile": "https://Stackoverflow.com/users/177527",
"pm_score": 5,
"selected": false,
"text": "<p>I ended up adding the \"characters into Panos's regular expression to get rid of the ones generated by the Microsoft serializer for when writing objects into an inline script:</p>\n\n<p>So if you have a property in your C# <a href=\"http://en.wiktionary.org/wiki/code-behind\" rel=\"noreferrer\">code-behind</a> that's something like</p>\n\n<pre><code>protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}\n</code></pre>\n\n<p>And in your aspx you have</p>\n\n<pre><code><script type=\"text/javascript\">\n var myObject = '<%= JsonObject %>';\n</script>\n</code></pre>\n\n<p>You'd get something like</p>\n\n<pre><code>var myObject = '{\"StartDate\":\"\\/Date(1255131630400)\\/\"}';\n</code></pre>\n\n<p>Notice the double quotes.</p>\n\n<p>To get this into a form that eval will correctly deserialize, I used:</p>\n\n<pre><code>myObject = myObject.replace(/\"\\/Date\\((\\d+)\\)\\/\"/g, 'new Date($1)');\n</code></pre>\n\n<p>I use <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"noreferrer\">Prototype</a> and to use it I added</p>\n\n<pre><code>String.prototype.evalJSONWithDates = function() {\n var jsonWithDates = this.replace(/\"\\/Date\\((\\d+)\\)\\/\"/g, 'new Date($1)');\n return jsonWithDates.evalJSON(true);\n}\n</code></pre>\n"
},
{
"answer_id": 1611713,
"author": "Ray Linder",
"author_id": 444000,
"author_profile": "https://Stackoverflow.com/users/444000",
"pm_score": 3,
"selected": false,
"text": "<p>A late post, but for those who searched this post.</p>\n\n<p>Imagine this:</p>\n\n<pre><code> [Authorize(Roles = \"Administrator\")]\n [Authorize(Roles = \"Director\")]\n [Authorize(Roles = \"Human Resources\")]\n [HttpGet]\n public ActionResult GetUserData(string UserIdGuidKey)\n {\n if (UserIdGuidKey!= null)\n {\n var guidUserId = new Guid(UserIdGuidKey);\n var memuser = Membership.GetUser(guidUserId);\n var profileuser = Profile.GetUserProfile(memuser.UserName);\n var list = new {\n UserName = memuser.UserName,\n Email = memuser.Email ,\n IsApproved = memuser.IsApproved.ToString() ,\n IsLockedOut = memuser.IsLockedOut.ToString() ,\n LastLockoutDate = memuser.LastLockoutDate.ToString() ,\n CreationDate = memuser.CreationDate.ToString() ,\n LastLoginDate = memuser.LastLoginDate.ToString() ,\n LastActivityDate = memuser.LastActivityDate.ToString() ,\n LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,\n IsOnline = memuser.IsOnline.ToString() ,\n FirstName = profileuser.FirstName ,\n LastName = profileuser.LastName ,\n NickName = profileuser.NickName ,\n BirthDate = profileuser.BirthDate.ToString() ,\n };\n return Json(list, JsonRequestBehavior.AllowGet);\n }\n return Redirect(\"Index\");\n }\n</code></pre>\n\n<p>As you can see, I'm utilizing C# 3.0's feature for creating the \"Auto\" Generics. It's a bit lazy, but I like it and it works. \nJust a note: Profile is a custom class I've created for my web application project.</p>\n"
},
{
"answer_id": 1648041,
"author": "Jé Queue",
"author_id": 199305,
"author_profile": "https://Stackoverflow.com/users/199305",
"pm_score": 4,
"selected": false,
"text": "<p>Don't over-think this. Like we've done for decades, pass a numeric offset from the de-facto standard epoch of 1 Jan 1970 midnight GMT/UTC/&c in number of seconds (or milliseconds) since this epoch. JavaScript likes it, Java likes it, C likes it, and the Internet likes it.</p>\n"
},
{
"answer_id": 1977936,
"author": "Aaron",
"author_id": 2742,
"author_profile": "https://Stackoverflow.com/users/2742",
"pm_score": 6,
"selected": false,
"text": "<p>The original example: </p>\n\n<pre><code>/Date(1224043200000)/ \n</code></pre>\n\n<p>does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)</p>\n\n<p>I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.</p>\n\n<p>In a WCF service I have:</p>\n\n<pre><code>[OperationContract]\n[WebInvoke(\n RequestFormat = WebMessageFormat.Json,\n ResponseFormat = WebMessageFormat.Json,\n BodyStyle = WebMessageBodyStyle.WrappedRequest\n )]\nApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );\n</code></pre>\n\n<p>ApptVisitLinkInfo is defined simply:</p>\n\n<pre><code>public class ApptVisitLinkInfo {\n string Field1 { get; set; }\n DateTime Field2 { get; set; }\n ...\n}\n</code></pre>\n\n<p>When \"Field2\" is returned as Json from the service the value is:</p>\n\n<pre><code>/Date(1224043200000-0600)/\n</code></pre>\n\n<p>Notice the timezone offset included as part of the value.</p>\n\n<p>The modified regex:</p>\n\n<pre><code>/\\/Date\\((.*?)\\)\\//gi\n</code></pre>\n\n<p>It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.</p>\n\n<p>The resulting line of JavaScript for the replace is: </p>\n\n<pre><code>replace(/\\/Date\\((.*?)\\)\\//gi, \"new Date($1)\");\n</code></pre>\n"
},
{
"answer_id": 2091162,
"author": "Jason Jong",
"author_id": 209254,
"author_profile": "https://Stackoverflow.com/users/209254",
"pm_score": 7,
"selected": false,
"text": "<p>For those using Newtonsoft <a href=\"http://james.newtonking.com/pages/json-net.aspx\" rel=\"noreferrer\"><strong>Json.NET</strong></a>, read up on how to do it via <em><a href=\"http://james.newtonking.com/archive/2009/04/12/native-json-in-ie8-firefox-3-5-plus-json-net.aspx\" rel=\"noreferrer\"><strong>Native JSON in IE8, Firefox 3.5 plus Json.NET</strong></a></em>.</p>\n\n<p>Also the documentation on changing the format of dates written by Json.NET is useful:\n<a href=\"http://james.newtonking.com/projects/json/help/?topic=html/DatesInJSON.htm\" rel=\"noreferrer\"><strong>Serializing Dates with Json.NET</strong></a></p>\n\n<p>For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the <code>IsoDateTimeConverter()</code>. Note that since Json.NET 4.5 the default date format is ISO so the code below isn't needed.</p>\n\n<pre><code>string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());\n</code></pre>\n\n<p>The JSON will come through as</p>\n\n<pre><code>\"fieldName\": \"2009-04-12T20:44:55\"\n</code></pre>\n\n<p>Finally, some JavaScript to convert the ISO date to a JavaScript date:</p>\n\n<pre><code>function isoDateReviver(value) {\n if (typeof value === 'string') {\n var a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)(?:([\\+-])(\\d{2})\\:(\\d{2}))?Z?$/.exec(value);\n if (a) {\n var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);\n return new Date(utcMilliseconds);\n }\n }\n return value;\n}\n</code></pre>\n\n<p>I used it like this</p>\n\n<pre><code>$(\"<span />\").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo(\"#\" + divName);\n</code></pre>\n"
},
{
"answer_id": 2316066,
"author": "Roy Tinker",
"author_id": 163227,
"author_profile": "https://Stackoverflow.com/users/163227",
"pm_score": 12,
"selected": true,
"text": "<p><code>eval()</code> is not necessary. This will work fine:</p>\n<pre><code>var date = new Date(parseInt(jsonDate.substr(6)));\n</code></pre>\n<p>The <code>substr()</code> function takes out the <code>/Date(</code> part, and the <code>parseInt()</code> function gets the integer and ignores the <code>)/</code> at the end. The resulting number is passed into the <code>Date</code> constructor.</p>\n<hr />\n<p>I have intentionally left out the radix (the 2nd argument to <code>parseInt</code>); see <a href=\"https://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date#comment19286516_2316066\">my comment below</a>.</p>\n<p>Also, I completely agree with <a href=\"https://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date#comment20315450_2316066\">Rory's comment</a>: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.</p>\n<p>For ISO-8601 formatted JSON dates, just pass the string into the <code>Date</code> constructor:</p>\n<pre><code>var date = new Date(jsonDate); //no ugly parsing needed; full timezone support\n</code></pre>\n"
},
{
"answer_id": 2825210,
"author": "Midhat",
"author_id": 9425,
"author_profile": "https://Stackoverflow.com/users/9425",
"pm_score": 3,
"selected": false,
"text": "<p>Mootools solution:</p>\n\n<pre><code>new Date(Date(result.AppendDts)).format('%x')\n</code></pre>\n\n<p>Requires mootools-more. Tested using mootools-1.2.3.1-more on Firefox 3.6.3 and IE 7.0.5730.13</p>\n"
},
{
"answer_id": 3200078,
"author": "Kyle Alan Hale",
"author_id": 386146,
"author_profile": "https://Stackoverflow.com/users/386146",
"pm_score": 3,
"selected": false,
"text": "<p>FYI, for anyone using Python on the server side: datetime.datetime().ctime() returns a string that is natively parsable by \"new Date()\". That is, if you create a new datetime.datetime instance (such as with datetime.datetime.now), the string can be included in the JSON string, and then that string can be passed as the first argument to the Date constructor. I haven't yet found any exceptions, but I haven't tested it too rigorously, either.</p>\n"
},
{
"answer_id": 3797510,
"author": "Michael Vashchinsky",
"author_id": 260240,
"author_profile": "https://Stackoverflow.com/users/260240",
"pm_score": 3,
"selected": false,
"text": "<p>I get the date like this: </p>\n\n<pre><code>\"/Date(1276290000000+0300)/\"\n</code></pre>\n\n<p>In some examples the date is in slightly different formats:</p>\n\n<pre><code>\"/Date(12762900000000300)/\"\n\"Date(1276290000000-0300)\"\n</code></pre>\n\n<p>etc.</p>\n\n<p>So I came up with the following RegExp:</p>\n\n<pre><code>/\\/+Date\\(([\\d+]+)\\)\\/+/\n</code></pre>\n\n<p>and the final code is:</p>\n\n<pre><code>var myDate = new Date(parseInt(jsonWcfDate.replace(/\\/+Date\\(([\\d+-]+)\\)\\/+/, '$1')));\n</code></pre>\n\n<p>Hope it helps.</p>\n\n<p>Update:\nI found this link from Microsoft:\n<a href=\"http://www.asp.net/ajaxLibrary/jquery_webforms_serialize_dates_to_json.ashx\" rel=\"noreferrer\">How do I Serialize Dates with JSON?</a></p>\n\n<p>This seems like the one we are all looking for.</p>\n"
},
{
"answer_id": 3797545,
"author": "Dan Beam",
"author_id": 234201,
"author_profile": "https://Stackoverflow.com/users/234201",
"pm_score": 4,
"selected": false,
"text": "<p>Posting in awesome thread:</p>\n\n<pre><code>var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));\nalert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));\n</code></pre>\n"
},
{
"answer_id": 3930211,
"author": "StarTrekRedneck",
"author_id": 181865,
"author_profile": "https://Stackoverflow.com/users/181865",
"pm_score": 3,
"selected": false,
"text": "<p>This is frustrating. My solution was to parse out the \"/ and /\" from the value generated by ASP.NET's JavaScriptSerializer so that, though JSON may not have a date literal, it still gets interpreted by the browser as a date, which is what all I really want:<code>{\"myDate\":Date(123456789)}</code></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1341719/custom-javascriptconverter-for-datetime/3930187#3930187\">Custom JavaScriptConverter for DateTime?</a></p>\n\n<p>I must emphasize the accuracy of Roy Tinker's comment. This is not legal JSON. It's a dirty, dirty hack on the server to remove the issue before it becomes a problem for JavaScript. It will choke a JSON parser. I used it for getting off the ground, but I do not use this any more. However, I still feel the best answer lies with changing how the server formats the date, for example, ISO as mentioned elsewhere.</p>\n"
},
{
"answer_id": 4540069,
"author": "Robert Koritnik",
"author_id": 75642,
"author_profile": "https://Stackoverflow.com/users/75642",
"pm_score": 6,
"selected": false,
"text": "<h2>Don't repeat yourself - automate date conversion using <code>$.parseJSON()</code></h2>\n\n<p>Answers to your post provide manual date conversion to JavaScript dates. I've extended jQuery's <code>$.parseJSON()</code> just a little bit, so it's able to automatically parse dates when you instruct it to. It processes ASP.NET formatted dates (<code>/Date(12348721342)/</code>) as well as ISO formatted dates (<code>2010-01-01T12.34.56.789Z</code>) that are supported by native JSON functions in browsers (and libraries like json2.js).</p>\n\n<p>Anyway. If you don't want to repeat your date conversion code over and over again I suggest you read <a href=\"http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html\">this blog post</a> and get the code that will make your life a little easier.</p>\n"
},
{
"answer_id": 4928137,
"author": "Chris Moschini",
"author_id": 176877,
"author_profile": "https://Stackoverflow.com/users/176877",
"pm_score": 5,
"selected": false,
"text": "<h1>Updated</h1>\n\n<p>We have an internal UI library that has to cope with both Microsoft's ASP.NET built-in JSON format, like <code>/Date(msecs)/</code>, asked about here originally, and most JSON's date format including JSON.NET's, like <code>2014-06-22T00:00:00.0</code>. In addition we need to cope with <a href=\"https://stackoverflow.com/a/15939945/176877\">oldIE's inability to cope with anything but 3 decimal places</a>.</p>\n\n<p>We first detect what kind of date we're consuming, parse it into a normal JavaScript <code>Date</code> object, then format that out.</p>\n\n<p>1) Detect Microsoft Date format</p>\n\n<pre><code>// Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'\nfunction looksLikeMSDate(s) {\n return /^\\/Date\\(/.test(s);\n}\n</code></pre>\n\n<p>2) Detect ISO date format</p>\n\n<pre><code>var isoDateRegex = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d\\d?\\d?)?([\\+-]\\d\\d:\\d\\d|Z)?$/;\n\nfunction looksLikeIsoDate(s) {\n return isoDateRegex.test(s);\n}\n</code></pre>\n\n<p>3) Parse MS date format:</p>\n\n<pre><code>function parseMSDate(s) {\n // Jump forward past the /Date(, parseInt handles the rest\n return new Date(parseInt(s.substr(6)));\n}\n</code></pre>\n\n<p>4) Parse ISO date format.</p>\n\n<p>We do at least have a way to be sure that we're dealing with standard ISO dates or ISO dates modified to always have three millisecond places (<a href=\"https://stackoverflow.com/a/15939945/176877\">see above</a>), so the code is different depending on the environment.</p>\n\n<p>4a) Parse standard ISO Date format, cope with oldIE's issues:</p>\n\n<pre><code>function parseIsoDate(s) {\n var m = isoDateRegex.exec(s);\n\n // Is this UTC, offset, or undefined? Treat undefined as UTC.\n if (m.length == 7 || // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC\n (m.length > 7 && (\n !m[7] || // Array came back length 9 with undefined for 7 and 8\n m[7].charAt(0) != '.' || // ms portion, no tz offset, or no ms portion, Z\n !m[8] || // ms portion, no tz offset\n m[8] == 'Z'))) { // ms portion and Z\n // JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.\n var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));\n } else {\n // local\n var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);\n }\n\n return d;\n}\n</code></pre>\n\n<p>4b) Parse ISO format with a fixed three millisecond decimal places - much easier:</p>\n\n<pre><code>function parseIsoDate(s) {\n return new Date(s);\n}\n</code></pre>\n\n<p>5) Format it:</p>\n\n<pre><code>function hasTime(d) {\n return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());\n}\n\nfunction zeroFill(n) {\n if ((n + '').length == 1)\n return '0' + n;\n\n return n;\n}\n\nfunction formatDate(d) {\n if (hasTime(d)) {\n var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();\n s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());\n } else {\n var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();\n }\n\n return s;\n}\n</code></pre>\n\n<p>6) Tie it all together:</p>\n\n<pre><code>function parseDate(s) {\n var d;\n if (looksLikeMSDate(s))\n d = parseMSDate(s);\n else if (looksLikeIsoDate(s))\n d = parseIsoDate(s);\n else\n return null;\n\n return formatDate(d);\n}\n</code></pre>\n\n<p>The below old answer is useful for tying this date formatting into jQuery's own JSON parsing so you get Date objects instead of strings, or if you're still stuck in jQuery <1.5 somehow.</p>\n\n<h2>Old Answer</h2>\n\n<p>If you're using jQuery 1.4's Ajax function with ASP.NET MVC, you can turn all DateTime properties into Date objects with:</p>\n\n<pre><code>// Once\njQuery.parseJSON = function(d) {return eval('(' + d + ')');};\n\n$.ajax({\n ...\n dataFilter: function(d) {\n return d.replace(/\"\\\\\\/(Date\\(-?\\d+\\))\\\\\\/\"/g, 'new $1');\n },\n ...\n});\n</code></pre>\n\n<p>In jQuery 1.5 you can avoid overriding the <code>parseJSON</code> method globally by using the converters option in the Ajax call.</p>\n\n<p><a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"noreferrer\">http://api.jquery.com/jQuery.ajax/</a></p>\n\n<p>Unfortunately you have to switch to the older eval route in order to get Dates to parse globally in-place - otherwise you need to convert them on a more case-by-case basis post-parse.</p>\n"
},
{
"answer_id": 5589633,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 5,
"selected": false,
"text": "<p>In jQuery 1.5, as long as you have <a href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\" rel=\"noreferrer\">json2.js</a> to cover for older browsers, you can deserialize all dates coming from Ajax as follows:</p>\n\n<pre><code>(function () {\n var DATE_START = \"/Date(\";\n var DATE_START_LENGTH = DATE_START.length;\n\n function isDateString(x) {\n return typeof x === \"string\" && x.startsWith(DATE_START);\n }\n\n function deserializeDateString(dateString) {\n var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));\n var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);\n return utcDate;\n }\n\n function convertJSONDates(key, value) {\n if (isDateString(value)) {\n return deserializeDateString(value);\n }\n return value;\n }\n\n window.jQuery.ajaxSetup({\n converters: {\n \"text json\": function(data) {\n return window.JSON.parse(data, convertJSONDates);\n }\n }\n });\n}());\n</code></pre>\n\n<p>I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript <code>Date</code> object that has the proper ticks value to reflect this. That is, calling <code>getUTCHours()</code>, etc. on the date will return the same value as it did on the server, and calling <code>getHours()</code> will return the value in the user's local timezone as determined by their browser.</p>\n\n<p>This does not take into account <a href=\"http://en.wikipedia.org/wiki/Windows_Communication_Foundation\" rel=\"noreferrer\">WCF</a> format with timezone offsets, though that would be relatively easy to add.</p>\n"
},
{
"answer_id": 6381155,
"author": "Nick Perkins",
"author_id": 138939,
"author_profile": "https://Stackoverflow.com/users/138939",
"pm_score": 4,
"selected": false,
"text": "<p>Everyone of these answers has one thing in common: they all store dates as a single value (usually a string).</p>\n\n<p>Another option is to take advantage of the inherent structure of JSON, and represent a date as list of numbers:</p>\n\n<pre><code>{ \"name\":\"Nick\",\n \"birthdate\":[1968,6,9] }\n</code></pre>\n\n<p>Of course, you would have to make sure both ends of the conversation agree on the format (year, month, day), and which fields are meant to be dates,... but it has the advantage of completely avoiding the issue of date-to-string conversion. It's all numbers -- no strings at all. Also, using the order: year, month, day also allows proper sorting by date.</p>\n\n<p>Just thinking outside the box here -- a JSON date doesn't have to be stored as a string.</p>\n\n<p>Another bonus to doing it this way is that you can easily (and efficiently) select all records for a given year or month by leveraging the way <a href=\"http://en.wikipedia.org/wiki/CouchDB\" rel=\"noreferrer\">CouchDB</a> handles queries on array values.</p>\n"
},
{
"answer_id": 6545263,
"author": "在路上",
"author_id": 824464,
"author_profile": "https://Stackoverflow.com/users/824464",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var obj = eval('(' + \"{Date: \\/Date(1278903921551)\\/}\".replace(/\\/Date\\((\\d+)\\)\\//gi, \"new Date($1)\") + ')');\nvar dateValue = obj[\"Date\"];\n</code></pre>\n"
},
{
"answer_id": 7241202,
"author": "dominic",
"author_id": 919395,
"author_profile": "https://Stackoverflow.com/users/919395",
"pm_score": 4,
"selected": false,
"text": "<p>Using the jQuery UI datepicker - really only makes sense if you're already including jQuery UI:</p>\n\n<pre><code>$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6)))); \n</code></pre>\n\n<p>output: </p>\n\n<blockquote>\n <p>October 15, 2008</p>\n</blockquote>\n"
},
{
"answer_id": 10743718,
"author": "Scott Willeke",
"author_id": 51061,
"author_profile": "https://Stackoverflow.com/users/51061",
"pm_score": 4,
"selected": false,
"text": "<p>Just to add another approach here, the \"ticks approach\" that <a href=\"http://en.wikipedia.org/wiki/Windows_Communication_Foundation\" rel=\"noreferrer\">WCF</a> takes is prone to problems with timezones if you're not extremely careful such as described <a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0a6c84a3-5348-4ea0-b33f-eb411a2e1c97\" rel=\"noreferrer\">here</a> and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:</p>\n\n<p><strong>In WCF/.NET:</strong></p>\n\n<p><em>Where CreationDate is a System.DateTime; ToString(\"o\") is using .NET's <a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Roundtrip\" rel=\"noreferrer\">Round-trip format specifier</a> that generates an ISO 8601-compliant date string</em></p>\n\n<pre><code>new MyInfo {\n CreationDate = r.CreationDate.ToString(\"o\"),\n};\n</code></pre>\n\n<p><strong>In JavaScript</strong></p>\n\n<p><em>Just after retrieving the JSON I go fixup the dates to be JavaSript Date objects using the Date constructor which accepts an ISO 8601 date string...</em></p>\n\n<pre><code>$.getJSON(\n \"MyRestService.svc/myinfo\",\n function (data) {\n $.each(data.myinfos, function (r) {\n this.CreatedOn = new Date(this.CreationDate);\n });\n // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).\n alert(data.myinfos[0].CreationDate.toLocaleString());\n }\n)\n</code></pre>\n\n<p>Once you have a JavaScript date you can use all the convenient and reliable Date methods like <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toDateString\" rel=\"noreferrer\">toDateString</a>, <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toLocaleString\" rel=\"noreferrer\">toLocaleString</a>, etc.</p>\n"
},
{
"answer_id": 11261404,
"author": "Thulasiram",
"author_id": 1085778,
"author_profile": "https://Stackoverflow.com/users/1085778",
"pm_score": 3,
"selected": false,
"text": "<p>Add the <a href=\"http://en.wikipedia.org/wiki/JQuery_UI\" rel=\"noreferrer\">jQuery UI</a> plugin in your page:</p>\n\n<pre><code>function DateFormate(dateConvert) {\n return $.datepicker.formatDate(\"dd/MM/yyyy\", eval('new ' + dateConvert.slice(1, -1)));\n};\n</code></pre>\n"
},
{
"answer_id": 11883218,
"author": "Umar Malik",
"author_id": 1423894,
"author_profile": "https://Stackoverflow.com/users/1423894",
"pm_score": 3,
"selected": false,
"text": "<p>Below is a pretty simple solution for parsing JSON dates. Use the below functions as per your requirement. You just need to pass the JSON format Date fetched as a parameter to the functions below:</p>\n\n<pre><code>function JSONDate(dateStr) {\n var m, day;\n jsonDate = dateStr;\n var d = new Date(parseInt(jsonDate.substr(6)));\n m = d.getMonth() + 1;\n if (m < 10)\n m = '0' + m\n if (d.getDate() < 10)\n day = '0' + d.getDate()\n else\n day = d.getDate();\n return (m + '/' + day + '/' + d.getFullYear())\n}\n\nfunction JSONDateWithTime(dateStr) {\n jsonDate = dateStr;\n var d = new Date(parseInt(jsonDate.substr(6)));\n var m, day;\n m = d.getMonth() + 1;\n if (m < 10)\n m = '0' + m\n if (d.getDate() < 10)\n day = '0' + d.getDate()\n else\n day = d.getDate();\n var formattedDate = m + \"/\" + day + \"/\" + d.getFullYear();\n var hours = (d.getHours() < 10) ? \"0\" + d.getHours() : d.getHours();\n var minutes = (d.getMinutes() < 10) ? \"0\" + d.getMinutes() : d.getMinutes();\n var formattedTime = hours + \":\" + minutes + \":\" + d.getSeconds();\n formattedDate = formattedDate + \" \" + formattedTime;\n return formattedDate;\n}\n</code></pre>\n"
},
{
"answer_id": 13798318,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's easy to convert JSON date to a JavaScript Date:</p>\n\n<pre><code>var s = Response.StartDate; \ns = s.replace('/Date(', '');\n\ns = s.replace(')/', '');\n\nvar expDate = new Date(parseInt(s));\n</code></pre>\n"
},
{
"answer_id": 15463979,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<h2><strong><a href=\"http://jsfiddle.net/2Nf5x/\">Click here to check the Demo</a></strong></h2>\n\n<h2><strong>JavaScript/jQuery</strong></h2>\n\n<pre><code>var = MyDate_String_Value = \"/Date(1224043200000)/\"\nvar value = new Date\n (\n parseInt(MyDate_String_Value.replace(/(^.*\\()|([+-].*$)/g, ''))\n );\nvar dat = value.getMonth() +\n 1 +\n \"/\" +\n value.getDate() +\n \"/\" +\n value.getFullYear();\n</code></pre>\n\n<h2><strong>Result</strong> - \"10/15/2008\"</h2>\n"
},
{
"answer_id": 16558140,
"author": "martinoss",
"author_id": 551698,
"author_profile": "https://Stackoverflow.com/users/551698",
"pm_score": 3,
"selected": false,
"text": "<p>You also can use the JavaScript library <a href=\"http://momentjs.com/\" rel=\"noreferrer\">moment.js</a>, which comes in handy when you plan do deal with different localized formats and perform other operations with dates values:</p>\n\n<pre><code>function getMismatch(id) {\n $.getJSON(\"Main.aspx?Callback=GetMismatch\",\n { MismatchId: id },\n\n function (result) {\n $(\"#AuthMerchId\").text(result.AuthorizationMerchantId);\n $(\"#SttlMerchId\").text(result.SettlementMerchantId);\n $(\"#CreateDate\").text(moment(result.AppendDts).format(\"L\"));\n $(\"#ExpireDate\").text(moment(result.ExpiresDts).format(\"L\"));\n $(\"#LastUpdate\").text(moment(result.LastUpdateDts).format(\"L\"));\n $(\"#LastUpdatedBy\").text(result.LastUpdateNt);\n $(\"#ProcessIn\").text(result.ProcessIn);\n }\n );\n return false;\n}\n</code></pre>\n\n<p>Setting up localization is as easy as adding configuration files (you get them at momentjs.com) to your project and configuring the language:</p>\n\n<pre><code>moment.lang('de');\n</code></pre>\n"
},
{
"answer_id": 16558354,
"author": "Venemo",
"author_id": 202919,
"author_profile": "https://Stackoverflow.com/users/202919",
"pm_score": 5,
"selected": false,
"text": "<p>I also had to search for a solution to this problem and eventually I came across moment.js which is a nice library that can parse this date format and many more.</p>\n\n<pre><code>var d = moment(yourdatestring)\n</code></pre>\n\n<p>It saved some headache for me so I thought I'd share it with you. :)<br>\nYou can find some more info about it here: <a href=\"http://momentjs.com/\">http://momentjs.com/</a></p>\n"
},
{
"answer_id": 18858181,
"author": "Juan Carlos Puerto",
"author_id": 823784,
"author_profile": "https://Stackoverflow.com/users/823784",
"pm_score": 3,
"selected": false,
"text": "<p>What if <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"noreferrer\">.NET</a> returns...</p>\n\n<pre><code>return DateTime.Now.ToString(\"u\"); //\"2013-09-17 15:18:53Z\"\n</code></pre>\n\n<p>And then in JavaScript...</p>\n\n<pre><code>var x = new Date(\"2013-09-17 15:18:53Z\");\n</code></pre>\n"
},
{
"answer_id": 20237879,
"author": "Safeer Hussain",
"author_id": 826611,
"author_profile": "https://Stackoverflow.com/users/826611",
"pm_score": 2,
"selected": false,
"text": "<p>As a side note, KendoUI supports to convert Microsoft JSON date. \nSo, If your project has the reference to \"KendoUI\", you may simply use</p>\n\n<pre><code>var newDate = kendo.parseDate(jsonDate);\n</code></pre>\n"
},
{
"answer_id": 25490561,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 2,
"selected": false,
"text": "<p>This uses a <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">regular expression</a>, and it works as well:</p>\n\n<pre><code>var date = new Date(parseInt(/^\\/Date\\((.*?)\\)\\/$/.exec(jsonDate)[1], 10));\n</code></pre>\n"
},
{
"answer_id": 31854756,
"author": "Luminous",
"author_id": 2567273,
"author_profile": "https://Stackoverflow.com/users/2567273",
"pm_score": 2,
"selected": false,
"text": "<p>Another regex example you can try using:</p>\n\n<pre><code>var mydate = json.date\nvar date = new Date(parseInt(mydate.replace(/\\/Date\\((-?\\d+)\\)\\//, '$1');\nmydate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();\n</code></pre>\n\n<p><code>date.getMonth()</code> returns an integer 0 - 11 so we must add 1 to get the right month number wise</p>\n"
},
{
"answer_id": 35152855,
"author": "Ravi Mehta",
"author_id": 2504151,
"author_profile": "https://Stackoverflow.com/users/2504151",
"pm_score": 4,
"selected": false,
"text": "<p>This may can also help you. </p>\n\n<pre><code> function ToJavaScriptDate(value) { //To Parse Date from the Returned Parsed Date\n var pattern = /Date\\(([^)]+)\\)/;\n var results = pattern.exec(value);\n var dt = new Date(parseFloat(results[1]));\n return (dt.getMonth() + 1) + \"/\" + dt.getDate() + \"/\" + dt.getFullYear();\n }\n</code></pre>\n"
},
{
"answer_id": 47657364,
"author": "Reuel Ribeiro",
"author_id": 2561091,
"author_profile": "https://Stackoverflow.com/users/2561091",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way I can suggest is using regex on <code>JS</code> as:</p>\n\n<pre><code>//Only use [0] if you are sure that the string matches the pattern\n//Otherwise, verify if 'match' returns something\n\"/Date(1512488018202)/\".match(/\\d+/)[0] \n</code></pre>\n"
},
{
"answer_id": 49189419,
"author": "Harun Diluka Heshan",
"author_id": 9208617,
"author_profile": "https://Stackoverflow.com/users/9208617",
"pm_score": 3,
"selected": false,
"text": "<p>In the following code. I have</p>\n\n<p><strong>1.</strong> Retrieved the timestamp from the date string.</p>\n\n<p><strong>2.</strong> And parsed it into <code>Int</code></p>\n\n<p><strong>3.</strong> Finally Created a <code>Date</code> using it.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var dateString = \"/Date(1224043200000)/\";\r\nvar seconds = parseInt(dateString.replace(/\\/Date\\(([0-9]+)[^+]\\//i, \"$1\"));\r\nvar date = new Date(seconds);\r\nconsole.log(date);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 50292370,
"author": "Vignesh Subramanian",
"author_id": 848841,
"author_profile": "https://Stackoverflow.com/users/848841",
"pm_score": 2,
"selected": false,
"text": "<p>I use this simple function for getting date from Microsoft JSON Date</p>\n\n<pre><code>function getDateValue(dateVal) {\n return new Date(parseInt(dateVal.replace(/\\D+/g, '')));\n};\n</code></pre>\n\n<p><code>replace(/\\D+/g, '')</code> will remove all characters other than numbers </p>\n\n<p><code>parseInt</code> will convert the string to number</p>\n\n<p>Usage</p>\n\n<pre><code>$scope.ReturnDate = getDateValue(result.JSONDateVariable)\n</code></pre>\n"
},
{
"answer_id": 51208640,
"author": "Noor All Safaet",
"author_id": 4859275,
"author_profile": "https://Stackoverflow.com/users/4859275",
"pm_score": 2,
"selected": false,
"text": "<p>Try this...</p>\n\n<pre><code>function formatJSONDate(jsonDate) {\n var date = jsonDate;\n var parsedDate = new Date(parseInt(date.toString().substring(6)));\n var newDate = new Date(parsedDate);\n var getMonth = newDate.getMonth() + 1;\n var getDay = newDate.getDay();\n var getYear = newDate.getFullYear(); \n\n var standardDate = (getMonth<10 ? '0' : '') + getMonth + '/' + (getDay<10 ? '0' : '') + getDay + '/' + getYear;\n return standardDate;\n }\n</code></pre>\n\n<p>getYear() returns the year - 1900, This has been deprecated for a while now, it's best to use getFullYear()</p>\n"
},
{
"answer_id": 56401104,
"author": "b_levitt",
"author_id": 852208,
"author_profile": "https://Stackoverflow.com/users/852208",
"pm_score": 3,
"selected": false,
"text": "<p><strong>TLDR: You cannot reliably convert that date-only value, send a string instead...</strong></p>\n\n<p>...or at least that is how almost all of these answers should start off.</p>\n\n<p>There is a number of conversion issues that are happening here.</p>\n\n<p><strong>This Is a Date Without Time</strong></p>\n\n<p>Something everybody seems to be missing is how many trailing zeros there are in the question - it is almost certainly started out as a date without time:</p>\n\n<pre><code>/Date(1224043200000)/\n</code></pre>\n\n<p>When executing this from a javascript console as a new Date (the basis of many answers)</p>\n\n<pre><code>new Date(1224043200000)\n</code></pre>\n\n<p>You get:</p>\n\n<p><a href=\"https://i.stack.imgur.com/L3r43.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/L3r43.png\" alt=\"enter image description here\"></a></p>\n\n<p>The original asker was probably in EST and had a pure date (sql) or a DateTime (not DateTimeOffset) with midnight.</p>\n\n<p>In other words, the intention here is that the time portion is meaningless. However, if the browser executes this in the same timezone as the server that generated it it doesn't matter and most of the answers work.</p>\n\n<p><strong>Bit By Timezone</strong></p>\n\n<p>But, if you execute the code above on a machine with a different timezone (PST for example):</p>\n\n<p><a href=\"https://i.stack.imgur.com/GGoOw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/GGoOw.png\" alt=\"enter image description here\"></a></p>\n\n<p>You'll note that we are now a <strong>day behind</strong> in this other timezone. This will not be fixed by changing the serializer (which will still include timezone in the iso format)</p>\n\n<p><strong>The Problem</strong></p>\n\n<p>Date (sql) and DateTime (.net) do not have timezone on them, but as soon as you convert them to something that does (javascript inferred thru json in this case), the default action in .net is to assume the current timezone.</p>\n\n<p>The number that the serialization is creating is milliseconds since unix epoch or:</p>\n\n<pre><code>(DateTimeOffset.Parse(\"10/15/2008 00:00:00Z\") - DateTimeOffset.Parse(\"1/1/1970 00:00:00Z\")).TotalMilliseconds;\n</code></pre>\n\n<p>Which is something that new Date() in javascript takes as a parameter. Epoch is from UTC, so now you've got timezone info in there whether you wanted it or not.</p>\n\n<p><strong>Possible solutions:</strong></p>\n\n<p>It might be safer to create a string property on your serialized object that represents the date ONLY - a string with \"10/15/2008\" is not likely to confuse anybody else with this mess. Though even there you have to be careful on the parsing side:\n<a href=\"https://stackoverflow.com/a/31732581\">https://stackoverflow.com/a/31732581</a></p>\n\n<p>However, in the spirit of providing an answer to the question asked, as is:</p>\n\n<pre><code>function adjustToLocalMidnight(serverMidnight){ \n var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes\n var localOffset=-(new Date()).getTimezoneOffset(); \n return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)\n}\n\nvar localMidnightDate = adjustToLocalMidnight(new Date(parseInt(jsonDate.substr(6))));\n</code></pre>\n"
},
{
"answer_id": 61235930,
"author": "suhas sasuke",
"author_id": 9129689,
"author_profile": "https://Stackoverflow.com/users/9129689",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using Kotlin then this will solve your problem.</p>\n\n<pre><code>val dataString = \"/Date(1586583441106)/\"\nval date = Date(Long.parseLong(dataString.substring(6, dataString.length - 2)))\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
I'm taking my first crack at [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:
```
/Date(1224043200000)/
```
From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the `jQuery.UI.datepicker` plugin using `$.datepicker.formatDate()` without any success.
FYI: Here's the solution I came up with using a combination of the answers here:
```
function getMismatch(id) {
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function (result) {
$("#AuthMerchId").text(result.AuthorizationMerchantId);
$("#SttlMerchId").text(result.SettlementMerchantId);
$("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
$("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
$("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
$("#LastUpdatedBy").text(result.LastUpdateNt);
$("#ProcessIn").text(result.ProcessIn);
}
);
return false;
}
function formatJSONDate(jsonDate) {
var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
return newDate;
}
```
This solution got my object from the callback method and displayed the dates on the page properly using the date format library.
|
`eval()` is not necessary. This will work fine:
```
var date = new Date(parseInt(jsonDate.substr(6)));
```
The `substr()` function takes out the `/Date(` part, and the `parseInt()` function gets the integer and ignores the `)/` at the end. The resulting number is passed into the `Date` constructor.
---
I have intentionally left out the radix (the 2nd argument to `parseInt`); see [my comment below](https://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date#comment19286516_2316066).
Also, I completely agree with [Rory's comment](https://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date#comment20315450_2316066): ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.
For ISO-8601 formatted JSON dates, just pass the string into the `Date` constructor:
```
var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
```
|
206,401 |
<p>i want to call a series of .sql scripts to create the initial database structure</p>
<ol>
<li>script1.sql</li>
<li>script2.sql
etc.</li>
</ol>
<p>is there any way of doing this without sqlcmd or stored procedures <strong>or any other kind of code that is not sql</strong> ?
just inside a .sql file.</p>
|
[
{
"answer_id": 273079,
"author": "Chris Ballance",
"author_id": 1551,
"author_profile": "https://Stackoverflow.com/users/1551",
"pm_score": 2,
"selected": false,
"text": "<p>Sure. Just create a little app that pulls in all the .sql files you want and executes them. Do it in VB.NET as follows:</p>\n\n<pre><code>Sub ExecuteSqlScript(FilePath As String)\n\n Dim Script As String\n Dim FileNumber As Integer\n Dim Delimiter As String\n Dim aSubscript() As String\n Dim Subscript As String\n Dim i As Long\n\n Delimiter = \";\"\n FileNumber = FreeFile\n Script = String(FileLen(FilePath), vbNullChar)\n\n ' Grab the scripts inside the file\n Open FilePath For Binary As #FileNumber\n Get #FileNumber, , Script\n Close #FileNumber\n\n ' Put the scripts into an array\n aSubscript = Split(Script, Delimiter)\n\n ' Run each script in the array\n For i = 0 To UBound(aSubscript) - 1\n aSubscript(i) = Trim(aSubscript(i))\n Subscript = aSubscript(i)\n CurrentProject.Connection.Execute Subscript\n\n Next i\n\nEnd Sub\n</code></pre>\n\n<p>Example from: <a href=\"http://snipplr.com/view/3879/run-sql-script-from-external-file/\" rel=\"nofollow noreferrer\">http://snipplr.com/view/3879/run-sql-script-from-external-file/</a></p>\n"
},
{
"answer_id": 433701,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 4,
"selected": false,
"text": "<p>you could try this:</p>\n\n<pre><code>exec master..xp_cmdshell 'osql -E -ix:\\path\\filename.sql'\n</code></pre>\n\n<p>osql must be in the path, the full filename must be known, and logins have to be set up correctly (options -E or -U)</p>\n"
},
{
"answer_id": 433708,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "<p>There's no reason to exclude stored procedures. You don't need to include \"any other kind of code that is not sql\", plus</p>\n\n<p>EXEC someothersp</p>\n\n<p>which will be required (or its equivalent) in any other solution.</p>\n\n<p>What's your reason for excluding them? I would sure think it beats writing code in yet another language.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15193/"
] |
i want to call a series of .sql scripts to create the initial database structure
1. script1.sql
2. script2.sql
etc.
is there any way of doing this without sqlcmd or stored procedures **or any other kind of code that is not sql** ?
just inside a .sql file.
|
you could try this:
```
exec master..xp_cmdshell 'osql -E -ix:\path\filename.sql'
```
osql must be in the path, the full filename must be known, and logins have to be set up correctly (options -E or -U)
|
206,402 |
<p>Every morning we have a process that issues numerous queries (~10000) to DB2 on an AS400/iSeries/i6 (whatever IBM calls it nowadays), in the last 2 months, the operators have been complaining that our query locks a couple of files preventing them from completing their nightly processing. The queries are very simplisitic, e.g</p>
<pre><code>Select [FieldName] from OpenQuery('<LinkedServerName>', 'Select [FieldName] from [LibraryName].[FieldName] where [SomeField]=[SomeParameter]')
</code></pre>
<p>I am not an expert on the iSeries side of the house and was wondering if anyone had any insight on lock escalation from an AS400/Db2 perspective. The ID that is causing the lock has been confirmed to be the ID we registered our linked server as and we know its most likely us because the [Library] and [FileName] are consistent with the query we are issuing.</p>
<p>This has just started happening recently. Is it possible that our select statements which are causing the AS400 to escalate locks? The problem is they are not being released without manual intervention. </p>
|
[
{
"answer_id": 206556,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 3,
"selected": true,
"text": "<p>Try adding \"FOR READ ONLY\" to the query then it won't lock records as you retrieve them.</p>\n"
},
{
"answer_id": 207443,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 0,
"selected": false,
"text": "<p>Writes to the files on the AS/400 side from an RPG/COBOL/JPL job program will cause a file lock (by default I think). The job will be unable to get this lock when you are reading. The solution we used was ... don't read the files when jobs are running. We created a big schedule sheet in excel and put all the sql servers' and as/400's jobs on it in times slots w/ color coding for importance and server. That way no conflicts or out of date extract files either. </p>\n"
},
{
"answer_id": 231823,
"author": "Paul Morgan",
"author_id": 16322,
"author_profile": "https://Stackoverflow.com/users/16322",
"pm_score": 0,
"selected": false,
"text": "<p>You might have Commitment Control causing a lock for a Repeatable Read. Check the SQL Server ODBC connection associated with <code><linkedServerName></code> to change the commitment control. </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7280/"
] |
Every morning we have a process that issues numerous queries (~10000) to DB2 on an AS400/iSeries/i6 (whatever IBM calls it nowadays), in the last 2 months, the operators have been complaining that our query locks a couple of files preventing them from completing their nightly processing. The queries are very simplisitic, e.g
```
Select [FieldName] from OpenQuery('<LinkedServerName>', 'Select [FieldName] from [LibraryName].[FieldName] where [SomeField]=[SomeParameter]')
```
I am not an expert on the iSeries side of the house and was wondering if anyone had any insight on lock escalation from an AS400/Db2 perspective. The ID that is causing the lock has been confirmed to be the ID we registered our linked server as and we know its most likely us because the [Library] and [FileName] are consistent with the query we are issuing.
This has just started happening recently. Is it possible that our select statements which are causing the AS400 to escalate locks? The problem is they are not being released without manual intervention.
|
Try adding "FOR READ ONLY" to the query then it won't lock records as you retrieve them.
|
206,405 |
<p>I like to have my code warning free for VS.NET and GCC, and I like to have my code 64-bit ready.</p>
<p>Today I wrote a little module that deals with in memory buffers and provides access to the data via a file-style interface (e.g. you can read bytes, write bytes, seek around etc.).</p>
<p>As the data-type for current read position and size I used size_t since that seems to be the most natural choice. I get around the warnings and it ought to work in 64-bit as well. </p>
<p>Just in case: My structure looks like this:</p>
<pre><code>typedef struct
{
unsigned char * m_Data;
size_t m_CurrentReadPosition;
size_t m_DataSize;
} MyMemoryFile;
</code></pre>
<p>The signedness of <code>size_t</code> seems not to be defined in practice. A Google code-search proved that.</p>
<p>Now I'm in a dilemma: I want to check additions with <code>size_t</code> for overflows because I have to deal with user supplied data and third party libraries will use my code. However, for the overflow check I have to know the sign-ness. It makes a huge difference in the implementation. </p>
<p>So - how the heck should I write such a code in a platform and compiler independent way? </p>
<p>Can I check the signedness of <code>size_t</code> at run or compile-time? That would solve my problem. Or maybe <code>size_t</code> wasn't the best idea in the first place.</p>
<p>Any ideas?</p>
<p><strong>EDIT</strong>: I'm looking for a solution for the C-language!</p>
|
[
{
"answer_id": 206422,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 3,
"selected": false,
"text": "<p><code>size_t</code> should be unsigned.</p>\n\n<p>It's typically defined as unsigned long.</p>\n\n<p>I've never seen it be defined otherwise. <code>ssize_t</code> is its signed counterpart.</p>\n\n<p>EDIT:\nGCC defines it as signed in some circumstances. compiling in ASNI C mode or std-99 should force it to be unsigned.</p>\n"
},
{
"answer_id": 206442,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://www.codeplex.com/SafeInt\" rel=\"nofollow noreferrer\">safeint</a>. It is a class designed by Michael Howard and released as open source from Microsoft. It is designed to make working with integers where overflow is identified as a risk. All overflows are converted to exceptions and handled. The class is designed to make correct usage easy.</p>\n\n<p>For example :</p>\n\n<pre><code>char CouldBlowUp(char a, char b, char c)\n{\n SafeInt<char> sa(a), sb(b), sc(c);\n\n try\n {\n return (sa * sb + sc).Value();\n }\n catch(SafeIntException err)\n {\n ComplainLoudly(err.m_code);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Also safeint is used a lot internally at Microsoft in products like Office.</p>\n\n<p>Ref:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms972705.aspx\" rel=\"nofollow noreferrer\">link text</a></p>\n"
},
{
"answer_id": 206460,
"author": "Francisco Soto",
"author_id": 3695,
"author_profile": "https://Stackoverflow.com/users/3695",
"pm_score": -1,
"selected": false,
"text": "<p>I am not sure if I understand the question exactly, but maybe you can do something like:</p>\n\n<pre><code>temp = value_to_be_added_to;\n\nvalue_to_be_added_to += value_to_add;\n\nif (temp > value_to_be_added_to)\n{\n overflow...\n}\n</code></pre>\n\n<p>Since it will wrap back to lower values you can easily check if it overflowed.</p>\n"
},
{
"answer_id": 206489,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>For C language, use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ff521693(v=vs.85).aspx\" rel=\"nofollow noreferrer\">IntSafe</a>. Also released by Microsoft (not to be confused with the C++ library SafeInt). IntSafe is a set of C language function calls that can perform math and do conversions safely.\n<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ff521693(v=vs.85).aspx\" rel=\"nofollow noreferrer\">updated URL for intsafe functions</a></p>\n"
},
{
"answer_id": 206494,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 3,
"selected": false,
"text": "<p><code>size_t</code> is an unsigned integral type, according to the C++ C standards. Any implementation that has <code>size_t</code> signed is seriously nonconforming, and probably has other portability problems as well. It is guaranteed to wrap around when overflowing, meaning that you can write tests like <code>if (a + b < a)</code> to find overflow.</p>\n\n<p><code>size_t</code> is an excellent type for anything involving memory. You're doing it right.</p>\n"
},
{
"answer_id": 206584,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": true,
"text": "<p>Regarding the whether <code>size</code>_t is signed or unsigned and GCC (from an old GCC manual - I'm not sure if it's still there):</p>\n\n<blockquote>\n <p>There is a potential problem with the\n <code>size_t</code> type and versions of GCC prior\n to release 2.4. ANSI C requires that\n <code>size_t</code> always be an unsigned type. For\n compatibility with existing systems'\n header files, GCC defines <code>size_t</code> in\n <code>stddef.h</code> to be whatever type the\n system's <code>sys/types.h</code> defines it to\n be. Most Unix systems that define\n <code>size_t</code> in <code>sys/types.h</code>, define it to\n be a signed type. Some code in the\n library depends on <code>size_t</code> being an\n unsigned type, and will not work\n correctly if it is signed.</p>\n \n <p>The GNU C library code which expects\n <code>size_t</code> to be unsigned is correct. The\n definition of <code>size_t</code> as a signed type\n is incorrect. We plan that in version\n 2.4, GCC will always define <code>size_t</code> as an unsigned type, and the\n 'fixincludes' script will massage the\n system's <code>sys/types.h</code> so as not to\n conflict with this.</p>\n \n <p>In the meantime, we work around this\n problem by telling GCC explicitly to\n use an unsigned type for <code>size_t</code> when\n compiling the GNU C library.\n 'configure' will automatically detect\n what type GCC uses for <code>size_t</code> arrange\n to override it if necessary.</p>\n</blockquote>\n\n<p>If you want a signed version of <code>size_t</code> use <code>ptrdiff_t</code> or on some systems there is a typedef for <code>ssize_t</code>.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
] |
I like to have my code warning free for VS.NET and GCC, and I like to have my code 64-bit ready.
Today I wrote a little module that deals with in memory buffers and provides access to the data via a file-style interface (e.g. you can read bytes, write bytes, seek around etc.).
As the data-type for current read position and size I used size\_t since that seems to be the most natural choice. I get around the warnings and it ought to work in 64-bit as well.
Just in case: My structure looks like this:
```
typedef struct
{
unsigned char * m_Data;
size_t m_CurrentReadPosition;
size_t m_DataSize;
} MyMemoryFile;
```
The signedness of `size_t` seems not to be defined in practice. A Google code-search proved that.
Now I'm in a dilemma: I want to check additions with `size_t` for overflows because I have to deal with user supplied data and third party libraries will use my code. However, for the overflow check I have to know the sign-ness. It makes a huge difference in the implementation.
So - how the heck should I write such a code in a platform and compiler independent way?
Can I check the signedness of `size_t` at run or compile-time? That would solve my problem. Or maybe `size_t` wasn't the best idea in the first place.
Any ideas?
**EDIT**: I'm looking for a solution for the C-language!
|
Regarding the whether `size`\_t is signed or unsigned and GCC (from an old GCC manual - I'm not sure if it's still there):
>
> There is a potential problem with the
> `size_t` type and versions of GCC prior
> to release 2.4. ANSI C requires that
> `size_t` always be an unsigned type. For
> compatibility with existing systems'
> header files, GCC defines `size_t` in
> `stddef.h` to be whatever type the
> system's `sys/types.h` defines it to
> be. Most Unix systems that define
> `size_t` in `sys/types.h`, define it to
> be a signed type. Some code in the
> library depends on `size_t` being an
> unsigned type, and will not work
> correctly if it is signed.
>
>
> The GNU C library code which expects
> `size_t` to be unsigned is correct. The
> definition of `size_t` as a signed type
> is incorrect. We plan that in version
> 2.4, GCC will always define `size_t` as an unsigned type, and the
> 'fixincludes' script will massage the
> system's `sys/types.h` so as not to
> conflict with this.
>
>
> In the meantime, we work around this
> problem by telling GCC explicitly to
> use an unsigned type for `size_t` when
> compiling the GNU C library.
> 'configure' will automatically detect
> what type GCC uses for `size_t` arrange
> to override it if necessary.
>
>
>
If you want a signed version of `size_t` use `ptrdiff_t` or on some systems there is a typedef for `ssize_t`.
|
206,447 |
<p>I am trying to use a class from a C# assembly in vb.net. The class has ambiguous members because vb.net is case insensitive. The class is something like this:</p>
<pre>
public class Foo {
public enum FORMAT {ONE, TWO, THREE};
public FORMAT Format {
get {...}
set {...}
}
}
</pre>
<p>I try to access the enum: Foo.FORMAT.ONE</p>
<p>This is not possible because there is also a property named 'format'.</p>
<p>I can not change the C# assembly. How can I get around this and reference the enum from vb.net?</p>
|
[
{
"answer_id": 206475,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": true,
"text": "<p>I don't think you can get around this. Get in touch with the author of the C# component you are trying to use and convince them to fix their code.</p>\n\n<p>Incidentally, this is the primary reason behind the <code>CLSCompliant(true)</code> attribute, which if you are writing APIs or other code that has a high probability of being used by other languages you should always set. It would have flagged this issue for the original author to be aware of and fix correctly.</p>\n"
},
{
"answer_id": 206599,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of ways you can work around it, but neither one is really a good option.</p>\n\n<p>One is to create a C# project and completely wrap the class, changing the ambiguous members into unambiguous ones. Depending on how big the class is, it could be a lot of work, though you only have to wrap the members you need, obviously.</p>\n\n<p>The other is to use reflection, which isn't as much work as wrapping, but is still pointless work compared to the author just writing the code correctly in the first place.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10034/"
] |
I am trying to use a class from a C# assembly in vb.net. The class has ambiguous members because vb.net is case insensitive. The class is something like this:
```
public class Foo {
public enum FORMAT {ONE, TWO, THREE};
public FORMAT Format {
get {...}
set {...}
}
}
```
I try to access the enum: Foo.FORMAT.ONE
This is not possible because there is also a property named 'format'.
I can not change the C# assembly. How can I get around this and reference the enum from vb.net?
|
I don't think you can get around this. Get in touch with the author of the C# component you are trying to use and convince them to fix their code.
Incidentally, this is the primary reason behind the `CLSCompliant(true)` attribute, which if you are writing APIs or other code that has a high probability of being used by other languages you should always set. It would have flagged this issue for the original author to be aware of and fix correctly.
|
206,469 |
<p>Need a refresher on bits/bytes, hex notation and how it relates to programming (C# preferred).</p>
<p>Looking for a good reading list (online preferably).</p>
|
[
{
"answer_id": 206504,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 0,
"selected": false,
"text": "<p>A bit is either 1 or 0.</p>\n\n<p>A byte is 8 bits. </p>\n\n<p>Each character in hex is 4 bits represented as 0-F</p>\n\n<ul>\n<li>0000 is 0 </li>\n<li>0001 is 1</li>\n<li>0010 is 2</li>\n<li>0011 is 3</li>\n<li>...</li>\n<li>1110 is E</li>\n<li>1111 is F</li>\n</ul>\n\n<p>There's a pretty good intro to C#'s bit-munching operations <a href=\"http://www.c-sharpcorner.com/UploadFile/chandrahundigam/BitWiserOpsInCS11082005050940AM/BitWiserOpsInCS.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 206519,
"author": "mannu",
"author_id": 15858,
"author_profile": "https://Stackoverflow.com/users/15858",
"pm_score": 0,
"selected": false,
"text": "<p>Here is some basic reading: <a href=\"http://www.learn-c.com/data_lines.htm\" rel=\"nofollow noreferrer\">http://www.learn-c.com/data_lines.htm</a></p>\n\n<p>Bits and bytes hardly ever relates to C# since the CLR handles memory by itself. There are classes and methods handling hex notation and all those things in the framework too. But, it is still a fun read.</p>\n"
},
{
"answer_id": 206666,
"author": "Ichorus",
"author_id": 27247,
"author_profile": "https://Stackoverflow.com/users/27247",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1593270038\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Write Great Code</a> is a good primer on this topic among others...brings you from the bare metal to higher order languages.</p>\n"
},
{
"answer_id": 1128731,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 2,
"selected": false,
"text": "<p>There are several layers to consider here:</p>\n\n<ul>\n<li>Electronic</li>\n</ul>\n\n<p>In the electronic paradigm, everything is a wire.</p>\n\n<p>A single wire represents a single bit. </p>\n\n<p>0 is the LOW voltage, 1 is the\nHIGH voltage. The voltages may be <code>[0,5], [-3.3, 3], [-5, 5], [0, 1.3]</code>,\netc. The key thing is that there are only two voltage levels which control\nthe action of the transistors. </p>\n\n<p>A byte is a collection of wires(To be precise, it's probably collected in a set of flip-flops called registers, but let's leave it as \"wires\" for now).</p>\n\n<ul>\n<li>Programming</li>\n</ul>\n\n<p>A bit is 0 or 1. </p>\n\n<p>A byte is - in modern systems - 8 bits. Ancient systems might have had 10-bit bytes or other sizes; they don't exist today. </p>\n\n<p>A <em>nybble</em> is 4 bits; half a byte.</p>\n\n<p>Hexadecimal is an efficient representation of 8 bits. For example: F\nmaps to <code>1111 1111</code>. That is more efficient than writing 15. Plus, it is quite clear if you are writing down multiple byte values: FF is unambiguous; 1515 can be read several different ways.</p>\n\n<p>Historically, octal has been also used(base 8). However, the only place where I have met it is in the Unix permissions. </p>\n\n<p>Since on the electronic layer, it is most efficient to collect memory\nin groups of 2^n, hex is a natural notation for representing\nmemory. Further, if you happen to work at the driver level, you may\nneed to specifically control a given bit, which will require the use\nof bit-level operators. It is clear which bytes are on HI if you say\n<code>F & outputByte</code> than <code>15 & outputByte</code>.</p>\n\n<p>In general, much of modern programming does not need to concern itself\nwith binary and hexadecimal. However, if you are in a place where you\nneed to know it, there is no slipping by - you <em>really</em> need to know\nit then. </p>\n\n<p>Particular areas that need the knowledge of binary include: embedded\nsystems, driver writing, operating system writing, network protocols,\nand compression algorithms.</p>\n\n<p>While you wanted C#, C# is really not the right language for bit-level\nmanipulation. Traditionally, C and C++ are the languages used for bit\nwork. Erlang works with bit manipulation, and Perl supports it as\nwell. VHDL is completely bit-oriented, but is fairly difficult to work\nwith from the typical programming perspective.</p>\n\n<p>Here is some sample C code for performing different logical operations:</p>\n\n<pre><code>char a, b, c; \nc = a ^ b; //XOR\nc = a & b; //AND\nc = a | b; //OR\nc = ~(a & b); //NOT AND(NAND)\nc = ~a; //NOT\nc = a << 2; //Left shift 2 places\nc = a >> 2; //Right shift 2 places.\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Need a refresher on bits/bytes, hex notation and how it relates to programming (C# preferred).
Looking for a good reading list (online preferably).
|
There are several layers to consider here:
* Electronic
In the electronic paradigm, everything is a wire.
A single wire represents a single bit.
0 is the LOW voltage, 1 is the
HIGH voltage. The voltages may be `[0,5], [-3.3, 3], [-5, 5], [0, 1.3]`,
etc. The key thing is that there are only two voltage levels which control
the action of the transistors.
A byte is a collection of wires(To be precise, it's probably collected in a set of flip-flops called registers, but let's leave it as "wires" for now).
* Programming
A bit is 0 or 1.
A byte is - in modern systems - 8 bits. Ancient systems might have had 10-bit bytes or other sizes; they don't exist today.
A *nybble* is 4 bits; half a byte.
Hexadecimal is an efficient representation of 8 bits. For example: F
maps to `1111 1111`. That is more efficient than writing 15. Plus, it is quite clear if you are writing down multiple byte values: FF is unambiguous; 1515 can be read several different ways.
Historically, octal has been also used(base 8). However, the only place where I have met it is in the Unix permissions.
Since on the electronic layer, it is most efficient to collect memory
in groups of 2^n, hex is a natural notation for representing
memory. Further, if you happen to work at the driver level, you may
need to specifically control a given bit, which will require the use
of bit-level operators. It is clear which bytes are on HI if you say
`F & outputByte` than `15 & outputByte`.
In general, much of modern programming does not need to concern itself
with binary and hexadecimal. However, if you are in a place where you
need to know it, there is no slipping by - you *really* need to know
it then.
Particular areas that need the knowledge of binary include: embedded
systems, driver writing, operating system writing, network protocols,
and compression algorithms.
While you wanted C#, C# is really not the right language for bit-level
manipulation. Traditionally, C and C++ are the languages used for bit
work. Erlang works with bit manipulation, and Perl supports it as
well. VHDL is completely bit-oriented, but is fairly difficult to work
with from the typical programming perspective.
Here is some sample C code for performing different logical operations:
```
char a, b, c;
c = a ^ b; //XOR
c = a & b; //AND
c = a | b; //OR
c = ~(a & b); //NOT AND(NAND)
c = ~a; //NOT
c = a << 2; //Left shift 2 places
c = a >> 2; //Right shift 2 places.
```
|
206,473 |
<p>Is there a way to compile an Eclipse-based Java project from the command line? </p>
<p>I'm trying to automate my build (using FinalBuilder not ant), and I'm neither a Java nor Eclipse expert. I can probably figure out how to do this with straight java command line options, but then the Eclipse project feels like a lot of wasted effort. </p>
<p>In the event that there is no way to compile an Eclipse project via the command line, is there a way to generate the required java command line from within Eclipse? Or are there some files I can poke around to find the compile steps it is doing behind the scenes? </p>
<hr>
<p>Guys, I'm looking for an answer that does <em>NOT</em> include ant. Let me re-iterate the original question ....... Is there a way to build an Eclipse project from the command line?</p>
<p>I don't think this is an unreasonable question given that I can do something like this for visual studio:</p>
<pre><code>devenv.exe /build "Debug|Any CPU" "C:\Projects\MyProject\source\MyProject.sln"
</code></pre>
|
[
{
"answer_id": 206497,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 3,
"selected": false,
"text": "<p>The normal apporoach works the other way around: You create your build based upon <a href=\"http://maven.apache.org/\" rel=\"noreferrer\">maven</a> or <a href=\"http://ant.apache.org\" rel=\"noreferrer\">ant</a> and then use integrations for your IDE of choice so that you are independent from it, which is esp. important when you try to bring new team members up to speed or use a contious integration server for automated builds. I recommend to use maven and let it do the heavy lifting for you. Create a pom file and generate the eclipse project via mvn eclipse:eclipse. HTH</p>\n"
},
{
"answer_id": 206502,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/133234/building-eclipse-plugins-and-features-on-the-command-line\">This question</a> contains some useful links on headless builds, but they are mostly geared towards building plugins. I'm not sure how much of it can be applied to pure Java projects.</p>\n"
},
{
"answer_id": 206587,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "<p>To complete André's answer, an ant solution could be like the one described in <a href=\"http://www.emacsblog.org/2007/02/13/emacs-jdee-ant-and-the-eclipse-java-compiler/\" rel=\"nofollow noreferrer\">Emacs, JDEE, Ant, and the Eclipse Java Compiler</a>, as in:</p>\n\n<pre><code> <javac\n srcdir=\"${src}\"\n destdir=\"${build.dir}/classes\"> \n <compilerarg \n compiler=\"org.eclipse.jdt.core.JDTCompilerAdapter\" \n line=\"-warn:+unused -Xemacs\"/>\n <classpath refid=\"compile.classpath\" />\n </javac>\n</code></pre>\n\n<p>The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.</p>\n\n<p>You can find a <a href=\"http://dev.eclipse.org/newslists/news.eclipse.platform.rcp/msg31872.html\" rel=\"nofollow noreferrer\">full ant script example here</a> which would be <strong><em>invoked in a command line</em></strong> with:</p>\n\n<pre><code>java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data \"C:\\Documents and Settings\\Administrator\\workspace\" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose\n</code></pre>\n\n<hr>\n\n<p>BUT all that involves ant, which is not what Keith is after.</p>\n\n<p>For a batch compilation, please refer to <strong><a href=\"http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_api_compile.htm\" rel=\"nofollow noreferrer\">Compiling Java code</a></strong>, especially the section \"<strong><em>Using the batch compiler</em></strong>\"</p>\n\n<blockquote>\n <p>The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.<br>\n Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.</p>\n</blockquote>\n\n<p>Running the batch compiler From the command line would give</p>\n\n<pre><code>java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>java -jar ecj.jar -classpath rt.jar A.java\n</code></pre>\n\n<p>All java compilation options are detailed in that section as well.</p>\n\n<p>The difference with the Visual Studio command line compilation feature is that <strong><em>Eclipse does not seem to directly read its .project and .classpath in a command-line argument</em></strong>. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.</p>\n\n<p>So, then short answer is: \"yes, Eclipse kind of does.\" ;)</p>\n"
},
{
"answer_id": 207392,
"author": "pdeva",
"author_id": 14316,
"author_profile": "https://Stackoverflow.com/users/14316",
"pm_score": -1,
"selected": false,
"text": "<p>Short answer. No.\nEclipse does not have a command line switch like Visual Studio to build a project.</p>\n"
},
{
"answer_id": 333407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Hi Just addition to VonC comments. I am using ecj compiler to compile my project. it was throwing expcetion that some of the classes are not found. But the project was bulding fine with javac compiler.</p>\n\n<p>So just I added the classes into the classpath(which we have to pass as argument) and now its working fine... :)</p>\n\n<p>Kulbir Singh</p>\n"
},
{
"answer_id": 1433396,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 7,
"selected": true,
"text": "<p>You can build an eclipse project via a workspace from the command line:</p>\n\n<pre><code>eclipsec.exe -noSplash -data \"D:\\Source\\MyProject\\workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n</code></pre>\n\n<p>It uses the <code>jdt apt</code> plugin to build your workspace automatically. This is also known as a 'Headless Build'. Damn hard to figure out. If you're not using a win32 exe, you can try this:</p>\n\n<pre><code>java -cp startup.jar -noSplash -data \"D:\\Source\\MyProject\\workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>Several years ago eclipse replaced <code>startup.jar</code> with the \"equinox launcher\"</p>\n\n<p><a href=\"https://wiki.eclipse.org/Equinox_Launcher\" rel=\"noreferrer\">https://wiki.eclipse.org/Equinox_Launcher</a></p>\n\n<p>On Eclipse Mars (MacOX):</p>\n\n<pre><code>java -jar /Applications/Eclipse.app/Contents/Eclipse/plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar -noSplash -data \"workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n</code></pre>\n\n<p>The <code>-data</code> parameter specifies the location of your workspace.</p>\n\n<p>The version number for the equinox launcher will depend on what version of eclipse you have.</p>\n"
},
{
"answer_id": 19099609,
"author": "Charles Thomas",
"author_id": 2812597,
"author_profile": "https://Stackoverflow.com/users/2812597",
"pm_score": 3,
"selected": false,
"text": "<p>After 27 years, I too, am uncomfortable developing in an IDE. I tried these suggestions (above) - and probably just didn't follow everything right -- so I did a web-search and found what worked for me at '<a href=\"http://incise.org/android-development-on-the-command-line.html\" rel=\"noreferrer\">http://incise.org/android-development-on-the-command-line.html</a>'.</p>\n\n<p>The answer seemed to be a combination of all the answers above (please tell me if I'm wrong and accept my apologies if so).</p>\n\n<p>As mentioned above, eclipse/adt does not create the necessary ant files. In order to compile without eclipse IDE (and without creating ant scripts):</p>\n\n<p>1) Generate build.xml in your top level directory:</p>\n\n<pre><code>android list targets (to get target id used below)\n\nandroid update project --target target_id --name project_name --path top_level_directory\n\n ** my sample project had a target_id of 1 and a project name of 't1', and \n I am building from the top level directory of project\n my command line looks like android update project --target 1 --name t1 --path `pwd`\n</code></pre>\n\n<p>2) Next I compile the project. I was a little confused by the request to not use 'ant'.\n Hopefully -- requester meant that he didn't want to write any ant scripts. I say this \n because the next step is to compile the application using ant</p>\n\n<pre><code> ant target\n\n this confused me a little bit, because i thought they were talking about the\n android device, but they're not. It's the mode (debug/release)\n my command line looks like ant debug\n</code></pre>\n\n<p>3) To install the apk onto the device I had to use ant again:</p>\n\n<pre><code> ant target install\n\n ** my command line looked like ant debug install\n</code></pre>\n\n<p>4) To run the project on my android phone I use adb.</p>\n\n<pre><code> adb shell 'am start -n your.project.name/.activity'\n\n ** Again there was some confusion as to what exactly I had to use for project \n My command line looked like adb shell 'am start -n com.example.t1/.MainActivity'\n I also found that if you type 'adb shell' you get put to a cli shell interface\n where you can do just about anything from there.\n</code></pre>\n\n<p>3A) A side note: To view the log from device use:</p>\n\n<pre><code> adb logcat\n</code></pre>\n\n<p>3B) A second side note: The link mentioned above also includes instructions for building the entire project from the command.</p>\n\n<p>Hopefully, this will help with the question. I know I was really happy to find <em>anything</em> about this topic here.</p>\n"
},
{
"answer_id": 30632723,
"author": "jkwinn26",
"author_id": 2157385,
"author_profile": "https://Stackoverflow.com/users/2157385",
"pm_score": 1,
"selected": false,
"text": "<p>Just wanted to add my two cents to this. I tried doing as @Kieveli suggested for non win32 (repeated below) but it didn't work for me (on CentOS with Eclipse: Luna):</p>\n\n<pre><code>java -cp startup.jar -noSplash -data \"D:\\Source\\MyProject\\workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n</code></pre>\n\n<p>On my particular setup on CentOS using Eclipse (Luna) this worked:</p>\n\n<pre><code>$ECLIPSE_HOME/eclipse -nosplash -application org.eclipse.jdt.apt.core.aptBuild startup.jar -data ~/workspace\n</code></pre>\n\n<p>The output should look something like this:</p>\n\n<pre><code>Building workspace\nBuilding '/RemoteSystemsTempFiles'\nBuilding '/test'\nInvoking 'Java Builder' on '/test'.\nCleaning output folder for test\nBuild done\nBuilding workspace\nBuilding '/RemoteSystemsTempFiles'\nBuilding '/test'\nInvoking 'Java Builder' on '/test'.\nPreparing to build test\nCleaning output folder for test\nCopying resources to the output folder\nAnalyzing sources\nCompiling test/src/com/company/test/tool\nBuild done\n</code></pre>\n\n<p>Not quite sure why it apparently did it twice, but it seems to work.</p>\n"
},
{
"answer_id": 72432790,
"author": "Ashkan Ansarifard",
"author_id": 19231107,
"author_profile": "https://Stackoverflow.com/users/19231107",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to just add this comment to this question for anyone who may encounter this issue in the future.</p>\n<p>Once, I was working on a project and building complex and inter-related JAVA projects from CMD (using ECLIPSE) was my only option. So, all you need to is this:</p>\n<ul>\n<li><p>Download your desired ECLIPSE IDE (tested it with ECLIPSE OXYGEN, Eclipse IDE for Enterprise Java and Web Developers and Eclipse IDE for Java Developers and it works fine)</p>\n</li>\n<li><p>Open your project in the ECLIPSE and change the ECLIPSE configuration based on your project</p>\n</li>\n<li><p>Close the ECLIPSE and save the .metadata created from your ECLIPSE (If your workspace is going to be refreshed in the future)</p>\n</li>\n<li><p>Run this script in the CMD:</p>\n</li>\n</ul>\n<pre><code>"%ECLIPSE_IDE%\\eclipsec.exe" -noSplash -data "YOUR_WORKSPACE" -application org.eclipse.jdt.apt.core.aptBuild\n</code></pre>\n<p><strong>So, all I wanted to say is that, I could not build using the above commands without the .metadata being in the workspace. Make sure it exists there. If you need, make a copy of .metadata and copy-paste it each time your want to execute the commands.</strong></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5208/"
] |
Is there a way to compile an Eclipse-based Java project from the command line?
I'm trying to automate my build (using FinalBuilder not ant), and I'm neither a Java nor Eclipse expert. I can probably figure out how to do this with straight java command line options, but then the Eclipse project feels like a lot of wasted effort.
In the event that there is no way to compile an Eclipse project via the command line, is there a way to generate the required java command line from within Eclipse? Or are there some files I can poke around to find the compile steps it is doing behind the scenes?
---
Guys, I'm looking for an answer that does *NOT* include ant. Let me re-iterate the original question ....... Is there a way to build an Eclipse project from the command line?
I don't think this is an unreasonable question given that I can do something like this for visual studio:
```
devenv.exe /build "Debug|Any CPU" "C:\Projects\MyProject\source\MyProject.sln"
```
|
You can build an eclipse project via a workspace from the command line:
```
eclipsec.exe -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild
```
It uses the `jdt apt` plugin to build your workspace automatically. This is also known as a 'Headless Build'. Damn hard to figure out. If you're not using a win32 exe, you can try this:
```
java -cp startup.jar -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild
```
**Update**
Several years ago eclipse replaced `startup.jar` with the "equinox launcher"
<https://wiki.eclipse.org/Equinox_Launcher>
On Eclipse Mars (MacOX):
```
java -jar /Applications/Eclipse.app/Contents/Eclipse/plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar -noSplash -data "workspace" -application org.eclipse.jdt.apt.core.aptBuild
```
The `-data` parameter specifies the location of your workspace.
The version number for the equinox launcher will depend on what version of eclipse you have.
|
206,484 |
<p>I tried searching around, but I couldn't find anything that would help me out.</p>
<p>I'm trying to do this in SQL:</p>
<pre><code>declare @locationType varchar(50);
declare @locationID int;
SELECT column1, column2
FROM viewWhatever
WHERE
CASE @locationType
WHEN 'location' THEN account_location = @locationID
WHEN 'area' THEN xxx_location_area = @locationID
WHEN 'division' THEN xxx_location_division = @locationID
</code></pre>
<p>I know that I shouldn't have to put '= @locationID' at the end of each one, but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line...</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 206500,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 9,
"selected": true,
"text": "<pre><code>declare @locationType varchar(50);\ndeclare @locationID int;\n\nSELECT column1, column2\nFROM viewWhatever\nWHERE\n@locationID = \n CASE @locationType\n WHEN 'location' THEN account_location\n WHEN 'area' THEN xxx_location_area \n WHEN 'division' THEN xxx_location_division \n END\n</code></pre>\n"
},
{
"answer_id": 206518,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 3,
"selected": false,
"text": "<p>I'd say this is an indicator of a flawed table structure. Perhaps the different location types should be separated in different tables, enabling you to do much richer querying and also avoid having superfluous columns around.</p>\n\n<p>If you're unable to change the structure, something like the below might work:</p>\n\n<pre><code>SELECT\n *\nFROM\n Test\nWHERE\n Account_Location = (\n CASE LocationType\n WHEN 'location' THEN @locationID\n ELSE Account_Location\n END\n )\n AND\n Account_Location_Area = (\n CASE LocationType\n WHEN 'area' THEN @locationID\n ELSE Account_Location_Area\n END\n )\n</code></pre>\n\n<p>And so forth... We can't change the structure of the query on the fly, but we can override it by making the predicates equal themselves out.</p>\n\n<p>EDIT: The above suggestions are of course much better, just ignore mine.</p>\n"
},
{
"answer_id": 206520,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with this is that when the SQL engine goes to evaluate the expression, it checks the FROM portion to pull the proper tables, and then the WHERE portion to provide some base criteria, so it cannot properly evaluate a dynamic condition on which column to check against.</p>\n\n<p>You can use a WHERE clause when you're checking the WHERE criteria in the predicate, such as</p>\n\n<pre><code>WHERE account_location = CASE @locationType\n WHEN 'business' THEN 45\n WHEN 'area' THEN 52\n END\n</code></pre>\n\n<p>so in your particular case, you're going to need put the query into a stored procedure or create three separate queries.</p>\n"
},
{
"answer_id": 206712,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 6,
"selected": false,
"text": "<p>Here you go.</p>\n\n<pre><code>SELECT\n column1, \n column2\nFROM\n viewWhatever\nWHERE\nCASE \n WHEN @locationType = 'location' AND account_location = @locationID THEN 1\n WHEN @locationType = 'area' AND xxx_location_area = @locationID THEN 1\n WHEN @locationType = 'division' AND xxx_location_division = @locationID THEN 1\n ELSE 0\nEND = 1\n</code></pre>\n"
},
{
"answer_id": 858666,
"author": "Lukek",
"author_id": 106180,
"author_profile": "https://Stackoverflow.com/users/106180",
"pm_score": 6,
"selected": false,
"text": "<p>without a case statement...</p>\n\n<pre><code>SELECT column1, column2\nFROM viewWhatever\nWHERE\n (@locationType = 'location' AND account_location = @locationID)\n OR\n (@locationType = 'area' AND xxx_location_area = @locationID)\n OR\n (@locationType = 'division' AND xxx_location_division = @locationID)\n</code></pre>\n"
},
{
"answer_id": 6183682,
"author": "Durre Najaf",
"author_id": 777162,
"author_profile": "https://Stackoverflow.com/users/777162",
"pm_score": 2,
"selected": false,
"text": "<p>Please try this query.\nAnswer To above post:</p>\n\n<pre><code>select @msgID, account_id\n from viewMailAccountsHeirachy\n where \n CASE @smartLocationType\n WHEN 'store' THEN account_location\n WHEN 'area' THEN xxx_location_area \n WHEN 'division' THEN xxx_location_division \n WHEN 'company' THEN xxx_location_company \n END = @smartLocation\n</code></pre>\n"
},
{
"answer_id": 9031189,
"author": "shah134pk",
"author_id": 1173161,
"author_profile": "https://Stackoverflow.com/users/1173161",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>WHERE (\n @smartLocationType IS NULL \n OR account_location = (\n CASE\n WHEN @smartLocationType IS NOT NULL \n THEN @smartLocationType\n ELSE account_location \n END\n )\n)\n</code></pre>\n"
},
{
"answer_id": 28297668,
"author": "Mike Clark",
"author_id": 4261022,
"author_profile": "https://Stackoverflow.com/users/4261022",
"pm_score": -1,
"selected": false,
"text": "<p>Try this query. Its very easy to understand:</p>\n\n<pre><code>CREATE TABLE PersonsDetail(FirstName nvarchar(20), LastName nvarchar(20), GenderID int);\nGO\n\nINSERT INTO PersonsDetail VALUES(N'Gourav', N'Bhatia', 2),\n (N'Ramesh', N'Kumar', 1),\n (N'Ram', N'Lal', 2),\n (N'Sunil', N'Kumar', 3),\n (N'Sunny', N'Sehgal', 1),\n (N'Malkeet', N'Shaoul', 3),\n (N'Jassy', N'Sohal', 2);\nGO\n\nSELECT FirstName, LastName, Gender =\n CASE GenderID\n WHEN 1 THEN 'Male'\n WHEN 2 THEN 'Female'\n ELSE 'Unknown'\n END\nFROM PersonsDetail\n</code></pre>\n"
},
{
"answer_id": 30701950,
"author": "kavitha Reddy",
"author_id": 3073215,
"author_profile": "https://Stackoverflow.com/users/3073215",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Case Statement in SQL Server Example\n\nSyntax\n\nCASE [ expression ]\n\n WHEN condition_1 THEN result_1\n WHEN condition_2 THEN result_2\n ...\n WHEN condition_n THEN result_n\n\n ELSE result\n\nEND\n\nExample\n\nSELECT contact_id,\nCASE website_id\n WHEN 1 THEN 'TechOnTheNet.com'\n WHEN 2 THEN 'CheckYourMath.com'\n ELSE 'BigActivities.com'\nEND\nFROM contacts;\n\nOR\n\nSELECT contact_id,\nCASE\n WHEN website_id = 1 THEN 'TechOnTheNet.com'\n WHEN website_id = 2 THEN 'CheckYourMath.com'\n ELSE 'BigActivities.com'\nEND\nFROM contacts;\n</code></pre>\n"
},
{
"answer_id": 32334349,
"author": "Mohammad Atiour Islam",
"author_id": 1077346,
"author_profile": "https://Stackoverflow.com/users/1077346",
"pm_score": 3,
"selected": false,
"text": "<p>OR operator can be alternative of case when in where condition</p>\n\n<pre><code>ALTER PROCEDURE [dbo].[RPT_340bClinicDrugInventorySummary]\n -- Add the parameters for the stored procedure here\n @ClinicId BIGINT = 0,\n @selecttype int,\n @selectedValue varchar (50)\nAS\nBEGIN\n-- SET NOCOUNT ON added to prevent extra result sets from\n-- interfering with SELECT statements.\nSET NOCOUNT ON;\nSELECT\n drugstock_drugname.n_cur_bal,drugname.cdrugname,clinic.cclinicname\n\nFROM drugstock_drugname\nINNER JOIN drugname ON drugstock_drugname.drugnameid_FK = drugname.drugnameid_PK\nINNER JOIN drugstock_drugndc ON drugname.drugnameid_PK = drugstock_drugndc.drugnameid_FK\nINNER JOIN drugndc ON drugstock_drugndc.drugndcid_FK = drugndc.drugid_PK\nLEFT JOIN clinic ON drugstock_drugname.clinicid_FK = clinic.clinicid_PK\n\nWHERE (@ClinicId = 0 AND 1 = 1)\n OR (@ClinicId != 0 AND drugstock_drugname.clinicid_FK = @ClinicId)\n\n -- Alternative Case When You can use OR\n AND ((@selecttype = 1 AND 1 = 1)\n OR (@selecttype = 2 AND drugname.drugnameid_PK = @selectedValue)\n OR (@selecttype = 3 AND drugndc.drugid_PK = @selectedValue)\n OR (@selecttype = 4 AND drugname.cdrugclass = 'C2')\n OR (@selecttype = 5 AND LEFT(drugname.cdrugclass, 1) = 'C'))\n\nORDER BY clinic.cclinicname, drugname.cdrugname\nEND\n</code></pre>\n"
},
{
"answer_id": 62828645,
"author": "Darshan Balar",
"author_id": 13903887,
"author_profile": "https://Stackoverflow.com/users/13903887",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CREATE PROCEDURE [dbo].[Temp_Proc_Select_City]\n @StateId INT\nAS \n BEGIN \n SELECT * FROM tbl_City \n WHERE \n @StateID = CASE WHEN ISNULL(@StateId,0) = 0 THEN 0 ELSE StateId END ORDER BY CityName\n END\n</code></pre>\n"
},
{
"answer_id": 64345237,
"author": "Omid Karami",
"author_id": 4519223,
"author_profile": "https://Stackoverflow.com/users/4519223",
"pm_score": 0,
"selected": false,
"text": "<p>Try this query, it's very easy and useful: Its ready to execute!</p>\n<pre><code>USE tempdb\nGO\n\nIF NOT OBJECT_ID('Tempdb..Contacts') IS NULL\n DROP TABLE Contacts\n\nCREATE TABLE Contacts(ID INT, FirstName VARCHAR(100), LastName VARCHAR(100))\nINSERT INTO Contacts (ID, FirstName, LastName)\nSELECT 1, 'Omid', 'Karami'\nUNION ALL\nSELECT 2, 'Alen', 'Fars'\nUNION ALL\nSELECT 3, 'Sharon', 'b'\nUNION ALL\nSELECT 4, 'Poja', 'Kar'\nUNION ALL\nSELECT 5, 'Ryan', 'Lasr'\nGO\n \nDECLARE @FirstName VARCHAR(100)\nSET @FirstName = 'Omid'\n \nDECLARE @LastName VARCHAR(100)\nSET @LastName = '' \n \nSELECT FirstName, LastName\nFROM Contacts\nWHERE \n FirstName = CASE\n WHEN LEN(@FirstName) > 0 THEN @FirstName \n ELSE FirstName \n END\nAND\n LastName = CASE\n WHEN LEN(@LastName) > 0 THEN @LastName \n ELSE LastName\n END\nGO\n</code></pre>\n"
},
{
"answer_id": 66486829,
"author": "Mark Longmire",
"author_id": 933260,
"author_profile": "https://Stackoverflow.com/users/933260",
"pm_score": -1,
"selected": false,
"text": "<p>This worked for me.</p>\n<code>\nCREATE TABLE PER_CAL ( CAL_YEAR INT, CAL_PER INT )\nINSERT INTO PER_CAL( CAL_YEAR, CAL_PER ) VALUES ( 20,1 ), ( 20,2 ), ( 20,3 ), ( 20,4 ), ( 20,5 ), ( 20,6 ), ( 20,7 ), ( 20,8 ), ( 20,9 ), ( 20,10 ), ( 20,11 ), ( 20,12 ), \n( 99,1 ), ( 99,2 ), ( 99,3 ), ( 99,4 ), ( 99,5 ), ( 99,6 ), ( 99,7 ), ( 99,8 ), ( 99,9 ), ( 99,10 ), ( 99,11 ), ( 99,12 )\n</code>\n<p>The 4 digit century is determined by the rule, if the year is 50 or more, the century is 1900, otherwise 2000.</p>\n<p>Given two 6 digit periods that mark the start and end period, like a quarter, return the rows that fall in that range.</p>\n<code>\n-- 1st quarter of 2020\nSELECT * FROM PER_CAL WHERE (( CASE WHEN CAL_YEAR > 50 THEN 1900 ELSE 2000 END + CAL_YEAR ) * 100 + CAL_PER ) BETWEEN 202001 AND 202003\n-- 4th quarter of 1999\nSELECT * FROM PER_CAL WHERE (( CASE WHEN CAL_YEAR > 50 THEN 1900 ELSE 2000 END + CAL_YEAR ) * 100 + CAL_PER ) BETWEEN 199910 AND 199912\n</code>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
I tried searching around, but I couldn't find anything that would help me out.
I'm trying to do this in SQL:
```
declare @locationType varchar(50);
declare @locationID int;
SELECT column1, column2
FROM viewWhatever
WHERE
CASE @locationType
WHEN 'location' THEN account_location = @locationID
WHEN 'area' THEN xxx_location_area = @locationID
WHEN 'division' THEN xxx_location_division = @locationID
```
I know that I shouldn't have to put '= @locationID' at the end of each one, but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line...
How can I do this?
|
```
declare @locationType varchar(50);
declare @locationID int;
SELECT column1, column2
FROM viewWhatever
WHERE
@locationID =
CASE @locationType
WHEN 'location' THEN account_location
WHEN 'area' THEN xxx_location_area
WHEN 'division' THEN xxx_location_division
END
```
|
206,495 |
<p>I have a listbox containing and image and a button. By default the button is hidden. I want to make the button visible whenever I hover over an item in the listbox.
The XAML I am using is below. Thanks</p>
<pre><code><Window.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1" Margin="6">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=FullPath}" Height="150" Width="150"/>
<Button x:Name="sideButton" Width="20" Visibility="Hidden"/>
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
</code></pre>
|
[
{
"answer_id": 206537,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "<p>Ok, try this in your button declaration:</p>\n\n<pre><code><Button x:Name=\"sideButton\" Width=\"20\">\n <Button.Style>\n <Style TargetType=\"{x:Type Button}\">\n <Setter Property=\"Visibility\" Value=\"Hidden\" />\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsMouseOver}\" Value=\"True\">\n <Setter Property=\"Visibility\" Value=\"Visible\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </Button.Style>\n</Button>\n</code></pre>\n\n<p>So I'm using a style with a trigger to look back up the visual tree until I find a <code>ListBoxItem</code>, and when its <code>IsMouseOver</code> property flips over to <code>True</code> I set the <code>button</code>'s visibility to <code>Visible</code>.</p>\n\n<p>See if it's close to what you want.</p>\n"
},
{
"answer_id": 207670,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 4,
"selected": false,
"text": "<p>This <code>Style</code> does what you need. On mouse over, the button becomes only visible when the pointer is over the <code>ListBoxItem</code>. The special trick is to bind to the <code>TemplatedParent</code> for reaching <code>IsMouseOver</code> and use <code>TargetName</code> on the <code>Setter</code> to only affect the <code>Button</code>.</p>\n\n<pre><code><Style TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"ContentTemplate\">\n <Setter.Value>\n <DataTemplate>\n <Border BorderBrush=\"Black\"\n BorderThickness=\"1\"\n Margin=\"6\">\n <StackPanel Orientation=\"Horizontal\">\n <Image Source=\"{Binding Path=FullPath}\"\n Height=\"150\"\n Width=\"150\" />\n <Button x:Name=\"sideButton\"\n Width=\"20\"\n Visibility=\"Hidden\" />\n </StackPanel>\n </Border>\n <DataTemplate.Triggers>\n <DataTrigger Binding=\"{Binding IsMouseOver,RelativeSource={RelativeSource TemplatedParent}}\"\n Value=\"True\">\n <Setter Property=\"Visibility\"\n TargetName=\"sideButton\"\n Value=\"Visible\" />\n </DataTrigger>\n </DataTemplate.Triggers>\n </DataTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 207860,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 3,
"selected": false,
"text": "<p>@David is showing the right way, \nBut I have one suggestion to your XAML architecture. If you don't have any DataBinding on the Button it is better to put that in to the ListBoxItem style than the DataTemplate as bellow.</p>\n\n<pre><code> <Style TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"ContentTemplate\">\n <Setter.Value>\n <DataTemplate>\n <Border BorderBrush=\"Black\"\n BorderThickness=\"1\"\n Margin=\"6\">\n <StackPanel Orientation=\"Horizontal\">\n <Image Source=\"{Binding Path=FullPath}\"\n Height=\"150\"\n Width=\"150\" /> \n </StackPanel>\n </Border>\n </DataTemplate>\n </Setter.Value>\n </Setter> \n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ListBoxItem}\">\n <Grid Background=\"Transparent\">\n <Button x:Name=\"sideButton\" Width=\"20\" HorizontalAlignment=\"Right\" Visibility=\"Hidden\" />\n <ContentPresenter/> \n </Grid>\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsMouseOver\" Value=\"True\">\n <Setter Property=\"Visibility\"\n TargetName=\"sideButton\"\n Value=\"Visible\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter> \n </Style>\n</code></pre>\n"
},
{
"answer_id": 1943235,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>One solution to find what item was clicked is to add the following Event setter</p>\n\n<p>XAML\n\n </p>\n\n<p>C#\nvoid ListBoxItem_MouseEnter(object sender, MouseEventArgs e)\n {\n _memberVar = (sender as ListBoxItem).Content;\n }</p>\n"
},
{
"answer_id": 2242456,
"author": "donovan",
"author_id": 533213,
"author_profile": "https://Stackoverflow.com/users/533213",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Just wondering, if we use the technique above, how do we determine what item the button was clicked on?</p>\n</blockquote>\n\n<p>To answer Brian's question, in the button click handler you can walk up the visual tree to find the item that contains the button:</p>\n\n<pre><code> DependencyObject dep = (DependencyObject)e.OriginalSource;\n while ((dep != null) && !(dep is ListBoxItem))\n {\n dep = VisualTreeHelper.GetParent(dep);\n }\n\n if (dep != null)\n {\n // TODO: do stuff with the item here.\n }\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a listbox containing and image and a button. By default the button is hidden. I want to make the button visible whenever I hover over an item in the listbox.
The XAML I am using is below. Thanks
```
<Window.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1" Margin="6">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=FullPath}" Height="150" Width="150"/>
<Button x:Name="sideButton" Width="20" Visibility="Hidden"/>
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
```
|
Ok, try this in your button declaration:
```
<Button x:Name="sideButton" Width="20">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsMouseOver}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
```
So I'm using a style with a trigger to look back up the visual tree until I find a `ListBoxItem`, and when its `IsMouseOver` property flips over to `True` I set the `button`'s visibility to `Visible`.
See if it's close to what you want.
|
206,512 |
<p>At work, we have a testing tool that is used to send queries to a data source. The tool takes in input as XML files. The XML files were simple and easy to parse as long as the data structures we tried to represent were one layer deep. But now these data structures are more complex and representing them in XML is getting to be highly confusing. Any thoughts on what I can use to represent the data structures instead of XML?</p>
<p>Example:</p>
<p>Before:
</p>
<pre class="lang-cpp prettyprint-override"><code>class Foo {
int userId;
string name;
string address;
string eMail;
}
</code></pre>
<p>Now:</p>
<pre class="lang-cpp prettyprint-override"><code>class Foo {
int userId,
string name,
vector<Location> loc,
map<string, string> attributes;
}
class Location {
Address addr; //class Address
vector<LocatedTime> lcTime; //class LocatedTime
Position ps; //class Position
}
</code></pre>
<p>... and so on to have any number of nested structures.</p>
<p>I was leaning towards JSON but am open to any representation formats.</p>
|
[
{
"answer_id": 206524,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.yaml.org\" rel=\"nofollow noreferrer\">YAML</a> may be what you're looking for.</p>\n"
},
{
"answer_id": 206538,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at <a href=\"http://code.google.com/p/protobuf/\" rel=\"nofollow noreferrer\">Protocol Buffers</a>? Binary serialization which is pretty efficient in processing time and storage space. Currently \"properly\" supported in C++, Java and Python, with more implementations coming (from third parties - such as myself; I'm implementing a C# port).</p>\n"
},
{
"answer_id": 208267,
"author": "Randy Hudson",
"author_id": 19406,
"author_profile": "https://Stackoverflow.com/users/19406",
"pm_score": 1,
"selected": false,
"text": "<p>You might consider using Lua (or another scripting language). You get a nice data structure syntax (roughly on par with JSON), with the full power of a programming language. Thus you have variables (you can build up your data structures piece by piece, symbolically declare recurring values, etc.), loops (test data is often repetitive), functions (think of them as macros for boilerplate constructs in your data).</p>\n\n<p>Lua is a particularly attractive candidate for this sort of use because it's small (adds 100-200K to your program) and has a pretty elegant interface to and from C code.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28385/"
] |
At work, we have a testing tool that is used to send queries to a data source. The tool takes in input as XML files. The XML files were simple and easy to parse as long as the data structures we tried to represent were one layer deep. But now these data structures are more complex and representing them in XML is getting to be highly confusing. Any thoughts on what I can use to represent the data structures instead of XML?
Example:
Before:
```cpp
class Foo {
int userId;
string name;
string address;
string eMail;
}
```
Now:
```cpp
class Foo {
int userId,
string name,
vector<Location> loc,
map<string, string> attributes;
}
class Location {
Address addr; //class Address
vector<LocatedTime> lcTime; //class LocatedTime
Position ps; //class Position
}
```
... and so on to have any number of nested structures.
I was leaning towards JSON but am open to any representation formats.
|
[YAML](http://www.yaml.org) may be what you're looking for.
|
206,528 |
<p>I have this function in my Javascript Code that updates html fields with their new values whenever it is called. The problem cannot be with the function itself because it works brilliantly in every section except for one. Here is the JS function:</p>
<pre><code> function updateFields() {
document.getElementById('bf').innerHTML = bill.time[breakfast][bill.pointPartOfWeek];
document.getElementById('ln').innerHTML = bill.time[lunch][bill.pointPartOfWeek];
document.getElementById('dn').innerHTML = bill.time[dinner][bill.pointPartOfWeek];
document.getElementById('se').innerHTML = bill.time[special][bill.pointPartOfWeek];
document.getElementById('fdr').innerHTML = bill.time[full][bill.pointPartOfWeek];
document.getElementById('cost').innerHTML = bill.cost;
}
</code></pre>
<p>And it executes fine in the following instance:</p>
<pre><code> <select onchange='if(this.selectedIndex == 0) {bill.unholiday();updateFields()} else { bill.holiday();updateFields()}' id='date' name='date'>
<option value='else'>Jan. 02 - Nov. 20</option>
<option value='christmas'>Nov. 20 - Jan. 01</option>
</select>
</code></pre>
<p>but in this very similar code, the last line of the function doesn't seem to execute (it doesn't update the cost field, but updates everything else)</p>
<pre><code> <select onchange='if(this.selectedIndex == 0) {bill.pointPartOfWeek = 1;} else { bill.pointPartOfWeek = 2;}updateFields();alert(updateFields());' id='day' name='day'>
<option value='0'>Monday thru Thursday</option>
<option value='1'>Friday, Saturday, or Sunday</option>
</select>
<br />
</code></pre>
<p>Strangely enough, the total cost variable itself is updated, but the field that represents the variable is not. If you use another section of the page that wouldn't change the value of the total cost but calls the updateFields function again, the cost field then updates correctly. It must be an issue with the function called. </p>
<p>Note: we know that the function executes because it does 5 out of 6 of the things it is supposed to do. This is a strange issue. </p>
<p>Edit: The pastebin for the entire page my be helpful. Here it is:</p>
<p><a href="http://pastebin.com/f70d584d3" rel="nofollow noreferrer">http://pastebin.com/f70d584d3</a></p>
|
[
{
"answer_id": 206569,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 3,
"selected": true,
"text": "<p>I'm curious, is it possible that there are actually 2 elements with an id of \"cost\"? That could, by updating the first one it finds, cause this issue. Different browsers may have different ways of implementing document.getElementById() so you might get even more inconsistent results with different browsers if this is the case.</p>\n\n<p>UPDATE: It turns out that you need to call bill.holiday() or bill.unholiday() before calling updateFields() in your second select.</p>\n"
},
{
"answer_id": 206653,
"author": "DocileWalnut",
"author_id": 28302,
"author_profile": "https://Stackoverflow.com/users/28302",
"pm_score": 1,
"selected": false,
"text": "<p>My experience with getElementById has been mixed at best, and that's most likely your issue. Probably some sort of browser DOM bug where you've got two items with the same ID, or something like that.</p>\n\n<p>I use <a href=\"http://www.prototypejs.org\" rel=\"nofollow noreferrer\">Prototype</a> which lets you avoid ambiguities and finicky browsers with a simple call: </p>\n\n<pre><code>document.getElementById('bf')\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>$('bf')\n</code></pre>\n\n<p>And similarly you can update the innerHTML of an element easily:</p>\n\n<pre><code>$('bf').update(bill.time[breakfast][bill.pointPartOfWeek]);\n</code></pre>\n\n<p>Check it out. It's saved my bacon more than a couple times.</p>\n"
},
{
"answer_id": 206808,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that the cost property on the billiard object has not been updated when you call updateFields(). You need to call bill.calculate() which updates the cost property.</p>\n"
},
{
"answer_id": 206895,
"author": "objectivesea",
"author_id": 27763,
"author_profile": "https://Stackoverflow.com/users/27763",
"pm_score": 0,
"selected": false,
"text": "<p>I understand now why Eric's solution worked... which lead me to a better solution.</p>\n\n<p>His post was deleted for some reason, but I commented on his other post paraphrasing his answer. </p>\n\n<p>Anyways,\nHe said to call holiday() or unholiday(). When you look at those functions you'll see on the last line of code:</p>\n\n<pre><code>this.setRoom(this.pointPartOfDay,this.pointPartOfWeek);\n</code></pre>\n\n<p>Then everything starts to make sense. Before, I just set pointPartOfWeek to its new value and moved on. but pointPartOfDay is just an array address. I never actually updated the room cost. This also explains why cost eventually corrects itself. As long as pointPartOfWeek doesn't change, calls to setRoom will still fix the amount (even in another event). </p>\n\n<p>The fun of debugging...</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27763/"
] |
I have this function in my Javascript Code that updates html fields with their new values whenever it is called. The problem cannot be with the function itself because it works brilliantly in every section except for one. Here is the JS function:
```
function updateFields() {
document.getElementById('bf').innerHTML = bill.time[breakfast][bill.pointPartOfWeek];
document.getElementById('ln').innerHTML = bill.time[lunch][bill.pointPartOfWeek];
document.getElementById('dn').innerHTML = bill.time[dinner][bill.pointPartOfWeek];
document.getElementById('se').innerHTML = bill.time[special][bill.pointPartOfWeek];
document.getElementById('fdr').innerHTML = bill.time[full][bill.pointPartOfWeek];
document.getElementById('cost').innerHTML = bill.cost;
}
```
And it executes fine in the following instance:
```
<select onchange='if(this.selectedIndex == 0) {bill.unholiday();updateFields()} else { bill.holiday();updateFields()}' id='date' name='date'>
<option value='else'>Jan. 02 - Nov. 20</option>
<option value='christmas'>Nov. 20 - Jan. 01</option>
</select>
```
but in this very similar code, the last line of the function doesn't seem to execute (it doesn't update the cost field, but updates everything else)
```
<select onchange='if(this.selectedIndex == 0) {bill.pointPartOfWeek = 1;} else { bill.pointPartOfWeek = 2;}updateFields();alert(updateFields());' id='day' name='day'>
<option value='0'>Monday thru Thursday</option>
<option value='1'>Friday, Saturday, or Sunday</option>
</select>
<br />
```
Strangely enough, the total cost variable itself is updated, but the field that represents the variable is not. If you use another section of the page that wouldn't change the value of the total cost but calls the updateFields function again, the cost field then updates correctly. It must be an issue with the function called.
Note: we know that the function executes because it does 5 out of 6 of the things it is supposed to do. This is a strange issue.
Edit: The pastebin for the entire page my be helpful. Here it is:
<http://pastebin.com/f70d584d3>
|
I'm curious, is it possible that there are actually 2 elements with an id of "cost"? That could, by updating the first one it finds, cause this issue. Different browsers may have different ways of implementing document.getElementById() so you might get even more inconsistent results with different browsers if this is the case.
UPDATE: It turns out that you need to call bill.holiday() or bill.unholiday() before calling updateFields() in your second select.
|
206,532 |
<p>Is there any reason something like this would not work?</p>
<p>This is the logic I have used many times to update a record in a table with LINQ:</p>
<pre><code> DataClasses1DataContext db = new DataClasses1DataContext();
User updateUser = db.Users.Single(e => e.user == user);
updateUser.InUse = !updateUser.InUse;
db.Log = new System.IO.StreamWriter(@"c:\temp\linq.log") { AutoFlush = true };
db.SubmitChanges();
</code></pre>
<p>(updateUser.InUse is a bit field) </p>
<p>For some reason it isn't working. When I check the linq.log it is completely blank.</p>
<p>Could there be a problem with my .dbml? Other tables seem to work fine but I've compared properties in the .dbml and they all match.</p>
<p>It's as if the <code>db.SubmitChanges()</code>; does not detect any updates being required.</p>
|
[
{
"answer_id": 206561,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Is the InUse property a \"normal\" one as far as LINQ is concerned? (e.g. it's not autogenerated or anything funky like that?)</p>\n\n<p>Alternatively, I don't suppose it's a Nullable<bool> is it, with a current value of null? If so, your update line isn't actually doing anything - for nullable Booleans, !null = null.</p>\n"
},
{
"answer_id": 208480,
"author": "ctrlShiftBryan",
"author_id": 6161,
"author_profile": "https://Stackoverflow.com/users/6161",
"pm_score": 7,
"selected": true,
"text": "<p>The table could not be updated properly because it had no primary key. (Actually it had the column but the constraint was not copied when I did a SELECT INTO my dev table). <strong>The DataContext class requires a primary key for updates.</strong> </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
] |
Is there any reason something like this would not work?
This is the logic I have used many times to update a record in a table with LINQ:
```
DataClasses1DataContext db = new DataClasses1DataContext();
User updateUser = db.Users.Single(e => e.user == user);
updateUser.InUse = !updateUser.InUse;
db.Log = new System.IO.StreamWriter(@"c:\temp\linq.log") { AutoFlush = true };
db.SubmitChanges();
```
(updateUser.InUse is a bit field)
For some reason it isn't working. When I check the linq.log it is completely blank.
Could there be a problem with my .dbml? Other tables seem to work fine but I've compared properties in the .dbml and they all match.
It's as if the `db.SubmitChanges()`; does not detect any updates being required.
|
The table could not be updated properly because it had no primary key. (Actually it had the column but the constraint was not copied when I did a SELECT INTO my dev table). **The DataContext class requires a primary key for updates.**
|
206,558 |
<p>I continually get these errors when I try to update tables based on another table. I end up rewriting the query, change the order of joins, change some groupings and then it eventually works, but I just don't quite get it.</p>
<p>What is a 'multi-part identifier'?<br>
When is a 'multi-part identifier' not able to be bound?<br>
What is it being bound to anyway?<br>
In what cases will this error occur?<br>
What are the best ways to prevent it? </p>
<p>The specific error from SQL Server 2005 is:</p>
<blockquote>
<p>The multi-part identifier "..." could not be bound.</p>
</blockquote>
<p>Here is an example:</p>
<pre><code>UPDATE [test].[dbo].[CompanyDetail]
SET Mnemonic = [dbBWKMigration].[dbo].[Company].[MNEMONIC],
[Company Code] = [dbBWKMigration].[dbo].[Company].[COMPANYCODE]
WHERE [Company Name] = **[dbBWKMigration].[dbo].[Company].[COMPANYNAME]**
</code></pre>
<p>The actual error:</p>
<blockquote>
<p>Msg 4104, Level 16, State 1, Line 3 The multi-part identifier
"dbBWKMigration.dbo.Company.COMPANYNAME" could not be bound.</p>
</blockquote>
|
[
{
"answer_id": 206581,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 3,
"selected": false,
"text": "<p>Binding = your textual representation of a specific column gets mapped to a physical column in some table, in some database, on some server.</p>\n\n<p>Multipart identifier could be: MyDatabase.dbo.MyTable. If you get any of these identifiers wrong, then you have a multipart identifier that cannot be mapped.</p>\n\n<p>The best way to avoid it is to write the query right the first time, or use a plugin for management studio that provides intellisense and thus help you out by avoiding typos.</p>\n"
},
{
"answer_id": 206645,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 8,
"selected": true,
"text": "<p>A multipart identifier is any description of a field or table that contains multiple parts - for instance MyTable.SomeRow - if it can't be bound that means there's something wrong with it - either you've got a simple typo, or a confusion between table and column. It can also be caused by using reserved words in your table or field names and not surrounding them with [].\nIt can also be caused by not including all of the required columns in the target table.</p>\n\n<p>Something like <a href=\"http://www.red-gate.com/products/SQL_Prompt/index.htm\" rel=\"noreferrer\">redgate sql prompt</a> is brilliant for avoiding having to manually type these (it even auto-completes joins based on foreign keys), but isn't free. SQL server 2008 supports intellisense out of the box, although it isn't quite as complete as the redgate version.</p>\n"
},
{
"answer_id": 206655,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 3,
"selected": false,
"text": "<p>You probably have a typo. For instance, if you have a table named Customer in a database named Sales, you could refer to it as Sales..Customer (although it is better to refer to it including the owner name (dbo is the default owner) like Sales.dbo.Customer.</p>\n\n<p>If you typed Sales...Customer, you might have gotten the message you got.</p>\n"
},
{
"answer_id": 206667,
"author": "Lieutenant Frost",
"author_id": 2018855,
"author_profile": "https://Stackoverflow.com/users/2018855",
"pm_score": 4,
"selected": false,
"text": "<p>It's probably a typo. Look for the places in your code where you call [schema].[TableName] (basically anywhere you reference a field) and make sure everything is spelled correctly.</p>\n\n<p>Personally, I try to avoid this by using aliases for all my tables. It helps tremendously when you can shorten a long table name to an acronym of it's description (i.e. WorkOrderParts -> WOP), and also makes your query more readable.</p>\n\n<p>Edit: As an added bonus, you'll save TONS of keystrokes when all you have to type is a three or four-letter alias vs. the schema, table, and field names all together.</p>\n"
},
{
"answer_id": 206694,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "<p>If you are sure that it is not a typo spelling-wise, perhaps it is a typo case-wise.</p>\n\n<p>What collation are you using? Check it.</p>\n"
},
{
"answer_id": 6143015,
"author": "jo-mso",
"author_id": 771804,
"author_profile": "https://Stackoverflow.com/users/771804",
"pm_score": 3,
"selected": false,
"text": "<p>I found that I get these a lot when I try to abbreviate, such as:</p>\n\n<pre><code>Table1 t1, Table2 t2 \nwhere t1.ID = t2.ID\n</code></pre>\n\n<p>Changing it to: </p>\n\n<pre><code>Table1, Table2 \nwhere Table1.ID = Table2.ID\n</code></pre>\n\n<p>Makes the query work and not throw the error.</p>\n"
},
{
"answer_id": 6414061,
"author": "amadelle",
"author_id": 806967,
"author_profile": "https://Stackoverflow.com/users/806967",
"pm_score": 6,
"selected": false,
"text": "<p>Actually sometimes when you are updating one table from another table's data, I think one of the common issues that cause this error, is when you use your table abbreviations incorrectly <em>or when they are not needed</em>. The correct statement is below:</p>\n\n<pre><code>Update Table1\nSet SomeField = t2.SomeFieldValue \nFrom Table1 t1 \nInner Join Table2 as t2\n On t1.ID = t2.ID\n</code></pre>\n\n<p>Notice that <strong><code>SomeField</code></strong> column from <strong>Table1</strong> doesn't have the <code>t1</code> qualifier as <strong><code>t1.SomeField</code></strong> but is just <code>SomeField</code>. </p>\n\n<p>If one tries to update it by specifying <strong><code>t1.SomeField</code></strong> the statement will return the multi-part error that you have noticed.</p>\n"
},
{
"answer_id": 8521731,
"author": "Matthew Setter",
"author_id": 222011,
"author_profile": "https://Stackoverflow.com/users/222011",
"pm_score": 2,
"selected": false,
"text": "<p>I had this issue and it turned out to be an incorrect table alias. Correcting this resolved the issue.</p>\n"
},
{
"answer_id": 11111430,
"author": "Upio",
"author_id": 1467869,
"author_profile": "https://Stackoverflow.com/users/1467869",
"pm_score": 2,
"selected": false,
"text": "<p>When updating tables make sure you do not reference the field your updating via the alias.</p>\n\n<p>I just had the error with the following code</p>\n\n<pre><code>update [page] \nset p.pagestatusid = 1\nfrom [page] p\njoin seed s on s.seedid = p.seedid\nwhere s.providercode = 'agd'\nand p.pagestatusid = 0\n</code></pre>\n\n<p>I had to remove the alias reference in the set statement so it reads like this</p>\n\n<pre><code>update [page] \nset pagestatusid = 1\nfrom [page] p\njoin seed s on s.seedid = p.seedid\nwhere s.providercode = 'agd'\nand p.pagestatusid = 0\n</code></pre>\n"
},
{
"answer_id": 14902629,
"author": "unnknown",
"author_id": 614263,
"author_profile": "https://Stackoverflow.com/users/614263",
"pm_score": 2,
"selected": false,
"text": "<p>Mine was putting the schema on the table Alias by mistake:</p>\n\n<pre><code>SELECT * FROM schema.CustomerOrders co\nWHERE schema.co.ID = 1 -- oops!\n</code></pre>\n"
},
{
"answer_id": 44765141,
"author": "Andrew Day",
"author_id": 3200163,
"author_profile": "https://Stackoverflow.com/users/3200163",
"pm_score": 1,
"selected": false,
"text": "<p>I had <code>P.PayeeName AS 'Payer' --,</code>\nand the two comment lines threw this error</p>\n"
},
{
"answer_id": 46045037,
"author": "MT_Shikomba",
"author_id": 7652487,
"author_profile": "https://Stackoverflow.com/users/7652487",
"pm_score": 1,
"selected": false,
"text": "<p>I actually forgot to join the table to the others that's why i got the error</p>\n\n<p>Supposed to be this way:</p>\n\n<pre><code> CREATE VIEW reserved_passangers AS\n SELECT dbo.Passenger.PassName, dbo.Passenger.Address1, dbo.Passenger.Phone\n FROM dbo.Passenger, dbo.Reservation, dbo.Flight\n WHERE (dbo.Passenger.PassNum = dbo.Reservation.PassNum) and\n (dbo.Reservation.Flightdate = 'January 15 2004' and Flight.FlightNum =562)\n</code></pre>\n\n<p>And not this way:</p>\n\n<pre><code> CREATE VIEW reserved_passangers AS\n SELECT dbo.Passenger.PassName, dbo.Passenger.Address1, dbo.Passenger.Phone\n FROM dbo.Passenger, dbo.Reservation\n WHERE (dbo.Passenger.PassNum = dbo.Reservation.PassNum) and\n (dbo.Reservation.Flightdate = 'January 15 2004' and Flight.FlightNum = 562)\n</code></pre>\n"
},
{
"answer_id": 48294922,
"author": "Onkar Vidhate",
"author_id": 8765669,
"author_profile": "https://Stackoverflow.com/users/8765669",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Error Code</strong></p>\n\n<pre><code>FROM \n dbo.Category C LEFT OUTER JOIN \n dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN \n dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN \n dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN \n dbo.trainer ON dbo.trainer.TopicID =dbo.SubModule.subModuleID \n</code></pre>\n\n<p><strong>Solution Code</strong></p>\n\n<pre><code> FROM \n dbo.Category C LEFT OUTER JOIN \n dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN \n dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN \n dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN \n dbo.trainer ON dbo.trainer.TopicID = SM.subModuleID \n</code></pre>\n\n<p>as you can see, in error code, <code>dbo.SubModule</code> is already defined as SM, but I am using <code>dbo.SubModule</code> in next line, hence there was an error.\nuse declared name instead of actual name. Problem solved.</p>\n"
},
{
"answer_id": 49201018,
"author": "ramnz",
"author_id": 391817,
"author_profile": "https://Stackoverflow.com/users/391817",
"pm_score": 1,
"selected": false,
"text": "<p>My best advise when having the error is to use [] braquets to sorround table names, the abbreviation of tables causes sometimes errors, (sometime table abbreviations just work fine...weird)</p>\n"
},
{
"answer_id": 53438852,
"author": "Malhaar Punjabi",
"author_id": 6918303,
"author_profile": "https://Stackoverflow.com/users/6918303",
"pm_score": 2,
"selected": false,
"text": "<p>Adding table alias in front Set field causes this problem in my case.</p>\n<p><strong>Right</strong></p>\n<pre><code>Update Table1\nSet SomeField = t2.SomeFieldValue \nFrom Table1 t1 \nInner Join Table2 as t2\n On t1.ID = t2.ID\n</code></pre>\n<p><strong>Wrong</strong></p>\n<pre><code>Update Table1\nSet t1.SomeField = t2.SomeFieldValue \nFrom Table1 t1 \nInner Join Table2 as t2\n On t1.ID = t2.ID\n</code></pre>\n"
},
{
"answer_id": 54537079,
"author": "clamum",
"author_id": 1396613,
"author_profile": "https://Stackoverflow.com/users/1396613",
"pm_score": 1,
"selected": false,
"text": "<p>I was getting this error and just could not see where the problem was. I double checked all of my aliases and syntax and nothing looked out of place. The query was similar to ones I write all the time.</p>\n\n<p>I decided to just re-write the query (I originally had copied it from a report .rdl file) below, over again, and it ran fine. Looking at the queries now, they look the same to me, but my re-written one works.</p>\n\n<p>Just wanted to say that it might be worth a shot if nothing else works.</p>\n"
},
{
"answer_id": 55093343,
"author": "David Morrow",
"author_id": 5331336,
"author_profile": "https://Stackoverflow.com/users/5331336",
"pm_score": 1,
"selected": false,
"text": "<p>When you type the FROM table those errors will disappear.\nType FROM below what your typing then Intellisense will work and multi-part identifier will work.</p>\n"
},
{
"answer_id": 60162574,
"author": "Neloy Sarothi",
"author_id": 12461803,
"author_profile": "https://Stackoverflow.com/users/12461803",
"pm_score": 1,
"selected": false,
"text": "<p>I faced this problem and solved it but there is a difference between your and mine code. In spite of I think you can understand what is \"the multi-part identifier could not be bound\"</p>\n\n<p>When I used this code </p>\n\n<pre><code> select * from tbTest where email = [email protected]\n</code></pre>\n\n<p>I faced Multi-part identifier problem</p>\n\n<p>but when I use single quotation for email address It solved</p>\n\n<pre><code> select * from tbTest where email = '[email protected]'\n</code></pre>\n"
},
{
"answer_id": 67901187,
"author": "TheRealJenius",
"author_id": 13229797,
"author_profile": "https://Stackoverflow.com/users/13229797",
"pm_score": 0,
"selected": false,
"text": "<p>I had exactly the same issue, and similar to your coding I had missed out the <strong>FROM</strong> field, once it is added, the query knows what table to read the data from</p>\n"
},
{
"answer_id": 68292209,
"author": "abovetempo",
"author_id": 7231971,
"author_profile": "https://Stackoverflow.com/users/7231971",
"pm_score": 0,
"selected": false,
"text": "<p>Mine worked after removing square brackets in a SUBSTRING method. I changed from</p>\n<blockquote>\n<p><strong>SUBSTRING([dbo.table].[column],15,2)</strong></p>\n</blockquote>\n<p>to</p>\n<blockquote>\n<p><strong>SUBSTRING(dbo.table.column,15,2)</strong></p>\n</blockquote>\n"
},
{
"answer_id": 72702682,
"author": "John",
"author_id": 7054019,
"author_profile": "https://Stackoverflow.com/users/7054019",
"pm_score": 0,
"selected": false,
"text": "<p>CTRL+SHIFT+R (refreshing the Intellisense) took care of it for me.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73794/"
] |
I continually get these errors when I try to update tables based on another table. I end up rewriting the query, change the order of joins, change some groupings and then it eventually works, but I just don't quite get it.
What is a 'multi-part identifier'?
When is a 'multi-part identifier' not able to be bound?
What is it being bound to anyway?
In what cases will this error occur?
What are the best ways to prevent it?
The specific error from SQL Server 2005 is:
>
> The multi-part identifier "..." could not be bound.
>
>
>
Here is an example:
```
UPDATE [test].[dbo].[CompanyDetail]
SET Mnemonic = [dbBWKMigration].[dbo].[Company].[MNEMONIC],
[Company Code] = [dbBWKMigration].[dbo].[Company].[COMPANYCODE]
WHERE [Company Name] = **[dbBWKMigration].[dbo].[Company].[COMPANYNAME]**
```
The actual error:
>
> Msg 4104, Level 16, State 1, Line 3 The multi-part identifier
> "dbBWKMigration.dbo.Company.COMPANYNAME" could not be bound.
>
>
>
|
A multipart identifier is any description of a field or table that contains multiple parts - for instance MyTable.SomeRow - if it can't be bound that means there's something wrong with it - either you've got a simple typo, or a confusion between table and column. It can also be caused by using reserved words in your table or field names and not surrounding them with [].
It can also be caused by not including all of the required columns in the target table.
Something like [redgate sql prompt](http://www.red-gate.com/products/SQL_Prompt/index.htm) is brilliant for avoiding having to manually type these (it even auto-completes joins based on foreign keys), but isn't free. SQL server 2008 supports intellisense out of the box, although it isn't quite as complete as the redgate version.
|
206,564 |
<p><em>[This question is related to but not the same as <a href="https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c">this one</a>.]</em></p>
<p>My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning:</p>
<pre><code>long t = 0;
bool b = false;
b = t; // performance warning: forcing long to bool
b = (bool)t; // performance warning
b = bool(t); // performance warning
b = static_cast<bool>(t); // performance warning
b = t ? true : false; // ok, no warning
b = t != 0; // ok
b = !!t; // ok
</code></pre>
<p>This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.</p>
<p>So my question is: what is the performance implication of casting/converting to <code>bool</code>? Does explicit conversion have better performance in some circumstance (e.g., for certain target architectures or processors)? Does implicit conversion somehow confuse the optimizer?</p>
<p>Microsoft's <a href="http://msdn.microsoft.com/en-us/library/b6801kcy.aspx" rel="noreferrer">explanation</a> of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.</p>
|
[
{
"answer_id": 206570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>The performance is identical across the board. It involves a couple of instructions on x86, maybe 3 on some other architectures.</p>\n\n<p>On x86 / VC++, they all do</p>\n\n<pre><code>cmp DWORD PTR [whatever], 0\nsetne al\n</code></pre>\n\n<p>GCC generates the same thing, but without the warnings (at any warning-level).</p>\n"
},
{
"answer_id": 206575,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know, there is no warning on any other compiler for this. The only way I can think that this would cause a performance loss is that the compiler has to compare the entire integer to 0 and then assign the bool appropriately (unlike a conversion such as a char to bool, where the result can be copied over because a bool is one byte and so they are effectively the same), or an integral conversion which involves copying some or all of the source to the destination, possibly after a zero of the destination if it's bigger than the source (in terms of memory).</p>\n\n<p>It's yet another one of Microsoft's useless and unhelpful ideas as to what constitutes good code, and leads us to have to put up with stupid definitions like this:</p>\n\n<pre><code>template <typename T>\ninline bool to_bool (const T& t)\n { return t ? true : false; }\n</code></pre>\n"
},
{
"answer_id": 206578,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "<p>Based on your link to MS' explanation, it appears that if the value is <em>merely</em> 1 or 0, there is not performance hit, but if it's any <em>other</em> non-0 value that a comparison must be built at compile time?</p>\n"
},
{
"answer_id": 206579,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like premature optimization to me. Are you expecting that the performance of the cast to seriously effect the performance of your app? Maybe if you are writing kernel code or device drivers but in most cases, they all should be ok.</p>\n"
},
{
"answer_id": 206580,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think performance is the issue here. The reason you get a warning is that information is lost during conversion from int to bool.</p>\n"
},
{
"answer_id": 206597,
"author": "WolfmanDragon",
"author_id": 13491,
"author_profile": "https://Stackoverflow.com/users/13491",
"pm_score": 0,
"selected": false,
"text": "<p>In C++ a bool ISA int with only two values 0 = false, 1 = true. The compiler only has to check one bit. To be perfectly clear, true != 0, so any int can override bool, it just cost processing cycles to do so. </p>\n\n<p>By using a long as in the code sample, you are forcing a lot more bit checks, which will cause a performance hit. </p>\n\n<p>No this is not premature optimization, it is quite crazy to use code that takes more processing time across the board. This is simply good coding practice.</p>\n"
},
{
"answer_id": 206619,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you're writing code for a <b>really</b> critical inner loop (simulator core, ray-tracer, etc.) there is no point in worrying about any performance hits in this case. There are other more important things to worry about in your code (and other more significant performance traps lurking, I'm sure).</p>\n"
},
{
"answer_id": 206632,
"author": "Bill Forster",
"author_id": 3955,
"author_profile": "https://Stackoverflow.com/users/3955",
"pm_score": 3,
"selected": false,
"text": "<p>The performance warning does actually make a little bit of sense. I've had it as well and my curiousity led me to investigate with the disassembler. It is trying to tell you that the compiler has to generate some code to coerce the value to either 0 or 1. Because you are insisting on a bool, the old school C idea of 0 or anything else doesn't apply.</p>\n\n<p>You can avoid that tiny performance hit if you really want to. The best way is to avoid the cast altogether and use a bool from the start. If you must have an int, you could just use if( int ) instead of if( bool ). The code generated will simply check whether the int is 0 or not. No extra code to make sure the value is 1 if it's not 0 will be generated.</p>\n"
},
{
"answer_id": 206633,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>Microsoft's explanation seems to be that what they're trying to say is:</p>\n\n<blockquote>\n <p>Hey, if you're using an int, but are\n only storing true or false information in\n it, make it a bool!</p>\n</blockquote>\n\n<p>I'm skeptical about how much would be gained performance-wise, but MS may have found that there was some gain (for their use, anyway). Microsoft's code does tend to run an awful lot, so maybe they've found the micro-optimization to be worthwhile. I believe that a fair bit of what goes into the MS compiler is to support stuff they find useful themselves (only makes sense, right?).</p>\n\n<p>And you get rid of some dirty, little casts to boot.</p>\n"
},
{
"answer_id": 206639,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 6,
"selected": true,
"text": "<p>I was puzzled by this behaviour, until I found this link:</p>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633\" rel=\"noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633</a></p>\n\n<p>Apparently, coming from the Microsoft Developer who \"owns\" this warning:</p>\n\n<blockquote>\n <p><i> This warning is surprisingly\n helpful, and found a bug in my code\n just yesterday. I think Martin is\n taking \"performance warning\" out of\n context.</p>\n \n <p><b>It's not about the generated code,\n it's about whether or not the\n programmer has signalled an intent to\n change a value from int to bool</b>.\n There is a penalty for that, and the\n user has the choice to use \"int\"\n instead of \"bool\" consistently (or\n more likely vice versa) to avoid the\n \"boolifying\" codegen. [...]</p>\n \n <p><b>It is an old warning, and may have\n outlived its purpose, but it's\n behaving as designed here.</b> </i></p>\n</blockquote>\n\n<p>So it seems to me the warning is more about style and avoiding some mistakes than anything else.</p>\n\n<p>Hope this will answer your question...</p>\n\n<p>:-p</p>\n"
},
{
"answer_id": 1064428,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>long t;\nbool b;\nint i;\nsigned char c;\n...\n</code></pre>\n\n<p>You get a warning when you do anything that would be \"free\" if bool wasn't required to be 0 or 1. b = !!t is effectively assigning the result of the (language built-in, non-overrideable) <code>bool operator!(long)</code></p>\n\n<p>You shouldn't expect the ! or != operators to cost zero asm instructions even with an optimizing compiler. It is usually true that int i = t is usually optimized away completely. Or even signed char c = t; (on x86/amd64, if t is in the %eax register, after c = t, using c just means using %al. amd64 has byte addressing for every register, BTW. IIRC, in x86 some registers don't have byte addressing.)</p>\n\n<p>Anyway, <code>b = t; i = b<code>; isn't the same as <code>c = t; i = c;</code> it's i = !!t;</code> instead of i = t & 0xff</code>;</p>\n\n<p>Err, I guess everyone already knows all that from the previous replies. My point was, the warning made sense to me, since it caught cases where the compiler had to do things you didn't really tell it to, like !!BOOL on return because you declared the function bool, but are returning an integral value that could be true and != 1. e.g. a lot of windows stuff returns BOOL (int).</p>\n\n<p>This is one of MSVC's few warnings that G++ doesn't have. I'm a lot more used to g++, and it definitely warns about stuff MSVC doesn't, but that I'm glad it told me about. I wrote a portab.h header file with stubs for the MFC/Win32 classes/macros/functions I used. This got the MFC app I'm working on to compile on my GNU/Linux machine at home (and with cygwin). I mainly wanted to be able to compile-test what I was working on at home, but I ended up finding g++'s warnings very useful. It's also a lot stricter about e.g. templates...</p>\n\n<p>On bool in general, I'm not sure it makes for better code when used as a return values and parameter passing. Even for locals, g++ 4.3 doesn't seem to figure out that it doesn't have to coerce the value to 0 or 1 before branching on it. If it's a local variable and you never take its address, the compiler should keep it in whatever size is fastest. If it has to spill it from registers to the stack, it could just as well keep it in 4 bytes, since that may be slightly faster. (It uses a lot of movsx (sign-extension) instructions when loading/storing (non-local) bools, but I don't really remember what it did for automatic (local stack) variables. I do remember seeing it reserve an odd amount of stack space (not a multiple of 4) in functions that had some bools locals.)</p>\n\n<p>Using bool flags was slower than int with the Digital Mars D compiler as of last year:\n<a href=\"http://www.digitalmars.com/d/archives/digitalmars/D/opEquals_needs_to_return_bool_71813.html\" rel=\"nofollow noreferrer\">http://www.digitalmars.com/d/archives/digitalmars/D/opEquals_needs_to_return_bool_71813.html</a>\n(D is a lot like C++, but abandons full C backwards compat to define some nice new semantics, and good support for template metaprogramming. e.g. \"static if\" or \"static assert\" instead of template hacks or cpp macros. I'd really like to give D a try sometime. :)</p>\n\n<p>For data structures, it can make sense, e.g. if you want to pack a couple flags before an int and then some doubles in a struct you're going to have quite a lot of.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
*[This question is related to but not the same as [this one](https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c).]*
My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning:
```
long t = 0;
bool b = false;
b = t; // performance warning: forcing long to bool
b = (bool)t; // performance warning
b = bool(t); // performance warning
b = static_cast<bool>(t); // performance warning
b = t ? true : false; // ok, no warning
b = t != 0; // ok
b = !!t; // ok
```
This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.
So my question is: what is the performance implication of casting/converting to `bool`? Does explicit conversion have better performance in some circumstance (e.g., for certain target architectures or processors)? Does implicit conversion somehow confuse the optimizer?
Microsoft's [explanation](http://msdn.microsoft.com/en-us/library/b6801kcy.aspx) of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.
|
I was puzzled by this behaviour, until I found this link:
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633>
Apparently, coming from the Microsoft Developer who "owns" this warning:
>
> *This warning is surprisingly
> helpful, and found a bug in my code
> just yesterday. I think Martin is
> taking "performance warning" out of
> context.*
>
>
> **It's not about the generated code,
> it's about whether or not the
> programmer has signalled an intent to
> change a value from int to bool**.
> There is a penalty for that, and the
> user has the choice to use "int"
> instead of "bool" consistently (or
> more likely vice versa) to avoid the
> "boolifying" codegen. [...]
>
>
> **It is an old warning, and may have
> outlived its purpose, but it's
> behaving as designed here.**
>
>
>
So it seems to me the warning is more about style and avoiding some mistakes than anything else.
Hope this will answer your question...
:-p
|
206,577 |
<p>We are trying to move from using SQL DMO to SMO in our COM+ based application, as we are dropping support for SQL Server 2000 and adding support for SQL Server 2008 in addition to SQL Server 2005. </p>
<p>I have been reading around on this, and found this particular quip on <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=289491&SiteID=1" rel="nofollow noreferrer">this microsoft forum:</a></p>
<blockquote>"SMO is only supported in VB/C#.Net 2005. It requires the .Net 2.0 Framework, which isn't available in VB/VC 6."</blockquote>
<p>Is it true? Googling in general and googling stackoverflow did not throw up and definitive answers.</p>
<p>Is it possible to implement SQL SMO using VB6?</p>
<p><strong>Edit: I used a COM Wrapper to get around this... check out my answer below for some more details.</strong></p>
|
[
{
"answer_id": 206620,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": -1,
"selected": false,
"text": "<p>I haven't tried it, but you could probably write vb.net code to interact with SQL SMO, and then write a com wrapper for the vb.net code. Of course, you'll still need to .net framework to use it.</p>\n\n<p>Instead, I would suggest that you migrate away from SQL DMO and SQL SMO. Anything you do with DMO or SMO can be done without it. Of course, it won't be easy, but googling for replacement code (using straight T-SQL instead of SQL DMO) will provide you the answers you need.</p>\n"
},
{
"answer_id": 207056,
"author": "Mike L",
"author_id": 12085,
"author_profile": "https://Stackoverflow.com/users/12085",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know of a way you can get to SMO via VB6. I'd agree with G Mastros about doing a COM/Interop approach to implement .NET code directly.</p>\n\n<p>An alternative to consider is that you could shell out to Powershell, executing a script that would do your .NET SMO work. You still have the pre-requisite of requiring the .NET framework (and Powershell obviously), but it would get the job done. Your script could take parameters for credentials, database name, backup type, etc.</p>\n\n<p>I implement this a lot at clients who have SQL Express (no SQL Agent for backups, like MSDE). I hook up a scheduled task which invokes the script and manages their backups.</p>\n\n<p>If helpful, here is a script -- largely stolen but I have modified it somewhat:</p>\n\n<pre><code>param (\n [string] $ServerName,\n [string] $DatabaseName,\n [string] $Backuptype,\n [string] $BackupPath,\n [int] $NumDays\n)\nGet-ChildItem $BackupPath | where {$_.LastWriteTime -le (Get-Date).AddDays(-$NumDays)} | remove-item\n[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SqlServer.Smo\") | out-null\n[System.IO.Directory]::CreateDirectory($BackupPath) | out-null\n$srv=New-Object \"Microsoft.SqlServer.Management.Smo.Server\" \"$servername\"\n$bck=new-object \"Microsoft.SqlServer.Management.Smo.Backup\"\n\nif ($Backuptype -eq \"FULL\") \n{\n$bck.Action = 'Database' \n$extenstion=\".BAK\" \n$text1=\"Full Backup\"\n}\n\nif ($Backuptype -eq \"TRAN\") \n{\n$bck.Action = 'Log' \n$bck.LogTruncation = 2\n$extenstion=\".TRN\" \n$text1=\"Transactional Log Backup\"\n}\n\nif ($Backuptype -eq \"DIFF\") \n{ \n$bck.Incremental = 1 \n$extenstion=\".DIFF\" \n$text1=\"Differential Backup\"\n}\n\n$fil=new-object \"Microsoft.SqlServer.Management.Smo.BackupDeviceItem\"\n$fil.DeviceType='File'\n$fil.Name=[System.IO.Path]::Combine($BackupPath, $DatabaseName+ \"_\"+ [DateTime]::Now.ToString(\"yyyy_MM_dd_HH_mm\")+$extenstion)\n$bck.Devices.Add($fil)\n$bck.Database=$DatabaseName\n$bck.SqlBackup($srv)\nwrite-host $text1 of $Databasename done\n</code></pre>\n\n<p>It can do full, differential, and transactional backups and uniquely names each resulting file based on the date and time, deleting all files older than a certain number of days.</p>\n\n<p>The syntax to call it is:</p>\n\n<pre><code>.\\Backup.ps1 INSTANCENAME DATABASENAME FULL|TRAN|DIFF PATH DAYSTOKEEP\n</code></pre>\n\n<p>so...</p>\n\n<pre><code>.\\Backup.ps1 SQLEXPRESS Northwind FULL C:\\TempHold\\Test 30\n.\\Backup.ps1 SQLEXPRESS Northwind TRAN C:\\TempHold\\Test 30\n.\\Backup.ps1 SQLEXPRESS Northwind DIFF C:\\TempHold\\Test 30\n</code></pre>\n\n<p>To Schedule in Task Scheduler, pass in:</p>\n\n<pre><code>powershell c:\\temphold\\test\\backup.ps1 \"SQLEXPRESS Northwind DIFF C:\\TempHold\\Test 30\"\n</code></pre>\n"
},
{
"answer_id": 227659,
"author": "Mostlyharmless",
"author_id": 12881,
"author_profile": "https://Stackoverflow.com/users/12881",
"pm_score": 3,
"selected": true,
"text": "<p>Okay I figured out how to do this.</p>\n\n<p>The problem was that VB6 has no .Net 2.0 support and hence we cannot use SMO with VB6.</p>\n\n<p>To get around that, I wrote a COM wrapper in C# which uses SMO and maps (mostly) one-to-one with the kind of functionality I want from from my VB app.</p>\n\n<p>Basically, Create a C# project, add the SMO references as needed, add the following lines above the class declaration to make it COM visible:</p>\n\n<pre><code>[ComVisible(true)]\n\n[GuidAttribute(\"{guid here}\")]\n\n[ClassInterface(ClassInterfaceType.AutoDual)] // <--- Not recommended, but well...\n</code></pre>\n\n<p>In the project properties, in the \"Build\" section, make sure the \"Register For COM Interop\" box is checked. Compile and import into the VB6 app and you are in business!!</p>\n\n<p>As is the case with trying to hammer any two different systems together, there will be some manipulations you will need to do with what you pass between the VB6 app and the C# Wrapper... but its not too hard.</p>\n\n<p>Please comment if you need any more information/details.</p>\n"
},
{
"answer_id": 31995074,
"author": "Ved",
"author_id": 2484025,
"author_profile": "https://Stackoverflow.com/users/2484025",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your post. It helps me to understand that there is a solution to use SQLSMO from VB6 using COM Wrapper. I followed the steps you detailed, but my solution doesn't work . I am doing this basically: </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n</code></pre>\n\n<p>using System.Text;\nusing System.Runtime.InteropServices;\nnamespace WrapperCOM\n{</p>\n\n<pre><code>[System.Runtime.InteropServices.ComVisible(true)]\n\n[GuidAttribute(\"1d93750c-7465-4a3e-88d1-5e538afe7145\")]\n\n\n\n[ClassInterface(ClassInterfaceType.AutoDual)]\npublic class Class1\n{\n public Class1() { }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>I also added the following references for SQLSMO:</p>\n\n<p>•Microsoft.SqlServer.ConnectionInfo.dll</p>\n\n<p>•Microsoft.SqlServer.Smo.dll</p>\n\n<p>•Microsoft.SqlServer.Management.Sdk.Sfc.dll</p>\n\n<p>•Microsoft.SqlServer.SqlEnum.dll</p>\n\n<p>Finally when I run the VB6 after importing the .tlb file and creating an object like this - \nCreateObject(\"COMWrapper.Class1\"), It fails. It gives \"RunTime Error...\"</p>\n\n<p>Pls advise as to what's that I am missing here...</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12881/"
] |
We are trying to move from using SQL DMO to SMO in our COM+ based application, as we are dropping support for SQL Server 2000 and adding support for SQL Server 2008 in addition to SQL Server 2005.
I have been reading around on this, and found this particular quip on [this microsoft forum:](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=289491&SiteID=1)
> "SMO is only supported in VB/C#.Net 2005. It requires the .Net 2.0 Framework, which isn't available in VB/VC 6."
Is it true? Googling in general and googling stackoverflow did not throw up and definitive answers.
Is it possible to implement SQL SMO using VB6?
**Edit: I used a COM Wrapper to get around this... check out my answer below for some more details.**
|
Okay I figured out how to do this.
The problem was that VB6 has no .Net 2.0 support and hence we cannot use SMO with VB6.
To get around that, I wrote a COM wrapper in C# which uses SMO and maps (mostly) one-to-one with the kind of functionality I want from from my VB app.
Basically, Create a C# project, add the SMO references as needed, add the following lines above the class declaration to make it COM visible:
```
[ComVisible(true)]
[GuidAttribute("{guid here}")]
[ClassInterface(ClassInterfaceType.AutoDual)] // <--- Not recommended, but well...
```
In the project properties, in the "Build" section, make sure the "Register For COM Interop" box is checked. Compile and import into the VB6 app and you are in business!!
As is the case with trying to hammer any two different systems together, there will be some manipulations you will need to do with what you pass between the VB6 app and the C# Wrapper... but its not too hard.
Please comment if you need any more information/details.
|
206,595 |
<p>I have a page that contains a user control that is just a personalized dropdown list . I assign to each item the attribute <code>onClick=__doPostBack('actrl',0)</code>.</p>
<p>when I click the page postback fine and I got the expected results. However in IE6 my page doesn't change to the new values loaded from the server.</p>
<p>The weird thing is that when I shift + click on the link The page reload fine with all changes. </p>
<p>I tried to disable caching on the page but no luck.</p>
<p>using all this code</p>
<pre><code>Response.CacheControl = "no-cache"
Response.AddHeader("Pragma", "no-cache")
Response.Expires = -1
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Page.Response.Cache.SetExpires(DateTime.Now.AddDays(-30))
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Page.Response.Cache.SetNoServerCaching()
Page.Response.Cache.SetNoStore()
Response.Cache.SetNoStore()
</code></pre>
<p>Also when I debug the application I can see that the generated html to be rendered is correct, but it is not rendered.</p>
<p>This problem happens only in IE6.</p>
|
[
{
"answer_id": 206605,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that IE6 is not reloading the page from the server (its just grabbing the cached copy), however on a form post IE6 SHOULD reload. Why are you adding the _doPostBack as an attribute, those should be autogenerated on any asp.net control that needs to post back.</p>\n"
},
{
"answer_id": 207259,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 3,
"selected": true,
"text": "<p>This is a known IE6 bug (#223) with magical HTTP get requests.</p>\n\n<p>See the bug here:\n<a href=\"http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html</a></p>\n\n<p>It happens when an inline event handler causes a page change in IE6.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10968/"
] |
I have a page that contains a user control that is just a personalized dropdown list . I assign to each item the attribute `onClick=__doPostBack('actrl',0)`.
when I click the page postback fine and I got the expected results. However in IE6 my page doesn't change to the new values loaded from the server.
The weird thing is that when I shift + click on the link The page reload fine with all changes.
I tried to disable caching on the page but no luck.
using all this code
```
Response.CacheControl = "no-cache"
Response.AddHeader("Pragma", "no-cache")
Response.Expires = -1
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Page.Response.Cache.SetExpires(DateTime.Now.AddDays(-30))
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Page.Response.Cache.SetNoServerCaching()
Page.Response.Cache.SetNoStore()
Response.Cache.SetNoStore()
```
Also when I debug the application I can see that the generated html to be rendered is correct, but it is not rendered.
This problem happens only in IE6.
|
This is a known IE6 bug (#223) with magical HTTP get requests.
See the bug here:
<http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html>
It happens when an inline event handler causes a page change in IE6.
|
206,600 |
<p>This is happening on Vista.
I created a new dialog based MFC project to test this. I added a CEdit control to my dialog. I called SetLimitText to let my CEdit receive 100000 characters. I tried both:</p>
<pre><code>this->m_cedit1.SetLimitText(100000);
UpdateData(FALSE);
</code></pre>
<p>and </p>
<pre><code>static_cast<CEdit*>(GetDlgItem(IDC_EDIT1))->LimitText(100000);
</code></pre>
<p>I placed these calls on InitDialog.</p>
<p>after I paste 5461 characters into my CEdit, it becomes empty and unresponsive. Any ideas as to what is causing this and workarounds to be able to paste long strings of text in a CEdit or any other control?</p>
<p>note: 5461 is 0x1555 or 1010101010101 in binary, which i find quite odd.</p>
<p>if I paste 5460 characters I have no problems.</p>
|
[
{
"answer_id": 421845,
"author": "rec",
"author_id": 14022,
"author_profile": "https://Stackoverflow.com/users/14022",
"pm_score": 4,
"selected": true,
"text": "<p>I contacted microsof support. </p>\n\n<p>The goal was to have approximately\n 240000 characters in one single\n editable line of text.</p>\n\n<p>I am able to reproduce the issue on\n Windows Vista (x64 and x32 both) but\n <em>not</em> on Windows XP. </p>\n\n<p>this code works fine in XP:</p>\n\n<pre><code> BOOL ClongeditXPDlg::OnInitDialog()\n {\n CDialog::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n UINT limit = m_longEdit.GetLimitText();\n m_longEdit.SetLimitText(240000);\n UINT limit2 = m_longEdit.GetLimitText();\n\n CString str;\n str = _T(\"\");\n for(int i = 0; i < 250000; i++)\n str += _T(\"a\");\n\n m_longEdit.SetWindowText(str);\n\n return TRUE; // return TRUE unless you set the focus to a control\n }\n</code></pre>\n\n<p>If I use a CRichEdit control instead,\n when I press \"end\" key or \"right\n arrow\" key after pasting a long string\n inside, i cannot see all the\n characters in the Rich Edit Control.\n trying to scroll past the last visible\n character produces a beep. The rest of\n the characters are there, I know this\n because if i double-click the Rich\n Edit Control and copy the text using\n ctrl-c and then paste it on a text\n editor, I can see the 240000\n characters. So the control is holding\n the right amount of characters, but\n the last characters are not viewable\n except in an external editor, so my\n original problem remains.</p>\n\n<p>Here are the answers by microsoft\n representatives:</p>\n\n<blockquote>\n <p>Problem here is that an edit control\n with a large number of characters in\n it does not paint its text.</p>\n \n <p>I tried setting different characters,\n and discovered that I could fit more\n 'l's than 'x's than 'm's. The issue\n isn't directly the number of\n characters, but is likely the number\n of pixels. Multiplying the number of\n visible characters by the pixel width\n of the characters in the selected font\n shows that the limit is about 32k\n pixels.</p>\n</blockquote>\n\n<p>another answer from microsoft:</p>\n\n<blockquote>\n <p>I did extensive research on this issue\n and would like to update you about the\n case progress.</p>\n \n <p>The primary difference between the\n Edit control on Vista and on XP is\n that the Edit control on Vista\n pre-composes its glyphs for better\n international support (internally, it\n ends up calling ExtTextOut with\n ETO_GLYPH_INDEX and an array of glyphs\n rather than a string of characters. \n This ends up saving the glyph indices\n into a metafile and so runs into the\n 32k pixel limit. When too many\n characters are provided, ExtTextOut\n fails and draws nothing. The Edit\n control on XP doesn't precompose the\n glyphs and so doesn't have this\n problem, but won't handle\n international characters as well.</p>\n \n <p>The edit control on XP will clip at\n 32k, but since that is offscreen it\n isn't obvious. When scrolling to the\n right, it starts with the first\n visible character so the visible part\n of the control is always earlier than\n 32k pixels.</p>\n \n <p>The RichEdit control draws the\n beginning, but after hitting End,\n edits occur mostly offscreen. \n RichEdit 3.0 and 4.1 gives similar\n behavior. This appears to be the 32k\n pixel limit of RichEdit control, as\n the it draws its text on an offscreen\n bitmap before displaying it to the\n screen.</p>\n \n <p>Considering these points, the behavior\n is by design. You would need to create\n your own control to get the behavior\n of displaying as big string as 240000\n in a single line.</p>\n</blockquote>\n\n<p>and the last one: </p>\n\n<blockquote>\n <p>I did further research on this issue\n for finding any light weight\n workaround for overcoming 32k pixels\n limit, but unfortunately it seems that\n there is no workaround for this.</p>\n \n <p>Couple of alternatives that we tried\n are RichEdit 3.0, RichEdit\n 4.1, using UniScribe, using different fonts etc., but none of them seems to\n suffice your requirement.</p>\n \n <p>Possibly, you would need to create\n your own custom control if you wish to\n display an editable single-line string\n which exceeds 32k pixel limit in\n Windows Vista.</p>\n</blockquote>\n"
},
{
"answer_id": 561291,
"author": "Jack Bolding",
"author_id": 5882,
"author_profile": "https://Stackoverflow.com/users/5882",
"pm_score": 1,
"selected": false,
"text": "<p>FYI -- if the text is read-only/dsiplay only, you can add some CR-LFs to the string to fix the display of the text. It appears that the ExtTextOut function works slightly different when the newlines. Since it is a single-line edit box the newlines are stripped so the text looks the same -- unless you copy and paste it, then the linefeeds will be in the string... </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14022/"
] |
This is happening on Vista.
I created a new dialog based MFC project to test this. I added a CEdit control to my dialog. I called SetLimitText to let my CEdit receive 100000 characters. I tried both:
```
this->m_cedit1.SetLimitText(100000);
UpdateData(FALSE);
```
and
```
static_cast<CEdit*>(GetDlgItem(IDC_EDIT1))->LimitText(100000);
```
I placed these calls on InitDialog.
after I paste 5461 characters into my CEdit, it becomes empty and unresponsive. Any ideas as to what is causing this and workarounds to be able to paste long strings of text in a CEdit or any other control?
note: 5461 is 0x1555 or 1010101010101 in binary, which i find quite odd.
if I paste 5460 characters I have no problems.
|
I contacted microsof support.
The goal was to have approximately
240000 characters in one single
editable line of text.
I am able to reproduce the issue on
Windows Vista (x64 and x32 both) but
*not* on Windows XP.
this code works fine in XP:
```
BOOL ClongeditXPDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
UINT limit = m_longEdit.GetLimitText();
m_longEdit.SetLimitText(240000);
UINT limit2 = m_longEdit.GetLimitText();
CString str;
str = _T("");
for(int i = 0; i < 250000; i++)
str += _T("a");
m_longEdit.SetWindowText(str);
return TRUE; // return TRUE unless you set the focus to a control
}
```
If I use a CRichEdit control instead,
when I press "end" key or "right
arrow" key after pasting a long string
inside, i cannot see all the
characters in the Rich Edit Control.
trying to scroll past the last visible
character produces a beep. The rest of
the characters are there, I know this
because if i double-click the Rich
Edit Control and copy the text using
ctrl-c and then paste it on a text
editor, I can see the 240000
characters. So the control is holding
the right amount of characters, but
the last characters are not viewable
except in an external editor, so my
original problem remains.
Here are the answers by microsoft
representatives:
>
> Problem here is that an edit control
> with a large number of characters in
> it does not paint its text.
>
>
> I tried setting different characters,
> and discovered that I could fit more
> 'l's than 'x's than 'm's. The issue
> isn't directly the number of
> characters, but is likely the number
> of pixels. Multiplying the number of
> visible characters by the pixel width
> of the characters in the selected font
> shows that the limit is about 32k
> pixels.
>
>
>
another answer from microsoft:
>
> I did extensive research on this issue
> and would like to update you about the
> case progress.
>
>
> The primary difference between the
> Edit control on Vista and on XP is
> that the Edit control on Vista
> pre-composes its glyphs for better
> international support (internally, it
> ends up calling ExtTextOut with
> ETO\_GLYPH\_INDEX and an array of glyphs
> rather than a string of characters.
> This ends up saving the glyph indices
> into a metafile and so runs into the
> 32k pixel limit. When too many
> characters are provided, ExtTextOut
> fails and draws nothing. The Edit
> control on XP doesn't precompose the
> glyphs and so doesn't have this
> problem, but won't handle
> international characters as well.
>
>
> The edit control on XP will clip at
> 32k, but since that is offscreen it
> isn't obvious. When scrolling to the
> right, it starts with the first
> visible character so the visible part
> of the control is always earlier than
> 32k pixels.
>
>
> The RichEdit control draws the
> beginning, but after hitting End,
> edits occur mostly offscreen.
> RichEdit 3.0 and 4.1 gives similar
> behavior. This appears to be the 32k
> pixel limit of RichEdit control, as
> the it draws its text on an offscreen
> bitmap before displaying it to the
> screen.
>
>
> Considering these points, the behavior
> is by design. You would need to create
> your own control to get the behavior
> of displaying as big string as 240000
> in a single line.
>
>
>
and the last one:
>
> I did further research on this issue
> for finding any light weight
> workaround for overcoming 32k pixels
> limit, but unfortunately it seems that
> there is no workaround for this.
>
>
> Couple of alternatives that we tried
> are RichEdit 3.0, RichEdit
> 4.1, using UniScribe, using different fonts etc., but none of them seems to
> suffice your requirement.
>
>
> Possibly, you would need to create
> your own custom control if you wish to
> display an editable single-line string
> which exceeds 32k pixel limit in
> Windows Vista.
>
>
>
|
206,608 |
<p>I'm trying to see if the user has pressed a decimal separator in a text box, and either allow or suppress it depending on other parameters.</p>
<p>The NumberdecimalSeparator returns as 46, or '.' on my US system. Many other countries use ',' as the separator. The KeyDown event sets the KeyValue to 190 when I press the period.</p>
<p>Do I just continue to look for commas/periods, or is there a better way?</p>
|
[
{
"answer_id": 206649,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": false,
"text": "<p>The call</p>\n\n<pre><code>CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator\n</code></pre>\n\n<p>gets the decimal separator for the current user interface culture. You can use other cultures to get the separator for other languages.</p>\n\n<hr>\n\n<p>EDIT</p>\n\n<p>From the 166 cultures that are reported in my system (<code>CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count()</code>), it seems that only two separators are used: period and comma. You can try this in your system:</p>\n\n<pre><code>var seps = CultureInfo.GetCultures(CultureTypes.SpecificCultures)\n .Select(ci => ci.NumberFormat.NumberDecimalSeparator)\n .Distinct()\n .ToList();\n</code></pre>\n\n<p>Assuming that this is true, this method may be helpful (note that the <code>keyCode</code> is OR'ed with the <code>modifiers</code> flag in order to eliminate invalid combinations):</p>\n\n<pre><code> private bool IsDecimalSeparator(Keys keyCode, Keys modifiers)\n {\n Keys fullKeyCode = keyCode | modifiers;\n if (fullKeyCode.Equals(Keys.Decimal)) // value=110\n return true;\n\n string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;\n if (uiSep.Equals(\".\"))\n return fullKeyCode.Equals(Keys.OemPeriod); // value=190\n else if (uiSep.Equals(\",\"))\n return fullKeyCode.Equals(Keys.Oemcomma); // value=188\n throw new ApplicationException(string.Format(\"Unknown separator found {0}\", uiSep));\n }\n</code></pre>\n\n<p>A last note: According to <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.keys(VS.71).aspx\" rel=\"noreferrer\">Keys enumeration</a>, the value 46 that you mention corresponds to the DEL (Delete) key (i.e. the point when Num Lock is OFF).</p>\n"
},
{
"answer_id": 207403,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "<p>The problem here is that the values in the <code>KeyEventArgs</code> are key codes, not characters. If you handle <code>KeyPress</code> instead, you will get a char in the <code>KeyPressEventArgs</code> which you can use for the comparison.</p>\n\n<p>Note: You should really compare the <code>NumberDecimalSeparator</code> characters as it is a string, not a single character so you need to consider scenarios where there is more than one character in the string.</p>\n"
},
{
"answer_id": 59545576,
"author": "Leonardo Hernández",
"author_id": 5848216,
"author_profile": "https://Stackoverflow.com/users/5848216",
"pm_score": 0,
"selected": false,
"text": "<p>If you need know if the char pressed is decimal separator:</p>\n\n<pre><code>private void Control_KeyPress(object sender, KeyPressEventArgs e)\n{\n char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];\n if (e.KeyCahr == separador)\n {\n // true\n }\n else\n {\n // false\n }\n}\n</code></pre>\n\n<p>But, if you need acept decimal numpad key as decimal separator of any culture:</p>\n\n<pre><code> private bool decimalSeparator = false;\n private void Control_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.Decimal)\n decimalSeparator = true;\n }\n\n private void Control_KeyPress(object sender, KeyPressEventArgs e)\n {\n if (decimalSeparator)\n {\n e.KeyChar = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];\n decimalSeparator = false;\n }\n }\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to see if the user has pressed a decimal separator in a text box, and either allow or suppress it depending on other parameters.
The NumberdecimalSeparator returns as 46, or '.' on my US system. Many other countries use ',' as the separator. The KeyDown event sets the KeyValue to 190 when I press the period.
Do I just continue to look for commas/periods, or is there a better way?
|
The call
```
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
```
gets the decimal separator for the current user interface culture. You can use other cultures to get the separator for other languages.
---
EDIT
From the 166 cultures that are reported in my system (`CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count()`), it seems that only two separators are used: period and comma. You can try this in your system:
```
var seps = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Select(ci => ci.NumberFormat.NumberDecimalSeparator)
.Distinct()
.ToList();
```
Assuming that this is true, this method may be helpful (note that the `keyCode` is OR'ed with the `modifiers` flag in order to eliminate invalid combinations):
```
private bool IsDecimalSeparator(Keys keyCode, Keys modifiers)
{
Keys fullKeyCode = keyCode | modifiers;
if (fullKeyCode.Equals(Keys.Decimal)) // value=110
return true;
string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals("."))
return fullKeyCode.Equals(Keys.OemPeriod); // value=190
else if (uiSep.Equals(","))
return fullKeyCode.Equals(Keys.Oemcomma); // value=188
throw new ApplicationException(string.Format("Unknown separator found {0}", uiSep));
}
```
A last note: According to [Keys enumeration](http://msdn.microsoft.com/en-us/library/system.windows.forms.keys(VS.71).aspx), the value 46 that you mention corresponds to the DEL (Delete) key (i.e. the point when Num Lock is OFF).
|
206,611 |
<p>How can I setup a default value to a property defined as follow:</p>
<pre><code>public int MyProperty { get; set; }
</code></pre>
<p>That is using "prop" [tab][tab] in VS2008 (code snippet).</p>
<p>Is it possible without falling back in the "old way"?:</p>
<pre><code>private int myProperty = 0; // default value
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
</code></pre>
<p>Thanks for your time.
Best regards.</p>
|
[
{
"answer_id": 206615,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 4,
"selected": true,
"text": "<p>Just set the \"default\" value within your constructor.</p>\n\n<pre><code>public class Person\n{\n public Person()\n {\n this.FirstName = string.Empty;\n }\n\n public string FirstName { get; set; }\n}\n</code></pre>\n\n<p>Also, they're called Automatic Properties.</p>\n"
},
{
"answer_id": 206636,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": false,
"text": "<p>My preference would be to do things \"the old way\", rather than init in the constructor. If you later add another constructor you'll have to be sure to call the first one from it, or your properties will be uninitialized.</p>\n"
},
{
"answer_id": 807007,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>[DefaultValue(\"MyFirstName\")]\npublic string FirstName { get; set; }</p>\n"
},
{
"answer_id": 34060547,
"author": "AllDayPiano",
"author_id": 1451100,
"author_profile": "https://Stackoverflow.com/users/1451100",
"pm_score": 2,
"selected": false,
"text": "<p>Even though this is an older Thread i'd like to add some new way implemented in C# > Vers. 6:</p>\n\n<p><a href=\"https://msdn.microsoft.com/de-de/library/bb384054.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/de-de/library/bb384054.aspx</a></p>\n\n<pre><code>public int MyInt { get; set; } = 0;\npublic string MyString { get; set; } = \"Lorem Ipsum\";\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
How can I setup a default value to a property defined as follow:
```
public int MyProperty { get; set; }
```
That is using "prop" [tab][tab] in VS2008 (code snippet).
Is it possible without falling back in the "old way"?:
```
private int myProperty = 0; // default value
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
```
Thanks for your time.
Best regards.
|
Just set the "default" value within your constructor.
```
public class Person
{
public Person()
{
this.FirstName = string.Empty;
}
public string FirstName { get; set; }
}
```
Also, they're called Automatic Properties.
|
206,614 |
<p><strong>Preface</strong></p>
<p>I'm using the newly released Microsoft Virtual Earth SDK v6.2 which has built-in support for pushpin clustering. I realize there are custom ways of doing clustering where my question is easy to answer, but I'd like to leverage the built-in support as much as possible, so this question is specifically related to using the clustering feature of the VE 6.2 SDK.</p>
<p><strong>The Problem</strong></p>
<p>After enabling the built-in clustering (via VEShapeLayer.SetClusteringConfiguration), the clusters are created as expected, however, they have the default information in them which says something like "X items located here - zoom in to see details". In the app I'm working on, I need to display more information than that - I either need to allow the user to click on the pushpin and VE will automatically zoom in so that the points are now distinct OR display the names of the points in the infobox attached to the cluster pushpin. The catch is that cluster shape that VE creates for me does not appear to be editable until after all of the clustering logic has run...at that point, I don't know what original pushpins belong to that particular cluster. Is there a way to make this happen without resorting to creating a custom clustering implementation?</p>
|
[
{
"answer_id": 206615,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 4,
"selected": true,
"text": "<p>Just set the \"default\" value within your constructor.</p>\n\n<pre><code>public class Person\n{\n public Person()\n {\n this.FirstName = string.Empty;\n }\n\n public string FirstName { get; set; }\n}\n</code></pre>\n\n<p>Also, they're called Automatic Properties.</p>\n"
},
{
"answer_id": 206636,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": false,
"text": "<p>My preference would be to do things \"the old way\", rather than init in the constructor. If you later add another constructor you'll have to be sure to call the first one from it, or your properties will be uninitialized.</p>\n"
},
{
"answer_id": 807007,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>[DefaultValue(\"MyFirstName\")]\npublic string FirstName { get; set; }</p>\n"
},
{
"answer_id": 34060547,
"author": "AllDayPiano",
"author_id": 1451100,
"author_profile": "https://Stackoverflow.com/users/1451100",
"pm_score": 2,
"selected": false,
"text": "<p>Even though this is an older Thread i'd like to add some new way implemented in C# > Vers. 6:</p>\n\n<p><a href=\"https://msdn.microsoft.com/de-de/library/bb384054.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/de-de/library/bb384054.aspx</a></p>\n\n<pre><code>public int MyInt { get; set; } = 0;\npublic string MyString { get; set; } = \"Lorem Ipsum\";\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25886/"
] |
**Preface**
I'm using the newly released Microsoft Virtual Earth SDK v6.2 which has built-in support for pushpin clustering. I realize there are custom ways of doing clustering where my question is easy to answer, but I'd like to leverage the built-in support as much as possible, so this question is specifically related to using the clustering feature of the VE 6.2 SDK.
**The Problem**
After enabling the built-in clustering (via VEShapeLayer.SetClusteringConfiguration), the clusters are created as expected, however, they have the default information in them which says something like "X items located here - zoom in to see details". In the app I'm working on, I need to display more information than that - I either need to allow the user to click on the pushpin and VE will automatically zoom in so that the points are now distinct OR display the names of the points in the infobox attached to the cluster pushpin. The catch is that cluster shape that VE creates for me does not appear to be editable until after all of the clustering logic has run...at that point, I don't know what original pushpins belong to that particular cluster. Is there a way to make this happen without resorting to creating a custom clustering implementation?
|
Just set the "default" value within your constructor.
```
public class Person
{
public Person()
{
this.FirstName = string.Empty;
}
public string FirstName { get; set; }
}
```
Also, they're called Automatic Properties.
|
206,652 |
<p>I'm working on moving from using tables for layout purposes to using divs (yes, yes the great debate). I've got 3 divs, a header, content and footer. The header and footer are 50px each. How do I get the footer div to stay at the bottom of the page, and the content div to fill the space in between? I don't want to hard code the content divs height because the screen resolution can change.</p>
|
[
{
"answer_id": 206693,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": -1,
"selected": false,
"text": "<p>if you are trying to maximize the height of your content div, in the CSS add </p>\n\n<p>height: 100%;</p>\n"
},
{
"answer_id": 209427,
"author": "Traingamer",
"author_id": 27609,
"author_profile": "https://Stackoverflow.com/users/27609",
"pm_score": 3,
"selected": false,
"text": "<p>To expand on Mitchel Sellers answer, give your content div height: 100% and give it a auto margin.</p>\n\n<p>For a full explanation and example, see Ryan Fait's <a href=\"http://ryanfait.com/resources/footer-stick-to-bottom-of-page/\" rel=\"noreferrer\">CSS Sticky Footer</a>.</p>\n\n<p>Since you know the size (height) of your header, put it inside the content div (or use margins).</p>\n\n<p>Position absolute will give you problems if your content is larger (taller) than the window.</p>\n"
},
{
"answer_id": 209508,
"author": "Andy Brudtkuhl",
"author_id": 12442,
"author_profile": "https://Stackoverflow.com/users/12442",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#footer {\n clear: both;\n}\n</code></pre>\n"
},
{
"answer_id": 210603,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 5,
"selected": false,
"text": "<p>To summarize (and this came from the <a href=\"http://ryanfait.com/resources/footer-stick-to-bottom-of-page/\" rel=\"noreferrer\">CSS Sticky Footer</a> link provided by Traingamer), this is what I used:</p>\n\n<pre><code>html, body \n{ \n height: 100%; \n} \n\n#divHeader\n{\n height: 100px;\n}\n\n#divContent\n{\n min-height: 100%; \n height: auto !important; /*Cause footer to stick to bottom in IE 6*/\n height: 100%; \n margin: 0 auto -100px; /*Allow for footer height*/\n vertical-align:bottom;\n}\n\n#divFooter, #divPush\n{\n height: 100px; /*Push must be same height as Footer */\n}\n\n<div id=\"divContent\">\n <div id=\"divHeader\">\n Header\n </div>\n\n Content Text\n\n <div id=\"divPush\"></div>\n</div>\n<div id=\"divFooter\">\n Footer\n</div>\n</code></pre>\n"
},
{
"answer_id": 38627224,
"author": "Reggie Pinkham",
"author_id": 2927114,
"author_profile": "https://Stackoverflow.com/users/2927114",
"pm_score": 6,
"selected": true,
"text": "<h1>Flexbox solution</h1>\n\n<p>Using flex layout we can achieve this while allowing for natural height header and footer. Both the header and footer will stick to the top and bottom of the viewport respectively (much like a native mobile app) and the main content area will fill the remaining space, while any vertical overflow will be scrollable within that area.</p>\n\n<p><a href=\"https://jsfiddle.net/osvx1zoo/3/\" rel=\"noreferrer\">See JS Fiddle</a></p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><body>\n <header>\n ...\n </header>\n <main>\n ...\n </main>\n <footer>\n ...\n </footer>\n</body> \n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>html, body {\n margin: 0;\n height: 100%;\n min-height: 100%;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n}\n\nheader,\nfooter {\n flex: none;\n}\n\nmain {\n overflow-y: scroll;\n -webkit-overflow-scrolling: touch;\n flex: auto;\n}\n</code></pre>\n"
},
{
"answer_id": 51147756,
"author": "Allen",
"author_id": 667335,
"author_profile": "https://Stackoverflow.com/users/667335",
"pm_score": 2,
"selected": false,
"text": "<p>A way to do this using CSS Grid:</p>\n\n<p><strong>index.html</strong></p>\n\n<pre><code><html>\n <head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link href=\"main.css\" rel=\"stylesheet\">\n </head>\n <body>\n <main>\n <header>Header</header>\n <section>Content</section>\n <footer>Footer</footer>\n </main>\n </body>\n</html>\n</code></pre>\n\n<p><strong>main.css</strong></p>\n\n<pre><code>body {\n margin: 0;\n}\nmain {\n height: 100%;\n display: grid;\n grid-template-rows: 100px auto 100px;\n}\nsection {\n height: 100%;\n}\n</code></pre>\n"
},
{
"answer_id": 62364679,
"author": "Sumit Yadav",
"author_id": 8216693,
"author_profile": "https://Stackoverflow.com/users/8216693",
"pm_score": 0,
"selected": false,
"text": "<p>Use CSS grid instead it is supported by nearly all the browser</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html{\r\n height: 100%;\r\n}\r\nbody{\r\n margin: 0;\r\n padding: 0;\r\n height: 100%;\r\n}\r\n\r\n.main-body{\r\n display: grid;\r\n /* let content auto to occupy remaining height and pass value in fit-content with min-height for header and footer */\r\n grid-template-rows: fit-content(8rem) auto fit-content(8rem);\r\n grid-template-areas: \"header\" \"main\" \"footer\";\r\n}\r\n\r\n.main-header{\r\n background-color: yellow;\r\n grid-area: header;\r\n}\r\n\r\n.main-content{\r\n grid-area: main;\r\n}\r\n\r\n.main-footer{\r\n background-color: green;\r\n grid-area: footer;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body class=\"main-body\">\r\n <header class=\"main-header\">\r\n HEADER\r\n </header>\r\n <main class=\"main-content\">\r\n this is content\r\n </main>\r\n <footer class=\"main-footer\">\r\n this is footer\r\n </footer>\r\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
I'm working on moving from using tables for layout purposes to using divs (yes, yes the great debate). I've got 3 divs, a header, content and footer. The header and footer are 50px each. How do I get the footer div to stay at the bottom of the page, and the content div to fill the space in between? I don't want to hard code the content divs height because the screen resolution can change.
|
Flexbox solution
================
Using flex layout we can achieve this while allowing for natural height header and footer. Both the header and footer will stick to the top and bottom of the viewport respectively (much like a native mobile app) and the main content area will fill the remaining space, while any vertical overflow will be scrollable within that area.
[See JS Fiddle](https://jsfiddle.net/osvx1zoo/3/)
**HTML**
```
<body>
<header>
...
</header>
<main>
...
</main>
<footer>
...
</footer>
</body>
```
**CSS**
```
html, body {
margin: 0;
height: 100%;
min-height: 100%;
}
body {
display: flex;
flex-direction: column;
}
header,
footer {
flex: none;
}
main {
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
flex: auto;
}
```
|
206,659 |
<p>I am using ASP.NET to transmit a .jar file. This code works perfectly on IE. However on Firefox the file downloads, corrupt. What is the best way to fix it? Below is the code I am using.</p>
<pre><code>private void TransferFile()
{
try
{
string filePath = Server.MapPath("SomeJarFIle.jar");
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
// Clear the content of the response
//Response.ClearContent();
Response.Clear();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(file.Extension.ToLower());
// Write the file into the response
//Response.TransmitFile(file.FullName);
Response.WriteFile(file.FullName);
// End the response
Response.End();
}
else
{
this.Response.Write("Error in finding file. Please try again.");
this.Response.Flush();
}
}
catch (Exception ex)
{
this.Response.Write(string.Format("Error: {0}", ex.Message));
}
}
private string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".htm":
case ".html":
case ".log":
return "text/HTML";
case ".txt":
return "text/plain";
case ".doc":
return "application/ms-word";
case ".tiff":
case ".tif":
return "image/tiff";
case ".asf":
return "video/x-ms-asf";
case ".avi":
return "video/avi";
case ".zip":
return "application/zip";
case ".xls":
case ".csv":
return "application/vnd.ms-excel";
case ".gif":
return "image/gif";
case ".jpg":
case "jpeg":
return "image/jpeg";
case ".bmp":
return "image/bmp";
case ".wav":
return "audio/wav";
case ".mp3":
return "audio/mpeg3";
case ".mpg":
case "mpeg":
return "video/mpeg";
case ".rtf":
return "application/rtf";
case ".asp":
return "text/asp";
case ".pdf":
return "application/pdf";
case ".fdf":
return "application/vnd.fdf";
case ".ppt":
return "application/mspowerpoint";
case ".dwg":
return "image/vnd.dwg";
case ".msg":
return "application/msoutlook";
case ".xml":
case ".sdxl":
return "application/xml";
case ".xdp":
return "application/vnd.adobe.xdp+xml";
case ".jar":
return "application/java-archive";
default:
return "application/octet-stream";
}
}
</code></pre>
<p>UPDATE:</p>
<p>I added the type </p>
<pre><code>case ".jar":
return "application/java-archive";
</code></pre>
<p>And that did not fix the problem. If I zipped up the .jar file it was able to be transmitted fine.</p>
<p>I did notice when I tested againist my localhost the file was downloaded with no issues. However when I push it up to the web server is when I get the problem.</p>
|
[
{
"answer_id": 206676,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 3,
"selected": true,
"text": "<p>I don't see a case for \".jar\" in the ReturnExtension() function (which I think might be better off named \"ReturnMimetype\"). Could that be the problem, or did you just forget to paste it in?</p>\n\n<p>The mimetype for .jar is supposed to be <strong>application/java-archive</strong>. Details here: <a href=\"http://en.wikipedia.org/wiki/Jar-file\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Jar-file</a></p>\n\n<p>I think this is the issue. I remember having the same type of problem when I transmitted a .docx file (which is actually a zip file with a different extension, as a .jar files). The download worked fine in IE, but Firefox corrupted it. The solution was to send the correct mimetype.</p>\n"
},
{
"answer_id": 206684,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>I only see two things, it doesn't appear you have a mime type for the .jar file extension.</p>\n\n<p>Two I personally use writefile rather than transmit, but I'm not sure of the difference.</p>\n"
},
{
"answer_id": 206700,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 1,
"selected": false,
"text": "<p>Use Response.WriteFile or Response.BinaryWrite, there are some known strange behaviours with the TransmitFile method. </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
I am using ASP.NET to transmit a .jar file. This code works perfectly on IE. However on Firefox the file downloads, corrupt. What is the best way to fix it? Below is the code I am using.
```
private void TransferFile()
{
try
{
string filePath = Server.MapPath("SomeJarFIle.jar");
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
// Clear the content of the response
//Response.ClearContent();
Response.Clear();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(file.Extension.ToLower());
// Write the file into the response
//Response.TransmitFile(file.FullName);
Response.WriteFile(file.FullName);
// End the response
Response.End();
}
else
{
this.Response.Write("Error in finding file. Please try again.");
this.Response.Flush();
}
}
catch (Exception ex)
{
this.Response.Write(string.Format("Error: {0}", ex.Message));
}
}
private string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".htm":
case ".html":
case ".log":
return "text/HTML";
case ".txt":
return "text/plain";
case ".doc":
return "application/ms-word";
case ".tiff":
case ".tif":
return "image/tiff";
case ".asf":
return "video/x-ms-asf";
case ".avi":
return "video/avi";
case ".zip":
return "application/zip";
case ".xls":
case ".csv":
return "application/vnd.ms-excel";
case ".gif":
return "image/gif";
case ".jpg":
case "jpeg":
return "image/jpeg";
case ".bmp":
return "image/bmp";
case ".wav":
return "audio/wav";
case ".mp3":
return "audio/mpeg3";
case ".mpg":
case "mpeg":
return "video/mpeg";
case ".rtf":
return "application/rtf";
case ".asp":
return "text/asp";
case ".pdf":
return "application/pdf";
case ".fdf":
return "application/vnd.fdf";
case ".ppt":
return "application/mspowerpoint";
case ".dwg":
return "image/vnd.dwg";
case ".msg":
return "application/msoutlook";
case ".xml":
case ".sdxl":
return "application/xml";
case ".xdp":
return "application/vnd.adobe.xdp+xml";
case ".jar":
return "application/java-archive";
default:
return "application/octet-stream";
}
}
```
UPDATE:
I added the type
```
case ".jar":
return "application/java-archive";
```
And that did not fix the problem. If I zipped up the .jar file it was able to be transmitted fine.
I did notice when I tested againist my localhost the file was downloaded with no issues. However when I push it up to the web server is when I get the problem.
|
I don't see a case for ".jar" in the ReturnExtension() function (which I think might be better off named "ReturnMimetype"). Could that be the problem, or did you just forget to paste it in?
The mimetype for .jar is supposed to be **application/java-archive**. Details here: <http://en.wikipedia.org/wiki/Jar-file>
I think this is the issue. I remember having the same type of problem when I transmitted a .docx file (which is actually a zip file with a different extension, as a .jar files). The download worked fine in IE, but Firefox corrupted it. The solution was to send the correct mimetype.
|
206,661 |
<p>Yes, <a href="http://en.wikipedia.org/wiki/There_is_more_than_one_way_to_do_it" rel="noreferrer">There's More Than One Way To Do It</a> but there must be a canonical or most efficient or most concise way. I'll add answers I know of and see what percolates to the top.</p>
<p>To be clear, the question is how best to read the contents of a file into a string.
One solution per answer.</p>
|
[
{
"answer_id": 206681,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 5,
"selected": false,
"text": "<pre><code>open(my $f, '<', $filename) or die \"OPENING $filename: $!\\n\";\n$string = do { local($/); <$f> };\nclose($f);\n</code></pre>\n"
},
{
"answer_id": 206682,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 7,
"selected": true,
"text": "<p>How about this:</p>\n\n<pre><code>use File::Slurp;\nmy $text = read_file($filename);\n</code></pre>\n\n<p>ETA: note <a href=\"https://rt.cpan.org/Ticket/Display.html?id=83126\" rel=\"noreferrer\">Bug #83126 for File-Slurp: Security hole with encoding(UTF-8)</a>. I now recommend using <a href=\"https://metacpan.org/pod/File::Slurper\" rel=\"noreferrer\">File::Slurper</a> (disclaimer: I wrote it), also because it has better defaults around encodings:</p>\n\n<pre><code>use File::Slurper 'read_text';\nmy $text = read_text($filename);\n</code></pre>\n\n<p>or <a href=\"https://metacpan.org/pod/Path::Tiny\" rel=\"noreferrer\">Path::Tiny</a>:</p>\n\n<pre><code>use Path::Tiny;\npath($filename)->slurp_utf8;\n</code></pre>\n"
},
{
"answer_id": 206683,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 3,
"selected": false,
"text": "<pre><code>{\n open F, $filename or die \"Can't read $filename: $!\";\n local $/; # enable slurp mode, locally.\n $file = <F>;\n close F;\n}\n</code></pre>\n"
},
{
"answer_id": 206688,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 1,
"selected": false,
"text": "<p>Candidate for the worst way to do it! (See comment.)</p>\n\n<pre><code>open(F, $filename) or die \"OPENING $filename: $!\\n\";\n@lines = <F>;\nclose(F);\n$string = join('', @lines);\n</code></pre>\n"
},
{
"answer_id": 206741,
"author": "mopoke",
"author_id": 14054,
"author_profile": "https://Stackoverflow.com/users/14054",
"pm_score": 2,
"selected": false,
"text": "<p>See the summary of <a href=\"https://metacpan.org/module/Perl6::Slurp\" rel=\"nofollow noreferrer\">Perl6::Slurp</a> which is incredibly flexible and generally does the right thing with very little effort.</p>\n"
},
{
"answer_id": 206778,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 6,
"selected": false,
"text": "<p>I like doing this with a <code>do</code> block in which I localize <code>@ARGV</code> so I can use the diamond operator to do the file magic for me. </p>\n\n<pre><code> my $contents = do { local(@ARGV, $/) = $file; <> };\n</code></pre>\n\n<p>If you need this to be a bit more robust, you can easily turn this into a subroutine.</p>\n\n<p><s>If you need something really robust that handles all sorts of special cases, use <a href=\"http://search.cpan.org/dist/File-Slurp\" rel=\"noreferrer\">File::Slurp</a>. Even if you aren't going to use it, take a look at the source to see all the wacky situations it has to handle.</s> <a href=\"http://search.cpan.org/dist/File-Slurp\" rel=\"noreferrer\">File::Slurp</a> has a <a href=\"https://rt.cpan.org/Ticket/Display.html?id=83126\" rel=\"noreferrer\">big security problem</a> that doesn't look to have a solution. Part of this is its failure to properly handle encodings. Even my quick answer has that problem. If you need to handle the encoding (maybe because you don't make everything UTF-8 by default), this expands to:</p>\n\n<pre><code>my $contents = do {\n open my $fh, '<:encoding(UTF-8)', $file or die '...';\n local $/;\n <$fh>;\n };\n</code></pre>\n\n<p>If you don't need to change the file, you might be able to use <a href=\"http://www.metacpan.org/module/File::Map\" rel=\"noreferrer\">File::Map</a>.</p>\n"
},
{
"answer_id": 206794,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 4,
"selected": false,
"text": "<p>Things to think about (especially when compared with other solutions):</p>\n\n<ol>\n<li>Lexical filehandles</li>\n<li>Reduce scope</li>\n<li>Reduce magic</li>\n</ol>\n\n<p>So I get:</p>\n\n<pre><code>my $contents = do {\n local $/;\n open my $fh, $filename or die \"Can't open $filename: $!\";\n <$fh>\n};\n</code></pre>\n\n<p>I'm not a big fan of magic <> except when actually using magic <>. Instead of faking it out, why not just use the open call directly? It's not much more work, and is explicit. (True magic <>, especially when handling \"-\", is far more work to perfectly emulate, but we aren't using it here anyway.)</p>\n"
},
{
"answer_id": 207438,
"author": "dwarring",
"author_id": 2105284,
"author_profile": "https://Stackoverflow.com/users/2105284",
"pm_score": 3,
"selected": false,
"text": "<p>mmap (Memory mapping) of strings may be useful when you:</p>\n\n<ul>\n<li> Have very large strings, that you don't want to load into memory\n<li> Want a blindly fast initialisation (you get gradual I/O on access)\n<li> Have random or lazy access to the string.\n<li> May want to update the string, but are only extending it or replacing characters:\n</ul>\n\n<pre><code>#!/usr/bin/perl\nuse warnings; use strict;\n\nuse IO::File;\nuse Sys::Mmap;\n\nsub sip {\n\n my $file_name = shift;\n my $fh;\n\n open ($fh, '+<', $file_name)\n or die \"Unable to open $file_name: $!\";\n\n my $str;\n\n mmap($str, 0, PROT_READ|PROT_WRITE, MAP_SHARED, $fh)\n or die \"mmap failed: $!\";\n\n return $str;\n}\n\nmy $str = sip('/tmp/words');\n\nprint substr($str, 100,20);\n</code></pre>\n\n<p><strong>Update: May 2012</strong></p>\n\n<p>The following should be pretty well equivalent, after replacing <a href=\"http://search.cpan.org/dist/Sys-Mmap/\" rel=\"nofollow noreferrer\">Sys::Mmap</a> with <a href=\"http://search.cpan.org/dist/File-Map/\" rel=\"nofollow noreferrer\">File::Map</a></p>\n\n<pre><code>#!/usr/bin/perl\nuse warnings; use strict;\n\nuse File::Map qw{map_file};\n\nmap_file(my $str => '/tmp/words', '+<');\n\nprint substr($str, 100, 20);\n</code></pre>\n"
},
{
"answer_id": 207611,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "<p>This is neither fast, nor platform independent, and really evil, but it's short (and I've seen this in Larry Wall's code ;-):</p>\n\n<pre><code> my $contents = `cat $file`;\n</code></pre>\n\n<p>Kids, don't do that at home ;-).</p>\n"
},
{
"answer_id": 214761,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 5,
"selected": false,
"text": "<p>In writing <a href=\"http://search.cpan.org/perldoc?File::Slurp\" rel=\"noreferrer\">File::Slurp</a> (which is the best way), Uri Guttman did a lot of research in the many ways of slurping and which is most efficient. He wrote down <a href=\"http://search.cpan.org/~drolsky/File-Slurp-9999.13/extras/slurp_article.pod\" rel=\"noreferrer\">his findings here</a> and incorporated them info File::Slurp.</p>\n"
},
{
"answer_id": 348597,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>use Path::Class;\nfile('/some/path')->slurp;\n</code></pre>\n"
},
{
"answer_id": 1753848,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a nice comparison of the most popular ways to do it:</p>\n\n<p><a href=\"http://poundcomment.wordpress.com/2009/08/02/perl-read-entire-file/\" rel=\"nofollow noreferrer\">http://poundcomment.wordpress.com/2009/08/02/perl-read-entire-file/</a></p>\n"
},
{
"answer_id": 7017092,
"author": "Prakash K",
"author_id": 159470,
"author_profile": "https://Stackoverflow.com/users/159470",
"pm_score": 3,
"selected": false,
"text": "<pre><code>use IO::All;\n\n# read into a string (scalar context)\n$contents = io($filename)->slurp;\n\n# read all lines an array (array context)\n@lines = io($filename)->slurp;\n</code></pre>\n"
},
{
"answer_id": 10106476,
"author": "Trizen",
"author_id": 1326646,
"author_profile": "https://Stackoverflow.com/users/1326646",
"pm_score": 2,
"selected": false,
"text": "<p>Nobody said anything about read or sysread, so here is a simple and fast way:</p>\n\n<pre><code>my $string;\n{\n open my $fh, '<', $file or die \"Can't open $file: $!\";\n read $fh, $string, -s $file; # or sysread\n close $fh;\n}\n</code></pre>\n"
},
{
"answer_id": 26608540,
"author": "Qtax",
"author_id": 107152,
"author_profile": "https://Stackoverflow.com/users/107152",
"pm_score": 2,
"selected": false,
"text": "<p>For one-liners you can usually use <a href=\"http://perldoc.perl.org/perlrun.html#*-0*%5b_octal%2fhexadecimal_%5d\" rel=\"nofollow\">the <code>-0</code> switch</a> (with <code>-n</code>) to make perl read the whole file at once (if the file doesn't contain any null bytes):</p>\n\n<pre><code>perl -n0e 'print \"content is in $_\\n\"' filename\n</code></pre>\n\n<p>If it's a binary file, you could use <code>-0777</code>:</p>\n\n<pre><code>perl -n0777e 'print length' filename\n</code></pre>\n"
},
{
"answer_id": 30518178,
"author": "user4951120",
"author_id": 4951120,
"author_profile": "https://Stackoverflow.com/users/4951120",
"pm_score": 1,
"selected": false,
"text": "<p>Adjust the special record separator variable <code>$/</code></p>\n\n<pre><code>undef $/;\nopen FH, '<', $filename or die \"$!\\n\";\nmy $contents = <FH>;\nclose FH;\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] |
Yes, [There's More Than One Way To Do It](http://en.wikipedia.org/wiki/There_is_more_than_one_way_to_do_it) but there must be a canonical or most efficient or most concise way. I'll add answers I know of and see what percolates to the top.
To be clear, the question is how best to read the contents of a file into a string.
One solution per answer.
|
How about this:
```
use File::Slurp;
my $text = read_file($filename);
```
ETA: note [Bug #83126 for File-Slurp: Security hole with encoding(UTF-8)](https://rt.cpan.org/Ticket/Display.html?id=83126). I now recommend using [File::Slurper](https://metacpan.org/pod/File::Slurper) (disclaimer: I wrote it), also because it has better defaults around encodings:
```
use File::Slurper 'read_text';
my $text = read_text($filename);
```
or [Path::Tiny](https://metacpan.org/pod/Path::Tiny):
```
use Path::Tiny;
path($filename)->slurp_utf8;
```
|
206,689 |
<p>I have a menu that I am using and it will change the background color when I hover using <code>a:hover</code> but I want to know how to change the <code>class=line</code> so that it sticks. </p>
<p>So from the home if they click contacts the home pages </p>
<blockquote>
<p>from (a href="#" class="clr") to (a href="#")</p>
</blockquote>
<p>and Contacts would change </p>
<blockquote>
<p>from (a href="#") to (a href="#" class="clr")</p>
</blockquote>
<p>any help?</p>
<p>JD</p>
|
[
{
"answer_id": 206705,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 1,
"selected": false,
"text": "<p>The way to change class (I assume you're talking of the DOM), in javascript is:</p>\n\n<pre><code>document.getElementById(\"element\").className='myClass';\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 206706,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you are wanting to highlight the navigational item that you're on. My answer <a href=\"https://stackoverflow.com/questions/188124/programmatic-solution-to-change-navigation-id-to-highlight-current-page-aspnet#189069\">here</a> is fairly valid in this question as well, I believe:</p>\n\n<p>It's a better semantic match and likely an easier variable to set to keep the navigation using the same classes or ids everywhere and only alter the body element's id to match:</p>\n\n<pre><code><li id=\"homeNav\">home</li>\n<li id=\"blogNav\">blog</li>\n</code></pre>\n\n<p>and then on each page...</p>\n\n<pre><code><body id=\"home\">\n<body id=\"blog\">\n</code></pre>\n\n<p>And in the css:</p>\n\n<pre><code>#home #homeNav {background-image:url(homeNav-on.jpg);}\n#blog #blogNav {background-image:url(blogNav-on.jpg);}\n</code></pre>\n"
},
{
"answer_id": 207719,
"author": "PHLAK",
"author_id": 27025,
"author_profile": "https://Stackoverflow.com/users/27025",
"pm_score": 0,
"selected": false,
"text": "<p>This may not apply to you, but it may lead you down the right path. If you are using PHP, stick this in your head before the doctype declaration or the (x)html tag:</p>\n\n<pre><code><?php\n // Get current page file name\n $url = Explode('/', $_SERVER[\"PHP_SELF\"]);\n $page = $parts[count($url) - 1];\n?>\n</code></pre>\n\n<p>Then, in your menu item where you would like the class designation, place the following, but change \"index.php\" to the name of the page: </p>\n\n<pre><code><?php if ($page == \"index.php\") echo ' class=\"current\"' ?>\n</code></pre>\n\n<p>So ultimately your menu should look similar to this: </p>\n\n<pre><code><div id=\"navigation\">\n <ul>\n <li><a href=\"index.php\"<?php if ($page == \"index.php\") echo ' class=\"current\"' ?>>Home</a></li>\n <li><a href=\"page1.php\"<?php if ($page == \"page1.php\") echo ' class=\"current\"' ?>>Resume</a></li>\n <li><a href=\"page2.php\"<?php if ($page == \"page2.php\") echo ' class=\"current\"' ?>>Photography</a></li>\n </ul>\n</div>\n</code></pre>\n\n<p>Last step is adding the CSS:</p>\n\n<pre><code>#navigation ul li a.current {\n background-color: #FFF;\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 207942,
"author": "Martin Kool",
"author_id": 216896,
"author_profile": "https://Stackoverflow.com/users/216896",
"pm_score": 1,
"selected": false,
"text": "<p>The mechanism we use frequently is by having a few generic event listeners on the body and have all required events bubble up. Once caught, we check for a certain className (or className pattern) on the triggering element. If such a className is found, we consider it a state identifier, and we trigger behavior based on such states.</p>\n\n<p>For instance, we have defined className pairs (such as \"selected\" and \"unselected\") with the default behavior of toggling. Or make them exclusive by giving the parent element the className \"exclusive-selected\". </p>\n\n<p>A simple mechanism like that can be extended to your liking and can be very powerful.</p>\n\n<p>Allow me to post a simple demonstration. Non-generic, but it is just to illustrate the inner workings of such a mechanism. For this example I consider the className pair \"selected\" and \"unselected\" to be exclusive.</p>\n\n<pre><code><html>\n <head>\n <script>\n document.onclick = function(evt) {\n var el = window.event? event.srcElement : evt.target;\n if (el && el.className == \"unselected\") {\n el.className = \"selected\";\n var siblings = el.parentNode.childNodes;\n for (var i = 0, l = siblings.length; i < l; i++) {\n var sib = siblings[i];\n if (sib != el && sib.className == \"selected\")\n sib.className = \"unselected\";\n }\n }\n }\n </script>\n <style>\n .selected { background: #f00; }\n </style>\n </head>\n <body>\n <a href=\"#\" class=\"selected\">One</a> \n <a href=\"#\" class=\"unselected\">Two</a> \n <a href=\"#\" class=\"unselected\">Three</a>\n </body>\n</html>\n</code></pre>\n\n<p>It ought to work on IE, Firefox and other browsers. Of course this mechanism can be made generic and have all kinds of className states and behaviors implemented.</p>\n"
},
{
"answer_id": 207998,
"author": "Eli",
"author_id": 27580,
"author_profile": "https://Stackoverflow.com/users/27580",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to check out jQuery (jquery.com).</p>\n\n<p>Using jQuery, you would change the class (and stick it) like this:</p>\n\n<pre><code>$('#link-id').addClass('your-class');\n</code></pre>\n\n<p>You could bind the code to the links like this:</p>\n\n<pre><code>$('#link-id').mouseover(\n function(){\n $(this).addClass('your-class');\n }\n);\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/Attributes\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Attributes</a></p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a menu that I am using and it will change the background color when I hover using `a:hover` but I want to know how to change the `class=line` so that it sticks.
So from the home if they click contacts the home pages
>
> from (a href="#" class="clr") to (a href="#")
>
>
>
and Contacts would change
>
> from (a href="#") to (a href="#" class="clr")
>
>
>
any help?
JD
|
I believe you are wanting to highlight the navigational item that you're on. My answer [here](https://stackoverflow.com/questions/188124/programmatic-solution-to-change-navigation-id-to-highlight-current-page-aspnet#189069) is fairly valid in this question as well, I believe:
It's a better semantic match and likely an easier variable to set to keep the navigation using the same classes or ids everywhere and only alter the body element's id to match:
```
<li id="homeNav">home</li>
<li id="blogNav">blog</li>
```
and then on each page...
```
<body id="home">
<body id="blog">
```
And in the css:
```
#home #homeNav {background-image:url(homeNav-on.jpg);}
#blog #blogNav {background-image:url(blogNav-on.jpg);}
```
|
206,717 |
<p>How can I replace multiple spaces in a string with only one space in C#?</p>
<p>Example:</p>
<pre><code>1 2 3 4 5
</code></pre>
<p>would be:</p>
<pre><code>1 2 3 4 5
</code></pre>
|
[
{
"answer_id": 206720,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 10,
"selected": true,
"text": "<pre><code>string sentence = \"This is a sentence with multiple spaces\";\nRegexOptions options = RegexOptions.None;\nRegex regex = new Regex(\"[ ]{2,}\", options); \nsentence = regex.Replace(sentence, \" \");\n</code></pre>\n"
},
{
"answer_id": 206724,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "<pre><code>string xyz = \"1 2 3 4 5\";\nxyz = string.Join( \" \", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));\n</code></pre>\n"
},
{
"answer_id": 206799,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "<p>Consolodating other answers, per Joel, and hopefully improving slightly as I go:</p>\n\n<p>You can do this with <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(VS.71).aspx\" rel=\"noreferrer\"><code>Regex.Replace()</code></a>:</p>\n\n<pre><code>string s = Regex.Replace (\n \" 1 2 4 5\", \n @\"[ ]{2,}\", \n \" \"\n );\n</code></pre>\n\n<p>Or with <a href=\"http://msdn.microsoft.com/en-us/library/system.string.split(VS.71).aspx\" rel=\"noreferrer\"><code>String.Split()</code></a>:</p>\n\n<pre><code>static class StringExtensions\n{\n public static string Join(this IList<string> value, string separator)\n {\n return string.Join(separator, value.ToArray());\n }\n}\n\n//...\n\nstring s = \" 1 2 4 5\".Split (\n \" \".ToCharArray(), \n StringSplitOptions.RemoveEmptyEntries\n ).Join (\" \");\n</code></pre>\n"
},
{
"answer_id": 206917,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>It's much simpler than all that:</p>\n\n<pre><code>while(str.Contains(\" \")) str = str.Replace(\" \", \" \");\n</code></pre>\n"
},
{
"answer_id": 206946,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 10,
"selected": false,
"text": "<p>I like to use:</p>\n\n<pre><code>myString = Regex.Replace(myString, @\"\\s+\", \" \");\n</code></pre>\n\n<p>Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.</p>\n"
},
{
"answer_id": 219268,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>I just wrote a new <code>Join</code> that I like, so I thought I'd re-answer, with it:</p>\n\n<pre><code>public static string Join<T>(this IEnumerable<T> source, string separator)\n{\n return string.Join(separator, source.Select(e => e.ToString()).ToArray());\n}\n</code></pre>\n\n<p>One of the cool things about this is that it work with collections that aren't strings, by calling ToString() on the elements. Usage is still the same:</p>\n\n<pre><code>//...\n\nstring s = \" 1 2 4 5\".Split (\n \" \".ToCharArray(), \n StringSplitOptions.RemoveEmptyEntries\n ).Join (\" \");\n</code></pre>\n"
},
{
"answer_id": 304547,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 4,
"selected": false,
"text": "<pre><code>myString = Regex.Replace(myString, \" {2,}\", \" \");\n</code></pre>\n"
},
{
"answer_id": 2878200,
"author": "Brenda Bell",
"author_id": 346589,
"author_profile": "https://Stackoverflow.com/users/346589",
"pm_score": 5,
"selected": false,
"text": "<p>I think Matt's answer is the best, but I don't believe it's quite right. If you want to replace newlines, you must use:</p>\n\n<pre><code>myString = Regex.Replace(myString, @\"\\s+\", \" \", RegexOptions.Multiline);\n</code></pre>\n"
},
{
"answer_id": 11947581,
"author": "cuongle",
"author_id": 783681,
"author_profile": "https://Stackoverflow.com/users/783681",
"pm_score": 5,
"selected": false,
"text": "<p>Another approach which uses LINQ:</p>\n\n<pre><code> var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));\n str = string.Join(\" \", list);\n</code></pre>\n"
},
{
"answer_id": 13642266,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 0,
"selected": false,
"text": "<p>Old skool:</p>\n\n<pre><code>string oldText = \" 1 2 3 4 5 \";\nstring newText = oldText\n .Replace(\" \", \" \" + (char)22 )\n .Replace( (char)22 + \" \", \"\" )\n .Replace( (char)22 + \"\", \"\" );\n\nAssert.That( newText, Is.EqualTo( \" 1 2 3 4 5 \" ) );\n</code></pre>\n"
},
{
"answer_id": 16776096,
"author": "Nolonar",
"author_id": 1169228,
"author_profile": "https://Stackoverflow.com/users/1169228",
"pm_score": 4,
"selected": false,
"text": "<p>For those, who don't like <code>Regex</code>, here is a method that uses the <code>StringBuilder</code>:</p>\n\n<pre><code> public static string FilterWhiteSpaces(string input)\n {\n if (input == null)\n return string.Empty;\n\n StringBuilder stringBuilder = new StringBuilder(input.Length);\n for (int i = 0; i < input.Length; i++)\n {\n char c = input[i];\n if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))\n stringBuilder.Append(c);\n }\n return stringBuilder.ToString();\n }\n</code></pre>\n\n<p>In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.</p>\n\n<p>Keep in mind, that it does <em>not</em> remove leading or trailing spaces, only multiple occurrences of such.</p>\n"
},
{
"answer_id": 24847573,
"author": "Paul Easter",
"author_id": 3583929,
"author_profile": "https://Stackoverflow.com/users/3583929",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.</p>\n\n<pre><code>pattern: (?m:^ +| +$|( ){2,})\nreplacement: $1\n</code></pre>\n\n<p>Its a little difficult to read since we're dealing with empty space, so here it is again with the \"spaces\" replaced with a \"_\". </p>\n\n<pre><code>pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.\n</code></pre>\n\n<p>The \"(?m:\" construct enables the \"multi-line\" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.</p>\n"
},
{
"answer_id": 28896999,
"author": "ravish.hacker",
"author_id": 1367413,
"author_profile": "https://Stackoverflow.com/users/1367413",
"pm_score": 3,
"selected": false,
"text": "<p>You can simply do this in one line solution!</p>\n\n<pre><code>string s = \"welcome to london\";\ns.Replace(\" \", \"()\").Replace(\")(\", \"\").Replace(\"()\", \" \");\n</code></pre>\n\n<p>You can choose other brackets (or even other characters) if you like.</p>\n"
},
{
"answer_id": 30230993,
"author": "somebody",
"author_id": 3323231,
"author_profile": "https://Stackoverflow.com/users/3323231",
"pm_score": 3,
"selected": false,
"text": "<p>This is a shorter version, which should only be used if you are only doing this once, as it creates a new instance of the <code>Regex</code> class every time it is called.</p>\n\n<pre><code>temp = new Regex(\" {2,}\").Replace(temp, \" \"); \n</code></pre>\n\n<p>If you are not too acquainted with regular expressions, here's a short explanation:</p>\n\n<p>The <code>{2,}</code> makes the regex search for the character preceding it, and finds substrings between 2 and unlimited times.<br>\nThe <code>.Replace(temp, \" \")</code> replaces all matches in the string temp with a space.</p>\n\n<p>If you want to use this multiple times, here is a better option, as it creates the regex IL at compile time:</p>\n\n<pre><code>Regex singleSpacify = new Regex(\" {2,}\", RegexOptions.Compiled);\ntemp = singleSpacify.Replace(temp, \" \");\n</code></pre>\n"
},
{
"answer_id": 33817748,
"author": "ScubaSteve",
"author_id": 787958,
"author_profile": "https://Stackoverflow.com/users/787958",
"pm_score": 5,
"selected": false,
"text": "<p>Regex can be rather slow even with simple tasks. This creates an extension method that can be used off of any <code>string</code>. </p>\n\n<pre><code> public static class StringExtension\n {\n public static String ReduceWhitespace(this String value)\n {\n var newString = new StringBuilder();\n bool previousIsWhitespace = false;\n for (int i = 0; i < value.Length; i++)\n {\n if (Char.IsWhiteSpace(value[i]))\n {\n if (previousIsWhitespace)\n {\n continue;\n }\n\n previousIsWhitespace = true;\n }\n else\n {\n previousIsWhitespace = false;\n }\n\n newString.Append(value[i]);\n }\n\n return newString.ToString();\n }\n }\n</code></pre>\n\n<p>It would be used as such:</p>\n\n<pre><code>string testValue = \"This contains too much whitespace.\"\ntestValue = testValue.ReduceWhitespace();\n// testValue = \"This contains too much whitespace.\"\n</code></pre>\n"
},
{
"answer_id": 34953510,
"author": "Ahmed Aljaff",
"author_id": 3995545,
"author_profile": "https://Stackoverflow.com/users/3995545",
"pm_score": 1,
"selected": false,
"text": "<p><strong>try this method</strong> </p>\n\n<pre><code>private string removeNestedWhitespaces(char[] st)\n{\n StringBuilder sb = new StringBuilder();\n int indx = 0, length = st.Length;\n while (indx < length)\n {\n sb.Append(st[indx]);\n indx++;\n while (indx < length && st[indx] == ' ')\n indx++;\n if(sb.Length > 1 && sb[0] != ' ')\n sb.Append(' ');\n }\n return sb.ToString();\n}\n</code></pre>\n\n<p>use it like this: </p>\n\n<pre><code>string test = removeNestedWhitespaces(\"1 2 3 4 5\".toCharArray());\n</code></pre>\n"
},
{
"answer_id": 35336638,
"author": "Learner1947",
"author_id": 3528695,
"author_profile": "https://Stackoverflow.com/users/3528695",
"pm_score": 1,
"selected": false,
"text": "<p>I can remove whitespaces with this </p>\n\n<pre><code>while word.contains(\" \") //double space\n word = word.Replace(\" \",\" \"); //replace double space by single space.\nword = word.trim(); //to remove single whitespces from start & end.\n</code></pre>\n"
},
{
"answer_id": 35440518,
"author": "Tom Gullen",
"author_id": 356635,
"author_profile": "https://Stackoverflow.com/users/356635",
"pm_score": 1,
"selected": false,
"text": "<p>Without using regular expressions:</p>\n\n<pre><code>while (myString.IndexOf(\" \", StringComparison.CurrentCulture) != -1)\n{\n myString = myString.Replace(\" \", \" \");\n}\n</code></pre>\n\n<p>OK to use on short strings, but will perform badly on long strings with lots of spaces.</p>\n"
},
{
"answer_id": 48326219,
"author": "Stephen du Buis",
"author_id": 4035321,
"author_profile": "https://Stackoverflow.com/users/4035321",
"pm_score": 3,
"selected": false,
"text": "<p>no Regex, no Linq... removes leading and trailing spaces as well as reducing any embedded multiple space segments to one space</p>\n\n<pre><code>string myString = \" 0 1 2 3 4 5 \";\nmyString = string.Join(\" \", myString.Split(new char[] { ' ' }, \nStringSplitOptions.RemoveEmptyEntries));\n</code></pre>\n\n<p>result:\"0 1 2 3 4 5\"</p>\n"
},
{
"answer_id": 49017046,
"author": "The_Black_Smurf",
"author_id": 315493,
"author_profile": "https://Stackoverflow.com/users/315493",
"pm_score": 2,
"selected": false,
"text": "<p>Many answers are providing the right output but for those looking for the best performances, I did improve <a href=\"https://stackoverflow.com/a/16776096/315493\">Nolanar's answer</a> (which was the best answer for performance) by about 10%.</p>\n\n<pre><code>public static string MergeSpaces(this string str)\n{\n\n if (str == null)\n {\n return null;\n }\n else\n {\n StringBuilder stringBuilder = new StringBuilder(str.Length);\n\n int i = 0;\n foreach (char c in str)\n {\n if (c != ' ' || i == 0 || str[i - 1] != ' ')\n stringBuilder.Append(c);\n i++;\n }\n return stringBuilder.ToString();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 51988575,
"author": "M.Hassan",
"author_id": 3142139,
"author_profile": "https://Stackoverflow.com/users/3142139",
"pm_score": 2,
"selected": false,
"text": "<p>Use the regex pattern </p>\n\n<pre><code> [ ]+ #only space\n\n var text = Regex.Replace(inputString, @\"[ ]+\", \" \");\n</code></pre>\n"
},
{
"answer_id": 53520268,
"author": "Patrick Artner",
"author_id": 7505395,
"author_profile": "https://Stackoverflow.com/users/7505395",
"pm_score": 1,
"selected": false,
"text": "<p>Mix of <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">StringBuilder</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">Enumerable.Aggregate()</a> as extension method for strings:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>using System;\nusing System.Linq;\nusing System.Text;\n\npublic static class StringExtension\n{\n public static string CondenseSpaces(this string s)\n {\n return s.Aggregate(new StringBuilder(), (acc, c) =>\n {\n if (c != ' ' || acc.Length == 0 || acc[acc.Length - 1] != ' ')\n acc.Append(c);\n return acc;\n }).ToString();\n }\n\n public static void Main()\n {\n const string input = " (five leading spaces) (five internal spaces) (five trailing spaces) ";\n \n Console.WriteLine(" Input: \\"{0}\\"", input);\n Console.WriteLine("Output: \\"{0}\\"", StringExtension.CondenseSpaces(input));\n }\n}\n</code></pre>\n<p>Executing this program produces the following output:</p>\n<pre class=\"lang-none prettyprint-override\"><code> Input: " (five leading spaces) (five internal spaces) (five trailing spaces) "\nOutput: " (five leading spaces) (five internal spaces) (five trailing spaces) "\n</code></pre>\n"
},
{
"answer_id": 56180189,
"author": "Code",
"author_id": 9787173,
"author_profile": "https://Stackoverflow.com/users/9787173",
"pm_score": 3,
"selected": false,
"text": "<pre><code>// Mysample string\nstring str ="hi you are a demo";\n\n//Split the words based on white sapce\nvar demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));\n \n//Join the values back and add a single space in between\nstr = string.Join(" ", demo);\n// output: string str ="hi you are a demo";\n</code></pre>\n"
},
{
"answer_id": 58849324,
"author": "Reap",
"author_id": 8705563,
"author_profile": "https://Stackoverflow.com/users/8705563",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a <em>slight modification</em> on <a href=\"https://stackoverflow.com/a/16776096/8705563\">Nolonar original answer</a>.</p>\n\n<p>Checking if the character is not just a space, but any whitespace, use this: </p>\n\n<p>It will replace any multiple whitespace character with a single space.</p>\n\n<pre><code>public static string FilterWhiteSpaces(string input)\n{\n if (input == null)\n return string.Empty;\n\n var stringBuilder = new StringBuilder(input.Length);\n for (int i = 0; i < input.Length; i++)\n {\n char c = input[i];\n if (i == 0 || !char.IsWhiteSpace(c) || (char.IsWhiteSpace(c) && \n !char.IsWhiteSpace(strValue[i - 1])))\n stringBuilder.Append(c);\n }\n return stringBuilder.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 66389169,
"author": "Giedrius",
"author_id": 212121,
"author_profile": "https://Stackoverflow.com/users/212121",
"pm_score": -1,
"selected": false,
"text": "<p>I looked over proposed solutions, could not find the one that would handle mix of white space characters acceptable for my case, for example:</p>\n<ul>\n<li><code>Regex.Replace(input, @"\\s+", " ")</code> - it will eat your line breaks, if they are mixed with spaces, for example <code>\\n \\n</code> sequence will be replaced with <code> </code></li>\n<li><code>Regex.Replace(source, @"(\\s)\\s+", "$1")</code> - it will depend on whitespace first character, meaning that it again might eat your line breaks</li>\n<li><code>Regex.Replace(source, @"[ ]{2,}", " ")</code> - it won't work correctly when there's mix of whitespace characters - for example <code>"\\t \\t "</code></li>\n</ul>\n<p>Probably not perfect, but quick solution for me was:</p>\n<pre><code>Regex.Replace(input, @"\\s+", \n(match) => match.Value.IndexOf('\\n') > -1 ? "\\n" : " ", RegexOptions.Multiline)\n</code></pre>\n<p>Idea is - line break wins over the spaces and tabs.</p>\n<p>This won't handle windows line breaks correctly, but it would be easy to adjust to work with that too, don't know regex that well - may be it is possible to fit into single pattern.</p>\n"
},
{
"answer_id": 69616112,
"author": "Demetris Leptos",
"author_id": 314320,
"author_profile": "https://Stackoverflow.com/users/314320",
"pm_score": 1,
"selected": false,
"text": "<p>How about going rogue?</p>\n<pre><code>public static string MinimizeWhiteSpace(\n this string _this)\n {\n if (_this != null)\n {\n var returned = new StringBuilder();\n var inWhiteSpace = false;\n var length = _this.Length;\n for (int i = 0; i < length; i++)\n {\n var character = _this[i];\n if (char.IsWhiteSpace(character))\n {\n if (!inWhiteSpace)\n {\n inWhiteSpace = true;\n returned.Append(' ');\n }\n }\n else\n {\n inWhiteSpace = false;\n returned.Append(character);\n }\n }\n return returned.ToString();\n }\n else\n {\n return null;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 70113294,
"author": "Bibin Gangadharan",
"author_id": 11225521,
"author_profile": "https://Stackoverflow.com/users/11225521",
"pm_score": -1,
"selected": false,
"text": "<p>The following code remove all the multiple spaces into a single space</p>\n<pre><code> public string RemoveMultipleSpacesToSingle(string str)\n {\n string text = str;\n do\n {\n //text = text.Replace(" ", " ");\n text = Regex.Replace(text, @"\\s+", " ");\n } while (text.Contains(" "));\n return text;\n }\n</code></pre>\n"
},
{
"answer_id": 71204719,
"author": "Vasilis Plavos",
"author_id": 6996666,
"author_profile": "https://Stackoverflow.com/users/6996666",
"pm_score": -1,
"selected": false,
"text": "<p>You can create a StringsExtensions file with a method like <strong>RemoveDoubleSpaces()</strong>.</p>\n<p><strong>StringsExtensions.cs</strong></p>\n<pre><code>public static string RemoveDoubleSpaces(this string value) \n{\n Regex regex = new Regex("[ ]{2,}", RegexOptions.None);\n value = regex.Replace(value, " ");\n\n // this removes space at the end of the value (like "demo ")\n // and space at the start of the value (like " hi")\n value = value.Trim(' ');\n\n return value;\n}\n</code></pre>\n<p>And then you can use it like this:</p>\n<pre><code>string stringInput =" hi here is a demo ";\n\nstring stringCleaned = stringInput.RemoveDoubleSpaces();\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
How can I replace multiple spaces in a string with only one space in C#?
Example:
```
1 2 3 4 5
```
would be:
```
1 2 3 4 5
```
|
```
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
```
|
206,718 |
<p>I want to load the data into session so that when the next button is clicked in crystal report viewer then in should load the data from the datatable instead retrieving the data again from the database. Here goes my code... </p>
<pre><code> ReportDocument rpt = new ReportDocument();
DataTable resultSet = new DataTable();
string reportpath = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString.Get("id") == "5")
{
string publication = Request.QueryString.Get("pub");
DateTime date = DateTime.Parse(Request.QueryString.Get("date"));
int pages = int.Parse(Request.QueryString.Get("pages"));
int sort = int.Parse(Request.QueryString.Get("sort"));
if (sort == 0)
{
reportpath = Server.MapPath("IssuesReport.rpt");
rpt.Load(reportpath);
DataTable resultSet1 = RetrievalProcedures.IssuesReport(date, publication, pages);
Session["Record"] = resultSet1;
}
DataTable report = (DataTable)Session["Record"];
rpt.SetDataSource(report);
CrystalReportViewer1.ReportSource = rpt;
</code></pre>
<p>I am trying this code but when i clicked the next button it gives me the error that invalid report source..i guess the session is null thats why its giving me this error.</p>
<p>Any sugesstions how can I solve this...</p>
|
[
{
"answer_id": 206739,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": true,
"text": "<p>I think you'd want to use the Cache object with a unique key for each user instead of Session here.</p>\n\n<p>Pseudo code:</p>\n\n<pre><code>var data = Cache[\"Record_999\"] as DataTable;\nif (data == null) {\n // get from db\n // insert into cache\n}\nSetDataSource(data);\n</code></pre>\n"
},
{
"answer_id": 207116,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "<p>The problem lies not in with using Session, it lies with the logic used to determine when to retrieve data. Session is the correct approach to use here as Cache is shared across requests - that is, User A would see the report User B just configured if User B was the first user to execute code that used Cache instead of Session.</p>\n\n<pre><code>if (!Page.IsPostBack)\n{\n if (Request.QueryString.Get(\"id\") == \"5\")\n {\n string publication = Request.QueryString.Get(\"pub\");\n DateTime date = DateTime.Parse(Request.QueryString.Get(\"date\"));\n int pages = int.Parse(Request.QueryString.Get(\"pages\"));\n int sort = int.Parse(Request.QueryString.Get(\"sort\"));\n // fixed the statement below to key off of session\n if (Session[\"Record\"] == null)\n {\n reportpath = Server.MapPath(\"IssuesReport.rpt\");\n rpt.Load(reportpath);\n Session[\"Record\"] = RetrievalProcedures.IssuesReport(date, publication, pages);\n }\n\n rpt.SetDataSource((DataTable)Session[\"Record\"]);\n CrystalReportViewer1.ReportSource = rpt;\n // ....\n }\n} \n</code></pre>\n"
},
{
"answer_id": 207155,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>`Could it be that sort is not 0? If sort is not 0 and the user is accessing the page for the first time(Session[\"Record\"] has not been set before) he might get the error.\nmight want to try:</p>\n\n<pre><code>if(sort==0 || Session[\"Record\"] == null)\n{\n// do your magic\n}\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
] |
I want to load the data into session so that when the next button is clicked in crystal report viewer then in should load the data from the datatable instead retrieving the data again from the database. Here goes my code...
```
ReportDocument rpt = new ReportDocument();
DataTable resultSet = new DataTable();
string reportpath = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString.Get("id") == "5")
{
string publication = Request.QueryString.Get("pub");
DateTime date = DateTime.Parse(Request.QueryString.Get("date"));
int pages = int.Parse(Request.QueryString.Get("pages"));
int sort = int.Parse(Request.QueryString.Get("sort"));
if (sort == 0)
{
reportpath = Server.MapPath("IssuesReport.rpt");
rpt.Load(reportpath);
DataTable resultSet1 = RetrievalProcedures.IssuesReport(date, publication, pages);
Session["Record"] = resultSet1;
}
DataTable report = (DataTable)Session["Record"];
rpt.SetDataSource(report);
CrystalReportViewer1.ReportSource = rpt;
```
I am trying this code but when i clicked the next button it gives me the error that invalid report source..i guess the session is null thats why its giving me this error.
Any sugesstions how can I solve this...
|
I think you'd want to use the Cache object with a unique key for each user instead of Session here.
Pseudo code:
```
var data = Cache["Record_999"] as DataTable;
if (data == null) {
// get from db
// insert into cache
}
SetDataSource(data);
```
|
206,719 |
<p>My junk mail folder has been filling up with messages composed in what appears to be the Cyrillic alphabet. If a message body or a message subject is in Cyrillic, I want to permanently delete it.</p>
<p>On my screen I see Cyrillic characters, but when I iterate through the messages in VBA within Outlook, the "Subject" property of the message returns question marks.</p>
<p>How can I determine if the subject of the message is in Cyrillic characters?</p>
<p>(Note: I have examined the "InternetCodepage" property - it's usually Western European.)</p>
|
[
{
"answer_id": 206745,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>the \"Subject\" property of the message returns a bunch of question marks.</p>\n</blockquote>\n\n<p>A classic string encoding problem. Sounds like that property is returning ASCII but you want UTF-8 or Unicode.</p>\n"
},
{
"answer_id": 206862,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 0,
"selected": false,
"text": "<p>It seems to me you have an easy solution already - just look for any subject line with (say) 5 question marks in it</p>\n"
},
{
"answer_id": 207326,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>String</code> datatype in VB/VBA can handle Unicode characters, but the IDE itself has trouble displaying them (hence the question marks). </p>\n\n<p>I wrote an <code>IsCyrillic</code> function that might help you out. The function takes a single <code>String</code> argument and returns <code>True</code> if the string contains at least one Cyrillic character. I tested this code with Outlook 2007 and it seems to work fine. To test it, I sent myself a few e-mails with Cyrillic text in the subject line and verified that my test code could correctly pick out those e-mails from among everything else in my Inbox.</p>\n\n<p>So, I actually have two code snippets:</p>\n\n<ul>\n<li>The code that contains the <code>IsCyrillic</code> function. This can be copy-pasted\ninto a new VBA module or added to\nthe code you already have.</li>\n<li>The <code>Test</code> routine I wrote (in Outlook VBA) to test that the code actually works. It demonstrates how to use the <code>IsCyrillic</code> function.</li>\n</ul>\n\n<h3>The Code</h3>\n\n<pre><code>Option Explicit\n\nPublic Const errInvalidArgument = 5\n\n' Returns True if sText contains at least one Cyrillic character'\n' NOTE: Assumes UTF-16 encoding'\n\nPublic Function IsCyrillic(ByVal sText As String) As Boolean\n\n Dim i As Long\n\n ' Loop through each char. If we hit a Cryrillic char, return True.'\n\n For i = 1 To Len(sText)\n\n If IsCharCyrillic(Mid(sText, i, 1)) Then\n IsCyrillic = True\n Exit Function\n End If\n\n Next\n\nEnd Function\n\n' Returns True if the given character is part of the Cyrillic alphabet'\n' NOTE: Assumes UTF-16 encoding'\n\nPrivate Function IsCharCyrillic(ByVal sChar As String) As Boolean\n\n ' According to the first few Google pages I found, '\n ' Cyrillic is stored at U+400-U+52f '\n\n Const CYRILLIC_START As Integer = &H400\n Const CYRILLIC_END As Integer = &H52F\n\n ' A (valid) single Unicode char will be two bytes long'\n\n If LenB(sChar) <> 2 Then\n Err.Raise errInvalidArgument, _\n \"IsCharCyrillic\", _\n \"sChar must be a single Unicode character\"\n End If\n\n ' Get Unicode value of character'\n\n Dim nCharCode As Integer\n nCharCode = AscW(sChar)\n\n ' Is char code in the range of the Cyrillic characters?'\n\n If (nCharCode >= CYRILLIC_START And nCharCode <= CYRILLIC_END) Then\n IsCharCyrillic = True\n End If\n\nEnd Function\n</code></pre>\n\n<p><br/></p>\n\n<h3>Example Usage</h3>\n\n<pre><code>' On my box, this code iterates through my Inbox. On your machine,'\n' you may have to switch to your Inbox in Outlook before running this code.'\n' I placed this code in `ThisOutlookSession` in the VBA editor. I called'\n' it in the Immediate window by typing `ThisOutlookSession.TestIsCyrillic`'\n\nPublic Sub TestIsCyrillic()\n\n Dim oItem As Object\n Dim oMailItem As MailItem\n\n For Each oItem In ThisOutlookSession.ActiveExplorer.CurrentFolder.Items\n\n If TypeOf oItem Is MailItem Then\n\n Set oMailItem = oItem\n\n If IsCyrillic(oMailItem.Subject) Then\n\n ' I just printed out the offending subject line '\n ' (it will display as ? marks, but I just '\n ' wanted to see it output something) '\n ' In your case, you could change this line to: '\n ' '\n ' oMailItem.Delete '\n ' '\n ' to actually delete the message '\n\n Debug.Print oMailItem.Subject\n\n End If\n\n End If\n\n Next\n\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16415/"
] |
My junk mail folder has been filling up with messages composed in what appears to be the Cyrillic alphabet. If a message body or a message subject is in Cyrillic, I want to permanently delete it.
On my screen I see Cyrillic characters, but when I iterate through the messages in VBA within Outlook, the "Subject" property of the message returns question marks.
How can I determine if the subject of the message is in Cyrillic characters?
(Note: I have examined the "InternetCodepage" property - it's usually Western European.)
|
The `String` datatype in VB/VBA can handle Unicode characters, but the IDE itself has trouble displaying them (hence the question marks).
I wrote an `IsCyrillic` function that might help you out. The function takes a single `String` argument and returns `True` if the string contains at least one Cyrillic character. I tested this code with Outlook 2007 and it seems to work fine. To test it, I sent myself a few e-mails with Cyrillic text in the subject line and verified that my test code could correctly pick out those e-mails from among everything else in my Inbox.
So, I actually have two code snippets:
* The code that contains the `IsCyrillic` function. This can be copy-pasted
into a new VBA module or added to
the code you already have.
* The `Test` routine I wrote (in Outlook VBA) to test that the code actually works. It demonstrates how to use the `IsCyrillic` function.
### The Code
```
Option Explicit
Public Const errInvalidArgument = 5
' Returns True if sText contains at least one Cyrillic character'
' NOTE: Assumes UTF-16 encoding'
Public Function IsCyrillic(ByVal sText As String) As Boolean
Dim i As Long
' Loop through each char. If we hit a Cryrillic char, return True.'
For i = 1 To Len(sText)
If IsCharCyrillic(Mid(sText, i, 1)) Then
IsCyrillic = True
Exit Function
End If
Next
End Function
' Returns True if the given character is part of the Cyrillic alphabet'
' NOTE: Assumes UTF-16 encoding'
Private Function IsCharCyrillic(ByVal sChar As String) As Boolean
' According to the first few Google pages I found, '
' Cyrillic is stored at U+400-U+52f '
Const CYRILLIC_START As Integer = &H400
Const CYRILLIC_END As Integer = &H52F
' A (valid) single Unicode char will be two bytes long'
If LenB(sChar) <> 2 Then
Err.Raise errInvalidArgument, _
"IsCharCyrillic", _
"sChar must be a single Unicode character"
End If
' Get Unicode value of character'
Dim nCharCode As Integer
nCharCode = AscW(sChar)
' Is char code in the range of the Cyrillic characters?'
If (nCharCode >= CYRILLIC_START And nCharCode <= CYRILLIC_END) Then
IsCharCyrillic = True
End If
End Function
```
### Example Usage
```
' On my box, this code iterates through my Inbox. On your machine,'
' you may have to switch to your Inbox in Outlook before running this code.'
' I placed this code in `ThisOutlookSession` in the VBA editor. I called'
' it in the Immediate window by typing `ThisOutlookSession.TestIsCyrillic`'
Public Sub TestIsCyrillic()
Dim oItem As Object
Dim oMailItem As MailItem
For Each oItem In ThisOutlookSession.ActiveExplorer.CurrentFolder.Items
If TypeOf oItem Is MailItem Then
Set oMailItem = oItem
If IsCyrillic(oMailItem.Subject) Then
' I just printed out the offending subject line '
' (it will display as ? marks, but I just '
' wanted to see it output something) '
' In your case, you could change this line to: '
' '
' oMailItem.Delete '
' '
' to actually delete the message '
Debug.Print oMailItem.Subject
End If
End If
Next
End Sub
```
|
206,734 |
<p>The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from <code>the_base_class</code>.</p>
<pre><code>class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
</code></pre>
<p>Defining <code>self.somedata</code> in the <code>__init__</code> function is obviously the correct way to get around this (so each class has it's own <code>somedata</code> dict) - but when is such behavior desirable?</p>
|
[
{
"answer_id": 206765,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 6,
"selected": true,
"text": "<p>You are right, <code>somedata</code> is shared between all instances of the class and it's subclasses, because it is created at class <em>definition</em> time. The lines </p>\n\n<pre><code>somedata = {}\nsomedata['was_false_in_base'] = False\n</code></pre>\n\n<p>are executed when the class is defined, i.e. when the interpreter encounters the <code>class</code> statement - <strong>not</strong> when the instance is created (think static initializer blocks in Java). If an attribute does not exist in a class instance, the class object is checked for the attribute.</p>\n\n<p>At class definition time, you can run arbritrary code, like this:</p>\n\n<pre><code> import sys\n class Test(object):\n if sys.platform == \"linux2\":\n def hello(self):\n print \"Hello Linux\"\n else:\n def hello(self):\n print \"Hello ~Linux\"\n</code></pre>\n\n<p>On a Linux system, <code>Test().hello()</code> will print <code>Hello Linux</code>, on all other systems the other string will be printed.</p>\n\n<p>In constrast, objects in <code>__init__</code> are created at <em>instantiation</em> time and belong to the instance only (when they are assigned to <code>self</code>):</p>\n\n<pre><code>class Test(object):\n def __init__(self):\n self.inst_var = [1, 2, 3]\n</code></pre>\n\n<p>Objects defined on a class object rather than instance can be useful in many cases. For instance, you might want to cache instances of your class, so that instances with the same member values can be shared (assuming they are supposed to be immutable):</p>\n\n<pre><code>class SomeClass(object):\n __instances__ = {}\n\n def __new__(cls, v1, v2, v3):\n try:\n return cls.__insts__[(v1, v2, v3)]\n except KeyError:\n return cls.__insts__.setdefault(\n (v1, v2, v3), \n object.__new__(cls, v1, v2, v3))\n</code></pre>\n\n<p>Mostly, I use data in class bodies in conjunction with metaclasses or generic factory methods.</p>\n"
},
{
"answer_id": 206800,
"author": "TimB",
"author_id": 4193,
"author_profile": "https://Stackoverflow.com/users/4193",
"pm_score": 4,
"selected": false,
"text": "<p>Note that part of the behavior you’re seeing is due to <code>somedata</code> being a <code>dict</code>, as opposed to a simple data type such as a <code>bool</code>.</p>\n\n<p>For instance, see this different example which behaves differently (although very similar):</p>\n\n<pre><code>class the_base_class:\n somedata = False\n\nclass subclassthing(the_base_class):\n def __init__(self):\n print self.somedata\n\n\n>>> first = subclassthing()\nFalse\n>>> first.somedata = True\n>>> print first.somedata\nTrue\n>>> second = subclassthing()\nFalse\n>>> print first.somedata\nTrue\n>>> del first\n>>> del second\n>>> third = subclassthing()\nFalse\n</code></pre>\n\n<p>The reason this example behaves differently from the one given in the question is because here <code>first.somedata</code> is being given a new value (the object <code>True</code>), whereas in the first example the dict object referenced by <code>first.somedata</code> (and also by the other subclass instances) is being modified.</p>\n\n<p>See Torsten Marek’s comment to this answer for further clarification.</p>\n"
},
{
"answer_id": 206840,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 2,
"selected": false,
"text": "<p>I think the easiest way to understand this (so that you can predict behavior) is to realize that your <code>somedata</code> is an attribute of the class and not the instance of that class if you define it that way.</p>\n\n<p>There is really only one <code>somedata</code> at all times because in your example you didn't assign to that name but used it to look up a dict and then assign an item (key, value) to it. It's a gotcha that is a consequence of how the python interpreter works and can be confusing at first.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from `the_base_class`.
```
class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
```
Defining `self.somedata` in the `__init__` function is obviously the correct way to get around this (so each class has it's own `somedata` dict) - but when is such behavior desirable?
|
You are right, `somedata` is shared between all instances of the class and it's subclasses, because it is created at class *definition* time. The lines
```
somedata = {}
somedata['was_false_in_base'] = False
```
are executed when the class is defined, i.e. when the interpreter encounters the `class` statement - **not** when the instance is created (think static initializer blocks in Java). If an attribute does not exist in a class instance, the class object is checked for the attribute.
At class definition time, you can run arbritrary code, like this:
```
import sys
class Test(object):
if sys.platform == "linux2":
def hello(self):
print "Hello Linux"
else:
def hello(self):
print "Hello ~Linux"
```
On a Linux system, `Test().hello()` will print `Hello Linux`, on all other systems the other string will be printed.
In constrast, objects in `__init__` are created at *instantiation* time and belong to the instance only (when they are assigned to `self`):
```
class Test(object):
def __init__(self):
self.inst_var = [1, 2, 3]
```
Objects defined on a class object rather than instance can be useful in many cases. For instance, you might want to cache instances of your class, so that instances with the same member values can be shared (assuming they are supposed to be immutable):
```
class SomeClass(object):
__instances__ = {}
def __new__(cls, v1, v2, v3):
try:
return cls.__insts__[(v1, v2, v3)]
except KeyError:
return cls.__insts__.setdefault(
(v1, v2, v3),
object.__new__(cls, v1, v2, v3))
```
Mostly, I use data in class bodies in conjunction with metaclasses or generic factory methods.
|
206,735 |
<p>I need a SQL query that returns ContactDate, SortName, City, ContactType, and Summary from the tables below. If any value is null, I need it to return the text “No Entry”.</p>
<p><strong>ContactTable</strong></p>
<ul>
<li><em>ContactID</em></li>
<li>ContactDate </li>
<li>UserID </li>
<li>Summary </li>
<li>ContactType</li>
<li>SortName</li>
</ul>
<p><strong>UserTable</strong></p>
<ul>
<li><em>UserID</em></li>
<li>FirstName</li>
<li>LastName </li>
<li>AddressID</li>
</ul>
<p><strong>AddressTable</strong></p>
<ul>
<li><em>AddressID</em></li>
<li>City</li>
<li>Street </li>
<li>State</li>
<li>Zip</li>
</ul>
|
[
{
"answer_id": 206752,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT COALESCE(CAST(CONVERT(VARCHAR(10), ContactTable.ContactDate, 101) AS VARCHAR(10)), 'No Entry') AS ContactDate,\n COALESCE(ContactTable.SortName, 'No Entry') AS SortName,\n COALESCE(AddressTable.City, 'No Entry') AS City,\n COALESCE(ContactTable.ContactType, 'No Entry') AS ContactType\nFROM ContactTable\nLEFT OUTER JOIN UserTable ON ContactTable.UserID = UserTable.UserID\nLEFT OUTER JOIN AddressTable ON UserTable.AddressID = AddressTable.AddressID\n</code></pre>\n\n<p><a href=\"http://www.blackwasp.co.uk/SQLDateTimeFormats.aspx\" rel=\"noreferrer\">Here</a> is a chart of SQL DateTime formats for the CONVERT statement above.</p>\n"
},
{
"answer_id": 206754,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT \n ISNULL(ContactDate, 'No Entry') AS ContactDate\nFROM Table\n</code></pre>\n\n<p>Using ISNULL is pretty simple.</p>\n"
},
{
"answer_id": 206761,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 3,
"selected": false,
"text": "<p>COALESCE() on any platform that is worth its weight in salt.</p>\n\n<p>Make sure to handle casting issues.</p>\n\n<p>Such as:</p>\n\n<pre><code>--(SQL Server)\nSELECT\n C.ContactID,\n COALESCE(CAST(CONVERT(varchar(10), C.ContactDate, 101) AS varchar(10), 'No Entry') AS ContactDate,\n COALESCE(SorName, 'No Entry') AS SortName\n</code></pre>\n\n<p>etc., etc.</p>\n"
},
{
"answer_id": 206993,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 0,
"selected": false,
"text": "<p>Using '<strong>IIF</strong>' is an Access DB solution but may work in other DBs.</p>\n\n<pre><code>SELECT IIF(IsNull(Foo), 'No Entry' ,Foo), IIF(IsNull(Bar), 'No Entry' ,Bar) From TableName \n</code></pre>\n\n<p>The function IIF returns one of 2 values depends of the evaluation of an expression.<br>\nSQL Syntax:\n IIF( expression, true-value1, false-value ) </p>\n"
},
{
"answer_id": 207005,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 1,
"selected": false,
"text": "<p>The Oracle version of this function is called <code>nvl</code>. Same usage -- <code>SELECT nvl(col_name, desired_value) FROM foo</code>.</p>\n\n<p>The more general version of this is <code>decode</code>, which has three parameters and allows you to specify which column value you want to perform a replacement for (so you can replace all 'Johnny' with 'John' or something).</p>\n"
},
{
"answer_id": 207204,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>You can also make different calls for each column. It will take more individual calls, but it may be faster if you don't have many rows to update.</p>\n\n<pre>\nupdate ContactTable\nset ContactDate = 'No Entry'\nwhere ContactDate is null;\n</pre>\n\n<p>Repeat for each column.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8900/"
] |
I need a SQL query that returns ContactDate, SortName, City, ContactType, and Summary from the tables below. If any value is null, I need it to return the text “No Entry”.
**ContactTable**
* *ContactID*
* ContactDate
* UserID
* Summary
* ContactType
* SortName
**UserTable**
* *UserID*
* FirstName
* LastName
* AddressID
**AddressTable**
* *AddressID*
* City
* Street
* State
* Zip
|
```
SELECT COALESCE(CAST(CONVERT(VARCHAR(10), ContactTable.ContactDate, 101) AS VARCHAR(10)), 'No Entry') AS ContactDate,
COALESCE(ContactTable.SortName, 'No Entry') AS SortName,
COALESCE(AddressTable.City, 'No Entry') AS City,
COALESCE(ContactTable.ContactType, 'No Entry') AS ContactType
FROM ContactTable
LEFT OUTER JOIN UserTable ON ContactTable.UserID = UserTable.UserID
LEFT OUTER JOIN AddressTable ON UserTable.AddressID = AddressTable.AddressID
```
[Here](http://www.blackwasp.co.uk/SQLDateTimeFormats.aspx) is a chart of SQL DateTime formats for the CONVERT statement above.
|
206,751 |
<p>I have a couple tables in which I created an object ID as either an Int or Bigint, and in both cases, they seem to autoincrement by 10 (ie, the first insert is object ID 1, the second is object ID 11, the third is object ID 21, etc). Two questions:</p>
<ol>
<li><p>Why does it do that?</p></li>
<li><p>Is that a problem?</p></li>
</ol>
|
[
{
"answer_id": 206769,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 6,
"selected": false,
"text": "<p>Check to see the seed value of the autoincrement isn't set to 10.</p>\n\n<p>You can check by:</p>\n\n<pre><code>SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want';\n</code></pre>\n\n<p>As noted elsewhere you can change by using the system variable @@set_auto_increment_increment</p>\n\n<pre><code>SET @@auto_increment_increment=1;\n</code></pre>\n\n<p>If you want to start the values at a number other than one you can go:</p>\n\n<pre><code>ALTER TABLE tbl AUTO_INCREMENT = 100;\n</code></pre>\n"
},
{
"answer_id": 206781,
"author": "Jim Fiorato",
"author_id": 650,
"author_profile": "https://Stackoverflow.com/users/650",
"pm_score": 3,
"selected": false,
"text": "<p>The auto increment increment value is set in the MySQL system variables.</p>\n\n<p>See here:\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#option_mysqld_auto-increment-increment\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#option_mysqld_auto-increment-increment</a></p>\n"
},
{
"answer_id": 20558038,
"author": "user427969",
"author_id": 427969,
"author_profile": "https://Stackoverflow.com/users/427969",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks @Jim Fiorato for providing the link.</p>\n\n<p>To check how much the auto increment value increments by, use the following query:</p>\n\n<pre><code>SHOW VARIABLES LIKE 'auto_inc%';\n\n+--------------------------+-------+\n| Variable_name | Value |\n+--------------------------+-------+\n| auto_increment_increment | 10 |\n| auto_increment_offset | 4 |\n+--------------------------+-------+\n</code></pre>\n"
},
{
"answer_id": 31969004,
"author": "user1709374",
"author_id": 1709374,
"author_profile": "https://Stackoverflow.com/users/1709374",
"pm_score": 6,
"selected": false,
"text": "<p>Please do not change the <code>auto_increment_increment</code>. ClearDB is doing this on purpose. It's explained in <a href=\"https://www.cleardb.com/developers/help/faq#general_16\" rel=\"noreferrer\">the documentation</a>:</p>\n\n<blockquote>\n <p>ClearDB uses circular replication to provide master-master MySQL\n support. As such, certain things such as auto_increment keys (or\n sequences) must be configured in order for one master not to use the\n same key as the other, in all cases. We do this by configuring MySQL\n to skip certain keys, and by enforcing MySQL to use a specific offset\n for each key used. The reason why we use a value of 10 instead of 2 is\n for future development.</p>\n</blockquote>\n"
},
{
"answer_id": 41527360,
"author": "kimon",
"author_id": 7389111,
"author_profile": "https://Stackoverflow.com/users/7389111",
"pm_score": 1,
"selected": false,
"text": "<p>autoincriment value can jump if using insert with IGNORE attribute in case when record was not created</p>\n\n<pre><code>insert IGNORE into my_table set column=1\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a couple tables in which I created an object ID as either an Int or Bigint, and in both cases, they seem to autoincrement by 10 (ie, the first insert is object ID 1, the second is object ID 11, the third is object ID 21, etc). Two questions:
1. Why does it do that?
2. Is that a problem?
|
Check to see the seed value of the autoincrement isn't set to 10.
You can check by:
```
SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want';
```
As noted elsewhere you can change by using the system variable @@set\_auto\_increment\_increment
```
SET @@auto_increment_increment=1;
```
If you want to start the values at a number other than one you can go:
```
ALTER TABLE tbl AUTO_INCREMENT = 100;
```
|
206,767 |
<p>I want to implement forms authentication on an ASP.NET website, the site should seek the user on the database to get some data and then authenticate against LDAP (Active Directory) to validate the user/password combo.</p>
<p>After that I need to keep a instance of class that represents the user to use it in various forms.</p>
<p>I tried to do it before with a login control, that checks the previous conditions and do an <code>AuthenticateEventArgs.Authenticated = true</code> and placed the object inside the session: <code>Session ["user"] = authenticatedUser;</code> but I had problem synchronizing both of them (the session expired before the auth cookie and I got NullReferenceExceptions when the pages tried to use the now defunct session object).</p>
<p>Which is the best way to accomplish this? Is there some way to sync the session timeout with the cookie lifespan? The user object should be saved in any other way? Did I miss the point?</p>
<p><b>UPDATE:
I cannot use windows auth provider because the site should be accesible from outside out priate network.
</b></p>
|
[
{
"answer_id": 206773,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": true,
"text": "<p>I would use Windows Authentication as the main authentication provider, but roll my own simple database persistence for user information.</p>\n\n<p>Your session method would work, you can adjust session timeout in IIS and match it to the authentication cookie timeout.</p>\n\n<p>Also, you can do something like this in a HTTPModule to catch edge cases (app pool recycles etc) that also clear session</p>\n\n<p>Psuedocode:</p>\n\n<pre><code>if (session[\"user\"] == null)\n{\n Authentication.SignOut();\n}\n</code></pre>\n\n<p>This would force the user to authenticate.</p>\n"
},
{
"answer_id": 206972,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>I set the session and auth cookie timeout values to the same value. I use sliding windows for my auth cookie. I also make it a habit to never assume that values I get out of the session are non-null before attempting to use them. I often abstract all of the session functionality out into a proxy class that contains strongly typed properties for the values I store in the session. The error handling for bad session data is localized in the proxy. </p>\n"
},
{
"answer_id": 211451,
"author": "Bryan",
"author_id": 22033,
"author_profile": "https://Stackoverflow.com/users/22033",
"pm_score": 0,
"selected": false,
"text": "<p>Storing the user info in the session will work fine. To sync session timeout and auth cookie timeout, just edit your web.config:</p>\n\n<pre><code><sessionState timeout=\"XX\" />\n<authentication mode=\"Forms\">\n <forms loginUrl=\"Login.aspx\" timeout=\"XX\" />\n</authentication>\n</code></pre>\n\n<p>Both values are in minutes. </p>\n\n<p>Test for null EVERY time you get a value from the Session!</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23020/"
] |
I want to implement forms authentication on an ASP.NET website, the site should seek the user on the database to get some data and then authenticate against LDAP (Active Directory) to validate the user/password combo.
After that I need to keep a instance of class that represents the user to use it in various forms.
I tried to do it before with a login control, that checks the previous conditions and do an `AuthenticateEventArgs.Authenticated = true` and placed the object inside the session: `Session ["user"] = authenticatedUser;` but I had problem synchronizing both of them (the session expired before the auth cookie and I got NullReferenceExceptions when the pages tried to use the now defunct session object).
Which is the best way to accomplish this? Is there some way to sync the session timeout with the cookie lifespan? The user object should be saved in any other way? Did I miss the point?
**UPDATE:
I cannot use windows auth provider because the site should be accesible from outside out priate network.**
|
I would use Windows Authentication as the main authentication provider, but roll my own simple database persistence for user information.
Your session method would work, you can adjust session timeout in IIS and match it to the authentication cookie timeout.
Also, you can do something like this in a HTTPModule to catch edge cases (app pool recycles etc) that also clear session
Psuedocode:
```
if (session["user"] == null)
{
Authentication.SignOut();
}
```
This would force the user to authenticate.
|
206,770 |
<p>In a previous question, I learned how to keep a footer div at the bottom of the page. (<a href="https://stackoverflow.com/questions/206652/how-to-create-div-to-fill-all-space-between-header-and-footer-div">see other question</a>)</p>
<p>Now I'm trying to vertically center content between the header and footer divs.</p>
<p>so what I've got is:</p>
<pre><code>#divHeader
{
height: 50px;
}
#divContent
{
position:absolute;
}
#divFooter
{
height: 50px;
position:absolute;
bottom:0;
width:100%;
}
<div id="divHeader">
Header
</div>
<div id="divContent">
Content
</div>
<div id="divFooter">
Footer
</div>
</code></pre>
<p>I've tried creating a parent div to house the existing 3 divs and giving that div a vertical-align:middle; but that gets me nowhere.</p>
|
[
{
"answer_id": 206812,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>You need to either set the <code>height</code> of the div to fill the whole content area or its coordinates have to be in the center. Something like <code>top:50%; left:50%</code> but of course that will make the div a bit off to the bottom-right.</p>\n"
},
{
"answer_id": 206827,
"author": "abahgat",
"author_id": 27565,
"author_profile": "https://Stackoverflow.com/users/27565",
"pm_score": 1,
"selected": false,
"text": "<p>In alternative, as far as I remember, you can using hacks like <a href=\"http://www.jakpsatweb.cz/css/priklady/vertical-align-final-solution-en.html\" rel=\"nofollow noreferrer\">this</a> (more info <a href=\"http://www.jakpsatweb.cz/css/css-vertical-center-solution.html\" rel=\"nofollow noreferrer\">here</a>).</p>\n"
},
{
"answer_id": 207172,
"author": "CoolGravatar",
"author_id": 24059,
"author_profile": "https://Stackoverflow.com/users/24059",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe try:</p>\n\n<pre>\n#divHeader\n{\n height: 50px;\n}\n\n#divContent\n{\n /*position:absolute;*/\n width: 900px;\n margin-left: auto;\n margin-right: auto;\n}\n\n#divFooter\n{\n height: 50px;\n position:absolute;\n bottom:0;\n width:100%;\n}\n</pre>\n"
},
{
"answer_id": 209729,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": true,
"text": "<p>In CSS2:</p>\n\n<pre><code>html,body {height:100%;}\nbody {display:table;}\ndiv {display:table-row;}\n#content {\n display:table-cell;\n vertical-align:middle;\n}\n</code></pre>\n\n<p>&</p>\n\n<pre><code><body>\n<div>header</div>\n<div id=\"content\">content</div>\n<div>footer</div>\n</body>\n</code></pre>\n\n<p><a href=\"http://codepen.io/anon/pen/doMwvJ\" rel=\"nofollow noreferrer\">http://codepen.io/anon/pen/doMwvJ</a></p>\n\n<p>In old IE (<=7) you have to use trick with absolute positioning that marxidad mentioned.</p>\n\n<p>And in latest browsers <a href=\"http://flexboxin5.com/\" rel=\"nofollow noreferrer\">you can use flexbox instead</a>.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
In a previous question, I learned how to keep a footer div at the bottom of the page. ([see other question](https://stackoverflow.com/questions/206652/how-to-create-div-to-fill-all-space-between-header-and-footer-div))
Now I'm trying to vertically center content between the header and footer divs.
so what I've got is:
```
#divHeader
{
height: 50px;
}
#divContent
{
position:absolute;
}
#divFooter
{
height: 50px;
position:absolute;
bottom:0;
width:100%;
}
<div id="divHeader">
Header
</div>
<div id="divContent">
Content
</div>
<div id="divFooter">
Footer
</div>
```
I've tried creating a parent div to house the existing 3 divs and giving that div a vertical-align:middle; but that gets me nowhere.
|
In CSS2:
```
html,body {height:100%;}
body {display:table;}
div {display:table-row;}
#content {
display:table-cell;
vertical-align:middle;
}
```
&
```
<body>
<div>header</div>
<div id="content">content</div>
<div>footer</div>
</body>
```
<http://codepen.io/anon/pen/doMwvJ>
In old IE (<=7) you have to use trick with absolute positioning that marxidad mentioned.
And in latest browsers [you can use flexbox instead](http://flexboxin5.com/).
|
206,775 |
<p>I am trying to detect which web in sharepoint that the user is looking at right now. One approach could be to read the URls from the browser and try to compare them to a reference URL to the sharepoint solution. I have not yet been able to locate any solution that works in both IE and Firefox.</p>
<p>The idea is to write a small C# app that will harvest the URLs and do the comparing. </p>
<p>TIA</p>
|
[
{
"answer_id": 206784,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 1,
"selected": false,
"text": "<p>You are unlikely to find such an answer. All modern browsers restrict the ability of JavaScript on a page to access such info as it poses such a big privacy risk to the user.</p>\n"
},
{
"answer_id": 206829,
"author": "Parappa",
"author_id": 9974,
"author_profile": "https://Stackoverflow.com/users/9974",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible to do this in a very hacky and prone to breakage way using the Win32 API function FindWindow.</p>\n\n<p>The following C++ example that finds a running instance of the windows Calculator and gets the value of the edit field in it. You should be able to do something similar in C#. Disclaimer: I haven't actually checked to make sure this code compiles, sorry. :)</p>\n\n<pre><code>float GetCalcResult(void)\n{\n float retval = 0.0f;\n\n HWND calc= FindWindow(\"SciCalc\", \"Calculator\");\n if (calc == NULL) {\n calc= FindWindow(\"Calc\", \"Calculator\");\n }\n if (calc == NULL) {\n MessageBox(NULL, \"calculator not found\", \"Error\", MB_OK);\n return 0.0f;\n }\n HWND calcEdit = FindWindowEx(calc, 0, \"Edit\", NULL);\n if (calcEdit == NULL) {\n MessageBox(NULL, \"error finding calc edit box\", \"Error\", MB_OK);\n return 0.0f;\n }\n\n long len = SendMessage(calcEdit, WM_GETTEXTLENGTH, 0, 0) + 1;\n char* temp = (char*) malloc(len);\n SendMessage(calcEdit, WM_GETTEXT, len, (LPARAM) temp);\n retval = atof(temp);\n free(temp);\n\n return retval;\n}\n</code></pre>\n\n<p>In order to find out the right parameters to use in FindWindow and FindWindowEx, use the Visual Studio tool Spy++ to inspect a running instance of your browser window. Sorry, I don't have a code sample for web browsers on-hand, but it should be possible. Note that your solution will be Windows OS specific, and also changes to the UI architecture in future versions of the web browsers could cause your solution to stop working.</p>\n\n<p>Using this method to lift the URL right out of the address bar obviously only works for the current tab. I can't see how this would work for all tabs unless you did something really tricky like simulating user input to cycle through the tabs. That would be very intrusive and a user could easily mess up your application by interrupting it with input of their own, but it might work if you're writing something that runs unattended, like an automated test script. If that is the case, you may want to look into other tools like <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt</a>.</p>\n\n<p>This advice is all paraphrased from a <a href=\"http://www.elenkist.com/bushido_burrito/blog/?p=15\" rel=\"nofollow noreferrer\">blog post</a> I once wrote. Good luck!</p>\n"
},
{
"answer_id": 218771,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Just off the top of my head, you might consider using the built-in Firefox language (no idea what it's called). I'm sure it provides a mechanism to do exactally what you talking about. Otherwise those plugin's written for delicious, etc, wouldn't work.</p>\n\n<p>As for IE, you're going to need to either do it in C++ or find some managed wrapper for this. I'm not sure how to make an IE plugin, but if you dig deep enough, you should be able to find something.</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 13121936,
"author": "Sameer",
"author_id": 1782948,
"author_profile": "https://Stackoverflow.com/users/1782948",
"pm_score": 2,
"selected": false,
"text": "<p>Its fairly easy in IE using the ActiveX shell application object in Javascript. Below is the sample code:</p>\n\n<pre><code>function GetURL()\n{\n var oShell = new ActiveXObject('shell.application');\n var oColl = oShell.Windows();\n for (var i = 0;i<oColl.count;i++)\n {\n try\n {\n var Title = oColl(i).document.title;\n if (Title.indexOf('DesiredTitle') != -1)\n {\n alert ('Title-'+oColl(i).document.title);\n alert ('Location-'+oColl(i).location);\n }\n }\n catch (err)\n {\n alert (err);\n }\n }\n}\n</code></pre>\n\n<p>I am still trying to find out a way in firefox.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23499/"
] |
I am trying to detect which web in sharepoint that the user is looking at right now. One approach could be to read the URls from the browser and try to compare them to a reference URL to the sharepoint solution. I have not yet been able to locate any solution that works in both IE and Firefox.
The idea is to write a small C# app that will harvest the URLs and do the comparing.
TIA
|
It is possible to do this in a very hacky and prone to breakage way using the Win32 API function FindWindow.
The following C++ example that finds a running instance of the windows Calculator and gets the value of the edit field in it. You should be able to do something similar in C#. Disclaimer: I haven't actually checked to make sure this code compiles, sorry. :)
```
float GetCalcResult(void)
{
float retval = 0.0f;
HWND calc= FindWindow("SciCalc", "Calculator");
if (calc == NULL) {
calc= FindWindow("Calc", "Calculator");
}
if (calc == NULL) {
MessageBox(NULL, "calculator not found", "Error", MB_OK);
return 0.0f;
}
HWND calcEdit = FindWindowEx(calc, 0, "Edit", NULL);
if (calcEdit == NULL) {
MessageBox(NULL, "error finding calc edit box", "Error", MB_OK);
return 0.0f;
}
long len = SendMessage(calcEdit, WM_GETTEXTLENGTH, 0, 0) + 1;
char* temp = (char*) malloc(len);
SendMessage(calcEdit, WM_GETTEXT, len, (LPARAM) temp);
retval = atof(temp);
free(temp);
return retval;
}
```
In order to find out the right parameters to use in FindWindow and FindWindowEx, use the Visual Studio tool Spy++ to inspect a running instance of your browser window. Sorry, I don't have a code sample for web browsers on-hand, but it should be possible. Note that your solution will be Windows OS specific, and also changes to the UI architecture in future versions of the web browsers could cause your solution to stop working.
Using this method to lift the URL right out of the address bar obviously only works for the current tab. I can't see how this would work for all tabs unless you did something really tricky like simulating user input to cycle through the tabs. That would be very intrusive and a user could easily mess up your application by interrupting it with input of their own, but it might work if you're writing something that runs unattended, like an automated test script. If that is the case, you may want to look into other tools like [AutoIt](http://www.autoitscript.com/autoit3/).
This advice is all paraphrased from a [blog post](http://www.elenkist.com/bushido_burrito/blog/?p=15) I once wrote. Good luck!
|
206,783 |
<p>I have a JavaScript resource that has the possibility of being edited at any time. Once it is edited I would want it to be propagated to the user's browser relatively quickly (like maybe 15 minutes or so), however, the frequency of this resource being editing is few and far between (maybe 2 a month).</p>
<p>I'd rather the resource to be cached in the browser, since it will be retrieved frequently, but I'd also like the cache to get reset on the browser at a semi-regular interval.</p>
<p>I know I can pass a no-cache header when I request for the resource, but I was wondering when the cache would automatically reset itself on the browser if I did not pass no-cache.</p>
<p>I imagine this would be independent for each browser, but I'm not sure.</p>
<p>I tried to Google this, but most of the hits I found were about clearing the browser's cache... which isn't what I'm looking for.</p>
|
[
{
"answer_id": 206789,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 4,
"selected": false,
"text": "<p>Put a version on your javascript code like this that is updated when you make a change</p>\n\n<pre><code><script src=\"/code.js?ver=123\" type=\"text/javascript\"></script>\n</code></pre>\n\n<p>They will then always get new version.</p>\n"
},
{
"answer_id": 206821,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 4,
"selected": false,
"text": "<p>HTTP provides several controls for caching that browsers ignore in different ways. If you set a reasonable expiration date, most browsers will check to see if they have the current version are appropriate frequencies.</p>\n\n<p>The search term you want to include here (to avoid browser user instructions) is HTTP.</p>\n\n<p>For more see: </p>\n\n<ul>\n<li><a href=\"http://www.mnot.net/cache_docs/\" rel=\"noreferrer\">Caching Tutorial for Web Authors and Webmasters</a></li>\n<li><a href=\"http://www.web-caching.com/mnot_tutorial/how.html\" rel=\"noreferrer\">How Web Caches Work</a> (a little old, but still useful).</li>\n<li><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html\" rel=\"noreferrer\">HTTP/1.1: Caching in HTTP</a></li>\n</ul>\n"
},
{
"answer_id": 207861,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 7,
"selected": true,
"text": "<p>You may pass a version string as a get parameter to the URL of your script tag. The parameter won't be evaluated by the static JavaScript file but force the browser to get the new version. </p>\n\n<p>If you do not want to assign the version string every time you edited the source you may compute it based on the file system time stamp or your subversion commit number:</p>\n\n<pre><code><script src=\"/script.js?time_stamp=1224147832156\" type=\"text/javascript\"></script>\n<script src=\"/script.js?svn_version=678\" type=\"text/javascript\"></script>\n</code></pre>\n\n<p> </p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
I have a JavaScript resource that has the possibility of being edited at any time. Once it is edited I would want it to be propagated to the user's browser relatively quickly (like maybe 15 minutes or so), however, the frequency of this resource being editing is few and far between (maybe 2 a month).
I'd rather the resource to be cached in the browser, since it will be retrieved frequently, but I'd also like the cache to get reset on the browser at a semi-regular interval.
I know I can pass a no-cache header when I request for the resource, but I was wondering when the cache would automatically reset itself on the browser if I did not pass no-cache.
I imagine this would be independent for each browser, but I'm not sure.
I tried to Google this, but most of the hits I found were about clearing the browser's cache... which isn't what I'm looking for.
|
You may pass a version string as a get parameter to the URL of your script tag. The parameter won't be evaluated by the static JavaScript file but force the browser to get the new version.
If you do not want to assign the version string every time you edited the source you may compute it based on the file system time stamp or your subversion commit number:
```
<script src="/script.js?time_stamp=1224147832156" type="text/javascript"></script>
<script src="/script.js?svn_version=678" type="text/javascript"></script>
```
|
206,788 |
<p>I've installed the Windows XAMPP package on three separate computers, 2 running Windows Vista 32 bit ( 1 Ultimate / 1 Home Premium ) and 1 running Windows Vista 64 Home Premium.</p>
<p>After enabling xdebug in php.ini and restarting apache, viewing the default XAMPP localhost index causes apache to crash in the same way every time, reporting 'php_xdebug.dll' as the Fault Module Name.</p>
<p>Here's the full report from the Windows Crash Reporter thing:</p>
<pre><code>Problem signature:
Problem Event Name: APPCRASH
Application Name: apache.exe
Application Version: 2.2.9.0
Application Timestamp: 4853f994
Fault Module Name: php_xdebug.dll
Fault Module Version: 2.0.3.0
Fault Module Timestamp: 47fcd9b9
Exception Code: c0000005
Exception Offset: 00008493
OS Version: 6.0.6001.2.1.0.768.3
Locale ID: 1033
Additional Information 1: a34a
Additional Information 2: c9c5f4fd744690d388ab9d5b3eb051a7
Additional Information 3: cb2e
Additional Information 4: 650bb5690556a17e911375b94d3e16f0
</code></pre>
<p>I've tried Googling this issue but haven't found any resolution, only reports of similar errors. </p>
<p>EDIT: I enabled the extension line for php_xdebug.dll and that seems to have stopped the crashing so far. </p>
|
[
{
"answer_id": 261492,
"author": "user34052",
"author_id": 34052,
"author_profile": "https://Stackoverflow.com/users/34052",
"pm_score": 1,
"selected": false,
"text": "<p>Via some other forum I found a possible hint - while generally apache on xampp uses the php.ini that is inside the apache/bin directory, some modules don't. So I toyed around with the php.ini in that directory (simply moving it out of harms way worked for me so far, as in renaming/deleting it). Might wanna give it a try at least.</p>\n"
},
{
"answer_id": 454334,
"author": "Nikola Stjelja",
"author_id": 32582,
"author_profile": "https://Stackoverflow.com/users/32582",
"pm_score": 1,
"selected": false,
"text": "<p>I found the solution for this problem. You can find it here: <a href=\"http://wiki.mpsoftware.dk/index.php?title=Tutorial_on_how_to_configure_Xdebug_to_work_with_phpDesigner_2008\" rel=\"nofollow noreferrer\">http://wiki.mpsoftware.dk/index.php?title=Tutorial_on_how_to_configure_Xdebug_to_work_with_phpDesigner_2008</a></p>\n\n<p>The problem is that XDebug is not compatible with Zend optimizer so you need to comment all sections under the [Zend] section.</p>\n"
},
{
"answer_id": 463475,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>make sure you have the latest version of xdebug? I had the same issues with an oldish version of xampp, downloaded the latest .dll of xdebug, changed mapping in php.ini, and worked a treat.</p>\n\n<p>Took me several hours to get though .. grr</p>\n"
},
{
"answer_id": 509597,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Open php.ini in xampp\\apache\\bin folder (not in xampp\\php folder).</li>\n<li>Locate extension=php_xdebug.dll line.</li>\n<li>Uncomment it.</li>\n</ol>\n"
},
{
"answer_id": 511747,
"author": "David",
"author_id": 9908,
"author_profile": "https://Stackoverflow.com/users/9908",
"pm_score": 1,
"selected": false,
"text": "<p>There can only be typically ONE engine level extension for PHP. I am currently using the latest xampp lite package on my machine with xdebug and its fine.</p>\n\n<p>Using grep ( gnu32 package for windows ) or some other text filter, get a list of every line in your PHP file that has the word \"extension\" in it and make sure you know exactly which packages are being used for your wamp stack.</p>\n\n<p>Next up. xdebug works better as a engine extension, but as a couple people have pointed out it can be used as a regular extension as well. The loss of performance between engine and normal extensions is that profiling isn't nearly as accurate, editor -> server debugging isn't reliable and doesn't appear to work on anything but explicit xdebug_break() statements.</p>\n\n<p>Last couple things to try is to call php -i and pipe that to a text file. If it crashes there, then its time to go to more drastic measures. Find all php.ini files on your windows machine and one by one rename them to something like php.disabled.ini or disabled_php.ini and try the php -i call again. Its very possible you've got a php.ini file lurking in some strange locations like c:\\ | c:\\windows\\ | c:\\windows\\system or somewhere else that takes precedence in the path then what your expecting it to be xammp\\apache\\bin</p>\n"
},
{
"answer_id": 539958,
"author": "fredarin",
"author_id": 25038,
"author_profile": "https://Stackoverflow.com/users/25038",
"pm_score": 1,
"selected": false,
"text": "<p>There's a Windows compatibility list <a href=\"http://www.apachefriends.org/winxampp/win32-compatibility-current.txt\" rel=\"nofollow noreferrer\">available here</a>. Seems xdebug is not supported for Vista...</p>\n"
},
{
"answer_id": 539988,
"author": "ryeguy",
"author_id": 49018,
"author_profile": "https://Stackoverflow.com/users/49018",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem too. Downgrade your installation of XAMPP to the previous version, and the bug is fixed. I'm not sure what exactly was causing it, but this is the only solution known at the moment. You can get the second most recent version <a href=\"http://sourceforge.net/project/showfiles.php?group_id=61776&package_id=89552&release_id=627831\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 567318,
"author": "cyberhobo",
"author_id": 68638,
"author_profile": "https://Stackoverflow.com/users/68638",
"pm_score": 1,
"selected": false,
"text": "<p>Matty's answer helped me keep Apache from crashing, but I can't get a remote debugging session working. Whenever I try to step through the code, my client complains that the connection has been closed, so still no debugging for me yet.</p>\n\n<p>But, in case it's useful to anyone else, here are the edits I made to the apache\\bin\\php.ini file in XAMPP 1.6.8 (the same worked in 1.7.0). Line 671:</p>\n\n<pre><code>extension=php_xdebug-2.0.4-5.2.8.dll\n</code></pre>\n\n<p>and line 1297 I added:</p>\n\n<pre><code>[XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension_ts=\"\\xampplite\\php\\ext\\php_xdebug-2.0.4-5.2.8.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=127.0.0.1\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"\\xampplite\\tmp\"\nxdebug.trace_output_dir=\"\\xampplite\\tmp\"\n</code></pre>\n"
},
{
"answer_id": 585894,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I got a solution working for Vista using a combination of the above so if this helps anyone here goes...</p>\n\n<p>Eclipse Europa - Version: 3.3.2 Build id: M20080221-1800 </p>\n\n<p>XAMPP - win32 version 1.6.8 installer</p>\n\n<p>xdebug - php_xdebug-2.0.2-5.2.5.dll</p>\n\n<p>Contents of ~/xampp/apache/bin/php.ini</p>\n\n<pre><code>[Zend]\n;zend_extension_ts = \"C:\\xampp\\php\\zendOptimizer\\lib\\ZendExtensionManager.dll\"\n;zend_extension_manager.optimizer_ts = \"C:\\xampp\\php\\zendOptimizer\\lib\\Optimizer\"\n;zend_optimizer.enable_loader = 0\n;zend_optimizer.optimization_level=15\n;;zend_optimizer.license_path =\n; Local Variables:\n; tab-width: 4\n; End:\n\n[XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension_ts=\"C:\\xampp\\php\\ext\\php_xdebug-2.0.2-5.2.5.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=127.0.0.1\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"C:\\xampp\\tmp\"\n</code></pre>\n\n<p>And the absolutely crucial bit for me....</p>\n\n<pre><code>;extension=php_xdebug-2.0.2-5.2.5.dll\n</code></pre>\n\n<p>That's right ! Comment out the above line.</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 607703,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your comment, I resolved the problem using this version of php_xdebug-2.0.2-5.2.5.dll, work for me on Windows Vista Business 64bit......the php.ini configuration is the same, just to use this xdebug dll version.......thanks </p>\n\n<p>Hermes</p>\n"
},
{
"answer_id": 665813,
"author": "MrFox",
"author_id": 32726,
"author_profile": "https://Stackoverflow.com/users/32726",
"pm_score": 0,
"selected": false,
"text": "<p>According to this <a href=\"http://bugs.xdebug.org/view.php?id=410\" rel=\"nofollow noreferrer\">Issue</a> I suggest you disable these two lines in your <code>php.ini</code>:</p>\n\n<pre><code>;xdebug.profiler_enable=1\n;xdebug.profiler_output_dir=\"(temp_dir)\"\n</code></pre>\n\n<p>worked for me</p>\n"
},
{
"answer_id": 716055,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using Vista x86 SP1, XAMPP 1.6.8 and php_xdebug-2.0.2-5.2.5.dll plugin.\nRecently I've noticed that when I run xampp-control.exe through right-click => run as administrator, all crashes pass away :) \nSometimes occurs but very rare and I can use debugger in Eclipse PDT.\nCheck out my sollution</p>\n"
},
{
"answer_id": 833805,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I'm running XAMPP for Windows Version 1.7.1 on my Win7 machine with xDebug and it works perfect.</p>\n\n<p>Check if you have SP1 installed, and then follow <a href=\"http://docs.joomla.org/Setting_up_your_workstation_for_Joomla!_development#Edit_PHP.INI_File\" rel=\"nofollow noreferrer\">these notes</a>:</p>\n\n<ol>\n<li><p>Find the line containing <code>implicit_flush</code> and set it as follows:</p>\n\n<p><code>implicit_flush = On</code></p></li>\n<li><p>Find the section called <code>[Zend]</code> and comment out all of the lines by putting a semi-colon (\";\") at the start of each line.</p></li>\n<li><p>Find the line: <code>zend_extension = \"c:\\xampp\\php\\ext\\php_xdebug.dll\"</code> and uncomment it.</p></li>\n<li><p>Find the <code>[XDebug]</code> section and uncomment all of the lines (except for the first line which is an actual comment). For Windows, it should look like the example below:</p>\n\n<pre><code>[XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension_ts=\"C:\\xampp\\php\\ext\\php_xdebug.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=localhost\nxdebug.remote_port=10000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"C:\\xampp\\tmp\"\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 886059,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Ran across this doing a Google search for why XDebug was crashing my WAMP Apache. I just upgraded to a Vista 64 laptop with the current version of WAMP(2.0), and here is what I put in my php.ini to make the crashing stop.</p>\n\n<p>I am using NetBeans as my IDE, and debugging works just fine.</p>\n\n<p>First off, comment out in your active php.ini.</p>\n\n<pre><code>;extension=php_xdebug-2.0.4-5.2.8.dll\n</code></pre>\n\n<p>Then add this to the bottom of your active php.ini (Adjust your directories and xdebug filename accordingly.)</p>\n\n<pre><code>[XDebug]\n; Only Zend OR (!) XDebug\nzend_extension_ts=\"C:/Program Files (x86)/wamp/bin/php/php5.2.9-2/ext/php_xdebug-2.0.4-5.2.8.dll\"\nxdebug.remote_enable=on\nxdebug.remote_host=localhost\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=0\nxdebug.profiler_output_dir=\"C:/Program Files (x86)/wamp/tmp\"\n</code></pre>\n"
},
{
"answer_id": 1005992,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>there is a thread safety problem with XDebug on Vista, I had the same problem using IIS7 with PHP as an ISAPI module, the server crashed randomly if the xdebug.dll was loaded, then I found an article that described that PHP+XDebug (on Vista) should be run in a single-thread-mode.</p>\n\n<p>I got it to work following way:</p>\n\n<p>A non-thread-safe PHP version, a non-thread-safe xdebug.dll for your PHP version, in php.ini it shuold be loaded as zend_extension=\"C:/FullPathToXdebugDll\" (without \"_ts\"!), running php in CGI (or better FastCGI) mode. (CGI/FastCGI forces it to be single-threaded).</p>\n\n<p>here the link to the article:\n<a href=\"http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis-70/\" rel=\"nofollow noreferrer\">http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis-70/</a></p>\n\n<p>Now I'm looking for a possibility to do the same thing with Xampp or InstantRails (or something like that) to run it on my notebook (Vista Home Premium has no IIS), but i dont know how to force apache to run in a single-thread-mode, does someone know how to do that?</p>\n"
},
{
"answer_id": 1174342,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Eugen has it right for me.</p>\n\n<ul>\n<li><p>Go download the non thread safe dll at <a href=\"http://xdebug.org/download.php\" rel=\"nofollow noreferrer\">http://xdebug.org/download.php</a><br>\ni.e. \n5.2 VC6 Non-thread-safe (32 bit)</p></li>\n<li><p>save it into your <code>\\xampp\\php\\ext</code> directory</p></li>\n<li><p>open your php.ini<br>\n<code>C:\\xampp\\php\\php.ini</code></p></li>\n</ul>\n\n<p>Scroll to the bottom and find <code>[XDebug]</code> and replace</p>\n\n<pre><code>zend_extension_ts=\"C:\\xampp\\php\\ext\\php_xdebug.dll\"\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>zend_extension=\"C:\\xampp\\php\\ext\\php_xdebug-2.0.5-5.2-nts.dll\"\n</code></pre>\n\n<p>so it looks like this:</p>\n\n<pre><code>[XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension=\"C:\\xampp\\php\\ext\\php_xdebug-2.0.5-5.2-nts.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=127.0.0.1\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"C:\\xampp\\tmp\"\n</code></pre>\n"
},
{
"answer_id": 1562746,
"author": "user106011",
"author_id": 106011,
"author_profile": "https://Stackoverflow.com/users/106011",
"pm_score": 1,
"selected": false,
"text": "<p>This might be helpful to someone. I had a repeatable Apache crash when debugging PHP web pages with Eclipse and XDebug and tried all kinds of reinstalls and PHP.INI changes and eventually figured out that my problem related to the use of a duplicate variable name in seperate files. One file included the other and both had (let's say) $foo. Once I renamed $foo to $newfoo in the second file, and restarted Apache, I got rid of my crashes. </p>\n\n<p>Also, kind of related, I was never able to get the PHP.INI file to work as is widely documented here and elsewhere. I had to remove the _ts from zend-extension, see below, to get the phpinfo() text: with Xdebug v2.0.5, Copyright (c) 2002-2008, by Derick Rethans.</p>\n\n<p>XAMPP 1.7.2 (using php_xdebug.dll that came with)\nPHP 5.3.0</p>\n\n<p>Here is my PHP.INI file snippet:</p>\n\n<p>xdebug.remote_enable=1\nxdebug.remote_host=\"127.0.0.1\"\nxdebug.remote_port=9000\nxdebug.remote_handler=\"dbgp\"\nzend_extension=\"C:\\xampp\\php\\ext\\php_xdebug.dll\"</p>\n"
},
{
"answer_id": 1876149,
"author": "Vafliik",
"author_id": 228226,
"author_profile": "https://Stackoverflow.com/users/228226",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem. It was resolved by latest version of xdebug (2.0.6). It is stil in dev mode, but for me it is more stable than previous releases :)</p>\n\n<p>It is a part of XAMPP 1.7.3beta <a href=\"http://www.apachefriends.org/en/xampp-beta.html\" rel=\"nofollow noreferrer\">http://www.apachefriends.org/en/xampp-beta.html</a></p>\n\n<p>Enabling xdebug was only matter of uncommenting one line in xampp/php/php.ini</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 2181521,
"author": "Vikram Phaneendra",
"author_id": 210933,
"author_profile": "https://Stackoverflow.com/users/210933",
"pm_score": 1,
"selected": false,
"text": "<p>install new version of XAMPP</p>\n"
},
{
"answer_id": 4558299,
"author": "Dane",
"author_id": 557647,
"author_profile": "https://Stackoverflow.com/users/557647",
"pm_score": 1,
"selected": false,
"text": "<p>I got it working using Xampp 1.7.3 (php 5.3.1) on Windows 7 Ultimate 6.1.7600. Following the author's post edit of un-commenting the line: <code>zend_extension = C:\\xampp\\php\\ext\\php_xdebug.dll</code>\nin xampp\\php\\php.ini, i managed to get the apache http server to stop crashing!</p>\n\n<p>Turns out Xampp comes with its own version of xdebug and I never even needed to download anything in the first place. You just need to un-comment the aforementioned line and enable the other features of xdebug you want in the [xdebug] section of php.ini. </p>\n\n<p>The version of xdebug that came with my install of Xampp is 2.0.6-dev. Hope this helps!</p>\n\n<p>EDIT: forgot to mention that I am running the x64 flavor of windows 7 :P</p>\n"
},
{
"answer_id": 4914260,
"author": "Thomas Hucke",
"author_id": 605389,
"author_profile": "https://Stackoverflow.com/users/605389",
"pm_score": 1,
"selected": false,
"text": "<p>Solution at <a href=\"http://community.activestate.com/forum-topic/apache-crashes#comment-9812\" rel=\"nofollow\">http://community.activestate.com/forum-topic/apache-crashes#comment-9812</a>\nObviousliy buggy apache module - runs php as CGI.</p>\n"
},
{
"answer_id": 5191738,
"author": "Alexey",
"author_id": 644413,
"author_profile": "https://Stackoverflow.com/users/644413",
"pm_score": 1,
"selected": false,
"text": "<p>May be my expirience will be useful:\nI use XAMPP 1.7.4, apache always crashes when trying to debug php page from eclipse with xdebug 2.1.0...\nI replaced xdebug 2.1.0 with xdebug 2.0.5 and now all goes right</p>\n"
},
{
"answer_id": 5282519,
"author": "moleculezz",
"author_id": 229510,
"author_profile": "https://Stackoverflow.com/users/229510",
"pm_score": 0,
"selected": false,
"text": "<p>I just installed xampp 1.7.4 using the zip file. With exception of 1.7.4 having a bug if you're using the .exe file, it works nicely with the provided xdebug file that comes with the package.</p>\n\n<p>I also used the <a href=\"http://docs.joomla.org/Setting_up_your_workstation_for_Joomla!_development\" rel=\"nofollow\">Joomla tutorial</a> to setup debugging.\nAll seems to be working well now.</p>\n"
},
{
"answer_id": 6337937,
"author": "ferweb",
"author_id": 796841,
"author_profile": "https://Stackoverflow.com/users/796841",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking in internet for this issue and tried many solutions and none of them worked.\nI tried this configuration, just a last test and worked for me, in Eclipse change under Windows/Preferences/PHP/Debug and select Xdebug as PHP debugger.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've installed the Windows XAMPP package on three separate computers, 2 running Windows Vista 32 bit ( 1 Ultimate / 1 Home Premium ) and 1 running Windows Vista 64 Home Premium.
After enabling xdebug in php.ini and restarting apache, viewing the default XAMPP localhost index causes apache to crash in the same way every time, reporting 'php\_xdebug.dll' as the Fault Module Name.
Here's the full report from the Windows Crash Reporter thing:
```
Problem signature:
Problem Event Name: APPCRASH
Application Name: apache.exe
Application Version: 2.2.9.0
Application Timestamp: 4853f994
Fault Module Name: php_xdebug.dll
Fault Module Version: 2.0.3.0
Fault Module Timestamp: 47fcd9b9
Exception Code: c0000005
Exception Offset: 00008493
OS Version: 6.0.6001.2.1.0.768.3
Locale ID: 1033
Additional Information 1: a34a
Additional Information 2: c9c5f4fd744690d388ab9d5b3eb051a7
Additional Information 3: cb2e
Additional Information 4: 650bb5690556a17e911375b94d3e16f0
```
I've tried Googling this issue but haven't found any resolution, only reports of similar errors.
EDIT: I enabled the extension line for php\_xdebug.dll and that seems to have stopped the crashing so far.
|
I'm running XAMPP for Windows Version 1.7.1 on my Win7 machine with xDebug and it works perfect.
Check if you have SP1 installed, and then follow [these notes](http://docs.joomla.org/Setting_up_your_workstation_for_Joomla!_development#Edit_PHP.INI_File):
1. Find the line containing `implicit_flush` and set it as follows:
`implicit_flush = On`
2. Find the section called `[Zend]` and comment out all of the lines by putting a semi-colon (";") at the start of each line.
3. Find the line: `zend_extension = "c:\xampp\php\ext\php_xdebug.dll"` and uncomment it.
4. Find the `[XDebug]` section and uncomment all of the lines (except for the first line which is an actual comment). For Windows, it should look like the example below:
```
[XDebug]
;; Only Zend OR (!) XDebug
zend_extension_ts="C:\xampp\php\ext\php_xdebug.dll"
xdebug.remote_enable=true
xdebug.remote_host=localhost
xdebug.remote_port=10000
xdebug.remote_handler=dbgp
xdebug.profiler_enable=1
xdebug.profiler_output_dir="C:\xampp\tmp"
```
|
206,793 |
<p>Why won't my connection string to SQL server work with Windows authentication? A sql user works fine, acme\administrator or [email protected] won't work. This is a Win Form app written in C#.</p>
<pre><code> {
OdbcConnection cn = null;
String connectionString;
connectionString = "Driver={SQL Server};Server=" + cbxDataSources.Text +";Database=" + strDatabase + ";";
connectionString += "UID=" + textBoxUserName.Text + ";";
connectionString += "PWD=" + textBoxPassword.Text + ";";
cn = new OdbcConnection(connectionString);
return cn;
}
</code></pre>
<p>Thanks guys</p>
|
[
{
"answer_id": 206804,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 4,
"selected": false,
"text": "<p>You are using SQL Server authentication.</p>\n\n<p>Windows authentication authenticates your connection with the Windows identity of the currently executing process or thread. You cannot set a username and password with Windows authentication. Instead, you set Integrated Security = SSPI.</p>\n"
},
{
"answer_id": 206825,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 3,
"selected": false,
"text": "<p>You have to connect using a Trusted Connection.</p>\n\n<p>2005:</p>\n\n<pre><code>Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;\n</code></pre>\n\n<p>2000:</p>\n\n<pre><code>Driver={SQL Server};Server=myServerAddress;Database=myDataBase;Trusted_Connection=Yes;\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Why won't my connection string to SQL server work with Windows authentication? A sql user works fine, acme\administrator or [email protected] won't work. This is a Win Form app written in C#.
```
{
OdbcConnection cn = null;
String connectionString;
connectionString = "Driver={SQL Server};Server=" + cbxDataSources.Text +";Database=" + strDatabase + ";";
connectionString += "UID=" + textBoxUserName.Text + ";";
connectionString += "PWD=" + textBoxPassword.Text + ";";
cn = new OdbcConnection(connectionString);
return cn;
}
```
Thanks guys
|
You are using SQL Server authentication.
Windows authentication authenticates your connection with the Windows identity of the currently executing process or thread. You cannot set a username and password with Windows authentication. Instead, you set Integrated Security = SSPI.
|
206,805 |
<p>I'm trying to use <code>tasklist</code> to find out which process is consuming more than X percent of my CPU (to later kill it with <code>taskkill</code>.) </p>
<p>How do I know what percent a time format represents?</p>
<p>The documentations says:</p>
<pre><code>TASKLIST options
/FI filter
</code></pre>
<p>And one filter may be:</p>
<pre><code>CPUTIME eq, ne, gt, lt, ge, le CPU time in the format: hh:mm:ss.
hh - number of hours,
mm - minutes, ss - seconds
</code></pre>
<p>If I try</p>
<pre><code>tasklist /FI "CPUTIME gt 00:00:10"
</code></pre>
<p>it works.</p>
<p>But if I </p>
<pre><code>tasklist /FI "CPUTIME gt 90"
</code></pre>
<p>it doesn't.</p>
<p>How can I know that time format represent 90%? Or 80%? What's the relationship between CPU usage time and the CPU usage percent?</p>
|
[
{
"answer_id": 206893,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": true,
"text": "<p>Tasklist's CPUTime is a measure of how much CPU time (cycles) have been used since the start of the process, so to convert that to a percent, it would be </p>\n\n<pre><code> (TotalProcessRuntime / CpuTime) / 100\n</code></pre>\n\n<p>At least, thats what I gather :)</p>\n"
},
{
"answer_id": 207439,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "<p>It doesn't look like there's an easy way to do this with tasklist, so I would suggest either doing this in VBscript or another scripting language, or using a different approach. If you're constrained to batch files then you could use the <a href=\"http://technet.microsoft.com/en-us/library/bb742610.aspx\" rel=\"noreferrer\">WMIC</a> command to get the list of running processes with their respective CPUTime:</p>\n\n<pre><code>C:\\> wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime\n\nName PercentProcessorTime\nIdle 0\nSystem 0\nSmss 0\ncsrss 0\nwinlogon 0\nservices 0\nlsass 0\n\n[...]\n\nwmiprvse 100\nwmic 0\n_Total 100\n</code></pre>\n\n<p>Note that this in my testing showed wmipsrv.exe as having 100% CPU, because it spiked while executing the WMI query. You should account for that in your script or you'll end up trying to kill the WMI service constantly ;)</p>\n\n<p>Reference: <br />\n<a href=\"http://waynes-world-it.blogspot.com/2008/09/useful-general-command-line-operations.html\" rel=\"noreferrer\">http://waynes-world-it.blogspot.com/2008/09/useful-general-command-line-operations.html</a> <br />\n<a href=\"http://technet.microsoft.com/en-us/library/bb742610.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/bb742610.aspx</a></p>\n"
},
{
"answer_id": 62625267,
"author": "SlightlyKosumi",
"author_id": 6561375,
"author_profile": "https://Stackoverflow.com/users/6561375",
"pm_score": 2,
"selected": false,
"text": "<p>tasklist does not tell you how long the process has been running for.\nIt tells you how much CPU time the various processes have taken up.\nTo get a percentage (and that will be an average percentage) you need to know how long your process has been running for.\nYou could for instance take snapshots 10 seconds apart, subtract the times, then find the process CPUTIME which is nearest to the number 10. (Well 10 times the number of CPU cores? not sure...)</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
I'm trying to use `tasklist` to find out which process is consuming more than X percent of my CPU (to later kill it with `taskkill`.)
How do I know what percent a time format represents?
The documentations says:
```
TASKLIST options
/FI filter
```
And one filter may be:
```
CPUTIME eq, ne, gt, lt, ge, le CPU time in the format: hh:mm:ss.
hh - number of hours,
mm - minutes, ss - seconds
```
If I try
```
tasklist /FI "CPUTIME gt 00:00:10"
```
it works.
But if I
```
tasklist /FI "CPUTIME gt 90"
```
it doesn't.
How can I know that time format represent 90%? Or 80%? What's the relationship between CPU usage time and the CPU usage percent?
|
Tasklist's CPUTime is a measure of how much CPU time (cycles) have been used since the start of the process, so to convert that to a percent, it would be
```
(TotalProcessRuntime / CpuTime) / 100
```
At least, thats what I gather :)
|
206,811 |
<p>My studio has a large codebase that has been developed over 10+ years. The coding standards that we started with were developed with few developers in house and long before we had to worry about any kind of standards related to C++.</p>
<p>Recently, we started a small R&D project in house and we updated our coding conventions to be more suitable for our environment. The R&D work is going to be integrated into existing project code. One major problem facing us is that we now have two standards for the two areas of work, and now the code bases will cross. I don't want two standards at the studio, and I'm actually quite happy to move forward with a single standard. (The 'how' of how we got into this situation isn't important -- just that we are and I had hoped that we wouldn't be.)</p>
<p>The problem is refactoring existing code. I'm not very keen on having two code bases (one relatively small and one very large) looking different. I am interested in doing some refactoring of one of the existing codebases to make it conform to the other standard. The problem is, the smaller code base is (IMO) the more desireable standard.</p>
<p>I started looking around for a tool that could do large scale refactoring for me. I'm not interested in rearranging and tightening code. I'm interested in changing things like</p>
<pre><code>class my_class {}
....
class my_class A;
</code></pre>
<p>to</p>
<pre><code>class MyClass {}
....
class MyClass A;
</code></pre>
<p>Basically doing function/variable level renaming. I'd prefer not to use something like Visual Assist because that will take a long time. I have upwards of 10000 source/header files with hundreds of thousands of lines of code. Using VA one class at a time would be a time killer and not worth the effort.</p>
<p>I did run across <a href="http://www.inspirel.com/vera/" rel="nofollow noreferrer">Vera</a> in another post on SO. That seems like it might do the job and do it well. I'd like to know if anyone has specific experience using Vera for the situation that I'm in, or has any other recommendations for tools that might get the job done. I think that it's important that this tool actually understand code structure so that we don't wind up just renaming variables in a search/replace manner because that will lead to subtle bugs if not done carefully.</p>
<p>EDIT: While my example shows I'm going from using _ between names to camelcase type notation, it might be more beneficial for us to move the other way. I'm really looking for a generic solution that will help with large scale renaming.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 206838,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": "<p>I think renaming variables is going to be tricky - fortunately you're going from _ convention to Capitalised so it won't be so hard (though _ is easier to read and better)</p>\n\n<p>I would take a code beautifier (eg <a href=\"http://astyle.sourceforge.net/astyle.html\" rel=\"nofollow noreferrer\">Artistic Style</a> or <a href=\"http://uncrustify.sourceforge.net/\" rel=\"nofollow noreferrer\">Uncrustify</a>) and modify them to do the conversion. You only need a few custom rules for this conversion so it won't be too hard.</p>\n"
},
{
"answer_id": 206889,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 4,
"selected": true,
"text": "<p>My process would be to rename each time someone touches a given module. Eventually, all modules would be refactored, but the incremental approach would result in less code breakage(assuming you have a complete set of tests. ;) ) </p>\n"
},
{
"answer_id": 206891,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 2,
"selected": false,
"text": "<p>I've made changes like this using custom scripts. If I can, I use sed. Otherwise I'll use a scripting language with good support for regular expressions. It is a crude hack which is sure to introduce bugs but unless you find a better solution, it is a path forward.</p>\n"
},
{
"answer_id": 207130,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO, variable renaming is simply not worth the effort. The important thing is that code is robust, readable and performant. Just adopt whatever style was used before and spend your time on important things.</p>\n"
},
{
"answer_id": 207779,
"author": "sudarkoff",
"author_id": 11419,
"author_profile": "https://Stackoverflow.com/users/11419",
"pm_score": 2,
"selected": false,
"text": "<p>Unless you have (1) a fairly complete set of reliable and automated tests and (2) a refactoring tool that understands C++ semantics (I haven't heard of such a tools), I would advise against making automated renames. Everywhere I worked the practice always was to only refactor modules you were working on at the moment. It's a lengthy but relatively painless process.</p>\n"
},
{
"answer_id": 876246,
"author": "none",
"author_id": 78244,
"author_profile": "https://Stackoverflow.com/users/78244",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to consider looking into \"<a href=\"https://wiki.mozilla.org/pork\" rel=\"nofollow noreferrer\">pork</a>\", which is used, created and maintained by the Mozilla folks, to do largely automated C++ source code analysis, including source code transformations such as <a href=\"http://blog.mozilla.com/tglek/2009/01/29/semantic-rewriting-of-code-with-pork-a-bitter-recap/\" rel=\"nofollow noreferrer\">refactorings</a>. It is scriptable using JavaScript and supports pretty complex semantic analyses and transformations. So renaming symbols is one of the easier things to do for pork. </p>\n\n<p>Now that <a href=\"http://blog.mozilla.com/tglek/2009/04/30/gcc-rant-progress/\" rel=\"nofollow noreferrer\">GCC plugins are on the way</a>, it is likely that such things are going to become easier in the future.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4405/"
] |
My studio has a large codebase that has been developed over 10+ years. The coding standards that we started with were developed with few developers in house and long before we had to worry about any kind of standards related to C++.
Recently, we started a small R&D project in house and we updated our coding conventions to be more suitable for our environment. The R&D work is going to be integrated into existing project code. One major problem facing us is that we now have two standards for the two areas of work, and now the code bases will cross. I don't want two standards at the studio, and I'm actually quite happy to move forward with a single standard. (The 'how' of how we got into this situation isn't important -- just that we are and I had hoped that we wouldn't be.)
The problem is refactoring existing code. I'm not very keen on having two code bases (one relatively small and one very large) looking different. I am interested in doing some refactoring of one of the existing codebases to make it conform to the other standard. The problem is, the smaller code base is (IMO) the more desireable standard.
I started looking around for a tool that could do large scale refactoring for me. I'm not interested in rearranging and tightening code. I'm interested in changing things like
```
class my_class {}
....
class my_class A;
```
to
```
class MyClass {}
....
class MyClass A;
```
Basically doing function/variable level renaming. I'd prefer not to use something like Visual Assist because that will take a long time. I have upwards of 10000 source/header files with hundreds of thousands of lines of code. Using VA one class at a time would be a time killer and not worth the effort.
I did run across [Vera](http://www.inspirel.com/vera/) in another post on SO. That seems like it might do the job and do it well. I'd like to know if anyone has specific experience using Vera for the situation that I'm in, or has any other recommendations for tools that might get the job done. I think that it's important that this tool actually understand code structure so that we don't wind up just renaming variables in a search/replace manner because that will lead to subtle bugs if not done carefully.
EDIT: While my example shows I'm going from using \_ between names to camelcase type notation, it might be more beneficial for us to move the other way. I'm really looking for a generic solution that will help with large scale renaming.
Thanks.
|
My process would be to rename each time someone touches a given module. Eventually, all modules would be refactored, but the incremental approach would result in less code breakage(assuming you have a complete set of tests. ;) )
|
206,820 |
<p>I would like to either prevent or handle a <code>StackOverflowException</code> that I am getting from a call to the <code>XslCompiledTransform.Transform</code> method within an <code>Xsl Editor</code> I am writing. The problem seems to be that the user can write an <code>Xsl script</code> that is infinitely recursive, and it just blows up on the call to the <code>Transform</code> method. (That is, the problem is not just the typical programmatic error, which is usually the cause of such an exception.)</p>
<p>Is there a way to detect and/or limit how many recursions are allowed? Or any other ideas to keep this code from just blowing up on me?</p>
|
[
{
"answer_id": 206842,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 7,
"selected": true,
"text": "<p>From Microsoft:</p>\n\n<blockquote>\n <p>Starting with the .NET Framework\n version 2.0, a StackOverflowException\n object cannot be caught by a try-catch\n block and the corresponding process is\n terminated by default. Consequently,\n users are advised to write their code\n to detect and prevent a stack\n overflow. For example, if your\n application depends on recursion, use\n a counter or a state condition to\n terminate the recursive loop.</p>\n</blockquote>\n\n<p>I'm assuming the exception is happening within an internal .NET method, and not in your code.</p>\n\n<p>You can do a couple things.</p>\n\n<ul>\n<li>Write code that checks the xsl for infinite recursion and notifies the user prior to applying a transform (Ugh).</li>\n<li>Load the XslTransform code into a separate process (Hacky, but less work).</li>\n</ul>\n\n<p>You can use the Process class to load the assembly that will apply the transform into a separate process, and alert the user of the failure if it dies, without killing your main app.</p>\n\n<p>EDIT: I just tested, here is how to do it:</p>\n\n<p>MainProcess:</p>\n\n<pre><code>// This is just an example, obviously you'll want to pass args to this.\nProcess p1 = new Process();\np1.StartInfo.FileName = \"ApplyTransform.exe\";\np1.StartInfo.UseShellExecute = false;\np1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n\np1.Start();\np1.WaitForExit();\n\nif (p1.ExitCode == 1) \n Console.WriteLine(\"StackOverflow was thrown\");\n</code></pre>\n\n<p>ApplyTransform Process:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n throw new StackOverflowException();\n }\n\n // We trap this, we can't save the process, \n // but we can prevent the \"ILLEGAL OPERATION\" window \n static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n if (e.IsTerminating)\n {\n Environment.Exit(1);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2117310,
"author": "Dmitry Dzygin",
"author_id": 256727,
"author_profile": "https://Stackoverflow.com/users/256727",
"pm_score": 3,
"selected": false,
"text": "<p>I would suggest creating a wrapper around XmlWriter object, so it would count amount of calls to WriteStartElement/WriteEndElement, and if you limit amount of tags to some number (f.e. 100), you would be able to throw a different exception, for example - InvalidOperation.</p>\n\n<p>That should solve the problem in the majority of the cases</p>\n\n<pre><code>public class LimitedDepthXmlWriter : XmlWriter\n{\n private readonly XmlWriter _innerWriter;\n private readonly int _maxDepth;\n private int _depth;\n\n public LimitedDepthXmlWriter(XmlWriter innerWriter): this(innerWriter, 100)\n {\n }\n\n public LimitedDepthXmlWriter(XmlWriter innerWriter, int maxDepth)\n {\n _maxDepth = maxDepth;\n _innerWriter = innerWriter;\n }\n\n public override void Close()\n {\n _innerWriter.Close();\n }\n\n public override void Flush()\n {\n _innerWriter.Flush();\n }\n\n public override string LookupPrefix(string ns)\n {\n return _innerWriter.LookupPrefix(ns);\n }\n\n public override void WriteBase64(byte[] buffer, int index, int count)\n {\n _innerWriter.WriteBase64(buffer, index, count);\n }\n\n public override void WriteCData(string text)\n {\n _innerWriter.WriteCData(text);\n }\n\n public override void WriteCharEntity(char ch)\n {\n _innerWriter.WriteCharEntity(ch);\n }\n\n public override void WriteChars(char[] buffer, int index, int count)\n {\n _innerWriter.WriteChars(buffer, index, count);\n }\n\n public override void WriteComment(string text)\n {\n _innerWriter.WriteComment(text);\n }\n\n public override void WriteDocType(string name, string pubid, string sysid, string subset)\n {\n _innerWriter.WriteDocType(name, pubid, sysid, subset);\n }\n\n public override void WriteEndAttribute()\n {\n _innerWriter.WriteEndAttribute();\n }\n\n public override void WriteEndDocument()\n {\n _innerWriter.WriteEndDocument();\n }\n\n public override void WriteEndElement()\n {\n _depth--;\n\n _innerWriter.WriteEndElement();\n }\n\n public override void WriteEntityRef(string name)\n {\n _innerWriter.WriteEntityRef(name);\n }\n\n public override void WriteFullEndElement()\n {\n _innerWriter.WriteFullEndElement();\n }\n\n public override void WriteProcessingInstruction(string name, string text)\n {\n _innerWriter.WriteProcessingInstruction(name, text);\n }\n\n public override void WriteRaw(string data)\n {\n _innerWriter.WriteRaw(data);\n }\n\n public override void WriteRaw(char[] buffer, int index, int count)\n {\n _innerWriter.WriteRaw(buffer, index, count);\n }\n\n public override void WriteStartAttribute(string prefix, string localName, string ns)\n {\n _innerWriter.WriteStartAttribute(prefix, localName, ns);\n }\n\n public override void WriteStartDocument(bool standalone)\n {\n _innerWriter.WriteStartDocument(standalone);\n }\n\n public override void WriteStartDocument()\n {\n _innerWriter.WriteStartDocument();\n }\n\n public override void WriteStartElement(string prefix, string localName, string ns)\n {\n if (_depth++ > _maxDepth) ThrowException();\n\n _innerWriter.WriteStartElement(prefix, localName, ns);\n }\n\n public override WriteState WriteState\n {\n get { return _innerWriter.WriteState; }\n }\n\n public override void WriteString(string text)\n {\n _innerWriter.WriteString(text);\n }\n\n public override void WriteSurrogateCharEntity(char lowChar, char highChar)\n {\n _innerWriter.WriteSurrogateCharEntity(lowChar, highChar);\n }\n\n public override void WriteWhitespace(string ws)\n {\n _innerWriter.WriteWhitespace(ws);\n }\n\n private void ThrowException()\n {\n throw new InvalidOperationException(string.Format(\"Result xml has more than {0} nested tags. It is possible that xslt transformation contains an endless recursive call.\", _maxDepth));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3564654,
"author": "jdehaan",
"author_id": 170443,
"author_profile": "https://Stackoverflow.com/users/170443",
"pm_score": 1,
"selected": false,
"text": "<p>With .NET 4.0 You can add the <code>HandleProcessCorruptedStateExceptions</code> attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.</p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Runtime.ExceptionServices;\n\nnamespace ExceptionCatching\n{\n public class Test\n {\n public void StackOverflow()\n {\n StackOverflow();\n }\n\n public void CustomException()\n {\n throw new Exception();\n }\n\n public unsafe void AccessViolation()\n {\n byte b = *(byte*)(8762765876);\n }\n }\n\n class Program\n {\n [HandleProcessCorruptedStateExceptions]\n static void Main(string[] args)\n {\n Test test = new Test();\n try {\n //test.StackOverflow();\n test.AccessViolation();\n //test.CustomException();\n }\n catch\n {\n Console.WriteLine(\"Caught.\");\n }\n\n Console.WriteLine(\"End of program\");\n\n }\n\n } \n}\n</code></pre>\n"
},
{
"answer_id": 3619253,
"author": "Shrike",
"author_id": 27703,
"author_profile": "https://Stackoverflow.com/users/27703",
"pm_score": 2,
"selected": false,
"text": "<p>If you application depends on 3d-party code (in Xsl-scripts) then you have to decide first do you want to defend from bugs in them or not.\nIf you really want to defend then I think you should execute your logic which prone to external errors in separate AppDomains.\nCatching StackOverflowException is not good.</p>\n\n<p>Check also this <a href=\"https://stackoverflow.com/questions/107735/stackoverflowexception-in-net\">question</a>.</p>\n"
},
{
"answer_id": 14059270,
"author": "sharp12345",
"author_id": 1279594,
"author_profile": "https://Stackoverflow.com/users/1279594",
"pm_score": -1,
"selected": false,
"text": "<p>You can read up this property every few calls, <code>Environment.StackTrace</code> , and if the stacktrace exceded a specific threshold that you preset, you can return the function.</p>\n\n<p>You should also try to replace some recursive functions with loops.</p>\n"
},
{
"answer_id": 17553381,
"author": "Fixation",
"author_id": 2565370,
"author_profile": "https://Stackoverflow.com/users/2565370",
"pm_score": 2,
"selected": false,
"text": "<p>I had a stackoverflow today and i read some of your posts and decided to help out the Garbage Collecter. </p>\n\n<p>I used to have a near infinite loop like this:</p>\n\n<pre><code> class Foo\n {\n public Foo()\n {\n Go();\n }\n\n public void Go()\n {\n for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)\n {\n byte[] b = new byte[1]; // Causes stackoverflow\n }\n }\n }\n</code></pre>\n\n<p>Instead let the resource run out of scope like this:</p>\n\n<pre><code>class Foo\n{\n public Foo()\n {\n GoHelper();\n }\n\n public void GoHelper()\n {\n for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)\n {\n Go();\n }\n }\n\n public void Go()\n {\n byte[] b = new byte[1]; // Will get cleaned by GC\n } // right now\n}\n</code></pre>\n\n<p>It worked for me, hope it helps someone.</p>\n"
},
{
"answer_id": 30681031,
"author": "atlaste",
"author_id": 1031591,
"author_profile": "https://Stackoverflow.com/users/1031591",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n<p><strong>NOTE</strong> The question in the bounty by @WilliamJockusch and the original question are different.</p>\n<p>This answer is about StackOverflow's in the general case of third-party libraries and what you can/can't do with them. If you're looking about the special case with XslTransform, see the accepted answer.</p>\n</blockquote>\n<hr />\n<p>Stack overflows happen because the data on the stack exceeds a certain limit (in bytes). The details of how this detection works can be found <a href=\"https://stackoverflow.com/questions/30327674/how-is-a-stackoverflowexception-detected/30327998#30327998\">here</a>.</p>\n<blockquote>\n<p>I'm wondering if there is a general way to track down StackOverflowExceptions. In other words, suppose I have infinite recursion somewhere in my code, but I have no idea where. I want to track it down by some means that is easier than stepping through code all over the place until I see it happening. I don't care how hackish it is.</p>\n</blockquote>\n<p>As I mentioned in the link, detecting a stack overflow from static code analysis would require solving the halting problem which is <em>undecidable</em>. Now that we've established that <em>there is no silver bullet</em>, I can show you a few tricks that I think helps track down the problem.</p>\n<p>I think this question can be interpreted in different ways, and since I'm a bit bored :-), I'll break it down into different variations.</p>\n<p><strong>Detecting a stack overflow in a test environment</strong></p>\n<p>Basically the problem here is that you have a (limited) test environment and want to detect a stack overflow in an (expanded) production environment.</p>\n<p>Instead of detecting the SO itself, I solve this by exploiting the fact that the stack depth can be set. The debugger will give you all the information you need. Most languages allow you to specify the stack size or the max recursion depth.</p>\n<p>Basically I try to force a SO by making the stack depth as small as possible. If it doesn't overflow, I can always make it bigger (=in this case: safer) for the production environment. The moment you get a stack overflow, you can manually decide if it's a 'valid' one or not.</p>\n<p>To do this, pass the stack size (in our case: a small value) to a Thread parameter, and see what happens. The default stack size in .NET is 1 MB, we're going to use a way smaller value:</p>\n<pre><code>class StackOverflowDetector\n{\n static int Recur()\n {\n int variable = 1;\n return variable + Recur();\n }\n\n static void Start()\n {\n int depth = 1 + Recur();\n }\n\n static void Main(string[] args)\n {\n Thread t = new Thread(Start, 1);\n t.Start();\n t.Join();\n Console.WriteLine();\n Console.ReadLine();\n }\n}\n</code></pre>\n<p><em>Note: we're going to use this code below as well.</em></p>\n<p>Once it overflows, you can set it to a bigger value until you get a SO that makes sense.</p>\n<p><strong>Creating exceptions before you SO</strong></p>\n<p>The <code>StackOverflowException</code> is not catchable. This means there's not much you can do when it has happened. So, if you believe something is bound to go wrong in your code, you can make your own exception in some cases. The only thing you need for this is the current stack depth; there's no need for a counter, you can use the real values from .NET:</p>\n<pre><code>class StackOverflowDetector\n{\n static void CheckStackDepth()\n {\n if (new StackTrace().FrameCount > 10) // some arbitrary limit\n {\n throw new StackOverflowException("Bad thread.");\n }\n }\n\n static int Recur()\n {\n CheckStackDepth();\n int variable = 1;\n return variable + Recur();\n }\n\n static void Main(string[] args)\n {\n try\n {\n int depth = 1 + Recur();\n }\n catch (ThreadAbortException e)\n {\n Console.WriteLine("We've been a {0}", e.ExceptionState);\n }\n Console.WriteLine();\n Console.ReadLine();\n }\n}\n</code></pre>\n<p>Note that this approach also works if you are dealing with third-party components that use a callback mechanism. The only thing required is that you can intercept <em>some</em> calls in the stack trace.</p>\n<p><strong>Detection in a separate thread</strong></p>\n<p>You explicitly suggested this, so here goes this one.</p>\n<p>You can try detecting a SO in a separate thread.. but it probably won't do you any good. A stack overflow can happen <em>fast</em>, even before you get a context switch. This means that this mechanism isn't reliable at all... <strong>I wouldn't recommend actually using it</strong>. It was fun to build though, so here's the code :-)</p>\n<pre><code>class StackOverflowDetector\n{\n static int Recur()\n {\n Thread.Sleep(1); // simulate that we're actually doing something :-)\n int variable = 1;\n return variable + Recur();\n }\n\n static void Start()\n {\n try\n {\n int depth = 1 + Recur();\n }\n catch (ThreadAbortException e)\n {\n Console.WriteLine("We've been a {0}", e.ExceptionState);\n }\n }\n\n static void Main(string[] args)\n {\n // Prepare the execution thread\n Thread t = new Thread(Start);\n t.Priority = ThreadPriority.Lowest;\n\n // Create the watch thread\n Thread watcher = new Thread(Watcher);\n watcher.Priority = ThreadPriority.Highest;\n watcher.Start(t);\n\n // Start the execution thread\n t.Start();\n t.Join();\n\n watcher.Abort();\n Console.WriteLine();\n Console.ReadLine();\n }\n\n private static void Watcher(object o)\n {\n Thread towatch = (Thread)o;\n\n while (true)\n {\n if (towatch.ThreadState == System.Threading.ThreadState.Running)\n {\n towatch.Suspend();\n var frames = new System.Diagnostics.StackTrace(towatch, false);\n if (frames.FrameCount > 20)\n {\n towatch.Resume();\n towatch.Abort("Bad bad thread!");\n }\n else\n {\n towatch.Resume();\n }\n }\n }\n }\n}\n</code></pre>\n<p>Run this in the debugger and have fun of what happens.</p>\n<p><strong>Using the characteristics of a stack overflow</strong></p>\n<p>Another interpretation of your question is: "Where are the pieces of code that could potentially cause a stack overflow exception?". Obviously the answer of this is: all code with recursion. For each piece of code, you can then do some manual analysis.</p>\n<p>It's also possible to determine this using static code analysis. What you need to do for that is to decompile all methods and figure out if they contain an infinite recursion. Here's some code that does that for you:</p>\n<pre><code>// A simple decompiler that extracts all method tokens (that is: call, callvirt, newobj in IL)\ninternal class Decompiler\n{\n private Decompiler() { }\n\n static Decompiler()\n {\n singleByteOpcodes = new OpCode[0x100];\n multiByteOpcodes = new OpCode[0x100];\n FieldInfo[] infoArray1 = typeof(OpCodes).GetFields();\n for (int num1 = 0; num1 < infoArray1.Length; num1++)\n {\n FieldInfo info1 = infoArray1[num1];\n if (info1.FieldType == typeof(OpCode))\n {\n OpCode code1 = (OpCode)info1.GetValue(null);\n ushort num2 = (ushort)code1.Value;\n if (num2 < 0x100)\n {\n singleByteOpcodes[(int)num2] = code1;\n }\n else\n {\n if ((num2 & 0xff00) != 0xfe00)\n {\n throw new Exception("Invalid opcode: " + num2.ToString());\n }\n multiByteOpcodes[num2 & 0xff] = code1;\n }\n }\n }\n }\n\n private static OpCode[] singleByteOpcodes;\n private static OpCode[] multiByteOpcodes;\n\n public static MethodBase[] Decompile(MethodBase mi, byte[] ildata)\n {\n HashSet<MethodBase> result = new HashSet<MethodBase>();\n\n Module module = mi.Module;\n\n int position = 0;\n while (position < ildata.Length)\n {\n OpCode code = OpCodes.Nop;\n\n ushort b = ildata[position++];\n if (b != 0xfe)\n {\n code = singleByteOpcodes[b];\n }\n else\n {\n b = ildata[position++];\n code = multiByteOpcodes[b];\n b |= (ushort)(0xfe00);\n }\n\n switch (code.OperandType)\n {\n case OperandType.InlineNone:\n break;\n case OperandType.ShortInlineBrTarget:\n case OperandType.ShortInlineI:\n case OperandType.ShortInlineVar:\n position += 1;\n break;\n case OperandType.InlineVar:\n position += 2;\n break;\n case OperandType.InlineBrTarget:\n case OperandType.InlineField:\n case OperandType.InlineI:\n case OperandType.InlineSig:\n case OperandType.InlineString:\n case OperandType.InlineTok:\n case OperandType.InlineType:\n case OperandType.ShortInlineR:\n position += 4;\n break;\n case OperandType.InlineR:\n case OperandType.InlineI8:\n position += 8;\n break;\n case OperandType.InlineSwitch:\n int count = BitConverter.ToInt32(ildata, position);\n position += count * 4 + 4;\n break;\n\n case OperandType.InlineMethod:\n int methodId = BitConverter.ToInt32(ildata, position);\n position += 4;\n try\n {\n if (mi is ConstructorInfo)\n {\n result.Add((MethodBase)module.ResolveMember(methodId, mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes));\n }\n else\n {\n result.Add((MethodBase)module.ResolveMember(methodId, mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments()));\n }\n }\n catch { } \n break;\n \n\n default:\n throw new Exception("Unknown instruction operand; cannot continue. Operand type: " + code.OperandType);\n }\n }\n return result.ToArray();\n }\n}\n\nclass StackOverflowDetector\n{\n // This method will be found:\n static int Recur()\n {\n CheckStackDepth();\n int variable = 1;\n return variable + Recur();\n }\n\n static void Main(string[] args)\n {\n RecursionDetector();\n Console.WriteLine();\n Console.ReadLine();\n }\n\n static void RecursionDetector()\n {\n // First decompile all methods in the assembly:\n Dictionary<MethodBase, MethodBase[]> calling = new Dictionary<MethodBase, MethodBase[]>();\n var assembly = typeof(StackOverflowDetector).Assembly;\n\n foreach (var type in assembly.GetTypes())\n {\n foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).OfType<MethodBase>())\n {\n var body = member.GetMethodBody();\n if (body!=null)\n {\n var bytes = body.GetILAsByteArray();\n if (bytes != null)\n {\n // Store all the calls of this method:\n var calls = Decompiler.Decompile(member, bytes);\n calling[member] = calls;\n }\n }\n }\n }\n\n // Check every method:\n foreach (var method in calling.Keys)\n {\n // If method A -> ... -> method A, we have a possible infinite recursion\n CheckRecursion(method, calling, new HashSet<MethodBase>());\n }\n }\n</code></pre>\n<p>Now, the fact that a method cycle contains recursion, is by no means a guarantee that a stack overflow will happen - it's just the most likely precondition for your stack overflow exception. In short, this means that this code will determine the pieces of code where a stack overflow <em>can</em> occur, which should narrow down most code considerably.</p>\n<p><strong>Yet other approaches</strong></p>\n<p>There are some other approaches you can try that I haven't described here.</p>\n<ol>\n<li>Handling the stack overflow by hosting the CLR process and handling it. Note that you still cannot 'catch' it.</li>\n<li>Changing all IL code, building another DLL, adding checks on recursion. Yes, that's quite possible (I've implemented it in the past :-); it's just difficult and involves a lot of code to get it right.</li>\n<li>Use the .NET profiling API to capture all method calls and use that to figure out stack overflows. For example, you can implement checks that if you encounter the same method X times in your call tree, you give a signal. There's a project <a href=\"https://github.com/MicrosoftArchive/clrprofiler\" rel=\"nofollow noreferrer\">clrprofiler</a> that will give you a head start.</li>\n</ol>\n"
},
{
"answer_id": 30681654,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 3,
"selected": false,
"text": "<p>This answer is for @WilliamJockusch.</p>\n\n<blockquote>\n <p>I'm wondering if there is a general way to track down\n StackOverflowExceptions. In other words, suppose I have infinite\n recursion somewhere in my code, but I have no idea where. I want to\n track it down by some means that is easier than stepping through code\n all over the place until I see it happening. I don't care how hackish\n it is. For example, It would be great to have a module I could\n activate, perhaps even from another thread, that polled the stack\n depth and complained if it got to a level I considered \"too high.\" For\n example, I might set \"too high\" to 600 frames, figuring that if the\n stack were too deep, that has to be a problem. Is something like that\n possible. Another example would be to log every 1000th method call\n within my code to the debug output. The chances this would get some\n evidence of the overlow would be pretty good, and it likely would not\n blow up the output too badly. The key is that it cannot involve\n writing a check wherever the overflow is happening. Because the entire\n problem is that I don't know where that is. Preferrably the solution\n should not depend on what my development environment looks like; i.e,\n it should not assumet that I am using C# via a specific toolset (e.g.\n VS).</p>\n</blockquote>\n\n<p>It sounds like you're keen to hear some debugging techniques to catch this StackOverflow so I thought I would share a couple for you to try.</p>\n\n<h2>1. Memory Dumps.</h2>\n\n<p><strong>Pro's</strong>: Memory Dumps are a sure fire way to work out the cause of a Stack Overflow. A C# MVP & I worked together troubleshooting a SO and he went on to blog about it <a href=\"http://blog.tatham.oddie.com.au/2009/07/04/diagnosing-stack-overflow-faults-in-asp-net-production-environments/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>This method is the fastest way to track down the problem.</p>\n\n<p>This method wont require you to reproduce problems by following steps seen in logs.</p>\n\n<p><strong>Con's</strong>: Memory Dumps are very large and you have to attach AdPlus/procdump the process.</p>\n\n<h2>2. Aspect Orientated Programming.</h2>\n\n<p><strong>Pro's</strong>: This is probably the easiest way for you to implement code that checks the size of the call stack from any method without writing code in every method of your application. There are a bunch of <a href=\"http://www.codeproject.com/Articles/28387/Rating-of-Open-Source-AOP-Frameworks-in-NET\" rel=\"nofollow noreferrer\">AOP Frameworks</a> that allow you to Intercept before and after calls.</p>\n\n<p>Will tell you the methods that are causing the Stack Overflow.</p>\n\n<p>Allows you to check the <code>StackTrace().FrameCount</code> at the entry and exit of all methods in your application.</p>\n\n<p><strong>Con's</strong>: It will have a performance impact - the hooks are embedded into the IL for every method and you cant really \"de-activate\" it out.</p>\n\n<p>It somewhat depends on your development environment tool set.</p>\n\n<h2>3. Logging User Activity.</h2>\n\n<p>A week ago I was trying to hunt down several hard to reproduce problems. I posted this QA <a href=\"https://stackoverflow.com/questions/30326673/user-activity-logging-see-variables-in-a-global-exception-handler\">User Activity Logging, Telemetry (and Variables in Global Exception Handlers)</a> . The conclusion I came to was a really simple user-actions-logger to see how to reproduce problems in a debugger when any unhandled exception occurs.</p>\n\n<p><strong>Pro's</strong>: You can turn it on or off at will (ie subscribing to events). </p>\n\n<p>Tracking the user actions doesn't require intercepting every method.</p>\n\n<p>You can count the number of events methods are subscribed too <em>far more simply than with AOP</em>. </p>\n\n<p>The log files are relatively small and focus on what actions you need to perform to reproduce the problem.</p>\n\n<p>It can help you to understand how users are using your application.</p>\n\n<p><strong>Con's</strong>: Isn't suited to a Windows Service <em>and I'm sure there are better tools like this for web apps</em>.</p>\n\n<p>Doesn't <em>necessarily</em> tell you the methods that cause the Stack Overflow.</p>\n\n<p>Requires you to step through logs manually reproducing problems rather than a Memory Dump where you can get it and debug it straight away.</p>\n\n<p> </p>\n\n<hr>\n\n<p>Maybe you might try all techniques I mention above and some that @atlaste posted and tell us which one's you found were the easiest/quickest/dirtiest/most acceptable to run in a PROD environment/etc. </p>\n\n<p>Anyway good luck tracking down this SO.</p>\n"
},
{
"answer_id": 30782671,
"author": "Nick Mertin",
"author_id": 3402566,
"author_profile": "https://Stackoverflow.com/users/3402566",
"pm_score": 0,
"selected": false,
"text": "<p>By the looks of it, apart from starting another process, there doesn't seem to be any way of handling a <code>StackOverflowException</code>. Before anyone else asks, I tried using <code>AppDomain</code>, but that didn't work:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\n\nnamespace StackOverflowExceptionAppDomainTest\n{\n class Program\n {\n static void recrusiveAlgorithm()\n {\n recrusiveAlgorithm();\n }\n static void Main(string[] args)\n {\n if(args.Length>0&&args[0]==\"--child\")\n {\n recrusiveAlgorithm();\n }\n else\n {\n var domain = AppDomain.CreateDomain(\"Child domain to test StackOverflowException in.\");\n domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { \"--child\" });\n domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>\n {\n Console.WriteLine(\"Detected unhandled exception: \" + e.ExceptionObject.ToString());\n };\n while (true)\n {\n Console.WriteLine(\"*\");\n Thread.Sleep(1000);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>If you do end up using the separate-process solution, however, I would recommend using <code>Process.Exited</code> and <code>Process.StandardOutput</code> and handle the errors yourself, to give your users a better experience.</p>\n"
},
{
"answer_id": 30798680,
"author": "Gentian Kasa",
"author_id": 4026354,
"author_profile": "https://Stackoverflow.com/users/4026354",
"pm_score": 1,
"selected": false,
"text": "<p>@WilliamJockusch, if I understood correctly your concern, it's not possible (from a mathematical point of view) to <strong>always</strong> identify an infinite recursion as it would mean to solve the <a href=\"http://en.wikipedia.org/wiki/Halting_problem\" rel=\"nofollow\">Halting problem</a>. To solve it you'd need a <a href=\"http://en.wikipedia.org/wiki/Super-recursive_algorithm\" rel=\"nofollow\">Super-recursive algorithm</a> (like <a href=\"http://www.ninagierasimczuk.com/flt2013/wp-content/uploads/2013/01/Putnam_1965.pdf\" rel=\"nofollow\">Trial-and-error predicates</a> for example) or a machine that can <a href=\"http://en.wikipedia.org/wiki/Hypercomputation\" rel=\"nofollow\">hypercompute</a> (an example is explained in the <a href=\"https://books.google.it/books?id=3tejKrkWkD8C&pg=PA31&lpg=PA31&dq=hintikka%20mutanen%20trial%20and%20error%20machines&source=bl&ots=CNquYM2lBb&sig=jBaAyN8XEzPJGUeHlCXOziSfQtc&hl=it&sa=X&ved=0CCEQ6AEwAGoVChMI-euAgeCJxgIVhizbCh07qQAP#v=onepage&q=hintikka%20mutanen%20trial%20and%20error%20machines&f=false\" rel=\"nofollow\">following section</a> - available as preview - of <a href=\"http://www.springer.com/us/book/9780387308869\" rel=\"nofollow\">this book</a>).</p>\n\n<p>From a practical point of view, you'd have to know:</p>\n\n<ul>\n<li>How much stack memory you have left at the given time</li>\n<li>How much stack memory your recursive method will need at the given time for the specific output.</li>\n</ul>\n\n<p>Keep in mind that, with the current machines, this data is extremely mutable due to multitasking and I haven't heard of a software that does the task.</p>\n\n<p>Let me know if something is unclear.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
I would like to either prevent or handle a `StackOverflowException` that I am getting from a call to the `XslCompiledTransform.Transform` method within an `Xsl Editor` I am writing. The problem seems to be that the user can write an `Xsl script` that is infinitely recursive, and it just blows up on the call to the `Transform` method. (That is, the problem is not just the typical programmatic error, which is usually the cause of such an exception.)
Is there a way to detect and/or limit how many recursions are allowed? Or any other ideas to keep this code from just blowing up on me?
|
From Microsoft:
>
> Starting with the .NET Framework
> version 2.0, a StackOverflowException
> object cannot be caught by a try-catch
> block and the corresponding process is
> terminated by default. Consequently,
> users are advised to write their code
> to detect and prevent a stack
> overflow. For example, if your
> application depends on recursion, use
> a counter or a state condition to
> terminate the recursive loop.
>
>
>
I'm assuming the exception is happening within an internal .NET method, and not in your code.
You can do a couple things.
* Write code that checks the xsl for infinite recursion and notifies the user prior to applying a transform (Ugh).
* Load the XslTransform code into a separate process (Hacky, but less work).
You can use the Process class to load the assembly that will apply the transform into a separate process, and alert the user of the failure if it dies, without killing your main app.
EDIT: I just tested, here is how to do it:
MainProcess:
```
// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.Start();
p1.WaitForExit();
if (p1.ExitCode == 1)
Console.WriteLine("StackOverflow was thrown");
```
ApplyTransform Process:
```
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
throw new StackOverflowException();
}
// We trap this, we can't save the process,
// but we can prevent the "ILLEGAL OPERATION" window
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
Environment.Exit(1);
}
}
}
```
|
206,853 |
<p>I'm running a console app (myApp.exe) which outputs a pseudo localized (unicode) string to the standard output.
If I run this in a regular command prompt(cmd.exe), the unicode data gets lost.
If I run this in a unicode command prompt(cmd.exe /u) or set the properties of the console to "Lucida Console" then the unicode string is maintained.</p>
<p>I'd like to run this app in C# and redirect the unicode string into a local variable. I'm using a Process object with RedirectStandardOutput = true, but the unicode string is always lost. </p>
<p>How can I specify to persist this unicode info?</p>
<pre><code> private static int RunDISM(string Args, out string ConsoleOutput)
{
Process process = new Process();
process.StartInfo.FileName = "myApp.exe";
process.StartInfo.Arguments = Args;
try
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
process.Start();
process.WaitForExit(Int32.MaxValue);
}
catch (Exception e)
{
WEX.Logging.Interop.Log.Assert("Failure while starting or running process.\nERROR: " + e.Message);
ConsoleOutput = null;
return EXITCODE_ERROR;
}
ConsoleOutput = process.StandardOutput.ReadToEnd();
return process.ExitCode;
}
</code></pre>
|
[
{
"answer_id": 207129,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you need to change the encoding on the StandardOutput stream from your console app, using the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.standardoutputencoding.aspx\" rel=\"nofollow noreferrer\">StandardOutputEncoding</a> property on ProcessStartInfo. Try adding the following code inside your try/catch block, before starting the process:</p>\n\n<pre><code>process.StartInfo.StandardOutputEncoding = Encoding.Unicode;\n</code></pre>\n\n<p>You might have to experiment with different encodings to see which is the right one for your case.</p>\n"
},
{
"answer_id": 2067280,
"author": "ziya",
"author_id": 248393,
"author_profile": "https://Stackoverflow.com/users/248393",
"pm_score": 2,
"selected": false,
"text": "<p>Get the bytes out and see if they make any sense:</p>\n\n<pre><code>var b = p.StandardOutput.CurrentEncoding.GetBytes(p.StandardOutput.ReadToEnd());\n</code></pre>\n\n<p>Once you figured out the actual encoding you can use the <a href=\"http://msdn.microsoft.com/en-us/library/zs0350fy.aspx\" rel=\"nofollow noreferrer\">standard encoding APIs</a> to convert the bytes into a string.</p>\n"
},
{
"answer_id": 60586335,
"author": "CSharper",
"author_id": 70799,
"author_profile": "https://Stackoverflow.com/users/70799",
"pm_score": 0,
"selected": false,
"text": "<p>First set <code>process.StartInfo.StandardOutputEncoding = Encoding.Default</code>.</p>\n\n<p>Then goto <code>Control Panel</code> > <code>Region</code> > <code>Administrative</code> > <code>Change system locale...</code> and set encoding of your pseudo localized string there.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165305/"
] |
I'm running a console app (myApp.exe) which outputs a pseudo localized (unicode) string to the standard output.
If I run this in a regular command prompt(cmd.exe), the unicode data gets lost.
If I run this in a unicode command prompt(cmd.exe /u) or set the properties of the console to "Lucida Console" then the unicode string is maintained.
I'd like to run this app in C# and redirect the unicode string into a local variable. I'm using a Process object with RedirectStandardOutput = true, but the unicode string is always lost.
How can I specify to persist this unicode info?
```
private static int RunDISM(string Args, out string ConsoleOutput)
{
Process process = new Process();
process.StartInfo.FileName = "myApp.exe";
process.StartInfo.Arguments = Args;
try
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
process.Start();
process.WaitForExit(Int32.MaxValue);
}
catch (Exception e)
{
WEX.Logging.Interop.Log.Assert("Failure while starting or running process.\nERROR: " + e.Message);
ConsoleOutput = null;
return EXITCODE_ERROR;
}
ConsoleOutput = process.StandardOutput.ReadToEnd();
return process.ExitCode;
}
```
|
It looks like you need to change the encoding on the StandardOutput stream from your console app, using the [StandardOutputEncoding](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.standardoutputencoding.aspx) property on ProcessStartInfo. Try adding the following code inside your try/catch block, before starting the process:
```
process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
```
You might have to experiment with different encodings to see which is the right one for your case.
|
206,857 |
<p>I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:</p>
<pre><code>class Consumer {
private:
vector<char> read(size_t n) {
// If the internal buffer has `n` elements, then dequeue them
// Otherwise wait for more data and try again
}
public:
void run() {
read(10);
read(4839);
// etc
}
void feed(const vector<char> &more) {
// Safely queue the data
// Notify `read` that there is now more data
}
};
</code></pre>
<p>In this case, <code>feed</code> and <code>run</code> will run on separate threads and <code>read</code> should be a blocking read (like <code>recv</code> and <code>fread</code>). Obviously, I will need some kind of mutual exclusion on my deque, and I will need some kind of notification system to inform <code>read</code> to try again.</p>
<p>I hear <strong>condition variables</strong> are the way to go, but all my multithreading experience lies with Windows and am having a hard time wrapping my head around them. </p>
<p>Thanks for any help!</p>
<p>(Yes, I know it's inefficient to return vectors. Let's not get into that.)</p>
|
[
{
"answer_id": 206868,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 1,
"selected": false,
"text": "<p>I'll throw down some semi-pseudo-code. Here are my comments:</p>\n\n<p>1)Very large grains of locking here. If you need faster access, you will want to rethink your data structures. The STL is not threadsafe.</p>\n\n<p>2)Lock will block until the mutex lets it through. The mutex structure is that it lets 1 thread through it at a time with the lock/unlock mechanism. No need for polling or for some kind of exception-esque structure. </p>\n\n<p>3)This is a pretty syntactically hacky cut at the problem. I'm not being precise with the API nor C++ syntax, but I believe it gives a semantically correct solution.</p>\n\n<p>4)Edited in response to comment.</p>\n\n<pre><code>class piper\n{\npthread_mutex queuemutex;\npthread_mutex readymutex;\nbool isReady; //init to false by constructor\n\n//whatever else\n};\n\npiper::read()\n{//whatever\npthread_mutex_lock(&queuemutex)\nif(myqueue.size() >= n)\n{ \n return_queue_vector.push_back(/* you know what to do here */)\n\n pthread_mutex_lock(&readymutex)\n isReady = false;\n pthread_mutex_unlock(&readymutex)\n}\npthread_mutex_unlock(&queuemutex)\n}\n\npiper::push_em_in()\n{\n//more whatever\npthread_mutex_lock(&queuemutex)\n//push push push\nif(myqueue.size() >= n)\n{\n pthread_mutex_lock(&readymutex)\n isReady = true;\n pthread_mutex_unlock(&readymutex)\n}\npthread_mutex_unlock(&queuemutex)\n}\n</code></pre>\n"
},
{
"answer_id": 206926,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 4,
"selected": true,
"text": "<p>This code is not production ready.\nNo error checking is done on the results of any library calls.</p>\n\n<p>I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that's about it.</p>\n\n<p>In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can cot be abused inside other methods of Consumer. But as long as you take note that the lock must be acquired before you use the condition variable (in any way) then this simple situation can stand as is.</p>\n\n<p>Out of interest have you checked the boost threading library?</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <pthread.h>\n\nclass LockThread\n{\n public:\n LockThread(pthread_mutex_t& m)\n :mutex(m)\n {\n pthread_mutex_lock(&mutex);\n }\n ~LockThread()\n {\n pthread_mutex_unlock(&mutex);\n }\n private:\n pthread_mutex_t& mutex;\n};\nclass Consumer\n{\n pthread_mutex_t lock;\n pthread_cond_t cond;\n std::vector<char> unreadData;\n public:\n Consumer()\n {\n pthread_mutex_init(&lock,NULL);\n pthread_cond_init(&cond,NULL);\n }\n ~Consumer()\n {\n pthread_cond_destroy(&cond);\n pthread_mutex_destroy(&lock);\n }\n\n private:\n std::vector<char> read(size_t n)\n {\n LockThread locker(lock);\n while (unreadData.size() < n)\n {\n // Must wait until we have n char.\n // This is a while loop because feed may not put enough in.\n\n // pthread_cond() releases the lock.\n // Thread will not be allowed to continue until\n // signal is called and this thread reacquires the lock.\n\n pthread_cond_wait(&cond,&lock);\n\n // Once released from the condition you will have re-aquired the lock.\n // Thus feed() must have exited and released the lock first.\n }\n\n /*\n * Not sure if this is exactly what you wanted.\n * But the data is copied out of the thread safe buffer\n * into something that can be returned.\n */\n std::vector<char> result(n); // init result with size n\n std::copy(&unreadData[0],\n &unreadData[n],\n &result[0]);\n\n unreadData.erase(unreadData.begin(),\n unreadData.begin() + n);\n return (result);\n }\npublic:\n void run()\n {\n read(10);\n read(4839);\n // etc\n }\n void feed(const std::vector<char> &more)\n {\n LockThread locker(lock);\n\n // Once we acquire the lock we can safely modify the buffer.\n std::copy(more.begin(),more.end(),std::back_inserter(unreadData));\n\n // Only signal the thread if you have the lock\n // Otherwise race conditions happen.\n pthread_cond_signal(&cond);\n\n // destructor releases the lock and thus allows read thread to continue.\n }\n};\n\n\nint main()\n{\n Consumer c;\n}\n</code></pre>\n"
},
{
"answer_id": 206944,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to use what I call a \"Syncronized Queue\". I wrap the normal queue and use a Semaphore class for both locking and making read block just as you desire:</p>\n\n<pre><code>#ifndef SYNCQUEUE_20061005_H_\n#define SYNCQUEUE_20061005_H_\n\n#include <queue>\n#include \"Semaphore.h\"\n\n// similar, but slightly simpler interface to std::queue\n// this queue implementation will serialize pushes and pops\n// and block on a pop while empty (as apposed to throwing an exception)\n// it also locks as neccessary on insertion and removal to avoid race \n// conditions\n\ntemplate <class T, class C = std::deque<T> > class SyncQueue {\nprotected:\n std::queue<T, C> m_Queue;\n Semaphore m_Semaphore;\n Mutex m_Mutex;\n\npublic:\n typedef typename std::queue<T, C>::value_type value_type;\n typedef typename std::queue<T, C>::size_type size_type;\n\n explicit SyncQueue(const C& a = C()) : m_Queue(a), m_Semaphore(0) {}\n\n bool empty() const { return m_Queue.empty(); }\n size_type size() const { return m_Queue.size(); }\n\n void push(const value_type& x);\n value_type pop();\n};\n\ntemplate <class T, class C>\nvoid SyncQueue<T, C>::push(const SyncQueue<T, C>::value_type &x) {\n // atomically push item\n m_Mutex.lock(); \n m_Queue.push(x); \n m_Mutex.unlock(); \n\n // let blocking semaphore know another item has arrived\n m_Semaphore.v();\n}\n\ntemplate <class T, class C>\ntypename SyncQueue<T, C>::value_type SyncQueue<T, C>::pop() {\n // block until we have at least one item\n m_Semaphore.p();\n\n // atomically read and pop front item\n m_Mutex.lock();\n value_type ret = m_Queue.front();\n m_Queue.pop();\n m_Mutex.unlock();\n\n return ret;\n}\n\n#endif\n</code></pre>\n\n<p>You can implement semaphores and mutexes with the appropriate primitives in your threading implementation.</p>\n\n<p>NOTE: this implementation is an example for single elements in a queue, but you could easily wrap this with a function which buffers results until N have been provided. something like this if it is a queue of chars:</p>\n\n<pre><code>std::vector<char> func(int size) {\n std::vector<char> result;\n while(result.size() != size) {\n result.push_back(my_sync_queue.pop());\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 206961,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>Just for fun, here is a quick and dirty implementation using Boost. It uses pthreads under the hood on platforms that support it, and on windows uses windows operations.</p>\n\n<pre><code>boost::mutex access;\nboost::condition cond;\n\n// consumer\ndata read()\n{\n boost::mutex::scoped_lock lock(access);\n // this blocks until the data is ready\n cond.wait(lock);\n\n // queue is ready\n return data_from_queue();\n}\n\n// producer\nvoid push(data)\n{\n boost::mutex::scoped_lock lock(access);\n // add data to queue\n\n if (queue_has_enough_data())\n cond.notify_one(); \n}\n</code></pre>\n"
},
{
"answer_id": 207026,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "<p>For even more fun, here is my final version. STL-ized for no good reason. :-)</p>\n\n<pre><code>#include <algorithm>\n#include <deque>\n#include <pthread.h>\n\ntemplate<typename T>\nclass MultithreadedReader {\n std::deque<T> buffer;\n pthread_mutex_t moreDataMutex;\n pthread_cond_t moreDataCond;\n\nprotected:\n template<typename OutputIterator>\n void read(size_t count, OutputIterator result) {\n pthread_mutex_lock(&moreDataMutex);\n\n while (buffer.size() < count) {\n pthread_cond_wait(&moreDataCond, &moreDataMutex);\n }\n std::copy(buffer.begin(), buffer.begin() + count, result);\n buffer.erase(buffer.begin(), buffer.begin() + count);\n\n pthread_mutex_unlock(&moreDataMutex);\n }\n\npublic:\n MultithreadedReader() {\n pthread_mutex_init(&moreDataMutex, 0);\n pthread_cond_init(&moreDataCond, 0);\n }\n\n ~MultithreadedReader() {\n pthread_cond_destroy(&moreDataCond);\n pthread_mutex_destroy(&moreDataMutex);\n }\n\n template<typename InputIterator>\n void feed(InputIterator first, InputIterator last) {\n pthread_mutex_lock(&moreDataMutex);\n\n buffer.insert(buffer.end(), first, last);\n pthread_cond_signal(&moreDataCond);\n\n pthread_mutex_unlock(&moreDataMutex);\n }\n};\n</code></pre>\n"
},
{
"answer_id": 807918,
"author": "bobmcn",
"author_id": 47833,
"author_profile": "https://Stackoverflow.com/users/47833",
"pm_score": 0,
"selected": false,
"text": "<p>Glib Asynchronous Queues provide the locking and sleep on reading an empty queue you are looking for. See <a href=\"http://library.gnome.org/devel/glib/2.20/glib-Asynchronous-Queues.html\" rel=\"nofollow noreferrer\">http://library.gnome.org/devel/glib/2.20/glib-Asynchronous-Queues.html</a> You can combine them with gthreads or gthread pools.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:
```
class Consumer {
private:
vector<char> read(size_t n) {
// If the internal buffer has `n` elements, then dequeue them
// Otherwise wait for more data and try again
}
public:
void run() {
read(10);
read(4839);
// etc
}
void feed(const vector<char> &more) {
// Safely queue the data
// Notify `read` that there is now more data
}
};
```
In this case, `feed` and `run` will run on separate threads and `read` should be a blocking read (like `recv` and `fread`). Obviously, I will need some kind of mutual exclusion on my deque, and I will need some kind of notification system to inform `read` to try again.
I hear **condition variables** are the way to go, but all my multithreading experience lies with Windows and am having a hard time wrapping my head around them.
Thanks for any help!
(Yes, I know it's inefficient to return vectors. Let's not get into that.)
|
This code is not production ready.
No error checking is done on the results of any library calls.
I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that's about it.
In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can cot be abused inside other methods of Consumer. But as long as you take note that the lock must be acquired before you use the condition variable (in any way) then this simple situation can stand as is.
Out of interest have you checked the boost threading library?
```
#include <iostream>
#include <vector>
#include <pthread.h>
class LockThread
{
public:
LockThread(pthread_mutex_t& m)
:mutex(m)
{
pthread_mutex_lock(&mutex);
}
~LockThread()
{
pthread_mutex_unlock(&mutex);
}
private:
pthread_mutex_t& mutex;
};
class Consumer
{
pthread_mutex_t lock;
pthread_cond_t cond;
std::vector<char> unreadData;
public:
Consumer()
{
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond,NULL);
}
~Consumer()
{
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&lock);
}
private:
std::vector<char> read(size_t n)
{
LockThread locker(lock);
while (unreadData.size() < n)
{
// Must wait until we have n char.
// This is a while loop because feed may not put enough in.
// pthread_cond() releases the lock.
// Thread will not be allowed to continue until
// signal is called and this thread reacquires the lock.
pthread_cond_wait(&cond,&lock);
// Once released from the condition you will have re-aquired the lock.
// Thus feed() must have exited and released the lock first.
}
/*
* Not sure if this is exactly what you wanted.
* But the data is copied out of the thread safe buffer
* into something that can be returned.
*/
std::vector<char> result(n); // init result with size n
std::copy(&unreadData[0],
&unreadData[n],
&result[0]);
unreadData.erase(unreadData.begin(),
unreadData.begin() + n);
return (result);
}
public:
void run()
{
read(10);
read(4839);
// etc
}
void feed(const std::vector<char> &more)
{
LockThread locker(lock);
// Once we acquire the lock we can safely modify the buffer.
std::copy(more.begin(),more.end(),std::back_inserter(unreadData));
// Only signal the thread if you have the lock
// Otherwise race conditions happen.
pthread_cond_signal(&cond);
// destructor releases the lock and thus allows read thread to continue.
}
};
int main()
{
Consumer c;
}
```
|
206,867 |
<p>I've done some research and I can't really find a preferred way to do updating of form controls from a worker thread in C#. I know about the BackgroundWorker component, but what is the best way to do it without using the BackgroundWorker component?</p>
|
[
{
"answer_id": 206871,
"author": "Mark",
"author_id": 26310,
"author_profile": "https://Stackoverflow.com/users/26310",
"pm_score": 3,
"selected": false,
"text": "<p>Why dont you want to do it using the BackgroundWorker? It has a fantastic callback event called ProgressChanged which lets the UI thread know about updates, perfect for progess bar-type updates and the like.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx\" rel=\"noreferrer\">link to details</a></p>\n"
},
{
"answer_id": 206877,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 1,
"selected": false,
"text": "<p>There's a discussion related to this <a href=\"https://stackoverflow.com/questions/6184/how-do-i-make-event-callbacks-into-my-win-forms-thread-safe#6189\">here</a> and one <a href=\"https://stackoverflow.com/questions/120540/how-to-update-components-in-different-threads-net-cf\">here</a>.</p>\n\n<p>Essentially, you use Invoke to accomplish it.</p>\n\n<p>Best of luck!</p>\n"
},
{
"answer_id": 206884,
"author": "AR.",
"author_id": 1354,
"author_profile": "https://Stackoverflow.com/users/1354",
"pm_score": 4,
"selected": true,
"text": "<p>There's a general rule of thumb that says don't update the UI from any thread other than the UI thread itself. Using the features of the BackgroundWorker is a good idea, but you don't want to and something is happening on a different thread, you should do an \"Invoke\" or BeginInvoke to force the delegate to execute the method on the UI thread.</p>\n\n<p>Edit: Jon B made this good point in the comments:</p>\n\n<blockquote>\n <p>Keep in mind that Invoke() is\n synchronous and BeginInvoke() is\n asynchronous. If you use Invoke(), you\n have to be careful not to cause a\n deadlock. I would recommend\n BeginInvoke() unless you really need\n the call to be synchronous.</p>\n</blockquote>\n\n<p>Some simple example code:</p>\n\n<pre><code>// Updates the textbox text.\nprivate void UpdateText(string text)\n{\n // Set the textbox text.\n m_TextBox.Text = text;\n}\n\npublic delegate void UpdateTextCallback(string text);\n\n// Then from your thread you can call this...\nm_TextBox.Invoke(new UpdateTextCallback(this.UpdateText),\n new object[]{\"Text generated on non-UI thread.\"});\n</code></pre>\n\n<p>The code above is from a FAQ about it <a href=\"http://blogs.msdn.com/csharpfaq/archive/2004/03/17/91685.aspx\" rel=\"noreferrer\">here</a> and a longer more involved one <a href=\"http://weblogs.asp.net/justin_rogers/articles/126345.aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 206984,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I would also consider InvokeRequired (VS2008 only) when calling Invoke. There are times that you will not be updating the UI from a seperate thread. It saves the overhead of creating the delegate etc.</p>\n\n<pre><code>if (InvokeRequired)\n {\n //This.Invoke added to circumvent cross threading exceptions.\n this.Invoke(new UpdateProgressBarHandler(UpdateProgressBar), new object[] { progressPercentage });\n }\n else\n {\n UpdateProgressBar(progressPercentage);\n }\n</code></pre>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
I've done some research and I can't really find a preferred way to do updating of form controls from a worker thread in C#. I know about the BackgroundWorker component, but what is the best way to do it without using the BackgroundWorker component?
|
There's a general rule of thumb that says don't update the UI from any thread other than the UI thread itself. Using the features of the BackgroundWorker is a good idea, but you don't want to and something is happening on a different thread, you should do an "Invoke" or BeginInvoke to force the delegate to execute the method on the UI thread.
Edit: Jon B made this good point in the comments:
>
> Keep in mind that Invoke() is
> synchronous and BeginInvoke() is
> asynchronous. If you use Invoke(), you
> have to be careful not to cause a
> deadlock. I would recommend
> BeginInvoke() unless you really need
> the call to be synchronous.
>
>
>
Some simple example code:
```
// Updates the textbox text.
private void UpdateText(string text)
{
// Set the textbox text.
m_TextBox.Text = text;
}
public delegate void UpdateTextCallback(string text);
// Then from your thread you can call this...
m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText),
new object[]{"Text generated on non-UI thread."});
```
The code above is from a FAQ about it [here](http://blogs.msdn.com/csharpfaq/archive/2004/03/17/91685.aspx) and a longer more involved one [here](http://weblogs.asp.net/justin_rogers/articles/126345.aspx).
|
206,885 |
<p>Let's say I've got some Perl code that increments a column in a specific row of a database each time it's hit, and I'm expecting it to be hit pretty frequently, so I'd like to optimize it with FCGI. Right now, I basically wrapped most of the code in something like this:</p>
<pre><code>while (FCGI::accept() >= 0) {
[code which currently creates a db connection and makes calls through it]
}
</code></pre>
<p>I'm wondering if it's better to put the database connection (my $dbh = DBI->connect(etc)) outside of the FCGI loop so that the script keeps the connection alive, or will I still gain the advantages of FCGI in speed & resources by leaving it in the loop?</p>
|
[
{
"answer_id": 206896,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 1,
"selected": false,
"text": "<p>You would still gain from FCGI even if you do keep your DB connection in the loop - but you would gain even more if you moved it out.</p>\n"
},
{
"answer_id": 206942,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 1,
"selected": false,
"text": "<p>Connect performance largely depends on the database you're using. PostgreSQL and MySQL are very fast to connect (MySQL especially), and thus usually connect on each request. Other databases such as Oracle are a bit slower and tend to require longer connection lifetimes. It should be easy to test by writing a while 1..100000 loop with DBI->connect() and disconnect to see how fast your database is.</p>\n"
},
{
"answer_id": 207160,
"author": "mpeters",
"author_id": 12094,
"author_profile": "https://Stackoverflow.com/users/12094",
"pm_score": 2,
"selected": false,
"text": "<p>bmdhacks is right that if you're using MySQL or PostgreSQL it doesn't matter as much since connections are pretty cheap. But no matter your database you will have speed gains by using persistent connections.</p>\n\n<p>But if you do decide to go with persistent connections you will need to worry about connection timeouts. These will happen at any time during the life of your program depending on your server settings and the amount of traffic you're getting. <code>ping()</code> is your friend here. And if you need more help, look at how <code>Apache::DBI</code> does it.</p>\n"
},
{
"answer_id": 214773,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 2,
"selected": false,
"text": "<p>Don't put the connection outside the loop, you might lose the connection and then you can't reconnect. You could put it into a global, but then you'd have to do the connection check and reconnects yourself.</p>\n\n<p>Instead, use <a href=\"http://search.cpan.org/perldoc?Ima::DBI\" rel=\"nofollow noreferrer\">Ima::DBI</a> or <a href=\"http://search.cpan.org/perldoc?DBI#connect_cached\" rel=\"nofollow noreferrer\"><code>DBI->connect_cached()</code></a> to do the connection caching for you. It'll do all the work to make sure the connection is alive and reconnect if necessary.</p>\n\n<p>But before you bother, do some benchmarking to find out where your bottleneck really is. I have had the database connection be the bottleneck in the past, but that was with Oracle and it was also 10+ years ago.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Let's say I've got some Perl code that increments a column in a specific row of a database each time it's hit, and I'm expecting it to be hit pretty frequently, so I'd like to optimize it with FCGI. Right now, I basically wrapped most of the code in something like this:
```
while (FCGI::accept() >= 0) {
[code which currently creates a db connection and makes calls through it]
}
```
I'm wondering if it's better to put the database connection (my $dbh = DBI->connect(etc)) outside of the FCGI loop so that the script keeps the connection alive, or will I still gain the advantages of FCGI in speed & resources by leaving it in the loop?
|
bmdhacks is right that if you're using MySQL or PostgreSQL it doesn't matter as much since connections are pretty cheap. But no matter your database you will have speed gains by using persistent connections.
But if you do decide to go with persistent connections you will need to worry about connection timeouts. These will happen at any time during the life of your program depending on your server settings and the amount of traffic you're getting. `ping()` is your friend here. And if you need more help, look at how `Apache::DBI` does it.
|
206,916 |
<p>I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget.
The thing is: I want to limit the characters that can be typed, so I'm trying to clear the Entry widget when I reach the specific number of characters (2 in this case), but it looks like I always miss the last typed character. I added the lost character in a print to show.</p>
<p>Here's the sample code:</p>
<pre><code>from Tkinter import *
class sampleFrame:
def __init__(self, master):
self.__frame = Frame(master)
self.__frame.pack()
def get_frame(self):
return self.__frame
class sampleClass:
def __init__(self, master):
self.__aLabel = Label(master,text="aLabel", width=10)
self.__aLabel.pack(side=LEFT)
self.__aEntry = Entry (master, width=2)
self.__aEntry.bind('<Key>', lambda event: self.callback(event, self.__aEntry))
self.__aEntry.pack(side=LEFT)
def callback(self, event, widgetName):
self.__value = widgetName.get()+event.char
print self.__value
if len(self.__value)>2:
widgetName.delete(2,4)
root = Tk()
aSampleFrame = sampleFrame(root)
aSampleClass = sampleClass(aSampleFrame.get_frame())
root.mainloop()
</code></pre>
<p>Any help will be much appreciated!</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 207018,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": true,
"text": "<p>At first, after you do the deletion, the event goes on with its normal processing, i.e. the character gets inserted. You need to signal to Tkinter that the event should be ignored.</p>\n\n<p>So in your code above, add the marked line:</p>\n\n<pre><code>if len(self.__value) > 2:\n widgetName.delete(2,4)\n return \"break\" # add this line\n</code></pre>\n\n<p>On the other hand, why do you go through the lambda? An event has a .widget attribute which you can use. So you can change your code into:</p>\n\n<pre><code> self.__aEntry.bind('<Key>', self.callback) # ※ here!\n self.__aEntry.pack(side=LEFT)\n\ndef callback(self, event):\n self.__value = event.widget.get()+event.char # ※ here!\n print self.__value\n if len(self.__value)>2:\n event.widget.delete(2,4) # ※ here!\n return \"break\"\n</code></pre>\n\n<p>All the changed lines are marked with \"here!\"</p>\n"
},
{
"answer_id": 225872,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 1,
"selected": false,
"text": "<p>To be a bit more specific, Tk widgets have what are called \"bindtags\". When an event is processed, each bindtag on the widget is considered in order to see if it has a binding. A widget by default will have as its bindtags the widget, the widget class, the root widget, and \"all\". Thus, bindings to the widget will occur before the default bindings. Once your binding has been processed you can prevent any further bindtags from being considered by returning a \"break\".</p>\n\n<p>The ramifications are this: if you make a binding on the widget, the class, root window and \"all\" bindings may fire as well. In addition, any binding you attach to the widget fires <em>before</em> the class binding which is where the default behavior (eg: the insertion of a character) happens. It is important to be aware of that in situations where you may want to handle the event after the default behavior rather than before.</p>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/206916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget.
The thing is: I want to limit the characters that can be typed, so I'm trying to clear the Entry widget when I reach the specific number of characters (2 in this case), but it looks like I always miss the last typed character. I added the lost character in a print to show.
Here's the sample code:
```
from Tkinter import *
class sampleFrame:
def __init__(self, master):
self.__frame = Frame(master)
self.__frame.pack()
def get_frame(self):
return self.__frame
class sampleClass:
def __init__(self, master):
self.__aLabel = Label(master,text="aLabel", width=10)
self.__aLabel.pack(side=LEFT)
self.__aEntry = Entry (master, width=2)
self.__aEntry.bind('<Key>', lambda event: self.callback(event, self.__aEntry))
self.__aEntry.pack(side=LEFT)
def callback(self, event, widgetName):
self.__value = widgetName.get()+event.char
print self.__value
if len(self.__value)>2:
widgetName.delete(2,4)
root = Tk()
aSampleFrame = sampleFrame(root)
aSampleClass = sampleClass(aSampleFrame.get_frame())
root.mainloop()
```
Any help will be much appreciated!
Thanks in advance
|
At first, after you do the deletion, the event goes on with its normal processing, i.e. the character gets inserted. You need to signal to Tkinter that the event should be ignored.
So in your code above, add the marked line:
```
if len(self.__value) > 2:
widgetName.delete(2,4)
return "break" # add this line
```
On the other hand, why do you go through the lambda? An event has a .widget attribute which you can use. So you can change your code into:
```
self.__aEntry.bind('<Key>', self.callback) # ※ here!
self.__aEntry.pack(side=LEFT)
def callback(self, event):
self.__value = event.widget.get()+event.char # ※ here!
print self.__value
if len(self.__value)>2:
event.widget.delete(2,4) # ※ here!
return "break"
```
All the changed lines are marked with "here!"
|
206,953 |
<p>I've got a collection (List<Rectangle>) which I need to sort left-right. That part's easy. Then I want to iterate through the Rectangles in their <em>original</em> order, but easily find their index in the sorted collection. indexOf() won't work, since I may have a number of equal objects. I can't help feeling there should be an easy way to do this.</p>
|
[
{
"answer_id": 206966,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't have tens of thousands of objects, you could just store them in two separate collections, one original, one sorted. Remember that collection classes in Java only store <em>references</em> to objects, so this doesn't take up as much memory as it might seem.</p>\n"
},
{
"answer_id": 206985,
"author": "eishay",
"author_id": 16201,
"author_profile": "https://Stackoverflow.com/users/16201",
"pm_score": 0,
"selected": false,
"text": "<p>Clone the lists and sort one of them. Having two references of the same object is will not matter too much with indexOf() since the pointers to the same object are the same and you can't tell between them. \nIf you have two objects that are equal but not identical and you do want to distinguish between them then you do have a problem since indexOf() is using the equal method.\nIn this case the best solution might be to simply iterate through the list and check for object identity (==).</p>\n"
},
{
"answer_id": 207015,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 3,
"selected": true,
"text": "<p>I've found a solution - but perhaps there is a neater/more optimal one out there.</p>\n\n<pre><code>List<Rectangle> originalRects = ...;\n\n/* record index of each rectangle object.\n * Using a hash map makes lookups efficient,\n * and using an IdentityHashMap means we lookup by object identity\n * not value.\n */\nIdentityHashMap<Rectangle, Integer> originalIndices = new IdentityHashMap<Rectangle, Integer>();\nfor(int i=0; i<originalRects.size(); i++) {\n originalIndices.put(originalRects.get(i), i);\n}\n\n/* copy rectangle list */\nList<Rectangle> sortedRects = new ArrayList<Rectangle>();\nsortedRects.addAll(originalRects);\n\n/* and sort */\nCollections.sort(sortedRects, new LeftToRightComparator());\n\n/* Loop through original list */\nfor(int i=0; i<sortedRects.size(); i++) {\n Rectangle rect = sortedRects.get(i);\n /* Lookup original index efficiently */\n int origIndex = originalIndices.get(rect);\n\n /* I know the original, and sorted indices plus the rectangle itself */\n...\n</code></pre>\n"
},
{
"answer_id": 207134,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 0,
"selected": false,
"text": "<p>Another way is to sort an array of indexes instead of sorting the original list. The array starts as an identity array a[0] = 0, a[1] = 1, etc, then use a custom comparator/sort to get an index array. doesn't require much extra space, as you only have an extra array of integers instead of another collection.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/206953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26334/"
] |
I've got a collection (List<Rectangle>) which I need to sort left-right. That part's easy. Then I want to iterate through the Rectangles in their *original* order, but easily find their index in the sorted collection. indexOf() won't work, since I may have a number of equal objects. I can't help feeling there should be an easy way to do this.
|
I've found a solution - but perhaps there is a neater/more optimal one out there.
```
List<Rectangle> originalRects = ...;
/* record index of each rectangle object.
* Using a hash map makes lookups efficient,
* and using an IdentityHashMap means we lookup by object identity
* not value.
*/
IdentityHashMap<Rectangle, Integer> originalIndices = new IdentityHashMap<Rectangle, Integer>();
for(int i=0; i<originalRects.size(); i++) {
originalIndices.put(originalRects.get(i), i);
}
/* copy rectangle list */
List<Rectangle> sortedRects = new ArrayList<Rectangle>();
sortedRects.addAll(originalRects);
/* and sort */
Collections.sort(sortedRects, new LeftToRightComparator());
/* Loop through original list */
for(int i=0; i<sortedRects.size(); i++) {
Rectangle rect = sortedRects.get(i);
/* Lookup original index efficiently */
int origIndex = originalIndices.get(rect);
/* I know the original, and sorted indices plus the rectangle itself */
...
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.