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
|
---|---|---|---|---|---|---|
268,153 |
<p>I am writing code in VS2005 using its STL.
I have one UI thread to read a vector, and a work thread to write to a vector.
I use ::boost::shared_ptr as vector element.</p>
<pre><code>vector<shared_ptr<Class>> vec;
</code></pre>
<p>but I find, if I manipulate the vec in both thread in the same time(I can guarantee they do not visit the same area, UI Thread always read the area that has the information)</p>
<p>vec.clear() seem can not release the resource. problem happend in shared_ptr, it can not release its resource.</p>
<p>What is the problem?
Does it because when the vector reach its order capacity, it reallocates in memory, then the original part is invalidated.</p>
<p>As far as I know when reallocating, iterator will be invalid, why some problem also happened when I used vec[i].
//-----------------------------------------------</p>
<p>What kinds of lock is needed?
I mean: If the vector's element is a shared_ptr, when a thread A get the point smart_p, the other thread B will wait till A finishes the operation on smart_p right?
Or just simply add lock when thread is trying to read the point, when the read opeation is finished, thread B can continu to do something.</p>
|
[
{
"answer_id": 268177,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p>When you're accessing the same resource from more than one thread, locking is necessary. If you don't, you have all sorts of strange behaviour, like you're seeing.</p>\n\n<p>Since you're using Boost, an easy way to use locking is to use the Boost.Thread library. The best kind of locks you can use for this scenario are reader/writer locks; they're called <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex\" rel=\"nofollow noreferrer\"><code>shared_mutex</code></a> in Boost.Thread.</p>\n\n<p>But yes, what you're seeing is essentially undefined behaviour, due to the lack of synchronisation between the threads. Hope this helps!</p>\n\n<p>Edit to answer OP's second question: You should use a reader lock when reading the smart pointer out of the vector, and a writer lock when writing or adding an item to the vector (so, the mutex is for the vector only). If multiple threads will be accessing the <em>pointed-to</em> object (i.e., what the smart pointer points to), then separate locks should be set up for them. In that case, you're better off putting a mutex object in the object class as well.</p>\n"
},
{
"answer_id": 273346,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 0,
"selected": false,
"text": "<p>Another alternative is to eliminate the locking altogether by ensuring that the vector is accessed in only one thread. For example, by having the worker thread send a message to the main thread with the element(s) to add to the vector.</p>\n"
},
{
"answer_id": 354480,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to do simultaneous access to a list or array like this. However, std::vector is not a good choice because of its resize behavior. To do it right needs a fixed-size array, or special locking or copy-update behavior on resize. It also needs independent front and back pointers again with locking or atomic update.</p>\n\n<p>Another answer mentioned message queues. A shared array as I described is a common and efficient way to implement those.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
I am writing code in VS2005 using its STL.
I have one UI thread to read a vector, and a work thread to write to a vector.
I use ::boost::shared\_ptr as vector element.
```
vector<shared_ptr<Class>> vec;
```
but I find, if I manipulate the vec in both thread in the same time(I can guarantee they do not visit the same area, UI Thread always read the area that has the information)
vec.clear() seem can not release the resource. problem happend in shared\_ptr, it can not release its resource.
What is the problem?
Does it because when the vector reach its order capacity, it reallocates in memory, then the original part is invalidated.
As far as I know when reallocating, iterator will be invalid, why some problem also happened when I used vec[i].
//-----------------------------------------------
What kinds of lock is needed?
I mean: If the vector's element is a shared\_ptr, when a thread A get the point smart\_p, the other thread B will wait till A finishes the operation on smart\_p right?
Or just simply add lock when thread is trying to read the point, when the read opeation is finished, thread B can continu to do something.
|
When you're accessing the same resource from more than one thread, locking is necessary. If you don't, you have all sorts of strange behaviour, like you're seeing.
Since you're using Boost, an easy way to use locking is to use the Boost.Thread library. The best kind of locks you can use for this scenario are reader/writer locks; they're called [`shared_mutex`](http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex) in Boost.Thread.
But yes, what you're seeing is essentially undefined behaviour, due to the lack of synchronisation between the threads. Hope this helps!
Edit to answer OP's second question: You should use a reader lock when reading the smart pointer out of the vector, and a writer lock when writing or adding an item to the vector (so, the mutex is for the vector only). If multiple threads will be accessing the *pointed-to* object (i.e., what the smart pointer points to), then separate locks should be set up for them. In that case, you're better off putting a mutex object in the object class as well.
|
268,180 |
<p>Ok guys and gals, here is my problem:</p>
<p>I've built a custom control that uses a textbox to present data to the user. </p>
<p>When the user interacts with the control the <strong>value of that textbox is altered with client side javascript</strong>.</p>
<p>I also have a button on my page. When the user clicks the button I want to take the value from the custom control (aka. the textbox) and use it elsewhere.</p>
<p>So, in the onClick event for the button I do something like this:</p>
<pre><code>this.myLabel.Text = this.customControl.Value;
</code></pre>
<p>The problem is that the custom control does not have the new textbox value available. In the custom control the textbox is empty. However, I can see the correct value in the Request.Form collection.</p>
<p>Am I doing something wrong here? Or should I be reading from Request.Form?!</p>
|
[
{
"answer_id": 268297,
"author": "James",
"author_id": 7837,
"author_profile": "https://Stackoverflow.com/users/7837",
"pm_score": 2,
"selected": true,
"text": "<p>Ah ha! I've solved my own problem!</p>\n\n<p>Because I had set Readonly=\"True\" on the textbox control ASP.NET was not picking up it's value from the postback.</p>\n\n<p>Instead I should have manually added the readonly attribute to the textbox during my user control construction.</p>\n\n<p>eg.</p>\n\n<pre><code>this.textBox.Attributes.Add(\"readonly\", \"readonly\");\n</code></pre>\n"
},
{
"answer_id": 282427,
"author": "AndreasKnudsen",
"author_id": 36465,
"author_profile": "https://Stackoverflow.com/users/36465",
"pm_score": 2,
"selected": false,
"text": "<p>Interesting, I didn't realize readonly TextBox doesn't get updated from viewstate.</p>\n\n<p>When I pull stunts like that in my web sites, I usually setup asp:HiddenFields that I dump data into with javascript (gotta love jQuery), and that I read values from on postbacks.</p>\n\n<p>Keeps things cleaner I find.</p>\n"
},
{
"answer_id": 874799,
"author": "Ashraf Sabry",
"author_id": 95970,
"author_profile": "https://Stackoverflow.com/users/95970",
"pm_score": 0,
"selected": false,
"text": "<p>Strange that you answered yourself!\nIn fact, I've faced this nuisance before, and cost me some time until I found a note in the visual studio documentation describing the cause, you can read it here <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.readonly.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.readonly.aspx</a> in the \"important note\" section.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7837/"
] |
Ok guys and gals, here is my problem:
I've built a custom control that uses a textbox to present data to the user.
When the user interacts with the control the **value of that textbox is altered with client side javascript**.
I also have a button on my page. When the user clicks the button I want to take the value from the custom control (aka. the textbox) and use it elsewhere.
So, in the onClick event for the button I do something like this:
```
this.myLabel.Text = this.customControl.Value;
```
The problem is that the custom control does not have the new textbox value available. In the custom control the textbox is empty. However, I can see the correct value in the Request.Form collection.
Am I doing something wrong here? Or should I be reading from Request.Form?!
|
Ah ha! I've solved my own problem!
Because I had set Readonly="True" on the textbox control ASP.NET was not picking up it's value from the postback.
Instead I should have manually added the readonly attribute to the textbox during my user control construction.
eg.
```
this.textBox.Attributes.Add("readonly", "readonly");
```
|
268,182 |
<p>We've just been given the following code as a solution for a complicated search query in a new application provided by offshore developers. I'm skeptical of the use of dynamic SQL because I could close the SQL statement using '; and then excute a nasty that will be performed on the database!</p>
<p>Any ideas on how to fix the injection attack?</p>
<pre><code>ALTER procedure [dbo].[SearchVenues] --'','',10,1,1,''
@selectedFeature as varchar(MAX),
@searchStr as varchar(100),
@pageCount as int,
@startIndex as int,
@searchId as int,
@venueName as varchar(100),
@range int,
@latitude varchar(100),
@longitude varchar(100),
@showAll int,
@OrderBy varchar(50),
@SearchOrder varchar(10)
AS
DECLARE @sqlRowNum as varchar(max)
DECLARE @sqlRowNumWhere as varchar(max)
DECLARE @withFunction as varchar(max)
DECLARE @withFunction1 as varchar(max)
DECLARE @endIndex as int
SET @endIndex = @startIndex + @pageCount -1
SET @sqlRowNum = ' SELECT Row_Number() OVER (ORDER BY '
IF @OrderBy = 'Distance'
SET @sqlRowNum = @sqlRowNum + 'dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') ' +@SearchOrder
ELSE
SET @sqlRowNum = @sqlRowNum + @OrderBy + ' '+ @SearchOrder
SET @sqlRowNum = @sqlRowNum + ' ) AS RowNumber,ID,RecordId,EliteStatus,Name,Description,
Address,TotalReviews,AverageFacilityRating,AverageServiceRating,Address1,Address2,Address3,Address4,Address5,Address6,PhoneNumber,
visitCount,referalCount,requestCount,imgUrl,Latitude,Longitude,
Convert(decimal(10,2),dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ')) as distance
FROM VenueAllData '
SET @sqlRowNumWhere = 'where Enabled=1 and EliteStatus <> 3 '
--PRINT('@sqlRowNum ='+@sqlRowNum)
IF @searchStr <> ''
BEGIN
IF (@searchId = 1) -- county search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address5 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 2 ) -- Town search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address4 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 3 ) -- postcode search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address6 like ''' + @searchStr + '%'''
END
IF (@searchId = 4) -- Search By Name
BEGIN
IF @venueName <> ''
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
ELSE
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @searchStr + '%'' OR Address like ''%'+ @searchStr+'%'' ) '
END
END
IF @venueName <> '' AND @searchId <> 4
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
set @sqlRowNum = @sqlRowNum + ' ' + @sqlRowNumWhere
--PRINT(@sqlRowNum)
IF @selectedFeature <> ''
BEGIN
DECLARE @val1 varchar (255)
Declare @SQLAttributes varchar(max)
Set @SQLAttributes = ''
Declare @tempAttribute varchar(max)
Declare @AttrId int
while (@selectedFeature <> '')
BEGIN
SET @AttrId = CAST(SUBSTRING(@selectedFeature,1,CHARINDEX(',',@selectedFeature)-1) AS Int)
Select @tempAttribute = ColumnName from Attribute where id = @AttrId
SET @selectedFeature = SUBSTRING(@selectedFeature,len(@AttrId)+2,len(@selectedFeature))
SET @SQLAttributes = @SQLAttributes + ' ' + @tempAttribute + ' = 1 And '
END
Set @SQLAttributes = SUBSTRING(@SQLAttributes,0,LEN(@SQLAttributes)-3)
set @sqlRowNum = @sqlRowNum + ' and ID in (Select VenueId from '
set @sqlRowNum = @sqlRowNum + ' CachedVenueAttributes WHERE ' + @SQLAttributes + ') '
END
IF @showAll <> 1
set @sqlRowNum = @sqlRowNum + ' and dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') <= ' + convert(varchar,@range )
set @withFunction = 'WITH LogEntries AS (' + @sqlRowNum + ')
SELECT * FROM LogEntries WHERE RowNumber between '+ Convert(varchar,@startIndex) +
' and ' + Convert(varchar,@endIndex) + ' ORDER BY ' + @OrderBy + ' ' + @SearchOrder
print(@withFunction)
exec(@withFunction)
</code></pre>
|
[
{
"answer_id": 268190,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "<p>See this <a href=\"https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks\">answer</a>.</p>\n\n<p>Also, these:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/239905/am-i-immune-to-sql-injections-if-i-use-stored-procedures\">Am I immune to SQL injections if I use stored procedures?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/228476/avoiding-sql-injection-in-sql-query-with-like-operator-using-parameters\">Avoiding SQL Injection in SQL query with Like Operator using parameters?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/139199/can-i-protect-against-sql-injection-by-escaping-single-quote-and-surrounding-us\">Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?</a></p>\n"
},
{
"answer_id": 268199,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 4,
"selected": true,
"text": "<p>As an aside, I would not use <code>EXEC</code>; rather I would use <code>sp_executesql</code>. See this superb article, <a href=\"http://www.sommarskog.se/dynamic_sql.html\" rel=\"noreferrer\">The Curse and Blessings of Dynamic SQL</a>, for the reason and other info on using dynamic sql.</p>\n"
},
{
"answer_id": 268378,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an optimized version of the query above that doesn't use dynamic SQL...</p>\n\n<pre><code>Declare @selectedFeature as varchar(MAX),\n@searchStr as varchar(100),\n@pageCount as int,\n@startIndex as int,\n@searchId as int,\n@venueName as varchar(100),\n@range int,\n@latitude varchar(100),\n@longitude varchar(100),\n@showAll int,\n@OrderBy varchar(50),\n@SearchOrder varchar(10)\n\nSet @startIndex = 1\nSet @pageCount = 50\n\n\n\nSet @searchStr = 'e'\nSet @searchId = 4\nSet @OrderBy = 'Address1'\nSet @showAll = 1\n--Select dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude)\n\n\nDECLARE @endIndex int\nSET @endIndex = @startIndex + @pageCount -1\n;\n\nWITH LogEntries as (\nSELECT \n Row_Number() \n OVER (ORDER BY \n CASE @OrderBy\n WHEN 'Distance' THEN Cast(dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude) as varchar(10))\n WHEN 'Name' THEN Name\n WHEN 'Address1' THEN Address1\n WHEN 'RecordId' THEN Cast(RecordId as varchar(10))\n WHEN 'EliteStatus' THEN Cast(EliteStatus as varchar(10))\n END) AS RowNumber,\nRecordId,EliteStatus,Name,Description,\nAddress,TotalReviews,AverageFacilityRating,AverageServiceRating,Address1,Address2,Address3,Address4,Address5,Address6,PhoneNumber,\nvisitCount,referalCount,requestCount,imgUrl,Latitude,Longitude,\nConvert(decimal(10,2),dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude)) as distance\nFROM VenueAllData \nwhere Enabled=1 and EliteStatus <> 3\nAnd \n (\n (Address5 like @searchStr + '%' And @searchId = 1) OR\n (Address4 like @searchStr + '%' And @searchId = 2) OR\n (Address6 like @searchStr + '%' And @searchId = 3) OR\n (\n (\n @searchId = 4 And \n (Name like '%' + @venueName + '%' OR Address like '%'+ @searchStr+'%')\n )\n )\n )\nAnd\n ID in (\n Select VenueID \n From CachedVenueAttributes \n --Extra Where Clause for the processing of VenueAttributes using @selectedFeature\n )\nAnd\n ( \n (@showAll = 1) Or\n (@showAll <> 1 and dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude) <= convert(varchar,@range )) \n )\n)\n\nSELECT * FROM LogEntries \nWHERE RowNumber between @startIndex and @endIndex \nORDER BY CASE @OrderBy\n WHEN 'Distance' THEN Cast(Distance as varchar(10))\n WHEN 'Name' THEN Name\n WHEN 'Address1' THEN Address1\n WHEN 'RecordId' THEN Cast(RecordId as varchar(10))\n WHEN 'EliteStatus' THEN Cast(EliteStatus as varchar(10))\n END\n</code></pre>\n\n<p>The only thing I haven't fixed is the selection from CachedVenueAttributes that seems to build up a where statement in a loop. I think I might put this in a table valued function, and refactor it in isolation to the rest of the procedure.</p>\n"
},
{
"answer_id": 268462,
"author": "David Waters",
"author_id": 12148,
"author_profile": "https://Stackoverflow.com/users/12148",
"pm_score": 0,
"selected": false,
"text": "<p>I like dynamic SQL for search.</p>\n\n<p>Where I have used it in the past I have used .Net prepared statements with any user generated string being passed in as a parameter NOT included as text in the SQL. </p>\n\n<p>To run with the existing solution you can do a number of thing to mitigate risk.</p>\n\n<ol>\n<li>White list input, validate input so that it can only contain a-zA-Z0-9\\w (alpha numerics and white space) (bad if you need to support unicode chars)</li>\n<li>Execute any dynamic sql as a restricted user. Set owner of stored proc to a user which has only read access to the tables concerned. deny write to all tables ect. Also when calling this stored proc you may need to do it with a user with similar restrictions on what they can do, as it appares MS-SQL executes dynamic sql within a storedproc as the calling user not the owner of the storedproc. </li>\n</ol>\n"
},
{
"answer_id": 51430681,
"author": "Jeremy Giaco",
"author_id": 4325690,
"author_profile": "https://Stackoverflow.com/users/4325690",
"pm_score": 0,
"selected": false,
"text": "<p>I've realized that this is a really old post, but when doing things like:</p>\n\n<pre><code> AND\n ( \n (@showAll = 1) \n OR (@showAll <> 1 \n AND dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude) <= convert(varchar,@range)) \n )\n</code></pre>\n\n<p>... an <code>OPTION(RECOMPILE)</code> will usually help pick a more concise plan, as long as it's not going to be executed a thousand times per second or anything.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
We've just been given the following code as a solution for a complicated search query in a new application provided by offshore developers. I'm skeptical of the use of dynamic SQL because I could close the SQL statement using '; and then excute a nasty that will be performed on the database!
Any ideas on how to fix the injection attack?
```
ALTER procedure [dbo].[SearchVenues] --'','',10,1,1,''
@selectedFeature as varchar(MAX),
@searchStr as varchar(100),
@pageCount as int,
@startIndex as int,
@searchId as int,
@venueName as varchar(100),
@range int,
@latitude varchar(100),
@longitude varchar(100),
@showAll int,
@OrderBy varchar(50),
@SearchOrder varchar(10)
AS
DECLARE @sqlRowNum as varchar(max)
DECLARE @sqlRowNumWhere as varchar(max)
DECLARE @withFunction as varchar(max)
DECLARE @withFunction1 as varchar(max)
DECLARE @endIndex as int
SET @endIndex = @startIndex + @pageCount -1
SET @sqlRowNum = ' SELECT Row_Number() OVER (ORDER BY '
IF @OrderBy = 'Distance'
SET @sqlRowNum = @sqlRowNum + 'dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') ' +@SearchOrder
ELSE
SET @sqlRowNum = @sqlRowNum + @OrderBy + ' '+ @SearchOrder
SET @sqlRowNum = @sqlRowNum + ' ) AS RowNumber,ID,RecordId,EliteStatus,Name,Description,
Address,TotalReviews,AverageFacilityRating,AverageServiceRating,Address1,Address2,Address3,Address4,Address5,Address6,PhoneNumber,
visitCount,referalCount,requestCount,imgUrl,Latitude,Longitude,
Convert(decimal(10,2),dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ')) as distance
FROM VenueAllData '
SET @sqlRowNumWhere = 'where Enabled=1 and EliteStatus <> 3 '
--PRINT('@sqlRowNum ='+@sqlRowNum)
IF @searchStr <> ''
BEGIN
IF (@searchId = 1) -- county search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address5 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 2 ) -- Town search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address4 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 3 ) -- postcode search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address6 like ''' + @searchStr + '%'''
END
IF (@searchId = 4) -- Search By Name
BEGIN
IF @venueName <> ''
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
ELSE
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @searchStr + '%'' OR Address like ''%'+ @searchStr+'%'' ) '
END
END
IF @venueName <> '' AND @searchId <> 4
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
set @sqlRowNum = @sqlRowNum + ' ' + @sqlRowNumWhere
--PRINT(@sqlRowNum)
IF @selectedFeature <> ''
BEGIN
DECLARE @val1 varchar (255)
Declare @SQLAttributes varchar(max)
Set @SQLAttributes = ''
Declare @tempAttribute varchar(max)
Declare @AttrId int
while (@selectedFeature <> '')
BEGIN
SET @AttrId = CAST(SUBSTRING(@selectedFeature,1,CHARINDEX(',',@selectedFeature)-1) AS Int)
Select @tempAttribute = ColumnName from Attribute where id = @AttrId
SET @selectedFeature = SUBSTRING(@selectedFeature,len(@AttrId)+2,len(@selectedFeature))
SET @SQLAttributes = @SQLAttributes + ' ' + @tempAttribute + ' = 1 And '
END
Set @SQLAttributes = SUBSTRING(@SQLAttributes,0,LEN(@SQLAttributes)-3)
set @sqlRowNum = @sqlRowNum + ' and ID in (Select VenueId from '
set @sqlRowNum = @sqlRowNum + ' CachedVenueAttributes WHERE ' + @SQLAttributes + ') '
END
IF @showAll <> 1
set @sqlRowNum = @sqlRowNum + ' and dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') <= ' + convert(varchar,@range )
set @withFunction = 'WITH LogEntries AS (' + @sqlRowNum + ')
SELECT * FROM LogEntries WHERE RowNumber between '+ Convert(varchar,@startIndex) +
' and ' + Convert(varchar,@endIndex) + ' ORDER BY ' + @OrderBy + ' ' + @SearchOrder
print(@withFunction)
exec(@withFunction)
```
|
As an aside, I would not use `EXEC`; rather I would use `sp_executesql`. See this superb article, [The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html), for the reason and other info on using dynamic sql.
|
268,184 |
<p>I have classX: </p>
<p>Sub New(ByVal item_line_no As String, ByVal item_text As String)</p>
<pre><code> ' check to ensure that the parameters do not exceed the file template limits
Select Case item_line_no.Length
Case Is > m_item_line_no_capacity
Throw New ArgumentOutOfRangeException(item_line_no, "Line No exceeds 4 characters")
Case Else
Me.m_item_line_no = item_line_no
End Select
Select Case item_text.Length
Case Is > m_item_free_text_capacity
Throw New ArgumentOutOfRangeException("Free Text Exceeds 130 characters")
Case Else
Me.m_item_free_text = item_text
End Select
End Sub
</code></pre>
<p>and the following unti to test one point of failure</p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")> _
<Test()> _
Sub testLineNoExceedsMaxLength()
Dim it As New X("aaaaa", "Test")
End Sub
</code></pre>
<p>When I run the test I expect to get the message thrown in the exception "Line No exceeds 4 characters"</p>
<p>However the unit test fails with the following message</p>
<pre><code>RecordTests.testLineNoExceedsMaxLength : FailedExpected exception message: Line No exceeds 4 characters
got: Line No exceeds 4 characters
Parameter name: aaaaa
</code></pre>
<p>I think the something simple but it driving me insane. </p>
<p>NOTE: in the declaration of the ExpectedException I get an obsolete warning stating that instead of </p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")>
</code></pre>
<p>it should be </p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedException="Line No exceeds 4 characters")>
</code></pre>
<p>However this throws a ExpectedException is not declared error! </p>
|
[
{
"answer_id": 268276,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "<p><s>The <code>ExpectedExceptionAttribute</code> is deprecated - i.e. you shouldn't use it at all. The best reference I could quickly find about this was this post (the original article is here).</s></p>\n\n<p>Your unit test would be a lot clearer if it was re-written:</p>\n\n<pre><code><Test()> _\nSub testLineNoExceedsMaxLength()\n Try\n\n Dim it As New X(\"aaaaa\", \"Test\")\n\n Catch ex as ArgumentOutOfRangeExcpetion\n\n Assert.That ( ex.Message, Is.Equal(\"Line No exceeds 4 characters\") )\n\n End Try\n\nEnd Sub\n</code></pre>\n\n<p>See also these articles </p>\n\n<ul>\n<li><a href=\"http://steve.emxsoftware.com/TDD/NUnit+and+the+ExpectedExceptionAttribute\" rel=\"nofollow noreferrer\">This one</a>, and</li>\n<li><a href=\"http://web.archive.org/web/20040228223704/http://cgi.skizz.plus.com/blog/dev/archives/000075.html\" rel=\"nofollow noreferrer\" title=\"Praise god for the Way Back Machine\">This one</a>.</li>\n</ul>\n"
},
{
"answer_id": 268292,
"author": "Dean",
"author_id": 11802,
"author_profile": "https://Stackoverflow.com/users/11802",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure I agree with your comment of the ExpectedException attribute being deprecated. </p>\n\n<p>It is still supported perfectly fine in 2.4 (version I am using) it is the ExpectedMessage in this case which is causing the deprecation issue</p>\n\n<p><a href=\"http://www.nunit.org/index.php?p=exception&r=2.4\" rel=\"nofollow noreferrer\">uUnit Exception Guide</a></p>\n"
},
{
"answer_id": 268313,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 3,
"selected": true,
"text": "<p>Ok. Just run this.</p>\n<p>The message for the exception is:</p>\n<blockquote>\n<p><strong>Line No exceeds 4 characters</strong></p>\n<p><strong>Parameter name: aaaaa</strong></p>\n</blockquote>\n<p>(Including the line break)</p>\n<p>You need to specify this all of this as the expected message:</p>\n<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedMessage="Line No exceeds 4 characters" & VbCrLf & "Parameter name: aaaaa")>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
I have classX:
Sub New(ByVal item\_line\_no As String, ByVal item\_text As String)
```
' check to ensure that the parameters do not exceed the file template limits
Select Case item_line_no.Length
Case Is > m_item_line_no_capacity
Throw New ArgumentOutOfRangeException(item_line_no, "Line No exceeds 4 characters")
Case Else
Me.m_item_line_no = item_line_no
End Select
Select Case item_text.Length
Case Is > m_item_free_text_capacity
Throw New ArgumentOutOfRangeException("Free Text Exceeds 130 characters")
Case Else
Me.m_item_free_text = item_text
End Select
End Sub
```
and the following unti to test one point of failure
```
<ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")> _
<Test()> _
Sub testLineNoExceedsMaxLength()
Dim it As New X("aaaaa", "Test")
End Sub
```
When I run the test I expect to get the message thrown in the exception "Line No exceeds 4 characters"
However the unit test fails with the following message
```
RecordTests.testLineNoExceedsMaxLength : FailedExpected exception message: Line No exceeds 4 characters
got: Line No exceeds 4 characters
Parameter name: aaaaa
```
I think the something simple but it driving me insane.
NOTE: in the declaration of the ExpectedException I get an obsolete warning stating that instead of
```
<ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")>
```
it should be
```
<ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedException="Line No exceeds 4 characters")>
```
However this throws a ExpectedException is not declared error!
|
Ok. Just run this.
The message for the exception is:
>
> **Line No exceeds 4 characters**
>
>
> **Parameter name: aaaaa**
>
>
>
(Including the line break)
You need to specify this all of this as the expected message:
```
<ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedMessage="Line No exceeds 4 characters" & VbCrLf & "Parameter name: aaaaa")>
```
|
268,208 |
<p>I have a Windows Service written in Delphi which runs a number of programs. </p>
<p>On Stopping the service, I want to also close these programs. When the service was originally written, this worked fine, but I think I've updated the tProcess component and now - The subordinate programs are not being closed. </p>
<p>in tProcess - Here's the code which starts the new processes. </p>
<pre><code> if CreateProcess( nil , PChar( FProcess.Command ) , nil , nil , False ,
NORMAL_PRIORITY_CLASS , nil , Directory ,
StartupInfo , ProcessInfo ) then
begin
if FProcess.Wait then
begin
WaitForSingleObject( ProcessInfo.hProcess , Infinite );
GetExitCodeProcess( ProcessInfo.hProcess , ExitCode );
if Assigned( FProcess.FOnFinished ) then
FProcess.FOnFinished( FProcess , ExitCode );
end;
CloseHandle( ProcessInfo.hProcess );
CloseHandle( ProcessInfo.hThread );
end;
</code></pre>
<p>Each of the executables called by this are Windows GUI Programs (With a close button at the top). </p>
<p>When I stop the service, I also want to stop (not kill) the programs I've started up via the createProcess procedure. </p>
<p>How would you do this? </p>
|
[
{
"answer_id": 268314,
"author": "utku_karatas",
"author_id": 14716,
"author_profile": "https://Stackoverflow.com/users/14716",
"pm_score": 2,
"selected": false,
"text": "<p>I'd use <strong>TJvCreateProcess</strong> component of <a href=\"http://jvcl.sourceforge.net/\" rel=\"nofollow noreferrer\">JVCL</a> which wraps about any process related functionality of win32 in a graceful way. This answer comes from Dont-touch-winapi-unless-really-required department :-)</p>\n"
},
{
"answer_id": 277040,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 1,
"selected": false,
"text": "<p>The only generic way to stop a process is to use <a href=\"http://msdn.microsoft.com/en-us/library/ms686714.aspx\" rel=\"nofollow noreferrer\">TerminateProcess</a>. But that's as far from graceful as you can get. To gracefully close a process, you need to tell the process that you'd like it to stop, and then hope it obeys. There is no way to do that in general, though.</p>\n\n<p>For a GUI program, the usual way to tell it that you want it to stop running is to close its main window. There's no formal idea of \"main window,\" though. A program can have zero or more windows, and there's no way to know externally which one you're supposed to close in order to make the program stop working.</p>\n\n<p>You could use <a href=\"http://msdn.microsoft.com/en-us/library/ms633497.aspx\" rel=\"nofollow noreferrer\">EnumWindows</a> to cycle through all the windows and select the ones that belong to your process. (They'd be the ones for which <a href=\"http://msdn.microsoft.com/en-us/library/ms633522.aspx\" rel=\"nofollow noreferrer\">GetWindowThreadProcessId</a> gives the same process ID that CreateProcess gave you.)</p>\n\n<p>Closing a window might not be enough. The program might display a dialog box (prompting for confirmation, or asking to save changes, etc.). You would need to know in advance how to dismiss that dialog box.</p>\n\n<p>Non-GUI programs can have similar problems. It might be enough to simulate a Ctrl+C keystroke. It might catch and handle that keystroke differently, though. It might have a menu system that expects you to type \"Q\" to quit the program.</p>\n\n<p>In short, you cannot gracefully close a program unless you know in advance how that program expects to be closed.</p>\n"
},
{
"answer_id": 277086,
"author": "Darian Miller",
"author_id": 35696,
"author_profile": "https://Stackoverflow.com/users/35696",
"pm_score": 2,
"selected": true,
"text": "<p>You want to enumerate open windows that match your launched ProcessId and tell those windows to close. Here's some sample code for that:</p>\n\n<pre><code>uses Windows;\n\ninterface \n\nfunction MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean; stdcall;\n\nimplementation\n\nfunction MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean; \nvar \n vID:DWORD; \nbegin \n GetWindowThreadProcessID(hHwnd, @vID); \n if vID = dwData then \n begin\n PostMessage(hHwnd, WM_CLOSE, 0, 0); //tell window to close gracefully\n Result := False; //can stop enumerating \n end \n else \n begin\n Result := TRUE; //keep enumerating until you find your id \n end; \nend;\n</code></pre>\n\n<p>Then you'll want to utilize this in your code when you want to shut down the launched applications:</p>\n\n<pre><code>Procedure TerminateMe(YourSavedProcessInfo:TProcessInformation);\nvar\n vExitCode:UINT;\nbegin\n GetExitCodeProcess(YourSavedProcessInfo.hProcess, vExitCode);\n if (vExitCode = STILL_ACTIVE) then //launched app still running..\n begin\n //tell it to close\n EnumWindows(@MyTerminateAppEnum, YourSavedProcessInfo.dwProcessId);\n\n if WaitForSingleObject(YourSavedProcessInfo.hProcess, TIMEOUT_VAL) <> WAIT_OBJECT_0 then\n begin\n if not TerminateProcess(YourSavedProcessInfo.hProcess, 0) then //didn't close, try to terminate\n begin\n //uh-oh Didn't close, didn't terminate..\n end;\n end;\n end;\n CloseHandle(YourSavedProcessInfo.hProcess);\n CloseHandle(YourSavedProcessInfo.hThread);\nend;\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
I have a Windows Service written in Delphi which runs a number of programs.
On Stopping the service, I want to also close these programs. When the service was originally written, this worked fine, but I think I've updated the tProcess component and now - The subordinate programs are not being closed.
in tProcess - Here's the code which starts the new processes.
```
if CreateProcess( nil , PChar( FProcess.Command ) , nil , nil , False ,
NORMAL_PRIORITY_CLASS , nil , Directory ,
StartupInfo , ProcessInfo ) then
begin
if FProcess.Wait then
begin
WaitForSingleObject( ProcessInfo.hProcess , Infinite );
GetExitCodeProcess( ProcessInfo.hProcess , ExitCode );
if Assigned( FProcess.FOnFinished ) then
FProcess.FOnFinished( FProcess , ExitCode );
end;
CloseHandle( ProcessInfo.hProcess );
CloseHandle( ProcessInfo.hThread );
end;
```
Each of the executables called by this are Windows GUI Programs (With a close button at the top).
When I stop the service, I also want to stop (not kill) the programs I've started up via the createProcess procedure.
How would you do this?
|
You want to enumerate open windows that match your launched ProcessId and tell those windows to close. Here's some sample code for that:
```
uses Windows;
interface
function MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean; stdcall;
implementation
function MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean;
var
vID:DWORD;
begin
GetWindowThreadProcessID(hHwnd, @vID);
if vID = dwData then
begin
PostMessage(hHwnd, WM_CLOSE, 0, 0); //tell window to close gracefully
Result := False; //can stop enumerating
end
else
begin
Result := TRUE; //keep enumerating until you find your id
end;
end;
```
Then you'll want to utilize this in your code when you want to shut down the launched applications:
```
Procedure TerminateMe(YourSavedProcessInfo:TProcessInformation);
var
vExitCode:UINT;
begin
GetExitCodeProcess(YourSavedProcessInfo.hProcess, vExitCode);
if (vExitCode = STILL_ACTIVE) then //launched app still running..
begin
//tell it to close
EnumWindows(@MyTerminateAppEnum, YourSavedProcessInfo.dwProcessId);
if WaitForSingleObject(YourSavedProcessInfo.hProcess, TIMEOUT_VAL) <> WAIT_OBJECT_0 then
begin
if not TerminateProcess(YourSavedProcessInfo.hProcess, 0) then //didn't close, try to terminate
begin
//uh-oh Didn't close, didn't terminate..
end;
end;
end;
CloseHandle(YourSavedProcessInfo.hProcess);
CloseHandle(YourSavedProcessInfo.hThread);
end;
```
|
268,272 |
<p>I have a dictionary where keys are strings, and values are integers.</p>
<pre><code>stats = {'a': 1, 'b': 3000, 'c': 0}
</code></pre>
<p>How do I get the key with the maximum value? In this case, it is <code>'b'</code>.</p>
<hr />
<p>Is there a nicer approach than using an intermediate list with reversed key-value tuples?</p>
<pre><code>inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
</code></pre>
|
[
{
"answer_id": 268285,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 11,
"selected": true,
"text": "<p>You can use <code>operator.itemgetter</code> for that:</p>\n<pre><code>import operator\nstats = {'a': 1000, 'b': 3000, 'c': 100}\nmax(stats.iteritems(), key=operator.itemgetter(1))[0]\n</code></pre>\n<p>And instead of building a new list in memory use <code>stats.iteritems()</code>. The <code>key</code> parameter to the <code>max()</code> function is a function that computes a key that is used to determine how to rank items.</p>\n<p>Please note that if you were to have another key-value pair 'd': 3000 that this method will only return <strong>one</strong> of the <strong>two</strong> even though they both have the maximum value.</p>\n<pre><code>>>> import operator\n>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}\n>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]\n'b' \n</code></pre>\n<p>If using Python3:</p>\n<pre><code>>>> max(stats.items(), key=operator.itemgetter(1))[0]\n'b'\n</code></pre>\n"
},
{
"answer_id": 268350,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Here is another one:</p>\n\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100}\nmax(stats.iterkeys(), key=lambda k: stats[k])\n</code></pre>\n\n<p>The function <code>key</code> simply returns the value that should be used for ranking and <code>max()</code> returns the demanded element right away.</p>\n"
},
{
"answer_id": 272269,
"author": "Tim Ottinger",
"author_id": 15929,
"author_profile": "https://Stackoverflow.com/users/15929",
"pm_score": 5,
"selected": false,
"text": "<pre><code>key, value = max(stats.iteritems(), key=lambda x:x[1])\n</code></pre>\n\n<p>If you don't care about value (I'd be surprised, but) you can do:</p>\n\n<pre><code>key, _ = max(stats.iteritems(), key=lambda x:x[1])\n</code></pre>\n\n<p>I like the tuple unpacking better than a [0] subscript at the end of the expression.\nI never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.</p>\n"
},
{
"answer_id": 280156,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 11,
"selected": false,
"text": "<pre><code>max(stats, key=stats.get)\n</code></pre>\n"
},
{
"answer_id": 12343826,
"author": "the wolf",
"author_id": 455276,
"author_profile": "https://Stackoverflow.com/users/455276",
"pm_score": 8,
"selected": false,
"text": "<p>I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:</p>\n<pre><code>def keywithmaxval(d):\n """ a) create a list of the dict's keys and values; \n b) return the key with the max value""" \n v = list(d.values())\n k = list(d.keys())\n return k[v.index(max(v))]\n</code></pre>\n<p>To give you an idea, here are some candidate methods:</p>\n<pre><code>def f1(): \n v = list(d1.values())\n k = list(d1.keys())\n return k[v.index(max(v))]\n \ndef f2():\n d3 = {v: k for k,v in d1.items()}\n return d3[max(d3)]\n \ndef f3():\n return list(filter(lambda t: t[1] == max(d1.values()), d1.items()))[0][0] \n \ndef f3b():\n # same as f3 but remove the call to max from the lambda\n m = max(d1.values())\n return list(filter(lambda t: t[1] == m, d1.items()))[0][0] \n \ndef f4():\n return [k for k, v in d1.items() if v == max(d1.values())][0] \n \ndef f4b():\n # same as f4 but remove the max from the comprehension\n m = max(d1.values())\n return [k for k,v in d1.items() if v == m][0] \n \ndef f5():\n return max(d1.items(), key=operator.itemgetter(1))[0] \n \ndef f6():\n return max(d1, key=d1.get) \n \ndef f7():\n """ a) create a list of the dict's keys and values; \n b) return the key with the max value""" \n v = list(d1.values())\n return list(d1.keys())[v.index(max(v))] \n \ndef f8():\n return max(d1, key=lambda k: d1[k]) \n \ntl = [f1, f2, f3b, f4b, f5, f6, f7, f8, f4, f3] \ncmpthese.cmpthese(tl, c=100) \n</code></pre>\n<p>The test dictionary:</p>\n<pre><code>d1 = {1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, \n 12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, \n 21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, \n 30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22, \n 39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12, \n 49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33, \n 58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28, \n 68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23, \n 78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31, \n 88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35, \n 98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63, \n 2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21, \n 124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16, \n 142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11, \n 161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32, \n 182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89, \n 208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84, \n 238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30, \n 263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118, \n 296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25, \n 55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108, \n 377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103, \n 1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23, \n 6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119, \n 592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41, \n 700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78, \n 1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99, \n 976: 24, 166: 112}\n</code></pre>\n<p>And the test results under Python 3.2:</p>\n<pre><code> rate/sec f4 f3 f3b f8 f5 f2 f4b f6 f7 f1\nf4 454 -- -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0%\nf3 466 2.6% -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0%\nf3b 14,715 3138.9% 3057.4% -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4%\nf8 18,070 3877.3% 3777.3% 22.8% -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2%\nf5 33,091 7183.7% 7000.5% 124.9% 83.1% -- -1.0% -2.0% -6.3% -18.6% -29.0%\nf2 33,423 7256.8% 7071.8% 127.1% 85.0% 1.0% -- -1.0% -5.3% -17.7% -28.3%\nf4b 33,762 7331.4% 7144.6% 129.4% 86.8% 2.0% 1.0% -- -4.4% -16.9% -27.5%\nf6 35,300 7669.8% 7474.4% 139.9% 95.4% 6.7% 5.6% 4.6% -- -13.1% -24.2%\nf7 40,631 8843.2% 8618.3% 176.1% 124.9% 22.8% 21.6% 20.3% 15.1% -- -12.8%\nf1 46,598 10156.7% 9898.8% 216.7% 157.9% 40.8% 39.4% 38.0% 32.0% 14.7% --\n</code></pre>\n<p>And under Python 2.7:</p>\n<pre><code> rate/sec f3 f4 f8 f3b f6 f5 f2 f4b f7 f1\nf3 384 -- -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2%\nf4 394 2.6% -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1%\nf8 13,079 3303.3% 3216.1% -- -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2%\nf3b 13,852 3504.5% 3412.1% 5.9% -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5%\nf6 18,325 4668.4% 4546.2% 40.1% 32.3% -- -1.8% -5.9% -13.5% -29.5% -59.6%\nf5 18,664 4756.5% 4632.0% 42.7% 34.7% 1.8% -- -4.1% -11.9% -28.2% -58.8%\nf2 19,470 4966.4% 4836.5% 48.9% 40.6% 6.2% 4.3% -- -8.1% -25.1% -57.1%\nf4b 21,187 5413.0% 5271.7% 62.0% 52.9% 15.6% 13.5% 8.8% -- -18.5% -53.3%\nf7 26,002 6665.8% 6492.4% 98.8% 87.7% 41.9% 39.3% 33.5% 22.7% -- -42.7%\nf1 45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1% 74.4% -- \n</code></pre>\n<p>You can see that <code>f1</code> is the fastest under Python 3.2 and 2.7 (or, more completely, <code>keywithmaxval</code> at the top of this post)</p>\n"
},
{
"answer_id": 17217820,
"author": "Erika Sawajiri",
"author_id": 2369716,
"author_profile": "https://Stackoverflow.com/users/2369716",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Counter = 0\nfor word in stats.keys():\n if stats[word]> counter:\n Counter = stats [word]\nprint Counter\n</code></pre>\n"
},
{
"answer_id": 23428922,
"author": "Climbs_lika_Spyder",
"author_id": 1290485,
"author_profile": "https://Stackoverflow.com/users/1290485",
"pm_score": 5,
"selected": false,
"text": "<p>Given that more than one entry my have the max value. I would make a list of the keys that have the max value as their value.</p>\n\n<pre><code>>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}\n>>> [key for m in [max(stats.values())] for key,val in stats.iteritems() if val == m]\n['b', 'd']\n</code></pre>\n\n<p>This will give you 'b' and any other max key as well.</p>\n\n<p>Note: For python 3 use <code>stats.items()</code> instead of <code>stats.iteritems()</code></p>\n"
},
{
"answer_id": 30043094,
"author": "watsonic",
"author_id": 695804,
"author_profile": "https://Stackoverflow.com/users/695804",
"pm_score": 4,
"selected": false,
"text": "<p>Per the iterated solutions via comments in the selected answer... </p>\n\n<p>In Python 3:</p>\n\n<pre><code>max(stats.keys(), key=(lambda k: stats[k]))\n</code></pre>\n\n<p>In Python 2:</p>\n\n<pre><code>max(stats.iterkeys(), key=(lambda k: stats[k]))\n</code></pre>\n"
},
{
"answer_id": 35256685,
"author": "I159",
"author_id": 629685,
"author_profile": "https://Stackoverflow.com/users/629685",
"pm_score": 6,
"selected": false,
"text": "<p>If you need to know only a key with the max value you can do it without <code>iterkeys</code> or <code>iteritems</code> because iteration through dictionary in Python is iteration through it's keys.</p>\n<pre><code>max_key = max(stats, key=lambda k: stats[k])\n</code></pre>\n<p><strong>EDIT:</strong></p>\n<p><em>From comments, @user1274878 :</em></p>\n<blockquote>\n<p>I am new to python. Can you please explain your answer in steps?</p>\n</blockquote>\n<p>Yep...</p>\n<h3>max</h3>\n<blockquote>\n<p>max(iterable[, key])</p>\n<p>max(arg1, arg2, *args[, key])</p>\n<p>Return the largest item in an iterable or the largest of two or more arguments.</p>\n</blockquote>\n<p>The optional <code>key</code> argument describes how to compare elements to get maximum among them:</p>\n<pre><code>lambda <item>: return <a result of operation with item> \n</code></pre>\n<p>Returned values will be compared.</p>\n<h3>Dict</h3>\n<p>Python dict is a hash table. A key of dict is a hash of an object declared as a key. Due to performance reasons iteration though a dict implemented as iteration through it's keys.</p>\n<p>Therefore we can use it to rid operation of obtaining a keys list.</p>\n<h3>Closure</h3>\n<blockquote>\n<p>A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope.</p>\n</blockquote>\n<p>The <code>stats</code> variable available through <code>__closure__</code> attribute of the <code>lambda</code> function as a pointer to the value of the variable defined in the parent scope.</p>\n"
},
{
"answer_id": 35585900,
"author": "ukrutt",
"author_id": 3061818,
"author_profile": "https://Stackoverflow.com/users/3061818",
"pm_score": 3,
"selected": false,
"text": "<p>With <code>collections.Counter</code> you could do</p>\n\n<pre><code>>>> import collections\n>>> stats = {'a':1000, 'b':3000, 'c': 100}\n>>> stats = collections.Counter(stats)\n>>> stats.most_common(1)\n[('b', 3000)]\n</code></pre>\n\n<p>If appropriate, you could simply start with an empty <code>collections.Counter</code> and add to it</p>\n\n<pre><code>>>> stats = collections.Counter()\n>>> stats['a'] += 1\n:\netc. \n</code></pre>\n"
},
{
"answer_id": 44088725,
"author": "Woooody Amadeus",
"author_id": 7375748,
"author_profile": "https://Stackoverflow.com/users/7375748",
"pm_score": 2,
"selected": false,
"text": "<p>+1 to <a href=\"https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary#comment73465439_280156\">@Aric Coady</a>'s simplest solution. <br>\nAnd also one way to random select one of keys with max value in the dictionary:<br></p>\n\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}\n\nimport random\nmaxV = max(stats.values())\n# Choice is one of the keys with max value\nchoice = random.choice([key for key, value in stats.items() if value == maxV])\n</code></pre>\n"
},
{
"answer_id": 45035132,
"author": "ragardner",
"author_id": 7655687,
"author_profile": "https://Stackoverflow.com/users/7655687",
"pm_score": 0,
"selected": false,
"text": "<p>I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:</p>\n\n<pre><code>import time\nimport operator\n\n\nd = {\"a\"+str(i): i for i in range(1000000)}\n\ndef t1(dct):\n mx = float(\"-inf\")\n key = None\n for k,v in dct.items():\n if v > mx:\n mx = v\n key = k\n return key\n\ndef t2(dct):\n v=list(dct.values())\n k=list(dct.keys())\n return k[v.index(max(v))]\n\ndef t3(dct):\n return max(dct.items(),key=operator.itemgetter(1))[0]\n\nstart = time.time()\nfor i in range(25):\n m = t1(d)\nend = time.time()\nprint (\"Iterating: \"+str(end-start))\n\nstart = time.time()\nfor i in range(25):\n m = t2(d)\nend = time.time()\nprint (\"List creating: \"+str(end-start))\n\nstart = time.time()\nfor i in range(25):\n m = t3(d)\nend = time.time()\nprint (\"Accepted answer: \"+str(end-start))\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>Iterating: 3.8201940059661865\nList creating: 6.928712844848633\nAccepted answer: 5.464320182800293\n</code></pre>\n"
},
{
"answer_id": 46043740,
"author": "user2399453",
"author_id": 2399453,
"author_profile": "https://Stackoverflow.com/users/2399453",
"pm_score": 1,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code> max(zip(stats.keys(), stats.values()), key=lambda t : t[1])[0]\n</code></pre>\n"
},
{
"answer_id": 47854612,
"author": "Karim Sonbol",
"author_id": 1802750,
"author_profile": "https://Stackoverflow.com/users/1802750",
"pm_score": 5,
"selected": false,
"text": "<p>To get the maximum key/value of the dictionary <code>stats</code>:</p>\n\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100}\n</code></pre>\n\n<ul>\n<li>Based on <strong>keys</strong></li>\n</ul>\n\n<p><code>>>> max(stats.items(), key = lambda x: x[0])\n('c', 100)</code></p>\n\n<ul>\n<li>Based on <strong>values</strong></li>\n</ul>\n\n<p><code>>>> max(stats.items(), key = lambda x: x[1])\n('b', 3000)</code></p>\n\n<p>Of course, if you want to get only the key or value from the result, you can use tuple indexing. For Example, to get the key corresponding to the maximum value:</p>\n\n<p><code>>>> max(stats.items(), key = lambda x: x[1])[0]\n'b'</code></p>\n\n<p><strong>Explanation</strong></p>\n\n<p>The dictionary method <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.items\" rel=\"noreferrer\"><code>items()</code></a> in Python 3 returns a <a href=\"https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects\" rel=\"noreferrer\">view object</a> of the dictionary. When this view object is iterated over, by the <code>max</code> function, it yields the dictionary items as tuples of the form <code>(key, value)</code>.</p>\n\n<p><code>>>> list(stats.items())\n[('c', 100), ('b', 3000), ('a', 1000)]</code></p>\n\n<p>When you use the <a href=\"https://docs.python.org/3/reference/expressions.html#lambda\" rel=\"noreferrer\"><code>lambda</code></a> expression <code>lambda x: x[1]</code>, in each iteration, <code>x</code> is one of these tuples <code>(key, value)</code>. So, by choosing the right index, you select whether you want to compare by keys or by values.</p>\n\n<p><strong>Python 2</strong></p>\n\n<p>For Python 2.2+ releases, the same code will work. However, it is better to use <a href=\"https://docs.python.org/2/library/stdtypes.html#dict.iteritems\" rel=\"noreferrer\"><code>iteritems()</code></a> dictionary method instead of <a href=\"https://docs.python.org/2/library/stdtypes.html#dict.items\" rel=\"noreferrer\"><code>items()</code></a> for performance.</p>\n\n<p><strong>Notes</strong></p>\n\n<ul>\n<li><p>This answer is based on the comments on <a href=\"https://stackoverflow.com/a/268285/1802750\">Climbs_lika_Spyder's answer</a>.</p></li>\n<li><p>The used code was tested on Python 3.5.2 and Python 2.7.10 . </p></li>\n</ul>\n"
},
{
"answer_id": 48180876,
"author": "Jasha",
"author_id": 4256346,
"author_profile": "https://Stackoverflow.com/users/4256346",
"pm_score": 3,
"selected": false,
"text": "<p><code>max((value, key) for key, value in stats.items())[1]</code></p>\n"
},
{
"answer_id": 50168872,
"author": "priya khokher",
"author_id": 5638335,
"author_profile": "https://Stackoverflow.com/users/5638335",
"pm_score": 4,
"selected": false,
"text": "<pre><code>d = {'A': 4,'B':10}\n\nmin_v = min(zip(d.values(), d.keys()))\n# min_v is (4,'A')\n\nmax_v = max(zip(d.values(), d.keys()))\n# max_v is (10,'B')\n</code></pre>\n"
},
{
"answer_id": 51978193,
"author": "leo022",
"author_id": 10132167,
"author_profile": "https://Stackoverflow.com/users/10132167",
"pm_score": 6,
"selected": false,
"text": "<p>Example:</p>\n\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100}\n</code></pre>\n\n<p>if you wanna find the max value with its key, maybe follwing could be simple, without any relevant functions.</p>\n\n<pre><code>max(stats, key=stats.get)\n</code></pre>\n\n<p>the output is the key which has the max value.</p>\n"
},
{
"answer_id": 52292146,
"author": "ron_g",
"author_id": 4916945,
"author_profile": "https://Stackoverflow.com/users/4916945",
"pm_score": 4,
"selected": false,
"text": "<p>I got here looking for how to return <code>mydict.keys()</code> based on the value of <code>mydict.values()</code>. Instead of just the one key returned, I was looking to return the top <em>x</em> number of values.</p>\n\n<p>This solution is simpler than using the <code>max()</code> function and you can easily change the number of values returned:</p>\n\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100}\n\nx = sorted(stats, key=(lambda key:stats[key]), reverse=True)\n['b', 'a', 'c']\n</code></pre>\n\n<p>If you want the single highest ranking key, just use the index:</p>\n\n<pre><code>x[0]\n['b']\n</code></pre>\n\n<p>If you want the top two highest ranking keys, just use list slicing:</p>\n\n<pre><code>x[:2]\n['b', 'a']\n</code></pre>\n"
},
{
"answer_id": 53100002,
"author": "jpp",
"author_id": 9209546,
"author_profile": "https://Stackoverflow.com/users/9209546",
"pm_score": 3,
"selected": false,
"text": "<p>A heap queue is a <strong>generalised</strong> solution which allows you to extract the top <em>n</em> keys ordered by value:</p>\n\n<pre><code>from heapq import nlargest\n\nstats = {'a':1000, 'b':3000, 'c': 100}\n\nres1 = nlargest(1, stats, key=stats.__getitem__) # ['b']\nres2 = nlargest(2, stats, key=stats.__getitem__) # ['b', 'a']\n\nres1_val = next(iter(res1)) # 'b'\n</code></pre>\n\n<p>Note <code>dict.__getitem__</code> is the method called by the syntactic sugar <code>dict[]</code>. As opposed to <code>dict.get</code>, it will return <code>KeyError</code> if a key is not found, which here cannot occur.</p>\n"
},
{
"answer_id": 57559867,
"author": "kslote1",
"author_id": 2507311,
"author_profile": "https://Stackoverflow.com/users/2507311",
"pm_score": 4,
"selected": false,
"text": "<p>I was not satisfied with any of these answers. <code>max</code> always picks the first key with the max value. The dictionary could have multiple keys with that value.</p>\n\n<pre><code>def keys_with_top_values(my_dict):\n return [key for (key, value) in my_dict.items() if value == max(my_dict.values())]\n</code></pre>\n\n<p>Posting this answer in case it helps someone out.\nSee the below SO post</p>\n\n<p><a href=\"https://stackoverflow.com/questions/6783000/which-maximum-does-python-pick-in-the-case-of-a-tie\">Which maximum does Python pick in the case of a tie?</a></p>\n"
},
{
"answer_id": 60209561,
"author": "Ignacio Alorre",
"author_id": 1773841,
"author_profile": "https://Stackoverflow.com/users/1773841",
"pm_score": 0,
"selected": false,
"text": "<p>In the case you have more than one key with the same value, for example:</p>\n\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}\n</code></pre>\n\n<p>You could get a collection with all the keys with max value as follow:</p>\n\n<pre><code>from collections import defaultdict\nfrom collections import OrderedDict\n\ngroupedByValue = defaultdict(list)\nfor key, value in sorted(stats.items()):\n groupedByValue[value].append(key)\n\n# {1000: ['a'], 3000: ['b', 'd', 'e'], 100: ['c']}\n\ngroupedByValue[max(groupedByValue)]\n# ['b', 'd', 'e']\n</code></pre>\n"
},
{
"answer_id": 60219795,
"author": "wkzhu",
"author_id": 7327411,
"author_profile": "https://Stackoverflow.com/users/7327411",
"pm_score": 2,
"selected": false,
"text": "<p>For scientific python users, here is a simple solution using Pandas:</p>\n<pre><code>import pandas as pd\npd.Series({'a': 1000, 'b': 3000, 'c': 100}).idxmax()\n\n>>> b\n</code></pre>\n"
},
{
"answer_id": 60230912,
"author": "pk786",
"author_id": 3827844,
"author_profile": "https://Stackoverflow.com/users/3827844",
"pm_score": 7,
"selected": false,
"text": "<p>You can use:</p>\n<pre><code>max(d, key=d.get) \n# which is equivalent to \nmax(d, key=lambda k: d.get(k))\n</code></pre>\n<p>To return the key-value pair use:</p>\n<pre><code>max(d.items(), key=lambda k: k[1])\n</code></pre>\n"
},
{
"answer_id": 62152615,
"author": "Ali Sajjad",
"author_id": 12065150,
"author_profile": "https://Stackoverflow.com/users/12065150",
"pm_score": 3,
"selected": false,
"text": "<p>Much simpler to understand approach:</p>\n<pre><code>mydict = { 'a':302, 'e':53, 'g':302, 'h':100 }\nmax_value_keys = [key for key in mydict.keys() if mydict[key] == max(mydict.values())]\nprint(max_value_keys) # prints a list of keys with max value\n</code></pre>\n<p><strong>Output:</strong> ['a', 'g']</p>\n<p>Now you can choose only one key:</p>\n<pre><code>maximum = mydict[max_value_keys[0]]\n</code></pre>\n"
},
{
"answer_id": 63745002,
"author": "Bhindi",
"author_id": 3839900,
"author_profile": "https://Stackoverflow.com/users/3839900",
"pm_score": 5,
"selected": false,
"text": "<pre class=\"lang-py prettyprint-override\"><code>max(stats, key=stats.get, default=None)\n</code></pre>\n<p>If <code>stats</code> could be an empty dictionary, using only <code>max(stats, key=stats.get)</code> will otherwise raise <code>ValueError</code>.</p>\n<p>This answer is safe to use so long as <code>None</code> is not a possible key in the dictionary.</p>\n"
},
{
"answer_id": 66924717,
"author": "Shaonsani",
"author_id": 7248950,
"author_profile": "https://Stackoverflow.com/users/7248950",
"pm_score": 2,
"selected": false,
"text": "<p>In case of stats is empty, one can check a condition before finding valued key like,</p>\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100}\nmax_key = None\nif bool(stats):\n max_key = max(stats, key=stats.get)\nprint(max_key)\n</code></pre>\n<p>This can first check if the dictionary is empty or not, then process.</p>\n<pre><code>>>> b\n</code></pre>\n"
},
{
"answer_id": 69237479,
"author": "BusBar_යසස්",
"author_id": 11327125,
"author_profile": "https://Stackoverflow.com/users/11327125",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n<pre><code>sorted(dict_name, key=dict_name.__getitem__, reverse=True)[0]\n</code></pre>\n"
},
{
"answer_id": 69237779,
"author": "Ashutosh",
"author_id": 6418029,
"author_profile": "https://Stackoverflow.com/users/6418029",
"pm_score": 3,
"selected": false,
"text": "<p>Following are two easy ways to extract key with max value from given dict</p>\n<pre><code>import time\nstats = {\n "a" : 1000,\n "b" : 3000,\n "c" : 90,\n "d" : 74,\n "e" : 72,\n }\n\nstart_time = time.time_ns()\nmax_key = max(stats, key = stats.get)\nprint("Max Key [", max_key, "]Time taken (ns)", time.time_ns() - start_time)\n\nstart_time = time.time_ns()\nmax_key = max(stats, key=lambda key: stats[key])\nprint("Max Key with Lambda[", max_key, "]Time taken (ns)", time.time_ns() - start_time)\n</code></pre>\n<blockquote>\n<p>Output</p>\n</blockquote>\n<pre><code>Max Key [ b ] Time taken (ns) 3100\nMax Key with Lambda [ b ] Time taken (ns) 1782\n</code></pre>\n<p>Solution with Lambda expression seems to be performing better for smaller inputs.</p>\n"
},
{
"answer_id": 73439643,
"author": "Allan",
"author_id": 13356494,
"author_profile": "https://Stackoverflow.com/users/13356494",
"pm_score": 0,
"selected": false,
"text": "<p>Just to add a situation where you want to select certain keys instead of all of them:</p>\n<pre><code>stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}\nkeys_to_search = ["a", "b", "c"]\n\nmax([k for k in keys_to_search], key=lambda x: stats[x])```\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34598/"
] |
I have a dictionary where keys are strings, and values are integers.
```
stats = {'a': 1, 'b': 3000, 'c': 0}
```
How do I get the key with the maximum value? In this case, it is `'b'`.
---
Is there a nicer approach than using an intermediate list with reversed key-value tuples?
```
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
```
|
You can use `operator.itemgetter` for that:
```
import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
```
And instead of building a new list in memory use `stats.iteritems()`. The `key` parameter to the `max()` function is a function that computes a key that is used to determine how to rank items.
Please note that if you were to have another key-value pair 'd': 3000 that this method will only return **one** of the **two** even though they both have the maximum value.
```
>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
```
If using Python3:
```
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
```
|
268,289 |
<p>I have a Nant build script which CruiseControl uses to build a solution on-demand.</p>
<p>However, we only recently got CruiseControl so our official build number is different from what is listed in CruiseControl.</p>
<p>I know CruiseControl injects some properties into build scripts so that I can access the CC build number in the script (CCNetLabel) but how do I pass a value back to CC to use as the build number on the UI screen?</p>
<p>Example, CC says build number 2</p>
<p>nAnt script increments a buildnumber.xml value every build, and the official build number is on 123.</p>
<p>I want the CC UI to show last successful build number: 123, not 2, so how do I pass that value back up?</p>
|
[
{
"answer_id": 268319,
"author": "Vinzz",
"author_id": 28922,
"author_profile": "https://Stackoverflow.com/users/28922",
"pm_score": 1,
"selected": false,
"text": "<p>Did you try to use some environment variables? I believe CCNet can handle these.</p>\n\n<p>I'll dig a bit on this.</p>\n\n<p>Well I see a solution, quite dirty, but anyhow:</p>\n\n<p>1- Add a <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Default+Labeller\" rel=\"nofollow noreferrer\">defaultlabeller</a> section in your CCNET project definition. It will contains the pattern of the build number you want to display.</p>\n\n<p>2- Within NAnt, have a script to update your configuration file, inserting the build number you want to see.</p>\n\n<p>3- Touch (in the Unix sense) the ccnet.exe.config file so as to make it re-load the projects configuration files.</p>\n\n<p>et voilà.</p>\n"
},
{
"answer_id": 268658,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>We had this problem as well. I ended up writing a special CC labelling plugin.</p>\n"
},
{
"answer_id": 269236,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 4,
"selected": true,
"text": "<p>A custom build labeler is required for this. Perforce is our source control provider and we derive our version number from it. The code is as follows:</p>\n\n<pre><code>/// <summary>\n/// Gets the latest change list number from perforce, for ccnet to consume as a build label.\n/// </summary>\n[ReflectorType( \"p4labeller\" )]\npublic class PerforceLabeller : ILabeller\n{\n // perforce executable (optional)\n [ReflectorProperty(\"executable\", Required = false)]\n public string P4Executable = \"p4.exe\";\n\n // perforce port (i.e. myserver:1234)\n [ReflectorProperty(\"port\", Required = false)]\n public string P4Port = String.Empty;\n\n // perforce user\n [ReflectorProperty(\"user\", Required = false)]\n public string P4User = String.Empty;\n\n // perforce client\n [ReflectorProperty(\"client\", Required = false)]\n public string P4Client = String.Empty;\n\n // perforce view (i.e. //Dev/Code1/...)\n [ReflectorProperty(\"view\", Required = false)]\n public string P4View = String.Empty;\n\n // Returns latest change list\n public string Generate( IIntegrationResult previousLabel )\n {\n return GetLatestChangelist(); \n }\n\n // Stores latest change list into a label\n public void Run( IIntegrationResult result )\n {\n result.Label = GetLatestChangelist();\n }\n\n // Gets the latest change list\n public string GetLatestChangelist()\n {\n // Build the arguments to pass to p4 to get the latest changelist\n string theArgs = \"-p \" + P4Port + \" -u \" + P4User + \" -c \" + P4Client + \" changes -m 1 -s submitted \" + P4View;\n Log.Info( string.Format( \"Getting latest change from Perforce using --> \" + theArgs ) );\n\n // Execute p4\n ProcessResult theProcessResult = new ProcessExecutor().Execute( new ProcessInfo( P4Executable, theArgs ) );\n\n // Extract the changelist # from the result\n Regex theRegex = new Regex( @\"\\s[0-9]+\\s\", RegexOptions.IgnoreCase );\n Match theMatch = theRegex.Match( theProcessResult.StandardOutput );\n return theMatch.Value.Trim();\n }\n}\n</code></pre>\n\n<p>The method, <strong>GetLatestChangelist</strong>, is where you would probably insert your own logic to talk to your version control system. In Perforce there is the idea of the last changelist which is unique. Our build numbers, and ultimately version numbers are based off of that. </p>\n\n<p>Once you build this (into an assembly dll), you'll have to hook it into ccnet. You can just drop the assembly into the server directory (next to ccnet.exe). </p>\n\n<p>Next you modify your ccnet project file to utilize this labeller. We did this with the <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Default+Labeller\" rel=\"nofollow noreferrer\">default labeller block</a>. Something like the following:</p>\n\n<pre><code><project>\n<labeller type=\"p4labeller\">\n <client>myclient</client>\n <executable>p4.exe</executable>\n <port>myserver:1234</port>\n <user>myuser</user>\n <view>//Code1/...</view>\n</labeller>\n<!-- Other project configuration to go here -->\n</project>\n</code></pre>\n\n<p>If you're just wanting the build number to show up in ccnet then you're done and don't really need to do anything else. However, you can access the label in your NAnt script if you wish by using the already provided <strong>CCNetLabel</strong> property. </p>\n\n<p>Hope this helps some. Let me know if you have any questions by posting to the comments.</p>\n"
},
{
"answer_id": 420887,
"author": "gbanfill",
"author_id": 45068,
"author_profile": "https://Stackoverflow.com/users/45068",
"pm_score": 0,
"selected": false,
"text": "<p>If your build numbers are sequential, you can just hack the cruise control state file to give it the correct build number to start with. Your looking for a file called [projectName].state.</p>\n\n<p>I changed the <strong>Label</strong> element to the correct number and the <strong>LastSuccessfulIntegrationLabel</strong> to be the new number.</p>\n"
},
{
"answer_id": 421010,
"author": "Jeffrey Fredrick",
"author_id": 35894,
"author_profile": "https://Stackoverflow.com/users/35894",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>However, we only recently got\n CruiseControl so our official build\n number is different from what is\n listed in CruiseControl.</p>\n</blockquote>\n\n<p>Sort of along the lines of what gbanfill said, you can tell CC what build numbers to start from, but there's no need to hack the .ser file. You can use the JMX interface to set the current build number to get it in sync with your NAnt build number.</p>\n\n<p>You can also set the <a href=\"http://cruisecontrol.sourceforge.net/main/configxml.html#labelincrementer\" rel=\"nofollow noreferrer\">default label</a> value to to your current build number, delete the .ser file and restart CC.</p>\n\n<p>But maybe the easiest thing is to write the build number into a property file from NAnt and then use the <a href=\"http://cruisecontrol.sourceforge.net/main/configxml.html#propertyfilelabelincrementer\" rel=\"nofollow noreferrer\">property file label incrementer</a> to read that file. (Be sure to to set setPreBuildIncrementer=\"true\")</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18818/"
] |
I have a Nant build script which CruiseControl uses to build a solution on-demand.
However, we only recently got CruiseControl so our official build number is different from what is listed in CruiseControl.
I know CruiseControl injects some properties into build scripts so that I can access the CC build number in the script (CCNetLabel) but how do I pass a value back to CC to use as the build number on the UI screen?
Example, CC says build number 2
nAnt script increments a buildnumber.xml value every build, and the official build number is on 123.
I want the CC UI to show last successful build number: 123, not 2, so how do I pass that value back up?
|
A custom build labeler is required for this. Perforce is our source control provider and we derive our version number from it. The code is as follows:
```
/// <summary>
/// Gets the latest change list number from perforce, for ccnet to consume as a build label.
/// </summary>
[ReflectorType( "p4labeller" )]
public class PerforceLabeller : ILabeller
{
// perforce executable (optional)
[ReflectorProperty("executable", Required = false)]
public string P4Executable = "p4.exe";
// perforce port (i.e. myserver:1234)
[ReflectorProperty("port", Required = false)]
public string P4Port = String.Empty;
// perforce user
[ReflectorProperty("user", Required = false)]
public string P4User = String.Empty;
// perforce client
[ReflectorProperty("client", Required = false)]
public string P4Client = String.Empty;
// perforce view (i.e. //Dev/Code1/...)
[ReflectorProperty("view", Required = false)]
public string P4View = String.Empty;
// Returns latest change list
public string Generate( IIntegrationResult previousLabel )
{
return GetLatestChangelist();
}
// Stores latest change list into a label
public void Run( IIntegrationResult result )
{
result.Label = GetLatestChangelist();
}
// Gets the latest change list
public string GetLatestChangelist()
{
// Build the arguments to pass to p4 to get the latest changelist
string theArgs = "-p " + P4Port + " -u " + P4User + " -c " + P4Client + " changes -m 1 -s submitted " + P4View;
Log.Info( string.Format( "Getting latest change from Perforce using --> " + theArgs ) );
// Execute p4
ProcessResult theProcessResult = new ProcessExecutor().Execute( new ProcessInfo( P4Executable, theArgs ) );
// Extract the changelist # from the result
Regex theRegex = new Regex( @"\s[0-9]+\s", RegexOptions.IgnoreCase );
Match theMatch = theRegex.Match( theProcessResult.StandardOutput );
return theMatch.Value.Trim();
}
}
```
The method, **GetLatestChangelist**, is where you would probably insert your own logic to talk to your version control system. In Perforce there is the idea of the last changelist which is unique. Our build numbers, and ultimately version numbers are based off of that.
Once you build this (into an assembly dll), you'll have to hook it into ccnet. You can just drop the assembly into the server directory (next to ccnet.exe).
Next you modify your ccnet project file to utilize this labeller. We did this with the [default labeller block](http://confluence.public.thoughtworks.org/display/CCNET/Default+Labeller). Something like the following:
```
<project>
<labeller type="p4labeller">
<client>myclient</client>
<executable>p4.exe</executable>
<port>myserver:1234</port>
<user>myuser</user>
<view>//Code1/...</view>
</labeller>
<!-- Other project configuration to go here -->
</project>
```
If you're just wanting the build number to show up in ccnet then you're done and don't really need to do anything else. However, you can access the label in your NAnt script if you wish by using the already provided **CCNetLabel** property.
Hope this helps some. Let me know if you have any questions by posting to the comments.
|
268,296 |
<p>is there a way to have a mysql select statement return fully qualified column names like "table.field" without using AS for every single field?</p>
<p>like so:</p>
<pre><code>SELECT *
FROM table1
LEFT JOIN table2 on table1.f_ID = table2.ID
</code></pre>
<p>and the result would be:
"table1.ID", "table1.name", "table2.ID", "table2.name", ...</p>
|
[
{
"answer_id": 268973,
"author": "user12861",
"author_id": 12861,
"author_profile": "https://Stackoverflow.com/users/12861",
"pm_score": 3,
"selected": true,
"text": "<p>Not really. You could write some dynamic SQL to accomplish this, but it wouldn't be simple. If you really want the dynamic SQL, let me know and I could try to whip something up.</p>\n"
},
{
"answer_id": 2309403,
"author": "Mihai Stancu",
"author_id": 278509,
"author_profile": "https://Stackoverflow.com/users/278509",
"pm_score": 1,
"selected": false,
"text": "<p>Using fully qualified field names in the statement would yield fully qualified field names in the result set.</p>\n\n<pre><code>SELECT table1.ID, table1.name, table2.ID, table2.name\nFROM table1 \nLEFT JOIN table2 on table1.f_ID = table2.ID\n</code></pre>\n\n<p>I realize that the burden you wished to get rid of is doing this manually. But if your application has any kind of knowledge about the layout of the database, it can be generated dynamically within the application.</p>\n\n<p>Just my 2 cents</p>\n"
},
{
"answer_id": 2675118,
"author": "user321297",
"author_id": 321297,
"author_profile": "https://Stackoverflow.com/users/321297",
"pm_score": 1,
"selected": false,
"text": "<p>You can write this as well:</p>\n\n<pre><code> SELECT table1.*, table2.*\n FROM table1 \nLEFT JOIN table2 on table1.f_ID = table2.ID\n</code></pre>\n\n<p>No need to specify each column, if you want them all</p>\n"
},
{
"answer_id": 8608381,
"author": "Paul Hutchinson",
"author_id": 511334,
"author_profile": "https://Stackoverflow.com/users/511334",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using PHP you can use PDO to get this result.</p>\n\n<p><code>$PDO->setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, true);</code></p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2523631/sql-select-from-multiple-tables\">SQL Select * from multiple tables</a> for more information.</p>\n"
},
{
"answer_id": 37485622,
"author": "MarkZ",
"author_id": 6391390,
"author_profile": "https://Stackoverflow.com/users/6391390",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select table1.* , table1='<======'\n\n table2.* , table2='<======'\n\nfrom table1 \n\n left join table2 on table1.f_ID = table2.ID\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427/"
] |
is there a way to have a mysql select statement return fully qualified column names like "table.field" without using AS for every single field?
like so:
```
SELECT *
FROM table1
LEFT JOIN table2 on table1.f_ID = table2.ID
```
and the result would be:
"table1.ID", "table1.name", "table2.ID", "table2.name", ...
|
Not really. You could write some dynamic SQL to accomplish this, but it wouldn't be simple. If you really want the dynamic SQL, let me know and I could try to whip something up.
|
268,321 |
<p>I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a <code>BiDictionaryOneToOne<T, S></code> which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't believe that I'm the first person to need this...</p>
<p>There is a BiDictionary in the answers to <a href="https://stackoverflow.com/questions/255341/getting-key-of-value-of-a-generic-dictionary">this question</a>, but it is not for unique elements (and also does not implement RemoveByFirst(T t) or RemoveBySecond(S s)). </p>
<p>Thanks!</p>
|
[
{
"answer_id": 268332,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>The question you refer to also shows a one-to-one implementation in <a href=\"https://stackoverflow.com/questions/255341/getting-key-of-value-of-a-generic-dictionary#255630\">this answer</a>. Adding RemoveByFirst and RemoveBySecond would be trivial - as would implementing extra interfaces etc.</p>\n"
},
{
"answer_id": 268380,
"author": "Tomas Pajonk",
"author_id": 4694,
"author_profile": "https://Stackoverflow.com/users/4694",
"pm_score": 2,
"selected": false,
"text": "<p>I have created such a class, using C5 collection classes.</p>\n\n<pre><code>public class Mapper<K,T> : IEnumerable<T>\n\n{\n C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();\n C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();\n\n\n /// <summary>\n /// Initializes a new instance of the Mapper class.\n /// </summary>\n public Mapper()\n {\n KToTMap = new TreeDictionary<K,T>();\n TToKMap = new HashDictionary<T,K>();\n }\n\n\n public void Add(K key, T value)\n {\n KToTMap.Add(key, value);\n TToKMap.Add(value, key);\n }\n\n public bool ContainsKey(K key)\n {\n return KToTMap.Contains(key);\n }\n\n public int Count\n {\n get { return KToTMap.Count; }\n }\n\n\n public K this[T obj]\n {\n get\n {\n return TToKMap[obj];\n }\n }\n\n public T this[K obj]\n {\n get\n {\n return KToTMap[obj];\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return KToTMap.Values.GetEnumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return KToTMap.Values.GetEnumerator();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 268545,
"author": "Joel in Gö",
"author_id": 6091,
"author_profile": "https://Stackoverflow.com/users/6091",
"pm_score": 7,
"selected": true,
"text": "<p>OK, here is my attempt (building on Jon's - thanks), archived here and open for improvement :</p>\n\n<pre><code>/// <summary>\n/// This is a dictionary guaranteed to have only one of each value and key. \n/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.\n/// </summary>\n/// <typeparam name=\"TFirst\">The type of the \"key\"</typeparam>\n/// <typeparam name=\"TSecond\">The type of the \"value\"</typeparam>\npublic class BiDictionaryOneToOne<TFirst, TSecond>\n{\n IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();\n IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();\n\n #region Exception throwing methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Throws an exception if either element is already in the dictionary\n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n public void Add(TFirst first, TSecond second)\n {\n if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))\n throw new ArgumentException(\"Duplicate first or second\");\n\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n }\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first\n /// Throws an exception if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <returns>the value corresponding to first</returns>\n public TSecond GetByFirst(TFirst first)\n {\n TSecond second;\n if (!firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n return second; \n }\n\n /// <summary>\n /// Find the TFirst corresponing to the Second second.\n /// Throws an exception if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <returns>the value corresponding to second</returns>\n public TFirst GetBySecond(TSecond second)\n {\n TFirst first;\n if (!secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n return first; \n }\n\n\n /// <summary>\n /// Remove the record containing first.\n /// If first is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"first\">the key of the record to delete</param>\n public void RemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n firstToSecond.Remove(first);\n secondToFirst.Remove(second);\n }\n\n /// <summary>\n /// Remove the record containing second.\n /// If second is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"second\">the key of the record to delete</param>\n public void RemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n secondToFirst.Remove(second);\n firstToSecond.Remove(first);\n }\n\n #endregion\n\n #region Try methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Returns false if either element is already in the dictionary \n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n /// <returns>true if successfully added, false if either element are already in the dictionary</returns>\n public Boolean TryAdd(TFirst first, TSecond second)\n {\n if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))\n return false;\n\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n return true;\n }\n\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first.\n /// Returns false if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <param name=\"second\">the corresponding value</param>\n /// <returns>true if first is in the dictionary, false otherwise</returns>\n public Boolean TryGetByFirst(TFirst first, out TSecond second)\n {\n return firstToSecond.TryGetValue(first, out second);\n }\n\n /// <summary>\n /// Find the TFirst corresponding to the TSecond second.\n /// Returns false if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <param name=\"first\">the corresponding value</param>\n /// <returns>true if second is in the dictionary, false otherwise</returns>\n public Boolean TryGetBySecond(TSecond second, out TFirst first)\n {\n return secondToFirst.TryGetValue(second, out first);\n }\n\n /// <summary>\n /// Remove the record containing first, if there is one.\n /// </summary>\n /// <param name=\"first\"></param>\n /// <returns> If first is not in the dictionary, returns false, otherwise true</returns>\n public Boolean TryRemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!firstToSecond.TryGetValue(first, out second))\n return false;\n\n firstToSecond.Remove(first);\n secondToFirst.Remove(second);\n return true;\n }\n\n /// <summary>\n /// Remove the record containing second, if there is one.\n /// </summary>\n /// <param name=\"second\"></param>\n /// <returns> If second is not in the dictionary, returns false, otherwise true</returns>\n public Boolean TryRemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!secondToFirst.TryGetValue(second, out first))\n return false;\n\n secondToFirst.Remove(second);\n firstToSecond.Remove(first);\n return true;\n }\n\n #endregion \n\n /// <summary>\n /// The number of pairs stored in the dictionary\n /// </summary>\n public Int32 Count\n {\n get { return firstToSecond.Count; }\n }\n\n /// <summary>\n /// Removes all items from the dictionary.\n /// </summary>\n public void Clear()\n {\n firstToSecond.Clear();\n secondToFirst.Clear();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15852877,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": "<p>This is same as accepted answer, but I provided <code>Update</code> methods as well, and over all little more fleshed out:</p>\n\n<pre><code>public class BiDictionary<TKey1, TKey2> : IEnumerable<Tuple<TKey1, TKey2>>\n{\n Dictionary<TKey1, TKey2> _forwards;\n Dictionary<TKey2, TKey1> _reverses;\n\n public int Count\n {\n get\n {\n if (_forwards.Count != _reverses.Count)\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n return _forwards.Count;\n }\n }\n\n public ICollection<TKey1> Key1s\n {\n get { return _forwards.Keys; }\n }\n\n public ICollection<TKey2> Key2s\n {\n get { return _reverses.Keys; }\n }\n\n public BiDictionary(IEqualityComparer<TKey1> comparer1 = null, IEqualityComparer<TKey2> comparer2 = null)\n {\n _forwards = new Dictionary<TKey1, TKey2>(comparer1);\n _reverses = new Dictionary<TKey2, TKey1>(comparer2);\n }\n\n\n\n public bool ContainsKey1(TKey1 key)\n {\n return ContainsKey(key, _forwards);\n }\n\n private static bool ContainsKey<S, T>(S key, Dictionary<S, T> dict)\n {\n return dict.ContainsKey(key);\n }\n\n public bool ContainsKey2(TKey2 key)\n {\n return ContainsKey(key, _reverses);\n }\n\n public TKey2 GetValueByKey1(TKey1 key)\n {\n return GetValueByKey(key, _forwards);\n }\n\n private static T GetValueByKey<S, T>(S key, Dictionary<S, T> dict)\n {\n return dict[key];\n }\n\n public TKey1 GetValueByKey2(TKey2 key)\n {\n return GetValueByKey(key, _reverses);\n }\n\n public bool TryGetValueByKey1(TKey1 key, out TKey2 value)\n {\n return TryGetValue(key, _forwards, out value);\n }\n\n private static bool TryGetValue<S, T>(S key, Dictionary<S, T> dict, out T value)\n {\n return dict.TryGetValue(key, out value);\n }\n\n public bool TryGetValueByKey2(TKey2 key, out TKey1 value)\n {\n return TryGetValue(key, _reverses, out value);\n }\n\n public bool Add(TKey1 key1, TKey2 key2)\n {\n if (ContainsKey1(key1) || ContainsKey2(key2)) // very important\n return false;\n\n AddOrUpdate(key1, key2);\n return true;\n }\n\n public void AddOrUpdateByKey1(TKey1 key1, TKey2 key2)\n {\n if (!UpdateByKey1(key1, key2))\n AddOrUpdate(key1, key2);\n }\n\n // dont make this public; a dangerous method used cautiously in this class\n private void AddOrUpdate(TKey1 key1, TKey2 key2)\n {\n _forwards[key1] = key2;\n _reverses[key2] = key1;\n }\n\n public void AddOrUpdateKeyByKey2(TKey2 key2, TKey1 key1)\n {\n if (!UpdateByKey2(key2, key1))\n AddOrUpdate(key1, key2);\n }\n\n public bool UpdateKey1(TKey1 oldKey, TKey1 newKey)\n {\n return UpdateKey(oldKey, _forwards, newKey, (key1, key2) => AddOrUpdate(key1, key2));\n }\n\n private static bool UpdateKey<S, T>(S oldKey, Dictionary<S, T> dict, S newKey, Action<S, T> updater)\n {\n T otherKey;\n if (!TryGetValue(oldKey, dict, out otherKey) || ContainsKey(newKey, dict))\n return false;\n\n Remove(oldKey, dict);\n updater(newKey, otherKey);\n return true;\n }\n\n public bool UpdateKey2(TKey2 oldKey, TKey2 newKey)\n {\n return UpdateKey(oldKey, _reverses, newKey, (key1, key2) => AddOrUpdate(key2, key1));\n }\n\n public bool UpdateByKey1(TKey1 key1, TKey2 key2)\n {\n return UpdateByKey(key1, _forwards, _reverses, key2, (k1, k2) => AddOrUpdate(k1, k2));\n }\n\n private static bool UpdateByKey<S, T>(S key1, Dictionary<S, T> forwards, Dictionary<T, S> reverses, T key2,\n Action<S, T> updater)\n {\n T otherKey;\n if (!TryGetValue(key1, forwards, out otherKey) || ContainsKey(key2, reverses))\n return false;\n\n if (!Remove(otherKey, reverses))\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n updater(key1, key2);\n return true;\n }\n\n public bool UpdateByKey2(TKey2 key2, TKey1 key1)\n {\n return UpdateByKey(key2, _reverses, _forwards, key1, (k1, k2) => AddOrUpdate(k2, k1));\n }\n\n public bool RemoveByKey1(TKey1 key)\n {\n return RemoveByKey(key, _forwards, _reverses);\n }\n\n private static bool RemoveByKey<S, T>(S key, Dictionary<S, T> keyDict, Dictionary<T, S> valueDict)\n {\n T otherKey;\n if (!TryGetValue(key, keyDict, out otherKey))\n return false;\n\n if (!Remove(key, keyDict) || !Remove(otherKey, valueDict))\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n return true;\n }\n\n private static bool Remove<S, T>(S key, Dictionary<S, T> dict)\n {\n return dict.Remove(key);\n }\n\n public bool RemoveByKey2(TKey2 key)\n {\n return RemoveByKey(key, _reverses, _forwards);\n }\n\n public void Clear()\n {\n _forwards.Clear();\n _reverses.Clear();\n }\n\n public IEnumerator<Tuple<TKey1, TKey2>> GetEnumerator()\n {\n if (_forwards.Count != _reverses.Count)\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n foreach (var item in _forwards)\n yield return Tuple.Create(item.Key, item.Value);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n</code></pre>\n\n<p>Similar to my answer <a href=\"https://stackoverflow.com/a/15852665/661933\">here</a></p>\n\n<p>Few things to note:</p>\n\n<ol>\n<li><p>I have implemented only <code>IEnumerable<></code>. I don't think <code>ICollection<></code> makes sense here since the method names all could be way different for this special collection structure. Up to you to decide what should go inside <code>IEnumerable<></code>. So now you have collection initializer syntax too, like </p>\n\n<pre><code>var p = new BiDictionary<int, string> { 1, \"a\" }, { 2, \"b\" } };\n</code></pre></li>\n<li><p>I have attempted for some weird exceptions to be thrown here and there - just for data integrity. Just to be on the safer side so that you know if ever my code has bugs.</p></li>\n<li><p>Performance: You can lookup for <code>Value</code> with either of the <code>Keys</code>, which means <code>Get</code> and <code>Contains</code> method require just 1 lookup (O(1)). <code>Add</code> requires 2 lookups and 2 adds. <code>Update</code> requires 1 lookup and 2 adds. <code>Remove</code> takes 3 lookups. All similar to accepted answer.</p></li>\n</ol>\n"
},
{
"answer_id": 15927912,
"author": "Athari",
"author_id": 293099,
"author_profile": "https://Stackoverflow.com/users/293099",
"pm_score": 4,
"selected": false,
"text": "<p>A more complete implementation of bidirectional dictionary:</p>\n\n<ul>\n<li><strong>Supports almost all interfaces</strong> of original <code>Dictionary<TKey,TValue></code> (except infrastructure interfaces):\n\n<ul>\n<li><code>IDictionary<TKey, TValue></code></li>\n<li><code>IReadOnlyDictionary<TKey, TValue></code></li>\n<li><code>IDictionary</code></li>\n<li><code>ICollection<KeyValuePair<TKey, TValue>></code> (this one and below are the base interfaces of the ones above)</li>\n<li><code>ICollection</code></li>\n<li><code>IReadOnlyCollection<KeyValuePair<TKey, TValue>></code></li>\n<li><code>IEnumerable<KeyValuePair<TKey, TValue>></code></li>\n<li><code>IEnumerable</code></li>\n</ul></li>\n<li><strong>Serialization</strong> using <code>SerializableAttribute</code>.</li>\n<li><strong>Debug view</strong> using <code>DebuggerDisplayAttribute</code> (with Count info) and <code>DebuggerTypeProxyAttribute</code> (for displaying key-value pairs in watches).</li>\n<li>Reverse dictionary is available as <code>IDictionary<TValue, TKey> Reverse</code> property and also implements all interfaces mentioned above. All operations on either dictionaries modify both.</li>\n</ul>\n\n<p>Usage:</p>\n\n<pre><code>var dic = new BiDictionary<int, string>();\ndic.Add(1, \"1\");\ndic[2] = \"2\";\ndic.Reverse.Add(\"3\", 3);\ndic.Reverse[\"4\"] = 4;\ndic.Clear();\n</code></pre>\n\n<p>Code is available in my private framework on GitHub: <a href=\"https://github.com/Athari/Alba.Framework/blob/master/Alba.Framework/Collections/Collections/BiDictionary(TFirst%2CTSecond).cs\" rel=\"noreferrer\">BiDictionary(TFirst,TSecond).cs</a> (<a href=\"https://github.com/Athari/Alba.Framework/blob/33cdaf77872d33608edc6b9a0f84f757a6bbcce2/Alba.Framework/Collections/Collections/BiDictionary(TFirst%2CTSecond).cs\" rel=\"noreferrer\">permalink</a>, <a href=\"https://github.com/Athari/Alba.Framework/search?q=bidictionary&ref=cmdform\" rel=\"noreferrer\">search</a>).</p>\n\n<p>Copy:</p>\n\n<pre><code>[Serializable]\n[DebuggerDisplay (\"Count = {Count}\"), DebuggerTypeProxy (typeof(DictionaryDebugView<,>))]\npublic class BiDictionary<TFirst, TSecond> : IDictionary<TFirst, TSecond>, IReadOnlyDictionary<TFirst, TSecond>, IDictionary\n{\n private readonly IDictionary<TFirst, TSecond> _firstToSecond = new Dictionary<TFirst, TSecond>();\n [NonSerialized]\n private readonly IDictionary<TSecond, TFirst> _secondToFirst = new Dictionary<TSecond, TFirst>();\n [NonSerialized]\n private readonly ReverseDictionary _reverseDictionary;\n\n public BiDictionary ()\n {\n _reverseDictionary = new ReverseDictionary(this);\n }\n\n public IDictionary<TSecond, TFirst> Reverse\n {\n get { return _reverseDictionary; }\n }\n\n public int Count\n {\n get { return _firstToSecond.Count; }\n }\n\n object ICollection.SyncRoot\n {\n get { return ((ICollection)_firstToSecond).SyncRoot; }\n }\n\n bool ICollection.IsSynchronized\n {\n get { return ((ICollection)_firstToSecond).IsSynchronized; }\n }\n\n bool IDictionary.IsFixedSize\n {\n get { return ((IDictionary)_firstToSecond).IsFixedSize; }\n }\n\n public bool IsReadOnly\n {\n get { return _firstToSecond.IsReadOnly || _secondToFirst.IsReadOnly; }\n }\n\n public TSecond this [TFirst key]\n {\n get { return _firstToSecond[key]; }\n set\n {\n _firstToSecond[key] = value;\n _secondToFirst[value] = key;\n }\n }\n\n object IDictionary.this [object key]\n {\n get { return ((IDictionary)_firstToSecond)[key]; }\n set\n {\n ((IDictionary)_firstToSecond)[key] = value;\n ((IDictionary)_secondToFirst)[value] = key;\n }\n }\n\n public ICollection<TFirst> Keys\n {\n get { return _firstToSecond.Keys; }\n }\n\n ICollection IDictionary.Keys\n {\n get { return ((IDictionary)_firstToSecond).Keys; }\n }\n\n IEnumerable<TFirst> IReadOnlyDictionary<TFirst, TSecond>.Keys\n {\n get { return ((IReadOnlyDictionary<TFirst, TSecond>)_firstToSecond).Keys; }\n }\n\n public ICollection<TSecond> Values\n {\n get { return _firstToSecond.Values; }\n }\n\n ICollection IDictionary.Values\n {\n get { return ((IDictionary)_firstToSecond).Values; }\n }\n\n IEnumerable<TSecond> IReadOnlyDictionary<TFirst, TSecond>.Values\n {\n get { return ((IReadOnlyDictionary<TFirst, TSecond>)_firstToSecond).Values; }\n }\n\n public IEnumerator<KeyValuePair<TFirst, TSecond>> GetEnumerator ()\n {\n return _firstToSecond.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator ()\n {\n return GetEnumerator();\n }\n\n IDictionaryEnumerator IDictionary.GetEnumerator ()\n {\n return ((IDictionary)_firstToSecond).GetEnumerator();\n }\n\n public void Add (TFirst key, TSecond value)\n {\n _firstToSecond.Add(key, value);\n _secondToFirst.Add(value, key);\n }\n\n void IDictionary.Add (object key, object value)\n {\n ((IDictionary)_firstToSecond).Add(key, value);\n ((IDictionary)_secondToFirst).Add(value, key);\n }\n\n public void Add (KeyValuePair<TFirst, TSecond> item)\n {\n _firstToSecond.Add(item);\n _secondToFirst.Add(item.Reverse());\n }\n\n public bool ContainsKey (TFirst key)\n {\n return _firstToSecond.ContainsKey(key);\n }\n\n public bool Contains (KeyValuePair<TFirst, TSecond> item)\n {\n return _firstToSecond.Contains(item);\n }\n\n public bool TryGetValue (TFirst key, out TSecond value)\n {\n return _firstToSecond.TryGetValue(key, out value);\n }\n\n public bool Remove (TFirst key)\n {\n TSecond value;\n if (_firstToSecond.TryGetValue(key, out value)) {\n _firstToSecond.Remove(key);\n _secondToFirst.Remove(value);\n return true;\n }\n else\n return false;\n }\n\n void IDictionary.Remove (object key)\n {\n var firstToSecond = (IDictionary)_firstToSecond;\n if (!firstToSecond.Contains(key))\n return;\n var value = firstToSecond[key];\n firstToSecond.Remove(key);\n ((IDictionary)_secondToFirst).Remove(value);\n }\n\n public bool Remove (KeyValuePair<TFirst, TSecond> item)\n {\n return _firstToSecond.Remove(item);\n }\n\n public bool Contains (object key)\n {\n return ((IDictionary)_firstToSecond).Contains(key);\n }\n\n public void Clear ()\n {\n _firstToSecond.Clear();\n _secondToFirst.Clear();\n }\n\n public void CopyTo (KeyValuePair<TFirst, TSecond>[] array, int arrayIndex)\n {\n _firstToSecond.CopyTo(array, arrayIndex);\n }\n\n void ICollection.CopyTo (Array array, int index)\n {\n ((IDictionary)_firstToSecond).CopyTo(array, index);\n }\n\n [OnDeserialized]\n internal void OnDeserialized (StreamingContext context)\n {\n _secondToFirst.Clear();\n foreach (var item in _firstToSecond)\n _secondToFirst.Add(item.Value, item.Key);\n }\n\n private class ReverseDictionary : IDictionary<TSecond, TFirst>, IReadOnlyDictionary<TSecond, TFirst>, IDictionary\n {\n private readonly BiDictionary<TFirst, TSecond> _owner;\n\n public ReverseDictionary (BiDictionary<TFirst, TSecond> owner)\n {\n _owner = owner;\n }\n\n public int Count\n {\n get { return _owner._secondToFirst.Count; }\n }\n\n object ICollection.SyncRoot\n {\n get { return ((ICollection)_owner._secondToFirst).SyncRoot; }\n }\n\n bool ICollection.IsSynchronized\n {\n get { return ((ICollection)_owner._secondToFirst).IsSynchronized; }\n }\n\n bool IDictionary.IsFixedSize\n {\n get { return ((IDictionary)_owner._secondToFirst).IsFixedSize; }\n }\n\n public bool IsReadOnly\n {\n get { return _owner._secondToFirst.IsReadOnly || _owner._firstToSecond.IsReadOnly; }\n }\n\n public TFirst this [TSecond key]\n {\n get { return _owner._secondToFirst[key]; }\n set\n {\n _owner._secondToFirst[key] = value;\n _owner._firstToSecond[value] = key;\n }\n }\n\n object IDictionary.this [object key]\n {\n get { return ((IDictionary)_owner._secondToFirst)[key]; }\n set\n {\n ((IDictionary)_owner._secondToFirst)[key] = value;\n ((IDictionary)_owner._firstToSecond)[value] = key;\n }\n }\n\n public ICollection<TSecond> Keys\n {\n get { return _owner._secondToFirst.Keys; }\n }\n\n ICollection IDictionary.Keys\n {\n get { return ((IDictionary)_owner._secondToFirst).Keys; }\n }\n\n IEnumerable<TSecond> IReadOnlyDictionary<TSecond, TFirst>.Keys\n {\n get { return ((IReadOnlyDictionary<TSecond, TFirst>)_owner._secondToFirst).Keys; }\n }\n\n public ICollection<TFirst> Values\n {\n get { return _owner._secondToFirst.Values; }\n }\n\n ICollection IDictionary.Values\n {\n get { return ((IDictionary)_owner._secondToFirst).Values; }\n }\n\n IEnumerable<TFirst> IReadOnlyDictionary<TSecond, TFirst>.Values\n {\n get { return ((IReadOnlyDictionary<TSecond, TFirst>)_owner._secondToFirst).Values; }\n }\n\n public IEnumerator<KeyValuePair<TSecond, TFirst>> GetEnumerator ()\n {\n return _owner._secondToFirst.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator ()\n {\n return GetEnumerator();\n }\n\n IDictionaryEnumerator IDictionary.GetEnumerator ()\n {\n return ((IDictionary)_owner._secondToFirst).GetEnumerator();\n }\n\n public void Add (TSecond key, TFirst value)\n {\n _owner._secondToFirst.Add(key, value);\n _owner._firstToSecond.Add(value, key);\n }\n\n void IDictionary.Add (object key, object value)\n {\n ((IDictionary)_owner._secondToFirst).Add(key, value);\n ((IDictionary)_owner._firstToSecond).Add(value, key);\n }\n\n public void Add (KeyValuePair<TSecond, TFirst> item)\n {\n _owner._secondToFirst.Add(item);\n _owner._firstToSecond.Add(item.Reverse());\n }\n\n public bool ContainsKey (TSecond key)\n {\n return _owner._secondToFirst.ContainsKey(key);\n }\n\n public bool Contains (KeyValuePair<TSecond, TFirst> item)\n {\n return _owner._secondToFirst.Contains(item);\n }\n\n public bool TryGetValue (TSecond key, out TFirst value)\n {\n return _owner._secondToFirst.TryGetValue(key, out value);\n }\n\n public bool Remove (TSecond key)\n {\n TFirst value;\n if (_owner._secondToFirst.TryGetValue(key, out value)) {\n _owner._secondToFirst.Remove(key);\n _owner._firstToSecond.Remove(value);\n return true;\n }\n else\n return false;\n }\n\n void IDictionary.Remove (object key)\n {\n var firstToSecond = (IDictionary)_owner._secondToFirst;\n if (!firstToSecond.Contains(key))\n return;\n var value = firstToSecond[key];\n firstToSecond.Remove(key);\n ((IDictionary)_owner._firstToSecond).Remove(value);\n }\n\n public bool Remove (KeyValuePair<TSecond, TFirst> item)\n {\n return _owner._secondToFirst.Remove(item);\n }\n\n public bool Contains (object key)\n {\n return ((IDictionary)_owner._secondToFirst).Contains(key);\n }\n\n public void Clear ()\n {\n _owner._secondToFirst.Clear();\n _owner._firstToSecond.Clear();\n }\n\n public void CopyTo (KeyValuePair<TSecond, TFirst>[] array, int arrayIndex)\n {\n _owner._secondToFirst.CopyTo(array, arrayIndex);\n }\n\n void ICollection.CopyTo (Array array, int index)\n {\n ((IDictionary)_owner._secondToFirst).CopyTo(array, index);\n }\n }\n}\n\ninternal class DictionaryDebugView<TKey, TValue>\n{\n private readonly IDictionary<TKey, TValue> _dictionary;\n\n [DebuggerBrowsable (DebuggerBrowsableState.RootHidden)]\n public KeyValuePair<TKey, TValue>[] Items\n {\n get\n {\n var array = new KeyValuePair<TKey, TValue>[_dictionary.Count];\n _dictionary.CopyTo(array, 0);\n return array;\n }\n }\n\n public DictionaryDebugView (IDictionary<TKey, TValue> dictionary)\n {\n if (dictionary == null)\n throw new ArgumentNullException(\"dictionary\");\n _dictionary = dictionary;\n }\n}\n\npublic static class KeyValuePairExts\n{\n public static KeyValuePair<TValue, TKey> Reverse<TKey, TValue> (this KeyValuePair<TKey, TValue> @this)\n {\n return new KeyValuePair<TValue, TKey>(@this.Value, @this.Key);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33674856,
"author": "Chris Chilvers",
"author_id": 35233,
"author_profile": "https://Stackoverflow.com/users/35233",
"pm_score": 1,
"selected": false,
"text": "<p>A bit late, but here's an implementation I wrote a while back. It handles a few interesting edge cases, such as when the key overrides the equality check to perform partial equality. This results in the main dictionary storing <code>A => 1</code> but the inverse storing <code>1 => A'</code>.</p>\n\n<p>You access the inverse dictionary via the <code>Inverse</code> property.</p>\n\n<pre><code>var map = new BidirectionalDictionary<int, int>();\nmap.Add(1, 2);\nvar result = map.Inverse[2]; // result is 1\n</code></pre>\n\n<hr>\n\n<pre><code>//\n// BidirectionalDictionary.cs\n//\n// Author:\n// Chris Chilvers <[email protected]>\n//\n// Copyright (c) 2009 Chris Chilvers\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Cadenza.Collections\n{\n public class BidirectionalDictionary<TKey, TValue> : IDictionary<TKey, TValue>\n {\n private readonly IEqualityComparer<TKey> keyComparer;\n private readonly IEqualityComparer<TValue> valueComparer;\n private readonly Dictionary<TKey, TValue> keysToValues;\n private readonly Dictionary<TValue, TKey> valuesToKeys;\n private readonly BidirectionalDictionary<TValue, TKey> inverse;\n\n\n public BidirectionalDictionary () : this (10, null, null) {}\n\n public BidirectionalDictionary (int capacity) : this (capacity, null, null) {}\n\n public BidirectionalDictionary (IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)\n : this (10, keyComparer, valueComparer)\n {\n }\n\n public BidirectionalDictionary (int capacity, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)\n {\n if (capacity < 0)\n throw new ArgumentOutOfRangeException (\"capacity\", capacity, \"capacity cannot be less than 0\");\n\n this.keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;\n this.valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;\n\n keysToValues = new Dictionary<TKey, TValue> (capacity, this.keyComparer);\n valuesToKeys = new Dictionary<TValue, TKey> (capacity, this.valueComparer);\n\n inverse = new BidirectionalDictionary<TValue, TKey> (this);\n }\n\n private BidirectionalDictionary (BidirectionalDictionary<TValue, TKey> inverse)\n {\n this.inverse = inverse;\n keyComparer = inverse.valueComparer;\n valueComparer = inverse.keyComparer;\n valuesToKeys = inverse.keysToValues;\n keysToValues = inverse.valuesToKeys;\n }\n\n\n public BidirectionalDictionary<TValue, TKey> Inverse {\n get { return inverse; }\n }\n\n\n public ICollection<TKey> Keys {\n get { return keysToValues.Keys; }\n }\n\n public ICollection<TValue> Values {\n get { return keysToValues.Values; }\n }\n\n public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()\n {\n return keysToValues.GetEnumerator ();\n }\n\n IEnumerator IEnumerable.GetEnumerator ()\n {\n return GetEnumerator ();\n }\n\n void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)\n {\n ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).CopyTo (array, arrayIndex);\n }\n\n\n public bool ContainsKey (TKey key)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n return keysToValues.ContainsKey (key);\n }\n\n public bool ContainsValue (TValue value)\n {\n if (value == null)\n throw new ArgumentNullException (\"value\");\n return valuesToKeys.ContainsKey (value);\n }\n\n bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> item)\n {\n return ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).Contains (item);\n }\n\n public bool TryGetKey (TValue value, out TKey key)\n {\n if (value == null)\n throw new ArgumentNullException (\"value\");\n return valuesToKeys.TryGetValue (value, out key);\n }\n\n public bool TryGetValue (TKey key, out TValue value)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n return keysToValues.TryGetValue (key, out value);\n }\n\n public TValue this[TKey key] {\n get { return keysToValues [key]; }\n set {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n if (value == null)\n throw new ArgumentNullException (\"value\");\n\n //foo[5] = \"bar\"; foo[6] = \"bar\"; should not be valid\n //as it would have to remove foo[5], which is unexpected.\n if (ValueBelongsToOtherKey (key, value))\n throw new ArgumentException (\"Value already exists\", \"value\");\n\n TValue oldValue;\n if (keysToValues.TryGetValue (key, out oldValue)) {\n // Use the current key for this value to stay consistent\n // with Dictionary<TKey, TValue> which does not alter\n // the key if it exists.\n TKey oldKey = valuesToKeys [oldValue];\n\n keysToValues [oldKey] = value;\n valuesToKeys.Remove (oldValue);\n valuesToKeys [value] = oldKey;\n } else {\n keysToValues [key] = value;\n valuesToKeys [value] = key;\n }\n }\n }\n\n public int Count {\n get { return keysToValues.Count; }\n }\n\n bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {\n get { return false; }\n }\n\n\n public void Add (TKey key, TValue value)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n if (value == null)\n throw new ArgumentNullException (\"value\");\n\n if (keysToValues.ContainsKey (key))\n throw new ArgumentException (\"Key already exists\", \"key\");\n if (valuesToKeys.ContainsKey (value))\n throw new ArgumentException (\"Value already exists\", \"value\");\n\n keysToValues.Add (key, value);\n valuesToKeys.Add (value, key);\n }\n\n public void Replace (TKey key, TValue value)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n if (value == null)\n throw new ArgumentNullException (\"value\");\n\n // replaces a key value pair, if the key or value already exists those mappings will be replaced.\n // e.g. you have; a -> b, b -> a; c -> d, d -> c\n // you add the mapping; a -> d, d -> a\n // this will remove both of the original mappings\n Remove (key);\n inverse.Remove (value);\n Add (key, value);\n }\n\n void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> item)\n {\n Add (item.Key, item.Value);\n }\n\n public bool Remove (TKey key)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n\n TValue value;\n if (keysToValues.TryGetValue (key, out value)) {\n keysToValues.Remove (key);\n valuesToKeys.Remove (value);\n return true;\n }\n else {\n return false;\n }\n }\n\n bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> item)\n {\n bool removed = ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).Remove (item);\n if (removed)\n valuesToKeys.Remove (item.Value);\n return removed;\n }\n\n public void Clear ()\n {\n keysToValues.Clear ();\n valuesToKeys.Clear ();\n }\n\n\n private bool ValueBelongsToOtherKey (TKey key, TValue value)\n {\n TKey otherKey;\n if (valuesToKeys.TryGetValue (value, out otherKey))\n // if the keys are not equal the value belongs to another key\n return !keyComparer.Equals (key, otherKey);\n else\n // value doesn't exist in map, thus it cannot belong to another key\n return false;\n }\n }\n}\n</code></pre>\n\n<p><a href=\"https://github.com/cadenza/cadenza/blob/master/src/Cadenza/Cadenza.Collections/BidirectionalDictionary.cs\" rel=\"nofollow\">Original source</a> and <a href=\"https://github.com/cadenza/cadenza/blob/master/src/Cadenza/Test/Cadenza.Collections/BidirectionalDictionaryTest.cs\" rel=\"nofollow\">tests</a> on github.</p>\n"
},
{
"answer_id": 35949314,
"author": "Lukas Z.",
"author_id": 2855278,
"author_profile": "https://Stackoverflow.com/users/2855278",
"pm_score": 2,
"selected": false,
"text": "<p>Another extension to the accepted answer. It implements IEnumerable so one can use foreach with that. I realize there are more answers with IEnumerable implementation but this one uses structs so it is <strong>garbage collector friendly</strong>.\nThis is especially usefull in <strong>Unity</strong> engine (checked with the profiler).</p>\n\n<pre><code>/// <summary>\n/// This is a dictionary guaranteed to have only one of each value and key. \n/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.\n/// It implements garbage-collector-friendly IEnumerable.\n/// </summary>\n/// <typeparam name=\"TFirst\">The type of the \"key\"</typeparam>\n/// <typeparam name=\"TSecond\">The type of the \"value\"</typeparam>\npublic class BiDictionary<TFirst, TSecond> : IEnumerable<BiDictionary<TFirst, TSecond>.Pair>\n{\n\n\n public struct Pair\n {\n public TFirst First;\n public TSecond Second;\n }\n\n\n public struct Enumerator : IEnumerator<Pair>, IEnumerator\n {\n\n public Enumerator(Dictionary<TFirst, TSecond>.Enumerator dictEnumerator)\n {\n _dictEnumerator = dictEnumerator;\n }\n\n public Pair Current\n {\n get\n {\n Pair pair;\n pair.First = _dictEnumerator.Current.Key;\n pair.Second = _dictEnumerator.Current.Value;\n return pair;\n }\n }\n\n object IEnumerator.Current\n {\n get\n {\n return Current;\n }\n }\n\n public void Dispose()\n {\n _dictEnumerator.Dispose();\n }\n\n public bool MoveNext()\n {\n return _dictEnumerator.MoveNext();\n }\n\n public void Reset()\n {\n throw new NotSupportedException();\n }\n\n private Dictionary<TFirst, TSecond>.Enumerator _dictEnumerator;\n\n }\n\n #region Exception throwing methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Throws an exception if either element is already in the dictionary\n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n public void Add(TFirst first, TSecond second)\n {\n if (_firstToSecond.ContainsKey(first) || _secondToFirst.ContainsKey(second))\n throw new ArgumentException(\"Duplicate first or second\");\n\n _firstToSecond.Add(first, second);\n _secondToFirst.Add(second, first);\n }\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first\n /// Throws an exception if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <returns>the value corresponding to first</returns>\n public TSecond GetByFirst(TFirst first)\n {\n TSecond second;\n if (!_firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n return second;\n }\n\n /// <summary>\n /// Find the TFirst corresponing to the Second second.\n /// Throws an exception if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <returns>the value corresponding to second</returns>\n public TFirst GetBySecond(TSecond second)\n {\n TFirst first;\n if (!_secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n return first;\n }\n\n\n /// <summary>\n /// Remove the record containing first.\n /// If first is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"first\">the key of the record to delete</param>\n public void RemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!_firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n _firstToSecond.Remove(first);\n _secondToFirst.Remove(second);\n }\n\n /// <summary>\n /// Remove the record containing second.\n /// If second is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"second\">the key of the record to delete</param>\n public void RemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!_secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n _secondToFirst.Remove(second);\n _firstToSecond.Remove(first);\n }\n\n #endregion\n\n #region Try methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Returns false if either element is already in the dictionary \n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n /// <returns>true if successfully added, false if either element are already in the dictionary</returns>\n public bool TryAdd(TFirst first, TSecond second)\n {\n if (_firstToSecond.ContainsKey(first) || _secondToFirst.ContainsKey(second))\n return false;\n\n _firstToSecond.Add(first, second);\n _secondToFirst.Add(second, first);\n return true;\n }\n\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first.\n /// Returns false if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <param name=\"second\">the corresponding value</param>\n /// <returns>true if first is in the dictionary, false otherwise</returns>\n public bool TryGetByFirst(TFirst first, out TSecond second)\n {\n return _firstToSecond.TryGetValue(first, out second);\n }\n\n /// <summary>\n /// Find the TFirst corresponding to the TSecond second.\n /// Returns false if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <param name=\"first\">the corresponding value</param>\n /// <returns>true if second is in the dictionary, false otherwise</returns>\n public bool TryGetBySecond(TSecond second, out TFirst first)\n {\n return _secondToFirst.TryGetValue(second, out first);\n }\n\n /// <summary>\n /// Remove the record containing first, if there is one.\n /// </summary>\n /// <param name=\"first\"></param>\n /// <returns> If first is not in the dictionary, returns false, otherwise true</returns>\n public bool TryRemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!_firstToSecond.TryGetValue(first, out second))\n return false;\n\n _firstToSecond.Remove(first);\n _secondToFirst.Remove(second);\n return true;\n }\n\n /// <summary>\n /// Remove the record containing second, if there is one.\n /// </summary>\n /// <param name=\"second\"></param>\n /// <returns> If second is not in the dictionary, returns false, otherwise true</returns>\n public bool TryRemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!_secondToFirst.TryGetValue(second, out first))\n return false;\n\n _secondToFirst.Remove(second);\n _firstToSecond.Remove(first);\n return true;\n }\n\n #endregion \n\n /// <summary>\n /// The number of pairs stored in the dictionary\n /// </summary>\n public Int32 Count\n {\n get { return _firstToSecond.Count; }\n }\n\n /// <summary>\n /// Removes all items from the dictionary.\n /// </summary>\n public void Clear()\n {\n _firstToSecond.Clear();\n _secondToFirst.Clear();\n }\n\n\n public Enumerator GetEnumerator()\n {\n //enumerator.Reset(firstToSecond.GetEnumerator());\n return new Enumerator(_firstToSecond.GetEnumerator());\n }\n\n IEnumerator<Pair> IEnumerable<Pair>.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n\n\n private Dictionary<TFirst, TSecond> _firstToSecond = new Dictionary<TFirst, TSecond>();\n private Dictionary<TSecond, TFirst> _secondToFirst = new Dictionary<TSecond, TFirst>();\n\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
] |
I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a `BiDictionaryOneToOne<T, S>` which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't believe that I'm the first person to need this...
There is a BiDictionary in the answers to [this question](https://stackoverflow.com/questions/255341/getting-key-of-value-of-a-generic-dictionary), but it is not for unique elements (and also does not implement RemoveByFirst(T t) or RemoveBySecond(S s)).
Thanks!
|
OK, here is my attempt (building on Jon's - thanks), archived here and open for improvement :
```
/// <summary>
/// This is a dictionary guaranteed to have only one of each value and key.
/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.
/// </summary>
/// <typeparam name="TFirst">The type of the "key"</typeparam>
/// <typeparam name="TSecond">The type of the "value"</typeparam>
public class BiDictionaryOneToOne<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
#region Exception throwing methods
/// <summary>
/// Tries to add the pair to the dictionary.
/// Throws an exception if either element is already in the dictionary
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
throw new ArgumentException("Duplicate first or second");
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
/// <summary>
/// Find the TSecond corresponding to the TFirst first
/// Throws an exception if first is not in the dictionary.
/// </summary>
/// <param name="first">the key to search for</param>
/// <returns>the value corresponding to first</returns>
public TSecond GetByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
throw new ArgumentException("first");
return second;
}
/// <summary>
/// Find the TFirst corresponing to the Second second.
/// Throws an exception if second is not in the dictionary.
/// </summary>
/// <param name="second">the key to search for</param>
/// <returns>the value corresponding to second</returns>
public TFirst GetBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
throw new ArgumentException("second");
return first;
}
/// <summary>
/// Remove the record containing first.
/// If first is not in the dictionary, throws an Exception.
/// </summary>
/// <param name="first">the key of the record to delete</param>
public void RemoveByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
throw new ArgumentException("first");
firstToSecond.Remove(first);
secondToFirst.Remove(second);
}
/// <summary>
/// Remove the record containing second.
/// If second is not in the dictionary, throws an Exception.
/// </summary>
/// <param name="second">the key of the record to delete</param>
public void RemoveBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
throw new ArgumentException("second");
secondToFirst.Remove(second);
firstToSecond.Remove(first);
}
#endregion
#region Try methods
/// <summary>
/// Tries to add the pair to the dictionary.
/// Returns false if either element is already in the dictionary
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns>true if successfully added, false if either element are already in the dictionary</returns>
public Boolean TryAdd(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
return false;
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
return true;
}
/// <summary>
/// Find the TSecond corresponding to the TFirst first.
/// Returns false if first is not in the dictionary.
/// </summary>
/// <param name="first">the key to search for</param>
/// <param name="second">the corresponding value</param>
/// <returns>true if first is in the dictionary, false otherwise</returns>
public Boolean TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
/// <summary>
/// Find the TFirst corresponding to the TSecond second.
/// Returns false if second is not in the dictionary.
/// </summary>
/// <param name="second">the key to search for</param>
/// <param name="first">the corresponding value</param>
/// <returns>true if second is in the dictionary, false otherwise</returns>
public Boolean TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
/// <summary>
/// Remove the record containing first, if there is one.
/// </summary>
/// <param name="first"></param>
/// <returns> If first is not in the dictionary, returns false, otherwise true</returns>
public Boolean TryRemoveByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
return false;
firstToSecond.Remove(first);
secondToFirst.Remove(second);
return true;
}
/// <summary>
/// Remove the record containing second, if there is one.
/// </summary>
/// <param name="second"></param>
/// <returns> If second is not in the dictionary, returns false, otherwise true</returns>
public Boolean TryRemoveBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
return false;
secondToFirst.Remove(second);
firstToSecond.Remove(first);
return true;
}
#endregion
/// <summary>
/// The number of pairs stored in the dictionary
/// </summary>
public Int32 Count
{
get { return firstToSecond.Count; }
}
/// <summary>
/// Removes all items from the dictionary.
/// </summary>
public void Clear()
{
firstToSecond.Clear();
secondToFirst.Clear();
}
}
```
|
268,322 |
<p>Why doesn't this work?</p>
<pre><code>DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
</code></pre>
<p>But if you cast the ShipNo to a varchar in the Case statement it DOES work?</p>
|
[
{
"answer_id": 268367,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 1,
"selected": false,
"text": "<p>From Books Online:</p>\n\n<pre><code>CASE\nWHEN Boolean_expression THEN result_expression \n [ ...n ] \n[ \n ELSE else_result_expression \n] \nEND\n</code></pre>\n\n<p>\"The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion.\"</p>\n\n<p>So Supplier and ShipNo must be the same datatype.</p>\n"
},
{
"answer_id": 2745328,
"author": "Tins",
"author_id": 329833,
"author_profile": "https://Stackoverflow.com/users/329833",
"pm_score": 3,
"selected": true,
"text": "<p>I am aware that this is old post but this is for any one who tumbles upon this issue and is looking for a solution:</p>\n\n<pre><code>SELECT ROW_NUMBER() OVER (ORDER BY \nCASE @OrderBy \n WHEN 'Supplier' THEN Supplier\nEND\nCASE @OrderBy\n WHEN 'ShipNo' THEN ShipNo \nEND \n)\n</code></pre>\n\n<p>basically you are putting each field in its own case. Do this only when their data type or value inside field differs for both the columns or when you are getting error such as</p>\n\n<p>conversion failed when trying to convert int to varchar or varchar to int..</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
Why doesn't this work?
```
DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
```
But if you cast the ShipNo to a varchar in the Case statement it DOES work?
|
I am aware that this is old post but this is for any one who tumbles upon this issue and is looking for a solution:
```
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
END
CASE @OrderBy
WHEN 'ShipNo' THEN ShipNo
END
)
```
basically you are putting each field in its own case. Do this only when their data type or value inside field differs for both the columns or when you are getting error such as
conversion failed when trying to convert int to varchar or varchar to int..
|
268,338 |
<p>Im trying to craft a regex that only returns <code><link></code> tag hrefs</p>
<p>Why does this regex return all hrefs including <a hrefs?</p>
<pre><code>(?&lt;=&lt;link\s+.*?)href\s*=\s*[\'\"][^\'\"]+
</code></pre>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" rev="stylesheet" href="idlecore-tidied.css?T_2_5_0_228" media="screen">
<a href="anotherurl">Slash Boxes&lt;/a>
</code></pre>
|
[
{
"answer_id": 268354,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/(?<=<link\\s+.*?)href\\s*=\\s*[\\'\\\"][^\\'\\\"]+[^>]*>/\n</code></pre>\n\n<p>i'm a little shaky on the back-references myself, so I left that in there. This regex though:</p>\n\n<pre><code>/(<link\\s+.*?)href\\s*=\\s*[\\'\\\"][^\\'\\\"]+[^>]*>/\n</code></pre>\n\n<p>...works in my Javascript test.</p>\n"
},
{
"answer_id": 268371,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": 0,
"selected": false,
"text": "<p>What regex flavor are you using? Perl, for one, doesn't support variable-length lookbehind. Where that's an option, I'd choose (edited to implement the very good idea from MizardX):</p>\n\n<pre><code>(?<=<link\\b[^<>]*?)href\\s*=\\s*(['\"])(?:(?!\\1).)+\\1\n</code></pre>\n\n<p>as a first approximation. That way the choice of quote character (' or \") will be matched.\nThe same for a language without support for (variable-length) lookbehind:</p>\n\n<pre><code>(?:<link\\b[^<>]*?)(href\\s*=\\s*(['\"])(?:(?!\\2).)+\\2)\n</code></pre>\n\n<p>\\1 will contain your match.</p>\n"
},
{
"answer_id": 268373,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 0,
"selected": false,
"text": "<pre><code>(?<=<link\\s+.*?)href\\s*=\\s*[\\'\\\"][^\\'\\\"]+\n</code></pre>\n\n<p>works with <a href=\"http://www.ultrapico.com/Expresso.htm\" rel=\"nofollow noreferrer\">Expresso</a> (I think Expresso runs on the .NET regex-engine). You could even refine this a bit more to match the closing <code>'</code> or \n<code>\"</code>:</p>\n\n<pre><code>(?<=<link\\s+.*?)href\\s*=\\s*([\\'\\\"])[^\\'\\\"]+(\\1)\n</code></pre>\n\n<p>Perhaps your regex-engine doesn't work with lookbehind assertions. A workaround would be</p>\n\n<pre><code>(?:<link\\s+.*?)(href\\s*=\\s*([\\'\\\"])[^\\'\\\"]+(\\2))\n</code></pre>\n\n<p>Your match will then be in the captured group 1.</p>\n"
},
{
"answer_id": 268405,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": true,
"text": "<p>Either</p>\n\n<pre><code>/(?<=<link\\b[^<>]*?)\\bhref=\\s*=\\s*(?:\"[^\"]*\"|'[^']'|\\S+)/\n</code></pre>\n\n<p>or</p>\n\n<pre><code>/<link\\b[^<>]*?\\b(href=\\s*=\\s*(?:\"[^\"]*\"|'[^']'|\\S+))/\n</code></pre>\n\n<p>The main difference is <code>[^<>]*?</code> instead of <code>.*?</code>. This is because you don't want it to continue the search into other tags.</p>\n"
},
{
"answer_id": 268546,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Avoid lookbehind for such simple case, just match what you need, and capture what you want to get.</p>\n\n<p>I got good results with <code><link\\s+[^>]*(href\\s*=\\s*(['\"]).*?\\2)</code> in The Regex Coach with s and g options.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
Im trying to craft a regex that only returns `<link>` tag hrefs
Why does this regex return all hrefs including <a hrefs?
```
(?<=<link\s+.*?)href\s*=\s*[\'\"][^\'\"]+
```
```html
<link rel="stylesheet" rev="stylesheet" href="idlecore-tidied.css?T_2_5_0_228" media="screen">
<a href="anotherurl">Slash Boxes</a>
```
|
Either
```
/(?<=<link\b[^<>]*?)\bhref=\s*=\s*(?:"[^"]*"|'[^']'|\S+)/
```
or
```
/<link\b[^<>]*?\b(href=\s*=\s*(?:"[^"]*"|'[^']'|\S+))/
```
The main difference is `[^<>]*?` instead of `.*?`. This is because you don't want it to continue the search into other tags.
|
268,357 |
<p>I have a couple of dropdown boxes on a normal ASP.Net page.</p>
<p>I would like the user to be able to change these and to have the page Pseudo-post back to the server and store these changes without the user having to hit a save button.</p>
<p>I don't really need to display anything additional as the dropdown itself will reflect the new value, but I would like to post this change back without having the entire page flash due to postback </p>
<p>I have heard that this is possible using AJAX.Net... </p>
<p>Can someone point me in the right direction?</p>
|
[
{
"answer_id": 268673,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 3,
"selected": true,
"text": "<p>Add a reference to System.Web.Extensions and System.Web.Extensions.Design to your website. Then put a scriptmanager on your page and wrap your ddl in an updatepanel. Do whatever you want on the back-end.\nFor example...</p>\n\n<pre><code><asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" />\n<asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\">\n <ContentTemplate>\n\n<asp:DropDownList ID=\"DropDownList1\" runat=\"server\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"yourDDL_SelectedIndexChanged\">\n</asp:DropDownList>\n\n </ContentTemplate>\n</asp:UpdatePanel>\n\nprotected void yourDDL_SelectedIndexChanged(object sender, EventArgs e)\n{\n// do whatever you want\n}\n</code></pre>\n"
},
{
"answer_id": 304682,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "<p>Depends upon your Ajax Framework, Ra-Ajax have a sample of that <a href=\"http://ra-ajax.org/samples/Ajax-DropDownList.aspx\" rel=\"nofollow noreferrer\">here</a>...</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
I have a couple of dropdown boxes on a normal ASP.Net page.
I would like the user to be able to change these and to have the page Pseudo-post back to the server and store these changes without the user having to hit a save button.
I don't really need to display anything additional as the dropdown itself will reflect the new value, but I would like to post this change back without having the entire page flash due to postback
I have heard that this is possible using AJAX.Net...
Can someone point me in the right direction?
|
Add a reference to System.Web.Extensions and System.Web.Extensions.Design to your website. Then put a scriptmanager on your page and wrap your ddl in an updatepanel. Do whatever you want on the back-end.
For example...
```
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="yourDDL_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
protected void yourDDL_SelectedIndexChanged(object sender, EventArgs e)
{
// do whatever you want
}
```
|
268,381 |
<p>I am trying to make a copy of a database to a new database on the same server. The server is my local computer running SQL 2008 Express under Windows XP.
Doing this should be quite easy using the SMO.Transfer class and it almost works!</p>
<p>My code is as follows (somewhat simplified):</p>
<pre><code>Server server = new Server("server");
Database sourceDatabase = server.Databases["source database"];
Database newDatbase = new Database(server, "new name");
newDatbase.Create();
Transfer transfer = new Transfer(sourceDatabase);
transfer.CopyAllObjects = true;
transfer.Options.WithDependencies = true;
transfer.DestinationDatabase = newDatbase.Name;
transfer.CopySchema = true;
transfer.CopyData = true;
StringCollection transferScript = transfer.ScriptTransfer();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand switchDatabase = new SqlCommand("USE " + newDatbase.Name, conn))
{
switchDatabase.ExecuteNonQuery();
}
foreach (string scriptLine in transferScript)
{
using (SqlCommand scriptCmd = new SqlCommand(scriptLine, conn, transaction))
{
int res = scriptCmd.ExecuteNonQuery();
}
}
}
</code></pre>
<p>What I do here is to first create a new database, then generate a copy script using the <code>Transfer</code> class and finally running the script in the new database. </p>
<p>This works fine for copying the structure, but the <code>CopyData</code> option doesn't work!</p>
<p>Are there any undocumented limits to the <code>CopyData</code> option? The documentation only says that the option specifies whether data is copied. </p>
<p>I tried using the <code>TransferData()</code> method to copy the databse without using a script but then I get an exception that says "Failed to connect to server" with an inner exception that says "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"</p>
<p>I also tried to enable Named Pipes on the server, but that doesn't help. </p>
<p>Edit:
I found a solution that works by making a backup and then restoring it to a new database. It's quite clumsy though, and slower than it should be, so I'm still looking for a better solution.</p>
|
[
{
"answer_id": 320877,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 5,
"selected": true,
"text": "<p>Well, after contacting Microsft Support I got it working properly, but it is slow and more or less useless. Doing a backup and then a restore is much faster and I will be using it as long as the new copy should live on the same server as the original. </p>\n\n<p>The working code is as follows:</p>\n\n<pre><code>ServerConnection conn = new ServerConnection(\"rune\\\\sql2008\");\nServer server = new Server(conn);\n\nDatabase newdb = new Database(server, \"new database\");\nnewdb.Create();\n\nTransfer transfer = new Transfer(server.Databases[\"source database\"]);\ntransfer.CopyAllObjects = true;\ntransfer.CopyAllUsers = true;\ntransfer.Options.WithDependencies = true;\ntransfer.DestinationDatabase = newdb.Name;\ntransfer.DestinationServer = server.Name;\ntransfer.DestinationLoginSecure = true;\ntransfer.CopySchema = true;\ntransfer.CopyData = true;\ntransfer.Options.ContinueScriptingOnError = true;\ntransfer.TransferData();\n</code></pre>\n\n<p>The trick was to set the DestinationDatabase property. This must be set even if the target is that same as the source. In addition I had to connect to the server as a named instance instead of using the other connection options.</p>\n"
},
{
"answer_id": 1030846,
"author": "Rob",
"author_id": 24204,
"author_profile": "https://Stackoverflow.com/users/24204",
"pm_score": 2,
"selected": false,
"text": "<p>Try setting <a href=\"http://msdn.microsoft.com/en-us/library/ms210363.aspx\" rel=\"nofollow noreferrer\"><strong>SetDefaultInitFields</strong></a> to true on the <strong>Server</strong> object.</p>\n\n<p>I had the same issue with the SMO database object running slowly. I guess this is because sql server doesn't like to retrieve entire objects and collections at once, instead lazy loading everything, causing a round-trip for each field, which for an entire database is pretty inefficient.</p>\n"
},
{
"answer_id": 7807931,
"author": "emy",
"author_id": 1001194,
"author_profile": "https://Stackoverflow.com/users/1001194",
"pm_score": 2,
"selected": false,
"text": "<p>I had a go at getting this working and have come up with an answer that doesn't use the Transfer class. Here is the Method i used:</p>\n\n<pre><code> public bool CreateScript(string oldDatabase, string newDatabase)\n {\n SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=\" + newDatabase + \";User Id=sa;Password=sa;\");\n try\n {\n Server sv = new Server();\n Database db = sv.Databases[oldDatabase];\n\n Database newDatbase = new Database(sv, newDatabase);\n newDatbase.Create(); \n\n ScriptingOptions options = new ScriptingOptions();\n StringBuilder sb = new StringBuilder();\n options.ScriptData = true;\n options.ScriptDrops = false;\n options.ScriptSchema = true;\n options.EnforceScriptingOptions = true;\n options.Indexes = true;\n options.IncludeHeaders = true;\n options.WithDependencies = true;\n\n TableCollection tables = db.Tables;\n\n conn.Open();\n foreach (Table mytable in tables)\n {\n foreach (string line in db.Tables[mytable.Name].EnumScript(options))\n {\n sb.Append(line + \"\\r\\n\");\n }\n }\n string[] splitter = new string[] { \"\\r\\nGO\\r\\n\" };\n string[] commandTexts = sb.ToString().Split(splitter, StringSplitOptions.RemoveEmptyEntries);\n foreach (string command in commandTexts)\n {\n SqlCommand comm = new SqlCommand(command, conn);\n comm.ExecuteNonQuery();\n }\n return true;\n }\n catch (Exception e)\n {\n System.Diagnostics.Debug.WriteLine(\"PROGRAM FAILED: \" + e.Message);\n return false;\n }\n finally\n {\n conn.Close();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 20454460,
"author": "emcuapharaon",
"author_id": 3079989,
"author_profile": "https://Stackoverflow.com/users/3079989",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<ol>\n<li>I have a Database named is Olddatabase</li>\n<li><p>I backup it to E:\\databackup\\Old.bak</p></li>\n<li><p>If you want to create a Duplicate Database from Olddatabase in the same server with name NewDatabase</p></li>\n</ol>\n\n<p>3.1 You can use command in query tool : EXEC OldDatabase.dbo.sp_helpfile;\nto determinat path of OldDatabase is stored in case you want to save NewDatabase in the same folder. </p>\n\n<p>or You can save NewDatabase in new Path which you want</p>\n\n<ol>\n<li><p>use this command in Query tool</p>\n\n<p>RESTORE DATABASE NewDatabase FROM DISK = 'E:\\databackup\\Old.bak'\nWITH MOVE 'OldDatabase' TO 'E:\\New path (or the same path)\\NewDatabase_Data.mdf',\nMOVE 'OldDatabase_log' TO 'E:\\New path (or the same path)\\NewDatabase_Log.ldf';</p></li>\n</ol>\n\n<p>Note: you can Use these command obove in c# with : Create a Store procedure in sql which include Above commands. And you can call the store procedure in C #</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30366/"
] |
I am trying to make a copy of a database to a new database on the same server. The server is my local computer running SQL 2008 Express under Windows XP.
Doing this should be quite easy using the SMO.Transfer class and it almost works!
My code is as follows (somewhat simplified):
```
Server server = new Server("server");
Database sourceDatabase = server.Databases["source database"];
Database newDatbase = new Database(server, "new name");
newDatbase.Create();
Transfer transfer = new Transfer(sourceDatabase);
transfer.CopyAllObjects = true;
transfer.Options.WithDependencies = true;
transfer.DestinationDatabase = newDatbase.Name;
transfer.CopySchema = true;
transfer.CopyData = true;
StringCollection transferScript = transfer.ScriptTransfer();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand switchDatabase = new SqlCommand("USE " + newDatbase.Name, conn))
{
switchDatabase.ExecuteNonQuery();
}
foreach (string scriptLine in transferScript)
{
using (SqlCommand scriptCmd = new SqlCommand(scriptLine, conn, transaction))
{
int res = scriptCmd.ExecuteNonQuery();
}
}
}
```
What I do here is to first create a new database, then generate a copy script using the `Transfer` class and finally running the script in the new database.
This works fine for copying the structure, but the `CopyData` option doesn't work!
Are there any undocumented limits to the `CopyData` option? The documentation only says that the option specifies whether data is copied.
I tried using the `TransferData()` method to copy the databse without using a script but then I get an exception that says "Failed to connect to server" with an inner exception that says "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
I also tried to enable Named Pipes on the server, but that doesn't help.
Edit:
I found a solution that works by making a backup and then restoring it to a new database. It's quite clumsy though, and slower than it should be, so I'm still looking for a better solution.
|
Well, after contacting Microsft Support I got it working properly, but it is slow and more or less useless. Doing a backup and then a restore is much faster and I will be using it as long as the new copy should live on the same server as the original.
The working code is as follows:
```
ServerConnection conn = new ServerConnection("rune\\sql2008");
Server server = new Server(conn);
Database newdb = new Database(server, "new database");
newdb.Create();
Transfer transfer = new Transfer(server.Databases["source database"]);
transfer.CopyAllObjects = true;
transfer.CopyAllUsers = true;
transfer.Options.WithDependencies = true;
transfer.DestinationDatabase = newdb.Name;
transfer.DestinationServer = server.Name;
transfer.DestinationLoginSecure = true;
transfer.CopySchema = true;
transfer.CopyData = true;
transfer.Options.ContinueScriptingOnError = true;
transfer.TransferData();
```
The trick was to set the DestinationDatabase property. This must be set even if the target is that same as the source. In addition I had to connect to the server as a named instance instead of using the other connection options.
|
268,384 |
<p>Why does the PRINT statement in T-SQL seem to only sometimes work? What are the constraints on using it? It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?</p>
|
[
{
"answer_id": 268419,
"author": "David T. Macknet",
"author_id": 6850,
"author_profile": "https://Stackoverflow.com/users/6850",
"pm_score": 8,
"selected": true,
"text": "<p>So, if you have a statement something like the following, you're saying that you get no 'print' result?</p>\n\n<pre>select * from sysobjects\nPRINT 'Just selected * from sysobjects'</pre>\n\n<p>If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is \"Messages\" and that's where the 'print' statements will show up.<br>\nIf you're concerned about the <i>timing</i> of seeing the print statements, you may want to try using something like</p>\n\n<pre>raiserror ('My Print Statement', 10,1) with nowait</pre>\n\n<p>This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.</p>\n"
},
{
"answer_id": 269983,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.</p>\n\n<p>Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.</p>\n\n<p>It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.</p>\n"
},
{
"answer_id": 2548623,
"author": "JohnOpincar",
"author_id": 16245,
"author_profile": "https://Stackoverflow.com/users/16245",
"pm_score": 2,
"selected": false,
"text": "<p>For the benefit of anyone else reading this question that really is missing print statements from their output, there actually are cases where the print executes but is not returned to the client. I can't tell you specifically what they are. I can tell you that if you put a go statement immediately before and after any print statement, you will see if it is executed.</p>\n"
},
{
"answer_id": 2928995,
"author": "JimCarden",
"author_id": 352896,
"author_profile": "https://Stackoverflow.com/users/352896",
"pm_score": 5,
"selected": false,
"text": "<p>Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:</p>\n\n<pre><code>RAISERROR ('Your message', 0, 1) WITH NOWAIT\n</code></pre>\n\n<p>RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.</p>\n\n<p>Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.</p>\n"
},
{
"answer_id": 11162818,
"author": "WEFX",
"author_id": 590719,
"author_profile": "https://Stackoverflow.com/users/590719",
"pm_score": 5,
"selected": false,
"text": "<p>I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.</p>\n\n<p>Example - This will fail:</p>\n\n<pre><code>declare @myID int=null\nprint 'First Statement: ' + convert(varchar(4), @myID)\n</code></pre>\n\n<p>Example - This will print:</p>\n\n<pre><code>declare @myID int=null\nprint 'Second Statement: ' + coalesce(Convert(varchar(4), @myID),'@myID is null')\n</code></pre>\n"
},
{
"answer_id": 17754379,
"author": "user2574678",
"author_id": 2574678,
"author_profile": "https://Stackoverflow.com/users/2574678",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
Why does the PRINT statement in T-SQL seem to only sometimes work? What are the constraints on using it? It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?
|
So, if you have a statement something like the following, you're saying that you get no 'print' result?
```
select * from sysobjects
PRINT 'Just selected * from sysobjects'
```
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the *timing* of seeing the print statements, you may want to try using something like
```
raiserror ('My Print Statement', 10,1) with nowait
```
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
|
268,391 |
<p>I want to use Visual Studio snippets to generate SQL code, for example we have standard naming conventions for foreign keys etc and it would be great if I could just expand a snippet in my SQL script file. </p>
<p>However as far as I can tell the only languages that are supported by the Snippet manager are C#, VB J# and XML</p>
<p><a href="http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx</a></p>
<p>Does anyone know of a way to have a snippet expand to SQL?</p>
<p>Derek</p>
|
[
{
"answer_id": 268419,
"author": "David T. Macknet",
"author_id": 6850,
"author_profile": "https://Stackoverflow.com/users/6850",
"pm_score": 8,
"selected": true,
"text": "<p>So, if you have a statement something like the following, you're saying that you get no 'print' result?</p>\n\n<pre>select * from sysobjects\nPRINT 'Just selected * from sysobjects'</pre>\n\n<p>If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is \"Messages\" and that's where the 'print' statements will show up.<br>\nIf you're concerned about the <i>timing</i> of seeing the print statements, you may want to try using something like</p>\n\n<pre>raiserror ('My Print Statement', 10,1) with nowait</pre>\n\n<p>This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.</p>\n"
},
{
"answer_id": 269983,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.</p>\n\n<p>Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.</p>\n\n<p>It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.</p>\n"
},
{
"answer_id": 2548623,
"author": "JohnOpincar",
"author_id": 16245,
"author_profile": "https://Stackoverflow.com/users/16245",
"pm_score": 2,
"selected": false,
"text": "<p>For the benefit of anyone else reading this question that really is missing print statements from their output, there actually are cases where the print executes but is not returned to the client. I can't tell you specifically what they are. I can tell you that if you put a go statement immediately before and after any print statement, you will see if it is executed.</p>\n"
},
{
"answer_id": 2928995,
"author": "JimCarden",
"author_id": 352896,
"author_profile": "https://Stackoverflow.com/users/352896",
"pm_score": 5,
"selected": false,
"text": "<p>Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:</p>\n\n<pre><code>RAISERROR ('Your message', 0, 1) WITH NOWAIT\n</code></pre>\n\n<p>RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.</p>\n\n<p>Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.</p>\n"
},
{
"answer_id": 11162818,
"author": "WEFX",
"author_id": 590719,
"author_profile": "https://Stackoverflow.com/users/590719",
"pm_score": 5,
"selected": false,
"text": "<p>I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.</p>\n\n<p>Example - This will fail:</p>\n\n<pre><code>declare @myID int=null\nprint 'First Statement: ' + convert(varchar(4), @myID)\n</code></pre>\n\n<p>Example - This will print:</p>\n\n<pre><code>declare @myID int=null\nprint 'Second Statement: ' + coalesce(Convert(varchar(4), @myID),'@myID is null')\n</code></pre>\n"
},
{
"answer_id": 17754379,
"author": "user2574678",
"author_id": 2574678,
"author_profile": "https://Stackoverflow.com/users/2574678",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28584/"
] |
I want to use Visual Studio snippets to generate SQL code, for example we have standard naming conventions for foreign keys etc and it would be great if I could just expand a snippet in my SQL script file.
However as far as I can tell the only languages that are supported by the Snippet manager are C#, VB J# and XML
<http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx>
Does anyone know of a way to have a snippet expand to SQL?
Derek
|
So, if you have a statement something like the following, you're saying that you get no 'print' result?
```
select * from sysobjects
PRINT 'Just selected * from sysobjects'
```
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the *timing* of seeing the print statements, you may want to try using something like
```
raiserror ('My Print Statement', 10,1) with nowait
```
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
|
268,421 |
<p>Heres a tricky one . .</p>
<p>I have a webpage (called PageA) that has a header and then simply includes an iframe. Lets call the page within the iframe PageB. PageB simply has a bunch of thumbnails but there are a lot so you have to scroll down on PageA to view them all. </p>
<p>When i scroll down to the bottom of the pageB and click on a thumbnail it looks like it takes me to a blank page. What actually happens is that it bring up the image but since the page that is just the image is much shorter in height, the scroll bar stays at the same location and doesn't adjust for it. I have to scroll up to the top of the page to view the picture.</p>
<p>Is there anyway when i click a link on a page that is within an iframe, the outer pages scroll bar goes back up to the top</p>
<p>thks,
ak</p>
|
[
{
"answer_id": 269428,
"author": "Dave Swersky",
"author_id": 34796,
"author_profile": "https://Stackoverflow.com/users/34796",
"pm_score": 1,
"selected": false,
"text": "<p>Javascript is your best bet. You can use the <a href=\"http://www.java2s.com/Code/JavaScriptReference/Javascript-Methods/scrollSyntaxParametersandNote.htm\" rel=\"nofollow noreferrer\">scroll() method</a> to scroll back up to the top of your IFRAME. Add a javascript handler in the body load so that each time you click a thumbnail, call a function that calls scroll() to scroll up.</p>\n"
},
{
"answer_id": 624093,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 4,
"selected": true,
"text": "<p>@mek after trying various methods, the best solution I've found is this:</p>\n\n<p>In the outer page, define a scroller function:</p>\n\n<pre><code><script type=\"text/javascript\">\n function gotop() {\n scroll(0,0);\n } \n</script>\n</code></pre>\n\n<p>Then when you define the iframe, set an onload handler (which fires each time the iframe source loads i.e. whenever you navigate to a new page in the iframe)</p>\n\n<pre><code><iframe id=\"myframe\" \n onload=\"try { gotop() } catch (e) {}\" \n src=\"http://yourframesource\"\n width=\"100%\" height=\"999\"\n scrolling=\"auto\" marginwidth=\"0\" marginheight=\"0\" \n frameborder=\"0\" vspace=\"0\" hspace=\"0\" >\n</iframe>\n</code></pre>\n\n<p>The nice thing about this approach is it means you do not need to make any changes to the pages included in the iframe (and the iframe contents can happily be in another domain - no cross-site scripting issues).</p>\n"
},
{
"answer_id": 992246,
"author": "beaudetious",
"author_id": 3622,
"author_profile": "https://Stackoverflow.com/users/3622",
"pm_score": 0,
"selected": false,
"text": "<p>I've spent a considerable amount of time trying to figure out how to scroll to the top of the iframe from within the PHP code I was calling (from within the parent ASP.NET page). I never figured I could scroll to the top using the same javascript but in the iframe's onload event. Thanks!</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
Heres a tricky one . .
I have a webpage (called PageA) that has a header and then simply includes an iframe. Lets call the page within the iframe PageB. PageB simply has a bunch of thumbnails but there are a lot so you have to scroll down on PageA to view them all.
When i scroll down to the bottom of the pageB and click on a thumbnail it looks like it takes me to a blank page. What actually happens is that it bring up the image but since the page that is just the image is much shorter in height, the scroll bar stays at the same location and doesn't adjust for it. I have to scroll up to the top of the page to view the picture.
Is there anyway when i click a link on a page that is within an iframe, the outer pages scroll bar goes back up to the top
thks,
ak
|
@mek after trying various methods, the best solution I've found is this:
In the outer page, define a scroller function:
```
<script type="text/javascript">
function gotop() {
scroll(0,0);
}
</script>
```
Then when you define the iframe, set an onload handler (which fires each time the iframe source loads i.e. whenever you navigate to a new page in the iframe)
```
<iframe id="myframe"
onload="try { gotop() } catch (e) {}"
src="http://yourframesource"
width="100%" height="999"
scrolling="auto" marginwidth="0" marginheight="0"
frameborder="0" vspace="0" hspace="0" >
</iframe>
```
The nice thing about this approach is it means you do not need to make any changes to the pages included in the iframe (and the iframe contents can happily be in another domain - no cross-site scripting issues).
|
268,426 |
<p>We're using Microsoft.Practices.CompositeUI.EventBroker to handle event subscription and publication in our application. The way that works is that you add an attribute to your event, specifying a topic name, like this:</p>
<pre><code>[EventPublication("example", PublicationScope.Global)]
public event EventHandler Example;
</code></pre>
<p>then you add another attribute to your handler, with the same topic name, like this:</p>
<pre><code>[EventSubscription("example", ThreadOption.Publisher)]
public void OnExample(object sender, EventArgs e)
{
...
}
</code></pre>
<p>Then you pass your objects to an EventInspector which matches everything up.</p>
<p>We need to debug this, so we're trying to create a debug class that subscribes to <em>all</em> the events. I can get a list of all the topic names... but only at runtime. So I need to be able to add attributes to a method at runtime, before we pass our debug object to the EventInspector.</p>
<p>How do I add attributes to a method at runtime?</p>
|
[
{
"answer_id": 268480,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Attributes are a compile-time feature (unless you are dealing with ComponentModel - but I suspect it is using reflection). As such, you cannot add attributes at runtime. It would a similar question to \"how do I add an extra method to a type at runtime?\". In regular C# / .NET (pre-DLR), you can't.</p>\n"
},
{
"answer_id": 268486,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "<p>You need to delve into the world of the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx\" rel=\"nofollow noreferrer\"><code>DynamicMethod</code></a>. However, as you need then to know MSIL, I really suggest you think hard about your architecture.</p>\n"
},
{
"answer_id": 268576,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 5,
"selected": true,
"text": "<p>What you are trying to achieve is quite complicated, so I will try to provide something just to get you started. This is what I think you would need to combine in order to achieve something:</p>\n\n<ol>\n<li>Define an abstract class <code>AbstractEventDebugger</code>, with a method <code>Search</code> that searches all of the <code>event</code> members, and registers them with the EventInspector. Also, define a method <code>IdentifyEvent</code> that will allow you to identify the event that has called it (this depends on you - what parameters will have, etc.).</li>\n<li>Define a <code>dynamic type</code> using <code>TypeBuilder</code> (as described <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.aspx\" rel=\"noreferrer\">here</a>), that inherits from your class. This class would be the class of your <code>debugger</code> object.</li>\n<li>Attach the Handlers to your class using <code>Reflection.Emit.MethodBuilder</code> (see <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.methodbuilder.aspx\" rel=\"noreferrer\">here</a>), which will be calling the <code>IdentifyEvent</code> method from the parent class and,</li>\n<li><code>Reflection.Emit</code> the attributes on the handlers using <code>CustomAttributeBuilder</code> class (see <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.customattributebuilder.aspx\" rel=\"noreferrer\">here</a>).</li>\n<li>Create an instance of your <code>dynamic</code> class and send it to the EventInspector.</li>\n<li>Fire it up <code>:)</code></li>\n</ol>\n\n<p><a href=\"http://blogs.msdn.com/joelpob/archive/2004/03/31/105282.aspx\" rel=\"noreferrer\">Here</a> is a sample on how to create a method that calls something (Actually it's the classic \"Hello world\").</p>\n\n<p>You will need to do a lot of tweaking in order to get it done well, but you will learn a lot about reflection.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 268733,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 1,
"selected": false,
"text": "<p>The EventInspector uses EventTopics (which are stored in the WorkItem) to do all the heavy lifting. Each EventTopic object has access to a TraceSource called </p>\n\n<p>Microsoft.Practices.CompositeUI.EventBroker.EventTopic</p>\n\n<p>Which you can enable in your app.config file like this:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.diagnostics>\n <switches>\n <add name=\"Microsoft.Practices.CompositeUI.EventBroker.EventTopic\" value=\"All\" />\n </switches>\n </system.diagnostics>\n</configuration>\n</code></pre>\n\n<p>This should make plenty of useful messages get routed to your debug window in Visual Studio. If you want to go beyond the VS debug window you have plenty of options. I'd recommend checking out the following article:</p>\n\n<p><a href=\"http://weblogs.asp.net/ralfw/archive/2007/10/31/code-instrumentation-with-tracesource-my-personal-vade-mecum.aspx\" rel=\"nofollow noreferrer\">Code Instrumentation with TraceSource My Persoanl Vade Mecum</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
We're using Microsoft.Practices.CompositeUI.EventBroker to handle event subscription and publication in our application. The way that works is that you add an attribute to your event, specifying a topic name, like this:
```
[EventPublication("example", PublicationScope.Global)]
public event EventHandler Example;
```
then you add another attribute to your handler, with the same topic name, like this:
```
[EventSubscription("example", ThreadOption.Publisher)]
public void OnExample(object sender, EventArgs e)
{
...
}
```
Then you pass your objects to an EventInspector which matches everything up.
We need to debug this, so we're trying to create a debug class that subscribes to *all* the events. I can get a list of all the topic names... but only at runtime. So I need to be able to add attributes to a method at runtime, before we pass our debug object to the EventInspector.
How do I add attributes to a method at runtime?
|
What you are trying to achieve is quite complicated, so I will try to provide something just to get you started. This is what I think you would need to combine in order to achieve something:
1. Define an abstract class `AbstractEventDebugger`, with a method `Search` that searches all of the `event` members, and registers them with the EventInspector. Also, define a method `IdentifyEvent` that will allow you to identify the event that has called it (this depends on you - what parameters will have, etc.).
2. Define a `dynamic type` using `TypeBuilder` (as described [here](http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.aspx)), that inherits from your class. This class would be the class of your `debugger` object.
3. Attach the Handlers to your class using `Reflection.Emit.MethodBuilder` (see [here](http://msdn.microsoft.com/en-us/library/system.reflection.emit.methodbuilder.aspx)), which will be calling the `IdentifyEvent` method from the parent class and,
4. `Reflection.Emit` the attributes on the handlers using `CustomAttributeBuilder` class (see [here](http://msdn.microsoft.com/en-us/library/system.reflection.emit.customattributebuilder.aspx)).
5. Create an instance of your `dynamic` class and send it to the EventInspector.
6. Fire it up `:)`
[Here](http://blogs.msdn.com/joelpob/archive/2004/03/31/105282.aspx) is a sample on how to create a method that calls something (Actually it's the classic "Hello world").
You will need to do a lot of tweaking in order to get it done well, but you will learn a lot about reflection.
Good luck!
|
268,429 |
<p>How to 'group by' a query using an alias, for example:</p>
<pre><code>select count(*), (select * from....) as alias_column
from table
group by alias_column
</code></pre>
<p>I get 'alias_column' : INVALID_IDENTIFIER error message. Why? How to group this query?</p>
|
[
{
"answer_id": 268447,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": true,
"text": "<pre><code>select\n count(count_col),\n alias_column\nfrom\n (\n select \n count_col, \n (select value from....) as alias_column \n from \n table\n ) as inline\ngroup by \n alias_column\n</code></pre>\n\n<p>Grouping normally works if you repeat the respective expression in the GROUP BY clause. Just mentioning an alias is not possible, because the SELECT step is the last step to happen the execution of a query, grouping happens earlier, when alias names are not yet defined.</p>\n\n<p>To GROUP BY the result of a sub-query, you will have to take a little detour and use an nested query, as indicated above.</p>\n"
},
{
"answer_id": 268474,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "<p>Nest the query with the alias column:</p>\n\n<pre><code>select count(*), alias_column\nfrom\n( select empno, (select deptno from emp where emp.empno = e.empno) as alias_column\n from emp e\n)\ngroup by alias_column;\n</code></pre>\n"
},
{
"answer_id": 268494,
"author": "ian_scho",
"author_id": 15530,
"author_profile": "https://Stackoverflow.com/users/15530",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select count(*), (select * from....) as alias_column \nfrom table \ngroup by (select * from....)\n</code></pre>\n\n<p>In Oracle you cannot use an alias in a group by clause.</p>\n"
},
{
"answer_id": 5720745,
"author": "Andrew",
"author_id": 561698,
"author_profile": "https://Stackoverflow.com/users/561698",
"pm_score": 2,
"selected": false,
"text": "<p>To use an alias in Oracle you need to ensure that the alias has been defined by your query at the point at which the alias is being used.</p>\n\n<p>The most straightforward way to do this is to simply treat the original query as a subquery -- in this case, </p>\n\n<pre><code>select count(*), (select * from....) as alias_column \nfrom table \ngroup by (select * from....)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>select count, alias_column \nfrom\n (select count(*) as count, (select * from....) as alias_column \n from table)\ngroup by alias_column \n</code></pre>\n\n<p>I can't speak to the performance implications, but it's very quick to write if you're trying to re-use an alias in your query - throw everything in parentheses and jump up a level...</p>\n"
},
{
"answer_id": 50260305,
"author": "augre",
"author_id": 4192212,
"author_profile": "https://Stackoverflow.com/users/4192212",
"pm_score": -1,
"selected": false,
"text": "<p>If you don't have to use an alias you could do it this way:</p>\n\n<pre><code>select \nEXTRACT(year from CURRENT_DATE), count(*) from something\ngroup by EXTRACT(year from CURRENT_DATE)\norder by EXTRACT(year from CURRENT_DATE)\n</code></pre>\n\n<p>Instead of using alias and subquery. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221/"
] |
How to 'group by' a query using an alias, for example:
```
select count(*), (select * from....) as alias_column
from table
group by alias_column
```
I get 'alias\_column' : INVALID\_IDENTIFIER error message. Why? How to group this query?
|
```
select
count(count_col),
alias_column
from
(
select
count_col,
(select value from....) as alias_column
from
table
) as inline
group by
alias_column
```
Grouping normally works if you repeat the respective expression in the GROUP BY clause. Just mentioning an alias is not possible, because the SELECT step is the last step to happen the execution of a query, grouping happens earlier, when alias names are not yet defined.
To GROUP BY the result of a sub-query, you will have to take a little detour and use an nested query, as indicated above.
|
268,432 |
<p>ASP.NET 3.5 SP1 adds a great new ScriptCombining feature to the ScriptManager object as demonstrated on <a href="http://www.asp.net/learn/3.5-SP1/video-296.aspx?wwwaspnetrdirset=1" rel="nofollow noreferrer">this video</a>. However he only demonstrates how to use the feature with the ScriptManager on the same page. I'd like to use this feature on a site where the scriptmanager is on the master page but can't figure out how to add the scripts I need for each page programmatically to the manager. I've found <a href="http://seejoelprogram.wordpress.com/2008/08/19/net-35-sp1-doesnt-provide-composite-script-registration-from-an-iscriptcontrol-out-of-the-box/" rel="nofollow noreferrer">this post</a> to use as a starting point, but I'm not really getting very far. can anyone give me a helping hand?</p>
<p>Thanks, Dan</p>
|
[
{
"answer_id": 269785,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 3,
"selected": true,
"text": "<p>Give this a shot:</p>\n\n<pre><code> ScriptReference SRef = new ScriptReference();\n SRef.Path = \"~/Scripts/Script.js\";\n\n\n ScriptManager.GetCurrent(Page).CompositeScript.Scripts.Add(SRef);\n</code></pre>\n\n<p>That will get the current scriptmanager (even if it is on a master page) and add a script reference to the CompositeScript properties.</p>\n"
},
{
"answer_id": 4622604,
"author": "Chris Herring",
"author_id": 77067,
"author_profile": "https://Stackoverflow.com/users/77067",
"pm_score": 1,
"selected": false,
"text": "<p>You can also do this in markup using <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanagerproxy.aspx\" rel=\"nofollow\">ScriptManagerProxy</a>.</p>\n\n<p>You can add the ScriptManager to the master page e.g.</p>\n\n<pre><code><asp:ScriptManager ID=\"ScriptManager\" runat=\"server\">\n <CompositeScript>\n <Scripts>\n <asp:ScriptReference name=\"WebForms.js\" assembly=\"System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n <asp:ScriptReference name=\"MicrosoftAjax.js\" assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n <asp:ScriptReference name=\"MicrosoftAjaxWebForms.js\" assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n </Scripts>\n </CompositeScript>\n</asp:ScriptManager>\n</code></pre>\n\n<p>And then add the ScriptManagerProxy to the content page e.g.</p>\n\n<pre><code><asp:Content ID=\"HomeContent\" ContentPlaceHolderID=\"PlaceHolder\" runat=\"Server\">\n <asp:ScriptManagerProxy runat=\"server\">\n <CompositeScript>\n <Scripts>\n <asp:ScriptReference Path=\"~/yourscript.js\" />\n </Scripts>\n </CompositeScript>\n </asp:ScriptManagerProxy>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2756/"
] |
ASP.NET 3.5 SP1 adds a great new ScriptCombining feature to the ScriptManager object as demonstrated on [this video](http://www.asp.net/learn/3.5-SP1/video-296.aspx?wwwaspnetrdirset=1). However he only demonstrates how to use the feature with the ScriptManager on the same page. I'd like to use this feature on a site where the scriptmanager is on the master page but can't figure out how to add the scripts I need for each page programmatically to the manager. I've found [this post](http://seejoelprogram.wordpress.com/2008/08/19/net-35-sp1-doesnt-provide-composite-script-registration-from-an-iscriptcontrol-out-of-the-box/) to use as a starting point, but I'm not really getting very far. can anyone give me a helping hand?
Thanks, Dan
|
Give this a shot:
```
ScriptReference SRef = new ScriptReference();
SRef.Path = "~/Scripts/Script.js";
ScriptManager.GetCurrent(Page).CompositeScript.Scripts.Add(SRef);
```
That will get the current scriptmanager (even if it is on a master page) and add a script reference to the CompositeScript properties.
|
268,444 |
<p>I'm hoping that someone has found a way of doing this already or that there is a library already in existence. It's one of those things that would be nice but is in no way necessary for the time being.</p>
<p>The functionality I'm looking for is something like <a href="http://www.datejs.com/" rel="nofollow noreferrer">datejs</a> in reverse.</p>
<p>Thanks,</p>
<p>Simon.</p>
<hr>
<p>Thanks, using something like the dddd example might be a good start towards usability. The more I think about this problem the more it depends on the values being used. I'm specifically dealing with a series of timestamped versions of a document so there is a good chance that they will be clustered. Today isn't so hot if you have saved it three times in the last five minutes.</p>
<p>If I come up with something I'll share it with the community.</p>
|
[
{
"answer_id": 268457,
"author": "mmiika",
"author_id": 6846,
"author_profile": "https://Stackoverflow.com/users/6846",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx</a> should get you on your way,</p>\n"
},
{
"answer_id": 268529,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>Actually, what you really want is the Custom DateTime Format strings:\n<a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4(VS.71).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/8kb3ddd4(VS.71).aspx</a></p>\n\n<pre><code>DateTime.Now.ToString(\"ggyyyy$dd-MMM (dddd)\")\n</code></pre>\n\n<p>will return \"A.D.2008$06-Nov (Thursday)\" if that's what you want.</p>\n\n<p>And to get something closr to datejs (\"in forward\"), you can use the same strings in <code>DateTime.ParseExact()</code></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35047/"
] |
I'm hoping that someone has found a way of doing this already or that there is a library already in existence. It's one of those things that would be nice but is in no way necessary for the time being.
The functionality I'm looking for is something like [datejs](http://www.datejs.com/) in reverse.
Thanks,
Simon.
---
Thanks, using something like the dddd example might be a good start towards usability. The more I think about this problem the more it depends on the values being used. I'm specifically dealing with a series of timestamped versions of a document so there is a good chance that they will be clustered. Today isn't so hot if you have saved it three times in the last five minutes.
If I come up with something I'll share it with the community.
|
Actually, what you really want is the Custom DateTime Format strings:
<http://msdn.microsoft.com/en-us/library/8kb3ddd4(VS.71).aspx>
```
DateTime.Now.ToString("ggyyyy$dd-MMM (dddd)")
```
will return "A.D.2008$06-Nov (Thursday)" if that's what you want.
And to get something closr to datejs ("in forward"), you can use the same strings in `DateTime.ParseExact()`
|
268,464 |
<pre><code><form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" >
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<a onclick="test(event, '1'); " href="#" >Click Here</a>
<script>
function test(event, id){
document.getElementById("frm_"+id).submit;
document.getElementById("tgt_"+id).submit;
}
</script>
</code></pre>
<p>Is it possible to open a new tab/window and change the current page ?</p>
|
[
{
"answer_id": 268477,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I know, it's not possible to submit two forms at once. Since you're using PHP however, why not take a look at the <a href=\"http://au2.php.net/manual/en/book.curl.php\" rel=\"nofollow noreferrer\">cURL</a> library? It lets you send POST and GET requests and parse the results in PHP.</p>\n\n<p>To answer the question in the title, if you simply want to open two pages with one click, you could do it like this (excuse the inline javascript):</p>\n\n<pre><code><a\n href=\"http://www.google.com\"\n target=\"_blank\"\n onclick=\"document.location.href='http://www.yahoo.com'\"\n>Click here to open Google in a new window and yahoo in this window</a>\n</code></pre>\n"
},
{
"answer_id": 268502,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 0,
"selected": false,
"text": "<p>You should use the window.open to open the new page and then submit the tabchange e.g.</p>\n\n<pre><code><form id=\"frm_1\" name=\"frm_1\" target=\"_self\" method=\"GET\" action=\"local_page.php\" >\n</form>\n<a onclick=\"test(event, '1'); \" href=\"#\" >Click Here</a>\n<script>\n function test(event, id){\n window.open(\"http://stackoverflow.com/\", \"_blank\");\n document.getElementById(\"tgt_\"+id).submit();\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 268572,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<p>Use the ‘target’ attribute on the form elements to make them submit to eg. a new window or an iframe, without reloading the current page (breaking any other form submissions).</p>\n\n<p>Your a.onclick should also return false to stop the href link being followed. Really this should be a button not a link.</p>\n\n<p>Avoid this sort of stuff unless you've got a specific good reason. Depending on what you're actually trying to do there is usually a better way.</p>\n"
},
{
"answer_id": 268831,
"author": "John Griffiths",
"author_id": 24765,
"author_profile": "https://Stackoverflow.com/users/24765",
"pm_score": 2,
"selected": true,
"text": "<pre><code><form id=\"frm_1\" name=\"frm_1\" target=\"_self\" method=\"POST\" action=\"local_page.php\" >\n<input type=\"hidden\" name=\"vital_param\" value=\"<?= $something ?>\">\n</form>\n\n<form id=\"tgt_1\" name=\"tgt_1\" target=\"_blank\" method=\"POST\" action=\"http://stackoverflow.com/\" >\n</form>\n\n<button type=\"submit\" onclick=\"test(event, '1'); \" >Click Here</button>\n\n<script>\n function test(event, id){\n window.open( document.getElementById(\"tgt_\"+id).action, \"_blank\");\n setTimeout('document.getElementById(\"frm_'+id+'\").submit();', 1000);\n\n return true;\n }\n</script>\n</code></pre>\n\n<p>tgt kept as source of target url, could be array or attribute.\nWithout setyTimeout() browser stays on current page (FF/IE).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24765/"
] |
```
<form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" >
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<a onclick="test(event, '1'); " href="#" >Click Here</a>
<script>
function test(event, id){
document.getElementById("frm_"+id).submit;
document.getElementById("tgt_"+id).submit;
}
</script>
```
Is it possible to open a new tab/window and change the current page ?
|
```
<form id="frm_1" name="frm_1" target="_self" method="POST" action="local_page.php" >
<input type="hidden" name="vital_param" value="<?= $something ?>">
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<button type="submit" onclick="test(event, '1'); " >Click Here</button>
<script>
function test(event, id){
window.open( document.getElementById("tgt_"+id).action, "_blank");
setTimeout('document.getElementById("frm_'+id+'").submit();', 1000);
return true;
}
</script>
```
tgt kept as source of target url, could be array or attribute.
Without setyTimeout() browser stays on current page (FF/IE).
|
268,468 |
<p>I noticed that the ASP.NET cache items are inspected (and possibly removed) every 20 seconds (and oddly enough each time at HH:MM:00, HH:MM:20 and HH:MM:40). I spent about 15 minutes looking how to change this parameter without any success. I also tried to set the following in web.config, but it did not help:</p>
<pre><code><cache privateBytesPollTime="00:00:05" />
</code></pre>
<p>I’m not trying to do anything crazy, but it would be nice if it was, say, 5 seconds instead of 20, or at least 10 for my application.</p>
|
[
{
"answer_id": 269368,
"author": "Dave Swersky",
"author_id": 34796,
"author_profile": "https://Stackoverflow.com/users/34796",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.cachesection.privatebytespolltime.aspx\" rel=\"nofollow noreferrer\">documentation</a>, privateBytesPollTime is for \"worker process memory usage\" and the default is 1 second. I don't think this relates to cache item removal.</p>\n\n<p>I did confirm your results using an item removal callback- it looks like items are removed at the bottom of the minute, :20, and :40 seconds. This suggests that an item may remain in the cache for up to 20 seconds past the AbsoluteExpiration set on them. I couldn't find any documentation stating whether the 20 second polling interval could be changed.</p>\n"
},
{
"answer_id": 270374,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 5,
"selected": true,
"text": "<p>Poking around with Reflector reveals that the the interval is hardcoded. Expiry is handled by an internal <code>CacheExpires</code> class, whose static constructor contains</p>\n\n<pre><code>_tsPerBucket = new TimeSpan(0, 0, 20);\n</code></pre>\n\n<p><code>_tsPerBucket</code> is <code>readonly</code>, so there can't be any configuration setting that modifies it later.</p>\n\n<p>The timer that will trigger the check for expired items is then set up in <code>CacheExpires.EnableExpirationTimer()</code>...</p>\n\n<pre><code>DateTime utcNow = DateTime.UtcNow;\nTimeSpan span = _tsPerBucket - new TimeSpan(utcNow.Ticks % _tsPerBucket.Ticks);\nthis._timer = new Timer(new TimerCallback(this.TimerCallback), null,\n span.Ticks / 0x2710L, _tsPerBucket.Ticks / 0x2710L);\n</code></pre>\n\n<p>The calculation of <code>span</code> ensures that the timer fires exactly on :00, :20, :40 seconds, though I can't see any reason to bother. The method that the timer calls is <code>internal</code>, so I don't think there's any way to set up your own timer to call it more often (ignoring reflection).</p>\n\n<p>However, the good news is that you shouldn't really have any reason to care about the interval. <code>Cache.Get()</code> checks that the item hasn't expired, and if it has then it removes the item from the cache immediately and returns <code>null</code>. Therefore you'll never get an expired item from the cache, even though expired items may stay in the cache for up to 20 seconds.</p>\n"
},
{
"answer_id": 7272610,
"author": "mipo",
"author_id": 923708,
"author_profile": "https://Stackoverflow.com/users/923708",
"pm_score": 2,
"selected": false,
"text": "<p>Crazy, but working solution (all steps are needed):</p>\n\n<pre><code>// New value for cache expiration cycle\n// System.Web.Caching.CacheExpires._tsPerBucket;\n// Set 1 seconds instead of 20sec\nconst string assembly = \"System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\";\nvar type = Type.GetType(\"System.Web.Caching.CacheExpires, \" + assembly, true, true);\nvar field = type.GetField(\"_tsPerBucket\", BindingFlags.Static | BindingFlags.NonPublic);\nfield.SetValue(null, TimeSpan.FromSeconds(1));\n\n// Recreate cache\n// HttpRuntime._theRuntime._cacheInternal = null;\n// HttpRuntime._theRuntime._cachePublic = null;\ntype = typeof (HttpRuntime);\nfield = type.GetField(\"_theRuntime\", BindingFlags.Static | BindingFlags.NonPublic);\nvar runtime = field.GetValue(null);\nfield = type.GetField(\"_cachePublic\", BindingFlags.NonPublic | BindingFlags.Instance);\nfield.SetValue(runtime, null);\nfield = type.GetField(\"_cacheInternal\", BindingFlags.NonPublic | BindingFlags.Instance);\nfield.SetValue(runtime, null);\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716/"
] |
I noticed that the ASP.NET cache items are inspected (and possibly removed) every 20 seconds (and oddly enough each time at HH:MM:00, HH:MM:20 and HH:MM:40). I spent about 15 minutes looking how to change this parameter without any success. I also tried to set the following in web.config, but it did not help:
```
<cache privateBytesPollTime="00:00:05" />
```
I’m not trying to do anything crazy, but it would be nice if it was, say, 5 seconds instead of 20, or at least 10 for my application.
|
Poking around with Reflector reveals that the the interval is hardcoded. Expiry is handled by an internal `CacheExpires` class, whose static constructor contains
```
_tsPerBucket = new TimeSpan(0, 0, 20);
```
`_tsPerBucket` is `readonly`, so there can't be any configuration setting that modifies it later.
The timer that will trigger the check for expired items is then set up in `CacheExpires.EnableExpirationTimer()`...
```
DateTime utcNow = DateTime.UtcNow;
TimeSpan span = _tsPerBucket - new TimeSpan(utcNow.Ticks % _tsPerBucket.Ticks);
this._timer = new Timer(new TimerCallback(this.TimerCallback), null,
span.Ticks / 0x2710L, _tsPerBucket.Ticks / 0x2710L);
```
The calculation of `span` ensures that the timer fires exactly on :00, :20, :40 seconds, though I can't see any reason to bother. The method that the timer calls is `internal`, so I don't think there's any way to set up your own timer to call it more often (ignoring reflection).
However, the good news is that you shouldn't really have any reason to care about the interval. `Cache.Get()` checks that the item hasn't expired, and if it has then it removes the item from the cache immediately and returns `null`. Therefore you'll never get an expired item from the cache, even though expired items may stay in the cache for up to 20 seconds.
|
268,476 |
<p>Take a very simple case as an example, say I have this URL:</p>
<pre><code>http://www.example.com/65167.html
</code></pre>
<p>and I wish to serve that content under:</p>
<pre><code>http://www.example.com/about
</code></pre>
<p><strong>UPDATE</strong>: Note that the 'bad' URL is the canonical one (it's produced by a CMS which uses it internally for linking), so <code>"/about"</code> is just a way of polishing it.</p>
<p>I have two broad options: a server-side redirect or a client-side one. I always thought that server-side would be preferable since it's more efficient, i.e. HTTP traffic is approximately halved. However, SEO techniques tend to favour a single URL for a resource, thus client-side is to be preferred.</p>
<p>How do you resolve this conflict, and are there other factors I've omitted?</p>
|
[
{
"answer_id": 268487,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 3,
"selected": true,
"text": "<p>Apache HTTPD's mod_rewrite can leave a browser showing a SEO-friendly URL in its location bar while redirecting to a numeric URL on the server:</p>\n\n<pre><code>RewriteEngine on\nRewriteRule ^/about$ /65167.html [L]\n</code></pre>\n"
},
{
"answer_id": 268685,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>I'm pretty sure Google understands <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2\" rel=\"nofollow noreferrer\">301 Moved Permanently</a>.</p>\n"
},
{
"answer_id": 315355,
"author": "Michael Glenn",
"author_id": 9424,
"author_profile": "https://Stackoverflow.com/users/9424",
"pm_score": 2,
"selected": false,
"text": "<p>A 301 is the wrong approach for this problem if you're redirecting from /about to /65167.html. Your CMS will only understand the 65167.html\nrequest but a 301 is basically telling Google that /about no longer exists and to index the 65167.html page. </p>\n\n<p>Ignacio is correct. You need to implement either mod_rewrite or something similar depending on your platform and hide the CMS assuming that you can actually re-write all your CMS generated links to something more friendly. </p>\n\n<p>A client side redirect is probably too complex to implement and a server side redirect will cause two requests to the server.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] |
Take a very simple case as an example, say I have this URL:
```
http://www.example.com/65167.html
```
and I wish to serve that content under:
```
http://www.example.com/about
```
**UPDATE**: Note that the 'bad' URL is the canonical one (it's produced by a CMS which uses it internally for linking), so `"/about"` is just a way of polishing it.
I have two broad options: a server-side redirect or a client-side one. I always thought that server-side would be preferable since it's more efficient, i.e. HTTP traffic is approximately halved. However, SEO techniques tend to favour a single URL for a resource, thus client-side is to be preferred.
How do you resolve this conflict, and are there other factors I've omitted?
|
Apache HTTPD's mod\_rewrite can leave a browser showing a SEO-friendly URL in its location bar while redirecting to a numeric URL on the server:
```
RewriteEngine on
RewriteRule ^/about$ /65167.html [L]
```
|
268,483 |
<p>I'm currently in the process of writing a wizard and want to make each page validate before moving onto the next page.</p>
<p>I want to prevent the user from progressing by calling the Validate() method on every child control on the page and and stopping navigation if any of them fail.</p>
<p>The problem is that the Validate() method on every child control is a private method so I can't access it directly. Can anyone give me some advice on how to get a result from the Validate() method on a TextBox (For example) using Reflection?</p>
<p>Many thanks!</p>
<p><strong>Edit: Sorry - should have specified, this is Windows Forms, .Net 2.0</strong></p>
|
[
{
"answer_id": 268514,
"author": "Jamey McElveen",
"author_id": 30099,
"author_profile": "https://Stackoverflow.com/users/30099",
"pm_score": 1,
"selected": false,
"text": "<p>If you are talking asp.net you can set the ValidationGroup attribute on the control then call <code>this.Validate(\"GroupName\")</code> on the page for the group you need to validate. </p>\n\n<p>Forget the group and just call <code>Validate()</code> if you need to validate the whole page. </p>\n"
},
{
"answer_id": 2136871,
"author": "Eric Smith",
"author_id": 86356,
"author_profile": "https://Stackoverflow.com/users/86356",
"pm_score": 2,
"selected": false,
"text": "<p>If the pages happen to be ContainerControl instances, you can just call ValidateChildren. If not, this seems to work on an individual control:</p>\n\n<pre><code>private void ValidateControl(Control control)\n{\n Type type = control.GetType();\n type.InvokeMember(\"PerformControlValidation\", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, control, new object[] { true });\n}\n</code></pre>\n"
},
{
"answer_id": 2280311,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 0,
"selected": false,
"text": "<p>No need for reflection - what you want is <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.containercontrol.validatechildren.aspx\" rel=\"nofollow noreferrer\">ContainerControl.ValidateChildren()</a> (call it on your form/dialog)</p>\n\n<p>Note that <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.containercontrol.validate.aspx\" rel=\"nofollow noreferrer\">ContainerControl.Validate()</a> will only validate the last control to have focus and its ancestors:</p>\n\n<blockquote>\n <p>The Validate method validates the last child control that is not validated and its ancestors up through, but not including, the current container control</p>\n</blockquote>\n\n<p>However, if your parent control is not a ContainerControl (Say, a Panel), reflection is indeed necessary - see NoBugz's answer <a href=\"http://social.msdn.microsoft.com/forums/en-US/winforms/thread/1cef306e-6d39-432b-b479-29140fd11766/\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4019/"
] |
I'm currently in the process of writing a wizard and want to make each page validate before moving onto the next page.
I want to prevent the user from progressing by calling the Validate() method on every child control on the page and and stopping navigation if any of them fail.
The problem is that the Validate() method on every child control is a private method so I can't access it directly. Can anyone give me some advice on how to get a result from the Validate() method on a TextBox (For example) using Reflection?
Many thanks!
**Edit: Sorry - should have specified, this is Windows Forms, .Net 2.0**
|
If the pages happen to be ContainerControl instances, you can just call ValidateChildren. If not, this seems to work on an individual control:
```
private void ValidateControl(Control control)
{
Type type = control.GetType();
type.InvokeMember("PerformControlValidation", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, control, new object[] { true });
}
```
|
268,490 |
<p>I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.</p>
<pre><code>var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
</code></pre>
<p>I would like to know if there is a better way to do this using jQuery. I've been experimenting with:</p>
<pre><code>var odv = $.create("div");
$.append(odv);
// And many more
</code></pre>
<p>But I'm not sure if this is any better.</p>
|
[
{
"answer_id": 268507,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 7,
"selected": false,
"text": "<p>Simply supplying the HTML of elements you want to add to a jQuery constructor <code>$()</code> will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's <code>append()</code> method.</p>\n\n<p>For example:</p>\n\n<pre><code>var t = $(\"<table cellspacing='0' class='text'></table>\");\n$.append(t);\n</code></pre>\n\n<p>You could then populate this table programmatically, if you wished.</p>\n\n<p>This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using <code>createElement</code> and then setting attributes like <code>cellSpacing</code> and <code>className</code> via JS. </p>\n"
},
{
"answer_id": 268520,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 11,
"selected": true,
"text": "<p>Here's your example in the \"one\" line.</p>\n\n<pre><code>this.$OuterDiv = $('<div></div>')\n .hide()\n .append($('<table></table>')\n .attr({ cellSpacing : 0 })\n .addClass(\"text\")\n )\n;\n</code></pre>\n\n<hr>\n\n<p><em>Update</em>: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about <code>$(\"<div>\")</code> vs <code>$(\"<div></div>\")</code> vs <code>$(document.createElement('div'))</code> as a way of creating new elements, and which is \"best\".</p>\n\n<p>I put together <a href=\"http://jsbin.com/elula3\" rel=\"noreferrer\">a small benchmark</a>, and here are roughly the results of repeating the above options 100,000 times:</p>\n\n<p><strong>jQuery 1.4, 1.5, 1.6</strong></p>\n\n<pre><code> Chrome 11 Firefox 4 IE9\n<div> 440ms 640ms 460ms\n<div></div> 420ms 650ms 480ms\ncreateElement 100ms 180ms 300ms\n</code></pre>\n\n<p><strong>jQuery 1.3</strong></p>\n\n<pre><code> Chrome 11\n<div> 770ms\n<div></div> 3800ms\ncreateElement 100ms\n</code></pre>\n\n<p><strong>jQuery 1.2</strong></p>\n\n<pre><code> Chrome 11\n<div> 3500ms\n<div></div> 3500ms\ncreateElement 100ms\n</code></pre>\n\n<p>I think it's no big surprise, but <code>document.createElement</code> is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds <em>per thousand elements</em>. </p>\n\n<hr>\n\n<p><strong>Update 2</strong></p>\n\n<p>Updated for <strong>jQuery 1.7.2</strong> and put the benchmark on <code>JSBen.ch</code> which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!</p>\n\n<p><a href=\"http://jsben.ch/#/ARUtz\" rel=\"noreferrer\">http://jsben.ch/#/ARUtz</a></p>\n"
},
{
"answer_id": 268523,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": -1,
"selected": false,
"text": "<p>jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.</p>\n\n<p>There are also plugins available that make use of the DOM over innerHTML like <a href=\"http://plugins.jquery.com/project/appendDom\" rel=\"nofollow noreferrer\">appendDOM</a>, <a href=\"http://plugins.jquery.com/project/DOMEC\" rel=\"nofollow noreferrer\">DOMEC</a> and <a href=\"http://plugins.jquery.com/project/FlyDOM\" rel=\"nofollow noreferrer\">FlyDOM</a> just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)</p>\n"
},
{
"answer_id": 2906828,
"author": "Randy",
"author_id": 338457,
"author_profile": "https://Stackoverflow.com/users/338457",
"pm_score": 2,
"selected": false,
"text": "<p>It's all pretty straight forward! Heres a couple quick examples...</p>\n\n<hr>\n\n<pre><code>var $example = $( XMLDocRoot );\n</code></pre>\n\n<hr>\n\n<pre><code>var $element = $( $example[0].createElement('tag') );\n// Note the [0], which is the root\n\n$element.attr({\nid: '1',\nhello: 'world'\n});\n</code></pre>\n\n<hr>\n\n<pre><code>var $example.find('parent > child').append( $element );\n</code></pre>\n"
},
{
"answer_id": 3253261,
"author": "abernier",
"author_id": 133327,
"author_profile": "https://Stackoverflow.com/users/133327",
"pm_score": 6,
"selected": false,
"text": "<p>Creating new DOM elements is a core feature of the <code>jQuery()</code> method, see:</p>\n\n<ul>\n<li><a href=\"http://api.jquery.com/jQuery/#creating-new-elements\" rel=\"noreferrer\">http://api.jquery.com/jQuery/#creating-new-elements</a></li>\n<li>and particulary <a href=\"http://api.jquery.com/jQuery/#example-1-1\" rel=\"noreferrer\">http://api.jquery.com/jQuery/#example-1-1</a></li>\n</ul>\n"
},
{
"answer_id": 4207056,
"author": "Shimon Doodkin",
"author_id": 466363,
"author_profile": "https://Stackoverflow.com/users/466363",
"pm_score": 4,
"selected": false,
"text": "<pre><code>var mydiv = $('<div />') // also works\n</code></pre>\n"
},
{
"answer_id": 4514397,
"author": "AcidicChip",
"author_id": 551783,
"author_profile": "https://Stackoverflow.com/users/551783",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var div = $('<div/>');\ndiv.append('Hello World!');\n</code></pre>\n\n<p>Is the shortest/easiest way to create a DIV element in jQuery.</p>\n"
},
{
"answer_id": 13544029,
"author": "kami",
"author_id": 163456,
"author_profile": "https://Stackoverflow.com/users/163456",
"pm_score": 6,
"selected": false,
"text": "<p>I'm doing like that:</p>\n\n<pre><code>$('<div/>',{\n text: 'Div text',\n class: 'className'\n}).appendTo('#parentDiv');\n</code></pre>\n"
},
{
"answer_id": 14493220,
"author": "Brian",
"author_id": 938380,
"author_profile": "https://Stackoverflow.com/users/938380",
"pm_score": 6,
"selected": false,
"text": "<p>since <code>jQuery1.8</code>, using <a href=\"http://api.jquery.com/jQuery.parseHTML/\" rel=\"noreferrer\"><code>$.parseHTML()</code></a> to create elements is a better choice.</p>\n\n<p>there are two benefits:</p>\n\n<p>1.if you use the old way, which may be something like <code>$(string)</code>, jQuery will examine the string to make sure you want to select a html tag or create a new element. By using <code>$.parseHTML()</code>, you tell jQuery that you want to create a new element explicitly, so the performance may be a little better.</p>\n\n<p>2.much more important thing is that you may suffer from cross site attack (<a href=\"http://blog.jquery.com/2012/06/22/jquery-1-8-beta-1-see-whats-coming-and-going/#xss-protection\" rel=\"noreferrer\">more info</a>) if you use the old way. if you have something like:</p>\n\n<pre><code> var userInput = window.prompt(\"please enter selector\");\n $(userInput).hide();\n</code></pre>\n\n<p>a bad guy can input <code><script src=\"xss-attach.js\"></script></code> to tease you. fortunately, <code>$.parseHTML()</code> avoid this embarrassment for you:</p>\n\n<pre><code>var a = $('<div>')\n// a is [<div></div>]\nvar b = $.parseHTML('<div>')\n// b is [<div></div>]\n$('<script src=\"xss-attach.js\"></script>')\n// jQuery returns [<script src=\"xss-attach.js\"></script>]\n$.parseHTML('<script src=\"xss-attach.js\"></script>')\n// jQuery returns []\n</code></pre>\n\n<p>However, please notice that <code>a</code> is a jQuery object while <code>b</code> is a html element:</p>\n\n<pre><code>a.html('123')\n// [<div>123</div>]\nb.html('123')\n// TypeError: Object [object HTMLDivElement] has no method 'html'\n$(b).html('123')\n// [<div>123</div>]\n</code></pre>\n"
},
{
"answer_id": 17161445,
"author": "Om Shankar",
"author_id": 1249219,
"author_profile": "https://Stackoverflow.com/users/1249219",
"pm_score": 5,
"selected": false,
"text": "<p><strong>UPDATE</strong></p>\n\n<p>As of the latest versions of jQuery, the following method doesn't assign properties passed in the second Object</p>\n\n<p><strong>Previous answer</strong></p>\n\n<p>I feel using <code>document.createElement('div')</code> together with <code>jQuery</code> is faster:</p>\n\n<pre><code>$(document.createElement('div'), {\n text: 'Div text',\n 'class': 'className'\n}).appendTo('#parentDiv');\n</code></pre>\n"
},
{
"answer_id": 18255277,
"author": "ern0",
"author_id": 185881,
"author_profile": "https://Stackoverflow.com/users/185881",
"pm_score": 3,
"selected": false,
"text": "<p>I've just made a small jQuery plugin for that: <a href=\"https://github.com/ern0/jquery.create\" rel=\"noreferrer\">https://github.com/ern0/jquery.create</a></p>\n\n<p>It follows your syntax:</p>\n\n<pre><code>var myDiv = $.create(\"div\");\n</code></pre>\n\n<p>DOM node ID can be specified as second parameter:</p>\n\n<pre><code>var secondItem = $.create(\"div\",\"item2\");\n</code></pre>\n\n<p>Is it serious? No. But this syntax is better than <em>$(\"<div></div>\")</em>, and it's a very good value for that money.</p>\n\n<p>I'm a new jQuery user, switching from DOMAssistant, which has a similar function: <a href=\"http://www.domassistant.com/documentation/DOMAssistantContent-module.php\" rel=\"noreferrer\">http://www.domassistant.com/documentation/DOMAssistantContent-module.php</a></p>\n\n<p>My plugin is simpler, I think attrs and content is better to add by chaining methods:</p>\n\n<pre><code>$(\"#container\").append( $.create(\"div\").addClass(\"box\").html(\"Hello, world!\") );\n</code></pre>\n\n<p>Also, it's a good example for a simple jQuery-plugin (the 100th one).</p>\n"
},
{
"answer_id": 19082040,
"author": "Adam Zielinski",
"author_id": 1510277,
"author_profile": "https://Stackoverflow.com/users/1510277",
"pm_score": 5,
"selected": false,
"text": "<p>Though this is a very old question, I thought it would be nice to update it with recent information;</p>\n\n<p>Since jQuery 1.8 there is a <a href=\"http://api.jquery.com/jQuery.parseHTML/\" rel=\"nofollow noreferrer\">jQuery.parseHTML()</a> function which is now a preferred way of creating elements. Also, there are some issues with parsing HTML via <code>$('(html code goes here)')</code>, fo example official jQuery website mentions the following in <a href=\"http://blog.jquery.com/2013/05/24/jquery-1-10-0-and-2-0-1-released/\" rel=\"nofollow noreferrer\">one of their release notes</a>:</p>\n\n<blockquote>\n <p>Relaxed HTML parsing: You can once again have leading spaces or\n newlines before tags in $(htmlString). We still strongly advise that\n you use $.parseHTML() when parsing HTML obtained from external\n sources, and may be making further changes to HTML parsing in the\n future.</p>\n</blockquote>\n\n<p>To relate to the actual question, provided example could be translated to:</p>\n\n<pre><code>this.$OuterDiv = $($.parseHTML('<div></div>'))\n .hide()\n .append($($.parseHTML('<table></table>'))\n .attr({ cellSpacing : 0 })\n .addClass(\"text\")\n )\n;\n</code></pre>\n\n<p>which is unfortunately less convenient than using just <code>$()</code>, but it gives you more control, for example you may choose to exclude script tags (it will leave inline scripts like <code>onclick</code> though):</p>\n\n<pre><code>> $.parseHTML('<div onclick=\"a\"></div><script></script>')\n[<div onclick=\"a\"></div>]\n\n> $.parseHTML('<div onclick=\"a\"></div><script></script>', document, true)\n[<div onclick=\"a\"></div>, <script></script>]\n</code></pre>\n\n<p>Also, here's a benchmark from the top answer adjusted to the new reality:</p>\n\n<p><a href=\"http://jsbin.com/eZiZAZ\" rel=\"nofollow noreferrer\">JSbin Link</a></p>\n\n<p><strong>jQuery 1.9.1</strong></p>\n\n<pre>\n $.parseHTML: 88ms\n $($.parseHTML): 240ms\n <div></div>: 138ms\n <div>: 143ms\n createElement: 64ms\n</pre>\n\n<p>It looks like <code>parseHTML</code> is much closer to <code>createElement</code> than <code>$()</code>, but all the boost is gone after wrapping the results in a new jQuery object</p>\n"
},
{
"answer_id": 56297382,
"author": "Vladislav Ladicky",
"author_id": 9805590,
"author_profile": "https://Stackoverflow.com/users/9805590",
"pm_score": 2,
"selected": false,
"text": "<p>Not mentioned in previous answers, so I'm adding working example how to create element elements with latest jQuery, also with additional attributes like content, class, or onclick callback:</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>const mountpoint = 'https://jsonplaceholder.typicode.com/users'\r\n\r\nconst $button = $('button')\r\nconst $tbody = $('tbody')\r\n\r\nconst loadAndRender = () => {\r\n $.getJSON(mountpoint).then(data => {\r\n\r\n $.each(data, (index, { id, username, name, email }) => {\r\n let row = $('<tr>')\r\n .append($('<td>', { text: id }))\r\n .append($('<td>', {\r\n text: username,\r\n class: 'click-me',\r\n on: {\r\n click: _ => {\r\n console.log(name)\r\n }\r\n }\r\n }))\r\n .append($('<td>', { text: email }))\r\n\r\n $tbody.append(row)\r\n })\r\n\r\n })\r\n}\r\n\r\n$button.on('click', loadAndRender)</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.click-me {\r\n background-color: lightgrey\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><table style=\"width: 100%\">\r\n <thead>\r\n <tr>\r\n <th>ID</th>\r\n <th>Username</th>\r\n <th>Email</th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n \r\n </tbody>\r\n</table>\r\n\r\n<button>Load and render</button>\r\n\r\n<script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64067381,
"author": "João Pimentel Ferreira",
"author_id": 1243247,
"author_profile": "https://Stackoverflow.com/users/1243247",
"pm_score": 2,
"selected": false,
"text": "<p>What about this, for example when you want to add a <code><option></code> element inside a <code><select></code></p>\n<pre class=\"lang-js prettyprint-override\"><code>$('<option/>')\n .val(optionVal)\n .text('some option')\n .appendTo('#mySelect')\n</code></pre>\n<p>You can obviously apply to any element</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('<div/>')\n .css('border-color', red)\n .text('some text')\n .appendTo('#parentDiv')\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
] |
I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.
```
var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
```
I would like to know if there is a better way to do this using jQuery. I've been experimenting with:
```
var odv = $.create("div");
$.append(odv);
// And many more
```
But I'm not sure if this is any better.
|
Here's your example in the "one" line.
```
this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
```
---
*Update*: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about `$("<div>")` vs `$("<div></div>")` vs `$(document.createElement('div'))` as a way of creating new elements, and which is "best".
I put together [a small benchmark](http://jsbin.com/elula3), and here are roughly the results of repeating the above options 100,000 times:
**jQuery 1.4, 1.5, 1.6**
```
Chrome 11 Firefox 4 IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
```
**jQuery 1.3**
```
Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms
```
**jQuery 1.2**
```
Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms
```
I think it's no big surprise, but `document.createElement` is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds *per thousand elements*.
---
**Update 2**
Updated for **jQuery 1.7.2** and put the benchmark on `JSBen.ch` which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!
<http://jsben.ch/#/ARUtz>
|
268,496 |
<p>The default output from Drupal's Form API is:</p>
<pre><code><input id="edit-submit" class="form-submit" type="submit" value="Save" name="op"/>
</code></pre>
<p>How do I theme that so I get:</p>
<pre><code><button id="edit-submit" class="form-submit" type="submit">
<span>Save</span>
</button>
</code></pre>
<p>I need the inner span-tag so I can use the sliding doors CSS technique.</p>
<p>I guess I need to override theme_button($element) from form.inc but my attempts so far have been unsuccessful.</p>
|
[
{
"answer_id": 271472,
"author": "FGM",
"author_id": 33991,
"author_profile": "https://Stackoverflow.com/users/33991",
"pm_score": 3,
"selected": true,
"text": "<p>The basic idea to themeing a form_foo if you're using a plain PHP theme (like Chameleon), is to write a function called theme_form_foo().</p>\n\n<p>You can also theme one element (like this button) specifically, by declaring a theme function just for it. See <a href=\"http://api.drupal.org/api/file/developer/topics/forms_api_reference.html#theme\" rel=\"nofollow noreferrer\">https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7</a></p>\n\n<p>Note that, with D6, in both cases you'll need to declare the function in the theme registry, otherwise Drupal won't notice this override. This is not necessary in D5. If you're using phptemplate, you'll need it too, although PHPtemplate takes care of the registry outside the forms case: <a href=\"http://drupal.org/node/132442#theme-registry\" rel=\"nofollow noreferrer\">http://drupal.org/node/132442#theme-registry</a></p>\n\n<p>The documentation for this is available on a.d.o. : <a href=\"http://drupal.org/node/132442#theme-registry\" rel=\"nofollow noreferrer\">http://api.drupal.org/api/file/developer/topics/forms_api.html</a></p>\n"
},
{
"answer_id": 271635,
"author": "larssg",
"author_id": 3842,
"author_profile": "https://Stackoverflow.com/users/3842",
"pm_score": 2,
"selected": false,
"text": "<p>I now have a function along the lines of</p>\n\n<pre><code>function mytheme_button($element) {\n return \"<button><span></span></button>\"; # lots of code missing here for clarity\n}\n</code></pre>\n\n<p>In order to make it work I simply cleared the cache and Drupal noticed and used it automatically.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842/"
] |
The default output from Drupal's Form API is:
```
<input id="edit-submit" class="form-submit" type="submit" value="Save" name="op"/>
```
How do I theme that so I get:
```
<button id="edit-submit" class="form-submit" type="submit">
<span>Save</span>
</button>
```
I need the inner span-tag so I can use the sliding doors CSS technique.
I guess I need to override theme\_button($element) from form.inc but my attempts so far have been unsuccessful.
|
The basic idea to themeing a form\_foo if you're using a plain PHP theme (like Chameleon), is to write a function called theme\_form\_foo().
You can also theme one element (like this button) specifically, by declaring a theme function just for it. See [https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7](http://api.drupal.org/api/file/developer/topics/forms_api_reference.html#theme)
Note that, with D6, in both cases you'll need to declare the function in the theme registry, otherwise Drupal won't notice this override. This is not necessary in D5. If you're using phptemplate, you'll need it too, although PHPtemplate takes care of the registry outside the forms case: <http://drupal.org/node/132442#theme-registry>
The documentation for this is available on a.d.o. : [http://api.drupal.org/api/file/developer/topics/forms\_api.html](http://drupal.org/node/132442#theme-registry)
|
268,499 |
<p>I can use an bitmap in a menu</p>
<pre><code>CMenu men;
CBitmap b;
b.LoadBitmap(IDB_0);
men.AppendMenu( MF_ENABLED,1,&b);
</code></pre>
<p>I can draw an icon into a DC</p>
<pre><code> CImageList IL;
IL.Create(70, 14, ILC_COLOR16 | ILC_MASK, 1, 0);
IL.Add(AfxGetApp()->LoadIcon(IDI_0));
IL.Draw ( pDC, 0, rcIcon.TopLeft(), ILD_BLEND50 );
</code></pre>
<p>But I cannot find a simple way to show an icon in a menu. I would like to do this</p>
<pre><code>CMenu men;
CBitmap b;
// here the miracle happens, load the icon into the bitmap
men.AppendMenu( MF_ENABLED,1,&b);
</code></pre>
<p>Seems like this should be possible.</p>
<hr>
<p>This is the same question as <a href="https://stackoverflow.com/questions/70386/icons-on-menus-of-mfc-feature-pack-classes">this</a>. However that question referred to the MFC feature pack, did not get answered, and has shown no activity for a month, so I thought it would be worthwhile to ask it again in reference to basic MFC.</p>
|
[
{
"answer_id": 268703,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 2,
"selected": false,
"text": "<p>I asked the question you reference.</p>\n\n<p>The way to add (normal, 16-bit color) icons to menus is to make a toolbar with the same resource id as the menu you want to have icons in. You then assign id's to each of the toolbar buttons, the same id's as the menu entries. Make a wizard-generated new MFC application and you'll see how it works there.</p>\n\n<p>The answers to the question I posted suggested that it should work the same for 32-bit images with transparency for the Feature Pack toolbars; I haven't gotten around to test it out though.</p>\n\n<p>If your specific problem is how to make dynamically-generated menus, I think you should pass the id of an existing entry in a toolbar and then that image will be used.</p>\n\n<p>Not a real answer to your question but maybe it'll point you in the right direction.</p>\n"
},
{
"answer_id": 269027,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": -1,
"selected": false,
"text": "<p>In order to set up a bitmap for a menu, you need to call CMenu::SetMenuItemInfo() for each item with something like this:</p>\n\n<pre><code>MENUITEMINFO mii;\nmii.cbSize = sizeof mii;\nmii.fMask = MIIM_BITMAP;\nmii.hbmpItem = bitmapHandle;\nmenu.SetMenuItemInfo(menuItem,&mii,TRUE);\n</code></pre>\n\n<p>A further complication with doing this is that this is okay for 256 colour bitmaps, but not full colour 32bit RGBA bitmaps - these will work, but only on Vista, and then only if you present the bitmap as pre-computed RGBA.</p>\n\n<p>In practice, in my code I get round this by using another feature of menu icons, which is to set the hbmpItem to HBMMENU_CALLBACK, which allows a callback to draw the bitmap: I do that for Windows XP and before. The code gets a bit too complicated to post here. As an example, you could have a look at my code at</p>\n\n<p><a href=\"http://www.ifarchive.org/if-archive/infocom/interpreters/frotz/WindowsFrotzSrc.zip\" rel=\"nofollow noreferrer\">http://www.ifarchive.org/if-archive/infocom/interpreters/frotz/WindowsFrotzSrc.zip</a></p>\n\n<p>Look in \"MenuBar.h\" and \"MenuBar.cpp\", particularly the code around MenuBar::SetBitmaps().</p>\n"
},
{
"answer_id": 896676,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Good code. Please note that this shows the bitmap image but it is always good to remove the blank space left to the string (used for check/unchek) if you are showing the image.\nI did like this.</p>\n\n<pre><code> MENUINFO mi;\n mi.cbSize = sizeof(mi);\n mi.fMask = MIM_STYLE;\n mi.dwStyle = MNS_NOCHECK;\n pcSubMenu->SetMenuInfo(&mi);\n\n MENUITEMINFO mii;\n mii.cbSize = sizeof mii;\n mii.fMask = MIIM_BITMAP;\n\n mii.hbmpItem = (HBITMAP)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_16_HELP),IMAGE_BITMAP,0,0,LR_SHARED |LR_VGACOLOR |LR_LOADTRANSPARENT);\n pcSubMenu->SetMenuItemInfo(ID_CONTENTS,&mii,FALSE);\n</code></pre>\n"
},
{
"answer_id": 1045656,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think what you are looking for is very similar to what's described here...\nwww.codeguru.com/cpp/controls/menu/bitmappedmenus/article.php/c165/</p>\n\n<p>mixed with what's described in www.codeproject.com/KB/shell/DynIcon.aspx</p>\n\n<p>Still have to see if it will work.</p>\n\n<p>Tamer</p>\n"
},
{
"answer_id": 9594523,
"author": "Lothar",
"author_id": 155082,
"author_profile": "https://Stackoverflow.com/users/155082",
"pm_score": 0,
"selected": false,
"text": "<p>On Windows Vista/Windows7 you can not do that, it's either a 32 BGRA image or the menu is not drawn in the new UI style. There is no workaround, maybe ownerdrawing but i read the style API is not working correctly with menus, so i never tried to get deeper in it.</p>\n\n<p>You should use 32bit BGRA Icons anyway.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582/"
] |
I can use an bitmap in a menu
```
CMenu men;
CBitmap b;
b.LoadBitmap(IDB_0);
men.AppendMenu( MF_ENABLED,1,&b);
```
I can draw an icon into a DC
```
CImageList IL;
IL.Create(70, 14, ILC_COLOR16 | ILC_MASK, 1, 0);
IL.Add(AfxGetApp()->LoadIcon(IDI_0));
IL.Draw ( pDC, 0, rcIcon.TopLeft(), ILD_BLEND50 );
```
But I cannot find a simple way to show an icon in a menu. I would like to do this
```
CMenu men;
CBitmap b;
// here the miracle happens, load the icon into the bitmap
men.AppendMenu( MF_ENABLED,1,&b);
```
Seems like this should be possible.
---
This is the same question as [this](https://stackoverflow.com/questions/70386/icons-on-menus-of-mfc-feature-pack-classes). However that question referred to the MFC feature pack, did not get answered, and has shown no activity for a month, so I thought it would be worthwhile to ask it again in reference to basic MFC.
|
I asked the question you reference.
The way to add (normal, 16-bit color) icons to menus is to make a toolbar with the same resource id as the menu you want to have icons in. You then assign id's to each of the toolbar buttons, the same id's as the menu entries. Make a wizard-generated new MFC application and you'll see how it works there.
The answers to the question I posted suggested that it should work the same for 32-bit images with transparency for the Feature Pack toolbars; I haven't gotten around to test it out though.
If your specific problem is how to make dynamically-generated menus, I think you should pass the id of an existing entry in a toolbar and then that image will be used.
Not a real answer to your question but maybe it'll point you in the right direction.
|
268,501 |
<p>On a Windows 2003 server I have a pure .NET 3.5 <code>C#</code> app (no unmanaged code). It connects to various other remote systems via sockets and acts like a data hub. It runs for 10-15 hours fine with no problem but from time to time it just disappears. If I watch the app using task manager the memory usage remains constant.</p>
<p>In the <code>Main()</code> function I wrap the invocation of the rest of the app in a <code>try .. catch</code> block which it just blows completely past - the catch block which logs the exception to a file is ignored. If I manually raise an exception for testing, the catch block is invoked.</p>
<p>Prior to entering the <code>try .. catch</code> I do :</p>
<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
</code></pre>
<p>The system has Dr. Watson on it, but nothing gets written in the directory <code>DRWTSN32.EXE</code> is pointing to.</p>
<p>How can I catch whatever exception is causing this?</p>
|
[
{
"answer_id": 268511,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "<p>If it's a Windows Forms application, you could try <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx\" rel=\"nofollow noreferrer\"><code>Application.ThreadException</code></a>.</p>\n"
},
{
"answer_id": 268524,
"author": "Joel Cunningham",
"author_id": 5360,
"author_profile": "https://Stackoverflow.com/users/5360",
"pm_score": 3,
"selected": false,
"text": "<p>Try using the debugging tools from microsoft. You can download them from <a href=\"http://www.microsoft.com/whdc/devtools/debugging/default.mspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Use adplus to capture the crash and then windbg to analyze it.</p>\n\n<p>adplus -crash -pn your.exe -quiet</p>\n\n<p>Lots of great info about debugging on windows on this <a href=\"http://blogs.msdn.com/tess/\" rel=\"noreferrer\">blog</a>.</p>\n"
},
{
"answer_id": 268616,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 2,
"selected": false,
"text": "<p>If this is a Windows Forms app, then it's likely that the unhandled exception is being caught by the window message pump, which is why you never see it. To deal with this, see <a href=\"https://stackoverflow.com/questions/233255/how-does-setunhandledexceptionfilter-work-in-net-winforms-applications#238357\">my answer here</a>.</p>\n\n<p>If it's a Windows service, then the exception might be appearing on a background thread and not being marshalled back to your main thread. To deal with this, you need to marshal any background thread back to your main thread, and the exception will be re-thrown there so that you can catch it. </p>\n\n<p>If it's a console app, then I'm a bit mystified.</p>\n\n<p><strong>EDIT</strong>: Your comment says this is a Windows Forms app. In that case, you're probably not seeing the exception because it's being handled by the built-in Windows Forms exception handler that does the following by default:</p>\n\n<ul>\n<li>Catches an unhandled managed exception when:\n\n<ul>\n<li>no debugger attached, and</li>\n<li>exception occurs during window message processing, and</li>\n<li>jitDebugging = false in App.Config.</li>\n</ul></li>\n<li>Shows dialog to user and prevents app termination.</li>\n</ul>\n\n<p>You can disable this behaviour by setting jitDebugging = true in App.Config. Then you should be able to see the unhandled exception by registering for the event Application.ThreadException, e.g. in C#:</p>\n\n<pre><code>Application.ThreadException += new Threading.ThreadExceptionHandler(CatchExceptions);\n</code></pre>\n"
},
{
"answer_id": 269387,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 1,
"selected": false,
"text": "<p>You could also <a href=\"http://www.cornetdesign.com/2008/06/debugging-net-windows-service-that-is.html\" rel=\"nofollow noreferrer\">attach WinDBG at startup</a> and enable breakpoints on .NET exceptions. You can then do a <code>!printexception</code> to see what is going on.</p>\n"
},
{
"answer_id": 271812,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 1,
"selected": false,
"text": "<p>There might be trace of the application in the EventLog.</p>\n\n<p>I have had a .Net app disappear without the possibility to catch an Exception. There was an entry in the EventLog every time this happened.</p>\n\n<p>To view the eventlog just type EventVwr on the command prompt, or run box.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35055/"
] |
On a Windows 2003 server I have a pure .NET 3.5 `C#` app (no unmanaged code). It connects to various other remote systems via sockets and acts like a data hub. It runs for 10-15 hours fine with no problem but from time to time it just disappears. If I watch the app using task manager the memory usage remains constant.
In the `Main()` function I wrap the invocation of the rest of the app in a `try .. catch` block which it just blows completely past - the catch block which logs the exception to a file is ignored. If I manually raise an exception for testing, the catch block is invoked.
Prior to entering the `try .. catch` I do :
```
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
```
The system has Dr. Watson on it, but nothing gets written in the directory `DRWTSN32.EXE` is pointing to.
How can I catch whatever exception is causing this?
|
Try using the debugging tools from microsoft. You can download them from [here](http://www.microsoft.com/whdc/devtools/debugging/default.mspx).
Use adplus to capture the crash and then windbg to analyze it.
adplus -crash -pn your.exe -quiet
Lots of great info about debugging on windows on this [blog](http://blogs.msdn.com/tess/).
|
268,526 |
<p>A site I am working on that is built using PHP is sometimes showing a completely blank page.
There are no error messages on the client or on the server.
The same page may display sometimes but not others.
All pages are working fine in IE7, Firefox 3, Safari and Opera.
All pages are XHTML with this meta element:</p>
<pre><code><meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
</code></pre>
<p>It <em>appears</em> that I have fixed the problem by adding this PHP code:</p>
<pre><code>header('Content-type: text/html; charset=utf-8');
</code></pre>
<p>I have read that this problem may be caused by XHTML, encoding, gzip compression, or caching, but nobody has been able to backup these guesses.</p>
<p>As the problem was intermittent I am not confident that my solution has actually solved the problem.</p>
<p>My question is, are there <em>reproducible</em> ways of having IE6 show a blank page when other browsers display content?
If so, what causes it and what solves it?</p>
|
[
{
"answer_id": 268571,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this exactly matches your experience. It depends on which specific version of IE (including service packs) is being used.</p>\n\n<p>A known rendering issue with IE6 SP2 & IE7 (both use the same rendering engine) is the existence of orphaned tags in your HTML. This may be an orphaned div or script tag.</p>\n\n<pre><code><script language=\"javascript\"> // no closing tag\nalert('hello world');\n<body>\nhello world\n</body>\n</code></pre>\n\n<p>The above renders just fine in IE6 SP1 and Firefox, but you will only see a blank page in IE6 SP2 & IE7.</p>\n\n<p>There are certain other tags that must have a separate closing tag. Check that any <code><div></code> and <code><script></code> tags have an ending <code></script></code> or <code><div></code> tag, not just a closing slash at the end of the opening tag. Another one is <code><textarea></code>. You have to have both tags. </p>\n\n<p><strong>You can test if this is occurring with your site if you can View Source of your blank page and get the source html even though your page is blank.</strong></p>\n"
},
{
"answer_id": 268577,
"author": "eddy147",
"author_id": 30759,
"author_profile": "https://Stackoverflow.com/users/30759",
"pm_score": 3,
"selected": true,
"text": "<p>This is a content-type problem from IE.\nIt does not know how to handle application/xhtml+xml.</p>\n\n<p>Although you write xhtml+xml, IE only knows text+html.\nIt will be the future before all agents know xhtml+xml</p>\n\n<p>change your meta tag with content type to content=\"text/html;</p>\n"
},
{
"answer_id": 268683,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like <a href=\"http://webbugtrack.blogspot.com/2007/08/bug-153-self-closing-script-tag-issues.html\" rel=\"nofollow noreferrer\">bug #153 \"Self Closing Script Tag\"</a> bug in IE, <strong>which is well known to cause blank pages</strong>.</p>\n\n<p>Due to IE's bug, you can <strong>NEVER</strong> code the following and expect it to work in IE.</p>\n\n<pre><code><script src=\"....\" />\n</code></pre>\n\n<p>(if the tag is self closing, you are in for a world of pain)</p>\n\n<p>Instead, always code as;</p>\n\n<pre><code><script src=\"....\"></script>\n</code></pre>\n"
},
{
"answer_id": 273922,
"author": "Mauricio",
"author_id": 33913,
"author_profile": "https://Stackoverflow.com/users/33913",
"pm_score": 0,
"selected": false,
"text": "<p>You should serve pages with the Content-Type header as text/html to IE users. You don't need to change the meta tag, just leave it as application/xhtml+xml (IE will ignore it).</p>\n"
},
{
"answer_id": 1530678,
"author": "Greg Lane",
"author_id": 185517,
"author_profile": "https://Stackoverflow.com/users/185517",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem that was language specific - only the page with multibyte characters didn't show in IE6 and IE7. Turns out in these two browsers, the order of the Content-Type meta tag and the title tag is a big deal. So putting the tag (which contained Japanese characters) after the meta tag fixed the problem.</p>\n"
},
{
"answer_id": 1729360,
"author": "Baha14",
"author_id": 210479,
"author_profile": "https://Stackoverflow.com/users/210479",
"pm_score": 0,
"selected": false,
"text": "<p>I got this bug due to a typing error.</p>\n\n<p>I wrote the meta tag :</p>\n\n<pre><code><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-15\" />\n</code></pre>\n\n<p>Thanks to you i corrected it to :</p>\n\n<pre><code><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n</code></pre>\n\n<p>and i haven't the problem now.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18333/"
] |
A site I am working on that is built using PHP is sometimes showing a completely blank page.
There are no error messages on the client or on the server.
The same page may display sometimes but not others.
All pages are working fine in IE7, Firefox 3, Safari and Opera.
All pages are XHTML with this meta element:
```
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
```
It *appears* that I have fixed the problem by adding this PHP code:
```
header('Content-type: text/html; charset=utf-8');
```
I have read that this problem may be caused by XHTML, encoding, gzip compression, or caching, but nobody has been able to backup these guesses.
As the problem was intermittent I am not confident that my solution has actually solved the problem.
My question is, are there *reproducible* ways of having IE6 show a blank page when other browsers display content?
If so, what causes it and what solves it?
|
This is a content-type problem from IE.
It does not know how to handle application/xhtml+xml.
Although you write xhtml+xml, IE only knows text+html.
It will be the future before all agents know xhtml+xml
change your meta tag with content type to content="text/html;
|
268,543 |
<p>I have an application with a main form. In this form I have placed three TActionMainMenuBars, because the application essentially runs in three different modes. </p>
<p>The menu bars are all constructed from actions stored(proxied) in an TActionManager on the main form. The ActionManager actually references actionlists on various other forms. </p>
<p>The menu bars are then shown+enabled and hidden+disabled such that only one is visible at a time. This works well, with the actions operating if clicked on or if navigated through using ALT and then the arrow keys or the character underlined in their caption. </p>
<p>The problem is however that the actions do not seem to respond to any shortcut key presses.</p>
<p>Does anyone know what could be causing the actions not to fire?</p>
<p>I will happily provide more information if needed, I am programming in C++Builder 2007 RAD Studio in WinXP SP3.</p>
<p>Thanks to anyone who reads this, or even reads this and comes up with a solution!</p>
<p>PeterMJ</p>
<p><strong>Update:</strong> I failed to stated that the shortcuts in the different menus overlap in that the same shortcuts are used in the different menus for different actions, but all shortcuts are unique in there own menu.</p>
<p>I have also since simplified the problem in a test application, with two TActionMainMenuBars, and all actions shared a single action manager. In this case I have two actions with the same shortcut. They are placed on different menus. Then one menu is enabled at a time. In this case the shortcuts do work, BUT when using the common shortcut only the action in the first menu is fired, <em>even</em> when the holding menu is disabled. </p>
<p>This is slightly better than my actual problem in that some actions do fire, but highlights that the actions are not being triggered correctly. Does anyone no of a solution?</p>
|
[
{
"answer_id": 270547,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 0,
"selected": false,
"text": "<p>Be sure that the actions you want to use are actually enabled.<br>\nIf you disable every action within an ActionMainMenuBar when you disable the bar, then you have a problem.<br>\nBe sure also to use available shortcuts, not conflicting with Windows global shortcuts.<br>\nOther than that I don't see why it wouldn't work. I tried with 2 ActionMainMenuBars in Delphi and the shortcuts worked.</p>\n"
},
{
"answer_id": 821813,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 2,
"selected": false,
"text": "<p>Enabling/disabling or showing/hiding of a ActioneMenuBar has no consequences for the actions on the menu bar. If you want to make some actions not available in a certain context/situation, you need to implement the \"OnUpdate\" event of either the action itself or the action list or action manager it is part of.</p>\n\n<p>For example, using the following OnUpdate event of your action manager, you can use a TCheckBox to decide which of two actions is currently activated. </p>\n\n<pre><code> if CheckBox1.Checked then\n begin\n Action1.Enabled:= False;\n Action2.Enabled:= True;\n end\n else\n begin\n Action1.Enabled:= True;\n Action2.Enabled:= False;\n end;\n</code></pre>\n\n<p>Imagine, both actions have the shortcut \"Ctrl+A\" assigned, this will mean that pressing Ctrl+A will only activate Action1 when CheckBox1 is not checked.</p>\n\n<p>However, there is still a problem. The VCL will stop looking for actions with a certain shortcut once it has found an action with the shortcut in an action manager or action list in the current form, even when the found action is not enabled.</p>\n\n<p>To solve this problem, you can use the OnUpdate event to dynamically set and reset the ShortCut property of actions like this:</p>\n\n<pre><code> if CheckBox1.Checked then\n begin\n Action1.Enabled:= False;\n Action1.ShortCut:= scNone;\n\n Action2.Enabled:= True;\n Action2.ShortCut:= ShortCut(ord('A'), [ssCtrl]);\n end\n else\n begin\n Action2.Enabled:= False;\n Action2.ShortCut:= scNone;\n\n Action1.Enabled:= True;\n Action1.ShortCut:= ShortCut(ord('A'), [ssCtrl]);\n end;\n</code></pre>\n\n<p>Using this code, pressing Ctrl+A will activate Action2, if CheckBox1 is checked and will activate Action1, if CheckBox1 is not checked.\nYou don't need to explicitly call the OnUpdate event of an action list or action manager. The event is fired regularly when the application is idle and waiting for user input.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an application with a main form. In this form I have placed three TActionMainMenuBars, because the application essentially runs in three different modes.
The menu bars are all constructed from actions stored(proxied) in an TActionManager on the main form. The ActionManager actually references actionlists on various other forms.
The menu bars are then shown+enabled and hidden+disabled such that only one is visible at a time. This works well, with the actions operating if clicked on or if navigated through using ALT and then the arrow keys or the character underlined in their caption.
The problem is however that the actions do not seem to respond to any shortcut key presses.
Does anyone know what could be causing the actions not to fire?
I will happily provide more information if needed, I am programming in C++Builder 2007 RAD Studio in WinXP SP3.
Thanks to anyone who reads this, or even reads this and comes up with a solution!
PeterMJ
**Update:** I failed to stated that the shortcuts in the different menus overlap in that the same shortcuts are used in the different menus for different actions, but all shortcuts are unique in there own menu.
I have also since simplified the problem in a test application, with two TActionMainMenuBars, and all actions shared a single action manager. In this case I have two actions with the same shortcut. They are placed on different menus. Then one menu is enabled at a time. In this case the shortcuts do work, BUT when using the common shortcut only the action in the first menu is fired, *even* when the holding menu is disabled.
This is slightly better than my actual problem in that some actions do fire, but highlights that the actions are not being triggered correctly. Does anyone no of a solution?
|
Enabling/disabling or showing/hiding of a ActioneMenuBar has no consequences for the actions on the menu bar. If you want to make some actions not available in a certain context/situation, you need to implement the "OnUpdate" event of either the action itself or the action list or action manager it is part of.
For example, using the following OnUpdate event of your action manager, you can use a TCheckBox to decide which of two actions is currently activated.
```
if CheckBox1.Checked then
begin
Action1.Enabled:= False;
Action2.Enabled:= True;
end
else
begin
Action1.Enabled:= True;
Action2.Enabled:= False;
end;
```
Imagine, both actions have the shortcut "Ctrl+A" assigned, this will mean that pressing Ctrl+A will only activate Action1 when CheckBox1 is not checked.
However, there is still a problem. The VCL will stop looking for actions with a certain shortcut once it has found an action with the shortcut in an action manager or action list in the current form, even when the found action is not enabled.
To solve this problem, you can use the OnUpdate event to dynamically set and reset the ShortCut property of actions like this:
```
if CheckBox1.Checked then
begin
Action1.Enabled:= False;
Action1.ShortCut:= scNone;
Action2.Enabled:= True;
Action2.ShortCut:= ShortCut(ord('A'), [ssCtrl]);
end
else
begin
Action2.Enabled:= False;
Action2.ShortCut:= scNone;
Action1.Enabled:= True;
Action1.ShortCut:= ShortCut(ord('A'), [ssCtrl]);
end;
```
Using this code, pressing Ctrl+A will activate Action2, if CheckBox1 is checked and will activate Action1, if CheckBox1 is not checked.
You don't need to explicitly call the OnUpdate event of an action list or action manager. The event is fired regularly when the application is idle and waiting for user input.
|
268,548 |
<p>I use CruiseControl.NET to automatically build my .NET 3.5 web applications, which works a treat. However, is there any way to automatically create a ZIP file of these builds, and put the ZIP's into a separate directory?</p>
<p>I have seen this is possible using NAnt but cannot find an example of how to get this working.</p>
<p>Can anyone offer help/examples?</p>
|
[
{
"answer_id": 268623,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using Nant, then doesn't the <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/zip.html\" rel=\"nofollow noreferrer\">Zip task</a> work for you?</p>\n"
},
{
"answer_id": 268635,
"author": "domruf",
"author_id": 7029,
"author_profile": "https://Stackoverflow.com/users/7029",
"pm_score": 0,
"selected": false,
"text": "<p>We are zipping the sources of a CruiseControl.NET project</p>\n\n<p>but we are using ant</p>\n\n<pre><code><target name=\"zipProject\">\n <mkdir dir=\"output\"/>\n <zip destfile=\"output\\sources.zip\" basedir=\"C:\\project\\src\" />\n</target>\n</code></pre>\n\n<p>i don't know about nant but i would expect it to be similar</p>\n"
},
{
"answer_id": 268925,
"author": "Alex York",
"author_id": 35064,
"author_profile": "https://Stackoverflow.com/users/35064",
"pm_score": 0,
"selected": false,
"text": "<p>@David: The NAnt Zip task is what I'm after, yes, but I'm asking how to integrate it as part of an automatic CruiseControl.NET build. If you take a look at the <a href=\"http://cruisecontrol.sourceforge.net/main/configxml.html#nant\" rel=\"nofollow noreferrer\" title=\"NAnt\">NAnt documentation for the cruise control config</a> it doesn't make it clear if I can run an NAnt task from inside the <code><tasks></code> XML node in my CruiseControl config - it only says that it can be part of a <code><schedule></code>.</p>\n\n<p>I have found a few examples of setting up your CruiseControl config and a few examples of NAnt tasks but nothing that integrates the two: specifically, zipping up a CruiseControl build.</p>\n\n<p>If anyone has some sample XML of their CruiseControl config, hooking up to an NAnt zip task, post samples here.</p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 877579,
"author": "foolshat",
"author_id": 108773,
"author_profile": "https://Stackoverflow.com/users/108773",
"pm_score": 2,
"selected": false,
"text": "<p>I've just added such a Nant task to our CC machine.</p>\n\n<p>See <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/zip.html\" rel=\"nofollow noreferrer\">http://nant.sourceforge.net/release/latest/help/tasks/zip.html</a></p>\n\n<p>Note when initially viewing the zip archive, it may appear as if all the files are at the same level, i.e no folders, but actually they folders are preserved.</p>\n\n<p>Notice how you can exclude file types or folders.</p>\n\n<p>You could take the approach of only including the file types you want and excluding the rest. </p>\n\n<p>First define properties for where the source files are allcode.dir and the name and location of the zip file sourcebackup.zip</p>\n\n<p>\n </p>\n\n<p>Now here is the nant task</p>\n\n<p>\n \n \n \n </p>\n\n<pre><code> <zip zipfile=\"${sourcebackup.zip}\" includeemptydirs=\"true\" verbose=\"true\"> \n <fileset basedir=\"${allcode.dir}\"> \n <include name=\"**/*\" /> \n <exclude name=\"**/_resharper*/**\" /> \n <exclude name=\"**/build/**\" /> \n <exclude name=\"**/obj/**\" /> \n <exclude name=\"**/bin/**\" /> \n <exclude name=\"**/*.dll\" /> \n <exclude name=\"**/*.scc\" /> \n <exclude name=\"**/*.log\" /> \n <exclude name=\"**/*.vssscc\" /> \n <exclude name=\"**/*.suo\" /> \n <exclude name=\"**/*.user\" /> \n <exclude name=\"**/*.pdb\" /> \n <exclude name=\"**/*.cache\" /> \n <exclude name=\"**/*.vspscc\" /> \n <exclude name=\"**/*.msi\" /> \n <exclude name=\"**/*.irs\" /> \n <exclude name=\"**/*.exe\" /> \n </fileset> \n</code></pre>\n\n<p> </p>\n\n<pre><code><echo message=\"########## Zipped##########\" />\n</code></pre>\n\n<p></p>\n\n<p>Call this from your cc build like any other nant task.\nWe find it best if each CC project calls a single task if possible, then you only have to change the nant script, and you can run the nant script on your local machine.</p>\n\n<p>Eg in the project block, we have the single target \"build\", which as part of its work calls ZipSource</p>\n\n<pre><code><targetList>\n <target>Build</target>\n </targetList>\n</code></pre>\n\n<p>We use the above for a BizTalk project.</p>\n\n<p>Enjoy.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35064/"
] |
I use CruiseControl.NET to automatically build my .NET 3.5 web applications, which works a treat. However, is there any way to automatically create a ZIP file of these builds, and put the ZIP's into a separate directory?
I have seen this is possible using NAnt but cannot find an example of how to get this working.
Can anyone offer help/examples?
|
I've just added such a Nant task to our CC machine.
See <http://nant.sourceforge.net/release/latest/help/tasks/zip.html>
Note when initially viewing the zip archive, it may appear as if all the files are at the same level, i.e no folders, but actually they folders are preserved.
Notice how you can exclude file types or folders.
You could take the approach of only including the file types you want and excluding the rest.
First define properties for where the source files are allcode.dir and the name and location of the zip file sourcebackup.zip
Now here is the nant task
```
<zip zipfile="${sourcebackup.zip}" includeemptydirs="true" verbose="true">
<fileset basedir="${allcode.dir}">
<include name="**/*" />
<exclude name="**/_resharper*/**" />
<exclude name="**/build/**" />
<exclude name="**/obj/**" />
<exclude name="**/bin/**" />
<exclude name="**/*.dll" />
<exclude name="**/*.scc" />
<exclude name="**/*.log" />
<exclude name="**/*.vssscc" />
<exclude name="**/*.suo" />
<exclude name="**/*.user" />
<exclude name="**/*.pdb" />
<exclude name="**/*.cache" />
<exclude name="**/*.vspscc" />
<exclude name="**/*.msi" />
<exclude name="**/*.irs" />
<exclude name="**/*.exe" />
</fileset>
```
```
<echo message="########## Zipped##########" />
```
Call this from your cc build like any other nant task.
We find it best if each CC project calls a single task if possible, then you only have to change the nant script, and you can run the nant script on your local machine.
Eg in the project block, we have the single target "build", which as part of its work calls ZipSource
```
<targetList>
<target>Build</target>
</targetList>
```
We use the above for a BizTalk project.
Enjoy.
|
268,574 |
<p>What good ruby gem sources would you recommend, besides <a href="http://gems.rubyforge.org/" rel="noreferrer">http://gems.rubyforge.org/</a> and <a href="http://gems.github.com/" rel="noreferrer">http://gems.github.com/</a>? It seems that RubyForge is missing most of the gems I look for these days...</p>
|
[
{
"answer_id": 268764,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 4,
"selected": false,
"text": "<p>As far as I know, those two are it, with the primary being rubyforge, since that's the only source that a stock RubyGems install will search? As popular as github is getting, gem developers still can't yet assume that github has been added as a gem source, and usually provide specific instructions like</p>\n\n<pre><code>gem sources -a http://gems.github.com\ngem install person-gemname\n</code></pre>\n\n<p>or</p>\n\n<pre><code>gem install person-gemname --source http://gems.github.com\n</code></pre>\n\n<p><strong>UPDATE</strong>: gems.rubyforge.org, gems.github.com, and gemcutter.org have all been replaced by <code>rubygems.org</code></p>\n"
},
{
"answer_id": 275585,
"author": "danmayer",
"author_id": 27738,
"author_profile": "https://Stackoverflow.com/users/27738",
"pm_score": 2,
"selected": false,
"text": "<p>Basically I agree that even if you are hosting projects on github or elsewhere all stable releases should be on RubyForge. The main reason is all the dependancies on gems, and it makes me happy when they are all in one place.</p>\n\n<p>Magnus Holm wrote about this \n<a href=\"http://judofyr.net/posts/dont-forget-about-rubyforge.html\" rel=\"nofollow noreferrer\">http://judofyr.net/posts/dont-forget-about-rubyforge.html</a></p>\n\n<p>and it was picked up by others as well\n<a href=\"http://www.infoq.com/news/2008/08/gems-from-rubyforge-and-github\" rel=\"nofollow noreferrer\">http://www.infoq.com/news/2008/08/gems-from-rubyforge-and-github</a></p>\n"
},
{
"answer_id": 975089,
"author": "Kris",
"author_id": 22237,
"author_profile": "https://Stackoverflow.com/users/22237",
"pm_score": 1,
"selected": false,
"text": "<p>It would be good to add a RubyForge mirror - however I cannot find one that is up and RubyForge now (10-june-09) is down...</p>\n"
},
{
"answer_id": 3651224,
"author": "Željko Filipin",
"author_id": 17469,
"author_profile": "https://Stackoverflow.com/users/17469",
"pm_score": 5,
"selected": false,
"text": "<p>This is now the official RubyGems source:</p>\n\n<pre><code>https://rubygems.org/\n</code></pre>\n"
},
{
"answer_id": 9378895,
"author": "Tyler Liu",
"author_id": 862862,
"author_profile": "https://Stackoverflow.com/users/862862",
"pm_score": 4,
"selected": false,
"text": "<p>Here is one from China: <a href=\"http://ruby.taobao.org/\" rel=\"nofollow noreferrer\">http://ruby.taobao.org/</a></p>\n\n<p>We Chinese users love it because it is much faster than the default two (access from China).</p>\n\n<p><strong>Update (2015-09-24):</strong></p>\n\n<p>https is required now, please use <a href=\"https://ruby.taobao.org/\" rel=\"nofollow noreferrer\">https://ruby.taobao.org/</a></p>\n"
},
{
"answer_id": 27184010,
"author": "Larry",
"author_id": 895007,
"author_profile": "https://Stackoverflow.com/users/895007",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative in Africa (South Africa in particular):</p>\n\n<p><a href=\"http://gems.cloudafrica.net/\" rel=\"nofollow\">http://gems.cloudafrica.net/</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7202/"
] |
What good ruby gem sources would you recommend, besides <http://gems.rubyforge.org/> and <http://gems.github.com/>? It seems that RubyForge is missing most of the gems I look for these days...
|
This is now the official RubyGems source:
```
https://rubygems.org/
```
|
268,587 |
<pre><code>
class C {
T a;
public:
C(T a): a(a) {;}
};
</code></pre>
<p>Is it legal?</p>
|
[
{
"answer_id": 268591,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "<p>Yes it is legal and works on all platforms. \nIt will correctly initialize your member variable a, to the passed in value a. </p>\n\n<p>It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :)</p>\n\n<p>Initialization lists with the same variable name works because the syntax of an initialization item in an initialization list is as follows:</p>\n\n<p><member>(<value>)</p>\n\n<p>You can verify what I wrote above by creating a simple program that does this: (It will not compile)</p>\n\n<pre><code>class A\n{\n\n A(int a)\n : a(5)//<--- try to initialize a non member variable to 5\n {\n }\n};\n</code></pre>\n\n<p>You will get a compiling error something like: A does not have a field named 'a'.</p>\n\n<hr>\n\n<p>On a side note:</p>\n\n<p>One reason why you <strong>may not want</strong> to use the same member name as parameter name is that you would be more prone to the following:</p>\n\n<pre><code>class A\n{\n\n A(int myVarriable)\n : myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly\n {\n }\n int myVariable;\n};\n</code></pre>\n\n<hr>\n\n<p>On a side note(2):</p>\n\n<p>One reason why you <strong>may want</strong> to use the same member name as parameter name is that you would be less prone to the following:</p>\n\n<pre><code>class A\n{\n\n A(int myVariable_)\n {\n //<-- do something with _myVariable, oops _myVariable wasn't initialized yet\n ...\n _myVariable = myVariable_;\n }\n int _myVariable;\n};\n</code></pre>\n\n<p>This could also happen with large initialization lists and you use _myVariable before initializing it in the initialization list. </p>\n"
},
{
"answer_id": 268646,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 2,
"selected": false,
"text": "<p>Legal: yes, as explained by Brian, compiler knows the name to expect in the initializer list must be a member (or a base class), not anything else.</p>\n\n<p>Good style: most likely not - for a lot of programmers (including you, it seems) the result is not obvious. Using a different name for the parameter will keep the code legal and make it a good style at the same time.</p>\n\n<p>I would prefer writing some of:</p>\n\n<pre><code>class C {\n T a_;\npublic:\n C(T a): a_(a) {}\n};\n\n\nclass C {\n T a;\n public:\n C(T value): a(value) {}\n};\n</code></pre>\n"
},
{
"answer_id": 272167,
"author": "yesraaj",
"author_id": 22076,
"author_profile": "https://Stackoverflow.com/users/22076",
"pm_score": 3,
"selected": false,
"text": "<p>if the formal parameter and the member is named same then beware of using this pointer inside constructor to use the member variable</p>\n\n<pre><code>class C {\n T a;\npublic:\n C(T a): a(a) {\nthis->a.sort ;//correct\na.sort();//will not affect the actual member variable\n}\n};\n</code></pre>\n"
},
{
"answer_id": 7740954,
"author": "Dragonion",
"author_id": 877194,
"author_profile": "https://Stackoverflow.com/users/877194",
"pm_score": 5,
"selected": false,
"text": "<p>One of the things that may lead to confusion regarding this topic is how variables are prioritized by the compiler. For example, if one of the constructor arguments has the same name as a class member you could write the following in the initialization list:</p>\n\n<pre><code>MyClass(int a) : a(a)\n{\n}\n</code></pre>\n\n<p>But does the above code have the same effect as this?</p>\n\n<pre><code>MyClass(int a)\n{\n a=a;\n}\n</code></pre>\n\n<p>The answer is no. Whenever you type \"a\" inside the body of the constructor the compiler will first look for a local variable or constructor argument called \"a\", and only if it doesn't find one will it start looking for a class member called \"a\" (and if none is available it will then look for a global variable called \"a\", by the way). The result is that the above statment \"a=a\" will assign the value stored in argument \"a\" to argument \"a\" rendering it a useless statement.</p>\n\n<p>In order to assign the value of the argument to the class member \"a\" you need to inform the compiler that you are referencing a value inside <strong>this</strong> class instance:</p>\n\n<pre><code>MyClass(int a)\n{\n this->a=a;\n}\n</code></pre>\n\n<p>Fine, but what if you did something like this (notice that there isn't an argument called \"a\"):</p>\n\n<pre><code>MyClass() : a(a)\n{\n}\n</code></pre>\n\n<p>Well, in that case the compiler would first look for an argument called \"a\" and when it discovered that there wasn't any it would assign the value of class member \"a\" to class member \"a\", which effectively would do nothing.</p>\n\n<p>Lastly you should know that you can only assign values to class members in the initialization list so the following will produce an error:</p>\n\n<pre><code>MyClass(int x) : x(100) // error: the class doesn't have a member called \"x\"\n{\n}\n</code></pre>\n"
},
{
"answer_id": 22492390,
"author": "Rick",
"author_id": 251914,
"author_profile": "https://Stackoverflow.com/users/251914",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with this practice, legal though it may be, is that compilers will consider the variables shadowed when -Wshadow is used, and it will obfuscate those warnings in other code.</p>\n\n<p>Moreover, in a non-trivial constructor, you make make a mistake, forgetting to put this-> in front of the member name.</p>\n\n<p>Java doesn't even allow this. It's bad practice, and should be avoided.</p>\n"
},
{
"answer_id": 68510992,
"author": "Soumadip Dey",
"author_id": 10439615,
"author_profile": "https://Stackoverflow.com/users/10439615",
"pm_score": 2,
"selected": false,
"text": "<p>Hey guys this is a great question. If you want to identical names for fields and constructor parameters / methods parameter you have to use scope resolution ( <code>::</code> ) operator or you can use this ( <code>this-></code> ) to map the parameter value with member like this please check the code snippet carefully you can understand easyly.</p>\n<pre><code>class Student{\n private :\n string name;\n int rollNumber;\n\n public:\n Student()\n {\n // default constructor\n }\n\n // parameterized constructor\n Student(string name, int rollNumber)\n {\n this->name = name;\n Student::rollNumber = rollNumber;\n }\n\n void display()\n {\n cout<<"Name: "<<name <<endl;\n cout<<"Roll Number: "<<rollNumber<<endl;\n }\n\n void setName(string name)\n {\n this->name = name;\n }\n\n void setrollNumber(int rollNumber)\n {\n Student::rollNumber = rollNumber;\n }\n\n};\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12151/"
] |
```
class C {
T a;
public:
C(T a): a(a) {;}
};
```
Is it legal?
|
Yes it is legal and works on all platforms.
It will correctly initialize your member variable a, to the passed in value a.
It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :)
Initialization lists with the same variable name works because the syntax of an initialization item in an initialization list is as follows:
<member>(<value>)
You can verify what I wrote above by creating a simple program that does this: (It will not compile)
```
class A
{
A(int a)
: a(5)//<--- try to initialize a non member variable to 5
{
}
};
```
You will get a compiling error something like: A does not have a field named 'a'.
---
On a side note:
One reason why you **may not want** to use the same member name as parameter name is that you would be more prone to the following:
```
class A
{
A(int myVarriable)
: myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly
{
}
int myVariable;
};
```
---
On a side note(2):
One reason why you **may want** to use the same member name as parameter name is that you would be less prone to the following:
```
class A
{
A(int myVariable_)
{
//<-- do something with _myVariable, oops _myVariable wasn't initialized yet
...
_myVariable = myVariable_;
}
int _myVariable;
};
```
This could also happen with large initialization lists and you use \_myVariable before initializing it in the initialization list.
|
268,595 |
<p>I am trying to put version information to my C# GUI framework retrieved from the latest ClearCase label. This was originally done from Visual Soursafe as below. </p>
<pre><code>vssDB = new VSSDatabaseClass();
vssDB.Open( databaseName, "vssadmin", "vssadmin" );
VSSItem item = vssDB.get_VSSItem( @"$\BuildDCP.bat", false );
foreach(VSSVersion vssVersion in item.get_Versions(0))
{
// Pull the first non-blank label and use that
if ( vssVersion.Label != "" )
{
labelID = vssVersion.Label.ToString();
break;
}
}
</code></pre>
<p>I am trying to do something similar using ClearCase since we changed our source code control from VSS to CC. Any help would be greatly appreciated.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 269607,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "<p>I really wish that the COM interfaces had better documentation, or were more obvious. Or that the code to ClearCase Explorer or Project Explorer were open source.</p>\n\n<p>I've done a few cool things, but I pretty much started by adding COM references to my C# project, and then started screwing around with the interfaces I found.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 269624,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": true,
"text": "<p>I believe this could be better achieved through a script, which would be called from your C# program.</p>\n\n<p>But you may be able to directly call some COM objects, through the <a href=\"http://www.ibm.com/developerworks/rational/library/06/0207_joshi/index.html\" rel=\"nofollow noreferrer\">CAL interface</a> provided with ClearCase.</p>\n\n<p>The documentation for the interface can be accessed through ClearCase help (Start>Programs>Rational ClearCase>ClearCase Help), where there's an entry for \"ClearCase Automation Library (CAL)\". An alternate path is to look in the ClearCase/bin directory for \"<strong>cc_cal.chm</strong>\".</p>\n\n<p>In VB, with CAL API, that would give something like:</p>\n\n<pre><code>Dim CC As New ClearCase.Application \nDim labelID As String\nSet aVersion = CC.Version(\"[Path-To]\\BuildDCP.bat\");\nSet someLabels = Ver.Labels;\nIf (someLabels.Count > 0) Then \n ' the first label listed is the most recently applied\n labelID = someLabels.Item(1).Type.Name\nEndIf\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to put version information to my C# GUI framework retrieved from the latest ClearCase label. This was originally done from Visual Soursafe as below.
```
vssDB = new VSSDatabaseClass();
vssDB.Open( databaseName, "vssadmin", "vssadmin" );
VSSItem item = vssDB.get_VSSItem( @"$\BuildDCP.bat", false );
foreach(VSSVersion vssVersion in item.get_Versions(0))
{
// Pull the first non-blank label and use that
if ( vssVersion.Label != "" )
{
labelID = vssVersion.Label.ToString();
break;
}
}
```
I am trying to do something similar using ClearCase since we changed our source code control from VSS to CC. Any help would be greatly appreciated.
Thanks!
|
I believe this could be better achieved through a script, which would be called from your C# program.
But you may be able to directly call some COM objects, through the [CAL interface](http://www.ibm.com/developerworks/rational/library/06/0207_joshi/index.html) provided with ClearCase.
The documentation for the interface can be accessed through ClearCase help (Start>Programs>Rational ClearCase>ClearCase Help), where there's an entry for "ClearCase Automation Library (CAL)". An alternate path is to look in the ClearCase/bin directory for "**cc\_cal.chm**".
In VB, with CAL API, that would give something like:
```
Dim CC As New ClearCase.Application
Dim labelID As String
Set aVersion = CC.Version("[Path-To]\BuildDCP.bat");
Set someLabels = Ver.Labels;
If (someLabels.Count > 0) Then
' the first label listed is the most recently applied
labelID = someLabels.Item(1).Type.Name
EndIf
```
|
268,604 |
<p>This code:</p>
<pre><code>#include <iostream>
int main( int, char **argv )
{
std::cout << 1.23e45 << std::endl;
}
</code></pre>
<p>prints </p>
<blockquote>
<p>1.23e+045</p>
</blockquote>
<p>when compiled with MS Visual Studio 2003, and</p>
<blockquote>
<p>1.23e+45</p>
</blockquote>
<p>on my Linux machine. </p>
<p>How can I specify the width of the exponent field (and why is there a difference in the first place)?</p>
|
[
{
"answer_id": 268650,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": -1,
"selected": false,
"text": "<p>Look into the iomanip header. It has a lot of width-precision etc... functionality.</p>\n"
},
{
"answer_id": 268693,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 2,
"selected": true,
"text": "<p>I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how)</p>\n\n<p>Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream.</p>\n\n<p>Seems a lot of work, and while not rocket science, no trivial task either.</p>\n\n<p>On the 'why' question: I know linux defines the exponent as minimum two digits, I suppose Windows specifies it as minimum three?</p>\n\n<pre><code>// on linux\nstd::cout << std::scientific << 1.23e4 << std::endl\n</code></pre>\n\n<p>Also adds a leading zero:</p>\n\n<pre><code>1.230000e+04\n</code></pre>\n"
},
{
"answer_id": 268947,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "<p>As a follow-up of @Pieter's answer, I've been looking inside the operator<< (ostream&, double). Indeed, there is no field to specify the significance or width of the exponent. On windows, the operator<< forwards to sprintf, which has no exponent-size either.</p>\n\n<p>In it's turn, the sprintf function (on Windows) calls into _cfltcvt_l, a function we have no source code for, but whose signature doesn't provide for an exponent-precision.</p>\n\n<p>I know nothing of the implementation on Linux.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
] |
This code:
```
#include <iostream>
int main( int, char **argv )
{
std::cout << 1.23e45 << std::endl;
}
```
prints
>
> 1.23e+045
>
>
>
when compiled with MS Visual Studio 2003, and
>
> 1.23e+45
>
>
>
on my Linux machine.
How can I specify the width of the exponent field (and why is there a difference in the first place)?
|
I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how)
Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream.
Seems a lot of work, and while not rocket science, no trivial task either.
On the 'why' question: I know linux defines the exponent as minimum two digits, I suppose Windows specifies it as minimum three?
```
// on linux
std::cout << std::scientific << 1.23e4 << std::endl
```
Also adds a leading zero:
```
1.230000e+04
```
|
268,629 |
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p>
<p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p>
<p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
|
[
{
"answer_id": 268660,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 6,
"selected": true,
"text": "<p>I should start by saying that \"I probably wouldn't do this myself, but I have in the past\". The serve_forever (from SocketServer.py) method looks like this:</p>\n\n<pre><code>def serve_forever(self):\n \"\"\"Handle one request at a time until doomsday.\"\"\"\n while 1:\n self.handle_request()\n</code></pre>\n\n<p>You could replace (in subclass) <code>while 1</code> with <code>while self.should_be_running</code>, and modify that value from a different thread. Something like:</p>\n\n<pre><code>def stop_serving_forever(self):\n \"\"\"Stop handling requests\"\"\"\n self.should_be_running = 0\n # Make a fake request to the server, to really force it to stop.\n # Otherwise it will just stop on the next request.\n # (Exercise for the reader.)\n self.make_a_fake_request_to_myself()\n</code></pre>\n\n<p>Edit: I dug up the actual code I used at the time:</p>\n\n<pre><code>class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):\n\n stopped = False\n allow_reuse_address = True\n\n def __init__(self, *args, **kw):\n SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)\n self.register_function(lambda: 'OK', 'ping')\n\n def serve_forever(self):\n while not self.stopped:\n self.handle_request()\n\n def force_stop(self):\n self.server_close()\n self.stopped = True\n self.create_dummy_request()\n\n def create_dummy_request(self):\n server = xmlrpclib.Server('http://%s:%s' % self.server_address)\n server.ping()\n</code></pre>\n"
},
{
"answer_id": 268686,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 5,
"selected": false,
"text": "<p>In my python 2.6 installation, I can call it on the underlying TCPServer - it still there inside your <code>HTTPServer</code>:</p>\n\n<pre><code>TCPServer.shutdown\n\n\n>>> import BaseHTTPServer\n>>> h=BaseHTTPServer.HTTPServer(('',5555), BaseHTTPServer.BaseHTTPRequestHandler)\n>>> h.shutdown\n<bound method HTTPServer.shutdown of <BaseHTTPServer.HTTPServer instance at 0x0100D800>>\n>>> \n</code></pre>\n"
},
{
"answer_id": 4020093,
"author": "wimerrill",
"author_id": 487114,
"author_profile": "https://Stackoverflow.com/users/487114",
"pm_score": 4,
"selected": false,
"text": "<p>I think you can use <code>[serverName].socket.close()</code></p>\n"
},
{
"answer_id": 19211760,
"author": "user2852263",
"author_id": 2852263,
"author_profile": "https://Stackoverflow.com/users/2852263",
"pm_score": 5,
"selected": false,
"text": "<p>Another way to do it, based on <a href=\"http://docs.python.org/2/library/basehttpserver.html#more-examples\">http://docs.python.org/2/library/basehttpserver.html#more-examples</a>, is: instead of serve_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each request. For example:</p>\n\n<pre><code>import CGIHTTPServer\nimport BaseHTTPServer\n\nKEEP_RUNNING = True\n\ndef keep_running():\n return KEEP_RUNNING\n\nclass Handler(CGIHTTPServer.CGIHTTPRequestHandler):\n cgi_directories = [\"/cgi-bin\"]\n\nhttpd = BaseHTTPServer.HTTPServer((\"\", 8000), Handler)\n\nwhile keep_running():\n httpd.handle_request()\n</code></pre>\n"
},
{
"answer_id": 22493362,
"author": "jsalter",
"author_id": 770829,
"author_profile": "https://Stackoverflow.com/users/770829",
"pm_score": 3,
"selected": false,
"text": "<p>In python 2.7, calling shutdown() works but only if you are serving via serve_forever, because it uses async select and a polling loop. Running your own loop with handle_request() ironically excludes this functionality because it implies a dumb blocking call.</p>\n\n<p>From SocketServer.py's BaseServer:</p>\n\n<pre><code>def serve_forever(self, poll_interval=0.5):\n \"\"\"Handle one request at a time until shutdown.\n\n Polls for shutdown every poll_interval seconds. Ignores\n self.timeout. If you need to do periodic tasks, do them in\n another thread.\n \"\"\"\n self.__is_shut_down.clear()\n try:\n while not self.__shutdown_request:\n # XXX: Consider using another file descriptor or\n # connecting to the socket to wake this up instead of\n # polling. Polling reduces our responsiveness to a\n # shutdown request and wastes cpu at all other times.\n r, w, e = select.select([self], [], [], poll_interval)\n if self in r:\n self._handle_request_noblock()\n finally:\n self.__shutdown_request = False\n self.__is_shut_down.set()\n</code></pre>\n\n<p>Heres part of my code for doing a blocking shutdown from another thread, using an event to wait for completion:</p>\n\n<pre><code>class MockWebServerFixture(object):\n def start_webserver(self):\n \"\"\"\n start the web server on a new thread\n \"\"\"\n self._webserver_died = threading.Event()\n self._webserver_thread = threading.Thread(\n target=self._run_webserver_thread)\n self._webserver_thread.start()\n\n def _run_webserver_thread(self):\n self.webserver.serve_forever()\n self._webserver_died.set()\n\n def _kill_webserver(self):\n if not self._webserver_thread:\n return\n\n self.webserver.shutdown()\n\n # wait for thread to die for a bit, then give up raising an exception.\n if not self._webserver_died.wait(5):\n raise ValueError(\"couldn't kill webserver\")\n</code></pre>\n"
},
{
"answer_id": 35358134,
"author": "serup",
"author_id": 3990012,
"author_profile": "https://Stackoverflow.com/users/3990012",
"pm_score": 1,
"selected": false,
"text": "<p>I tried all above possible solution and ended up with having a \"sometime\" issue - somehow it did not really do it - so I ended up making a dirty solution that worked all the time for me:</p>\n\n<p>If all above fails, then brute force kill your thread using something like this:</p>\n\n<pre><code>import subprocess\ncmdkill = \"kill $(ps aux|grep '<name of your thread> true'|grep -v 'grep'|awk '{print $2}') 2> /dev/null\"\nsubprocess.Popen(cmdkill, stdout=subprocess.PIPE, shell=True)\n</code></pre>\n"
},
{
"answer_id": 35576127,
"author": "Vianney Bajart",
"author_id": 5968045,
"author_profile": "https://Stackoverflow.com/users/5968045",
"pm_score": 5,
"selected": false,
"text": "<p>The event-loops ends on SIGTERM, <kbd>Ctrl</kbd>+<kbd>C</kbd> or when <code>shutdown()</code> is called.</p>\n\n<p><code>server_close()</code> must be called after <code>server_forever()</code> to close the listening socket.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import http.server\n\nclass StoppableHTTPServer(http.server.HTTPServer):\n def run(self):\n try:\n self.serve_forever()\n except KeyboardInterrupt:\n pass\n finally:\n # Clean-up server (close socket, etc.)\n self.server_close()\n</code></pre>\n\n<p>Simple server stoppable with user action (SIGTERM, <kbd>Ctrl</kbd>+<kbd>C</kbd>, ...):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>server = StoppableHTTPServer((\"127.0.0.1\", 8080),\n http.server.BaseHTTPRequestHandler)\nserver.run()\n</code></pre>\n\n<p>Server running in a thread:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import threading\n\nserver = StoppableHTTPServer((\"127.0.0.1\", 8080),\n http.server.BaseHTTPRequestHandler)\n\n# Start processing requests\nthread = threading.Thread(None, server.run)\nthread.start()\n\n# ... do things ...\n\n# Shutdown server\nserver.shutdown()\nthread.join()\n</code></pre>\n"
},
{
"answer_id": 50749656,
"author": "Vlad Tudorache",
"author_id": 9910960,
"author_profile": "https://Stackoverflow.com/users/9910960",
"pm_score": 2,
"selected": false,
"text": "<p>This method I use successfully (Python 3) to stop the server from the web application itself (a web page):</p>\n\n<pre><code>import http.server\nimport os\nimport re\n\nclass PatientHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):\n stop_server = False\n base_directory = \"/static/\"\n # A file to use as an \"server stopped user information\" page.\n stop_command = \"/control/stop.html\"\n def send_head(self):\n self.path = os.path.normpath(self.path)\n if self.path == PatientHTTPRequestHandler.stop_command and self.address_string() == \"127.0.0.1\":\n # I wanted that only the local machine could stop the server.\n PatientHTTPRequestHandler.stop_server = True\n # Allow the stop page to be displayed.\n return http.server.SimpleHTTPRequestHandler.send_head(self)\n if self.path.startswith(PatientHTTPRequestHandler.base_directory):\n return http.server.SimpleHTTPRequestHandler.send_head(self)\n else:\n return self.send_error(404, \"Not allowed\", \"The path you requested is forbidden.\")\n\nif __name__ == \"__main__\":\n httpd = http.server.HTTPServer((\"127.0.0.1\", 8080), PatientHTTPRequestHandler)\n # A timeout is needed for server to check periodically for KeyboardInterrupt\n httpd.timeout = 1\n while not PatientHTTPRequestHandler.stop_server:\n httpd.handle_request()\n</code></pre>\n\n<p>This way, pages served via base address <code>http://localhost:8080/static/</code> (example <code>http://localhost:8080/static/styles/common.css</code>) will be served by the default handler, an access to <code>http://localhost:8080/control/stop.html</code> from the server's computer will display <code>stop.html</code> then stop the server, any other option will be forbidden.</p>\n"
},
{
"answer_id": 62087704,
"author": "Helgi",
"author_id": 13642184,
"author_profile": "https://Stackoverflow.com/users/13642184",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import http.server\nimport socketserver\nimport socket as sck\nimport os\nimport threading\n\n\nclass myserver:\n def __init__(self, PORT, LOCATION):\n self.thrd = threading.Thread(None, self.run)\n self.Directory = LOCATION\n self.Port = PORT\n hostname = sck.gethostname()\n ip_address = sck.gethostbyname(hostname)\n self.url = 'http://' + ip_address + ':' + str(self.Port)\n Handler = http.server.SimpleHTTPRequestHandler\n self.httpd = socketserver.TCPServer((\"\", PORT), Handler)\n print('Object created, use the start() method to launch the server')\n def run(self):\n print('listening on: ' + self.url )\n os.chdir(self.Directory)\n print('myserver object started') \n print('Use the objects stop() method to stop the server')\n self.httpd.serve_forever()\n print('Quit handling')\n\n print('Sever stopped')\n print('Port ' + str(self.Port) + ' should be available again.')\n\n\n def stop(self):\n print('Stopping server')\n self.httpd.shutdown()\n self.httpd.server_close()\n print('Need just one more request before shutting down'\n\n\n def start(self):\n self.thrd.start()\n\ndef help():\n helpmsg = '''Create a new server-object by initialising\nNewServer = webserver3.myserver(Port_number, Directory_String)\nThen start it using NewServer.start() function\nStop it using NewServer.stop()'''\n print(helpmsg)\n</code></pre>\n\n<p>Not a experience python programmer, just wanting to share my comprehensive solution. Mostly based on snippets here and there. I usually import this script in my console and it allows me to set up multiple servers for different locations using their specific ports, sharing my content with other devices on the network.</p>\n"
},
{
"answer_id": 64438136,
"author": "Eric L",
"author_id": 9762732,
"author_profile": "https://Stackoverflow.com/users/9762732",
"pm_score": 3,
"selected": false,
"text": "<p>This is a simplified version of <a href=\"https://stackoverflow.com/a/62087704/9762732\">Helgi's answer</a> for python 3.7:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import threading\nimport time\nfrom http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler\n\n\nclass MyServer(threading.Thread):\n def run(self):\n self.server = ThreadingHTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)\n self.server.serve_forever()\n def stop(self):\n self.server.shutdown()\n\n\nif __name__ == '__main__':\n s = MyServer()\n s.start()\n print('thread alive:', s.is_alive()) # True\n time.sleep(2)\n s.stop()\n print('thread alive:', s.is_alive()) # False\n</code></pre>\n"
},
{
"answer_id": 67413124,
"author": "Tom Pohl",
"author_id": 20954,
"author_profile": "https://Stackoverflow.com/users/20954",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a context-flavored version for Python 3.7+ which I prefer because it cleans up automatically <em>and</em> you can specify the directory to serve:</p>\n<pre><code>from contextlib import contextmanager\nfrom functools import partial\nfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer\nfrom threading import Thread\n\n\n@contextmanager\ndef http_server(host: str, port: int, directory: str):\n server = ThreadingHTTPServer(\n (host, port), partial(SimpleHTTPRequestHandler, directory=directory)\n )\n server_thread = Thread(target=server.serve_forever, name="http_server")\n server_thread.start()\n\n try:\n yield\n finally:\n server.shutdown()\n server_thread.join()\n\n\ndef usage_example():\n import time\n\n with http_server("127.0.0.1", 8087, "."):\n # now you can use the web server\n time.sleep(100)\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.
The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdown` method, but it is missing in `HTTPServer`.
The whole `BaseHTTPServer` module has very little documentation :(
|
I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve\_forever (from SocketServer.py) method looks like this:
```
def serve_forever(self):
"""Handle one request at a time until doomsday."""
while 1:
self.handle_request()
```
You could replace (in subclass) `while 1` with `while self.should_be_running`, and modify that value from a different thread. Something like:
```
def stop_serving_forever(self):
"""Stop handling requests"""
self.should_be_running = 0
# Make a fake request to the server, to really force it to stop.
# Otherwise it will just stop on the next request.
# (Exercise for the reader.)
self.make_a_fake_request_to_myself()
```
Edit: I dug up the actual code I used at the time:
```
class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
stopped = False
allow_reuse_address = True
def __init__(self, *args, **kw):
SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
self.register_function(lambda: 'OK', 'ping')
def serve_forever(self):
while not self.stopped:
self.handle_request()
def force_stop(self):
self.server_close()
self.stopped = True
self.create_dummy_request()
def create_dummy_request(self):
server = xmlrpclib.Server('http://%s:%s' % self.server_address)
server.ping()
```
|
268,648 |
<p>I'm scanning through a file looking for lines that match a certain regex pattern, and then I want to print out the lines that match but in alphabetical order. I'm sure this is trivial but vbscript isn't my background</p>
<p>my array is defined as</p>
<pre><code>Dim lines(10000)
</code></pre>
<p>if that makes any difference, and I'm trying to execute my script from a normal cmd prompt</p>
|
[
{
"answer_id": 268659,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 7,
"selected": true,
"text": "<p>From <a href=\"http://www.microsoft.com/technet/scriptcenter/funzone/games/tips08/gtip1130.mspx#E4C\" rel=\"noreferrer\">microsoft</a></p>\n\n<p>Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript scripters were forced to write their own sort routines, be that a bubble sort routine, a heap sort, a quicksort, or some other type of sorting algorithm.</p>\n\n<p>So (using .Net as it is installed on my pc):</p>\n\n<pre><code>Set outputLines = CreateObject(\"System.Collections.ArrayList\")\n\n'add lines\noutputLines.Add output\noutputLines.Add output\n\noutputLines.Sort()\nFor Each outputLine in outputLines\n stdout.WriteLine outputLine\nNext\n</code></pre>\n"
},
{
"answer_id": 268661,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": "<p>You either have to write your own sort by hand, or maybe try this technique: </p>\n\n<p><a href=\"http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=83\" rel=\"nofollow noreferrer\">http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=83</a></p>\n\n<p>You can freely intermix server side javascript with VBScript, so wherever VBScript falls short, switch to javascript.</p>\n"
},
{
"answer_id": 268668,
"author": "Gabe",
"author_id": 9835,
"author_profile": "https://Stackoverflow.com/users/9835",
"pm_score": 0,
"selected": false,
"text": "<p>VBScript does not have a method for sorting arrays so you've got two options:</p>\n\n<ul>\n<li>Writing a sorting function like mergesort, from ground up.</li>\n<li>Use the JScript tip from <a href=\"http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=83\" rel=\"nofollow noreferrer\">this article</a></li>\n</ul>\n"
},
{
"answer_id": 268768,
"author": "wergeld",
"author_id": 33727,
"author_profile": "https://Stackoverflow.com/users/33727",
"pm_score": -1,
"selected": false,
"text": "<p>I actually just had to do something similar but with a 2D array yesterday. I am not that up to speed on vbscript and this process really bogged me down. I found that the articles <a href=\"https://web.archive.org/web/20180927040044/http://www.4guysfromrolla.com:80/webtech/011001-1.shtml\" rel=\"nofollow noreferrer\">here</a> were very well written and got me on the road to sorting in vbscript.</p>\n"
},
{
"answer_id": 268788,
"author": "Eric Weilnau",
"author_id": 13342,
"author_profile": "https://Stackoverflow.com/users/13342",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a QuickSort that I wrote for the arrays returned from the GetRows method of ADODB.Recordset.</p>\n\n<pre><code>'Author: Eric Weilnau\n'Date Written: 7/16/2003\n'Description: QuickSortDataArray sorts a data array using the QuickSort algorithm.\n' Its arguments are the data array to be sorted, the low and high\n' bound of the data array, the integer index of the column by which the\n' data array should be sorted, and the string \"asc\" or \"desc\" for the\n' sort order.\n'\nSub QuickSortDataArray(dataArray, loBound, hiBound, sortField, sortOrder)\n Dim pivot(), loSwap, hiSwap, count\n ReDim pivot(UBound(dataArray))\n\n If hiBound - loBound = 1 Then\n If (sortOrder = \"asc\" and dataArray(sortField,loBound) > dataArray(sortField,hiBound)) or (sortOrder = \"desc\" and dataArray(sortField,loBound) < dataArray(sortField,hiBound)) Then\n Call SwapDataRows(dataArray, hiBound, loBound)\n End If\n End If\n\n For count = 0 to UBound(dataArray)\n pivot(count) = dataArray(count,int((loBound + hiBound) / 2))\n dataArray(count,int((loBound + hiBound) / 2)) = dataArray(count,loBound)\n dataArray(count,loBound) = pivot(count)\n Next\n\n loSwap = loBound + 1\n hiSwap = hiBound\n\n Do\n Do While (sortOrder = \"asc\" and dataArray(sortField,loSwap) <= pivot(sortField)) or sortOrder = \"desc\" and (dataArray(sortField,loSwap) >= pivot(sortField))\n loSwap = loSwap + 1\n\n If loSwap > hiSwap Then\n Exit Do\n End If\n Loop\n\n Do While (sortOrder = \"asc\" and dataArray(sortField,hiSwap) > pivot(sortField)) or (sortOrder = \"desc\" and dataArray(sortField,hiSwap) < pivot(sortField))\n hiSwap = hiSwap - 1\n Loop\n\n If loSwap < hiSwap Then\n Call SwapDataRows(dataArray,loSwap,hiSwap)\n End If\n Loop While loSwap < hiSwap\n\n For count = 0 to Ubound(dataArray)\n dataArray(count,loBound) = dataArray(count,hiSwap)\n dataArray(count,hiSwap) = pivot(count)\n Next\n\n If loBound < (hiSwap - 1) Then\n Call QuickSortDataArray(dataArray, loBound, hiSwap-1, sortField, sortOrder)\n End If\n\n If (hiSwap + 1) < hiBound Then\n Call QuickSortDataArray(dataArray, hiSwap+1, hiBound, sortField, sortOrder)\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 308735,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": false,
"text": "<p>Disconnected recordsets can be useful.</p>\n\n<pre><code>Const adVarChar = 200 'the SQL datatype is varchar\n\n'Create a disconnected recordset\nSet rs = CreateObject(\"ADODB.RECORDSET\")\nrs.Fields.append \"SortField\", adVarChar, 25\n\nrs.CursorType = adOpenStatic\nrs.Open\nrs.AddNew \"SortField\", \"Some data\"\nrs.Update\nrs.AddNew \"SortField\", \"All data\"\nrs.Update\n\nrs.Sort = \"SortField\"\n\nrs.MoveFirst\n\nDo Until rs.EOF\n strList=strList & vbCrLf & rs.Fields(\"SortField\") \n rs.MoveNext\nLoop \n\nMsgBox strList\n</code></pre>\n"
},
{
"answer_id": 5209248,
"author": "Riccardo Quintan",
"author_id": 636071,
"author_profile": "https://Stackoverflow.com/users/636071",
"pm_score": 5,
"selected": false,
"text": "<p>I know this is a pretty old topic but it might come in handy for anyone in the future. the script below does what the fella was trying to achieve purely using vbscript. when sorted terms starting in capital letters will have priority.</p>\n\n<pre><code>for a = UBound(ArrayOfTerms) - 1 To 0 Step -1\n for j= 0 to a\n if ArrayOfTerms(j)>ArrayOfTerms(j+1) then\n temp=ArrayOfTerms(j+1)\n ArrayOfTerms(j+1)=ArrayOfTerms(j)\n ArrayOfTerms(j)=temp\n end if\n next\nnext \n</code></pre>\n"
},
{
"answer_id": 5779968,
"author": "Carlos Nunez",
"author_id": 314212,
"author_profile": "https://Stackoverflow.com/users/314212",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another vbscript implementation of quicksort. This is the in-place, unstable approach as defined in wikipedia (see here: <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Quicksort</a>). Uses much less memory (original implementation requires upper and lower temporary storage arrays to be created upon every iteration, which can increase memory size by n terms in the worst case).</p>\n\n<p>For ascending order, switch the signs. </p>\n\n<p>If you want to sort characters, use Asc(ch) function.</p>\n\n<pre><code>'-------------------------------------\n ' quicksort\n ' Carlos Nunez, created: 25 April, 2010.\n '\n ' NOTE: partition function also\n ' required\n '-------------------------------------\nfunction qsort(list, first, last)\n Dim i, j\n if (typeName(list) <> \"Variant()\" or ubound(list) = 0) then exit function 'list passed must be a collection or array.\n\n 'if the set size is less than 3, we can do a simple comparison sort.\n if (last-first) < 3 then\n for i = first to last\n for j = first to last\n if list(i) < list(j) then\n swap list,i,j\n end if\n next\n next\n else\n dim p_idx\n\n 'we need to set the pivot relative to the position of the subset currently being sorted.\n 'if the starting position of the subset is the first element of the whole set, then the pivot is the median of the subset.\n 'otherwise, the median is offset by the first position of the subset.\n '-------------------------------------------------------------------------------------------------------------------------\n if first-1 < 0 then\n p_idx = round((last-first)/2,0)\n else\n p_idx = round(((first-1)+((last-first)/2)),0)\n end if\n\n dim p_nidx: p_nidx = partition(list, first, last, p_idx)\n if p_nidx = -1 then exit function\n\n qsort list, first, p_nidx-1\n qsort list, p_nidx+1, last\n end if\nend function\n\n\nfunction partition(list, first, last, idx)\n Dim i\n partition = -1\n\n dim p_val: p_val = list(idx)\n swap list,idx,last\n dim swap_pos: swap_pos = first\n for i = first to last-1 \n if list(i) <= p_val then\n swap list,i,swap_pos\n swap_pos = swap_pos + 1\n end if\n next\n swap list,swap_pos,last\n\n partition = swap_pos\nend function\n\nfunction swap(list,a_pos,b_pos)\n dim tmp\n tmp = list(a_pos)\n list(a_pos) = list(b_pos)\n list(b_pos) = tmp \nend function\n</code></pre>\n"
},
{
"answer_id": 10351062,
"author": "Lewis Gordon",
"author_id": 1361158,
"author_profile": "https://Stackoverflow.com/users/1361158",
"pm_score": 1,
"selected": false,
"text": "<p>This is a vbscript implementation of merge sort. </p>\n\n<pre><code>'@Function Name: Sort\n'@Author: Lewis Gordon\n'@Creation Date: 4/26/12\n'@Description: Sorts a given array either in ascending or descending order, as specified by the\n' order parameter. This array is then returned at the end of the function.\n'@Prerequisites: An array must be allocated and have all its values inputted.\n'@Parameters:\n' $ArrayToSort: This is the array that is being sorted.\n' $Order: This is the sorting order that the array will be sorted in. This parameter \n' can either be \"ASC\" or \"DESC\" or ascending and descending, respectively.\n'@Notes: This uses merge sort under the hood. Also, this function has only been tested for\n' integers and strings in the array. However, this should work for any data type that\n' implements the greater than and less than comparators. This function also requires\n' that the merge function is also present, as it is needed to complete the sort.\n'@Examples:\n' Dim i\n' Dim TestArray(50)\n' Randomize\n' For i=0 to UBound(TestArray)\n' TestArray(i) = Int((100 - 0 + 1) * Rnd + 0)\n' Next\n' MsgBox Join(Sort(TestArray, \"DESC\"))\n'\n'@Return value: This function returns a sorted array in the specified order.\n'@Change History: None\n\n'The merge function.\nPublic Function Merge(LeftArray, RightArray, Order)\n 'Declared variables\n Dim FinalArray\n Dim FinalArraySize\n Dim i\n Dim LArrayPosition\n Dim RArrayPosition\n\n 'Variable initialization\n LArrayPosition = 0\n RArrayPosition = 0\n\n 'Calculate the expected size of the array based on the two smaller arrays.\n FinalArraySize = UBound(LeftArray) + UBound(RightArray) + 1\n ReDim FinalArray(FinalArraySize)\n\n 'This should go until we need to exit the function.\n While True\n\n 'If we are done with all the values in the left array. Add the rest of the right array\n 'to the final array.\n If LArrayPosition >= UBound(LeftArray)+1 Then\n For i=RArrayPosition To UBound(RightArray)\n FinalArray(LArrayPosition+i) = RightArray(i)\n Next\n Merge = FinalArray\n Exit Function\n\n 'If we are done with all the values in the right array. Add the rest of the left array\n 'to the final array.\n ElseIf RArrayPosition >= UBound(RightArray)+1 Then\n For i=LArrayPosition To UBound(LeftArray)\n FinalArray(i+RArrayPosition) = LeftArray(i)\n Next\n Merge = FinalArray\n Exit Function\n\n 'For descending, if the current value of the left array is greater than the right array \n 'then add it to the final array. The position of the left array will then be incremented\n 'by one.\n ElseIf LeftArray(LArrayPosition) > RightArray(RArrayPosition) And UCase(Order) = \"DESC\" Then\n FinalArray(LArrayPosition+RArrayPosition) = LeftArray(LArrayPosition)\n LArrayPosition = LArrayPosition + 1\n\n 'For ascending, if the current value of the left array is less than the right array \n 'then add it to the final array. The position of the left array will then be incremented\n 'by one.\n ElseIf LeftArray(LArrayPosition) < RightArray(RArrayPosition) And UCase(Order) = \"ASC\" Then\n FinalArray(LArrayPosition+RArrayPosition) = LeftArray(LArrayPosition)\n LArrayPosition = LArrayPosition + 1\n\n 'For anything else that wasn't covered, add the current value of the right array to the\n 'final array.\n Else\n FinalArray(LArrayPosition+RArrayPosition) = RightArray(RArrayPosition)\n RArrayPosition = RArrayPosition + 1\n End If\n Wend\nEnd Function\n\n'The main sort function.\nPublic Function Sort(ArrayToSort, Order)\n 'Variable declaration.\n Dim i\n Dim LeftArray\n Dim Modifier\n Dim RightArray\n\n 'Check to make sure the order parameter is okay.\n If Not UCase(Order)=\"ASC\" And Not UCase(Order)=\"DESC\" Then\n Exit Function\n End If\n 'If the array is a singleton or 0 then it is sorted.\n If UBound(ArrayToSort) <= 0 Then\n Sort = ArrayToSort\n Exit Function\n End If\n\n 'Setting up the modifier to help us split the array effectively since the round\n 'functions aren't helpful in VBScript.\n If UBound(ArrayToSort) Mod 2 = 0 Then\n Modifier = 1\n Else\n Modifier = 0\n End If\n\n 'Setup the arrays to about half the size of the main array.\n ReDim LeftArray(Fix(UBound(ArrayToSort)/2))\n ReDim RightArray(Fix(UBound(ArrayToSort)/2)-Modifier)\n\n 'Add the first half of the values to one array.\n For i=0 To UBound(LeftArray)\n LeftArray(i) = ArrayToSort(i)\n Next\n\n 'Add the other half of the values to the other array.\n For i=0 To UBound(RightArray)\n RightArray(i) = ArrayToSort(i+Fix(UBound(ArrayToSort)/2)+1)\n Next\n\n 'Merge the sorted arrays.\n Sort = Merge(Sort(LeftArray, Order), Sort(RightArray, Order), Order)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 17359670,
"author": "Leif Neland",
"author_id": 1678652,
"author_profile": "https://Stackoverflow.com/users/1678652",
"pm_score": 0,
"selected": false,
"text": "<p>When having large (\"wide\") arrays, instead of moving each element of a long row of data around, use a one-dimensional array with indexes of the array.</p>\n\n<p>initialize ptr_arr with 0,1,2,3,..uBound(arr)\nthen access data with </p>\n\n<pre><code>arr(field_index,ptr_arr(row_index))\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>arr(field_index,row_index)\n</code></pre>\n\n<p>and just swap the elements of ptr_arr instead of swapping the rows.</p>\n\n<p>If you are processing the array row by row, eg displaying it as a , you can take the lookout out of the inner loop:</p>\n\n<pre><code>max_col=uBound(arr,1)\nresponse.write \"<table>\"\nfor n = 0 to uBound(arr,2)\n response.write \"<tr>\"\n row=ptr_arr(n)\n for i=0 to max_col\n response.write \"<td>\"&arr(i,row)&\"</td>\"\n next\n response.write \"</tr>\nnext\nresponse.write \"</table>\" \n</code></pre>\n"
},
{
"answer_id": 24898238,
"author": "Andrew Dennison",
"author_id": 1454085,
"author_profile": "https://Stackoverflow.com/users/1454085",
"pm_score": 2,
"selected": false,
"text": "<p>If you are going to output the lines anyway, you could run the output through the sort command. Not elegant, but it does not require much work:</p>\n\n<pre><code>cscript.exe //nologo YOUR-SCRIPT | Sort\n</code></pre>\n\n<p>Note <strong>//nologo</strong> omits the logo lines (<em>Microsoft (R) Windows Script Host Version</em>... blah blah blah) from appearing in the middle of your sorted output. (I guess MS does not know what stderr is for.)</p>\n\n<p>See <a href=\"http://ss64.com/nt/sort.html\" rel=\"nofollow\">http://ss64.com/nt/sort.html</a> for details on sort.</p>\n\n<p><strong>/+n</strong> is the most useful option if your sort key does not start in the first column.</p>\n\n<p>Compares are always <strong>case-insensitive</strong>, which is lame.</p>\n"
},
{
"answer_id": 27437223,
"author": "Christopher J. Scharer",
"author_id": 4287094,
"author_profile": "https://Stackoverflow.com/users/4287094",
"pm_score": 2,
"selected": false,
"text": "<p>Some old school array sorting. Of course this only sorts single dimension arrays.</p>\n\n<p>'C:\\DropBox\\Automation\\Libraries\\Array.vbs</p>\n\n<pre><code>Option Explicit\n\nPublic Function Array_AdvancedBubbleSort(ByRef rarr_ArrayToSort(), ByVal rstr_SortOrder)\n' ==================================================================================\n' Date : 12/09/1999\n' Author : Christopher J. Scharer (CJS)\n' Description : Creates a sorted Array from a one dimensional array\n' in Ascending (default) or Descending order based on the rstr_SortOrder.\n' Variables :\n' rarr_ArrayToSort() The array to sort and return.\n' rstr_SortOrder The order to sort in, default ascending or D for descending.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_AdvancedBubbleSort\"\n Dim bln_Sorted\n Dim lng_Loop_01\n Dim str_SortOrder\n Dim str_Temp\n\n bln_Sorted = False\n str_SortOrder = Left(UCase(rstr_SortOrder), 1) 'We only need to know if the sort order is A(SENC) or D(ESEND)...and for that matter we really only need to know if it's D because we are defaulting to Ascending.\n Do While (bln_Sorted = False)\n bln_Sorted = True\n str_Temp = \"\"\n If (str_SortOrder = \"D\") Then\n 'Sort in descending order.\n For lng_Loop_01 = LBound(rarr_ArrayToSort) To (UBound(rarr_ArrayToSort) - 1)\n If (rarr_ArrayToSort(lng_Loop_01) < rarr_ArrayToSort(lng_Loop_01 + 1)) Then\n bln_Sorted = False\n str_Temp = rarr_ArrayToSort(lng_Loop_01)\n rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Loop_01 + 1)\n rarr_ArrayToSort(lng_Loop_01 + 1) = str_Temp\n End If\n If (rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) > rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)) Then\n bln_Sorted = False\n str_Temp = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1))\n rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)\n rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01) = str_Temp\n End If\n Next\n Else\n 'Default to Ascending.\n For lng_Loop_01 = LBound(rarr_ArrayToSort) To (UBound(rarr_ArrayToSort) - 1)\n If (rarr_ArrayToSort(lng_Loop_01) > rarr_ArrayToSort(lng_Loop_01 + 1)) Then\n bln_Sorted = False\n str_Temp = rarr_ArrayToSort(lng_Loop_01)\n rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Loop_01 + 1)\n rarr_ArrayToSort(lng_Loop_01 + 1) = str_Temp\n End If\n If (rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) < rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)) Then\n bln_Sorted = False\n str_Temp = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1))\n rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)\n rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01) = str_Temp\n End If\n Next\n End If\n Loop\nEnd Function\n\nPublic Function Array_BubbleSort(ByRef rarr_ArrayToSort())\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_BubbleSort\"\n Dim lng_Loop_01\n Dim lng_Loop_02\n Dim var_Temp\n\n For lng_Loop_01 = (UBound(rarr_ArrayToSort) - 1) To 0 Step -1\n For lng_Loop_02 = 0 To lng_Loop_01\n If rarr_ArrayToSort(lng_Loop_02) > rarr_ArrayToSort(lng_Loop_02 + 1) Then\n var_Temp = rarr_ArrayToSort(lng_Loop_02 + 1)\n rarr_ArrayToSort(lng_Loop_02 + 1) = rarr_ArrayToSort(lng_Loop_02)\n rarr_ArrayToSort(lng_Loop_02) = var_Temp\n End If\n Next\n Next\nEnd Function\n\nPublic Function Array_GetDimensions(ByVal rarr_Array)\n Const const_FUNCTION_NAME = \"Array_GetDimensions\"\n Dim int_Dimensions\n Dim int_Result\n Dim str_Dimensions\n\n int_Result = 0\n If IsArray(rarr_Array) Then\n On Error Resume Next\n Do\n int_Dimensions = -2\n int_Dimensions = UBound(rarr_Array, int_Result + 1)\n If int_Dimensions > -2 Then\n int_Result = int_Result + 1\n If int_Result = 1 Then\n str_Dimensions = str_Dimensions & int_Dimensions\n Else\n str_Dimensions = str_Dimensions & \":\" & int_Dimensions\n End If\n End If\n Loop Until int_Dimensions = -2\n On Error GoTo 0\n End If\n Array_GetDimensions = int_Result ' & \";\" & str_Dimensions\nEnd Function\n\nPublic Function Array_GetUniqueCombinations(ByVal rarr_Fields, ByRef robj_Combinations)\n Const const_FUNCTION_NAME = \"Array_GetUniqueCombinations\"\n Dim int_Element\n Dim str_Combination\n\n On Error Resume Next\n\n Array_GetUniqueCombinations = CBool(False)\n For int_Element = LBound(rarr_Fields) To UBound(rarr_Fields)\n str_Combination = rarr_Fields(int_Element)\n Call robj_Combinations.Add(robj_Combinations.Count & \":\" & str_Combination, 0)\n' Call Array_GetUniqueCombinationsSub(rarr_Fields, robj_Combinations, int_Element)\n Next 'int_Element\n For int_Element = LBound(rarr_Fields) To UBound(rarr_Fields)\n Call Array_GetUniqueCombinationsSub(rarr_Fields, robj_Combinations, int_Element)\n Next 'int_Element\n Array_GetUniqueCombinations = CBool(True)\nEnd Function 'Array_GetUniqueCombinations\n\nPublic Function Array_GetUniqueCombinationsSub(ByVal rarr_Fields, ByRef robj_Combinations, ByRef rint_LBound)\n Const const_FUNCTION_NAME = \"Array_GetUniqueCombinationsSub\"\n Dim int_Element\n Dim str_Combination\n\n On Error Resume Next\n\n Array_GetUniqueCombinationsSub = CBool(False)\n str_Combination = rarr_Fields(rint_LBound)\n For int_Element = (rint_LBound + 1) To UBound(rarr_Fields)\n str_Combination = str_Combination & \",\" & rarr_Fields(int_Element)\n Call robj_Combinations.Add(robj_Combinations.Count & \":\" & str_Combination, str_Combination)\n Next 'int_Element\n Array_GetUniqueCombinationsSub = CBool(True)\nEnd Function 'Array_GetUniqueCombinationsSub\n\nPublic Function Array_HeapSort(ByRef rarr_ArrayToSort())\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_HeapSort\"\n Dim lng_Loop_01\n Dim var_Temp\n Dim arr_Size\n\n arr_Size = UBound(rarr_ArrayToSort) + 1\n For lng_Loop_01 = ((arr_Size / 2) - 1) To 0 Step -1\n Call Array_SiftDown(rarr_ArrayToSort, lng_Loop_01, arr_Size)\n Next\n For lng_Loop_01 = (arr_Size - 1) To 1 Step -1\n var_Temp = rarr_ArrayToSort(0)\n rarr_ArrayToSort(0) = rarr_ArrayToSort(lng_Loop_01)\n rarr_ArrayToSort(lng_Loop_01) = var_Temp\n Call Array_SiftDown(rarr_ArrayToSort, 0, (lng_Loop_01 - 1))\n Next\nEnd Function\n\nPublic Function Array_InsertionSort(ByRef rarr_ArrayToSort())\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_InsertionSort\"\n Dim lng_ElementCount\n Dim lng_Loop_01\n Dim lng_Loop_02\n Dim lng_Index\n\n lng_ElementCount = UBound(rarr_ArrayToSort) + 1\n For lng_Loop_01 = 1 To (lng_ElementCount - 1)\n lng_Index = rarr_ArrayToSort(lng_Loop_01)\n lng_Loop_02 = lng_Loop_01\n Do While lng_Loop_02 > 0\n If rarr_ArrayToSort(lng_Loop_02 - 1) > lng_Index Then\n rarr_ArrayToSort(lng_Loop_02) = rarr_ArrayToSort(lng_Loop_02 - 1)\n lng_Loop_02 = (lng_Loop_02 - 1)\n End If\n Loop\n rarr_ArrayToSort(lng_Loop_02) = lng_Index\n Next\nEnd Function\n\nPrivate Function Array_Merge(ByRef rarr_ArrayToSort(), ByRef rarr_ArrayTemp(), ByVal rlng_Left, ByVal rlng_MiddleIndex, ByVal rlng_Right)\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Merges an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_Merge\"\n Dim lng_Loop_01\n Dim lng_LeftEnd\n Dim lng_ElementCount\n Dim lng_TempPos\n\n lng_LeftEnd = (rlng_MiddleIndex - 1)\n lng_TempPos = rlng_Left\n lng_ElementCount = (rlng_Right - rlng_Left + 1)\n Do While (rlng_Left <= lng_LeftEnd) _\n And (rlng_MiddleIndex <= rlng_Right)\n If rarr_ArrayToSort(rlng_Left) <= rarr_ArrayToSort(rlng_MiddleIndex) Then\n rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_Left)\n lng_TempPos = (lng_TempPos + 1)\n rlng_Left = (rlng_Left + 1)\n Else\n rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_MiddleIndex)\n lng_TempPos = (lng_TempPos + 1)\n rlng_MiddleIndex = (rlng_MiddleIndex + 1)\n End If\n Loop\n Do While rlng_Left <= lng_LeftEnd\n rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_Left)\n rlng_Left = (rlng_Left + 1)\n lng_TempPos = (lng_TempPos + 1)\n Loop\n Do While rlng_MiddleIndex <= rlng_Right\n rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_MiddleIndex)\n rlng_MiddleIndex = (rlng_MiddleIndex + 1)\n lng_TempPos = (lng_TempPos + 1)\n Loop\n For lng_Loop_01 = 0 To (lng_ElementCount - 1)\n rarr_ArrayToSort(rlng_Right) = rarr_ArrayTemp(rlng_Right)\n rlng_Right = (rlng_Right - 1)\n Next\nEnd Function\n\nPublic Function Array_MergeSort(ByRef rarr_ArrayToSort(), ByRef rarr_ArrayTemp(), ByVal rlng_FirstIndex, ByVal rlng_LastIndex)\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' Note :The rarr_ArrayTemp array that is passed in has to be dimensionalized to the same size\n' as the rarr_ArrayToSort array that is passed in prior to calling the function.\n' Also the rlng_FirstIndex variable should be the value of the LBound(rarr_ArrayToSort)\n' and the rlng_LastIndex variable should be the value of the UBound(rarr_ArrayToSort)\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_MergeSort\"\n Dim lng_MiddleIndex\n\n If rlng_LastIndex > rlng_FirstIndex Then\n ' Recursively sort the two halves of the list.\n lng_MiddleIndex = ((rlng_FirstIndex + rlng_LastIndex) / 2)\n Call Array_MergeSort(rarr_ArrayToSort, rarr_ArrayTemp, rlng_FirstIndex, lng_MiddleIndex)\n Call Array_MergeSort(rarr_ArrayToSort, rarr_ArrayTemp, lng_MiddleIndex + 1, rlng_LastIndex)\n ' Merge the results.\n Call Array_Merge(rarr_ArrayToSort, rarr_ArrayTemp, rlng_FirstIndex, lng_MiddleIndex + 1, rlng_LastIndex)\n End If\nEnd Function\n\nPublic Function Array_Push(ByRef rarr_Array, ByVal rstr_Value, ByVal rstr_Delimiter)\n Const const_FUNCTION_NAME = \"Array_Push\"\n Dim int_Loop\n Dim str_Array_01\n Dim str_Array_02\n\n 'If there is no delimiter passed in then set the default delimiter equal to a comma.\n If rstr_Delimiter = \"\" Then\n rstr_Delimiter = \",\"\n End If\n\n 'Check to see if the rarr_Array is actually an Array.\n If IsArray(rarr_Array) = True Then\n 'Verify that the rarr_Array variable is only a one dimensional array.\n If Array_GetDimensions(rarr_Array) <> 1 Then\n Array_Push = \"ERR, the rarr_Array variable passed in was not a one dimensional array.\"\n Exit Function\n End If\n If IsArray(rstr_Value) = True Then\n 'Verify that the rstr_Value variable is is only a one dimensional array.\n If Array_GetDimensions(rstr_Value) <> 1 Then\n Array_Push = \"ERR, the rstr_Value variable passed in was not a one dimensional array.\"\n Exit Function\n End If\n str_Array_01 = Split(rarr_Array, rstr_Delimiter)\n str_Array_02 = Split(rstr_Value, rstr_Delimiter)\n rarr_Array = Join(str_Array_01 & rstr_Delimiter & str_Array_02)\n Else\n On Error Resume Next\n ReDim Preserve rarr_Array(UBound(rarr_Array) + 1)\n If Err.Number <> 0 Then ' \"Subscript out of range\" An array that was passed in must have been Erased to re-create it with new elements (possibly when passing an array to be populated into a recursive function)\n ReDim rarr_Array(0)\n Err.Clear\n End If\n If IsObject(rstr_Value) = True Then\n Set rarr_Array(UBound(rarr_Array)) = rstr_Value\n Else\n rarr_Array(UBound(rarr_Array)) = rstr_Value\n End If\n End If\n Else\n 'Check to see if the rstr_Value is an Array.\n If IsArray(rstr_Value) = True Then\n 'Verify that the rstr_Value variable is is only a one dimensional array.\n If Array_GetDimensions(rstr_Value) <> 1 Then\n Array_Push = \"ERR, the rstr_Value variable passed in was not a one dimensional array.\"\n Exit Function\n End If\n rarr_Array = rstr_Value\n Else\n rarr_Array = Split(rstr_Value, rstr_Delimiter)\n End If\n End If\n Array_Push = UBound(rarr_Array)\nEnd Function\n\nPublic Function Array_QuickSort(ByRef rarr_ArrayToSort(), ByVal rlng_Low, ByVal rlng_High)\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' Note :The rlng_Low variable should be the value of the LBound(rarr_ArrayToSort)\n' and the rlng_High variable should be the value of the UBound(rarr_ArrayToSort)\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_QuickSort\"\n Dim var_Pivot\n Dim lng_Swap\n Dim lng_Low\n Dim lng_High\n\n lng_Low = rlng_Low\n lng_High = rlng_High\n var_Pivot = rarr_ArrayToSort((rlng_Low + rlng_High) / 2)\n Do While lng_Low <= lng_High\n Do While (rarr_ArrayToSort(lng_Low) < var_Pivot _\n And lng_Low < rlng_High)\n lng_Low = lng_Low + 1\n Loop\n Do While (var_Pivot < rarr_ArrayToSort(lng_High) _\n And lng_High > rlng_Low)\n lng_High = (lng_High - 1)\n Loop\n If lng_Low <= lng_High Then\n lng_Swap = rarr_ArrayToSort(lng_Low)\n rarr_ArrayToSort(lng_Low) = rarr_ArrayToSort(lng_High)\n rarr_ArrayToSort(lng_High) = lng_Swap\n lng_Low = (lng_Low + 1)\n lng_High = (lng_High - 1)\n End If\n Loop\n If rlng_Low < lng_High Then\n Call Array_QuickSort(rarr_ArrayToSort, rlng_Low, lng_High)\n End If\n If lng_Low < rlng_High Then\n Call Array_QuickSort(rarr_ArrayToSort, lng_Low, rlng_High)\n End If\nEnd Function\n\nPublic Function Array_SelectionSort(ByRef rarr_ArrayToSort())\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_SelectionSort\"\n Dim lng_ElementCount\n Dim lng_Loop_01\n Dim lng_Loop_02\n Dim lng_Min\n Dim var_Temp\n\n lng_ElementCount = UBound(rarr_ArrayToSort) + 1\n For lng_Loop_01 = 0 To (lng_ElementCount - 2)\n lng_Min = lng_Loop_01\n For lng_Loop_02 = (lng_Loop_01 + 1) To lng_ElementCount - 1\n If rarr_ArrayToSort(lng_Loop_02) < rarr_ArrayToSort(lng_Min) Then\n lng_Min = lng_Loop_02\n End If\n Next\n var_Temp = rarr_ArrayToSort(lng_Loop_01)\n rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Min)\n rarr_ArrayToSort(lng_Min) = var_Temp\n Next\nEnd Function\n\nPublic Function Array_ShellSort(ByRef rarr_ArrayToSort())\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sorts an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_ShellSort\"\n Dim lng_Loop_01\n Dim var_Temp\n Dim lng_Hold\n Dim lng_HValue\n\n lng_HValue = LBound(rarr_ArrayToSort)\n Do\n lng_HValue = (3 * lng_HValue + 1)\n Loop Until lng_HValue > UBound(rarr_ArrayToSort)\n Do\n lng_HValue = (lng_HValue / 3)\n For lng_Loop_01 = (lng_HValue + LBound(rarr_ArrayToSort)) To UBound(rarr_ArrayToSort)\n var_Temp = rarr_ArrayToSort(lng_Loop_01)\n lng_Hold = lng_Loop_01\n Do While rarr_ArrayToSort(lng_Hold - lng_HValue) > var_Temp\n rarr_ArrayToSort(lng_Hold) = rarr_ArrayToSort(lng_Hold - lng_HValue)\n lng_Hold = (lng_Hold - lng_HValue)\n If lng_Hold < lng_HValue Then\n Exit Do\n End If\n Loop\n rarr_ArrayToSort(lng_Hold) = var_Temp\n Next\n Loop Until lng_HValue = LBound(rarr_ArrayToSort)\nEnd Function\n\nPrivate Function Array_SiftDown(ByRef rarr_ArrayToSort(), ByVal rlng_Root, ByVal rlng_Bottom)\n' ==================================================================================\n' Date : 03/18/2008\n' Author : Christopher J. Scharer (CJS)\n' Description : Sifts the elements down in an array.\n' ==================================================================================\n Const const_FUNCTION_NAME = \"Array_SiftDown\"\n Dim bln_Done\n Dim max_Child\n Dim var_Temp\n\n bln_Done = False\n Do While ((rlng_Root * 2) <= rlng_Bottom) _\n And bln_Done = False\n If rlng_Root * 2 = rlng_Bottom Then\n max_Child = (rlng_Root * 2)\n ElseIf rarr_ArrayToSort(rlng_Root * 2) > rarr_ArrayToSort(rlng_Root * 2 + 1) Then\n max_Child = (rlng_Root * 2)\n Else\n max_Child = (rlng_Root * 2 + 1)\n End If\n If rarr_ArrayToSort(rlng_Root) < rarr_ArrayToSort(max_Child) Then\n var_Temp = rarr_ArrayToSort(rlng_Root)\n rarr_ArrayToSort(rlng_Root) = rarr_ArrayToSort(max_Child)\n rarr_ArrayToSort(max_Child) = var_Temp\n rlng_Root = max_Child\n Else\n bln_Done = True\n End If\n Loop\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 70152210,
"author": "Antoni Gual Via",
"author_id": 1955444,
"author_profile": "https://Stackoverflow.com/users/1955444",
"pm_score": 0,
"selected": false,
"text": "<p>An old but still asked question. People posted links to this solution that are broken nowadays, so I post an example:\nYou can use ScriptControl to access JScript's array sort\nYou can provide your own jscript sorting function.\nUnfortunateluy it works only in the 32 bit version of wsh...</p>\n<pre><code>a=split("this is a javascript array sort demo"," ")\n\nwscript.echo vbcrlf & "alphabeticaly"&vbcrlf\na=sort(a)\nfor each i in a\n wscript.echo i\nnext\nwscript.echo vbcrlf & "by length"&vbcrlf\na=sortbylength(a)\nfor each i in a\n wscript.echo i\nnext\n\nfunction sort(a)\nwith createobject("ScriptControl")\n .Language = "JScript"\n .AddCode "function sortvbs(a) {return a.toArray().sort().join('\\b')}"\n sort= split(.Run("sortvbs",a),chr(8))\n End With\nend function\n\n\nfunction sortbylength(a)\nwith createobject("ScriptControl")\n .Language = "JScript"\n .AddCode "function lensort(a,b){return((('' + a).length > ('' + b).length) ? 1 : ((('' + a).length < ('' + b).length) ? -1 : 0))}" \n .Addcode "function sortvbs(a) {return a.toArray().sort(lensort).join('\\b')}"\n sortbylength= split(.Run("sortvbs",a),chr(8))\n End With\nend function\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472/"
] |
I'm scanning through a file looking for lines that match a certain regex pattern, and then I want to print out the lines that match but in alphabetical order. I'm sure this is trivial but vbscript isn't my background
my array is defined as
```
Dim lines(10000)
```
if that makes any difference, and I'm trying to execute my script from a normal cmd prompt
|
From [microsoft](http://www.microsoft.com/technet/scriptcenter/funzone/games/tips08/gtip1130.mspx#E4C)
Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript scripters were forced to write their own sort routines, be that a bubble sort routine, a heap sort, a quicksort, or some other type of sorting algorithm.
So (using .Net as it is installed on my pc):
```
Set outputLines = CreateObject("System.Collections.ArrayList")
'add lines
outputLines.Add output
outputLines.Add output
outputLines.Sort()
For Each outputLine in outputLines
stdout.WriteLine outputLine
Next
```
|
268,651 |
<p>How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?</p>
<p>Here are a few references on the subject:</p>
<ul>
<li><a href="http://www.hibernate.org/333.html" rel="noreferrer">http://www.hibernate.org/333.html</a></li>
<li><a href="http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/" rel="noreferrer">http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/</a> </li>
<li><a href="http://in.relation.to/Bloggers/HibernateAndSwingDemoApp" rel="noreferrer">http://in.relation.to/Bloggers/HibernateAndSwingDemoApp</a></li>
</ul>
|
[
{
"answer_id": 268784,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 4,
"selected": true,
"text": "<p>Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.</p>\n\n<p>It may also be a good idea to implement a transparent session re-open in case the connection went dead -- users tend to leave applications open for extended periods of time, and it should continue to work Monday even if DB server was rebooted on weekend.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Jens Schauder provided a reason to use multiple sessions: partial (unwanted) updates to the session. Well, that comes down to the way you use Hibernate. </p>\n\n<p>Suppose we have two dialogs open (as in Jens' blog example). If user clicks a radiobox, and we immediately update a Hibernate entity associated with this radiobox, then, when user clicks Cancel, we're in trouble -- session is already updated.</p>\n\n<p>The right way, as I see it, is to update dialog variables (non-Hibernate objects) only. Then, when user clicks OK, we begin a transaction, merge updated objects, commit the transaction. No garbage gets ever saved into session.</p>\n\n<pre><code>MyHibernateUtils.begin();\nSettings settings = DaoSettings.load();\n// update setttings here\nDaoSettings.save(settings);\nMyHibernateUtils.commit(); \n</code></pre>\n\n<p>If we implement such a clean separation of concerns, we can later switch to multiple sessions with a simple change of MyHibernateUtils.begin() implementation.</p>\n\n<p>As for possible memory leak, well... Transaction.commit() calls Session.flush(), which AFAIK, cleans the cache too. Also, one may manually control the caching policy by calling Session.setCacheMode().</p>\n"
},
{
"answer_id": 273780,
"author": "Jens Schauder",
"author_id": 66686,
"author_profile": "https://Stackoverflow.com/users/66686",
"pm_score": 2,
"selected": false,
"text": "<p>Don't use a single session. For everything but the smallest applications, it will grow, collecting outdated data and become slower and slower, since the dirty check needs to check every entity in the session.</p>\n\n<p>If you don't need/want lazy loading and tracking of changes by Hibernate, you can use short-lived sessions. </p>\n\n<p>But if you want to benefit from the power of Hibernate use the approach I described in my blog:\n<a href=\"http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/\" rel=\"nofollow noreferrer\">http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/</a></p>\n\n<p>or in the German version:</p>\n\n<p><a href=\"http://blog.schauderhaft.de/2007/12/17/hibernate-sessions-in-fat-client-anwendungen/\" rel=\"nofollow noreferrer\">http://blog.schauderhaft.de/2007/12/17/hibernate-sessions-in-fat-client-anwendungen/</a></p>\n\n<p>AFAIK it is really the same approach described in the <a href=\"http://in.relation.to/Bloggers/HibernateAndSwingDemoApp\" rel=\"nofollow noreferrer\">http://in.relation.to/Bloggers/HibernateAndSwingDemoApp</a> but with a recommendation how to actually scope your session:\nOn Session per Frame, with the exception of modal Frames which use the session of the parent Frame. </p>\n\n<p>Just make sure never to combine objects from different sessions. It will cause lots of trouble.</p>\n\n<p>In reply to Vladimirs update:</p>\n\n<ul>\n<li>The cancel actually works extremely nice with my approach: throw away the session.</li>\n<li>session.flush does not fix the problem of the evergrowing session when you work with a single session for the application. Of course with the approach, you describe you can work with short-lived sessions which should work ok. BUT</li>\n<li>you lose a lot: lazy loading only works with attached objects, automatic detection of dirty objects. If you work with detached objects (or objects that aren't entities at all) you have to do this yourself.</li>\n</ul>\n"
},
{
"answer_id": 342095,
"author": "stili",
"author_id": 20763,
"author_profile": "https://Stackoverflow.com/users/20763",
"pm_score": 1,
"selected": false,
"text": "<p>Use one session per thread (<a href=\"http://www.hibernate.org/42.html#A6\" rel=\"nofollow noreferrer\">doc</a>) and a version or timestamp column to allow optimistic concurrency and thereby avoiding session-to-instance conflicts. Attach instances to session when needed unless you need long running transactions or a restrictive isolation level.</p>\n"
},
{
"answer_id": 616325,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Problem with \"''session per thread''\" is good Swing applications do the database access outside the EDT, usually in newly created SwingWorker threads. This way, \"''session per thread''\" quickly becomes \"''session per click''\".</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407003/"
] |
How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?
Here are a few references on the subject:
* <http://www.hibernate.org/333.html>
* <http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/>
* <http://in.relation.to/Bloggers/HibernateAndSwingDemoApp>
|
Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.
It may also be a good idea to implement a transparent session re-open in case the connection went dead -- users tend to leave applications open for extended periods of time, and it should continue to work Monday even if DB server was rebooted on weekend.
**Update**
Jens Schauder provided a reason to use multiple sessions: partial (unwanted) updates to the session. Well, that comes down to the way you use Hibernate.
Suppose we have two dialogs open (as in Jens' blog example). If user clicks a radiobox, and we immediately update a Hibernate entity associated with this radiobox, then, when user clicks Cancel, we're in trouble -- session is already updated.
The right way, as I see it, is to update dialog variables (non-Hibernate objects) only. Then, when user clicks OK, we begin a transaction, merge updated objects, commit the transaction. No garbage gets ever saved into session.
```
MyHibernateUtils.begin();
Settings settings = DaoSettings.load();
// update setttings here
DaoSettings.save(settings);
MyHibernateUtils.commit();
```
If we implement such a clean separation of concerns, we can later switch to multiple sessions with a simple change of MyHibernateUtils.begin() implementation.
As for possible memory leak, well... Transaction.commit() calls Session.flush(), which AFAIK, cleans the cache too. Also, one may manually control the caching policy by calling Session.setCacheMode().
|
268,652 |
<p>I'm using java and referring to the "double" datatype.
To keep it short, I'm reading some values from standard input that I read in my code as doubles (I would much rather use something like BigInteger but right now it's not possible).</p>
<p>I expect to get double values from the user but sometimes they might input things like:
999999999999999999999999999.9999999999
which I think is beyond an accurate representation for double and get's rounded to 1.0E27 (probably).</p>
<p>I would like to get some pointers on how to detect whether a specific value would be unable to be accurately represented in a double and would require rounding (so that I could refuse that value or other such actions).</p>
<p>Thank you very much</p>
|
[
{
"answer_id": 268662,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>Most values entered by humans won't be exactly representable with a double.</p>\n\n<p>For instance, do you want to prevent the user from entering 0.1? That's not exactly representable as a double.</p>\n\n<p>To find the scale of the error, you could do something like:</p>\n\n<pre><code>BigDecimal userAsDecimal = new BigDecimal(userInput);\ndouble userAsDouble = double.parseDouble(userInput);\nBigDecimal doubleToDecimal = new BigDecimal(userAsDouble);\nBigDecimal error = userAsDecimal.subtract(userAsDouble).abs();\n</code></pre>\n\n<p>Then check whether \"error\" is tolerably small.</p>\n"
},
{
"answer_id": 268665,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<pre><code>double orig = GetSomeDouble();\ndouble test1 = orig - 1;\nif ( orig == test1 )\n SomethingIsWrong();\ndouble test2 = test1 + 1;\nif ( orig != test2 )\n SomethingIsWrong();\n</code></pre>\n"
},
{
"answer_id": 268720,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 1,
"selected": false,
"text": "<p>You can't use a double to store something precisely in the way you're asking, very rarely a user may enter a number that a double can perfectly represent, but that would be coincidence only. If you need to store the exact number you could use a string so long as you don't need to do any manipulation. If you need more than that then there are probably libraries that are made for that kind of precise math.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15225/"
] |
I'm using java and referring to the "double" datatype.
To keep it short, I'm reading some values from standard input that I read in my code as doubles (I would much rather use something like BigInteger but right now it's not possible).
I expect to get double values from the user but sometimes they might input things like:
999999999999999999999999999.9999999999
which I think is beyond an accurate representation for double and get's rounded to 1.0E27 (probably).
I would like to get some pointers on how to detect whether a specific value would be unable to be accurately represented in a double and would require rounding (so that I could refuse that value or other such actions).
Thank you very much
|
Most values entered by humans won't be exactly representable with a double.
For instance, do you want to prevent the user from entering 0.1? That's not exactly representable as a double.
To find the scale of the error, you could do something like:
```
BigDecimal userAsDecimal = new BigDecimal(userInput);
double userAsDouble = double.parseDouble(userInput);
BigDecimal doubleToDecimal = new BigDecimal(userAsDouble);
BigDecimal error = userAsDecimal.subtract(userAsDouble).abs();
```
Then check whether "error" is tolerably small.
|
268,656 |
<p>I'm trying to control the main timeline of my flash application from a MovieClip that is a child of the main stage. Apparently, in ActionScript 2, you could do that using _root, but using root (since _root no longer exists) now gives an error:</p>
<pre><code>root.play();
</code></pre>
<p>"1061: Call to a possibly undefined method play through a reference with static type flash.display:DisplayObjectContainer."</p>
<p>Using the Stage class also doesn't work:</p>
<pre><code>stage.play();
</code></pre>
<p>"1061: Call to a possibly undefined method play through a reference with static type flash.display:Stage."</p>
<p>Is there any way to do this?</p>
|
[
{
"answer_id": 268777,
"author": "Randy Stegbauer",
"author_id": 34301,
"author_profile": "https://Stackoverflow.com/users/34301",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&catid=665&threadid=1387264&enterthread=y\" rel=\"nofollow noreferrer\">http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&catid=665&threadid=1387264&enterthread=y</a>,</p>\n\n<p>try something like<br>\n MovieClip(root).gotoAndPlay(\"menu\");</p>\n\n<p>Good Luck,<br>\nRandy Stegbauer</p>\n"
},
{
"answer_id": 268873,
"author": "Andres",
"author_id": 1815,
"author_profile": "https://Stackoverflow.com/users/1815",
"pm_score": 4,
"selected": true,
"text": "<p>You need to cast it to a MovieClip</p>\n\n<pre><code>(root as MovieClip).play()\n</code></pre>\n"
},
{
"answer_id": 1944256,
"author": "bagushutomo",
"author_id": 236581,
"author_profile": "https://Stackoverflow.com/users/236581",
"pm_score": 0,
"selected": false,
"text": "<p>Another way is separate your movieclip code into separate class while setting document class for your main fla.</p>\n\n<p>Assume the document class of your main fla is Main.as and your movieclip's class file is Movie.as, you can add Main class pointer as parameter in the Movie class constructor</p>\n\n<p>In Main.as</p>\n\n<p><code>public class Main() {\n var m = new Movie(this);\n}</code></p>\n\n<p>In Movie.as</p>\n\n<pre><code>public class Movie(m:Main) { m.gotoAndPlay(\"somewhere\"); }\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25280/"
] |
I'm trying to control the main timeline of my flash application from a MovieClip that is a child of the main stage. Apparently, in ActionScript 2, you could do that using \_root, but using root (since \_root no longer exists) now gives an error:
```
root.play();
```
"1061: Call to a possibly undefined method play through a reference with static type flash.display:DisplayObjectContainer."
Using the Stage class also doesn't work:
```
stage.play();
```
"1061: Call to a possibly undefined method play through a reference with static type flash.display:Stage."
Is there any way to do this?
|
You need to cast it to a MovieClip
```
(root as MovieClip).play()
```
|
268,671 |
<p>I have a HQL query that can generate either an IList of results, or an IEnumerable of results. </p>
<p>However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.</p>
<p>Is there any better way? I went with the CopyTo-approach.</p>
|
[
{
"answer_id": 268699,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "<p>Which version of .NET are you using? If it's .NET 3.5, I'd just call <code>ToArray()</code> and be done with it.</p>\n\n<p>If you only have a non-generic IEnumerable, do something like this:</p>\n\n<pre><code>IEnumerable query = ...;\nMyEntityType[] array = query.Cast<MyEntityType>().ToArray();\n</code></pre>\n\n<p>If you don't know the type within that method but the method's callers do know it, make the method generic and try this:</p>\n\n<pre><code>public static void T[] PerformQuery<T>()\n{\n IEnumerable query = ...;\n T[] array = query.Cast<T>().ToArray();\n return array;\n}\n</code></pre>\n"
},
{
"answer_id": 5703033,
"author": "Michael Joyce",
"author_id": 623004,
"author_profile": "https://Stackoverflow.com/users/623004",
"pm_score": 6,
"selected": false,
"text": "<p>Put the following in your .cs file:</p>\n\n<pre><code>using System.Linq;\n</code></pre>\n\n<p>You will then be able to use the following extension method from System.Linq.Enumerable:</p>\n\n<pre><code>public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)\n</code></pre>\n\n<p>I.e.</p>\n\n<pre><code>IEnumerable<object> query = ...;\nobject[] bob = query.ToArray();\n</code></pre>\n"
},
{
"answer_id": 16970830,
"author": "Philippe Matray",
"author_id": 2409554,
"author_profile": "https://Stackoverflow.com/users/2409554",
"pm_score": 3,
"selected": false,
"text": "<p>I feel like reinventing the wheel...</p>\n\n<pre><code>public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)\n{\n if (enumerable == null)\n throw new ArgumentNullException(\"enumerable\");\n\n return enumerable as T[] ?? enumerable.ToArray();\n}\n</code></pre>\n"
},
{
"answer_id": 35019023,
"author": "Lug",
"author_id": 435961,
"author_profile": "https://Stackoverflow.com/users/435961",
"pm_score": 3,
"selected": false,
"text": "<p>In case you don't have Linq, I solved it the following way:</p>\n\n<pre><code> private T[] GetArray<T>(IList<T> iList) where T: new()\n {\n var result = new T[iList.Count];\n\n iList.CopyTo(result, 0);\n\n return result;\n }\n</code></pre>\n\n<p>Hope it helps</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33663/"
] |
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.
However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.
Is there any better way? I went with the CopyTo-approach.
|
Which version of .NET are you using? If it's .NET 3.5, I'd just call `ToArray()` and be done with it.
If you only have a non-generic IEnumerable, do something like this:
```
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
```
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
```
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
```
|
268,674 |
<p>I have this ListBox which is bound to an ObservableCollection. Each object in the list implements an interface called ISelectable </p>
<pre><code>public interface ISelectable : INotifyPropertyChanged
{
event EventHandler IsSelected;
bool Selected { get; set; }
string DisplayText { get; }
}
</code></pre>
<p>I want to keep track of which object is selected regardless of how it is selected. The user could click on the representation of the object in the ListBox but it could also be that an object is selected via code. If the user selects an object via the ListBox I cast the the selected item to an ISelectable and set the Selected property to true.</p>
<pre><code>ISelectable selectable = (ISelectable)e.AddedItems[0];
selectable.Selected = true;
</code></pre>
<p>My problem is that when I select the object using code I can't get ListBox to change the selected item. I'm using a DataTemplate to show the selected object in a different color which means everything is displayed correctly. But the ListBox has the last object the user clicked as the SelectedItem which means that item can't be clicked without first selecting another object in the list.</p>
<p>Anyone got any idea on how to solve this? I pretty sure I can accomplish what I want by writing some custom code to handle the Mouse and Keyboard events but I rather not. I have tried adding a SelectedItem property to the collection and bind it to the ListBox's SelectItemProperty but no luck. </p>
|
[
{
"answer_id": 268692,
"author": "Pondidum",
"author_id": 1500,
"author_profile": "https://Stackoverflow.com/users/1500",
"pm_score": 1,
"selected": false,
"text": "<p>Have you looked at the list box's SelectedItemChanged and SelectedIndexChanged events?</p>\n\n<p>These should be triggered whenever a selection is changed, no matter how it is selected.</p>\n"
},
{
"answer_id": 269094,
"author": "Sorskoot",
"author_id": 31722,
"author_profile": "https://Stackoverflow.com/users/31722",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should fire the propertyChanged event when the select has changed. Add this code to the object that implements ISelectable. You'll end up with something like: </p>\n\n<pre><code>private bool _Selected;\n public bool Selected\n {\n get\n {\n return _Selected;\n }\n set\n {\n if (PropertyChanged != null) \n PropertyChanged(this, new PropertyChangedEventArgs(\"Selected\"));\n\n _Selected = value;\n }\n }\n</code></pre>\n\n<p>I've tried the folowing code: </p>\n\n<pre><code>public ObservableCollection<testClass> tests = new ObservableCollection<testClass>();\n\n public Window1()\n {\n InitializeComponent();\n tests.Add(new testClass(\"Row 1\"));\n tests.Add(new testClass(\"Row 2\"));\n tests.Add(new testClass(\"Row 3\"));\n tests.Add(new testClass(\"Row 4\"));\n tests.Add(new testClass(\"Row 5\"));\n tests.Add(new testClass(\"Row 6\"));\n TheList.ItemsSource = tests;\n }\n\n private void Button_Click(object sender, RoutedEventArgs e)\n {\n tests[3].Selected = true;\n TheList.SelectedItem = tests[3];\n }\n</code></pre>\n\n<p>where testClass implements ISelectable. </p>\n\n<p>The is a piece of xaml, nothing fancy:</p>\n\n<pre><code><ListBox Grid.Row=\"0\" x:Name=\"TheList\"></ListBox> \n<Button Grid.Row=\"1\" Click=\"Button_Click\">Select 4th</Button>\n</code></pre>\n\n<p>I hope this helps. </p>\n"
},
{
"answer_id": 270269,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 3,
"selected": true,
"text": "<p>You could also accomplish this by data binding ListBoxItem.IsSelected to your Selected property. The idea is to set the binding for each of the ListBoxItems as they are created. This can be done using a style that targets each of the ListBoxItems generated for the ListBox.</p>\n\n<p>This way when an item in the ListBox is selected/unselected, the corresponding Selected property will be updated. Likewise setting the Selected property in code will be reflected in the ListBox</p>\n\n<p>For this to work the Selected property must raise the PropertyChanged event.</p>\n\n<pre><code><List.Resources>\n <Style TargetType=\"ListBoxItem\">\n <Setter \n Property=\"IsSelected\" \n Value=\"{Binding \n Path=DataContext.Selected, \n RelativeSource={RelativeSource Self}}\" \n />\n </Style>\n</List.Resources>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] |
I have this ListBox which is bound to an ObservableCollection. Each object in the list implements an interface called ISelectable
```
public interface ISelectable : INotifyPropertyChanged
{
event EventHandler IsSelected;
bool Selected { get; set; }
string DisplayText { get; }
}
```
I want to keep track of which object is selected regardless of how it is selected. The user could click on the representation of the object in the ListBox but it could also be that an object is selected via code. If the user selects an object via the ListBox I cast the the selected item to an ISelectable and set the Selected property to true.
```
ISelectable selectable = (ISelectable)e.AddedItems[0];
selectable.Selected = true;
```
My problem is that when I select the object using code I can't get ListBox to change the selected item. I'm using a DataTemplate to show the selected object in a different color which means everything is displayed correctly. But the ListBox has the last object the user clicked as the SelectedItem which means that item can't be clicked without first selecting another object in the list.
Anyone got any idea on how to solve this? I pretty sure I can accomplish what I want by writing some custom code to handle the Mouse and Keyboard events but I rather not. I have tried adding a SelectedItem property to the collection and bind it to the ListBox's SelectItemProperty but no luck.
|
You could also accomplish this by data binding ListBoxItem.IsSelected to your Selected property. The idea is to set the binding for each of the ListBoxItems as they are created. This can be done using a style that targets each of the ListBoxItems generated for the ListBox.
This way when an item in the ListBox is selected/unselected, the corresponding Selected property will be updated. Likewise setting the Selected property in code will be reflected in the ListBox
For this to work the Selected property must raise the PropertyChanged event.
```
<List.Resources>
<Style TargetType="ListBoxItem">
<Setter
Property="IsSelected"
Value="{Binding
Path=DataContext.Selected,
RelativeSource={RelativeSource Self}}"
/>
</Style>
</List.Resources>
```
|
268,680 |
<p>I would like to monitor the number of threads used by a specific process on Linux.
Is there an easy way to get this information without impacting the performance of the process?</p>
|
[
{
"answer_id": 268705,
"author": "rhys keepence",
"author_id": 34676,
"author_profile": "https://Stackoverflow.com/users/34676",
"pm_score": 3,
"selected": false,
"text": "<p>JStack is quite inexpensive - one option would be to pipe the output through grep to find active threads and then pipe through wc -l.</p>\n\n<p>More graphically is JConsole, which displays the thread count for a given process.</p>\n"
},
{
"answer_id": 268717,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>Newer JDK distributions ship with JConsole and VisualVM. Both are fantastic tools for getting the dirty details from a running Java process. If you have to do this programmatically, investigate JMX.</p>\n"
},
{
"answer_id": 272716,
"author": "slav0nic",
"author_id": 2201031,
"author_profile": "https://Stackoverflow.com/users/2201031",
"pm_score": 8,
"selected": false,
"text": "<p>try</p>\n\n<pre><code>ps huH p <PID_OF_U_PROCESS> | wc -l\n</code></pre>\n\n<p>or <a href=\"http://htop.sourceforge.net/\" rel=\"noreferrer\">htop</a></p>\n"
},
{
"answer_id": 7216452,
"author": "flexo",
"author_id": 906726,
"author_profile": "https://Stackoverflow.com/users/906726",
"pm_score": 3,
"selected": false,
"text": "<p>If you use:</p>\n\n<pre><code>ps uH p <PID_OF_U_PROCESS> | wc -l\n</code></pre>\n\n<p>You have to subtract 1 to the result, as one of the lines \"wc\" is counting is the headers of the \"ps\" command.</p>\n"
},
{
"answer_id": 7216699,
"author": "bdonlan",
"author_id": 36723,
"author_profile": "https://Stackoverflow.com/users/36723",
"pm_score": 6,
"selected": false,
"text": "<p>Each thread in a process creates a directory under <code>/proc/<pid>/task</code>. Count the number of directories, and you have the number of threads.</p>\n"
},
{
"answer_id": 15406796,
"author": "MRalwasser",
"author_id": 324152,
"author_profile": "https://Stackoverflow.com/users/324152",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/jvmtop/\" rel=\"nofollow\">jvmtop</a> can show the current jvm thread count beside other metrics.</p>\n"
},
{
"answer_id": 21244557,
"author": "jlliagre",
"author_id": 211665,
"author_profile": "https://Stackoverflow.com/users/211665",
"pm_score": 3,
"selected": false,
"text": "<p>Here is one command that displays the number of threads of a given process :</p>\n\n<pre><code>ps -L -o pid= -p <pid> | wc -l\n</code></pre>\n\n<p>Unlike the other <code>ps</code> based answers, there is here no need to substract <code>1</code> from its output as there is no <code>ps</code> header line thanks to the <code>-o pid=</code>option.</p>\n"
},
{
"answer_id": 25459612,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p><code>ps -eLf</code> on the shell shall give you a list of all the threads and processes currently running on the system.\nOr, you can run <code>top</code> command then hit 'H' to toggle thread listings.</p>\n"
},
{
"answer_id": 29772733,
"author": "PbxMan",
"author_id": 1652451,
"author_profile": "https://Stackoverflow.com/users/1652451",
"pm_score": 6,
"selected": false,
"text": "<pre><code>cat /proc/<PROCESS_PID>/status | grep Threads\n</code></pre>\n"
},
{
"answer_id": 33368739,
"author": "Partly Cloudy",
"author_id": 109079,
"author_profile": "https://Stackoverflow.com/users/109079",
"pm_score": 0,
"selected": false,
"text": "<p>If you're interested in those threads which are really <em>active</em> -- as in doing something (not blocked, not timed_waiting, not reporting \"thread running\" but really waiting for a stream to give data) as opposed to sitting around idle but live -- then you might be interested in <a href=\"https://gist.github.com/ahgittin/3734619\" rel=\"nofollow\">jstack-active</a>.</p>\n\n<p>This simple bash script runs <code>jstack</code> then filters out all the threads which by heuristics seem to be idling, showing you stack traces for those threads which are actually consuming CPU cycles.</p>\n"
},
{
"answer_id": 34412722,
"author": "DiveInto",
"author_id": 404145,
"author_profile": "https://Stackoverflow.com/users/404145",
"pm_score": -1,
"selected": false,
"text": "<p>VisualVM can show clear states of threads of a given JVM process</p>\n\n<p><a href=\"https://i.stack.imgur.com/kbLlz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kbLlz.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 35421908,
"author": "Avinash Reddy",
"author_id": 4963254,
"author_profile": "https://Stackoverflow.com/users/4963254",
"pm_score": 3,
"selected": false,
"text": "<p><code>$ ps H p pid-id</code></p>\n\n<p>H - Lists all the individual threads in a process</p>\n\n<p>or</p>\n\n<p><code>$cat /proc/pid-id/status</code></p>\n\n<p>pid-id is the Process ID</p>\n\n<p>eg.. (Truncated the below output)</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>root@abc:~# cat /proc/8443/status\nName: abcdd\nState: S (sleeping)\nTgid: 8443\nVmSwap: 0 kB\nThreads: 4\nSigQ: 0/256556\nSigPnd: 0000000000000000\n</code></pre>\n"
},
{
"answer_id": 37713259,
"author": "Thejaswi R",
"author_id": 644289,
"author_profile": "https://Stackoverflow.com/users/644289",
"pm_score": 7,
"selected": false,
"text": "<p>To get the number of threads for a given pid:</p>\n\n<pre><code>$ ps -o nlwp <pid>\n</code></pre>\n\n<p>Where <code>nlwp</code> stands for <em>Number of Light Weight Processes (threads)</em>. Thus <code>ps</code> aliases <code>nlwp</code> to <code>thcount</code>, which means that</p>\n\n<pre><code>$ ps -o thcount <pid>\n</code></pre>\n\n<p>does also work.</p>\n\n<p>If you want to monitor the thread count, simply use <code>watch</code>:</p>\n\n<pre><code>$ watch ps -o thcount <pid>\n</code></pre>\n\n<p>To get the sum of all threads running in the system:</p>\n\n<pre><code>$ ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'\n</code></pre>\n"
},
{
"answer_id": 42277270,
"author": "Manuel Mndza Bañs",
"author_id": 7575716,
"author_profile": "https://Stackoverflow.com/users/7575716",
"pm_score": 1,
"selected": false,
"text": "<p>If you are trying to find out the number of threads using cpu for a given pid I would use:</p>\n\n<pre><code>top -bc -H -n2 -p <pid> | awk '{if ($9 != \"0.0\" && $1 ~ /^[0-9]+$/) print $1 }' | sort -u | wc -l\n</code></pre>\n"
},
{
"answer_id": 46885192,
"author": "Saeed Zahedian Abroodi",
"author_id": 8584198,
"author_profile": "https://Stackoverflow.com/users/8584198",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way is using \"htop\". You can install \"htop\" (a fancier version of top) which will show you all your cores, process and memory usage.</p>\n\n<p>Press \"Shift+H\" to show all process or press again to hide it.\nPress \"F4\" key to search your process name.</p>\n\n<p>Installing on Ubuntu or Debian:</p>\n\n<pre><code>sudo apt-get install htop\n</code></pre>\n\n<p>Installing on Redhat or CentOS:</p>\n\n<pre><code>yum install htop\ndnf install htop [On Fedora 22+ releases]\n</code></pre>\n\n<p>If you want to compile \"htop\" from source code, you will find it <a href=\"https://www.tecmint.com/install-htop-linux-process-monitoring-for-rhel-centos-fedora/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 63118210,
"author": "Andreas Foteas",
"author_id": 7948137,
"author_profile": "https://Stackoverflow.com/users/7948137",
"pm_score": 1,
"selected": false,
"text": "<p>If you want the number of threads per user in a linux system then you should use:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>ps -eLf | grep <USER> | awk '{ num += $6 } END { print num }'\n</code></pre>\n<p>where as <code><USER></code> use the desired user name.</p>\n"
},
{
"answer_id": 63856739,
"author": "Aleksey Kanaev",
"author_id": 2806415,
"author_profile": "https://Stackoverflow.com/users/2806415",
"pm_score": 3,
"selected": false,
"text": "<p>My answer is more gui, but still within terminal. Htop may be used with a bit of setup.</p>\n<ol>\n<li>Start htop.</li>\n<li>Enter setup menu by pressing F2.</li>\n<li>From leftmost column choose "Columns"</li>\n<li>From rightmost column choose the column to be added to main monitoring output, "NLWP" is what you are looking for.</li>\n<li>Press F10.</li>\n</ol>\n"
},
{
"answer_id": 66134471,
"author": "Serge Mosin",
"author_id": 1573766,
"author_profile": "https://Stackoverflow.com/users/1573766",
"pm_score": 2,
"selected": false,
"text": "<p>If you're looking for thread count for multiple processes, the other answers won't work well for you, since you won't see the process names or PIDs, which makes them rather useless. Use this instead:</p>\n<pre><code>ps -o pid,nlwp,args -p <pid_1> <pid_2> ... <pid_N>\n</code></pre>\n<p>In order to watch the changes live, just add <code>watch</code>:</p>\n<pre><code>watch ps -o pid,nlwp,args -p <pid_1> <pid_2> ... <pid_N>\n</code></pre>\n"
},
{
"answer_id": 74261349,
"author": "abhishek dubey",
"author_id": 16083181,
"author_profile": "https://Stackoverflow.com/users/16083181",
"pm_score": 0,
"selected": false,
"text": "<p>First get the process ID (pid) by executing below command:</p>\n<p>ps -ef | grep (for e.g ps -ef | grep java)</p>\n<p>Now replace the pid in below command and execute to get the total thread count of a process.</p>\n<p>ps huH p | wc -l</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I would like to monitor the number of threads used by a specific process on Linux.
Is there an easy way to get this information without impacting the performance of the process?
|
try
```
ps huH p <PID_OF_U_PROCESS> | wc -l
```
or [htop](http://htop.sourceforge.net/)
|
268,698 |
<p>This is somewhat of a follow-up question to this <a href="https://stackoverflow.com/questions/267045/is-there-a-benefit-to-having-both-an-abstract-class-and-an-interface">question</a>.</p>
<p>Suppose I have an inheritance tree as follows:</p>
<pre><code>Car -> Ford -> Mustang -> MustangGT
</code></pre>
<p>Is there a benefit to defining interfaces for <em>each</em> of these classes? Example:</p>
<pre><code>ICar -> IFord -> IMustang -> IMustangGT
</code></pre>
<p>I can see that maybe other classes (like <code>Chevy</code>) would want to implement <code>Icar</code> or <code>IFord</code> and maybe even <code>IMustang</code>, but probably not <code>IMustangGT</code> because it is so specific. Are the interfaces superfluous in this case?</p>
<p>Also, I would think that any class that would want to implement <code>IFord</code> would definitely want to use its one inheritance by inheriting from <code>Ford</code> so as not to duplicate code. If that is a given, what is the benefit of also implementing <code>IFord</code>?</p>
|
[
{
"answer_id": 268716,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 0,
"selected": false,
"text": "<p>I woudl create the first two levels, ICar and IFord and leave the second level alone until I need an interface at that second level. </p>\n"
},
{
"answer_id": 268721,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 5,
"selected": true,
"text": "<p>In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.</p>\n\n<p>And in response to the first part of your question, I would recommend against creating an interface for each of your classes. This would unnecessarily clutter your class structure. If you find you need an interface you can always add it later. Hope this helps!</p>\n\n<p>Adam</p>\n"
},
{
"answer_id": 268722,
"author": "Emile",
"author_id": 433589,
"author_profile": "https://Stackoverflow.com/users/433589",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say only make an interface for things you need to refer to. You may have some other classes or functions that need to know about a car, but how often will there be something that needs to know about a ford?</p>\n"
},
{
"answer_id": 268727,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 2,
"selected": false,
"text": "<p>Don't build stuff you don't need. If it turns out you need the interfaces, it's a small effort to go back and build them.</p>\n\n<p>Also, on the pedantic side, I hope you're not actually building something that looks like this hierarchy. This is not what inheritance should be used for. </p>\n"
},
{
"answer_id": 268744,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 2,
"selected": false,
"text": "<p>Create it only once that level of functionality becomes necessary.</p>\n<p>Re-factoring Code is always on on-going process.</p>\n<p>There are tools available that will allow you to extract to interface if necessary.\nE.G. <a href=\"https://web.archive.org/web/20171017223142/http://geekswithblogs.net/JaySmith/archive/2008/02/27/refactor-visual-studio-extract-interface.aspx\" rel=\"nofollow noreferrer\">http://geekswithblogs.net/JaySmith/archive/2008/02/27/refactor-visual-studio-extract-interface.aspx</a></p>\n"
},
{
"answer_id": 268747,
"author": "eddy147",
"author_id": 30759,
"author_profile": "https://Stackoverflow.com/users/30759",
"pm_score": -1,
"selected": false,
"text": "<p>Only inherit from Interfaces and abstract classes.</p>\n\n<p>\nIf you have a couple of classes wich are almost the same, and you need to implement the majority of methods, use and Interface in combination with buying the other object.\n<br>\nIf the Mustang classes are so different then not only create an interface ICar, but also IMustang.<br>\nSo class Ford and Mustang can inherit from ICar, and Mustang and MustangGT from ICar <b>and</b> IMustang.\n</p>\n\n<p>If you implement class Ford and a method is the same as Mustang, buy from Mustang:</p>\n\n<pre><code>class Ford{\n public function Foo(){\n ...\n Mustang mustang = new Mustang();\n return mustang.Foo();\n}\n</code></pre>\n"
},
{
"answer_id": 268754,
"author": "JohnIdol",
"author_id": 1311500,
"author_profile": "https://Stackoverflow.com/users/1311500",
"pm_score": 1,
"selected": false,
"text": "<p>Make an ICar and all the rest (Make=Ford, Model=Mustang, and stuff) as members of a class that implements the interface. </p>\n\n<p>You might wanna have your Ford class and for example GM class and both implement ICar in order to use polymorphism if you don't wanna go down the route of checking <code>Make == Whatever</code>, that's up to your style.</p>\n\n<p>Anyway - In my opinion those are attributes of a car not the other way around - you just need one interface because methods are common: Brake, SpeedUp, etc.</p>\n\n<p>Can a Ford do stuff that other cars cannot? I don't think so. </p>\n"
},
{
"answer_id": 268774,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Think carefully about how your objects need to interact with each other within your problem domain, and consider if you need to have more than one implementation of a particular abstract concept. Use Interfaces to provide a contract around a concept that other objects interact with. </p>\n\n<p>In your example, I would suggest that Ford is probably a Manufacturer and Mustang is a ModelName Value used by the Manufacturer Ford, therefore you might have something more like:</p>\n\n<p>IVehichle -> CarImpl, MotorbikeImpl - has-a Manufacturer has-many ModelNames</p>\n"
},
{
"answer_id": 268789,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>In this answer about the <a href=\"https://stackoverflow.com/questions/258285/is-a-java-interface-an-abstract-class#258294\">difference between interface and class</a>, I explained that:</p>\n\n<ul>\n<li>interface exposes what a concept <em>is</em> (in term of \"what <em>is</em>\" valid, at compilation time), and is used for <strong><em>values</em></strong> (MyInterface x = ...)</li>\n<li>class exposes what a concept <em>does</em> (actually executed at runtime), and is used for values or for objects (MyClass x or aMyClass.method() )</li>\n</ul>\n\n<p>So if you need to store into a 'Ford' variable (notion of 'value') different sub-classes of Ford, create an IFord. Otherwise, do not bother until you actually need it.</p>\n\n<p>That is one criteria: if it is not met, IFord is probably useless.<br>\nIf it is met, then the other criteria exposed in the previous answers apply: If a Ford has a richer API than a Car, an IFord is useful for polymorphisms purpose. If not, ICar is enough.</p>\n"
},
{
"answer_id": 268850,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 3,
"selected": false,
"text": "<p>I also agree with <a href=\"https://stackoverflow.com/questions/268698/inheritance-and-interfaces#268721\">adamalex's response</a> that interfaces should be shared by classes that should respond to certain methods.</p>\n\n<p>If classes have similar functionality, yet are not directly related to each other in an ancestral relationship, then an interface would be a good way to add that function to the classes without duplicating functionality between the two. (Or have multiple implementations with only subtle differences.)</p>\n\n<p>While we're using a car analogy, a concrete example. Let's say we have the following classes:</p>\n\n<pre><code>Car -> Ford -> Escape -> EscapeHybrid\nCar -> Toyota -> Corolla -> CorollaHybrid\n</code></pre>\n\n<p>Cars have <code>wheels</code> and can <code>Drive()</code> and <code>Steer()</code>. So those methods should exist in the <code>Car</code> class. (Probably the <code>Car</code> class will be an abstract class.)</p>\n\n<p>Going down the line, we get the distinction between <code>Ford</code> and <code>Toyota</code> (probably implemented as difference in the type of emblem on the car, again probably an abstract class.)</p>\n\n<p>Then, finally we have a <code>Escape</code> and <code>Corolla</code> class which are classes that are completely implemented as a car.</p>\n\n<p><strong>Now, how could we make a <em>Hybrid</em> vehicle?</strong></p>\n\n<p>We could have a subclass of <code>Escape</code> that is <code>EscapeHybrid</code> which adds a <code>FordsHybridDrive()</code> method, and a subclass of <code>Corolla</code> that is <code>CorollaHybrid</code> with <code>ToyotasHybridDrive()</code> method. The methods are basically doing the same thing, but yet we have different methods. <strong>Yuck.</strong> Seems like we can do better than that.</p>\n\n<p>Let's say that a hybrid has a <code>HybridDrive()</code> method. Since we don't want to end up having two different types of hybrids (in a perfect world), so we can make an <code>IHybrid</code> interface which has a <code>HybridDrive()</code> method.</p>\n\n<p>So, <strong>if we want to make an <code>EscapeHybrid</code> or <code>CorollaHybrid</code> class</strong>, all we have to do is to <strong>implement the <code>IHybrid</code> interface</strong>.</p>\n\n<p>For a real world example, let's take a look at Java. A class which can do a comparison of an object with another object implements the <code>Comparable</code> interface. As the name implies, the interface should be for a class that is <em>comparable</em>, hence the name \"Comparable\".</p>\n\n<p>Just as a matter of interest, a <a href=\"http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html\" rel=\"nofollow noreferrer\">car example</a> is used in the <a href=\"http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html\" rel=\"nofollow noreferrer\">Interfaces</a> lesson of the <a href=\"http://java.sun.com/docs/books/tutorial/java/TOC.html\" rel=\"nofollow noreferrer\">Java Tutorial</a>.</p>\n"
},
{
"answer_id": 268851,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": "<p>In my view interfaces are a tool to enforce a requirement that a class implement a certain signature, or (as I like to think of it) a certain \"Behavior\" To me I think if the Capital I at the beginning of my onterface names as a personal pronoun, and I try to name my interfaces so they can be read that way... ICanFly, IKnowHowToPersistMyself IAmDisplayable, etc... So in your example, I would not create an interface to Mirror the complete public signature of any specific class. I would analyze the public signature (the behavior) and then separate the members into smaller logical groups (the smaller the better) like (using your example) IMove, IUseFuel, ICarryPassengers, ISteerable, IAccelerate, IDepreciate, etc... And then apply those interfaces to whatever other classes in my system need them</p>\n"
},
{
"answer_id": 268867,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 0,
"selected": false,
"text": "<p>In general, the best way to think about this (and many questions in OO) is to think about the notion of a contract. </p>\n\n<p>A contract is defined as an agreement between two (or more) parties, that states specific obligations each party must meet; in a program, this is what services a class will provide, and what you have to provide the class in order to get the services. An interface states a contract that any class implementing the interface must satisfy.</p>\n\n<p>With that in mind, though, your question somewhat depends on what language you're using and what you want to do.</p>\n\n<p>After many years of doing OO (like, oh my god, 30 years) I would usually write an interface for every contract, especially in Java, because it makes tests so much easier: if I have an interface for the class, I can build mock objects easily, almost trivially.</p>\n"
},
{
"answer_id": 268886,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 0,
"selected": false,
"text": "<p>Interfaces are intended to be a generic public API, and users will be restricted to using this public API. Unless you intend users to be using the type-specific methods of <code>IMustangGT</code>, you may want to limit the interface hierarchy to <code>ICar</code> and <code>IExpensiveCar</code>.</p>\n"
},
{
"answer_id": 470770,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/408925.aspx\" rel=\"noreferrer\">You shouldn't implement any of those interfaces at all.</a></p>\n\n<p>Class inheritance describes <strong>what an object <em>is</em></strong> (eg: it's identity). This is fine, however most of the time what an object <em>is</em>, is far less important than what an object <em>does</em>. This is where interfaces come in.</p>\n\n<p>An interface should describe <strong>what an object <em>does</em>)</strong>, or what it acts like. By this I mean it's behavior, and the set of operations which make sense given that behaviour.</p>\n\n<p>As such, good interface names should usually be of the form <code>IDriveable</code>, <code>IHasWheels</code>, and so on. Sometimes the best way to describe this behaviour is to reference a well-known other object, so you can say \"acts like one of these\" (eg: <code>IList</code>) but IMHO that form of naming is in the minority.</p>\n\n<p>Given that logic, the scenarios where <em>interface inheritance</em> makes sense are completely and entirely different from the scenarios where <em>object inheritance</em> makes sense - often these scenarios don't relate to eachother at all.</p>\n\n<p>Hope that helps you think through the interfaces you should actually need :-)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
This is somewhat of a follow-up question to this [question](https://stackoverflow.com/questions/267045/is-there-a-benefit-to-having-both-an-abstract-class-and-an-interface).
Suppose I have an inheritance tree as follows:
```
Car -> Ford -> Mustang -> MustangGT
```
Is there a benefit to defining interfaces for *each* of these classes? Example:
```
ICar -> IFord -> IMustang -> IMustangGT
```
I can see that maybe other classes (like `Chevy`) would want to implement `Icar` or `IFord` and maybe even `IMustang`, but probably not `IMustangGT` because it is so specific. Are the interfaces superfluous in this case?
Also, I would think that any class that would want to implement `IFord` would definitely want to use its one inheritance by inheriting from `Ford` so as not to duplicate code. If that is a given, what is the benefit of also implementing `IFord`?
|
In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.
And in response to the first part of your question, I would recommend against creating an interface for each of your classes. This would unnecessarily clutter your class structure. If you find you need an interface you can always add it later. Hope this helps!
Adam
|
268,750 |
<p>I have a JFrame with a menu bar and a canvas covering all the remaining surface. When I click on the menu bar, the menu opens <strong>behind</strong> the Canvas and I can't see it. Has anyone experienced this? Other than resizing the Canvas (which I am reluctant to do) is there any solution?</p>
<p>Thanks,<br/>
Vlad</p>
|
[
{
"answer_id": 268815,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 4,
"selected": true,
"text": "<p>You're experiencing heavyweight vs. lightweight issues.</p>\n\n<p>The quick fix: </p>\n\n<pre><code>// Call this sometime before you use your menus \nJPopupMenu.setDefaultLightWeightPopupEnabled(false)\n</code></pre>\n\n<p><a href=\"http://java.sun.com/products/jfc/tsc/articles/mixing/index.html\" rel=\"noreferrer\">Heavyweight vs. Lightweight</a></p>\n"
},
{
"answer_id": 8672358,
"author": "Marco",
"author_id": 1086111,
"author_profile": "https://Stackoverflow.com/users/1086111",
"pm_score": 1,
"selected": false,
"text": "<p>That happened to me when i resized a Canvas that is on a JFrame.\nI just had to call </p>\n\n<blockquote>\n <p>validate()\n on the JFrame after the resize.</p>\n</blockquote>\n\n<p>Good luck!</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1155998/"
] |
I have a JFrame with a menu bar and a canvas covering all the remaining surface. When I click on the menu bar, the menu opens **behind** the Canvas and I can't see it. Has anyone experienced this? Other than resizing the Canvas (which I am reluctant to do) is there any solution?
Thanks,
Vlad
|
You're experiencing heavyweight vs. lightweight issues.
The quick fix:
```
// Call this sometime before you use your menus
JPopupMenu.setDefaultLightWeightPopupEnabled(false)
```
[Heavyweight vs. Lightweight](http://java.sun.com/products/jfc/tsc/articles/mixing/index.html)
|
268,771 |
<p>Ok, so I have this regex:</p>
<pre><code>( |^|>)(((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{2})(-)?( )?)?)([0-9]{7}))|((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{3})(-)?( )?)?)([0-9]{6}))|((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{1})(-)?( )?)?)([0-9]{8})))( |$|<)
</code></pre>
<p>It formats Dutch and Belgian phone numbers (I only want those hence the 31 and 32 as country code).</p>
<p>Its not much fun to decipher but as you can see it also has a lot duplicated. but now it does handles it very accurately</p>
<p>All the following European formatted phone numbers are accepted</p>
<pre><code>0031201234567
0031223234567
0031612345678
+31(0)20-1234567
+31(0)223-234567
+31(0)6-12345678
020-1234567
0223-234567
06-12345678
0201234567
0223234567
0612345678
</code></pre>
<p>and the following false formatted ones are not</p>
<pre><code>06-1234567 (mobile phone number in the Netherlands should have 8 numbers after 06 )
0223-1234567 (area code with home phone)
</code></pre>
<p>as opposed to this which is good.</p>
<pre><code>020-1234567 (area code with 3 numbers has 7 numbers for the phone as opposed to a 4 number area code which can only have 6 numbers for phone number)
</code></pre>
<p>As you can see it's the '-' character that makes it a little difficult but I need it in there because it's a part of the formatting usually used by people, and I want to be able to parse them all.</p>
<p>Now is my question... do you see a way to simplify this regex (or even improve it if you see a fault in it), while keeping the same rules?</p>
<p>You can test it at <a href="http://regextester.com/" rel="nofollow noreferrer">regextester.com</a></p>
<p>(The '( |^|>)' is to check if it is at the start of a word with the possibility it being preceded by either a new line or a '>'. I search for the phone numbers in HTML pages.) </p>
|
[
{
"answer_id": 268810,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 3,
"selected": false,
"text": "<p>Good Lord Almighty, what a mess! :) If you have high-level semantic or business rules (such as the ones you describe talking about European numbers, numbers in the Netherlands, etc.) you'd probably be better served breaking that single regexp test into several individual regexp tests, one for each of your high level rules.</p>\n\n<pre><code>if number =~ /...../ # Dutch mobiles\n # ...\nelsif number =~ /..../ # Belgian landlines\n # ...\n# etc.\nend\n</code></pre>\n\n<p>It'll be quite a bit easier to read and maintain and change that way.</p>\n"
},
{
"answer_id": 268852,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p>Split it into multiple expressions. For example (pseudo-code)...</p>\n\n<pre><code>phone_no_patterns = [\n /[0-9]{13}/, # 0031201234567\n /+(31|32)\\(0\\)\\d{2}-\\d{7}/ # +31(0)20-1234567\n # ..etc..\n]\ndef check_number(num):\n for pattern in phone_no_patterns:\n if num matches pattern:\n return match.groups\n</code></pre>\n\n<p>Then you just loop over each pattern, checking if each one matches..</p>\n\n<p>Splitting the patterns up makes its easy to fix specific numbers that are causing problems (which would be horrible with the single monolithic regex)</p>\n"
},
{
"answer_id": 268856,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>It's not an optimization, but you use</p>\n\n<pre><code>(-)?( )?\n</code></pre>\n\n<p>three times in your regex. This will cause you to match on phone numbers like these</p>\n\n<pre><code>+31(0)6-12345678\n+31(0)6 12345678\n</code></pre>\n\n<p>but will also match numbers containing a dash followed by a space, like</p>\n\n<pre><code>+31(0)6- 12345678\n</code></pre>\n\n<p>You can replace </p>\n\n<pre><code>(-)?( )?\n</code></pre>\n\n<p>with</p>\n\n<pre><code>(-| )?\n</code></pre>\n\n<p>to match either a dash <strong>or</strong> a space.</p>\n"
},
{
"answer_id": 269136,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>(31|32) looks bad. When matching 32, the regex engine will first try to match 31 (2 chars), fail, and backtrack two characters to match 31. It's more efficient to first match 3 (one character), try 1 (fail), backtrack one character and match 2.</p>\n\n<p>Of course, your regex fails on 0800- numbers; they're not 10 digits.</p>\n"
},
{
"answer_id": 269151,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "<p>First observation: reading the regex is a nightmare. It cries out for Perl's /x mode.</p>\n\n<p>Second observation: there are lots, and lots, and lots of capturing parentheses in the expression (42 if I count correctly; and 42 is, of course, \"The Answer to Life, the Universe, and Everything\" -- see Douglas Adams \"Hitchiker's Guide to the Galaxy\" if you need that explained).</p>\n\n<p>Bill the Lizard notes that you use '<code>(-)?( )?</code>' several times. There's no obvious advantage to that compared with '<code>-? ?</code>' or possibly '<code>[- ]?</code>', unless you are really intent on capturing the actual punctuation separately (but there are so many capturing parentheses working out which '$<em>n</em>' items to use would be hard).</p>\n\n<p>So, let's try editing a copy of your one-liner:</p>\n\n<pre><code>( |^|>)\n(\n ((((((\\+|00)(31|32)( )?(\\(0\\))?)|0)([0-9]{2})(-)?( )?)?)([0-9]{7})) |\n ((((((\\+|00)(31|32)( )?(\\(0\\))?)|0)([0-9]{3})(-)?( )?)?)([0-9]{6})) |\n ((((((\\+|00)(31|32)( )?(\\(0\\))?)|0)([0-9]{1})(-)?( )?)?)([0-9]{8}))\n)\n( |$|<)\n</code></pre>\n\n<p>OK - now we can see the regular structure of your regular expression.</p>\n\n<p>There's much more analysis possible from here. Yes, there can be vast improvements to the regular expression. The first, obvious, one is to extract the international prefix part, and apply that once (optionally, or require the leading zero) and then apply the national rules.</p>\n\n<pre><code>( |^|>)\n(\n (((\\+|00)(31|32)( )?(\\(0\\))?)|0)\n (((([0-9]{2})(-)?( )?)?)([0-9]{7})) |\n (((([0-9]{3})(-)?( )?)?)([0-9]{6})) |\n (((([0-9]{1})(-)?( )?)?)([0-9]{8}))\n)\n( |$|<)\n</code></pre>\n\n<p>Then we can simplify the punctuation as noted before, and remove some plausibly redundant parentheses, and improve the country code recognizer:</p>\n\n<pre><code>( |^|>)\n(\n (((\\+|00)3[12] ?(\\(0\\))?)|0)\n (((([0-9]{2})-? ?)?)[0-9]{7}) |\n (((([0-9]{3})-? ?)?)[0-9]{6}) |\n (((([0-9]{1})-? ?)?)[0-9]{8})\n)\n( |$|<)\n</code></pre>\n\n<p>We can observe that the regex does not enforce the rules on mobile phone codes (so it does not insist that '06' is followed by 8 digits, for example). It also seems to allow the 1, 2 or 3 digit 'exchange' code to be optional, even with an international prefix - probably not what you had in mind, and fixing that removes some more parentheses. We can remove still more parentheses after that, leading to:</p>\n\n<pre><code>( |^|>)\n(\n (((\\+|00)3[12] ?(\\(0\\))?)|0) # International prefix or leading zero\n ([0-9]{2}-? ?[0-9]{7}) | # xx-xxxxxxx\n ([0-9]{3}-? ?[0-9]{6}) | # xxx-xxxxxx\n ([0-9]{1}-? ?[0-9]{8}) # x-xxxxxxxx\n)\n( |$|<)\n</code></pre>\n\n<p>And you can work out further optimizations from here, I'd hope.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16805/"
] |
Ok, so I have this regex:
```
( |^|>)(((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{2})(-)?( )?)?)([0-9]{7}))|((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{3})(-)?( )?)?)([0-9]{6}))|((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{1})(-)?( )?)?)([0-9]{8})))( |$|<)
```
It formats Dutch and Belgian phone numbers (I only want those hence the 31 and 32 as country code).
Its not much fun to decipher but as you can see it also has a lot duplicated. but now it does handles it very accurately
All the following European formatted phone numbers are accepted
```
0031201234567
0031223234567
0031612345678
+31(0)20-1234567
+31(0)223-234567
+31(0)6-12345678
020-1234567
0223-234567
06-12345678
0201234567
0223234567
0612345678
```
and the following false formatted ones are not
```
06-1234567 (mobile phone number in the Netherlands should have 8 numbers after 06 )
0223-1234567 (area code with home phone)
```
as opposed to this which is good.
```
020-1234567 (area code with 3 numbers has 7 numbers for the phone as opposed to a 4 number area code which can only have 6 numbers for phone number)
```
As you can see it's the '-' character that makes it a little difficult but I need it in there because it's a part of the formatting usually used by people, and I want to be able to parse them all.
Now is my question... do you see a way to simplify this regex (or even improve it if you see a fault in it), while keeping the same rules?
You can test it at [regextester.com](http://regextester.com/)
(The '( |^|>)' is to check if it is at the start of a word with the possibility it being preceded by either a new line or a '>'. I search for the phone numbers in HTML pages.)
|
First observation: reading the regex is a nightmare. It cries out for Perl's /x mode.
Second observation: there are lots, and lots, and lots of capturing parentheses in the expression (42 if I count correctly; and 42 is, of course, "The Answer to Life, the Universe, and Everything" -- see Douglas Adams "Hitchiker's Guide to the Galaxy" if you need that explained).
Bill the Lizard notes that you use '`(-)?( )?`' several times. There's no obvious advantage to that compared with '`-? ?`' or possibly '`[- ]?`', unless you are really intent on capturing the actual punctuation separately (but there are so many capturing parentheses working out which '$*n*' items to use would be hard).
So, let's try editing a copy of your one-liner:
```
( |^|>)
(
((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{2})(-)?( )?)?)([0-9]{7})) |
((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{3})(-)?( )?)?)([0-9]{6})) |
((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{1})(-)?( )?)?)([0-9]{8}))
)
( |$|<)
```
OK - now we can see the regular structure of your regular expression.
There's much more analysis possible from here. Yes, there can be vast improvements to the regular expression. The first, obvious, one is to extract the international prefix part, and apply that once (optionally, or require the leading zero) and then apply the national rules.
```
( |^|>)
(
(((\+|00)(31|32)( )?(\(0\))?)|0)
(((([0-9]{2})(-)?( )?)?)([0-9]{7})) |
(((([0-9]{3})(-)?( )?)?)([0-9]{6})) |
(((([0-9]{1})(-)?( )?)?)([0-9]{8}))
)
( |$|<)
```
Then we can simplify the punctuation as noted before, and remove some plausibly redundant parentheses, and improve the country code recognizer:
```
( |^|>)
(
(((\+|00)3[12] ?(\(0\))?)|0)
(((([0-9]{2})-? ?)?)[0-9]{7}) |
(((([0-9]{3})-? ?)?)[0-9]{6}) |
(((([0-9]{1})-? ?)?)[0-9]{8})
)
( |$|<)
```
We can observe that the regex does not enforce the rules on mobile phone codes (so it does not insist that '06' is followed by 8 digits, for example). It also seems to allow the 1, 2 or 3 digit 'exchange' code to be optional, even with an international prefix - probably not what you had in mind, and fixing that removes some more parentheses. We can remove still more parentheses after that, leading to:
```
( |^|>)
(
(((\+|00)3[12] ?(\(0\))?)|0) # International prefix or leading zero
([0-9]{2}-? ?[0-9]{7}) | # xx-xxxxxxx
([0-9]{3}-? ?[0-9]{6}) | # xxx-xxxxxx
([0-9]{1}-? ?[0-9]{8}) # x-xxxxxxxx
)
( |$|<)
```
And you can work out further optimizations from here, I'd hope.
|
268,778 |
<p>I have a class called EventConsumer which defines an event EventConsumed and a method OnEventConsumed as follows:</p>
<pre><code>public event EventHandler EventConsumed;
public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
</code></pre>
<p>I need to add attributes to the at OnEventConsumed runtime, so I'm generating a subclass using System.Reflection.Emit. What I want is the MSIL equivalent of this:</p>
<pre><code>public override void OnEventConsumed(object sender, EventArgs e)
{
base.OnEventConsumed(sender, e);
}
</code></pre>
<p>What I have so far is this:</p>
<pre><code>...
MethodInfo baseMethod = typeof(EventConsumer).GetMethod("OnEventConsumed");
MethodBuilder methodBuilder = typeBuilder.DefineMethod("OnEventConsumed",
baseMethod.Attributes,
baseMethod.CallingConvention,
typeof(void),
new Type[] {typeof(object),
typeof(EventArgs)});
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
// load the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
// call the base method
ilGenerator.EmitCall(OpCodes.Callvirt, baseMethod, new Type[0] );
// return
ilGenerator.Emit(OpCodes.Ret);
...
</code></pre>
<p>I create the type, create an instance of the type, and call its OnEventConsumed function, and I get:</p>
<pre><code>Common Language Runtime detected an invalid program.
</code></pre>
<p>...which is not exactly helpful. What am I doing wrong? What's the correct MSIL to call the base class's event handler?</p>
|
[
{
"answer_id": 268803,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>The using</p>\n\n<pre><code>public virtual void OnEventConsumed(object sender, EventArgs e)\n{\n if (EventConsumed != null)\n EventConsumed(this, e);\n}\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>public virtual void OnEventConsumed(EventArgs e)\n{\n EventHandler handler = this.EventConsumed;\n if ( null != handler ) handler( this, e );\n}\n</code></pre>\n\n<p>.</p>\n\n<p>I think, you should use a <a href=\"http://msdn.microsoft.com/en-us/library/d81ee808.aspx\" rel=\"nofollow noreferrer\">ILGenerator.EmitCalli</a> and you should pass a type of return value ( i think null in this case ) and pass the types of arguments - i think \"new Type[]{ typeof(EventArgs)}</p>\n"
},
{
"answer_id": 268821,
"author": "Simon",
"author_id": 15371,
"author_profile": "https://Stackoverflow.com/users/15371",
"pm_score": 1,
"selected": false,
"text": "<p>I was actually really close - the problem was that I wasn't loading the 'this' argument, and that Callvirt calls the subclass method, where I actually wanted Call. So that section becomes:</p>\n\n<pre><code>// load 'this' and the first two args onto the stack\nilGenerator.Emit(OpCodes.Ldarg_0);\nilGenerator.Emit(OpCodes.Ldarg_1);\nilGenerator.Emit(OpCodes.Ldarg_2);\n\n// call the base method\nilGenerator.EmitCall(OpCodes.Call, baseMethod, new Type[0] );\n\n// return\nilGenerator.Emit(OpCodes.Ret);\n</code></pre>\n\n<p>Now it works fine.</p>\n"
},
{
"answer_id": 268829,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 4,
"selected": true,
"text": "<p>Here's the IL from a sample app:</p>\n\n<pre><code>\n.method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed\n {\n .maxstack 8\n L_0000: nop \n L_0001: ldarg.0 \n L_0002: ldarg.1 \n L_0003: ldarg.2 \n L_0004: call instance void SubclassSpike.BaseClass::OnEventConsumed(object, class [mscorlib]System.EventArgs)\n L_0009: nop \n L_000a: ret \n }\n</code></pre>\n\n<p>So I think you aren't loading the instance because you aren't doing a ldarg.0</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
I have a class called EventConsumer which defines an event EventConsumed and a method OnEventConsumed as follows:
```
public event EventHandler EventConsumed;
public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
```
I need to add attributes to the at OnEventConsumed runtime, so I'm generating a subclass using System.Reflection.Emit. What I want is the MSIL equivalent of this:
```
public override void OnEventConsumed(object sender, EventArgs e)
{
base.OnEventConsumed(sender, e);
}
```
What I have so far is this:
```
...
MethodInfo baseMethod = typeof(EventConsumer).GetMethod("OnEventConsumed");
MethodBuilder methodBuilder = typeBuilder.DefineMethod("OnEventConsumed",
baseMethod.Attributes,
baseMethod.CallingConvention,
typeof(void),
new Type[] {typeof(object),
typeof(EventArgs)});
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
// load the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
// call the base method
ilGenerator.EmitCall(OpCodes.Callvirt, baseMethod, new Type[0] );
// return
ilGenerator.Emit(OpCodes.Ret);
...
```
I create the type, create an instance of the type, and call its OnEventConsumed function, and I get:
```
Common Language Runtime detected an invalid program.
```
...which is not exactly helpful. What am I doing wrong? What's the correct MSIL to call the base class's event handler?
|
Here's the IL from a sample app:
```
.method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldarg.1
L_0003: ldarg.2
L_0004: call instance void SubclassSpike.BaseClass::OnEventConsumed(object, class [mscorlib]System.EventArgs)
L_0009: nop
L_000a: ret
}
```
So I think you aren't loading the instance because you aren't doing a ldarg.0
|
268,792 |
<p>I have a class <code>isSearching</code> with a single boolean property in a 'functions' file in my webapp. On my search page, I have a variable <code>oSearchHandler</code> declared as a <code>Public Shared</code> variable. How can I access the contents of <code>oSearchHandler</code> on other pages in my webapp?</p>
<p>Code with Session....</p>
<pre><code>'search.aspx
Public Function oSearchString(ByVal oTextBoxName As String) As String
For Each oKey As String In Request.Form.AllKeys
If oKey.Contains(oTextBoxName) Then
Session.Add("searching", True)
Session.Add("search-term", Request.Form(oKey))
Return Request.Form(oKey)
End If
Next
Return ""
End Function
'theMaster.master
<%
If Session("searching") Then
%><ul style="float: right;">
<li>
<div class="gsSearch">
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</div>
</li>
<li>
<div class="gsSearch">
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="true" PostBackUrl="search.aspx" CssClass="searchBtn" />
</div>
</li>
</ul>
<%
End If
%>
</code></pre>
<p>I think that the session will work just fine.</p>
|
[
{
"answer_id": 268811,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<p>You probably need a table say tblItems that simply store all the primary keys of the two tables. Inserting items would require two steps to ensure that when an item is entered into the tblSystemItems table that the PK is entered into the tblItems table.</p>\n\n<p>The third table then has a FK to tblItems. In a way tblItems is a parent of the other two items tables. To query for an Item it would be necessary to create a JOIN between tblItems, tblSystemItems and tblClientItems.</p>\n\n<p>[EDIT-for comment below] If the tblSystemItems and tblClientItems control their own PK then you can still let them. You would probably insert into tblSystemItems first then insert into tblItems. When you implement an inheritance structure using a tool like Hibernate you end up with something like this.</p>\n"
},
{
"answer_id": 268838,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 0,
"selected": false,
"text": "<p>You can create a unique id (db generated - sequence, autoinc, etc) for the table that references items, and create two additional columns (<strong>tblSystemItemsFK</strong> and <strong>tblClientItemsFk</strong>) where you reference the system items and client items respectively - <em>some</em> databases allows you to have a foreign key that is <em>nullable</em>.</p>\n\n<p>If you're using an ORM you can even easily distinguish client items and system items (this way you don't need to negative identifiers to prevent ID overlap) based on column information only.</p>\n\n<p>With a little more bakcground/context it is probably easier to determine an optimal solution.</p>\n"
},
{
"answer_id": 268962,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": "<p>Add a table called Items with a PK ItemiD, And a single column called ItemType = \"System\" or \"Client\" then have ClientItems table PK (named ClientItemId) and SystemItems PK (named SystemItemId) both also be FKs to Items.ItemId, (These relationships are zero to one relationships (0-1)</p>\n\n<p>Then in your third table that references an item, just have it's FK constraint reference the itemId in this extra (Items) table... </p>\n\n<p>If you are using stored procedures to implement inserts, just have the stored proc that inserts items insert a new record into the Items table first, and then, using the auto-generated PK value in that table insert the actual data record into either SystemItems or ClientItems (depending on which it is) as part of the same stored proc call, using the auto-generated (identity) value that the system inserted into the Items table ItemId column. </p>\n\n<p>This is called \"SubClassing\"</p>\n"
},
{
"answer_id": 270028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've been puzzling over your table design. I'm not certain that it is right. I realise that the third table may just be providing detail information, but I can't help thinking that the primary key is actually the one in your ITEM table and the FOREIGN keys are the ones in your system and client item tables. You'd then just need to do right outer joins from Item to the system and client item tables, and all constraints would work fine.</p>\n"
},
{
"answer_id": 279103,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 2,
"selected": true,
"text": "<p>sorry for the late answer, I've been struck with a serious case of weekenditis.</p>\n\n<p>As for utilizing a third table to include PKs from both client and system tables - I don't like that as that just overly complicates synchronization and still requires my app to know of the third table.</p>\n\n<p>Another issue that has arisen is that I have a third table that needs to reference an item - either system or client, it doesn't matter. Having the tables separated basically means I need to have two columns, a ClientItemID and a SystemItemID, each having a constraint for each of their tables with nullability - rather ugly.</p>\n\n<p>I ended up choosing a different solution. The whole issue was with easily synchronizing new system items into the tables without messing with client items, avoiding collisions and so forth.</p>\n\n<p>I ended up creating just a single table, Items. Items has a bit column named \"SystemItem\" that defines, well, the obvious. In my development / system database, I've got the PK as an int identity(1,1). After the table has been created in the client database, the identity key is changed to (-1,-1). That means client items go in the negative while system items go in the positive.</p>\n\n<p>For synchronizations I basically ignore anything with (SystemItem = 1) while synchronizing the rest using IDENTITY INSERT ON. Thus I'm able to synchronize while completely ignoring client items and avoiding collisions. I'm also able to reference just one \"Items\" table which covers both client and system items. The only thing to keep in mind is to fix the standard clustered key so it's descending to avoid all kinds of page restructuring when the client inserts new items (client updates vs system updates is like 99%/1%).</p>\n"
},
{
"answer_id": 280039,
"author": "Mike Shepard",
"author_id": 36429,
"author_profile": "https://Stackoverflow.com/users/36429",
"pm_score": 0,
"selected": false,
"text": "<p>I have a similar situation in a database I'm using. I have a \"candidate key\" on each table that I call EntityID. Then, if there's a table that needs to refer to items in more than one of the other tables, I use EntityID to refer to that row. I do have an Entity table to cross reference everything (so that EntityID is the primary key of the Entity table, and all other EntityID's are FKs), but I don't find myself using the Entity table very often.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
I have a class `isSearching` with a single boolean property in a 'functions' file in my webapp. On my search page, I have a variable `oSearchHandler` declared as a `Public Shared` variable. How can I access the contents of `oSearchHandler` on other pages in my webapp?
Code with Session....
```
'search.aspx
Public Function oSearchString(ByVal oTextBoxName As String) As String
For Each oKey As String In Request.Form.AllKeys
If oKey.Contains(oTextBoxName) Then
Session.Add("searching", True)
Session.Add("search-term", Request.Form(oKey))
Return Request.Form(oKey)
End If
Next
Return ""
End Function
'theMaster.master
<%
If Session("searching") Then
%><ul style="float: right;">
<li>
<div class="gsSearch">
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</div>
</li>
<li>
<div class="gsSearch">
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="true" PostBackUrl="search.aspx" CssClass="searchBtn" />
</div>
</li>
</ul>
<%
End If
%>
```
I think that the session will work just fine.
|
sorry for the late answer, I've been struck with a serious case of weekenditis.
As for utilizing a third table to include PKs from both client and system tables - I don't like that as that just overly complicates synchronization and still requires my app to know of the third table.
Another issue that has arisen is that I have a third table that needs to reference an item - either system or client, it doesn't matter. Having the tables separated basically means I need to have two columns, a ClientItemID and a SystemItemID, each having a constraint for each of their tables with nullability - rather ugly.
I ended up choosing a different solution. The whole issue was with easily synchronizing new system items into the tables without messing with client items, avoiding collisions and so forth.
I ended up creating just a single table, Items. Items has a bit column named "SystemItem" that defines, well, the obvious. In my development / system database, I've got the PK as an int identity(1,1). After the table has been created in the client database, the identity key is changed to (-1,-1). That means client items go in the negative while system items go in the positive.
For synchronizations I basically ignore anything with (SystemItem = 1) while synchronizing the rest using IDENTITY INSERT ON. Thus I'm able to synchronize while completely ignoring client items and avoiding collisions. I'm also able to reference just one "Items" table which covers both client and system items. The only thing to keep in mind is to fix the standard clustered key so it's descending to avoid all kinds of page restructuring when the client inserts new items (client updates vs system updates is like 99%/1%).
|
268,802 |
<p>In my Silverlight app I want a multi-line text box to expand every time the user hits Enter.</p>
<p>The difficult part is how to calculate the correct height based on the number of text lines.</p>
<p>I have tried the following but the textbox becomes too small:</p>
<pre><code>box.Height = box.FontSize*lineCount + box.Padding.Top + box.Padding.Bottom + box.BorderThickness.Top + box.BorderThickness.Bottom;
</code></pre>
<p>What am I missing here? Or maybe it can be done automatically somehow?</p>
<p>Thanks,
Jacob</p>
<p><strong>Edit:</strong> I suspect the problem to be in the FontSize property (does it use another size unit?)</p>
|
[
{
"answer_id": 279606,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 2,
"selected": false,
"text": "<p>This seems to be how the textbox works out of the box. Just make sure you set the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.acceptsreturn(VS.95).aspx\" rel=\"nofollow noreferrer\">AcceptsReturn</a>=\"True\" on the textbox. Also make sure you don't set the height of the Textbox so that it is calculated for you.</p>\n"
},
{
"answer_id": 2683688,
"author": "Mike Blandford",
"author_id": 28643,
"author_profile": "https://Stackoverflow.com/users/28643",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>TextBox</code> will fire a <code>SizeChanged</code> event, and it will also set the <code>ActualHeight</code> property. </p>\n\n<p>I don't think this was the case in Silverlight 2, when I had to use a <code>TextBlock</code> with the same font, set the padding to 4, and set the same text, and get the <code>ActualHeight</code> off that.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30056/"
] |
In my Silverlight app I want a multi-line text box to expand every time the user hits Enter.
The difficult part is how to calculate the correct height based on the number of text lines.
I have tried the following but the textbox becomes too small:
```
box.Height = box.FontSize*lineCount + box.Padding.Top + box.Padding.Bottom + box.BorderThickness.Top + box.BorderThickness.Bottom;
```
What am I missing here? Or maybe it can be done automatically somehow?
Thanks,
Jacob
**Edit:** I suspect the problem to be in the FontSize property (does it use another size unit?)
|
This seems to be how the textbox works out of the box. Just make sure you set the [AcceptsReturn](http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.acceptsreturn(VS.95).aspx)="True" on the textbox. Also make sure you don't set the height of the Textbox so that it is calculated for you.
|
268,808 |
<p>I have a need to determine what security group(s) a user is a member of from within a SQL Server Reporting Services report. Access to the report will be driven by membership to one of two groups: 'report_name_summary' and 'report_name_detail'. Once the user is executing the report, we want to be able to use their membership (or lack of membership) in the 'report_name_detail' group to determine whether or not a "drill down" should be allowed.</p>
<p>I don't know of any way out of the box to access the current user's AD security group membership, but am open to any suggestions for being able to access this info from within the report.</p>
|
[
{
"answer_id": 285601,
"author": "PJ8",
"author_id": 35490,
"author_profile": "https://Stackoverflow.com/users/35490",
"pm_score": 4,
"selected": true,
"text": "<p>You can add custom code to a report. <a href=\"http://msdn.microsoft.com/en-us/library/ms155798.aspx\" rel=\"noreferrer\">This link</a> has some examples.</p>\n\n<p>Theoretically, you should be able to write some code like this, and then use the return value to show/hide what you want. You may have permissions problems with this method, though.</p>\n\n<pre><code>Public Function ShouldReportBeHidden() As Boolean\nDim Principal As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())\nIf (Principal.IsInRole(\"MyADGroup\")) Then\n Return False\nElse\n Return True\nEnd If\nEnd Function\n</code></pre>\n\n<p><strong>Alternatively</strong>, you could add your detail report as a subreport of your summary report. Then you could use the security functionality built in to SSRS to restrict access to your sub report.</p>\n"
},
{
"answer_id": 18133807,
"author": "Ralph177",
"author_id": 315641,
"author_profile": "https://Stackoverflow.com/users/315641",
"pm_score": 1,
"selected": false,
"text": "<p>In Reporting Services just use :</p>\n\n<pre><code>Public Function IsMemberOfGroup() As Boolean\n\nIf System.Threading.Thread.CurrentPrincipal.IsInRole(\"MyADGroup\") Then\n Return True\nElse\n Return False\nEnd If\n\nEnd Function\n</code></pre>\n\n<p>as indicated in <a href=\"https://stackoverflow.com/questions/3095449/ssrs-windowsidentity-getcurrent-giving-me-nt-authority-network-service\">this posting</a></p>\n\n<p><em>Note: This works once the report is deployed to server but not in the IDE.</em></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1680/"
] |
I have a need to determine what security group(s) a user is a member of from within a SQL Server Reporting Services report. Access to the report will be driven by membership to one of two groups: 'report\_name\_summary' and 'report\_name\_detail'. Once the user is executing the report, we want to be able to use their membership (or lack of membership) in the 'report\_name\_detail' group to determine whether or not a "drill down" should be allowed.
I don't know of any way out of the box to access the current user's AD security group membership, but am open to any suggestions for being able to access this info from within the report.
|
You can add custom code to a report. [This link](http://msdn.microsoft.com/en-us/library/ms155798.aspx) has some examples.
Theoretically, you should be able to write some code like this, and then use the return value to show/hide what you want. You may have permissions problems with this method, though.
```
Public Function ShouldReportBeHidden() As Boolean
Dim Principal As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())
If (Principal.IsInRole("MyADGroup")) Then
Return False
Else
Return True
End If
End Function
```
**Alternatively**, you could add your detail report as a subreport of your summary report. Then you could use the security functionality built in to SSRS to restrict access to your sub report.
|
268,814 |
<p>Consider this:</p>
<pre><code>public class TestClass {
private String a;
private String b;
public TestClass()
{
a = "initialized";
}
public void doSomething()
{
String c;
a.notify(); // This is fine
b.notify(); // This is fine - but will end in an exception
c.notify(); // "Local variable c may not have been initialised"
}
}
</code></pre>
<p>I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?</p>
<p><strong>Edit</strong>: making the members private was my initial intention, and the question still stands...</p>
|
[
{
"answer_id": 268825,
"author": "user35094",
"author_id": 35094,
"author_profile": "https://Stackoverflow.com/users/35094",
"pm_score": 2,
"selected": false,
"text": "<p>The compiler can figure out that c will never be set. The b variable could be set by someone else after the constructor is called, but before doSomething(). Make b private and the compiler may be able to help.</p>\n"
},
{
"answer_id": 268834,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>The compiler can tell from the code for doSomething() that c is declared there and never initialized. Because it is local, there is no possibility that it is initialized elsewhere.</p>\n\n<p>It can't tell when or where you are going to call doSomething(). b is a public member. It is entirely possible that you would initialize it in other code before calling the method.</p>\n"
},
{
"answer_id": 268848,
"author": "jcoder",
"author_id": 417292,
"author_profile": "https://Stackoverflow.com/users/417292",
"pm_score": 5,
"selected": false,
"text": "<p>The language defines it this way.</p>\n<p>Instance variables of object type default to being initialized to null.\nLocal variables of object type are not initialized by default and it's a compile time error to access an undefined variable.</p>\n<p>See section 4.12.5 for SE7 (same section still as of SE14)\n<a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5\" rel=\"nofollow noreferrer\">http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5</a></p>\n"
},
{
"answer_id": 268909,
"author": "Yuval",
"author_id": 2819,
"author_profile": "https://Stackoverflow.com/users/2819",
"pm_score": 5,
"selected": false,
"text": "<p>Here's the deal. When you call</p>\n<pre><code>TestClass tc = new TestClass();\n</code></pre>\n<p>the <code>new</code> command performs four important tasks:</p>\n<ol>\n<li>Allocates memory on the heap for the new object.</li>\n<li>Initiates the class fields to their default values (numerics to 0, boolean to <code>false</code>, objects to <code>null</code>).</li>\n<li>Calls the constructor (which may re-initiate the fields, or may not).</li>\n<li>Returns a reference to the new object.</li>\n</ol>\n<p>So your fields 'a' and 'b' are both initiated to <code>null</code>, and 'a' is re-initiated in the constructor. This process is not relevant for method calling, so local variable 'c' is <em>never</em> initialized.</p>\n<p>For the gravely insomniac, read <a href=\"http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44670\" rel=\"nofollow noreferrer\">this</a>.</p>\n"
},
{
"answer_id": 269234,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 5,
"selected": true,
"text": "<p>The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised.</p>\n"
},
{
"answer_id": 10151727,
"author": "kazinix",
"author_id": 724689,
"author_profile": "https://Stackoverflow.com/users/724689",
"pm_score": 2,
"selected": false,
"text": "<p>Member-variables are initialized to null or to their default primitive values, if they are primitives.</p>\n\n<p>Local variables are UNDEFINED and are not initialized and you are responsible for setting the initial value. The compiler prevents you from using them.</p>\n\n<p>Therefore, b is initialized when the class TestClass is instantiated while c is undefined.</p>\n\n<p>Note: null is different from undefined.</p>\n"
},
{
"answer_id": 41881281,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 1,
"selected": false,
"text": "<p>You've actually identified one of the bigger holes in Java's system of generally attempting to find errors at edit/compile time rather than run time because--as the accepted answer said--it's difficult to tell if b is initialized or not.</p>\n\n<p>There are a few patterns to work around this flaw. First is \"Final by default\". If your members were final, you would have to fill them in with the constructor--and it would use path-analysis to ensure that every possible path fills in the finals (You could still assign it \"Null\" which would defeat the purpose but at least you would be forced to recognize that you were doing it intentionally).</p>\n\n<p>A second approach is strict null checking. You can turn it on in eclipse settings either by project or in default properties. I believe it would force you to null-check your b.notify() before you call it. This can quickly get out of hand so it tends to go with a set of annotations to make things simpler:</p>\n\n<p>The annotations might have different names but in concept once you turn on strict null checking and the annotations the types of variables are \"nullable\" and \"NotNull\". If you try to place a Nullable into a not-null variable you must check it for null first. Parameters and return types are also annotated so you don't have to check for null every single time you assign to a not-null variable.</p>\n\n<p>There is also a \"NotNullByDefault\" package level annotation that will make the editor assume that no variable can ever have a null value unless you tag it Nullable.</p>\n\n<p>These annotations mostly apply at the editor level--You can turn them on within eclipse and probably other editors--which is why they aren't necessarily standardized. (At least last time I check, Java 8 might have some annotations I haven't found yet)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24545/"
] |
Consider this:
```
public class TestClass {
private String a;
private String b;
public TestClass()
{
a = "initialized";
}
public void doSomething()
{
String c;
a.notify(); // This is fine
b.notify(); // This is fine - but will end in an exception
c.notify(); // "Local variable c may not have been initialised"
}
}
```
I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?
**Edit**: making the members private was my initial intention, and the question still stands...
|
The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised.
|
268,820 |
<p>I have a servlet that I would like to run within ColdFusion MX 7. I would like to make use of an existing ColdFusion DSN as a javax.sql.DataSource, if possible.</p>
<p>I thought something like </p>
<pre><code>coldfusion.server.ServiceFactory.getDataSourceService().getDatasource(dsname);
</code></pre>
<p>would work, but unfortunately the servlet returns</p>
<pre><code>java.lang.NoClassDefFoundError: coldfusion/server/ServiceFactory
</code></pre>
|
[
{
"answer_id": 268912,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 1,
"selected": false,
"text": "<p>That code will work fine, you just don't have ServiceFactory in your classpath. Ie, Java can't load that class. Try including a dependency on cfusion.jar from C:\\CFusionMX7\\lib.</p>\n"
},
{
"answer_id": 272072,
"author": "AlexJReid",
"author_id": 32320,
"author_profile": "https://Stackoverflow.com/users/32320",
"pm_score": 1,
"selected": true,
"text": "<p>It seems the simplest way to do this is to add an additional JNDI datasource into jrun-resources.xml. This can then be accessed in the conventional way:</p>\n\n<pre><code>Context context = new InitialContext();\nDataSource ds = (DataSource)context.lookup(\"mydatasource\"); \n</code></pre>\n\n<p>It does mean duplicating database connection configuration, but I would rather do this than work with the largely undocumented coldfusion.server.* classes. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32320/"
] |
I have a servlet that I would like to run within ColdFusion MX 7. I would like to make use of an existing ColdFusion DSN as a javax.sql.DataSource, if possible.
I thought something like
```
coldfusion.server.ServiceFactory.getDataSourceService().getDatasource(dsname);
```
would work, but unfortunately the servlet returns
```
java.lang.NoClassDefFoundError: coldfusion/server/ServiceFactory
```
|
It seems the simplest way to do this is to add an additional JNDI datasource into jrun-resources.xml. This can then be accessed in the conventional way:
```
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("mydatasource");
```
It does mean duplicating database connection configuration, but I would rather do this than work with the largely undocumented coldfusion.server.\* classes.
|
268,824 |
<p>We're working now on the design of a new API for our product, which will be exposed via web services. We have a dispute whether we should use strict parameters with well defined types (my opinion) or strings that will contain XML in whatever structure needed. It is quite obvious that ideally using a strict signature is safer, and it will allow our users to use tools like wsdl2java. OTOH, our product is developing rapidly, and if the parameters of a service will have to be changed, using XML (passed as a string or anyType - not complex type, which is well defined type) will not require the change of the interface.</p>
<p>So, what I'm asking for is basically rule of thumb recommendations - would you prefer using strict types or flexible XML? Have you had any significant problems using either way?</p>
<p>Thanks,
Eran</p>
|
[
{
"answer_id": 268912,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 1,
"selected": false,
"text": "<p>That code will work fine, you just don't have ServiceFactory in your classpath. Ie, Java can't load that class. Try including a dependency on cfusion.jar from C:\\CFusionMX7\\lib.</p>\n"
},
{
"answer_id": 272072,
"author": "AlexJReid",
"author_id": 32320,
"author_profile": "https://Stackoverflow.com/users/32320",
"pm_score": 1,
"selected": true,
"text": "<p>It seems the simplest way to do this is to add an additional JNDI datasource into jrun-resources.xml. This can then be accessed in the conventional way:</p>\n\n<pre><code>Context context = new InitialContext();\nDataSource ds = (DataSource)context.lookup(\"mydatasource\"); \n</code></pre>\n\n<p>It does mean duplicating database connection configuration, but I would rather do this than work with the largely undocumented coldfusion.server.* classes. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26039/"
] |
We're working now on the design of a new API for our product, which will be exposed via web services. We have a dispute whether we should use strict parameters with well defined types (my opinion) or strings that will contain XML in whatever structure needed. It is quite obvious that ideally using a strict signature is safer, and it will allow our users to use tools like wsdl2java. OTOH, our product is developing rapidly, and if the parameters of a service will have to be changed, using XML (passed as a string or anyType - not complex type, which is well defined type) will not require the change of the interface.
So, what I'm asking for is basically rule of thumb recommendations - would you prefer using strict types or flexible XML? Have you had any significant problems using either way?
Thanks,
Eran
|
It seems the simplest way to do this is to add an additional JNDI datasource into jrun-resources.xml. This can then be accessed in the conventional way:
```
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("mydatasource");
```
It does mean duplicating database connection configuration, but I would rather do this than work with the largely undocumented coldfusion.server.\* classes.
|
268,835 |
<p>I am new to Hibernate and attempting to run a java/spring example that retrieves data from a table in MS SqlServer. Everytime I try to run the program, the data source loads ok. But when spring tries to load the session facotry it gets the following error:</p>
<pre><code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in class path resource [ml/spring/src/applicationContext.xml]:
Instantiation of bean failed; nested exception is
java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Caused by: java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
</code></pre>
<p>Below is the application Context file I am using:</p>
<pre><code><!-- Data source bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName">
<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value></property>
<property name="url">
<value>jdbc:microsoft:sqlserver://machine:port</value></property>
<property name="username"><value>user</value></property>
<property name="password"><value>password</value></property>
</bean>
<!-- Session Factory Bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>authors.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=net.sf.hibernate.dialect.SQLServerDialect
</value>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</code></pre>
|
[
{
"answer_id": 268883,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": false,
"text": "<p>You are missing a JAR file containing the JTA API classes. You probably have one already when you downloaded Hibernate. It should be called something like:</p>\n\n<pre><code>jta-1.1.jar\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 43872451,
"author": "Georgios Syngouroglou",
"author_id": 1123501,
"author_profile": "https://Stackoverflow.com/users/1123501",
"pm_score": 0,
"selected": false,
"text": "<p>In case you are using maven, use <a href=\"https://mvnrepository.com/artifact/javax.transaction/jta/1.1\" rel=\"nofollow noreferrer\">this</a>,</p>\n\n<pre><code><dependency>\n <groupId>javax.transaction</groupId>\n <artifactId>jta</artifactId>\n <version>1.1</version>\n</dependency>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am new to Hibernate and attempting to run a java/spring example that retrieves data from a table in MS SqlServer. Everytime I try to run the program, the data source loads ok. But when spring tries to load the session facotry it gets the following error:
```
Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in class path resource [ml/spring/src/applicationContext.xml]:
Instantiation of bean failed; nested exception is
java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Caused by: java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
```
Below is the application Context file I am using:
```
<!-- Data source bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName">
<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value></property>
<property name="url">
<value>jdbc:microsoft:sqlserver://machine:port</value></property>
<property name="username"><value>user</value></property>
<property name="password"><value>password</value></property>
</bean>
<!-- Session Factory Bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>authors.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=net.sf.hibernate.dialect.SQLServerDialect
</value>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
```
|
You are missing a JAR file containing the JTA API classes. You probably have one already when you downloaded Hibernate. It should be called something like:
```
jta-1.1.jar
```
Hope this helps.
|
268,853 |
<p>This is just to satisfy my own curiosity.</p>
<p>Is there an implementation of this:</p>
<pre><code>float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
</code></pre>
<p>in C#? If it exists, post the code. </p>
<p>I guess I should have mentioned I was looking for a "safe" implementation... Either way, the BitConverter code solves the problem. The union idea is interesting. I'll test it and post my results.</p>
<p>Edit:
As expected, the unsafe method is the quickest, followed by using a union (inside the function), followed by the BitConverter. The functions were executed 10000000 times, and the I used the System.Diagnostics.Stopwatch class for timing. The results of the calculations are show in brackets.</p>
<pre><code>Input: 79.67
BitConverter Method: 00:00:01.2809018 (0.1120187)
Union Method: 00:00:00.6838758 (0.1120187)
Unsafe Method: 00:00:00.3376401 (0.1120187)
</code></pre>
<p>For completeness, I tested the built-in Math.Pow method, and the "naive" method (1/Sqrt(x)).</p>
<pre><code>Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
</code></pre>
<p>The difference between 1 / Math.Sqrt() is so small that I don't think one needs to resort to the Unsafe Fast InvSqrt() method in C# (or any other unsafe method). Unless one <em>really</em> needs to squeeze out that last bit of juice from the CPU... 1/Math.Sqrt() is also much more accurate.</p>
|
[
{
"answer_id": 268863,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see why it wouldn't be possible using the <strong>unsafe compiler option</strong>.</p>\n"
},
{
"answer_id": 268901,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 4,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx\" rel=\"nofollow noreferrer\">BitConverter</a> if you want to avoid unsafe code.</p>\n\n<pre><code>float InvSqrt(float x)\n{\n float xhalf = 0.5f * x;\n int i = BitConverter.SingleToInt32Bits(x);\n i = 0x5f3759df - (i >> 1);\n x = BitConverter.Int32BitsToSingle(i);\n x = x * (1.5f - xhalf * x * x);\n return x;\n}\n</code></pre>\n\n<p>The code above uses new methods introduced in .NET Core 2.0. For .NET Framework, you have to fall back to the following (which performs allocations):</p>\n\n<pre><code>float InvSqrt(float x)\n{\n float xhalf = 0.5f * x;\n int i = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);\n i = 0x5f3759df - (i >> 1);\n x = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);\n x = x * (1.5f - xhalf * x * x);\n return x;\n}\n</code></pre>\n\n<p>Otherwise, the C# code is exactly the same as the C code you gave, except that the method needs to be marked as unsafe:</p>\n\n<pre><code>unsafe float InvSqrt(float x) { ... }\n</code></pre>\n"
},
{
"answer_id": 268905,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 5,
"selected": true,
"text": "<p>You should be able to use the StructLayout and FieldOffset attributes to fake a union for plain old data like floats and ints.</p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit, Size=4)]\nprivate struct IntFloat {\n [FieldOffset(0)]\n public float floatValue;\n\n [FieldOffset(0)]\n public int intValue;\n\n // redundant assignment to avoid any complaints about uninitialized members\n IntFloat(int x) {\n floatValue = 0;\n intValue = x;\n }\n\n IntFloat(float x) { \n intValue = 0;\n floatValue = x;\n }\n\n public static explicit operator float (IntFloat x) {\n return x.floatValue;\n }\n\n public static explicit operator int (IntFloat x) { \n return x.intValue;\n }\n\n public static explicit operator IntFloat (int i) {\n return new IntFloat(i);\n }\n public static explicit operator IntFloat (float f) { \n return new IntFloat(f);\n }\n}\n</code></pre>\n\n<p>Then translating InvSqrt is easy.</p>\n"
},
{
"answer_id": 268933,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 3,
"selected": false,
"text": "<p>Definitely possible in unsafe mode. Note that even though in the Quake 3 source code the constant <code>0x5f3759df</code> was used, <a href=\"http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf\" rel=\"noreferrer\">numerical research showed</a> that the constant <code>0x5f375a86</code> actually yields better results for Newton Approximations.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
This is just to satisfy my own curiosity.
Is there an implementation of this:
```
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
```
in C#? If it exists, post the code.
I guess I should have mentioned I was looking for a "safe" implementation... Either way, the BitConverter code solves the problem. The union idea is interesting. I'll test it and post my results.
Edit:
As expected, the unsafe method is the quickest, followed by using a union (inside the function), followed by the BitConverter. The functions were executed 10000000 times, and the I used the System.Diagnostics.Stopwatch class for timing. The results of the calculations are show in brackets.
```
Input: 79.67
BitConverter Method: 00:00:01.2809018 (0.1120187)
Union Method: 00:00:00.6838758 (0.1120187)
Unsafe Method: 00:00:00.3376401 (0.1120187)
```
For completeness, I tested the built-in Math.Pow method, and the "naive" method (1/Sqrt(x)).
```
Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
```
The difference between 1 / Math.Sqrt() is so small that I don't think one needs to resort to the Unsafe Fast InvSqrt() method in C# (or any other unsafe method). Unless one *really* needs to squeeze out that last bit of juice from the CPU... 1/Math.Sqrt() is also much more accurate.
|
You should be able to use the StructLayout and FieldOffset attributes to fake a union for plain old data like floats and ints.
```
[StructLayout(LayoutKind.Explicit, Size=4)]
private struct IntFloat {
[FieldOffset(0)]
public float floatValue;
[FieldOffset(0)]
public int intValue;
// redundant assignment to avoid any complaints about uninitialized members
IntFloat(int x) {
floatValue = 0;
intValue = x;
}
IntFloat(float x) {
intValue = 0;
floatValue = x;
}
public static explicit operator float (IntFloat x) {
return x.floatValue;
}
public static explicit operator int (IntFloat x) {
return x.intValue;
}
public static explicit operator IntFloat (int i) {
return new IntFloat(i);
}
public static explicit operator IntFloat (float f) {
return new IntFloat(f);
}
}
```
Then translating InvSqrt is easy.
|
268,884 |
<p>I am trying to convert an access datetime field to a mysdl format, using the following string:</p>
<pre><code>select str_to_date('04/03/1974 12:21:22', '%Y %m %d %T');
</code></pre>
<p>While I do not get an error, I do not get the expected result, instead I get this:</p>
<pre><code>+---------------------------------------------------+
| str_to_date('04/03/1974 12:21:22', '%Y %m %d %T') |
+---------------------------------------------------+
| NULL |
+---------------------------------------------------+
1 row in set, 1 warning (0.01 sec)
</code></pre>
<p>The access dates are in this format:</p>
<pre><code>06.10.2008 14:19:08
</code></pre>
<p>I am not sure what I am missing.</p>
<p>As a side question, I am wondering if it is possible when importing a csv file to change the data in a column before? I want to replace the insert_date and update_date fields with my own dates, and I am not sure if it would be easier to do this before importing or after.</p>
<p>Many thanks for assistance.</p>
|
[
{
"answer_id": 268932,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "<p>First things first, the str_to_date shown doesn't work because the format doesn't match the string. '%Y %m %d %T' would work if the date was something like '1974 04 03 12:21:22'</p>\n\n<p>The correct format should be '%m/%d/%Y %T' (month/day/year time). or '%d/%m/%Y %T' (day/month/year time).</p>\n\n<p>As for access, it looks liks changing the above to use . where the / is should work.</p>\n"
},
{
"answer_id": 268942,
"author": "andyhky",
"author_id": 2764,
"author_profile": "https://Stackoverflow.com/users/2764",
"pm_score": 3,
"selected": true,
"text": "<p>Your syntax for the function is off.</p>\n\n<p>Try:</p>\n\n<pre><code>select str_to_date('04/03/1974 12:21:22', '%m/%d/%Y %T');\n</code></pre>\n\n<p>The second parameter is telling the function where the parts of the dates are located in your string.</p>\n\n<p>For your access question:</p>\n\n<pre><code>select str_to_date('06.10.2008 14:19:08', '%m.%d.%Y %T');\n</code></pre>\n"
},
{
"answer_id": 274306,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 0,
"selected": false,
"text": "<p>It's not clear to me which end of this you're using, the Access end or the MySQL end, though it looks like you are trying to solve it with MySQL's functions. If your problem is that you've exported CSV from Access/Jet and it's not in the expected format, then maybe you need to fix the CSV export from Access to use a format that MySQL understands.</p>\n\n<p>If you have the ability to use the Access/Jet database, it might also be simpler to set up an ODBC DSN for your MySQL database, and then create linked tables in Access, to which you can then directly append data from the Access tables into your MySQL tables. The MyODBC driver will then take care of the data conversions for you.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
I am trying to convert an access datetime field to a mysdl format, using the following string:
```
select str_to_date('04/03/1974 12:21:22', '%Y %m %d %T');
```
While I do not get an error, I do not get the expected result, instead I get this:
```
+---------------------------------------------------+
| str_to_date('04/03/1974 12:21:22', '%Y %m %d %T') |
+---------------------------------------------------+
| NULL |
+---------------------------------------------------+
1 row in set, 1 warning (0.01 sec)
```
The access dates are in this format:
```
06.10.2008 14:19:08
```
I am not sure what I am missing.
As a side question, I am wondering if it is possible when importing a csv file to change the data in a column before? I want to replace the insert\_date and update\_date fields with my own dates, and I am not sure if it would be easier to do this before importing or after.
Many thanks for assistance.
|
Your syntax for the function is off.
Try:
```
select str_to_date('04/03/1974 12:21:22', '%m/%d/%Y %T');
```
The second parameter is telling the function where the parts of the dates are located in your string.
For your access question:
```
select str_to_date('06.10.2008 14:19:08', '%m.%d.%Y %T');
```
|
268,885 |
<p>What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ?</p>
|
[
{
"answer_id": 268888,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 6,
"selected": true,
"text": "<p>The primary key value will be in that property after the SubmitChanges().</p>\n\n<pre><code>MyTable record = new MyTable();\nrecord.Name = \"James Curran\";\ndb.MyTable.InsertOnSubmit(record);\ndb.SubmitChanges();\nConsole.WriteLine(\"record inserted as ID : {0}\", record.Id);\n</code></pre>\n"
},
{
"answer_id": 268967,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 1,
"selected": false,
"text": "<p>Any field with AutoGeneratedValue=true will be filled in after that record is submitted to the database by dc.SubmitChanges()</p>\n"
},
{
"answer_id": 11699824,
"author": "kazem",
"author_id": 787931,
"author_profile": "https://Stackoverflow.com/users/787931",
"pm_score": 3,
"selected": false,
"text": "<pre><code>// Create a new Order object.\nOrder ord = new Order\n{\n OrderID = 12000,\n ShipCity = \"Seattle\",\n OrderDate = DateTime.Now\n // …\n};\n\n// Add the new object to the Orders collection.\ndb.Orders.InsertOnSubmit(ord);\n\n// Submit the change to the database.\ntry\n{\n db.SubmitChanges();\n}\ncatch (Exception e)\n{\n Console.WriteLine(e);\n // Make some adjustments.\n // ...\n // Try again.\n db.SubmitChanges();\n}\nreturn ord.OrderID;\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26809/"
] |
What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ?
|
The primary key value will be in that property after the SubmitChanges().
```
MyTable record = new MyTable();
record.Name = "James Curran";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
Console.WriteLine("record inserted as ID : {0}", record.Id);
```
|
268,891 |
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p>
<pre><code>mydict = dict(
one=['foo', 'bar', 'foobar', 'barfoo', 'example'],
two=['bar', 'example', 'foobar'],
three=['foo', 'example'])
</code></pre>
<p>i'd like to replace all the occurrences of "example" by "someotherword". </p>
<p>While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?</p>
|
[
{
"answer_id": 269043,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": true,
"text": "<pre><code>for arr in mydict.values():\n for i, s in enumerate(arr):\n if s == 'example':\n arr[i] = 'someotherword'\n</code></pre>\n"
},
{
"answer_id": 270535,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:</p>\n\n<pre><code>replacements = {'example' : 'someotherword'}\n\nnewdict = dict((k, [replacements.get(x,x) for x in v]) \n for (k,v) in mydict.iteritems())\n</code></pre>\n\n<p>This also has the advantage that its easy to extend with new words just by adding them to the replacements dict. If you want to mutate an existing dict in place, you can use the same approach:</p>\n\n<pre><code>for l in mydict.values():\n l[:]=[replacements.get(x,x) for x in l]\n</code></pre>\n\n<p>However it's probably going to be slower than <a href=\"https://stackoverflow.com/questions/268891/replacing-multiple-occurrences-in-nested-arrays#269043\">J.F Sebastian's</a> solution, as it rebuilds the whole list rather than just modifying the changed elements in place.</p>\n"
},
{
"answer_id": 271294,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another take:</p>\n\n<pre><code>for key, val in mydict.items():\n mydict[key] = [\"someotherword\" if x == \"example\" else x for x in val]\n</code></pre>\n\n<p>I've found that building lists is <strong>very</strong> fast, but of course profile if performance is important.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35100/"
] |
I've got this python dictionary "mydict", containing arrays, here's what it looks like :
```
mydict = dict(
one=['foo', 'bar', 'foobar', 'barfoo', 'example'],
two=['bar', 'example', 'foobar'],
three=['foo', 'example'])
```
i'd like to replace all the occurrences of "example" by "someotherword".
While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?
|
```
for arr in mydict.values():
for i, s in enumerate(arr):
if s == 'example':
arr[i] = 'someotherword'
```
|
268,898 |
<h3>Duplicate:</h3>
<blockquote>
<p><a href="https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e">What happens if you call erase on a map element while iterating from begin to end</a></p>
<p><a href="https://stackoverflow.com/questions/180516/how-to-filter-items-from-a-stdmap">How to filter items from a stdmap</a><br></p>
</blockquote>
<p>I have a map <code>map1<string,vector<string>></code> i have a iterator for this map "itr".
i want to delete the entry from this map which is pointed by "itr".
i can use the function map1.erase(itr); after this line the iterator "itr" becomes invalid.
as per my requirement in my project,the iterator must point to the next element. can any body help me regerding this
thans in advance:)
santhosh</p>
|
[
{
"answer_id": 268964,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 2,
"selected": false,
"text": "<pre><code>map<...>::iterator tmp(iter++);\nmap1.erase(tmp);\n</code></pre>\n"
},
{
"answer_id": 268979,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <boost/next_prior.hpp>\n\nmap<string,vector<string> >::iterator next = boost::next(itr);\nmap1.erase(iter);\niter = next;\n</code></pre>\n"
},
{
"answer_id": 269061,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 3,
"selected": false,
"text": "<p>You can post-increment the iterator while passing it as argument to erase:</p>\n\n<pre><code>myMap.erase(itr++)\n</code></pre>\n\n<p>This way, the element that was pointed by <code>itr</code> before the erase is deleted, and the iterator is incremented to point to the next element in the map. If you're doing this in a loop, beware not to increment the iterator twice.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/180516/how-to-filter-items-from-a-stdmap#180772\">this answer</a> from a similar question, or what has been responded to <a href=\"https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e\">this question</a>.</p>\n"
},
{
"answer_id": 269717,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>Simple Answer:</p>\n\n<pre><code>map.erase(iter++); // Post increment. Increments iterator,\n // returns previous value for use in erase method\n</code></pre>\n\n<p>Asked and answered before:<br>\n<a href=\"https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e\">What happens if you call erase on a map element while iterating from begin to end</a><br>\n<a href=\"https://stackoverflow.com/questions/180516/how-to-filter-items-from-a-stdmap\">How to filter items from a stdmap</a><br></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
### Duplicate:
>
> [What happens if you call erase on a map element while iterating from begin to end](https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e)
>
>
> [How to filter items from a stdmap](https://stackoverflow.com/questions/180516/how-to-filter-items-from-a-stdmap)
>
>
>
>
I have a map `map1<string,vector<string>>` i have a iterator for this map "itr".
i want to delete the entry from this map which is pointed by "itr".
i can use the function map1.erase(itr); after this line the iterator "itr" becomes invalid.
as per my requirement in my project,the iterator must point to the next element. can any body help me regerding this
thans in advance:)
santhosh
|
You can post-increment the iterator while passing it as argument to erase:
```
myMap.erase(itr++)
```
This way, the element that was pointed by `itr` before the erase is deleted, and the iterator is incremented to point to the next element in the map. If you're doing this in a loop, beware not to increment the iterator twice.
See also [this answer](https://stackoverflow.com/questions/180516/how-to-filter-items-from-a-stdmap#180772) from a similar question, or what has been responded to [this question](https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e).
|
268,899 |
<p>Multistrings (double null-terminated string of null-separated strings) are common in the Windows API. What's a good method for converting a multistring returned from an API to a C# string collection and vice versa?</p>
<p>I'm especially interested in proper handling of character encoding (Windows XP an later).</p>
<p>The following method seems to be okay for creating a multistring, but I don't have an example of decoding a multistring.</p>
<pre><code>static string StringArrayToMultiString(
ICollection<string> stringArray
)
{
StringBuilder multiString = new StringBuilder();
if (stringArray != null)
{
foreach (string s in stringArray)
{
multiString.Append(s);
multiString.Append('\0');
}
}
return multiString.ToString();
}
</code></pre>
|
[
{
"answer_id": 268944,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "<p>This might be naïve, but how about:</p>\n\n<pre><code>static string[] MultiStringToArray(string multiString)\n{\n return multiString.TrimEnd('\\0').Split('\\0');\n}\n</code></pre>\n\n<p><strike>\nAlso - aren't you missing the final <code>\\0</code> (you state double-null-terminated) in <code>StringArrayToMultiString</code>?</strike> And it might be easier to call if the array was a <code>params string[]</code> array - something like:</p>\n\n<pre><code> static string StringArrayToMultiString(params string[] values)\n{\n if (values == null) throw new ArgumentNullException(\"values\");\n StringBuilder multiString = new StringBuilder();\n\n foreach (string s in values)\n {\n multiString.Append(s);\n multiString.Append('\\0');\n }\n return multiString.ToString();\n}\n</code></pre>\n\n<p>[edited after clarification about final \\0]</p>\n"
},
{
"answer_id": 269441,
"author": "k...m",
"author_id": 35090,
"author_profile": "https://Stackoverflow.com/users/35090",
"pm_score": 2,
"selected": false,
"text": "<p>I've tested the StringArrayToMultiString method, using the ChangeServiceConfig() function to change the dependencies of a Windows service, and it works nicely for zero, one and many strings.</p>\n\n<p>In the meantime, I've worked out a solution for decoding a multistring received from an API call. For example, the SCardListReaders() function returns a multistring of PC/SC reader names. I declared this as:</p>\n\n<pre><code>[DllImport(\"winscard.dll\", CharSet = CharSet.Auto)]\nstatic extern int SCardListReaders(\n IntPtr context,\n string groups,\n char[] readers,\n ref uint readersLen\n );\n</code></pre>\n\n<p>Note that the readers parameter, which returns the multistring, is declared as char[]. The return value is easily parsed and converted into a collection of strings:</p>\n\n<pre><code>static string[] MultiStringToArray(\n char[] multistring\n )\n{\n List<string> stringList = new List<string>();\n int i = 0;\n while (i < multistring.Length)\n {\n int j = i;\n if (multistring[j++] == '\\0') break;\n while (j < multistring.Length)\n {\n if (multistring[j++] == '\\0')\n {\n stringList.Add(new string(multistring, i, j - i - 1));\n i = j;\n break;\n }\n }\n }\n\n return stringList.ToArray();\n}\n</code></pre>\n"
},
{
"answer_id": 1457068,
"author": "David",
"author_id": 176821,
"author_profile": "https://Stackoverflow.com/users/176821",
"pm_score": 1,
"selected": false,
"text": "<p>In the MSDN documentation for RegistryKey.SetValue() and RegistryKey.GetValue(), the examples simply pass in, or cast to, string[], respectively. Is there something wrong with that?</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35090/"
] |
Multistrings (double null-terminated string of null-separated strings) are common in the Windows API. What's a good method for converting a multistring returned from an API to a C# string collection and vice versa?
I'm especially interested in proper handling of character encoding (Windows XP an later).
The following method seems to be okay for creating a multistring, but I don't have an example of decoding a multistring.
```
static string StringArrayToMultiString(
ICollection<string> stringArray
)
{
StringBuilder multiString = new StringBuilder();
if (stringArray != null)
{
foreach (string s in stringArray)
{
multiString.Append(s);
multiString.Append('\0');
}
}
return multiString.ToString();
}
```
|
This might be naïve, but how about:
```
static string[] MultiStringToArray(string multiString)
{
return multiString.TrimEnd('\0').Split('\0');
}
```
Also - aren't you missing the final `\0` (you state double-null-terminated) in `StringArrayToMultiString`? And it might be easier to call if the array was a `params string[]` array - something like:
```
static string StringArrayToMultiString(params string[] values)
{
if (values == null) throw new ArgumentNullException("values");
StringBuilder multiString = new StringBuilder();
foreach (string s in values)
{
multiString.Append(s);
multiString.Append('\0');
}
return multiString.ToString();
}
```
[edited after clarification about final \0]
|
268,902 |
<p>I have a few links that should all open in the same window or tab.
To accomplish this I've given the window a name like in this example code:</p>
<pre><code><a href="#" onClick='window.open("http://somesite.com", "mywindow", "");'>link 1</a>
<a href="#" onClick='window.open("http://someothersite.com", "mywindow", "");'>link 2</a>
</code></pre>
<p>This works OK in internet explorer, but firefox always opens a new tab/window.
Any ideas? </p>
|
[
{
"answer_id": 268951,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 4,
"selected": true,
"text": "<p>The window.open() function in Javascript is specifically designed to open a new window, please see: <a href=\"http://www.w3schools.com/HTMLDOM/met_win_open.asp\" rel=\"noreferrer\">w3schools documentation</a>. It actually sounds like IE is handling things in a non-standard way (which is hardly surprising). </p>\n\n<p>If you want to relocate the existing location to a new page using Javascript, you should look at the <a href=\"http://www.w3schools.com/HTMLDOM/met_loc_replace.asp\" rel=\"noreferrer\">location.replace()</a> function.</p>\n\n<p>Generally speaking I would recommend that you develop for Firefox and then fix for IE. Not only does Firefox offer better development tools but its implementation of W3C standards tends to be more correct.</p>\n"
},
{
"answer_id": 269039,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": false,
"text": "<p>By default FF uses a new tab if dimensions are omitted on the window.open parameters. You need to add dimensions for a new browser window.</p>\n\n<p>Try this:</p>\n\n<pre><code><a href=\"#\" onClick='window.open(\"http://somesite.com\", \"mywindow\", \"width=700\", \"height=500\");'>link 1</a>\n</code></pre>\n"
},
{
"answer_id": 269731,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": false,
"text": "<p>Actually, the W3Schools documentation linked to by <a href=\"https://stackoverflow.com/questions/268902/javascript-windowopen-strange-behavior-in-firefox#268951\">gabriel1836</a> is only a very very brief summary of functions. </p>\n\n<p>And Oddly, mozilla's own developer reference <em>CONTRADITCS</em> this logic. </p>\n\n<p><a href=\"https://developer.mozilla.org/En/DOM/Window.open\" rel=\"nofollow noreferrer\">MDC / DOM / Window.open</a></p>\n\n<blockquote>\n<pre><code>var WindowObjectReference = window.open(strUrl, \n strWindowName [, strWindowFeatures]); \n</code></pre>\n \n <p>If a window with the name\n <strong>strWindowName</strong> already exists, then,\n instead of opening a new window,\n <strong>strUrl</strong> is loaded into the existing\n window. In this case the return value\n of the method is the existing window\n and <strong>strWindowFeatures</strong> is ignored.\n Providing an empty string for <strong>strUrl</strong>\n is a way to get a reference to an open\n window by its name without changing\n the window's location. If you want to\n open a new window on every call of\n <strong>window.open()</strong>, you should use the\n special value <strong>_blank</strong> for\n <strong>strWindowName</strong>.</p>\n</blockquote>\n\n<p>However, the page also states that there are many extensions that can be installed that change this behaviour. </p>\n\n<p>So either the documentation mozilla provides for people targeting their own browser is <strong>wrong</strong> or something is odd with your test system :)</p>\n\n<p>Also, your current A-Href notation is bad for the web, and will infuriate users. </p>\n\n<pre><code> <a href=\"http://google.com\" \n onclick=\"window.open( this.href, 'windowName' ); return false\" >\n Text\n </a>\n</code></pre>\n\n<p>Is a SUBSTANTIALLY better way to do it. </p>\n\n<p>Many people will instinctively 'middle click' links they want to manually open in a new tab, and having your only href as \"#\" infuriates them to depravity. </p>\n\n<p>The \"#\" trick is a redundant and somewhat bad trick to stop the page going somewhere unintended, but this is only because of the lack of understanding of how to use <code>onclick</code> </p>\n\n<p>If you return <code><b>FALSE</b></code> from an on-click event, it will cancel the links default action ( the default action being navigating the <strong>current</strong> page away )</p>\n\n<p>Even better than this notation would be to use unintrusive javascript like so: </p>\n\n<pre><code> <a href=\"google.com\" rel=\"external\" >Text</a>\n</code></pre>\n\n<p>and later</p>\n\n<pre><code> <script type=\"text/javascript\">\n jQuery(function($){ \n $(\"a[rel*=external]\").click(function(){ \n window.open(this.href, 'newWindowName' ); \n return false; \n });\n }); \n </script>\n</code></pre>\n"
},
{
"answer_id": 1080492,
"author": "Spidey",
"author_id": 131326,
"author_profile": "https://Stackoverflow.com/users/131326",
"pm_score": 2,
"selected": false,
"text": "<p>Why don't you just use plain HTML like</p>\n\n<p><code><a href=\"http://www.google.com\" target=\"my_window_tab_frame_or_iframe\">Link</a></code></p>\n\n<p>instead of using JavaScript?</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24046/"
] |
I have a few links that should all open in the same window or tab.
To accomplish this I've given the window a name like in this example code:
```
<a href="#" onClick='window.open("http://somesite.com", "mywindow", "");'>link 1</a>
<a href="#" onClick='window.open("http://someothersite.com", "mywindow", "");'>link 2</a>
```
This works OK in internet explorer, but firefox always opens a new tab/window.
Any ideas?
|
The window.open() function in Javascript is specifically designed to open a new window, please see: [w3schools documentation](http://www.w3schools.com/HTMLDOM/met_win_open.asp). It actually sounds like IE is handling things in a non-standard way (which is hardly surprising).
If you want to relocate the existing location to a new page using Javascript, you should look at the [location.replace()](http://www.w3schools.com/HTMLDOM/met_loc_replace.asp) function.
Generally speaking I would recommend that you develop for Firefox and then fix for IE. Not only does Firefox offer better development tools but its implementation of W3C standards tends to be more correct.
|
268,923 |
<p>I'm building an application using the Supervising Controller pattern (Model View Presenter) and I am facing a difficulty. In my page I have a repeater control that will display each item of a collection I am passing to it. The reapeater item contains 2 dropdown list that allow the user to select a particular value. When I click the next button, I want the controller to retrieve those values. </p>
<p>How can I do that I a clean way? </p>
|
[
{
"answer_id": 269040,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>When controller-view interation get's too complex I usually split them up into subcontrollers and subviews.</p>\n\n<p>You can have the items in the repeater be user-controls that have their own views and controllers. Your main view can then have a list of subviews(usercontrols) that have their own controllers that are maintained by the main controller.</p>\n\n<p>When the user clicks next your main controller can signal all the subcontrollers to refresh their items from their views.</p>\n"
},
{
"answer_id": 1152483,
"author": "Berryl",
"author_id": 95245,
"author_profile": "https://Stackoverflow.com/users/95245",
"pm_score": 3,
"selected": true,
"text": "<p>You can also make a 'widget' interface for the drop down. I'll give you an easy example of a some working code for a TextBox widget so you get the idea.</p>\n\n<pre><code>public interface ITextWidget\n{\n event EventHandler TextChanged;\n string Text { get; set; }\n}\n\npublic abstract class TextWidget<T> : ITextWidget\n{\n\n protected T _wrappedWidget { get; set; }\n public event EventHandler TextChanged;\n\n protected void InvokeTextChanged(object sender, EventArgs e)\n {\n var textChanged = TextChanged;\n if (textChanged != null) textChanged(this, e);\n }\n\n public abstract string Text { get; set; }\n}\n</code></pre>\n\n<p>Notice that so far everything is technology agnostic. Now here's an implementation for a Win Forms TextBox:</p>\n\n<pre><code>public class TextBoxWidget : TextWidget<TextBox>\n{\n\n public TextBoxWidget(TextBox textBox)\n {\n textBox.TextChanged += InvokeTextChanged;\n _wrappedWidget = textBox;\n }\n\n public override string Text\n {\n get { return _wrappedWidget.Text; }\n set { _wrappedWidget.Text = value; }\n }\n}\n</code></pre>\n\n<p>This gets instantiated in the Form itself, which back to MVP is also the IViewWhatever:</p>\n\n<pre><code>public partial class ProjectPickerForm : Form, IProjectPickerView\n{\n\n private IProjectPickerPresenter _presenter;\n public void InitializePresenter(IProjectPickerPresenter presenter) {\n _presenter = presenter;\n _presenter.InitializeWidgets(\n ...\n new TextBoxWidget(txtDescription));\n }\n ...\n}\n</code></pre>\n\n<p>And in the Presenter:</p>\n\n<pre><code>public class ProjectPickerPresenter : IProjectPickerPresenter\n{\n ...\n public void InitializeWidgets(ITextWidget descriptionFilter) {\n\n Check.RequireNotNull<ITextWidget>(descriptionFilter, \"descriptionFilter\");\n DescriptionFilter = descriptionFilter;\n DescriptionFilter.Text = string.Empty;\n DescriptionFilter.TextChanged += OnDescriptionTextChanged;\n\n }\n ...\n\n public void OnDescriptionTextChanged(object sender, EventArgs e) {\n FilterService.DescriptionFilterValue = DescriptionFilter.Text;\n }\n</code></pre>\n\n<p>It's looks worse than it is to setup because most of the work is fairly mechanical once you get the idea. The clean part is that the presenter can get (and set) whatever info it needs on the widget without knowing or caring what the actual implemented widget is. It also lends itself to reuse with other widgets (you wind up building a library of them) of the same type (Win Forms here) and in other UI technologies as needed (once you have the interface / base class the implementation in another technology is trivial). It also is easy to test with mock objects because you have the interface. And your UI is now wonderfully ignorant of just about everything but UI related tasks. The downside is the bunch of classes per widget and a little learning curve to get comfortable with it.</p>\n\n<p>For your drop down, your might just need the SelectedIndexChanged type event, which you'd substitute for this examples TextChanged event.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201997/"
] |
I'm building an application using the Supervising Controller pattern (Model View Presenter) and I am facing a difficulty. In my page I have a repeater control that will display each item of a collection I am passing to it. The reapeater item contains 2 dropdown list that allow the user to select a particular value. When I click the next button, I want the controller to retrieve those values.
How can I do that I a clean way?
|
You can also make a 'widget' interface for the drop down. I'll give you an easy example of a some working code for a TextBox widget so you get the idea.
```
public interface ITextWidget
{
event EventHandler TextChanged;
string Text { get; set; }
}
public abstract class TextWidget<T> : ITextWidget
{
protected T _wrappedWidget { get; set; }
public event EventHandler TextChanged;
protected void InvokeTextChanged(object sender, EventArgs e)
{
var textChanged = TextChanged;
if (textChanged != null) textChanged(this, e);
}
public abstract string Text { get; set; }
}
```
Notice that so far everything is technology agnostic. Now here's an implementation for a Win Forms TextBox:
```
public class TextBoxWidget : TextWidget<TextBox>
{
public TextBoxWidget(TextBox textBox)
{
textBox.TextChanged += InvokeTextChanged;
_wrappedWidget = textBox;
}
public override string Text
{
get { return _wrappedWidget.Text; }
set { _wrappedWidget.Text = value; }
}
}
```
This gets instantiated in the Form itself, which back to MVP is also the IViewWhatever:
```
public partial class ProjectPickerForm : Form, IProjectPickerView
{
private IProjectPickerPresenter _presenter;
public void InitializePresenter(IProjectPickerPresenter presenter) {
_presenter = presenter;
_presenter.InitializeWidgets(
...
new TextBoxWidget(txtDescription));
}
...
}
```
And in the Presenter:
```
public class ProjectPickerPresenter : IProjectPickerPresenter
{
...
public void InitializeWidgets(ITextWidget descriptionFilter) {
Check.RequireNotNull<ITextWidget>(descriptionFilter, "descriptionFilter");
DescriptionFilter = descriptionFilter;
DescriptionFilter.Text = string.Empty;
DescriptionFilter.TextChanged += OnDescriptionTextChanged;
}
...
public void OnDescriptionTextChanged(object sender, EventArgs e) {
FilterService.DescriptionFilterValue = DescriptionFilter.Text;
}
```
It's looks worse than it is to setup because most of the work is fairly mechanical once you get the idea. The clean part is that the presenter can get (and set) whatever info it needs on the widget without knowing or caring what the actual implemented widget is. It also lends itself to reuse with other widgets (you wind up building a library of them) of the same type (Win Forms here) and in other UI technologies as needed (once you have the interface / base class the implementation in another technology is trivial). It also is easy to test with mock objects because you have the interface. And your UI is now wonderfully ignorant of just about everything but UI related tasks. The downside is the bunch of classes per widget and a little learning curve to get comfortable with it.
For your drop down, your might just need the SelectedIndexChanged type event, which you'd substitute for this examples TextChanged event.
|
268,929 |
<p>I have two Java classes: B, which extends another class A, as follows :</p>
<pre><code>class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
</code></pre>
<p>I would like to call the <code>A.myMethod()</code> from <code>B.myMethod()</code>. I am coming from the <a href="https://stackoverflow.com/questions/357307/how-to-call-a-parent-class-function-from-derived-class-function">C++ world</a>, and I don't know how to do this basic thing in Java.</p>
|
[
{
"answer_id": 268937,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 3,
"selected": false,
"text": "<p>call super.myMethod();</p>\n"
},
{
"answer_id": 268939,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 8,
"selected": true,
"text": "<p>The keyword you're looking for is <code>super</code>. See <a href=\"http://java.sun.com/docs/books/tutorial/java/IandI/super.html\" rel=\"noreferrer\">this guide</a>, for instance.</p>\n"
},
{
"answer_id": 268940,
"author": "Robin",
"author_id": 21925,
"author_profile": "https://Stackoverflow.com/users/21925",
"pm_score": 7,
"selected": false,
"text": "<p>Just call it using super.</p>\n\n<pre><code>public void myMethod()\n{\n // B stuff\n super.myMethod();\n // B stuff\n}\n</code></pre>\n"
},
{
"answer_id": 268941,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <a href=\"http://java.sun.com/docs/books/tutorial/java/IandI/super.html\" rel=\"nofollow noreferrer\">super</a> keyword.</p>\n"
},
{
"answer_id": 268946,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p><code>super.MyMethod()</code> should be called inside the <code>MyMethod()</code> of the <code>class B</code>. So it should be as follows</p>\n\n<pre><code>class A {\n public void myMethod() { /* ... */ }\n}\n\nclass B extends A {\n public void myMethod() { \n super.MyMethod();\n /* Another code */ \n }\n}\n</code></pre>\n"
},
{
"answer_id": 7427979,
"author": "kinshuk4",
"author_id": 3222727,
"author_profile": "https://Stackoverflow.com/users/3222727",
"pm_score": 2,
"selected": false,
"text": "<pre><code>super.baseMethod(params);\n</code></pre>\n\n<p>call the base methods with <strong>super</strong> keyword and pass the respective params.</p>\n"
},
{
"answer_id": 8134798,
"author": "Yograj kingaonkar",
"author_id": 1047310,
"author_profile": "https://Stackoverflow.com/users/1047310",
"pm_score": 4,
"selected": false,
"text": "<p>Answer is as follows:</p>\n\n<pre><code>super.Mymethod();\nsuper(); // calls base class Superclass constructor.\nsuper(parameter list); // calls base class parameterized constructor.\nsuper.method(); // calls base class method.\n</code></pre>\n"
},
{
"answer_id": 20717767,
"author": "umanathan",
"author_id": 3125035,
"author_profile": "https://Stackoverflow.com/users/3125035",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Using super keyword access parent class variable\nclass test {\n int is,xs;\n\n test(int i,int x) {\n is=i;\n xs=x;\n System.out.println(\"super class:\");\n }\n}\n\nclass demo extends test {\n int z;\n\n demo(int i,int x,int y) {\n super(i,x);\n z=y;\n System.out.println(\"re:\"+is);\n System.out.println(\"re:\"+xs);\n System.out.println(\"re:\"+z);\n }\n}\n\nclass free{\n public static void main(String ar[]){\n demo d=new demo(4,5,6);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20717843,
"author": "umanathan",
"author_id": 3125035,
"author_profile": "https://Stackoverflow.com/users/3125035",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class test\n{\n void message()\n {\n System.out.println(\"super class\");\n }\n}\n\nclass demo extends test\n{\n int z;\n demo(int y)\n {\n super.message();\n z=y;\n System.out.println(\"re:\"+z);\n }\n}\nclass free{\n public static void main(String ar[]){\n demo d=new demo(6);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23112447,
"author": "Gracjan Nawrot",
"author_id": 3541651,
"author_profile": "https://Stackoverflow.com/users/3541651",
"pm_score": 3,
"selected": false,
"text": "<p>I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.</p>\n\n<pre><code>class A\n{\n public void myMethod()\n { /* ... */ }\n}\n\nclass B extends A\n{\n public void myMethod()\n {\n super.myMethod(); // calling parent method\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36887310,
"author": "ashish rawat",
"author_id": 6178785,
"author_profile": "https://Stackoverflow.com/users/6178785",
"pm_score": 1,
"selected": false,
"text": "<p>If u r using these methods for initialization then use constructors of class A and pass super keyword inside the constructor of class B.</p>\n\n<p>Or if you want to call a method of super class from the subclass method then you have to use super keyword inside the subclass method like : \nsuper.myMethod();</p>\n"
},
{
"answer_id": 37280137,
"author": "Rahul Yadav",
"author_id": 5740896,
"author_profile": "https://Stackoverflow.com/users/5740896",
"pm_score": 2,
"selected": false,
"text": "<p>See, here you are overriding one of the method of the base class hence if you like to call base class method from inherited class then you have to use <strong><em>super</em></strong> keyword in the same method of the inherited class.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26465/"
] |
I have two Java classes: B, which extends another class A, as follows :
```
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
```
I would like to call the `A.myMethod()` from `B.myMethod()`. I am coming from the [C++ world](https://stackoverflow.com/questions/357307/how-to-call-a-parent-class-function-from-derived-class-function), and I don't know how to do this basic thing in Java.
|
The keyword you're looking for is `super`. See [this guide](http://java.sun.com/docs/books/tutorial/java/IandI/super.html), for instance.
|
268,982 |
<p>Please help!</p>
<p><em>Background info</em></p>
<p>I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the application is running on.</p>
<p>Everywhere I use the Linq DataContext I use a using { } statement, and pass in a result of a function which returns a SqlConnection object which has been opened and had an SqlCommand executed using it before returning to the DataContext constructor.. I.e.</p>
<pre><code>// In the application code
using (DataContext db = new DataContext(GetConnection()))
{
... Code
}
</code></pre>
<p>where getConnection looks like this (I've stripped out the 'fluff' from the function to make it more readable, but there is no additional functionality that is missing).</p>
<pre><code>// Function which gets an opened connection which is given back to the DataContext constructor
public static System.Data.SqlClient.SqlConnection GetConnection()
{
System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection(/* The connection string */);
if ( Conn != null )
{
try
{
Conn.Open();
}
catch (System.Data.SqlClient.SqlException SDSCSEx)
{
/* Error Handling */
}
using (System.Data.SqlClient.SqlCommand SetCmd = new System.Data.SqlClient.SqlCommand())
{
SetCmd.Connection = Conn;
SetCmd.CommandType = System.Data.CommandType.Text;
string CurrentUserID = System.String.Empty;
SetCmd.CommandText = "DECLARE @B VARBINARY(36); SET @B = CAST('" + CurrentUserID + "' AS VARBINARY(36)); SET CONTEXT_INFO @B";
try
{
SetCmd.ExecuteNonQuery();
}
catch (System.Exception)
{
/* Error Handling */
}
}
return Conn;
}
</code></pre>
<p><strong>I do not think that the application being a WPF one has any bearing on the issue I am having.</strong></p>
<p><em>The issue I am having</em> </p>
<p>Despite the SqlConnection being disposed along with the DataContext in Sql Server Management studio I can still see loads of open connections with :</p>
<pre><code>status : 'Sleeping'
command : 'AWAITING COMMAND'
last SQL Transact Command Batch : DECLARE @B VARBINARY(36); SET @B = CAST('GUID' AS VARBINARY(36)); SET CONTEXT_INFO @B
</code></pre>
<p>Eventually the connection pool gets used up and the application can't continue. </p>
<p>So I can only conclude that somehow running the SQLCommand to set the Context_Info is meaning that the connection doesn't get disposed of when the DataContext gets disposed. </p>
<p>Can anyone spot anything obvious that would be stopping the connections from being closed and disposed of when the DataContext they are used by are disposed?</p>
|
[
{
"answer_id": 268993,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/bb292288.aspx\" rel=\"noreferrer\">MSDN</a> (<code>DataContext Constructor (IDbConnection)</code>):</p>\n\n<blockquote>\n <p>If you provide an open connection, the\n DataContext will not close it.\n Therefore, do not instantiate a\n DataContext with an open connection\n unless you have a good reason to do\n this.</p>\n</blockquote>\n\n<p>So basically, it looks like your connections are waiting for GC to finalize them before they will be released. If you have lots of code that does this, one approach might be to overide <code>Dispose()</code> in the data-context's partial class, and close the connection - just be sure to document that the data-context assumes ownership of the connection!</p>\n\n<pre><code> protected override void Dispose(bool disposing)\n {\n if(disposing && this.Connection != null && this.Connection.State == ConnectionState.Open)\n {\n this.Connection.Close();\n this.Connection.Dispose();\n }\n base.Dispose(disposing);\n }\n</code></pre>\n\n<p>Personally, I would happily give it (regular data-context, w/o the hack above) an open connection as long as I was \"using\" the connection (allowing me to perform multiple operations) - i.e.</p>\n\n<pre><code>using(var conn = GetConnection())\n{\n // snip: some stuff involving conn\n\n using(var ctx = new FooContext(conn))\n {\n // snip: some stuff involving ctx\n }\n\n // snip: some more stuff involving conn\n}\n</code></pre>\n"
},
{
"answer_id": 268995,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>Dispose</code> should close the connections, as <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx\" rel=\"nofollow noreferrer\">MSDN</a> points out:</p>\n\n<blockquote>\n <p>If the SqlConnection goes out of\n scope, it won't be closed. Therefore,\n you must explicitly close the\n connection by calling Close or\n Dispose. Close and Dispose are\n functionally equivalent. If the\n connection pooling value Pooling is\n set to true or yes, the underlying\n connection is returned back to the\n connection pool. On the other hand, if\n Pooling is set to false or no, the\n underlying connection to the server is\n closed.</p>\n</blockquote>\n\n<p>My guess would be that your problem has something to do with <code>GetContext()</code>.</p>\n"
},
{
"answer_id": 268996,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>SqlProvider</code> used by the LINQ <code>DataContext</code> only closes the SQL connection (through <code>SqlConnectionManager.DisposeConnection</code>) if it was the one to open it. If you give an already-open <code>SqlConnection</code> object to the <code>DataContext</code> constructor, it will not close it for you. Thus, you should write:</p>\n\n<pre><code>using (SqlConnection conn = GetConnection())\nusing (DataContext db = new DataContext(conn))\n{\n ... Code \n}\n</code></pre>\n"
},
{
"answer_id": 269000,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 1,
"selected": false,
"text": "<p>I think the connection, while no longer referenced, is waiting for the GC to dispose of it fully.</p>\n\n<p>Solution:</p>\n\n<p>Create your own DataContext class which derives from the auto-generated one. (rename the base one so you don't have to change any other code).</p>\n\n<p>In your derived DataContext - add a Dispose() function. In that - dispose the inner connection. </p>\n"
},
{
"answer_id": 269139,
"author": "Ash",
"author_id": 31128,
"author_profile": "https://Stackoverflow.com/users/31128",
"pm_score": 1,
"selected": false,
"text": "<p>Well thanks for the help chaps, it has been solved now.. </p>\n\n<p>Essentially I took elements of most of the answers above and implemented the DataContext constructor as above (I already had overloaded the constructors so it wasn't a big change).</p>\n\n<pre><code>// Variable for storing the connection passed to the constructor\nprivate System.Data.SqlClient.SqlConnection _Connection;\n\npublic DataContext(System.Data.SqlClient.SqlConnection Connection) : base(Connection)\n{\n // Only set the reference if the connection is Valid and Open during construction\n if (Connection != null)\n {\n if (Connection.State == System.Data.ConnectionState.Open)\n {\n _Connection = Connection; \n }\n } \n}\n\nprotected override void Dispose(bool disposing)\n{ \n // Only try closing the connection if it was opened during construction \n if (_Connection!= null)\n {\n _Connection.Close();\n _Connection.Dispose();\n }\n\n base.Dispose(disposing);\n}\n</code></pre>\n\n<p>The reason for doing this rather than some of the suggestions above is that accessing <code>this.Connection</code> in the dispose method throws a <strong>ObjectDisposedException</strong>. </p>\n\n<p>And the above works as well as I was hoping!</p>\n"
},
{
"answer_id": 700316,
"author": "Abhijeet Patel",
"author_id": 84074,
"author_profile": "https://Stackoverflow.com/users/84074",
"pm_score": 2,
"selected": false,
"text": "<p>I experienced the same issue using the Entity Framework. My <code>ObjectContext</code> was wrapped around a <code>using</code> block.</p>\n\n<p>A connection was established when I called <code>SaveChanges()</code>, but after the <code>using</code> statement was out of scope, I noticed that SQL Management Studio still had a <code>\"AWAITING COMMAND\"</code> for the .NET SQL Client.\nIt looks like this has to do with the behavior of the ADO.NET provider which has connection pooling turned on by default.</p>\n\n<p>From \"<em>Using Connection Pooling with SQL Server</em>\" on <a href=\"http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a> (emphasis mine):</p>\n\n<blockquote>\n <p>Connection pooling reduces the number of times that new connections need to be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls <code>Open</code> on a connection, the pooler looks to see if there is an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. <strong>When the application calls <code>Close</code> on the connection, the pooler returns it to the pooled set of active connections instead of actually closing it. Once the connection is returned to the pool, it is ready to be reused on the next <code>Open</code> call.</strong></p>\n</blockquote>\n\n<p>Also <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearallpools(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>ClearAllPools</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearpool(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>ClearPool</code></a> seems useful to explicitly close all pooled connections if needed.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31128/"
] |
Please help!
*Background info*
I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the application is running on.
Everywhere I use the Linq DataContext I use a using { } statement, and pass in a result of a function which returns a SqlConnection object which has been opened and had an SqlCommand executed using it before returning to the DataContext constructor.. I.e.
```
// In the application code
using (DataContext db = new DataContext(GetConnection()))
{
... Code
}
```
where getConnection looks like this (I've stripped out the 'fluff' from the function to make it more readable, but there is no additional functionality that is missing).
```
// Function which gets an opened connection which is given back to the DataContext constructor
public static System.Data.SqlClient.SqlConnection GetConnection()
{
System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection(/* The connection string */);
if ( Conn != null )
{
try
{
Conn.Open();
}
catch (System.Data.SqlClient.SqlException SDSCSEx)
{
/* Error Handling */
}
using (System.Data.SqlClient.SqlCommand SetCmd = new System.Data.SqlClient.SqlCommand())
{
SetCmd.Connection = Conn;
SetCmd.CommandType = System.Data.CommandType.Text;
string CurrentUserID = System.String.Empty;
SetCmd.CommandText = "DECLARE @B VARBINARY(36); SET @B = CAST('" + CurrentUserID + "' AS VARBINARY(36)); SET CONTEXT_INFO @B";
try
{
SetCmd.ExecuteNonQuery();
}
catch (System.Exception)
{
/* Error Handling */
}
}
return Conn;
}
```
**I do not think that the application being a WPF one has any bearing on the issue I am having.**
*The issue I am having*
Despite the SqlConnection being disposed along with the DataContext in Sql Server Management studio I can still see loads of open connections with :
```
status : 'Sleeping'
command : 'AWAITING COMMAND'
last SQL Transact Command Batch : DECLARE @B VARBINARY(36); SET @B = CAST('GUID' AS VARBINARY(36)); SET CONTEXT_INFO @B
```
Eventually the connection pool gets used up and the application can't continue.
So I can only conclude that somehow running the SQLCommand to set the Context\_Info is meaning that the connection doesn't get disposed of when the DataContext gets disposed.
Can anyone spot anything obvious that would be stopping the connections from being closed and disposed of when the DataContext they are used by are disposed?
|
From [MSDN](http://msdn.microsoft.com/en-us/library/bb292288.aspx) (`DataContext Constructor (IDbConnection)`):
>
> If you provide an open connection, the
> DataContext will not close it.
> Therefore, do not instantiate a
> DataContext with an open connection
> unless you have a good reason to do
> this.
>
>
>
So basically, it looks like your connections are waiting for GC to finalize them before they will be released. If you have lots of code that does this, one approach might be to overide `Dispose()` in the data-context's partial class, and close the connection - just be sure to document that the data-context assumes ownership of the connection!
```
protected override void Dispose(bool disposing)
{
if(disposing && this.Connection != null && this.Connection.State == ConnectionState.Open)
{
this.Connection.Close();
this.Connection.Dispose();
}
base.Dispose(disposing);
}
```
Personally, I would happily give it (regular data-context, w/o the hack above) an open connection as long as I was "using" the connection (allowing me to perform multiple operations) - i.e.
```
using(var conn = GetConnection())
{
// snip: some stuff involving conn
using(var ctx = new FooContext(conn))
{
// snip: some stuff involving ctx
}
// snip: some more stuff involving conn
}
```
|
269,005 |
<p>I'm trying to do a subselect in pgsql aka postgresql and the example I found doesn't work:</p>
<pre><code>SELECT id FROM (SELECT * FROM table);
</code></pre>
|
[
{
"answer_id": 269033,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 1,
"selected": false,
"text": "<p>I think you need something like:</p>\n\n<pre><code>SELECT * FROM table WHERE id IN (SELECT id FROM table2);\n</code></pre>\n\n<p>I don't understand what your non-working subquery is attempting to do, it seems like you could just say <code>SELECT id FROM table</code> because presently its not valid SQL92 syntax.</p>\n"
},
{
"answer_id": 269037,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 3,
"selected": true,
"text": "<p>I just needed to add an AS for the subselect, like so:</p>\n\n<pre><code>SELECT id FROM (SELECT * FROM table) AS aliasname;\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35116/"
] |
I'm trying to do a subselect in pgsql aka postgresql and the example I found doesn't work:
```
SELECT id FROM (SELECT * FROM table);
```
|
I just needed to add an AS for the subselect, like so:
```
SELECT id FROM (SELECT * FROM table) AS aliasname;
```
|
269,010 |
<p>I have created a proc that grabs all the user tables in a local DB on my machine. I want to be able to create a flat file of all my tables using BCP and SQL. Its a dummy database in SQL 2000 connecting through windows authentication. I have set my enviroment path variable in WinXP SP2. I have created new users to access the db, switched off my firewall, using trusted connection. I have tried dozens of forums, no luck. </p>
<p>In dos command prompt I get the same error. </p>
<p>SQLState = 37000, NativeError = 4060
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database requested in login '[HelpDesk-EasyPay'. Login fails.</p>
<p>Here is my SP: </p>
<pre><code>@Path VARCHAR(100),
@UserName VARCHAR(15),
@PassWord VARCHAR(15),
@ServerName VARCHAR(15)
AS
set quoted_identifier off
set nocount on
declare @n int
declare @db varchar(40)
set @db=DB_NAME()
declare @TableName varchar(15)
declare @bcp varchar(200)
select identity(int,1,1) as tblNo,name tblname into #T from Sysobjects where xtype='u'
select @n=COUNT(*) from #T
WHILE (@n>0)
BEGIN
SELECT @TableName=tblname FROM #T WHERE tblno=@n
PRINT 'Now BCP out for table: ' + @TableName
SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + ".." + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"
EXEC(@bcp)
SET @n=@n-1
END
DROP TABLE #T
</code></pre>
<p>Can anyone advise. This seems to be a connection problem or BCP ? Not sure. </p>
<p>edit: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060</p>
|
[
{
"answer_id": 272094,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>Your brackets are extending over the entire qualified table name - only the individual components should be bracketed:</p>\n\n<pre><code>bcp [HelpDesk-EasyPay].dbo.[customer] out d:\\MSSQL\\Data\\customer.bcp -N -Utest -Ptest -T\n</code></pre>\n\n<p>should work, so you want:</p>\n\n<pre><code>SET @bcp = \"master..xp_cmdshell 'BCP \" + \"[\" + @db + \"]..[\" + @TableName + \"]\" + \" OUT\" + @Path + \"\" + @TableName+\".txt -c -U\" + @UserName + \" -P\" + @PassWord + \" -S\" + @ServerName + \" -T\" + \"'\" \n</code></pre>\n\n<p>in your code. It looks like the error message you gave was truncated, otherwise you would have been able to see that it was attempting to open database \"[HelpDesk-EasyPay.dbo.customer]\" which, of course, does not exist, and even if it did, you would then get an error that no table was specified.</p>\n"
},
{
"answer_id": 1613510,
"author": "podosta",
"author_id": 103585,
"author_profile": "https://Stackoverflow.com/users/103585",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same issue for the OUT (the minus character kills everything event the ^ don't work)</p>\n\n<p>I avoid it with the QUERYOUT. Like this :</p>\n\n<pre><code>SET @s = 'BCP \"SELECT * FROM [HelpDesk-EasyPay].dbo.customers\" QUERYOUT myfile.txt ...'\n</code></pre>\n"
},
{
"answer_id": 62831171,
"author": "Vs Kc",
"author_id": 10678455,
"author_profile": "https://Stackoverflow.com/users/10678455",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe someone will come in handy: I have the same issue with SQL Server 2017. The reason was the square brackets around the database name.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35109/"
] |
I have created a proc that grabs all the user tables in a local DB on my machine. I want to be able to create a flat file of all my tables using BCP and SQL. Its a dummy database in SQL 2000 connecting through windows authentication. I have set my enviroment path variable in WinXP SP2. I have created new users to access the db, switched off my firewall, using trusted connection. I have tried dozens of forums, no luck.
In dos command prompt I get the same error.
SQLState = 37000, NativeError = 4060
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database requested in login '[HelpDesk-EasyPay'. Login fails.
Here is my SP:
```
@Path VARCHAR(100),
@UserName VARCHAR(15),
@PassWord VARCHAR(15),
@ServerName VARCHAR(15)
AS
set quoted_identifier off
set nocount on
declare @n int
declare @db varchar(40)
set @db=DB_NAME()
declare @TableName varchar(15)
declare @bcp varchar(200)
select identity(int,1,1) as tblNo,name tblname into #T from Sysobjects where xtype='u'
select @n=COUNT(*) from #T
WHILE (@n>0)
BEGIN
SELECT @TableName=tblname FROM #T WHERE tblno=@n
PRINT 'Now BCP out for table: ' + @TableName
SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + ".." + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"
EXEC(@bcp)
SET @n=@n-1
END
DROP TABLE #T
```
Can anyone advise. This seems to be a connection problem or BCP ? Not sure.
edit: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060
|
Your brackets are extending over the entire qualified table name - only the individual components should be bracketed:
```
bcp [HelpDesk-EasyPay].dbo.[customer] out d:\MSSQL\Data\customer.bcp -N -Utest -Ptest -T
```
should work, so you want:
```
SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + "]..[" + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"
```
in your code. It looks like the error message you gave was truncated, otherwise you would have been able to see that it was attempting to open database "[HelpDesk-EasyPay.dbo.customer]" which, of course, does not exist, and even if it did, you would then get an error that no table was specified.
|
269,017 |
<p>So here is the simple code:</p>
<pre><code> [System.ComponentModel.DefaultValue(true)]
public bool AnyValue { get; set; }
</code></pre>
<p>I am sure I don't set AnyValue to false again (I just created it). This property is a property of a Page class of ASP.NET. And I am cheking the value in a button event handling function. But somehow it is still false.
I wonder when actually it is set true? On compile time? When class is instantiated?</p>
<p>What do you think about what I am doing wrong?</p>
|
[
{
"answer_id": 269023,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>DefaultValue does <strong>NOT</strong> set the value. </p>\n\n<p>What it does is tell VisualStudio what the default value is. When a visual element (Button, listbox etc) is selected on a form, and the Property panel is displayed, VS will <strong>bold</strong> the values of properties which are set to something besides the value given in DefaultValue.</p>\n\n<p>Hence in your case, since AnyValue is false, but it's DefaultValue is true, then is will display <strong>false</strong> in bold in the Property panel. If you were to manually change it to \"true\", then it will be displayed non-bolded.</p>\n"
},
{
"answer_id": 269089,
"author": "yusuf",
"author_id": 35012,
"author_profile": "https://Stackoverflow.com/users/35012",
"pm_score": 0,
"selected": false,
"text": "<p>So what is the best way to set default value like I meant?</p>\n\n<p>This seems a good way for me;</p>\n\n<pre><code> private bool myVal = true;\n public bool MyVal\n {\n get { return myVal; } \n set { myVal = value; }\n }\n</code></pre>\n"
},
{
"answer_id": 270502,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>As already stated, it doesn't set values.</p>\n\n<p>In addition to the <code>PropertyGrid</code>, <code>[DefaultValue]</code> is also used by various serializer implementations, such as <code>XmlSerializer</code> and <code>DataContractSerializer</code>. For info, there is also a second pattern: <code>bool ShouldSerialize{Name}()</code> that is respected by all 3.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35012/"
] |
So here is the simple code:
```
[System.ComponentModel.DefaultValue(true)]
public bool AnyValue { get; set; }
```
I am sure I don't set AnyValue to false again (I just created it). This property is a property of a Page class of ASP.NET. And I am cheking the value in a button event handling function. But somehow it is still false.
I wonder when actually it is set true? On compile time? When class is instantiated?
What do you think about what I am doing wrong?
|
DefaultValue does **NOT** set the value.
What it does is tell VisualStudio what the default value is. When a visual element (Button, listbox etc) is selected on a form, and the Property panel is displayed, VS will **bold** the values of properties which are set to something besides the value given in DefaultValue.
Hence in your case, since AnyValue is false, but it's DefaultValue is true, then is will display **false** in bold in the Property panel. If you were to manually change it to "true", then it will be displayed non-bolded.
|
269,026 |
<p>How can I document a member inline in .Net? Let me explain. Most tools that extract documentation from comments support some kind of inline documentation where you can add a brief after the member declaration. Something like:</p>
<pre><code>public static string MyField; /// <summary>Information about MyField.</summary>
</code></pre>
<p>Is there a way to do this in C# or the .NET languages?</p>
|
[
{
"answer_id": 269038,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 1,
"selected": false,
"text": "<p>Yep, just put it BEFORE the thing you want to comment</p>\n\n<pre><code>/// <summary>Information about MyField.</summary>\npublic static string MyField; \n</code></pre>\n"
},
{
"answer_id": 269045,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": true,
"text": "<p>No, you can't. XML comments are only supported as a block level comment, meaning it must be placed before the code element you are documenting. The common tools for extracting XML comments from .NET code do not understand how to parse inline comments like that. If you need this ability you will need to write your own parser.</p>\n"
},
{
"answer_id": 269055,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 2,
"selected": false,
"text": "<p>There is not a built-in way to do this. The XML documentation system is hierarchical; it defines a relationship between the tag <code><summary /></code> and the data that immediately follows it.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688/"
] |
How can I document a member inline in .Net? Let me explain. Most tools that extract documentation from comments support some kind of inline documentation where you can add a brief after the member declaration. Something like:
```
public static string MyField; /// <summary>Information about MyField.</summary>
```
Is there a way to do this in C# or the .NET languages?
|
No, you can't. XML comments are only supported as a block level comment, meaning it must be placed before the code element you are documenting. The common tools for extracting XML comments from .NET code do not understand how to parse inline comments like that. If you need this ability you will need to write your own parser.
|
269,042 |
<p>I´ve been looking for it yet in stackoverflow without success...</p>
<p>Is it posible a connection pooling in asp.net? Is it worthwhile? How?</p>
|
[
{
"answer_id": 269056,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": true,
"text": "<p>It is actually really simple, simply add the following parameters to your connection string and (either in code or in the web.config) and ASP.NET will pick up the rest:</p>\n\n<pre><code>Min Pool Size=5; Max Pool Size=60; Connect Timeout=300;\n</code></pre>\n\n<p><em>Note: The Connection Timeout is in seconds and is not required.</em></p>\n"
},
{
"answer_id": 3051876,
"author": "canistervacuumbagless",
"author_id": 326708,
"author_profile": "https://Stackoverflow.com/users/326708",
"pm_score": 1,
"selected": false,
"text": "<p>by default max pool is 100</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34432/"
] |
I´ve been looking for it yet in stackoverflow without success...
Is it posible a connection pooling in asp.net? Is it worthwhile? How?
|
It is actually really simple, simply add the following parameters to your connection string and (either in code or in the web.config) and ASP.NET will pick up the rest:
```
Min Pool Size=5; Max Pool Size=60; Connect Timeout=300;
```
*Note: The Connection Timeout is in seconds and is not required.*
|
269,044 |
<p><strong>Background:</strong> I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like</p>
<p><em><a href="http://example.com/#foobar" rel="noreferrer">http://example.com/#foobar</a></em></p>
<p>and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.</p>
<p><strong>Now the question:</strong> When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn <a href="http://example.com/#foobar" rel="noreferrer">http://example.com/#foobar</a> into <a href="http://example.com/" rel="noreferrer">http://example.com/</a> to update the permalink display. However, doing so using <code>parent.location.hash = ''</code> causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using <code>window.location.href = '/#'</code> won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?</p>
|
[
{
"answer_id": 269088,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 4,
"selected": false,
"text": "<p>Since you are controlling the action on the hash value, why not just use a token that means \"nothing\", like \"#_\" or \"#default\".</p>\n"
},
{
"answer_id": 269118,
"author": "Florin",
"author_id": 34565,
"author_profile": "https://Stackoverflow.com/users/34565",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$(document).ready(function() {\n $(\".lnk\").click(function(e) {\n e.preventDefault();\n $(this).attr(\"href\", \"stripped_url_via_desired_regex\");\n });\n });\n</code></pre>\n"
},
{
"answer_id": 1138931,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>So use </p>\n\n<p><code>parent.location.hash = ''</code> first</p>\n\n<p>then do</p>\n\n<pre><code>window.location.href=window.location.href.slice(0, -1);\n</code></pre>\n"
},
{
"answer_id": 4602517,
"author": "jazkat",
"author_id": 318380,
"author_profile": "https://Stackoverflow.com/users/318380",
"pm_score": 1,
"selected": false,
"text": "<p>There is also another option instead of using hash, \nyou could use <code>javascript: void(0);</code>\nExample: <code><a href=\"javascript:void(0);\" class=\"open_div\">Open Div</a></code></p>\n\n<p>I guess it also depends on when you need that kind of link, so you better check the following links:</p>\n\n<p>How to use it: <a href=\"http://www.brightcherry.co.uk/scribbles/2010/04/25/javascript-how-to-remove-the-trailing-hash-in-a-url/\" rel=\"nofollow noreferrer\">http://www.brightcherry.co.uk/scribbles/2010/04/25/javascript-how-to-remove-the-trailing-hash-in-a-url/</a>\nor check debate on what is better here: <a href=\"https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0\">Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?</a></p>\n"
},
{
"answer_id": 4602744,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": -1,
"selected": false,
"text": "<p>As others have said, you can't do it. Plus... seriously, as the <a href=\"http://balupton.com/sandbox/jquery-ajaxy/demo/\" rel=\"nofollow\">jQuery Ajaxy</a> author - I've deployed complete ajax websites for years now - and I can guarantee no end user has ever complained or perhaps ever even noticed that there is this hash thing going on, user's don't care as long as it works and their getting what they came for.</p>\n\n<p>A proper solution though is HTML5 PushState/ReplaceState/PopState ;-) Which doesn't need the fragement-identifier anymore:\n<a href=\"https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history\" rel=\"nofollow\">https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history</a>\nFor a HTML5 and HTML4 compatible project that supports this HTML5 State Functionality check out <a href=\"https://github.com/browserstate/History.js\" rel=\"nofollow\">https://github.com/browserstate/History.js</a> :-)</p>\n"
},
{
"answer_id": 4619108,
"author": "Chris Boyle",
"author_id": 6540,
"author_profile": "https://Stackoverflow.com/users/6540",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the shiny new HTML5 <code>window.history.pushState</code> and <code>replaceState</code> methods, as described in <a href=\"http://asciicasts.com/episodes/246-ajax-history-state\" rel=\"nofollow\">ASCIIcasts 246: AJAX History State</a> and <a href=\"https://github.com/blog/760-the-tree-slider\" rel=\"nofollow\">on the GitHub blog</a>. This lets you change the entire path (within the same origin host) not just the fragment. To try out this feature, <a href=\"https://github.com/chrisboyle/sgtpuzzles\" rel=\"nofollow\">browse around a GitHub repository</a> with a recent browser.</p>\n"
},
{
"answer_id": 13824103,
"author": "Matmas",
"author_id": 682025,
"author_profile": "https://Stackoverflow.com/users/682025",
"pm_score": 7,
"selected": true,
"text": "<p>As others have mentioned, <a href=\"https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_replaceState%28%29.C2.A0method\" rel=\"noreferrer\">replaceState</a> in HTML5 can be used to remove the URL fragment.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>// remove fragment as much as it can go without adding an entry in browser history:\nwindow.location.replace(\"#\");\n\n// slice off the remaining '#' in HTML5: \nif (typeof window.history.replaceState == 'function') {\n history.replaceState({}, '', window.location.href.slice(0, -1));\n}\n</code></pre>\n"
},
{
"answer_id": 34660797,
"author": "Manigandan Raamanathan",
"author_id": 5758712,
"author_profile": "https://Stackoverflow.com/users/5758712",
"pm_score": 2,
"selected": false,
"text": "<p>Put this code on head section.</p>\n\n<pre><code><script type=\"text/javascript\">\n var uri = window.location.toString();\n if (uri.indexOf(\"?\") > 0) {\n var clean_uri = uri.substring(0, uri.indexOf(\"?\"));\n window.history.replaceState({}, document.title, clean_uri);\n }\n</script>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34170/"
] |
**Background:** I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like
*<http://example.com/#foobar>*
and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.
**Now the question:** When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn <http://example.com/#foobar> into <http://example.com/> to update the permalink display. However, doing so using `parent.location.hash = ''` causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using `window.location.href = '/#'` won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?
|
As others have mentioned, [replaceState](https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_replaceState%28%29.C2.A0method) in HTML5 can be used to remove the URL fragment.
Here is an example:
```
// remove fragment as much as it can go without adding an entry in browser history:
window.location.replace("#");
// slice off the remaining '#' in HTML5:
if (typeof window.history.replaceState == 'function') {
history.replaceState({}, '', window.location.href.slice(0, -1));
}
```
|
269,058 |
<p>Lets say I have an array like this:</p>
<pre><code>string [] Filelist = ...
</code></pre>
<p>I want to create an Linq result where each entry has it's position in the array like this:</p>
<pre><code>var list = from f in Filelist
select new { Index = (something), Filename = f};
</code></pre>
<p>Index to be 0 for the 1st item, 1 for the 2nd, etc.</p>
<p>What should I use for the expression Index= ?</p>
|
[
{
"answer_id": 269070,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "<p>Don't use a query expression. Use <a href=\"http://msdn.microsoft.com/en-us/library/bb534869.aspx\" rel=\"noreferrer\">the overload of <code>Select</code> which passes you an index</a>:</p>\n\n<pre><code>var list = FileList.Select((file, index) => new { Index=index, Filename=file });\n</code></pre>\n"
},
{
"answer_id": 269109,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 2,
"selected": false,
"text": "<pre><code>string[] values = { \"a\", \"b\", \"c\" };\nint i = 0;\nvar t = (from v in values\nselect new { Index = i++, Value = v}).ToList();\n</code></pre>\n"
},
{
"answer_id": 50042465,
"author": "Artemious",
"author_id": 1830814,
"author_profile": "https://Stackoverflow.com/users/1830814",
"pm_score": 1,
"selected": false,
"text": "<p>You <strong>cannot get an index</strong> using pure LINQ query expressions (those with <code>from.. where.. select..</code> clauses).</p>\n\n<p>However, this doesn't mean you have to completely give up on this LINQ query style. </p>\n\n<p>You just have to <strong>get out of the LINQ query expression</strong> and use a <code>.Select(item, index)</code> method overload.</p>\n\n<pre><code>var newestExistingFilesWithIndexes = \n (from f in Filelist\n // we love LINQ query expressions\n where f.Exists\n // and we use it anywhere possible\n orderby f.LastModified descending\n select f)\n // but sometimes we have to get out and use LINQ extension methods\n .Select((f, index) => new { Index = index, Filename = f.Fullname});\n</code></pre>\n\n<p>or suppose, you need to filter a list based on item index ...</p>\n\n<pre><code>var newestExistingFilesOnlyEvenIndexes = \n // use the Select method overload to get the index\n (from f in Filelist.Select((file, index) => new { file, index })\n // only take item with an even index\n where f.index % 2 == 0\n where f.file.Exists\n orderby f.file.LastModified descending\n select f.file);\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28260/"
] |
Lets say I have an array like this:
```
string [] Filelist = ...
```
I want to create an Linq result where each entry has it's position in the array like this:
```
var list = from f in Filelist
select new { Index = (something), Filename = f};
```
Index to be 0 for the 1st item, 1 for the 2nd, etc.
What should I use for the expression Index= ?
|
Don't use a query expression. Use [the overload of `Select` which passes you an index](http://msdn.microsoft.com/en-us/library/bb534869.aspx):
```
var list = FileList.Select((file, index) => new { Index=index, Filename=file });
```
|
269,060 |
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError</code>.</p>
<p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p>
<p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
|
[
{
"answer_id": 269276,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 5,
"selected": false,
"text": "<p>+1 for the <a href=\"http://web.archive.org/web/20110709171259/http://chardet.feedparser.org/docs/faq.html\" rel=\"noreferrer\">chardet</a> module (suggested by <a href=\"https://stackoverflow.com/questions/269060/is-there-a-python-library-function-which-attempts-to-guess-the-character-encoding/269105#269105\"><code>@insin</code></a>).</p>\n\n<p>It is not in the standard library, but you can easily install it with the following command:</p>\n\n<pre><code>$ pip install chardet\n</code></pre>\n\n<p><a href=\"http://web.archive.org/web/20111003070626/http://chardet.feedparser.org/\" rel=\"noreferrer\">Example</a>:</p>\n\n<pre><code>>>> import chardet\n>>> import urllib\n>>> detect = lambda url: chardet.detect(urllib.urlopen(url).read())\n>>> detect('http://stackoverflow.com')\n{'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'} \n>>> detect('https://stackoverflow.com/questions/269060/is-there-a-python-lib')\n{'confidence': 0.98999999999999999, 'encoding': 'utf-8'}\n</code></pre>\n\n<p>See <a href=\"http://guide.python-distribute.org/installation.html#installing-pip\" rel=\"noreferrer\">Installing Pip</a> if you don't have one.</p>\n"
},
{
"answer_id": 271058,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 1,
"selected": false,
"text": "<p>The best way to do this that I've found is to iteratively try decoding a prospective with each of the most common encodings inside of a try except block.</p>\n"
},
{
"answer_id": 273631,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 5,
"selected": true,
"text": "<p>As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that.</p>\n\n<pre><code>def decode(s, encodings=('ascii', 'utf8', 'latin1')):\n for encoding in encodings:\n try:\n return s.decode(encoding)\n except UnicodeDecodeError:\n pass\n return s.decode('ascii', 'ignore')\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
] |
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a `UnicodeDecodeError`.
So, I'm looking for a function that takes a `str` and optionally some hints and does its darndest to give me back a `unicode`. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.
I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".
|
As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that.
```
def decode(s, encodings=('ascii', 'utf8', 'latin1')):
for encoding in encodings:
try:
return s.decode(encoding)
except UnicodeDecodeError:
pass
return s.decode('ascii', 'ignore')
```
|
269,062 |
<p>I want to use LabVIEW's Call Library Function Node to access a DLL function, and have this function return a string to displayed on my VI. How would I go about doing this? I am quite happy returning numbers from my DLL, but am really struggling to find any examples of how to return a string.</p>
|
[
{
"answer_id": 269608,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 3,
"selected": true,
"text": "<p>I assume from your question that you already have a DLL that can return numbers to Labview. To return a string from the DLL, I have created a DLL with the following C++ function</p>\n\n<pre><code>void returnString(char myString[])\n{\n const char *aString = \"test string\";\n memcpy(myString, aString, 12);\n}\n</code></pre>\n\n<p>In Labview I then use the Call Library Function Node and configure it as follows </p>\n\n<pre>\n Library Name or Path: c:\\path\\to\\my\\custom.dll\n Function Name: returnString\n Calling Convention: C\n\n Parameters: \n Parameter: return type\n type: void\n\n Parameter: arg1\n type: String\n string format: C String Pointer\n\n Function prototype:\n void returnString(CStr arg1);\n</pre>\n\n<p>After connect the arg1 output in the block diagram to a string indicator and run. The string \"test string\" should appear in the front panel. </p>\n\n<p>I tried to have the returnString function be of type CStr as in</p>\n\n<pre><code>CStr returnString()\n{ ...\n }\n</code></pre>\n\n<p>but I got build errors when compiling the DLL project.</p>\n\nUpdate\n\n<p>Thanks to @bk1e comment don't forget to pre-allocate space in Labview for the string.</p>\n"
},
{
"answer_id": 271309,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "<p>There are at least a few ways to return a string from a Call Library Function Node:</p>\n<ol>\n<li><p>Return a C string pointer from your DLL function, and configure the Call Library Function Node to have a return type of "C String Pointer". Note that the returned string must be valid after the function returns, so it can't be a pointer to a string allocated on the stack. It must be one of the following: allocated on the heap, statically allocated, a constant string literal, etc.</p>\n<p>It looks like <code>examples/dll/regexpr/Regular Expression Solution/VIs/Get Error String.vi</code> in the LabVIEW directory takes this approach.</p>\n</li>\n<li><p>Allocate a string in your VI, pass it to the Call Library Function Node using a "C String Pointer" parameter as Azim suggested, and overwrite its contents in the DLL. One way to allocate the string is to use Initialize Array to create a u8 array of the desired size, and then use Byte Array To String to convert it to a string.</p>\n<p>Be sure that the string you pass in is large enough to hold the contents of your string, and make sure to pass the string length to the DLL so that it knows how large the buffer is. I believe that the default parameter is an empty string. Figuring out the right string length may require calling into the DLL twice, if your VI's first guess isn't large enough.</p>\n</li>\n<li><p>Pass the string to the Call Library Function Node using a "String Handle" parameter, and use LabVIEW functions in your DLL to resize the string as necessary. This requires your DLL to be specifically designed to interface with LabVIEW and requires linking against a static library that is provided with LabVIEW.</p>\n<p>An example of this method ships with LabVIEW as <code>examples/dll/hostname/hostname.vi</code>.</p>\n</li>\n</ol>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1555/"
] |
I want to use LabVIEW's Call Library Function Node to access a DLL function, and have this function return a string to displayed on my VI. How would I go about doing this? I am quite happy returning numbers from my DLL, but am really struggling to find any examples of how to return a string.
|
I assume from your question that you already have a DLL that can return numbers to Labview. To return a string from the DLL, I have created a DLL with the following C++ function
```
void returnString(char myString[])
{
const char *aString = "test string";
memcpy(myString, aString, 12);
}
```
In Labview I then use the Call Library Function Node and configure it as follows
```
Library Name or Path: c:\path\to\my\custom.dll
Function Name: returnString
Calling Convention: C
Parameters:
Parameter: return type
type: void
Parameter: arg1
type: String
string format: C String Pointer
Function prototype:
void returnString(CStr arg1);
```
After connect the arg1 output in the block diagram to a string indicator and run. The string "test string" should appear in the front panel.
I tried to have the returnString function be of type CStr as in
```
CStr returnString()
{ ...
}
```
but I got build errors when compiling the DLL project.
Update
Thanks to @bk1e comment don't forget to pre-allocate space in Labview for the string.
|
269,063 |
<p>After moving a project from .NET 1.1 to .NET 2.0, MsBuild emits lots of warnings for some COM objects.</p>
<p>Sample code for test (actual code doesn't matter, just used to create the warnings):</p>
<pre><code>using System;
using System.DirectoryServices;
using ActiveDs;
namespace Test
{
public class Class1
{
public static void Main(string[] args)
{
string adsPath = String.Format("WinNT://{0}/{1}", args[0], args[1]);
DirectoryEntry localuser = new DirectoryEntry(adsPath);
IADsUser pUser = (IADsUser) localuser.NativeObject;
Console.WriteLine("User = {0}", pUser.ADsPath);
}
}
}
</code></pre>
<p>Warning messages look like</p>
<p><em>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets : warning : At least one of the arguments for 'ITypeLib.RemoteGetLibAttr' cannot be marshaled by the runtime marshaler. Such arguments will therefore be passed as a pointer and may require unsafe code to manipulate.</em></p>
<p>Observations:</p>
<ul>
<li>Happens for ActiveDs (11 warnings) and MSXML2 (54 warnings).</li>
<li>Not seen for our own COM objects.</li>
<li><code><Reference></code> entry in .csproj file contains attribute <code>WrapperTool = "tlbimp"</code></li>
<li>Despite of all warnings, no problems have been observed in the running system.</li>
</ul>
<p>Any idea how to get rid of the warnings?</p>
|
[
{
"answer_id": 1315018,
"author": "Joe Caffeine",
"author_id": 159770,
"author_profile": "https://Stackoverflow.com/users/159770",
"pm_score": -1,
"selected": false,
"text": "<p>You can stop the warnings with:</p>\n\n<pre>\n #pragma warning disable warning-list\n #pragma warning restore warning-list\n</pre>\n\n<p>where warning list is a comma seperated list of warning numbers.</p>\n\n<p>The warning means that the typelib you are importing contains something untranslatable into managed code but could be dealt with using pointer operations, in an unsafe code block. The code was untranslatable in .Net 1.1 as well, but the compiler wasn't smart enough to warn you about the trap you might walk into if you use one of the methods it's warning you about.</p>\n"
},
{
"answer_id": 1402834,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 4,
"selected": true,
"text": "<p>According to a comment in the <a href=\"http://msdn.microsoft.com/en-us/library/tt0cf3sx(VS.80).aspx\" rel=\"noreferrer\">MDSN article about TLBIMP for 2.0</a>, you can't fix this problem w/o running TLBIMP yourself.</p>\n\n<p>It was easy to reproduce your problem using VS. I also reproduced it running TLBIMP manually from a VS comment prompt:</p>\n\n<pre><code> tlbimp c:\\WINNT\\system32\\activeds.tlb /out:interop.activeds.dll\n</code></pre>\n\n<p>The fix was to use the /silent switch</p>\n\n<pre><code> tlbimp c:\\WINNT\\system32\\activeds.tlb /silent /out:interop.activeds.dll\n</code></pre>\n\n<p>As pointed out in the comment in the MSDN article, the COM reference becomes a .net assembly reference to the interop assembly you built yourself.</p>\n\n<p>I'm not a VS expert, but I made this work by adding a prebuild to project of:</p>\n\n<pre><code> \"$(DevEnvDir)\\..\\..\\SDK\\v2.0\\bin\\tlbimp\" c:\\WINNT\\system32\\activeds.tlb\n /namespace:ActiveDs /silent /out:\"$(ProjectDir)interop.activeds.dll\"\n</code></pre>\n\n<p>Built it once so I'd have a dll to add a reference with the browse tab. Added a reference to the interop.activeds.dll in my project root and then built again. You may want to do this some other way, like with an external make file via a C++ project. This is more of a POC.</p>\n\n<p>Note a funny difference in MSBUILD vs VS, $(DevEnvDir) has a trailing backslash but MSBUILD does not.</p>\n"
},
{
"answer_id": 33213457,
"author": "Hermann.Gruber",
"author_id": 2792414,
"author_profile": "https://Stackoverflow.com/users/2792414",
"pm_score": 4,
"selected": false,
"text": "<p>I had experienced the same problem and fixed it by editing the project file (.csproj), following a suggestion from here:</p>\n\n<p><a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/7a7c352b-20cb-4931-b3b5-27e899016f75/turning-off-msbuild-warnings-msb3305?forum=msbuild\">https://social.msdn.microsoft.com/Forums/vstudio/en-US/7a7c352b-20cb-4931-b3b5-27e899016f75/turning-off-msbuild-warnings-msb3305?forum=msbuild</a></p>\n\n<p>I added the following key to the property group of each build configuration: </p>\n\n<pre><code><ResolveComReferenceSilent>True</ResolveComReferenceSilent>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23772/"
] |
After moving a project from .NET 1.1 to .NET 2.0, MsBuild emits lots of warnings for some COM objects.
Sample code for test (actual code doesn't matter, just used to create the warnings):
```
using System;
using System.DirectoryServices;
using ActiveDs;
namespace Test
{
public class Class1
{
public static void Main(string[] args)
{
string adsPath = String.Format("WinNT://{0}/{1}", args[0], args[1]);
DirectoryEntry localuser = new DirectoryEntry(adsPath);
IADsUser pUser = (IADsUser) localuser.NativeObject;
Console.WriteLine("User = {0}", pUser.ADsPath);
}
}
}
```
Warning messages look like
*C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets : warning : At least one of the arguments for 'ITypeLib.RemoteGetLibAttr' cannot be marshaled by the runtime marshaler. Such arguments will therefore be passed as a pointer and may require unsafe code to manipulate.*
Observations:
* Happens for ActiveDs (11 warnings) and MSXML2 (54 warnings).
* Not seen for our own COM objects.
* `<Reference>` entry in .csproj file contains attribute `WrapperTool = "tlbimp"`
* Despite of all warnings, no problems have been observed in the running system.
Any idea how to get rid of the warnings?
|
According to a comment in the [MDSN article about TLBIMP for 2.0](http://msdn.microsoft.com/en-us/library/tt0cf3sx(VS.80).aspx), you can't fix this problem w/o running TLBIMP yourself.
It was easy to reproduce your problem using VS. I also reproduced it running TLBIMP manually from a VS comment prompt:
```
tlbimp c:\WINNT\system32\activeds.tlb /out:interop.activeds.dll
```
The fix was to use the /silent switch
```
tlbimp c:\WINNT\system32\activeds.tlb /silent /out:interop.activeds.dll
```
As pointed out in the comment in the MSDN article, the COM reference becomes a .net assembly reference to the interop assembly you built yourself.
I'm not a VS expert, but I made this work by adding a prebuild to project of:
```
"$(DevEnvDir)\..\..\SDK\v2.0\bin\tlbimp" c:\WINNT\system32\activeds.tlb
/namespace:ActiveDs /silent /out:"$(ProjectDir)interop.activeds.dll"
```
Built it once so I'd have a dll to add a reference with the browse tab. Added a reference to the interop.activeds.dll in my project root and then built again. You may want to do this some other way, like with an external make file via a C++ project. This is more of a POC.
Note a funny difference in MSBUILD vs VS, $(DevEnvDir) has a trailing backslash but MSBUILD does not.
|
269,073 |
<p>Is there a collection (BCL or other) that has the following characteristics:</p>
<p>Sends event if collection is changed AND sends event if any of the elements in the collection sends a <code>PropertyChanged</code> event. Sort of an <code>ObservableCollection<T></code> where <code>T: INotifyPropertyChanged</code> and the collection is also monitoring the elements for changes. </p>
<p>I could wrap an observable collection my self and do the event subscribe/unsubscribe when elements in the collection are added/removed but I was just wondering if any existing collections did this already?</p>
|
[
{
"answer_id": 269113,
"author": "soren.enemaerke",
"author_id": 9222,
"author_profile": "https://Stackoverflow.com/users/9222",
"pm_score": 6,
"selected": true,
"text": "<p>Made a quick implementation myself:</p>\n\n<pre><code>public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged\n{\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n Unsubscribe(e.OldItems);\n Subscribe(e.NewItems);\n base.OnCollectionChanged(e);\n }\n\n protected override void ClearItems()\n {\n foreach(T element in this)\n element.PropertyChanged -= ContainedElementChanged;\n\n base.ClearItems();\n }\n\n private void Subscribe(IList iList)\n {\n if (iList != null)\n {\n foreach (T element in iList)\n element.PropertyChanged += ContainedElementChanged;\n }\n }\n\n private void Unsubscribe(IList iList)\n {\n if (iList != null)\n {\n foreach (T element in iList)\n element.PropertyChanged -= ContainedElementChanged;\n }\n }\n\n private void ContainedElementChanged(object sender, PropertyChangedEventArgs e)\n {\n OnPropertyChanged(e);\n }\n}\n</code></pre>\n\n<p>Admitted, it would be kind of confusing and misleading to have the PropertyChanged fire on the collection when the property that actually changed is on a contained element, but it would fit my specific purpose. It could be extended with a new event that is fired instead inside ContainerElementChanged</p>\n\n<p>Thoughts?</p>\n\n<p>EDIT: Should note that the BCL ObservableCollection only exposes the INotifyPropertyChanged interface through an explicit implementation so you would need to provide a cast in order to attach to the event like so:</p>\n\n<pre><code>ObservableCollectionEx<Element> collection = new ObservableCollectionEx<Element>();\n((INotifyPropertyChanged)collection).PropertyChanged += (x,y) => ReactToChange();\n</code></pre>\n\n<p>EDIT2: Added handling of ClearItems, thanks Josh</p>\n\n<p>EDIT3: Added a correct unsubscribe for PropertyChanged, thanks Mark</p>\n\n<p>EDIT4: Wow, this is really learn-as-you-go :). KP noted that the event was fired with the collection as sender and not with the element when the a contained element changes. He suggested declaring a PropertyChanged event on the class marked with <em>new</em>. This would have a few issues which I'll try to illustrate with the sample below:</p>\n\n<pre><code> // work on original instance\n ObservableCollection<TestObject> col = new ObservableCollectionEx<TestObject>();\n ((INotifyPropertyChanged)col).PropertyChanged += (s, e) => { Trace.WriteLine(\"Changed \" + e.PropertyName); };\n\n var test = new TestObject();\n col.Add(test); // no event raised\n test.Info = \"NewValue\"; //Info property changed raised\n\n // working on explicit instance\n ObservableCollectionEx<TestObject> col = new ObservableCollectionEx<TestObject>();\n col.PropertyChanged += (s, e) => { Trace.WriteLine(\"Changed \" + e.PropertyName); };\n\n var test = new TestObject();\n col.Add(test); // Count and Item [] property changed raised\n test.Info = \"NewValue\"; //no event raised\n</code></pre>\n\n<p>You can see from the sample that 'overriding' the event has the side effect that you need to be extremely careful of which type of variable you use when subscribing to the event since that dictates which events you receive.</p>\n"
},
{
"answer_id": 269246,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 0,
"selected": false,
"text": "<p>Check out the <a href=\"http://www.itu.dk/research/c5\" rel=\"nofollow noreferrer\">C5 Generic Collection Library</a>. All of its collections contain events that you can use to attach callbacks for when items are added, removed, inserted, cleared, or when the collection changes.</p>\n\n<p>I am working for some extensions to that libary <a href=\"http://c5.xpdm.us\" rel=\"nofollow noreferrer\">here</a> that in the near future should allow for \"preview\" events that could allow you to cancel an add or change.</p>\n"
},
{
"answer_id": 269283,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use something built into the framework you can use <a href=\"http://msdn.microsoft.com/en-us/library/aa346595.aspx\" rel=\"nofollow noreferrer\">FreezableCollection</a>. Then you will want to listen to the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.freezable.changed.aspx\" rel=\"nofollow noreferrer\">Changed event</a>.</p>\n\n<blockquote>\n <p>Occurs when the Freezable or an object\n it contains is modified.</p>\n</blockquote>\n\n<p>Here is a small sample. The collection_Changed method will get called twice.</p>\n\n<pre><code>public partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n FreezableCollection<SolidColorBrush> collection = new FreezableCollection<SolidColorBrush>();\n collection.Changed += collection_Changed;\n SolidColorBrush brush = new SolidColorBrush(Colors.Red);\n collection.Add(brush);\n brush.Color = Colors.Blue;\n }\n\n private void collection_Changed(object sender, EventArgs e)\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3316435,
"author": "Mark Whitfeld",
"author_id": 311292,
"author_profile": "https://Stackoverflow.com/users/311292",
"pm_score": 3,
"selected": false,
"text": "<p>@soren.enemaerke:\nI would have made this comment on your answer post, but I can't (I don't know why, maybe because I don't have many rep points). Anyway, I just thought that I'd mention that in your code you posted I don't think that the Unsubscribe would work correctly because it is creating a new lambda inline and then trying to remove the event handler for it.</p>\n\n<p>I would change the add/remove event handler lines to something like:</p>\n\n<pre><code>element.PropertyChanged += ContainedElementChanged;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>element.PropertyChanged -= ContainedElementChanged;\n</code></pre>\n\n<p>And then change the ContainedElementChanged method signature to:</p>\n\n<pre><code>private void ContainedElementChanged(object sender, PropertyChangedEventArgs e)\n</code></pre>\n\n<p>This would recognise that the remove is for the same handler as the add and then remove it correctly. Hope this helps somebody :)</p>\n"
},
{
"answer_id": 8024284,
"author": "Lukas Cenovsky",
"author_id": 138803,
"author_profile": "https://Stackoverflow.com/users/138803",
"pm_score": 1,
"selected": false,
"text": "<p>I would use <a href=\"http://www.reactiveui.net/\" rel=\"nofollow\">ReactiveUI's</a> <code>ReactiveCollection</code>:</p>\n\n<pre><code>reactiveCollection.Changed.Subscribe(_ => ...);\n</code></pre>\n"
},
{
"answer_id": 15169241,
"author": "Ovi",
"author_id": 7233,
"author_profile": "https://Stackoverflow.com/users/7233",
"pm_score": 0,
"selected": false,
"text": "<p>@soren.enemaerke Made this a reply in order to post proper code as the comments section on your answer would render it unreadable.\nThe only issue I've had with the solution is that the particular element which triggers the <code>PropertyChanged</code> event is lost and you have no way of knowing in the <code>PropertyChanged</code> call.</p>\n\n<pre><code>col.PropertyChanged += (s, e) => { Trace.WriteLine(\"Changed \" + e.PropertyName)\n</code></pre>\n\n<p>To fix this I've created a new class <code>PropertyChangedEventArgsEx</code> and changed the <code>ContainedElementChanged</code> method within your class.</p>\n\n<p><em>new class</em></p>\n\n<pre><code>public class PropertyChangedEventArgsEx : PropertyChangedEventArgs\n{\n public object Sender { get; private set; }\n\n public PropertyChangedEventArgsEx(string propertyName, object sender) \n : base(propertyName)\n {\n this.Sender = sender;\n }\n}\n</code></pre>\n\n<p><em>changes to your class</em></p>\n\n<pre><code> private void ContainedElementChanged(object sender, PropertyChangedEventArgs e)\n {\n var ex = new PropertyChangedEventArgsEx(e.PropertyName, sender);\n OnPropertyChanged(ex);\n }\n</code></pre>\n\n<p>After this you can get the actual <code>Sender</code> element in <code>col.PropertyChanged += (s, e)</code> by casting <code>e</code> to <code>PropertyChangedEventArgsEx</code></p>\n\n<pre><code>((INotifyPropertyChanged)col).PropertyChanged += (s, e) =>\n {\n var argsEx = (PropertyChangedEventArgsEx)e;\n Trace.WriteLine(argsEx.Sender.ToString());\n };\n</code></pre>\n\n<p>Again, you should note the the <code>s</code> here is the collection of elements, not the actual element that triggered the event. Hence the new <code>Sender</code> property in the <code>PropertyChangedEventArgsEx</code> class.</p>\n"
},
{
"answer_id": 25675556,
"author": "Dave Sexton",
"author_id": 3970148,
"author_profile": "https://Stackoverflow.com/users/3970148",
"pm_score": 0,
"selected": false,
"text": "<p>Rxx 2.0 contains <a href=\"https://rxx.codeplex.com/SourceControl/latest#Main/Source/Rxx/System/Reactive/Linq/Observable2%20-%20PropertyChanges.cs\" rel=\"nofollow\">operators</a> that along with this <a href=\"https://rxx.codeplex.com/SourceControl/latest#Main/Source/Rxx/System/Reactive/NotifyCollectionChangedExtensions.cs\" rel=\"nofollow\">conversion operator</a> for <code>ObservableCollection<T></code> makes it easy to achieve your goal.</p>\n\n<pre><code>ObservableCollection<MyClass> collection = ...;\n\nvar changes = collection.AsCollectionNotifications<MyClass>();\nvar itemChanges = changes.PropertyChanges();\nvar deepItemChanges = changes.PropertyChanges(\n item => item.ChildItems.AsCollectionNotifications<MyChildClass>());\n</code></pre>\n\n<p>The following property changed notification patterns are supported for <code>MyClass</code> and <code>MyChildClass</code>: </p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/System.ComponentModel.INotifyPropertyChanged(v=vs.110).aspx\" rel=\"nofollow\">INotifyPropertyChanged</a></li>\n<li>[Property]Changed event pattern (legacy, for use by Component Model)</li>\n<li>WPF dependency properties</li>\n</ul>\n"
},
{
"answer_id": 48674119,
"author": "Scott Chamberlain",
"author_id": 80274,
"author_profile": "https://Stackoverflow.com/users/80274",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way to do it is just do</p>\n\n<pre><code>using System.ComponentModel;\npublic class Example\n{\n BindingList<Foo> _collection;\n\n public Example()\n {\n _collection = new BindingList<Foo>();\n _collection.ListChanged += Collection_ListChanged;\n }\n\n void Collection_ListChanged(object sender, ListChangedEventArgs e)\n {\n MessageBox.Show(e.ListChangedType.ToString());\n }\n\n}\n</code></pre>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/ms132742(v=vs.110).aspx\" rel=\"nofollow noreferrer\">BindingList</a> class as been in .net sence 2.0. It will fire it's <code>ListChanged</code> event any time a item in the collection fires <code>INotifyPropertyChanged</code>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9222/"
] |
Is there a collection (BCL or other) that has the following characteristics:
Sends event if collection is changed AND sends event if any of the elements in the collection sends a `PropertyChanged` event. Sort of an `ObservableCollection<T>` where `T: INotifyPropertyChanged` and the collection is also monitoring the elements for changes.
I could wrap an observable collection my self and do the event subscribe/unsubscribe when elements in the collection are added/removed but I was just wondering if any existing collections did this already?
|
Made a quick implementation myself:
```
public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
Unsubscribe(e.OldItems);
Subscribe(e.NewItems);
base.OnCollectionChanged(e);
}
protected override void ClearItems()
{
foreach(T element in this)
element.PropertyChanged -= ContainedElementChanged;
base.ClearItems();
}
private void Subscribe(IList iList)
{
if (iList != null)
{
foreach (T element in iList)
element.PropertyChanged += ContainedElementChanged;
}
}
private void Unsubscribe(IList iList)
{
if (iList != null)
{
foreach (T element in iList)
element.PropertyChanged -= ContainedElementChanged;
}
}
private void ContainedElementChanged(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(e);
}
}
```
Admitted, it would be kind of confusing and misleading to have the PropertyChanged fire on the collection when the property that actually changed is on a contained element, but it would fit my specific purpose. It could be extended with a new event that is fired instead inside ContainerElementChanged
Thoughts?
EDIT: Should note that the BCL ObservableCollection only exposes the INotifyPropertyChanged interface through an explicit implementation so you would need to provide a cast in order to attach to the event like so:
```
ObservableCollectionEx<Element> collection = new ObservableCollectionEx<Element>();
((INotifyPropertyChanged)collection).PropertyChanged += (x,y) => ReactToChange();
```
EDIT2: Added handling of ClearItems, thanks Josh
EDIT3: Added a correct unsubscribe for PropertyChanged, thanks Mark
EDIT4: Wow, this is really learn-as-you-go :). KP noted that the event was fired with the collection as sender and not with the element when the a contained element changes. He suggested declaring a PropertyChanged event on the class marked with *new*. This would have a few issues which I'll try to illustrate with the sample below:
```
// work on original instance
ObservableCollection<TestObject> col = new ObservableCollectionEx<TestObject>();
((INotifyPropertyChanged)col).PropertyChanged += (s, e) => { Trace.WriteLine("Changed " + e.PropertyName); };
var test = new TestObject();
col.Add(test); // no event raised
test.Info = "NewValue"; //Info property changed raised
// working on explicit instance
ObservableCollectionEx<TestObject> col = new ObservableCollectionEx<TestObject>();
col.PropertyChanged += (s, e) => { Trace.WriteLine("Changed " + e.PropertyName); };
var test = new TestObject();
col.Add(test); // Count and Item [] property changed raised
test.Info = "NewValue"; //no event raised
```
You can see from the sample that 'overriding' the event has the side effect that you need to be extremely careful of which type of variable you use when subscribing to the event since that dictates which events you receive.
|
269,080 |
<p>I am trying to write an interface between RSPEC (ruby flavoured BDD) and a Windows application. The application itself is written in an obscure language, but it has a C API to provide access. I've gone with Ruby/DL but am having difficulties getting even the most basic call to a DLL method to work. Here is what I have so far, in a file called gt4r.rb:</p>
<pre><code>require 'dl/import'
module Gt4r
extend DL::Importable
dlload 'c:\\gtdev\\r321\\bin\\gtvapi'
# GTD initialization/termination functions
extern 'int GTD_init(char *[], char *, char *)'
extern 'int GTD_initialize(char *, char *, char *)'
extern 'int GTD_done(void)'
extern 'int GTD_get_error_message(int, char **)'
end
</code></pre>
<p>My reading so far suggests that this is all I need to get going, so I wrote up a RSPEC example:</p>
<pre><code>require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
rv.should == 0
end
end
</code></pre>
<p>And when run...</p>
<pre><code>C:\code\GraphTalk>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (FAILED - 1)
1)
'Gt4r initializes' FAILED
expected: 0,
got: 13 (using ==)
./gt4r_spec.rb:9:
Finished in 0.031 seconds
1 example, 1 failure
</code></pre>
<p>The return value (13) is an actual return code, meaning an error, but when I try to add the gTD_get_error_message call to my RSPEC, I can't get the parameters to work.</p>
<p>Am I heading in the right direction and can anyone point to the next thing I can try?</p>
<p>Thanks,
Brett</p>
<hr>
<p>A follow up to this question, showing the part that fails when I try to get the error message from my target library:</p>
<pre><code>require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
Gt4r.gTD_get_error_message rv, @msg
@msg.should == ""
rv.should == 0
end
end
</code></pre>
<p>I expect the error message to be returned in @msg, but when run I get the following:</p>
<pre><code>Gt4r
(eval):5: [BUG] Segmentation fault
ruby 1.8.6 (2008-08-11) [i386-mswin32]
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
</code></pre>
<p>And this if I use a symbol (:msg) instead:</p>
<pre><code>C:\code\GraphTalk\gt4r_dl>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (ERROR - 1)
1)
NoMethodError in 'Gt4r initializes'
undefined method `to_ptr' for :msg:Symbol
(eval):5:in `call'
(eval):5:in `gTD_get_error_message'
./gt4r_spec.rb:9:
Finished in 0.046 seconds
1 example, 1 failure
</code></pre>
<p>Clearly I am missing something about passing parameters between ruby and C, but what?</p>
|
[
{
"answer_id": 269645,
"author": "a2800276",
"author_id": 27408,
"author_profile": "https://Stackoverflow.com/users/27408",
"pm_score": 4,
"selected": true,
"text": "<p>The general consensus is you want to avoid DL as much as possible. The (english) documentation is quite sketchy and the interface is difficult to use for anything but trivial examples.</p>\n\n<p>Ruby native C interface is MUCH easier to program against. Or you could use FFI, which fills a similiar niche to DL, originally comes from the rubinius project and has recently been ported to \"normal\" ruby. It has a nicer interface and is much less painful to use:</p>\n\n<p><a href=\"http://blog.headius.com/2008/10/ffi-for-ruby-now-available.html\" rel=\"noreferrer\">http://blog.headius.com/2008/10/ffi-for-ruby-now-available.html</a></p>\n"
},
{
"answer_id": 269662,
"author": "a2800276",
"author_id": 27408,
"author_profile": "https://Stackoverflow.com/users/27408",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>The return value (13) is an actual\n return code, meaning an error, but\n when I try to add the\n gTD_get_error_message call to my\n RSPEC, I can't get the parameters to\n work.</p>\n</blockquote>\n\n<p>It might help posting the error instead of the code that worked :) </p>\n\n<p>Basically, once you start having to deal with pointers as in (int, char **), things get ugly. </p>\n"
},
{
"answer_id": 468399,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You need to allocate the data pointer for msg to be written to, since otherise C will have nowhere to write the error messages. Use DL.mallo.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32322/"
] |
I am trying to write an interface between RSPEC (ruby flavoured BDD) and a Windows application. The application itself is written in an obscure language, but it has a C API to provide access. I've gone with Ruby/DL but am having difficulties getting even the most basic call to a DLL method to work. Here is what I have so far, in a file called gt4r.rb:
```
require 'dl/import'
module Gt4r
extend DL::Importable
dlload 'c:\\gtdev\\r321\\bin\\gtvapi'
# GTD initialization/termination functions
extern 'int GTD_init(char *[], char *, char *)'
extern 'int GTD_initialize(char *, char *, char *)'
extern 'int GTD_done(void)'
extern 'int GTD_get_error_message(int, char **)'
end
```
My reading so far suggests that this is all I need to get going, so I wrote up a RSPEC example:
```
require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
rv.should == 0
end
end
```
And when run...
```
C:\code\GraphTalk>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (FAILED - 1)
1)
'Gt4r initializes' FAILED
expected: 0,
got: 13 (using ==)
./gt4r_spec.rb:9:
Finished in 0.031 seconds
1 example, 1 failure
```
The return value (13) is an actual return code, meaning an error, but when I try to add the gTD\_get\_error\_message call to my RSPEC, I can't get the parameters to work.
Am I heading in the right direction and can anyone point to the next thing I can try?
Thanks,
Brett
---
A follow up to this question, showing the part that fails when I try to get the error message from my target library:
```
require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
Gt4r.gTD_get_error_message rv, @msg
@msg.should == ""
rv.should == 0
end
end
```
I expect the error message to be returned in @msg, but when run I get the following:
```
Gt4r
(eval):5: [BUG] Segmentation fault
ruby 1.8.6 (2008-08-11) [i386-mswin32]
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
```
And this if I use a symbol (:msg) instead:
```
C:\code\GraphTalk\gt4r_dl>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (ERROR - 1)
1)
NoMethodError in 'Gt4r initializes'
undefined method `to_ptr' for :msg:Symbol
(eval):5:in `call'
(eval):5:in `gTD_get_error_message'
./gt4r_spec.rb:9:
Finished in 0.046 seconds
1 example, 1 failure
```
Clearly I am missing something about passing parameters between ruby and C, but what?
|
The general consensus is you want to avoid DL as much as possible. The (english) documentation is quite sketchy and the interface is difficult to use for anything but trivial examples.
Ruby native C interface is MUCH easier to program against. Or you could use FFI, which fills a similiar niche to DL, originally comes from the rubinius project and has recently been ported to "normal" ruby. It has a nicer interface and is much less painful to use:
<http://blog.headius.com/2008/10/ffi-for-ruby-now-available.html>
|
269,081 |
<pre><code>template <class M, class A> class C { std::list<M> m_List; ... }
</code></pre>
<p>Is the above code possible? I would like to be able to do something similar.</p>
<p>Why I ask is that i get the following error:</p>
<pre><code>Error 1 error C2079: 'std::_List_nod<_Ty,_Alloc>::_Node::_Myval' uses undefined class 'M' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\list 41
</code></pre>
|
[
{
"answer_id": 269095,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 2,
"selected": false,
"text": "<p>Yes. This is very common.</p>\n\n<p>As xtofl mentioned, a forward declaration of your parameter would cause a problem at the time of template instantiation, which looks like what the error message is hinting at.</p>\n"
},
{
"answer_id": 269143,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. </p>\n\n<p>It is used a lot by the STL for things like allocators and iterators.</p>\n\n<p>It looks like you are running into some other issue. Perhaps you are missing a template on an out of line method body definition that was first declared in the ... you elided?</p>\n"
},
{
"answer_id": 269171,
"author": "Joe Corkery",
"author_id": 7587,
"author_profile": "https://Stackoverflow.com/users/7587",
"pm_score": 1,
"selected": false,
"text": "<p>This is a very common usage. </p>\n\n<p>You should make sure that the class M that is specified as the template parameter is fully declared before the creation of the first instance of class C. Perhaps you are missing a header file include or perhaps this is a namespace issue.</p>\n"
},
{
"answer_id": 269206,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 3,
"selected": true,
"text": "<p>My guess: you forward declared class M somewhere, and only declared it fully after the template instantiation.</p>\n\n<p>My hint: give your formal template arguments a different name than the actual ones. (i.e. class M)</p>\n\n<pre><code>// template definition file\n#include <list>\n\ntemplate< class aM, class aT >\nclass C {\n std::list<M> m_List;\n ...\n};\n</code></pre>\n\n<p>Example of a bad forward declaration, resulting in the mentioned error:</p>\n\n<pre><code>// bad template usage file causing the aforementioned error\nclass M;\n...\nC<M,OtherClass> c; // this would result in your error\n\nclass M { double data; };\n</code></pre>\n\n<p>Example of proper declaration, not resulting in the error:</p>\n\n<pre><code>// better template usage file\nclass M { double data; }; // or #include the class header\n...\n\nC<M,OtherClass> c; // this would have to compile\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23528/"
] |
```
template <class M, class A> class C { std::list<M> m_List; ... }
```
Is the above code possible? I would like to be able to do something similar.
Why I ask is that i get the following error:
```
Error 1 error C2079: 'std::_List_nod<_Ty,_Alloc>::_Node::_Myval' uses undefined class 'M' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\list 41
```
|
My guess: you forward declared class M somewhere, and only declared it fully after the template instantiation.
My hint: give your formal template arguments a different name than the actual ones. (i.e. class M)
```
// template definition file
#include <list>
template< class aM, class aT >
class C {
std::list<M> m_List;
...
};
```
Example of a bad forward declaration, resulting in the mentioned error:
```
// bad template usage file causing the aforementioned error
class M;
...
C<M,OtherClass> c; // this would result in your error
class M { double data; };
```
Example of proper declaration, not resulting in the error:
```
// better template usage file
class M { double data; }; // or #include the class header
...
C<M,OtherClass> c; // this would have to compile
```
|
269,093 |
<p>I've a terrible memory. Whenever I do a CONNECT BY query in Oracle - and I do mean <em>every</em> time - I have to think hard and usually through trial and error work out on which argument the PRIOR should go.</p>
<p>I don't know why I don't remember - but I don't.</p>
<p>Does anyone have a handy memory mnemonic so I always remember ?</p>
<p>For example:</p>
<p>To go <strong>down</strong> a tree from a node - obviously I had to look this up :) - you do something like:</p>
<pre><code>select
*
from
node
connect by
prior node_id = parent_node_id
start with
node_id = 1
</code></pre>
<p>So - I start with a <code>node_id</code> of 1 (the top of the branch) and the query looks for all nodes where the <code>parent_node_id</code> = 1 and then iterates down to the bottom of the tree.</p>
<p>To go <strong>up</strong> the tree the prior goes on the parent:</p>
<pre><code>select
*
from
node
connect by
node_id = prior parent_node_id
start with
node_id = 10
</code></pre>
<p>So starting somewhere down a branch (<code>node_id = 10</code> in this case) Oracle first gets all nodes where the <code>parent_node_id</code> is the same as the one for which <code>node_id</code> is 10.</p>
<p><strong>EDIT</strong>: I <strong>still</strong> get this wrong so thought I'd add a clarifying edit to expand on the accepted answer - here's how I remember it now:</p>
<pre><code>select
*
from
node
connect by
prior node_id = parent_node_id
start with
node_id = 1
</code></pre>
<p>The 'english language' version of this SQL I now read as...</p>
<blockquote>
<p>In NODE, starting with the row in
which <code>node_id = 1</code>, the next row
selected has its <code>parent_node_id</code>
equal to <code>node_id</code> from the previous
(prior) row.</p>
</blockquote>
<p><strong>EDIT</strong>: Quassnoi makes a great point - the order you write the SQL makes things a lot easier.</p>
<pre><code>select
*
from
node
start with
node_id = 1
connect by
parent_node_id = prior node_id
</code></pre>
<p>This feels a lot clearer to me - the "start with" gives the first row selected and the "connect by" gives the next row(s) - in this case the children of node_id = 1.</p>
|
[
{
"answer_id": 269122,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": true,
"text": "<p>Think about the order in which the records are going to be selected: the link-back column on each record must match the link-forward column on the PRIOR record selected.</p>\n"
},
{
"answer_id": 754290,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": false,
"text": "<p>I always try to put the expressions in <code>JOIN</code>'s in the following order:</p>\n\n<pre><code>joined.column = leading.column\n</code></pre>\n\n<p>This query:</p>\n\n<pre><code>SELECT t.value, d.name\nFROM transactions t\nJOIN\n dimensions d\nON d.id = t.dimension\n</code></pre>\n\n<p>can be treated either like \"for each transaction, find the corresponding dimension name\", or \"for each dimension, find all corresponding transaction values\".</p>\n\n<p>So, if I search for a given transaction, I put the expressions in the following order:</p>\n\n<pre><code>SELECT t.value, d.name\nFROM transactions t\nJOIN\n dimensions d\nON d.id = t.dimension\nWHERE t.id = :myid\n</code></pre>\n\n<p>, and if I search for a dimension, then:</p>\n\n<pre><code>SELECT t.value, d.name\nFROM dimensions d\nJOIN\n transactions t\nON t.dimension = d.id\nWHERE d.id = :otherid\n</code></pre>\n\n<p>Ther former query will most probably use index scans first on <code>(t.id)</code>, then on (<code>d.id</code>), while the latter one will use index scans first on <code>(d.id)</code>, then on <code>(t.dimension)</code>, and you can easily see it in the query itself: the searched fields are at left.</p>\n\n<p>The driving and driven tables may be not so obvious in a <code>JOIN</code>, but it's as clear as a bell for a <code>CONNECT BY</code> query: the <code>PRIOR</code> row is driving, the non-<code>PRIOR</code> is driven.</p>\n\n<p>That's why this query:</p>\n\n<pre><code>SELECT *\nFROM hierarchy\nSTART WITH\n id = :root\nCONNECT BY\n parent = PRIOR id\n</code></pre>\n\n<p>means \"find all rows whose <code>parent</code> is a given <code>id</code>\". This query builds a hierarchy.</p>\n\n<p>This can be treated like this:</p>\n\n<pre><code>connect_by(row) {\n add_to_rowset(row);\n\n /* parent = PRIOR id */\n /* PRIOR id is an rvalue */\n index_on_parent.searchKey = row->id;\n\n foreach child_row in index_on_parent.search {\n connect_by(child_row);\n }\n}\n</code></pre>\n\n<p>And this query:</p>\n\n<pre><code>SELECT *\nFROM hierarchy\nSTART WITH\n id = :leaf\nCONNECT BY\n id = PRIOR parent\n</code></pre>\n\n<p>means \"find the rows whose <code>id</code> is a given <code>parent</code>\". This query builds an ancestry chain.</p>\n\n<p><strong>Always put <code>PRIOR</code> in the right part of the expression.</strong></p>\n\n<p><strong>Think of <code>PRIOR column</code> as of a constant all your rows will be searched for.</strong></p>\n"
},
{
"answer_id": 53173301,
"author": "cartbeforehorse",
"author_id": 1176987,
"author_profile": "https://Stackoverflow.com/users/1176987",
"pm_score": 0,
"selected": false,
"text": "<p>Part of the reason that this is difficult to visualise each time, is because sometimes the data is modelled as <code>id</code> + <code>child_id</code>, and sometimes it is modelled as <code>id</code> + <code>parent_id</code>. Depending on which way round your data is modelled, you have to place your <code>PRIOR</code> keyword on the the opposite side.</p>\n\n<p>The trick I find, is always to look at the world through the eyes of the leaf-node of the tree you're trying to build.</p>\n\n<p>So (speaking as the leaf node) when I look up, I see my parent node, which I may also refer to as the <code>PRIOR</code> node. Ergo, my <code>ID</code> is the same as his <code>CHILD_ID</code>. So in this case <code>PRIOR child_id = id</code>.</p>\n\n<p>When the data is modelled the other way around (i.e. when I hold my parent's ID rather than him holding mine), my <code>parent_id</code> is the same value as his <code>id</code>. Ergo in this scenario <code>PRIOR id = parent_id</code>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] |
I've a terrible memory. Whenever I do a CONNECT BY query in Oracle - and I do mean *every* time - I have to think hard and usually through trial and error work out on which argument the PRIOR should go.
I don't know why I don't remember - but I don't.
Does anyone have a handy memory mnemonic so I always remember ?
For example:
To go **down** a tree from a node - obviously I had to look this up :) - you do something like:
```
select
*
from
node
connect by
prior node_id = parent_node_id
start with
node_id = 1
```
So - I start with a `node_id` of 1 (the top of the branch) and the query looks for all nodes where the `parent_node_id` = 1 and then iterates down to the bottom of the tree.
To go **up** the tree the prior goes on the parent:
```
select
*
from
node
connect by
node_id = prior parent_node_id
start with
node_id = 10
```
So starting somewhere down a branch (`node_id = 10` in this case) Oracle first gets all nodes where the `parent_node_id` is the same as the one for which `node_id` is 10.
**EDIT**: I **still** get this wrong so thought I'd add a clarifying edit to expand on the accepted answer - here's how I remember it now:
```
select
*
from
node
connect by
prior node_id = parent_node_id
start with
node_id = 1
```
The 'english language' version of this SQL I now read as...
>
> In NODE, starting with the row in
> which `node_id = 1`, the next row
> selected has its `parent_node_id`
> equal to `node_id` from the previous
> (prior) row.
>
>
>
**EDIT**: Quassnoi makes a great point - the order you write the SQL makes things a lot easier.
```
select
*
from
node
start with
node_id = 1
connect by
parent_node_id = prior node_id
```
This feels a lot clearer to me - the "start with" gives the first row selected and the "connect by" gives the next row(s) - in this case the children of node\_id = 1.
|
Think about the order in which the records are going to be selected: the link-back column on each record must match the link-forward column on the PRIOR record selected.
|
269,096 |
<p>I'm trying to create a WSTransfer implementation (I realise Roman Kiss has written one already for WCF - but it doesn't actually meet the specifications)</p>
<p>I've ended up abandoning data contracts on the service contacts because WSTransfer is loosely coupled; so each the create message looks like Message Create(Message request).</p>
<p>This works fine, and everything is lovely until it's time to fire back a response.</p>
<p>The problem I have is in the way a WSTransfer response is constructed. Taking create as the example the response looks like</p>
<pre><code><wxf:ResourceCreated>
<wsa:Address>....</wsa:Address>
<wsa:ReferenceProperties>
<xxx:MyID>....</xxx:MyId>
</wsa:ReferenceProperties>
</wxf:ResourceCreated>
</code></pre>
<p>As you can see there are 3 different XML namespaces within the response message.</p>
<p>Now, it's easy enough when one is involved; you can (even if you're not exposing it), create a data contract and set the values and fire it back </p>
<pre><code>Message response = Message.CreateMessage(request.Version,
"http://schemas.xmlsoap.org/ws/2004/09/transfer/CreateResponse",
resourceCreatedMessage);
</code></pre>
<p>However the problem arises in setting different namespaces for the child elements within the response; it appears WCF's datacontracts don't do this. Even using</p>
<pre><code>[MessageBodyMember(Namespace="....")]
</code></pre>
<p>on the individual elements within the response class don't appear to make any changes, everything becomes part of the namespace specified for the contract class.</p>
<p>So how do I apply different namespaces to individual elements in a WCF Message; either via a contract, or via some other jiggery pokery?</p>
|
[
{
"answer_id": 269122,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": true,
"text": "<p>Think about the order in which the records are going to be selected: the link-back column on each record must match the link-forward column on the PRIOR record selected.</p>\n"
},
{
"answer_id": 754290,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": false,
"text": "<p>I always try to put the expressions in <code>JOIN</code>'s in the following order:</p>\n\n<pre><code>joined.column = leading.column\n</code></pre>\n\n<p>This query:</p>\n\n<pre><code>SELECT t.value, d.name\nFROM transactions t\nJOIN\n dimensions d\nON d.id = t.dimension\n</code></pre>\n\n<p>can be treated either like \"for each transaction, find the corresponding dimension name\", or \"for each dimension, find all corresponding transaction values\".</p>\n\n<p>So, if I search for a given transaction, I put the expressions in the following order:</p>\n\n<pre><code>SELECT t.value, d.name\nFROM transactions t\nJOIN\n dimensions d\nON d.id = t.dimension\nWHERE t.id = :myid\n</code></pre>\n\n<p>, and if I search for a dimension, then:</p>\n\n<pre><code>SELECT t.value, d.name\nFROM dimensions d\nJOIN\n transactions t\nON t.dimension = d.id\nWHERE d.id = :otherid\n</code></pre>\n\n<p>Ther former query will most probably use index scans first on <code>(t.id)</code>, then on (<code>d.id</code>), while the latter one will use index scans first on <code>(d.id)</code>, then on <code>(t.dimension)</code>, and you can easily see it in the query itself: the searched fields are at left.</p>\n\n<p>The driving and driven tables may be not so obvious in a <code>JOIN</code>, but it's as clear as a bell for a <code>CONNECT BY</code> query: the <code>PRIOR</code> row is driving, the non-<code>PRIOR</code> is driven.</p>\n\n<p>That's why this query:</p>\n\n<pre><code>SELECT *\nFROM hierarchy\nSTART WITH\n id = :root\nCONNECT BY\n parent = PRIOR id\n</code></pre>\n\n<p>means \"find all rows whose <code>parent</code> is a given <code>id</code>\". This query builds a hierarchy.</p>\n\n<p>This can be treated like this:</p>\n\n<pre><code>connect_by(row) {\n add_to_rowset(row);\n\n /* parent = PRIOR id */\n /* PRIOR id is an rvalue */\n index_on_parent.searchKey = row->id;\n\n foreach child_row in index_on_parent.search {\n connect_by(child_row);\n }\n}\n</code></pre>\n\n<p>And this query:</p>\n\n<pre><code>SELECT *\nFROM hierarchy\nSTART WITH\n id = :leaf\nCONNECT BY\n id = PRIOR parent\n</code></pre>\n\n<p>means \"find the rows whose <code>id</code> is a given <code>parent</code>\". This query builds an ancestry chain.</p>\n\n<p><strong>Always put <code>PRIOR</code> in the right part of the expression.</strong></p>\n\n<p><strong>Think of <code>PRIOR column</code> as of a constant all your rows will be searched for.</strong></p>\n"
},
{
"answer_id": 53173301,
"author": "cartbeforehorse",
"author_id": 1176987,
"author_profile": "https://Stackoverflow.com/users/1176987",
"pm_score": 0,
"selected": false,
"text": "<p>Part of the reason that this is difficult to visualise each time, is because sometimes the data is modelled as <code>id</code> + <code>child_id</code>, and sometimes it is modelled as <code>id</code> + <code>parent_id</code>. Depending on which way round your data is modelled, you have to place your <code>PRIOR</code> keyword on the the opposite side.</p>\n\n<p>The trick I find, is always to look at the world through the eyes of the leaf-node of the tree you're trying to build.</p>\n\n<p>So (speaking as the leaf node) when I look up, I see my parent node, which I may also refer to as the <code>PRIOR</code> node. Ergo, my <code>ID</code> is the same as his <code>CHILD_ID</code>. So in this case <code>PRIOR child_id = id</code>.</p>\n\n<p>When the data is modelled the other way around (i.e. when I hold my parent's ID rather than him holding mine), my <code>parent_id</code> is the same value as his <code>id</code>. Ergo in this scenario <code>PRIOR id = parent_id</code>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525/"
] |
I'm trying to create a WSTransfer implementation (I realise Roman Kiss has written one already for WCF - but it doesn't actually meet the specifications)
I've ended up abandoning data contracts on the service contacts because WSTransfer is loosely coupled; so each the create message looks like Message Create(Message request).
This works fine, and everything is lovely until it's time to fire back a response.
The problem I have is in the way a WSTransfer response is constructed. Taking create as the example the response looks like
```
<wxf:ResourceCreated>
<wsa:Address>....</wsa:Address>
<wsa:ReferenceProperties>
<xxx:MyID>....</xxx:MyId>
</wsa:ReferenceProperties>
</wxf:ResourceCreated>
```
As you can see there are 3 different XML namespaces within the response message.
Now, it's easy enough when one is involved; you can (even if you're not exposing it), create a data contract and set the values and fire it back
```
Message response = Message.CreateMessage(request.Version,
"http://schemas.xmlsoap.org/ws/2004/09/transfer/CreateResponse",
resourceCreatedMessage);
```
However the problem arises in setting different namespaces for the child elements within the response; it appears WCF's datacontracts don't do this. Even using
```
[MessageBodyMember(Namespace="....")]
```
on the individual elements within the response class don't appear to make any changes, everything becomes part of the namespace specified for the contract class.
So how do I apply different namespaces to individual elements in a WCF Message; either via a contract, or via some other jiggery pokery?
|
Think about the order in which the records are going to be selected: the link-back column on each record must match the link-forward column on the PRIOR record selected.
|
269,101 |
<p>I'm using the code below to save a password to the registry, how do I convert it back? The code below isn't mine but it encrypts well.</p>
<p>Thanks</p>
<pre><code>using System.Security.Cryptography;
public static string EncodePasswordToBase64(string password)
{ byte[] bytes = Encoding.Unicode.GetBytes(password);
byte[] dst = new byte[bytes.Length];
byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
</code></pre>
|
[
{
"answer_id": 269114,
"author": "Lazarus",
"author_id": 19540,
"author_profile": "https://Stackoverflow.com/users/19540",
"pm_score": 3,
"selected": false,
"text": "<p>Take whatever the user enters as a password to gain access to the system, encrypt it the same way and then compare the encrypted values, that's the normal approach. I'm pretty sure that SHA1 is a trapdoor encryption, i.e. can't be back-tracked.</p>\n"
},
{
"answer_id": 269115,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 2,
"selected": false,
"text": "<p>I think one of the points of using hashes is that they can't be computed back.</p>\n\n<p>As someone else said, calculate the hash from the user's password and compare to the stored hash value.</p>\n"
},
{
"answer_id": 269121,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 5,
"selected": false,
"text": "<p>SHA1 is a <em>hash</em> algorithm, not an encryption algorithm. A hash algorithm is a one-way function which transforms data into a hash of that data, but the original data cannot be gotten back from the hash. An encryption algorithm is a two-way function which transforms data into encrypted data, and the encrypted data can then be transformed back into the original data.</p>\n"
},
{
"answer_id": 269125,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 3,
"selected": false,
"text": "<p>You don't.</p>\n\n<p>SHA1 is a hash, not encryption. It is a one-way operation; conversion back is not possible.</p>\n\n<p>(Ok this is not strictly true; if you have a table of possible SHA1 values and plain text values, a rainbow table then you might be luck)</p>\n\n<p>Also you should be salting your hashes, because you are, right now, vulnerable to rainbow table attacks. Jeff <a href=\"http://www.codinghorror.com/blog/archives/000949.html\" rel=\"nofollow noreferrer\">talks about this</a> a little more on his blog</p>\n"
},
{
"answer_id": 269126,
"author": "Duncan",
"author_id": 7140,
"author_profile": "https://Stackoverflow.com/users/7140",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, so I know this isn't answering your specific Q, but why do you want to convert it back?</p>\n\n<p>If it's to compare in order to provide authentication, the standard approach is to encrypt this text ALSO, and compare the stored password to the supplied password.</p>\n\n<p>This is more secure as it means that the original password never needs to be decrypted.</p>\n"
},
{
"answer_id": 269154,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 1,
"selected": false,
"text": "<p>Um, just curious but wouldn't that return the same hash for all passwords of the same length?</p>\n"
},
{
"answer_id": 269218,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 4,
"selected": false,
"text": "<p>To securely store a password so that it can be read back, use the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx\" rel=\"noreferrer\">ProtectedData</a> class.</p>\n\n<pre><code>public static string ProtectPassword(string password)\n{\n byte[] bytes = Encoding.Unicode.GetBytes(password);\n byte[] protectedPassword = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);\n return Convert.ToBase64String(protectedPassword);\n}\n\npublic static string UnprotectPassword(string protectedPassword)\n{\n byte[] bytes = Convert.FromBase64String(protectedPassword);\n byte[] password = ProtectedData.Unprotect(bytes, null, DataProtectionScope.CurrentUser);\n return Encoding.Unicode.GetString(password);\n}\n</code></pre>\n"
},
{
"answer_id": 269237,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 0,
"selected": false,
"text": "<p>Using your own code snippet above, what you want to do is call that method when the user initially chooses a password - but add to the password what is called a <a href=\"http://en.wikipedia.org/wiki/Salt_(cryptography)\" rel=\"nofollow noreferrer\">salt</a> somewhere in the password string (usually at the beginning or end). Then, when the user is attempting to authenticate later, they enter their password, you run that one along with the hash through this same method and if the two hashes are equal, it's a statistically excellent chance the passwords are equal and valid.</p>\n\n<p>This being said, SHA1 is known to have weaknesses and you should choose a stronger algorithm. If you want to stay in the SHA family, SHA512 is pretty good.</p>\n"
},
{
"answer_id": 269391,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "<p>You want to use encryption not hashing. SHA is fine but use the encryption methods for it. The problem with encryption is always where to put the key for it. You didn't mention whether this was a workstation or server you were doing this on. On a server, I find it better to just use ACL's to restrict access to the reg key. Admins can usually access the encryption key anyway...you have to have some trust somewhere. On a workstation then you can go with encryption and store the key in code or use a certificate and restrict access to it at least in a corp environment...not for sale software).</p>\n\n<p>You can use the ProtectedData class but be aware that it uses user profiles for its key usage and as such you have to make sure you are impersonating the user who has the profile with the key you need. This may or may not be trivial and may or may not cause headaches and security issues.</p>\n"
},
{
"answer_id": 269878,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In order to use the System.Security.Cryptography.ProtectedData class, you must add a reference to System.Security to your project.</p>\n\n<p>(Right mouse click on the References folder, choose \"Add Reference...\", find System.Security on the .NET Tab)</p>\n"
},
{
"answer_id": 399384,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I noticed the recent addition of the XMLEncryptedData class. For encrypting data to an XML file, is the XMLEncryptedData method more desirable than the DPAPI method?</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm using the code below to save a password to the registry, how do I convert it back? The code below isn't mine but it encrypts well.
Thanks
```
using System.Security.Cryptography;
public static string EncodePasswordToBase64(string password)
{ byte[] bytes = Encoding.Unicode.GetBytes(password);
byte[] dst = new byte[bytes.Length];
byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
```
|
SHA1 is a *hash* algorithm, not an encryption algorithm. A hash algorithm is a one-way function which transforms data into a hash of that data, but the original data cannot be gotten back from the hash. An encryption algorithm is a two-way function which transforms data into encrypted data, and the encrypted data can then be transformed back into the original data.
|
269,124 |
<p>I am reading a binary log file produced by a piece of equipment. </p>
<p>I have the data in a byte[]. </p>
<p>If I need to read two bytes to create a short I can do something like this:</p>
<pre><code>short value = (short)(byte[1] << 8);
value += byte[2];
</code></pre>
<p>Now I know the value is the correct for valid data. </p>
<p>How would I know if the file was messed up and lets say the values FF FF were in those two places in the byte array?</p>
<p>When I look at the resultant value of converting FF FF to a short, I get a -1.</p>
<p>Is this a normal value for FF FF?, or did the computer just hit some kind of short bound and roll over with invalid data?</p>
<p>For my purposes all of theses numbers are going to be positive. If FF FF is actually a short -1, then I just need to validate that all my results are postitive. </p>
<p>Thank you,<br>
Keith</p>
<p><em>BTW, I am also reading other number data types. I'll show them here just because.
The Read function is the basic part of reading from the byte[]. All the other data type reads use the basic Read() function.</em></p>
<pre><code> public byte Read()
{
//advance position and then return byte at position
byte returnValue;
if (_CurrentPosition < _count - 1)
{
returnValue= _array[_offset + ++_CurrentPosition];
return returnValue;
}
else
throw new System.IO.EndOfStreamException
("Cannot Read Array, at end of stream.");
}
public float ReadFloat()
{
byte[] floatTemp = new byte[4];
for (int i = 3; i >= 0; i--)
{
floatTemp[i] = Read();
}
float returnValue = System.BitConverter.ToSingle
(floatTemp, 0);
if (float.IsNaN(returnValue))
{
throw new Execption("Not a Number");
}
return returnValue;
}
public short ReadInt16()
{
short returnValue = (short)(Read() << 8);
returnValue += Read();
return returnValue;
}
public int ReadInt32()
{
int returnValue = Read() << 24;
returnValue += Read() << 16;
returnValue += Read() << 8;
returnValue += Read();
return returnValue;
}
</code></pre>
|
[
{
"answer_id": 269142,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 1,
"selected": false,
"text": "<p>Did you try to use ushort (unsigned short)?</p>\n"
},
{
"answer_id": 269152,
"author": "Joe Corkery",
"author_id": 7587,
"author_profile": "https://Stackoverflow.com/users/7587",
"pm_score": 0,
"selected": false,
"text": "<p>The value of FFFF for a \"short\" is -1 but the value of FFFF for an \"unsigned short\" is 65536. </p>\n\n<p>In this case you should make sure you are using an unsigned short if you are sure that all of your values will be positive.</p>\n"
},
{
"answer_id": 269156,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": true,
"text": "<p><code>0xffff</code> (all bits equal to 1) is -1 for signed shorts, yes. Read up on <a href=\"http://en.wikipedia.org/wiki/Two's_complement\" rel=\"nofollow noreferrer\">Two's complement</a> to learn more about the details. You can switch to a larger datatype, or (as suggested by Grzenio) just use an unsigned type.</p>\n"
},
{
"answer_id": 269201,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Well, you seemed to have found <code>BitConverter</code> for singles. Now let's see if we can get to to use it for everything else as well...</p>\n\n<pre><code>MemoryStream mem = new MemoryStream(_array);\n\n\nfloat ReadFloat(Stream str)\n{\n byte[] bytes = str.Read(out bytes, 0, 4);\n return BitConverter.ToSingle(bytes, 0)\n}\n\npublic int ReadInt32(Stream str)\n{\n byte[] bytes = str.Read(out bytes, 0, 4);\n return BitConverter.ToInt32(bytes, 0)\n}\n</code></pre>\n"
},
{
"answer_id": 269232,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 1,
"selected": false,
"text": "<p>I think you would be better served using the <A href=\"http://msdn.microsoft.com/en-us/library/system.bitconverter_members.aspx\" rel=\"nofollow noreferrer\">System.BitConverter</A> class. </p>\n\n<p>Specifically for shorts the <A href=\"http://msdn.microsoft.com/en-us/library/system.bitconverter.toint16.aspx\" rel=\"nofollow noreferrer\">ToInt16</A> method.</p>\n\n<p>You didn't mention it in your question, but you should also make sure that you know what endianess the hardware device is writing its data in. From your examples it looks like the float is in little endian, but the integers are in big endian? I doubt a hardware device would mix endianess in its output of binary data. </p>\n"
},
{
"answer_id": 269398,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 1,
"selected": false,
"text": "<p>Yes 0xFFFF is -1 for a signed short.</p>\n\n<p>Also, why wouldn't you use the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx\" rel=\"nofollow noreferrer\"><code>BinaryReader</code> class</a>?</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
I am reading a binary log file produced by a piece of equipment.
I have the data in a byte[].
If I need to read two bytes to create a short I can do something like this:
```
short value = (short)(byte[1] << 8);
value += byte[2];
```
Now I know the value is the correct for valid data.
How would I know if the file was messed up and lets say the values FF FF were in those two places in the byte array?
When I look at the resultant value of converting FF FF to a short, I get a -1.
Is this a normal value for FF FF?, or did the computer just hit some kind of short bound and roll over with invalid data?
For my purposes all of theses numbers are going to be positive. If FF FF is actually a short -1, then I just need to validate that all my results are postitive.
Thank you,
Keith
*BTW, I am also reading other number data types. I'll show them here just because.
The Read function is the basic part of reading from the byte[]. All the other data type reads use the basic Read() function.*
```
public byte Read()
{
//advance position and then return byte at position
byte returnValue;
if (_CurrentPosition < _count - 1)
{
returnValue= _array[_offset + ++_CurrentPosition];
return returnValue;
}
else
throw new System.IO.EndOfStreamException
("Cannot Read Array, at end of stream.");
}
public float ReadFloat()
{
byte[] floatTemp = new byte[4];
for (int i = 3; i >= 0; i--)
{
floatTemp[i] = Read();
}
float returnValue = System.BitConverter.ToSingle
(floatTemp, 0);
if (float.IsNaN(returnValue))
{
throw new Execption("Not a Number");
}
return returnValue;
}
public short ReadInt16()
{
short returnValue = (short)(Read() << 8);
returnValue += Read();
return returnValue;
}
public int ReadInt32()
{
int returnValue = Read() << 24;
returnValue += Read() << 16;
returnValue += Read() << 8;
returnValue += Read();
return returnValue;
}
```
|
`0xffff` (all bits equal to 1) is -1 for signed shorts, yes. Read up on [Two's complement](http://en.wikipedia.org/wiki/Two's_complement) to learn more about the details. You can switch to a larger datatype, or (as suggested by Grzenio) just use an unsigned type.
|
269,164 |
<p>I am looking for an elegant solution for removing content from an ASP.Net page if no data has been set. Let me explain this a little more.</p>
<p>I have some blocks of data on a page that contain some sub-sections with individual values in them. If no data has been set for one of the values I need to hide it (so it does not take up space). Also, if none of the values within a sub-section have been set, it needs to be hidden as well. Finally if none of the sub-sections are visible within the block/panel, then I need to hide the entire thing.</p>
<p>The layout is implemented using nested Panels/DIVs</p>
<pre><code><Panel id="block">
<Panel id="sub1">
<Panel id="value1-1">blah</Panel>
<Panel id="value1-2">blah</Panel>
</Panel>
<Panel id="sub2">
<Panel id="value2-1">blah</Panel>
<Panel id="value2-2">blah</Panel>
</Panel>
</panel>
</code></pre>
<p>I am wondering if anyone has any decent ideas on implementing something like this without writing a bunch of nested <strong>If..Else</strong> statements, and without creating a bunch of custom controls. Whatever I implement needs to be robust enough to handle changes in the markup without constantly manipulating the codebehind.</p>
<p>I am hoping there is a way to do this through some simple markup changes (custom attribute) and a recursive function call on PageLoad or PreRender.</p>
<p>Any help is greatly appreciated.</p>
<h2>EDIT:</h2>
<p>Ok so what makes this tricky is that there might be other controls inside the sub-sections that do not factor into the hiding and showing of the controls. And each <em>value</em> panel could potentially have controls in it that do not factor into whether or not it is shown. Example:</p>
<pre><code><Panel id="sub2">
<Image id="someImage" src="img.png" />
<Panel id="value2-1">
<Label>blah</Label>
<TextBox id="txtValue" />
</Panel>
<Panel id="value2-2">blah</Panel>
</Panel>
</code></pre>
<p>This is an over simplified example, but not far off from what I have to worry about.</p>
|
[
{
"answer_id": 269178,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "<p>Use recursion. Traverse the control tree in node first order. Use the visible property of the node as appropriate based on control values. Don't visit children if the parent is set to not visible</p>\n"
},
{
"answer_id": 269190,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>I think you're on the right track with recursion. But I'd stay away from custom attributes - stick to standards. All you really need is to set the Visible property on each panel via your recursive method.</p>\n"
},
{
"answer_id": 269195,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>it may be possible to avoid recursive traversal if you can write functions to return true/false for each group, e.g.</p>\n\n<pre><code><Panel id=\"block\" runat=\"server\" visible=\"<%=IsBlockVisible%>\">\n <Panel id=\"sub1\" runat=\"server\" visible=\"<%=IsSubVisible(1)%>\">\n <Panel id=\"value1-1\">blah</Panel>\n <Panel id=\"value1-2\">blah</Panel>\n </Panel>\n <Panel id=\"sub2\" runat=\"server\" visible=\"<%=IsSubVisible(2)%>\">\n <Panel id=\"value2-1\">blah</Panel>\n <Panel id=\"value2-2\">blah</Panel>\n </Panel>\n</panel>\n</code></pre>\n"
},
{
"answer_id": 269211,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a strict hierarchy block/sub/value and the data comes from a database, I suggest nested Repeaters and a stored procedure which returns 3 result sets</p>\n"
},
{
"answer_id": 269229,
"author": "Lazarus",
"author_id": 19540,
"author_profile": "https://Stackoverflow.com/users/19540",
"pm_score": 0,
"selected": false,
"text": "<p>I think we need to understand more about what you are trying to achieve in order to determine if it's the right approach in the first place.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11702/"
] |
I am looking for an elegant solution for removing content from an ASP.Net page if no data has been set. Let me explain this a little more.
I have some blocks of data on a page that contain some sub-sections with individual values in them. If no data has been set for one of the values I need to hide it (so it does not take up space). Also, if none of the values within a sub-section have been set, it needs to be hidden as well. Finally if none of the sub-sections are visible within the block/panel, then I need to hide the entire thing.
The layout is implemented using nested Panels/DIVs
```
<Panel id="block">
<Panel id="sub1">
<Panel id="value1-1">blah</Panel>
<Panel id="value1-2">blah</Panel>
</Panel>
<Panel id="sub2">
<Panel id="value2-1">blah</Panel>
<Panel id="value2-2">blah</Panel>
</Panel>
</panel>
```
I am wondering if anyone has any decent ideas on implementing something like this without writing a bunch of nested **If..Else** statements, and without creating a bunch of custom controls. Whatever I implement needs to be robust enough to handle changes in the markup without constantly manipulating the codebehind.
I am hoping there is a way to do this through some simple markup changes (custom attribute) and a recursive function call on PageLoad or PreRender.
Any help is greatly appreciated.
EDIT:
-----
Ok so what makes this tricky is that there might be other controls inside the sub-sections that do not factor into the hiding and showing of the controls. And each *value* panel could potentially have controls in it that do not factor into whether or not it is shown. Example:
```
<Panel id="sub2">
<Image id="someImage" src="img.png" />
<Panel id="value2-1">
<Label>blah</Label>
<TextBox id="txtValue" />
</Panel>
<Panel id="value2-2">blah</Panel>
</Panel>
```
This is an over simplified example, but not far off from what I have to worry about.
|
it may be possible to avoid recursive traversal if you can write functions to return true/false for each group, e.g.
```
<Panel id="block" runat="server" visible="<%=IsBlockVisible%>">
<Panel id="sub1" runat="server" visible="<%=IsSubVisible(1)%>">
<Panel id="value1-1">blah</Panel>
<Panel id="value1-2">blah</Panel>
</Panel>
<Panel id="sub2" runat="server" visible="<%=IsSubVisible(2)%>">
<Panel id="value2-1">blah</Panel>
<Panel id="value2-2">blah</Panel>
</Panel>
</panel>
```
|
269,172 |
<p>It appear that SQL Server like most other products Random Function really is not that random. So we have this nice little function to generate a 10 char value. Is there a better way to accomplish what the following does. I am betting there is.</p>
<pre><code>DECLARE @SaltCount INT;
SELECT @SaltCount = COUNT(*) FROM tmp_NewLogin;
PRINT 'Set Salt values for all records' + CAST(@SaltCount AS VARCHAR(10))
DECLARE @CharPool CHAR(83);
DECLARE @Salt VARCHAR(10);
SET @CharPool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"#$%&()*+,-./:;<=>?@';
SET NOCOUNT ON;
updateSaltValue:
SET @Salt = ''
SELECT @Salt = @Salt + SUBSTRING(@CharPool, number, 1) FROM
(
SELECT TOP 10 number FROM MASTER..[spt_values] WHERE TYPE = 'p' AND Number BETWEEN 1 AND 83
ORDER BY NEWID()
) AS t
UPDATE TOP(1) [table] SET [Salt] = @Salt WHERE [Salt] IS NULL
IF (@@ROWCOUNT > 0)
GOTO updateSaltValue
SET NOCOUNT OFF;
PRINT 'Completed setting salts for all records';
</code></pre>
|
[
{
"answer_id": 269222,
"author": "Aleksandar",
"author_id": 29511,
"author_profile": "https://Stackoverflow.com/users/29511",
"pm_score": 1,
"selected": false,
"text": "<p>According to books-on-line for rand() function: If seed is not specified, the Microsoft SQL Server 2005 Database Engine assigns a seed value at random. For a specified seed value, the result returned is always the same. <br />\nYou can avoid this with quick & dirty trick:</p>\n\n<ol>\n<li><p>Create view like this:</p>\n\n<pre><code>create view [dbo].[wrapped_rand_view]\nas\nselect rand( ) as random_value\n</code></pre></li>\n<li><p>Next create function that reads from the view:</p>\n\n<pre><code>create function [dbo].[wrapped_rand]()\nreturns float\nas\nbegin\ndeclare @f float\nset @f = (select random_value from wrapped_rand_view)\nreturn @f\n</code></pre></li>\n</ol>\n\n<p>In this way you have random seed each time when you call your wrapped_rand() function and distinct random value between 0 and 1.</p>\n"
},
{
"answer_id": 269445,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 0,
"selected": false,
"text": "<p>Not the full-alphabet-randomness you have but kind of random:</p>\n\n<pre><code>select substring(replace(newid(),'-',''),0,10)\n</code></pre>\n\n<p><strong>Edit:</strong> I learned from the comments that newid() isn't very good for randomness, especially in combination with substring.</p>\n"
},
{
"answer_id": 269689,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 4,
"selected": true,
"text": "<p>Most programmers make a mistake of reinventing the randomization functionality and end up with something that is not random at all. I'd recommend you to stick with built-in RAND() function. Seed it once then fetch as many values as you need.</p>\n"
},
{
"answer_id": 270083,
"author": "user12861",
"author_id": 12861,
"author_profile": "https://Stackoverflow.com/users/12861",
"pm_score": 2,
"selected": false,
"text": "<p>Reinventing RAND is a recipe for disaster. Where have you ever noticed it behaving incorrectly? I don't think you even need to seed it. SQL Server should seed it on its own just fine. Seeding should just be necessary when you need to produce the same \"random\" sequence several times when testing algorithms or some such.</p>\n"
},
{
"answer_id": 270910,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "<p>Use the Rand() function.... and seed it with something else random like the number of millesconds in the current sysDate or current timestamp... Or a call to NewId() function... </p>\n"
},
{
"answer_id": 8285307,
"author": "gngolakia",
"author_id": 1050111,
"author_profile": "https://Stackoverflow.com/users/1050111",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes there is a need to reset a password using a temporary password or generate a random password for a new user. </p>\n\n<p>The following stored procedure creates strings of random characters based on four parameters that configure the result.</p>\n\n<pre><code>> create proc [dbo].uspRandChars\n> @len int,\n> @min tinyint = 48,\n> @range tinyint = 74,\n> @exclude varchar(50) = '0:;<=>?@O[]`^\\/',\n> @output varchar(50) output as \n> declare @char char\n> set @output = ''\n> \n> while @len > 0 begin\n> select @char = char(round(rand() * @range + @min, 0))\n> if charindex(@char, @exclude) = 0 begin\n> set @output += @char\n> set @len = @len - 1\n> end\n> end\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24500/"
] |
It appear that SQL Server like most other products Random Function really is not that random. So we have this nice little function to generate a 10 char value. Is there a better way to accomplish what the following does. I am betting there is.
```
DECLARE @SaltCount INT;
SELECT @SaltCount = COUNT(*) FROM tmp_NewLogin;
PRINT 'Set Salt values for all records' + CAST(@SaltCount AS VARCHAR(10))
DECLARE @CharPool CHAR(83);
DECLARE @Salt VARCHAR(10);
SET @CharPool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"#$%&()*+,-./:;<=>?@';
SET NOCOUNT ON;
updateSaltValue:
SET @Salt = ''
SELECT @Salt = @Salt + SUBSTRING(@CharPool, number, 1) FROM
(
SELECT TOP 10 number FROM MASTER..[spt_values] WHERE TYPE = 'p' AND Number BETWEEN 1 AND 83
ORDER BY NEWID()
) AS t
UPDATE TOP(1) [table] SET [Salt] = @Salt WHERE [Salt] IS NULL
IF (@@ROWCOUNT > 0)
GOTO updateSaltValue
SET NOCOUNT OFF;
PRINT 'Completed setting salts for all records';
```
|
Most programmers make a mistake of reinventing the randomization functionality and end up with something that is not random at all. I'd recommend you to stick with built-in RAND() function. Seed it once then fetch as many values as you need.
|
269,193 |
<p>I've got two ListBox'es that are databound to the same BindingList.</p>
<p>The issue is that when changing the selected item from the GUI it's changing the position in the BindingList and then the BindingList signals the other ListBox to change its selected item.</p>
<p>So I've got the two ListBoxes Selected Item also synchronized which is not good for me.</p>
<p>I'd like to maintain the list of items in sync. without the cursor position.</p>
<p>How do I disable that cursor so it's not maintained?</p>
<p>sample code (just add two ListBoxes to the Form at design time and register the SelectedIndexChanged events and register the button click event with a button):</p>
<pre><code>public partial class Form1 : Form
{
BindingList<string> list = new BindingList<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
list.Add("bla1");
list.Add("bla2");
list.Add("bla3");
this.listBox1.DataSource = list;
this.listBox2.DataSource = list;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
System.Diagnostics.Trace.WriteLine("ListBox1: " + listBox1.SelectedItem.ToString());
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex != -1)
System.Diagnostics.Trace.WriteLine("ListBox2: " + listBox2.SelectedItem.ToString());
}
// Register this event to a button
private void button1_Click(object sender, EventArgs e)
{
list.Add("Test");
}
}
</code></pre>
<p>Thanks,
--Ran.</p>
|
[
{
"answer_id": 270622,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 2,
"selected": false,
"text": "<p>Declaring listBox1 and listBox2 to be of the following type seems to result in the desired behaviour.</p>\n\n<pre><code>class MyListBox: ListBox {\n\n protected override void OnSelectedIndexChanged (EventArgs a) {\n if (DataManager != null) {\n DataManager.SuspendBinding();\n }\n }\n\n}\n</code></pre>\n\n<p>Regards,\ntamberg</p>\n"
},
{
"answer_id": 277825,
"author": "Ran",
"author_id": 35139,
"author_profile": "https://Stackoverflow.com/users/35139",
"pm_score": 0,
"selected": false,
"text": "<p>My solution for this issue is to use a normal List instead of the BindingList and just call (before the change) on the Form object:\n this.BindingContext[Your List].SuspendBinding();\nand after the change to the List\n this.BindingContext[Your List].ResumeBinding();\nThis updates all the bounded controls.</p>\n\n<p>Notice it's also noted in the <a href=\"http://msdn.microsoft.com/en-us/library/w67sdsex.aspx\" rel=\"nofollow noreferrer\">MSDN link here</a>:</p>\n\n<blockquote>\n <p>\"If you are bound to a data source that does not implement the IBindingList interface, such as an ArrayList, the bound control's data will not be updated when the data source is updated. For example, if you have a combo box bound to an ArrayList and data is added to the ArrayList, these new items will not appear in the combo box. However, you can force the combo box to be updated by calling the SuspendBinding and ResumeBinding methods on the instance of the BindingContext class to which the control is bound.\"</p>\n</blockquote>\n"
},
{
"answer_id": 277850,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 4,
"selected": true,
"text": "<p>Add this line to <code>Form_Load</code>:</p>\n\n\n\n<pre><code>this.listBox1.BindingContext = new BindingContext();\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35139/"
] |
I've got two ListBox'es that are databound to the same BindingList.
The issue is that when changing the selected item from the GUI it's changing the position in the BindingList and then the BindingList signals the other ListBox to change its selected item.
So I've got the two ListBoxes Selected Item also synchronized which is not good for me.
I'd like to maintain the list of items in sync. without the cursor position.
How do I disable that cursor so it's not maintained?
sample code (just add two ListBoxes to the Form at design time and register the SelectedIndexChanged events and register the button click event with a button):
```
public partial class Form1 : Form
{
BindingList<string> list = new BindingList<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
list.Add("bla1");
list.Add("bla2");
list.Add("bla3");
this.listBox1.DataSource = list;
this.listBox2.DataSource = list;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
System.Diagnostics.Trace.WriteLine("ListBox1: " + listBox1.SelectedItem.ToString());
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex != -1)
System.Diagnostics.Trace.WriteLine("ListBox2: " + listBox2.SelectedItem.ToString());
}
// Register this event to a button
private void button1_Click(object sender, EventArgs e)
{
list.Add("Test");
}
}
```
Thanks,
--Ran.
|
Add this line to `Form_Load`:
```
this.listBox1.BindingContext = new BindingContext();
```
|
269,207 |
<p>I have implemented a SAX parser in Java by extending the default handler. The XML has a ñ in its content. When it hits this character it breaks. I print out the char array in the character method and it simply ends with the character before the ñ. The parser seems to stop after this as no other methods are called even though there is still much more content. ie the endElement method is never called again. Has anyone run into this problem before or have any suggestion on how to deal with it?</p>
|
[
{
"answer_id": 269288,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": true,
"text": "<p>What's the encoding on the file? Make sure the file's encoding decloration matches it. Your parser may be defaulting to ascii or ISO-8859-1. You can set the encoding like so</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n</code></pre>\n\n<p>UTF-8 will cover that character, just make sure that's what the file actually is in.</p>\n"
},
{
"answer_id": 269294,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": false,
"text": "<p>If you are saving your XMLs in ASCII, you can only use the lower half (first 128 characters) of the 8-bit character table. To include accented, or other non-english characters in your XML, you will either have to save your XML in UTF-8 or escape your charaters like &#241; for ñ.</p>\n"
},
{
"answer_id": 34519333,
"author": "Amarnath Reddy Dornala",
"author_id": 5728198,
"author_profile": "https://Stackoverflow.com/users/5728198",
"pm_score": 0,
"selected": false,
"text": "<p>I faced this issue. XML stream you are feeding must me read as ascii, encode ascii to 'UTF-8' within code or change it to character stream and all will be fine. </p>\n\n<p>something like this will help you:</p>\n\n<pre><code>File F = new File(C://Location);\nBuffeReader Readfile = new BufferReader(F);\nInputSource Encode = new InputSource(Readfile);\nEncode.setEncoding(\"UTF-8\");\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35140/"
] |
I have implemented a SAX parser in Java by extending the default handler. The XML has a ñ in its content. When it hits this character it breaks. I print out the char array in the character method and it simply ends with the character before the ñ. The parser seems to stop after this as no other methods are called even though there is still much more content. ie the endElement method is never called again. Has anyone run into this problem before or have any suggestion on how to deal with it?
|
What's the encoding on the file? Make sure the file's encoding decloration matches it. Your parser may be defaulting to ascii or ISO-8859-1. You can set the encoding like so
```
<?xml version="1.0" encoding="UTF-8"?>
```
UTF-8 will cover that character, just make sure that's what the file actually is in.
|
269,223 |
<p>As I understand, the pimpl idiom is exists only because C++ forces you to place all the private class members in the header. If the header were to contain only the public interface, theoretically, any change in class implementation would not have necessitated a recompile for the rest of the program. </p>
<p>What I want to know is why C++ is not designed to allow such a convenience. Why does it demand at all for the private parts of a class to be openly displayed in the header (no pun intended)?</p>
|
[
{
"answer_id": 269239,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 2,
"selected": false,
"text": "<p>May be because the size of the class is required when passing its instance by values, aggregating it in other classes, etc ?</p>\n\n<p>If C++ did not support value semantics, it would have been fine, but it does.</p>\n"
},
{
"answer_id": 269242,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 3,
"selected": false,
"text": "<p>Someone will have a much more verbose answer than I, but the quick response is two-fold: the compiler needs to know all the members of a struct to determine the storage space requirements, and the compiler needs to know the ordering of those members to generate offsets in a deterministic way. </p>\n\n<p>The language is already fairly complicated; I think a mechanism to split the definitions of structured data across the code would be a bit of a calamity.</p>\n\n<p>Typically, I've always seen <a href=\"http://en.wikipedia.org/wiki/Policy-based_design\" rel=\"noreferrer\">policy classes</a> used to define implementation behavior in a Pimpl-manner. I think there are some added benefits of using a policy pattern -- easier to interchange implementations, can easily combine multiple partial implementations into a single unit which allow you to break up the implementation code into functional, reusable units, etc.</p>\n"
},
{
"answer_id": 269251,
"author": "Dan Hewett",
"author_id": 17975,
"author_profile": "https://Stackoverflow.com/users/17975",
"pm_score": 4,
"selected": true,
"text": "<p>This has to do with the size of the object. The h file is used, among other things, to determine the size of the object. If the private members are not given in it, then you would not know how large an object to new.</p>\n\n<p>You can simulate, however, your desired behavior by the following:</p>\n\n<pre><code>class MyClass\n{\npublic:\n // public stuff\n\nprivate:\n#include \"MyClassPrivate.h\"\n};\n</code></pre>\n\n<p>This does not enforce the behavior, but it gets the private stuff out of the .h file.\nOn the down side, this adds another file to maintain.\nAlso, in visual studio, the intellisense does not work for the private members - this could be a plus or a minus.</p>\n"
},
{
"answer_id": 269554,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, but...</p>\n\n<p>You need to read Stroustrup's \"Design and Evolution of C++\" book. It would have inhibited the uptake of C++.</p>\n"
},
{
"answer_id": 269599,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 3,
"selected": false,
"text": "<p>You're all ignoring the point of the question -</p>\n\n<p>Why must the developer type out the PIMPL code?</p>\n\n<p>For me, the best answer I can come up with is that we don't have a good way to express C++ code that allows you to operate on it. For instance, compile-time (or pre-processor, or whatever) reflection or a code DOM.</p>\n\n<p>C++ badly needs one or both of these to be available to a developer to do meta-programming.</p>\n\n<p>Then you could write something like this in your public MyClass.h:</p>\n\n<pre><code>#pragma pimpl(MyClass_private.hpp)\n</code></pre>\n\n<p>And then write your own, really quite trivial wrapper generator.</p>\n"
},
{
"answer_id": 270156,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": 3,
"selected": false,
"text": "<p>I think there is a confusion here. The problem is not about headers. Headers don't do anything (they are just ways to include common bits of source text among several source-code files).</p>\n\n<p>The problem, as much as there is one, is that class declarations in C++ have to define everything, public and private, that an instance needs to have in order to work. (The same is true of Java, but the way reference to externally-compiled classes works makes the use of anything like shared headers unnecessary.) </p>\n\n<p>It is in the nature of common Object-Oriented Technologies (not just the C++ one) that someone needs to know the concrete class that is used and how to use its constructor to deliver an implementation, even if you are using only the public parts. The device in (3, below) hides it. The practice in (1, below) separates the concerns, whether you do (3) or not.</p>\n\n<ol>\n<li><p>Use abstract classes that define only the public parts, mainly methods, and let the implementation class inherit from that abstract class. So, using the usual convention for headers, there is an abstract.hpp that is shared around. There is also an implementation.hpp that declares the inherited class and that is only passed around to the modules that implement methods of the implementation. The implementation.hpp file will #include \"abstract.hpp\" for use in the class declaration it makes, so that there is a single maintenance point for the declaration of the abstracted interface. </p></li>\n<li><p>Now, if you want to enforce hiding of the implementation class declaration, you need to have some way of requesting construction of a concrete instance without possessing the specific, complete class declaration: you can't use new and you can't use local instances. (You can delete though.) Introduction of helper functions (including methods on other classes that deliver references to class instances) is the substitute.</p></li>\n<li><p>Along with or as part of the header file that is used as the shared definition for the abstract class/interface, include function signatures for external helper functions. These function should be implemented in modules that are part of the specific class implementations (so they see the full class declaration and can exercise the constructor). The signature of the helper function is probably much like that of the constructor, but it returns an instance reference as a result (This constructor proxy can return a NULL pointer and it can even throw exceptions if you like that sort of thing). The helper function constructs a particular implementation instance and returns it cast as a reference to an instance of the abstract class. </p></li>\n</ol>\n\n<p>Mission accomplished. </p>\n\n<p>Oh, and recompilation and relinking should work the way you want, avoiding recompilation of calling modules when only the implementation changes (since the calling module no longer does any storage allocations for the implementations).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32688/"
] |
As I understand, the pimpl idiom is exists only because C++ forces you to place all the private class members in the header. If the header were to contain only the public interface, theoretically, any change in class implementation would not have necessitated a recompile for the rest of the program.
What I want to know is why C++ is not designed to allow such a convenience. Why does it demand at all for the private parts of a class to be openly displayed in the header (no pun intended)?
|
This has to do with the size of the object. The h file is used, among other things, to determine the size of the object. If the private members are not given in it, then you would not know how large an object to new.
You can simulate, however, your desired behavior by the following:
```
class MyClass
{
public:
// public stuff
private:
#include "MyClassPrivate.h"
};
```
This does not enforce the behavior, but it gets the private stuff out of the .h file.
On the down side, this adds another file to maintain.
Also, in visual studio, the intellisense does not work for the private members - this could be a plus or a minus.
|
269,252 |
<p>Is there an event for when a document is edited?
If not, does anyone know where I could find a list of the available VBA events?</p>
|
[
{
"answer_id": 269323,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>Here are the events for the document object:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa140279(office.10).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa140279(office.10).aspx</a></p>\n\n<p><strong>Events</strong></p>\n\n<pre><code>DocumentBeforeClose : Immediately before any open document closes. \nDocumentBeforePrint : Before any open document is printed. \nDocumentBeforeSave : Before any open document is saved. \nDocumentChange : A new document is created, when an existing document is opened, or when another document is made the active document. \nDocumentOpen : A document is opened. \nEPostageInsert : A user inserts electronic postage into a document. \nEPostagePropertyDialog : A user clicks the E-postage Properties (Labels and Envelopes dialog box) button or Print Electronic Postage toolbar button. This event allows a third-party software application to intercept and show their properties dialog box. \nMailMergeAfterMerge : After all records in a mail merge have merged successfully. \nMailMergeAfterRecordMerge : After each record in the data source successfully merges in a mail merge. \nMailMergeBeforeMerge : A merge is executed before any records merge. \nMailMergeBeforeRecordMerge : As a merge is executed for the individual records in a merge. \nMailMergeDataSourceLoad : The data source is loaded for a mail merge. \nMailMergeDataSourceValidate : A user performs address verification by clicking Validate in the Mail Merge Recipients dialog box. \nMailMergeWizardSendToCustom : The custom button is clicked on step six of the Mail Merge Wizard. \nMailMergeWizardStateChange : A user changes from a specified step to a specified step in the Mail Merge Wizard. \nNewDocument : A new document is created. \nQuit : The user quits Word. \nWindowActivate : Any document window is activated. \nWindowBeforeDoubleClick : The editing area of a document window is double-clicked, before the default double-click action. \nWindowBeforeRightClick : The editing area of a document window is right-clicked, before the default right-click action. \nWindowDeactivate : Any document window is deactivated. \nWindowSelectionChange : The selection changes in the active document window. \nWindowSize : The application window is resized or moved. \n</code></pre>\n\n<p>There are also Auto Macros:</p>\n\n<p>AutoNew, AutoOpen, AutoExec, AutoExit </p>\n"
},
{
"answer_id": 272426,
"author": "joe",
"author_id": 5653,
"author_profile": "https://Stackoverflow.com/users/5653",
"pm_score": 0,
"selected": false,
"text": "<p>To intercept any Word command, you can:</p>\n\n<p>1.</p>\n\n<p>Press Alt+ F8 to bring up the Macros dialog and where it says “Macros in”,\nselect “Word Commands”.</p>\n\n<p>2.</p>\n\n<p>Find and select one of the commands you want to intercept – for instance, to intercept the Print commands you need to find FilePrint and FilePrintDefault. To intercept the Save commands you need to find FileSave, FileSaveAs and FileSaveAll</p>\n\n<p>3.</p>\n\n<p>Where it says “Macros in”, select the template you want to store the macro in, and click “Create”.</p>\n\n<p>4.</p>\n\n<p>The code needed to execute the command will be written for you; just add your own code. </p>\n"
},
{
"answer_id": 413998,
"author": "joe",
"author_id": 5653,
"author_profile": "https://Stackoverflow.com/users/5653",
"pm_score": 1,
"selected": false,
"text": "<p>The command is WindowSelectionChange</p>\n"
},
{
"answer_id": 31534183,
"author": "wideweide",
"author_id": 5126587,
"author_profile": "https://Stackoverflow.com/users/5126587",
"pm_score": 0,
"selected": false,
"text": "<p>You may try autohotkey to listen the keypress event,look at my code:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/31470984/capturing-keydown-event-of-ms-word\">Capturing keydown event of MS Word</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
Is there an event for when a document is edited?
If not, does anyone know where I could find a list of the available VBA events?
|
Here are the events for the document object:
<http://msdn.microsoft.com/en-us/library/aa140279(office.10).aspx>
**Events**
```
DocumentBeforeClose : Immediately before any open document closes.
DocumentBeforePrint : Before any open document is printed.
DocumentBeforeSave : Before any open document is saved.
DocumentChange : A new document is created, when an existing document is opened, or when another document is made the active document.
DocumentOpen : A document is opened.
EPostageInsert : A user inserts electronic postage into a document.
EPostagePropertyDialog : A user clicks the E-postage Properties (Labels and Envelopes dialog box) button or Print Electronic Postage toolbar button. This event allows a third-party software application to intercept and show their properties dialog box.
MailMergeAfterMerge : After all records in a mail merge have merged successfully.
MailMergeAfterRecordMerge : After each record in the data source successfully merges in a mail merge.
MailMergeBeforeMerge : A merge is executed before any records merge.
MailMergeBeforeRecordMerge : As a merge is executed for the individual records in a merge.
MailMergeDataSourceLoad : The data source is loaded for a mail merge.
MailMergeDataSourceValidate : A user performs address verification by clicking Validate in the Mail Merge Recipients dialog box.
MailMergeWizardSendToCustom : The custom button is clicked on step six of the Mail Merge Wizard.
MailMergeWizardStateChange : A user changes from a specified step to a specified step in the Mail Merge Wizard.
NewDocument : A new document is created.
Quit : The user quits Word.
WindowActivate : Any document window is activated.
WindowBeforeDoubleClick : The editing area of a document window is double-clicked, before the default double-click action.
WindowBeforeRightClick : The editing area of a document window is right-clicked, before the default right-click action.
WindowDeactivate : Any document window is deactivated.
WindowSelectionChange : The selection changes in the active document window.
WindowSize : The application window is resized or moved.
```
There are also Auto Macros:
AutoNew, AutoOpen, AutoExec, AutoExit
|
269,263 |
<p>I have just been getting into low level programming (reading/writing to memory that sort of thing) and have run into an issue i cannot find an answer to.</p>
<p>The piece of information i want to read from has an address that is relative to a DLL loaded in memory e,g, it is at mydll.dll + 0x01234567. the problem im having is that the dll moves around in memory but the offset stays the same. Is there anyway to find out the location of this dll in memory.</p>
<p>I am currently trying to do this preferably in c# but i would be grateful for help in most highish level languages.</p>
|
[
{
"answer_id": 269290,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>From a Win32 perspective you need to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx\" rel=\"nofollow noreferrer\">GetModuleHandle</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms683201(VS.85).aspx\" rel=\"nofollow noreferrer\">GetModuleInformation</a> functions. These let you look the module handle up by name, and then retrieve information, including the base address about that handle.</p>\n\n<p>It should be straight forward to wrap these APIs using the standard P/Invoke wrappers.</p>\n"
},
{
"answer_id": 280960,
"author": "Paul Harris",
"author_id": 35148,
"author_profile": "https://Stackoverflow.com/users/35148",
"pm_score": 3,
"selected": true,
"text": "<p>i tried the method Rob Walker suggested and could not get it to work (i think it did not work because the dll was loaded as part of another executable so it could not be found so easily).</p>\n\n<p>I did however discover a solution that worked for me so here it is:</p>\n\n<p>i created an object of type Process</p>\n\n<pre><code>String appToHookTo = \"applicationthatloadedthedll\";\nProcess[] foundProcesses = Process.GetProcessesByName(appToHookTo)\nProcessModuleCollection modules = foundProcesses[0].Modules;\nProcessModule dllBaseAdressIWant = null;\nforeach (ProcessModule i in modules) {\nif (i.ModuleName == \"nameofdlliwantbaseadressof\") {\n dllBaseAdressIWant = i;\n }\n }\n</code></pre>\n\n<p>now you have the module you can just do dllbaseAdressIWant.BaseAddress to get the value.</p>\n\n<p>Hope this helps</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35148/"
] |
I have just been getting into low level programming (reading/writing to memory that sort of thing) and have run into an issue i cannot find an answer to.
The piece of information i want to read from has an address that is relative to a DLL loaded in memory e,g, it is at mydll.dll + 0x01234567. the problem im having is that the dll moves around in memory but the offset stays the same. Is there anyway to find out the location of this dll in memory.
I am currently trying to do this preferably in c# but i would be grateful for help in most highish level languages.
|
i tried the method Rob Walker suggested and could not get it to work (i think it did not work because the dll was loaded as part of another executable so it could not be found so easily).
I did however discover a solution that worked for me so here it is:
i created an object of type Process
```
String appToHookTo = "applicationthatloadedthedll";
Process[] foundProcesses = Process.GetProcessesByName(appToHookTo)
ProcessModuleCollection modules = foundProcesses[0].Modules;
ProcessModule dllBaseAdressIWant = null;
foreach (ProcessModule i in modules) {
if (i.ModuleName == "nameofdlliwantbaseadressof") {
dllBaseAdressIWant = i;
}
}
```
now you have the module you can just do dllbaseAdressIWant.BaseAddress to get the value.
Hope this helps
|
269,267 |
<p>Excel has a Conditional Formatting... option under the Format menu that allows you to change the style/color/font/whatever of a cell depending upon its value. But it only allows three conditions.</p>
<p>How do I get Excel to display say, six different background cell colors depending upon the value of the cell? (IE Make the cell red if the value is "Red", and blue if "Blue" etc.)</p>
|
[
{
"answer_id": 269278,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 4,
"selected": true,
"text": "<p>You will need to write something in VBA.</p>\n\n<p>See example here: <a href=\"http://www.ozgrid.com/VBA/excel-conditional-formatting-limit.htm\" rel=\"nofollow noreferrer\">Get Around Excels 3 Criteria Limit in Conditional Formatting</a>:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n\nDim icolor As Integer\n\n If Not Intersect(Target, Range(\"A1:A10\")) is Nothing Then\n\n Select Case Target\n\n Case 1 To 5\n icolor = 6\n Case 6 To 10\n icolor = 12\n Case 11 To 15\n icolor = 7\n Case 16 To 20\n icolor = 53\n Case 21 To 25\n icolor = 15\n Case 26 To 30\n icolor = 42\n Case Else\n 'Whatever\n End Select\n\n Target.Interior.ColorIndex = icolor\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 269409,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 2,
"selected": false,
"text": "<p>Excel 2007 allows more than three conditions. Quoting from <a href=\"http://msdn.microsoft.com/en-us/library/bb286672(office.11).aspx\" rel=\"nofollow noreferrer\">this Microsoft page</a>:</p>\n\n<p>EDIT: Ah, there's a \"feature\" in the linking code: parentheses in a link cited in parentheses aren't being handled correctly. That link is: <a href=\"http://msdn.microsoft.com/en-us/library/bb286672(office.11).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb286672(office.11).aspx</a></p>\n\n<blockquote>\n <p>Other benefits of the changes to\n conditional formatting in Excel 2007\n are the ability to specify more than\n three conditions, to reorder\n conditions, and to have more than one\n condition resolve to True.</p>\n</blockquote>\n\n<p>Otherwise. you're stuck with messy alternatives as described, I'm afraid.</p>\n"
},
{
"answer_id": 270890,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can use VBA macros to do this... </p>\n\n<p>here is one vba macro that might be better if need lots of cases\n<a href=\"http://chandoo.org/wp/2008/10/14/more-than-3-conditional-formats-in-excel/\" rel=\"nofollow noreferrer\">http://chandoo.org/wp/2008/10/14/more-than-3-conditional-formats-in-excel/</a></p>\n\n<p>you need to preformat 'n' cells with the way you want to format your entire range. and then use the macro in that url to get the effect.</p>\n"
},
{
"answer_id": 273791,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 2,
"selected": false,
"text": "<p>put this in a module in your VBA project. You can then highlight a range in a sheet and run the sub from the Tools > Macro > Macros menu item to color each cell in the selected range. </p>\n\n<pre><code>Public Sub ColorCells()\n\nDim cell, rng As Range\nDim color As Integer\nDim sheet As Worksheet\n\nApplication.ScreenUpdating = False\nApplication.StatusBar = \"Coloring Cells\"\n\n Set rng = Application.Selection\n Set sheet = Application.ActiveSheet\n\nFor Each cell In rng.cells\n\n Select Case Trim(LCase(cell))\n\n Case \"blue\"\n\n color = 5\n\n Case \"red\"\n\n color = 3\n\n Case \"yellow\"\n\n color = 6\n\n Case \"green\"\n\n color = 4\n\n Case \"purple\"\n\n color = 7\n\n Case \"orange\"\n\n color = 46\n\n Case Else\n\n color = 0\n End Select\n\n sheet.Range(cell.Address).Interior.ColorIndex = color\n\nNext cell\n\nApplication.ScreenUpdating = True\nApplication.StatusBar = \"Ready\"\n\nEnd Sub\n</code></pre>\n\n<p>If users are entering new color names into cells then you could put this in the sheet code in the VBA project to color the cells as a user is entering the color names into cells</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n\nIf Target.cells.Count > 1 Then Exit Sub\n\nDim color As Integer\n\n Select Case Trim(LCase(Target))\n\n Case \"blue\"\n\n color = 5\n\n Case \"red\"\n\n color = 3\n\n Case \"yellow\"\n\n color = 6\n\n Case \"green\"\n\n color = 4\n\n Case \"purple\"\n\n color = 7\n\n Case \"orange\"\n\n color = 46\n\n Case Else\n\n color = 0\n\n End Select\n\nTarget.Interior.ColorIndex = color\n\nEnd Sub\n</code></pre>\n\n<p>EDIT: Added Trim function around the case statement expression to test, so that accidental leading/trailing spaces in cells are ignored :)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35154/"
] |
Excel has a Conditional Formatting... option under the Format menu that allows you to change the style/color/font/whatever of a cell depending upon its value. But it only allows three conditions.
How do I get Excel to display say, six different background cell colors depending upon the value of the cell? (IE Make the cell red if the value is "Red", and blue if "Blue" etc.)
|
You will need to write something in VBA.
See example here: [Get Around Excels 3 Criteria Limit in Conditional Formatting](http://www.ozgrid.com/VBA/excel-conditional-formatting-limit.htm):
```
Private Sub Worksheet_Change(ByVal Target As Range)
Dim icolor As Integer
If Not Intersect(Target, Range("A1:A10")) is Nothing Then
Select Case Target
Case 1 To 5
icolor = 6
Case 6 To 10
icolor = 12
Case 11 To 15
icolor = 7
Case 16 To 20
icolor = 53
Case 21 To 25
icolor = 15
Case 26 To 30
icolor = 42
Case Else
'Whatever
End Select
Target.Interior.ColorIndex = icolor
End If
End Sub
```
|
269,285 |
<p>I have this simple controller:</p>
<pre><code>public class OneController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(IList<TestModel> m)
{
return View(m);
}
}
</code></pre>
<p>And a very simple view with two objects of type TestModel, properly indexed.
When I submit the form with invalid data, I get the view with the errors highlighted.
However, when I re-submit it (without changing anything), I get this error:</p>
<blockquote>
<p>[NullReferenceException: Object reference not set to an instance of an
object.]
System.Web.Mvc.DefaultModelBinder.UpdateCollection(ModelBindingContext
bindingContext, Type itemType) +612
System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext
bindingContext) +519
System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext
bindingContext) +829
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ParameterInfo
parameterInfo) +313
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(MethodInfo
methodInfo) +399
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
+232
System.Web.Mvc.Controller.ExecuteCore()
+152
System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +86
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +28
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase
httpContext) +332
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext
httpContext) +55
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext
httpContext) +28
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+358
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+64</p>
</blockquote>
<p>Any idea on how can I debug this?</p>
|
[
{
"answer_id": 269745,
"author": "Jeff Sheldon",
"author_id": 33910,
"author_profile": "https://Stackoverflow.com/users/33910",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure I can answer without seeing more of the code and how your form is setup.\nBut, you could take a look at <a href=\"http://www.haacked.com\" rel=\"nofollow noreferrer\">Phil Haack's</a> blog entry about <a href=\"http://www.haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx\" rel=\"nofollow noreferrer\">Model Binding To A List</a>.<br/>Hope this helps.</p>\n"
},
{
"answer_id": 269861,
"author": "pgb",
"author_id": 7277,
"author_profile": "https://Stackoverflow.com/users/7277",
"pm_score": 3,
"selected": true,
"text": "<p>I was already looking at that article, and found the bug I was having (subtle, yet critical).\nIf you render the hidden field with the index using Html.Hidden, the helper will \"accumulate\" the previous values, so you'll end up with a hidden saying index=1, and the next saying index=1,2.</p>\n\n<p>Changing the helper call to a manually coded hidden field fixed the issue.</p>\n"
},
{
"answer_id": 426803,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks that fixed it!</p>\n\n<p>I replaced</p>\n\n<pre><code><%= Html.Hidden(\"submitFormFields.index\", controlID) %>\n</code></pre>\n\n<p>with</p>\n\n<pre><code><input type=\"hidden\" id=\"submitFormFields.index\" name=\"submitFormFields.index\" value=\"<%=controlID %>\" />\n</code></pre>\n\n<p>Should we report this as a bug - It would be nice to have it fixed for ASP.Net MVC RC1</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] |
I have this simple controller:
```
public class OneController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(IList<TestModel> m)
{
return View(m);
}
}
```
And a very simple view with two objects of type TestModel, properly indexed.
When I submit the form with invalid data, I get the view with the errors highlighted.
However, when I re-submit it (without changing anything), I get this error:
>
> [NullReferenceException: Object reference not set to an instance of an
> object.]
> System.Web.Mvc.DefaultModelBinder.UpdateCollection(ModelBindingContext
> bindingContext, Type itemType) +612
> System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext
> bindingContext) +519
> System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext
> bindingContext) +829
> System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ParameterInfo
> parameterInfo) +313
> System.Web.Mvc.ControllerActionInvoker.GetParameterValues(MethodInfo
> methodInfo) +399
> System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
> controllerContext, String actionName)
> +232
> System.Web.Mvc.Controller.ExecuteCore()
> +152
> System.Web.Mvc.ControllerBase.Execute(RequestContext
> requestContext) +86
> System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
> requestContext) +28
> System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase
> httpContext) +332
> System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext
> httpContext) +55
> System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext
> httpContext) +28
> System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
> +358
> System.Web.HttpApplication.ExecuteStep(IExecutionStep
> step, Boolean& completedSynchronously)
> +64
>
>
>
Any idea on how can I debug this?
|
I was already looking at that article, and found the bug I was having (subtle, yet critical).
If you render the hidden field with the index using Html.Hidden, the helper will "accumulate" the previous values, so you'll end up with a hidden saying index=1, and the next saying index=1,2.
Changing the helper call to a manually coded hidden field fixed the issue.
|
269,308 |
<p>I have the following autorun.inf</p>
<pre><code>[Autorun]
action="Blah, Inc."
open=marketing.exe
icon=blah.ico
label="Blah, Inc."
</code></pre>
<p>On Vista, the autorun dialog shows "Publisher not specified". How do I specify a publisher?</p>
|
[
{
"answer_id": 269503,
"author": "Bogdan",
"author_id": 24022,
"author_profile": "https://Stackoverflow.com/users/24022",
"pm_score": 2,
"selected": false,
"text": "<p>You specify the publisher by signing your executable file, not by writing it in the autorun.inf file.</p>\n\n<p>How to do it...beats me, I'm a Java developer. Maybe someone else can tell you how.</p>\n"
},
{
"answer_id": 269540,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": true,
"text": "<p>Bogdan is right: You need to sign your executable.\nYou can use <em>SignTool</em> from Microsoft for this. Taken from the <a href=\"http://msdn.microsoft.com/en-us/library/aa387764.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p><em>SignTool tool is a command-line tool that digitally signs files, verifies signatures in files, or time stamps files. (...) The tool is installed in the \\Bin folder of the Microsoft Windows Software Development Kit (SDK) installation path.\n SignTool is available as part of the Windows SDK, which you can download as part of the Windows SDK for Windows Server 2008 and .NET Framework 3.5.</em></p>\n</blockquote>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] |
I have the following autorun.inf
```
[Autorun]
action="Blah, Inc."
open=marketing.exe
icon=blah.ico
label="Blah, Inc."
```
On Vista, the autorun dialog shows "Publisher not specified". How do I specify a publisher?
|
Bogdan is right: You need to sign your executable.
You can use *SignTool* from Microsoft for this. Taken from the [MSDN](http://msdn.microsoft.com/en-us/library/aa387764.aspx):
>
> *SignTool tool is a command-line tool that digitally signs files, verifies signatures in files, or time stamps files. (...) The tool is installed in the \Bin folder of the Microsoft Windows Software Development Kit (SDK) installation path.
> SignTool is available as part of the Windows SDK, which you can download as part of the Windows SDK for Windows Server 2008 and .NET Framework 3.5.*
>
>
>
|
269,326 |
<p>I'm running Apache on Windows XP via Xampplite, and could use help configuring my virtual directory. Here's what I'm hoping to do on my dev box:</p>
<ol>
<li>I want my source files to live outside of the xampp htdocs dir</li>
<li>on my local machine I can access the project at <a href="http://myproject" rel="noreferrer">http://myproject</a></li>
<li>others on my local network can access the project at my.ip.address/myproject</li>
<li>keep localhost pointing to the xampp's htdocs folder so I can easily add other projects.</li>
</ol>
<p>I've got 1 & 2 working by editing the windows hosts file, and adding a virtual directory in xampp's apache\conf\extra\httpd-vhosts.conf file. I don't immediately see how to do 3 without messing up 4.</p>
|
[
{
"answer_id": 269378,
"author": "sprugman",
"author_id": 24197,
"author_profile": "https://Stackoverflow.com/users/24197",
"pm_score": 6,
"selected": true,
"text": "<p>Figured it out: use <strong>Alias</strong> for #3, instead of VirtualHost, thus:</p>\n\n<pre><code>Alias /myproject \"C:/path/to/my/project\"\n<Directory \"C:/path/to/my/project\">\n Options Indexes FollowSymLinks MultiViews ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all\n</Directory>\n</code></pre>\n"
},
{
"answer_id": 270018,
"author": "jeremyasnyder",
"author_id": 33143,
"author_profile": "https://Stackoverflow.com/users/33143",
"pm_score": 4,
"selected": false,
"text": "<h2>To accomplish your list of needs.</h2>\n\n<p>1) Make the directory:</p>\n\n<blockquote>\n <p>mkdir c:\\xampp\\sites\\myproject</p>\n</blockquote>\n\n<p>2) Edit c:\\windows\\system32\\drivers\\etc\\hosts so it contains this line:</p>\n\n<blockquote>\n <p>127.0.0.1 myproject</p>\n</blockquote>\n\n<p>and add the following to c:\\xampp\\apache\\conf\\extra\\httpd-vhosts.conf:</p>\n\n<blockquote>\n<pre><code> NameVirtualHost myproject:80\n\n <VirtualHost myproject:80>\n DocumentRoot c:/xampp/sites/myproject\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all \n </Directory>\n</code></pre>\n</blockquote>\n\n<p>3) Add the following lines to the end of c:\\xampp\\apache\\conf\\httpd.conf:</p>\n\n<blockquote>\n<pre><code> Alias /myproject/ \"/xampp/sites/myproject/\"\n\n <Directory \"/xampp/sites/myproject\">\n AllowOverride None\n Options None\n Order allow,deny\n Allow from all\n </Directory>\n</code></pre>\n</blockquote>\n\n<p>4) Leave DocumentRoot, Directory, etc in c:\\xampp\\apache\\conf\\httpd.conf alone to accomplish this. For reference these lines would be:</p>\n\n<blockquote>\n<pre><code> DocumentRoot \"/xampp/htdocs\"\n\n <Directory />\n Options FollowSymLinks\n AllowOverride None\n Order deny,allow\n Deny from all\n </Directory>\n\n <Directory \"/xampp/htdocs\">\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all\n </Directory>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 1258950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>NameVirtualHost myproject:80\n < VirtualHost myproject:80 ><br>\n < /Directory ></p>\n</blockquote>\n\n<p>Must be: </p>\n\n<blockquote>\n <p>NameVirtualHost myproject:80\n < VirtualHost myproject:80 ><br>\n <strong>< /VirtualHost ></strong></p>\n</blockquote>\n\n<p>greets ;)</p>\n"
},
{
"answer_id": 2879643,
"author": "Nilanjan",
"author_id": 346752,
"author_profile": "https://Stackoverflow.com/users/346752",
"pm_score": 0,
"selected": false,
"text": "<p>resolved the issue. it was missing the directory tag.</p>\n\n<pre><code>NameVirtualHost myproject:80\n<VirtualHost myproject:80>\n DocumentRoot \"D:/Solution\"\n <Directory \"D:/Solution\">\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all\n </Directory> \n</VirtualHost>\n</code></pre>\n"
},
{
"answer_id": 13417247,
"author": "Stefan Michev",
"author_id": 754571,
"author_profile": "https://Stackoverflow.com/users/754571",
"pm_score": 2,
"selected": false,
"text": "<p>First enable: LoadModule alias_module modules/mod_alias.so</p>\n\n<pre><code><IfModule alias_module>\n Alias /ddd \"D:/prj/customer/www\"\n\n <Directory \"D:/prj/customer/www\">\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride all\n Order allow,deny\n Allow from all\n </Directory>\n</IfModule>\n</code></pre>\n\n<p>Tested on WAMP 2.2 and its working: http:// localhost/ddd</p>\n"
},
{
"answer_id": 20372975,
"author": "Shaikh Salman",
"author_id": 2823168,
"author_profile": "https://Stackoverflow.com/users/2823168",
"pm_score": -1,
"selected": false,
"text": "<p>Problem resolved in a simplest way and less steps\nNo Need of creating virtual host just change the location of target directory.</p>\n\n<p>Here's what i have done for configuration:\nI've done it by editing the C:/xampp/apache/conf/httpd.conf file\nChangings that I have done in httpd.conf file\nAdded this script right after\nScriptAlias /cgi-bin/ \"C:/xampp/apache)/\"</p>\n\n<p>Alias /projectXYZ \"C:/pathtomyproject\"\n\n Options Indexes FollowSymLinks MultiViews ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all</p>\n\n<p></p>\n\n<p>Pathtomyproject = Complete path of project</p>\n\n<p>And changed the url of Document Root\nDocumentRoot \" C:/pathtomyproject \"</p>\n\n<p>Now restart the Apache Server by stopping the server.\nI have stopped Apache server, and then again started the Apache Server. </p>\n\n<p>Source: <a href=\"http://bytespedia.blogspot.com/2013/12/creating-virtual-directory-in-apache.html\" rel=\"nofollow\">http://bytespedia.blogspot.com/2013/12/creating-virtual-directory-in-apache.html</a></p>\n"
},
{
"answer_id": 21566403,
"author": "4pi",
"author_id": 2450246,
"author_profile": "https://Stackoverflow.com/users/2450246",
"pm_score": 1,
"selected": false,
"text": "<p>In httpd.conf add the following lines, mutatis mutandis:</p>\n\n<pre><code><IfModule alias_module>\n Alias /angular-phonecat \"C:/DEV/git-workspace/angular-phonecat\"\n</IfModule>\n\n<Directory \"C:/DEV/git-workspace/angular-phonecat\">\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride all\n Order allow,deny\n Allow from all\n Require all granted\n</Directory>\n</code></pre>\n\n<p>This worked great on my (Windows) XAMPP installation after restarting the Apache server. I had to add the \"Require all granted\", but otherwise it is pretty much the same as the above answers.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24197/"
] |
I'm running Apache on Windows XP via Xampplite, and could use help configuring my virtual directory. Here's what I'm hoping to do on my dev box:
1. I want my source files to live outside of the xampp htdocs dir
2. on my local machine I can access the project at <http://myproject>
3. others on my local network can access the project at my.ip.address/myproject
4. keep localhost pointing to the xampp's htdocs folder so I can easily add other projects.
I've got 1 & 2 working by editing the windows hosts file, and adding a virtual directory in xampp's apache\conf\extra\httpd-vhosts.conf file. I don't immediately see how to do 3 without messing up 4.
|
Figured it out: use **Alias** for #3, instead of VirtualHost, thus:
```
Alias /myproject "C:/path/to/my/project"
<Directory "C:/path/to/my/project">
Options Indexes FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
```
|
269,366 |
<p>Until this morning, I have had Apache 2.0 running as a service using a local account which was configured with appropriate permissions. Sometime yesterday, someone must have changed something, and now Apache 2.0 won't start as a service under this account.</p>
<p>I made the account an Administrator temporarily, and Apache 2.0 starts fine.</p>
<p>I tried following the access listed in the <a href="http://httpd.apache.org/docs/2.0/platform/windows.html" rel="nofollow noreferrer">official documentation</a>, but it seems to require more access. <strong>Does anyone know what access Apache 2.0 needs to start as a service?</strong></p>
<p>I'm running Apache 2.0.63 with SVN 1.4.6 and mod_auth_sspi for windows domain authentication.</p>
<p>I also checked the syntax of the configuration file from command-line using the <strong>-t</strong> parameter, but I received the message <strong>Syntax OK</strong>.</p>
<p>Here's the error I get when starting as a service from command-line:</p>
<pre>
X:\>net start apache2
The Apache2 service is starting.
The Apache2 service could not be started.
A service specific error occurred: 1.
More help is available by typing NET HELPMSG 3547.
</pre>
|
[
{
"answer_id": 290764,
"author": "HitLikeAHammer",
"author_id": 35165,
"author_profile": "https://Stackoverflow.com/users/35165",
"pm_score": 3,
"selected": true,
"text": "<p>I have discovered the problem. After establishing the connection and the message listener the service went into a loop with Thread.Sleep(500). Dumb. I refactored the service to start everything up in OnStart and dispose of it in OnStop.</p>\n\n<p>Since doing that, everything is running perfectly.</p>\n\n<p>Classic ID-10-T error occurring between keyboard and chair.</p>\n"
},
{
"answer_id": 302728,
"author": "theGecko",
"author_id": 39022,
"author_profile": "https://Stackoverflow.com/users/39022",
"pm_score": 0,
"selected": false,
"text": "<p>we have just come across exactly the same issue using a .Net service talking to ActiveMQ, but ours locks up after only about 10-20 messages being delivered.</p>\n\n<p>Have tried it with and without the spring framework and it's slightly better without (unless I'm imagining things).</p>\n\n<p>Would you mind checking over this code and letting me know if it bears any resemblance to your own?</p>\n\n<pre><code>ConnectionFactory connectionFactory = new ConnectionFactory(\"tcp://activemq:61616\");\n\nConnection connection = (Connection)connectionFactory.CreateConnection();\nconnection.Start();\n\nSession session = (Session)connection.CreateSession(AcknowledgementMode.AutoAcknowledge);\nIDestination queue = session.GetQueue(\"test.queue\");\n\nMessageConsumer consumer = (MessageConsumer)session.CreateConsumer(queue);\n\nfor (int i = 0; i < 1000; i++)\n{\n IMessage msg = consumer.Receive();\n if (msg != null)\n Console.WriteLine((msg as ITextMessage).Text);\n}\n</code></pre>\n"
},
{
"answer_id": 303710,
"author": "HitLikeAHammer",
"author_id": 35165,
"author_profile": "https://Stackoverflow.com/users/35165",
"pm_score": 1,
"selected": false,
"text": "<p>My code is a little different. Instead of polling in a loop I set up a listener that responds to an \"OnMessage\" event. My code is similar to the code below. My actual code has lot of irrelevant stuff in it but the spirit is the same - hope this helps.</p>\n\n<pre><code>factory = new Apache.NMS.ActiveMQ.ConnectionFactory(\"tcp://activemq:61616\");\n\nconnection = factory.QueueConnection(factory, \"MyQueue\", AcknowledgementMode.AutoAcknowledge)\n\nconsumer = connection.Session.CreateConsumer(connection.Queue, \"2 > 1\"); //Get every msg\n\nconsumer.Listener += new MessageListener(OnMessage);\n\n\nprivate void OnMessage(IMessage message)\n{\n //Process message here.;\n}\n</code></pre>\n"
},
{
"answer_id": 305297,
"author": "theGecko",
"author_id": 39022,
"author_profile": "https://Stackoverflow.com/users/39022",
"pm_score": 1,
"selected": false,
"text": "<p>Never mind, I found it here:</p>\n\n<p><a href=\"http://remark.wordpress.com/articles/transactional-message-processing-with-activemq-and-nms/\" rel=\"nofollow noreferrer\">Transactional Message Processing with ActiveMQ and NMS</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2273/"
] |
Until this morning, I have had Apache 2.0 running as a service using a local account which was configured with appropriate permissions. Sometime yesterday, someone must have changed something, and now Apache 2.0 won't start as a service under this account.
I made the account an Administrator temporarily, and Apache 2.0 starts fine.
I tried following the access listed in the [official documentation](http://httpd.apache.org/docs/2.0/platform/windows.html), but it seems to require more access. **Does anyone know what access Apache 2.0 needs to start as a service?**
I'm running Apache 2.0.63 with SVN 1.4.6 and mod\_auth\_sspi for windows domain authentication.
I also checked the syntax of the configuration file from command-line using the **-t** parameter, but I received the message **Syntax OK**.
Here's the error I get when starting as a service from command-line:
```
X:\>net start apache2
The Apache2 service is starting.
The Apache2 service could not be started.
A service specific error occurred: 1.
More help is available by typing NET HELPMSG 3547.
```
|
I have discovered the problem. After establishing the connection and the message listener the service went into a loop with Thread.Sleep(500). Dumb. I refactored the service to start everything up in OnStart and dispose of it in OnStop.
Since doing that, everything is running perfectly.
Classic ID-10-T error occurring between keyboard and chair.
|
269,367 |
<p>I have a form which is used to <em>insert/display</em> and <em>update</em>. In the edit mode (<em>update</em>), when I pass my <code>BO</code> back to the Controller, what is the best possible way to check if any of the property values were changed, in order to execute the update to the datastore? </p>
<pre><code>textbox1.text = CustomerController.GetCustomerInformation(id).Name
</code></pre>
<p>A customer object is returned from the controller. I need to check if the the object is dirty in order to execute an update. I would assume the object sent from the client has to be compared with the one sent from the controller when I do:</p>
<pre><code>CustomerController.Save(customer)
</code></pre>
<p>How is this normally done?</p>
|
[
{
"answer_id": 269371,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 3,
"selected": true,
"text": "<p>A good way is to have an IsDirty flag on the object and have all the setable properties update that flag if they are changed. Have the flag initialized to false when the object is loaded. </p>\n\n<p>An example property would look like this:</p>\n\n<pre><code>public string Name {\n get { return _name; }\n set {\n _name = value;\n _isDirty = true;\n }\n}\n</code></pre>\n\n<p>Then when you get the object back you can simply check, <code>Customer.IsDirty</code> to see if you need to commit the changes to the database. And as an added bonus you get some humour from the resulting text :) (<em>oh those dirty customers</em>)</p>\n\n<p>You can also opt to always save the object regardless of whether it has been changed, my preference is to use a flag.</p>\n"
},
{
"answer_id": 269392,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "<p>I am no expert but I would use boolean flag property on the object to indicate it is dirty. I was beat to the answer lol.</p>\n"
},
{
"answer_id": 269469,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx\" rel=\"nofollow noreferrer\">INotifyPropertyChanged</a> interface. A more detailed explanation of how to implement it is available <a href=\"http://msdn.microsoft.com/en-us/library/ms229614.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 269525,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "<p>Note that the \"dirty flag approach\" (in its simple form) works for value types (int, bool, ...) and strings but not for reference types. E.g. if a property is of type <code>List<int></code> or <code>Address</code>, you can make it \"dirty\" without calling the setter method (<code>myCust.Address.City = \"...\"</code> calls only the getter method).</p>\n\n<p>If this is the case, you may find useful a reflection-based approach (add the following method to your BO):</p>\n\n<pre><code>public bool IsDirty(object other)\n{\n if (other == null || this.GetType() != other.GetType())\n throw new ArgumentException(\"other\");\n\n foreach (PropertyInfo pi in this.GetType().GetProperties())\n {\n if (pi.GetValue(this, null) != pi.GetValue(other, null))\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>Customer customer = new Customer();\n// ... set all properties\nif (customer.IsDirty(CustomerController.GetCustomerInformation(id)))\n CustomerController.Save(customer);\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
I have a form which is used to *insert/display* and *update*. In the edit mode (*update*), when I pass my `BO` back to the Controller, what is the best possible way to check if any of the property values were changed, in order to execute the update to the datastore?
```
textbox1.text = CustomerController.GetCustomerInformation(id).Name
```
A customer object is returned from the controller. I need to check if the the object is dirty in order to execute an update. I would assume the object sent from the client has to be compared with the one sent from the controller when I do:
```
CustomerController.Save(customer)
```
How is this normally done?
|
A good way is to have an IsDirty flag on the object and have all the setable properties update that flag if they are changed. Have the flag initialized to false when the object is loaded.
An example property would look like this:
```
public string Name {
get { return _name; }
set {
_name = value;
_isDirty = true;
}
}
```
Then when you get the object back you can simply check, `Customer.IsDirty` to see if you need to commit the changes to the database. And as an added bonus you get some humour from the resulting text :) (*oh those dirty customers*)
You can also opt to always save the object regardless of whether it has been changed, my preference is to use a flag.
|
269,373 |
<p>I want to do something like this:</p>
<pre><code><MyTemplate>
<span><%# Container.Title %></span>
<MySubTemplate>
<span><%# Container.Username %></span>
</MySubTemplate>
</MyTemplate>
</code></pre>
<p>Assuming I have a list of Titles that each have a list of Usernames.. If this is a correct approach how can I do this or what is a better way?</p>
|
[
{
"answer_id": 272940,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it this way. You can also use:</p>\n\n<ul>\n<li>Labels</li>\n<li>Span runat=\"server\" and add them programmatically</li>\n<li>(ghetto) string.replace</li>\n</ul>\n"
},
{
"answer_id": 273051,
"author": "Max Schilling",
"author_id": 29662,
"author_profile": "https://Stackoverflow.com/users/29662",
"pm_score": 2,
"selected": true,
"text": "<p>If you have a list of titles, that each have their own list of UserNames, it seems like you want to do something with nested repeaters (or other controls), not templates...</p>\n\n<pre><code> <asp:Repeater ID=\"rptTitle\" runat=\"server\" >\n <ItemTemplate>\n <%# Eval(\"Title\") %>\n <asp:Repeater ID=\"rptUsers\" runat=\"server\" >\n <ItemTemplate>\n <%# Eval(\"UserName\") %>\n </ItemTemplate>\n </asp:Repeater>\n </ItemTemplate>\n </asp:Repeater>\n</code></pre>\n\n<p>And then bind the rptUsers during the ItemDataBound event of rptTitle...</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
] |
I want to do something like this:
```
<MyTemplate>
<span><%# Container.Title %></span>
<MySubTemplate>
<span><%# Container.Username %></span>
</MySubTemplate>
</MyTemplate>
```
Assuming I have a list of Titles that each have a list of Usernames.. If this is a correct approach how can I do this or what is a better way?
|
If you have a list of titles, that each have their own list of UserNames, it seems like you want to do something with nested repeaters (or other controls), not templates...
```
<asp:Repeater ID="rptTitle" runat="server" >
<ItemTemplate>
<%# Eval("Title") %>
<asp:Repeater ID="rptUsers" runat="server" >
<ItemTemplate>
<%# Eval("UserName") %>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
```
And then bind the rptUsers during the ItemDataBound event of rptTitle...
|
269,384 |
<p>I'm still getting used to the sizers in wxWidgets, and as such can't seem to make them do what I want.</p>
<p>I want a large panel that will contain a list of other panels/boxes, which each then contain a set of text fields</p>
<pre><code>----------------------
| label text box |
| label2 text box2 |
----------------------
----------------------
| label text box |
| label2 text box2 |
----------------------
----------------------
| label text box |
| label2 text box2 |
----------------------
</code></pre>
<p>I also need to be able to add (at the end), and remove(anywhere) these boxes.
If there's too many to fit in the containing panel a vertical scroll bar is also required.</p>
<p>This is what I've tried so far, it works for the first box that's created with the containing panel, but additional added items are just a small box in the top left of the main panel, even though the sizer code is the same for all boxes.</p>
<pre><code>//itemsList is a container containg a list of *Item pointers to each box/panel/whatever the right name is
Items::Items(wxWindow *parent)
:wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_SUNKEN)
{
//one sstarting item
OnAdd(wxCommandEvent());
}
void Items::OnAdd(wxCommandEvent &event)
{
unsigned id = itemsList .size();
Item *item = new Item(this,id);
itemsList .push_back(item);
RebuildSizer();
}
void Items::RebuildSizer()
{
this->SetSizer(0,true);
wxBoxSizer *sizerV = new wxBoxSizer(wxVERTICAL);
for(std::vector<Item*>::iterator it = itemsList .begin(); it != itemsList .end(); ++it)
sizerV->Add(*it, 1, wxEXPAND | wxLEFT | wxRIGHT, 5);
SetSizer(sizerV);
}
void Items::OnRemove (wxCommandEvent &event, unsigned itemId)
{
delete itemsList [itemId];
itemsList .erase(items.begin()+itemId);
for(std::vector<Item*>::iterator it = itemsList .begin()+itemId; it != itemsList .end(); ++it)
(*it)->ChangeId(itemId++);
RebuildSizer();
}
</code></pre>
<p>Also what's the best way to lay out the contents of each box? I was thinking of using a 2 by 2 grid sizer but I'm not sure how to make the text boxes to expand to be as wide as possible while making the labels stay as small as possible (but also maintaining the alignment between the 2 text boxes)?</p>
|
[
{
"answer_id": 269502,
"author": "Ralph",
"author_id": 23154,
"author_profile": "https://Stackoverflow.com/users/23154",
"pm_score": 2,
"selected": true,
"text": "<p>\"If theres too many to fit in the containing panel a vertical scroll bar is also required.\"</p>\n\n<p>You could have a look at wxScrolledWindow.</p>\n\n<p>\"additional added items are just a small box in the top left of the main panel\"</p>\n\n<p>I am not sure, but, maybe a call to wxSizer::Layout() will help.</p>\n\n<p>\"Also whats the best way to lay out the contents of each box?\"</p>\n\n<p>Have a look at <a href=\"http://neume.sourceforge.net/sizerdemo/\" rel=\"nofollow noreferrer\">this sizerdemo</a>. If it is not mandatory, that the labels stay as small as possible, you could give the labels a fixed width and only let the text boxes grow. If you want to adapt the size when adding or removing new boxes, you could implement the OnSize() event handler.</p>\n"
},
{
"answer_id": 269517,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>May I suggest to you to post this question to one of the <a href=\"http://www.wxwidgets.org/support/maillst2.htm\" rel=\"nofollow noreferrer\">wxWidgets mailing list</a>? They will be able to help you very quickly.</p>\n"
},
{
"answer_id": 270000,
"author": "SteveL",
"author_id": 1913,
"author_profile": "https://Stackoverflow.com/users/1913",
"pm_score": 0,
"selected": false,
"text": "<p>Can I also recommend the <a href=\"http://wxforum.shadonet.com/\" rel=\"nofollow noreferrer\">wxForum</a>, I have found it very useful for wxWidgets questions in the past.</p>\n\n<p>More specifically for scrolling <a href=\"http://docs.wxwidgets.org/stable/wx_wxscrolledwindow.html#wxscrolledwindow\" rel=\"nofollow noreferrer\">wxScrolledWindow</a> should help, use wxScrolledWindow->SetSizer with your top level sizer (the one that contains your controls) to set up a scrolled area, also check out the samples called scroll, scrollsub and vscroll included in wxWidgets (in the samples directory of your wxwidgets install).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
I'm still getting used to the sizers in wxWidgets, and as such can't seem to make them do what I want.
I want a large panel that will contain a list of other panels/boxes, which each then contain a set of text fields
```
----------------------
| label text box |
| label2 text box2 |
----------------------
----------------------
| label text box |
| label2 text box2 |
----------------------
----------------------
| label text box |
| label2 text box2 |
----------------------
```
I also need to be able to add (at the end), and remove(anywhere) these boxes.
If there's too many to fit in the containing panel a vertical scroll bar is also required.
This is what I've tried so far, it works for the first box that's created with the containing panel, but additional added items are just a small box in the top left of the main panel, even though the sizer code is the same for all boxes.
```
//itemsList is a container containg a list of *Item pointers to each box/panel/whatever the right name is
Items::Items(wxWindow *parent)
:wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_SUNKEN)
{
//one sstarting item
OnAdd(wxCommandEvent());
}
void Items::OnAdd(wxCommandEvent &event)
{
unsigned id = itemsList .size();
Item *item = new Item(this,id);
itemsList .push_back(item);
RebuildSizer();
}
void Items::RebuildSizer()
{
this->SetSizer(0,true);
wxBoxSizer *sizerV = new wxBoxSizer(wxVERTICAL);
for(std::vector<Item*>::iterator it = itemsList .begin(); it != itemsList .end(); ++it)
sizerV->Add(*it, 1, wxEXPAND | wxLEFT | wxRIGHT, 5);
SetSizer(sizerV);
}
void Items::OnRemove (wxCommandEvent &event, unsigned itemId)
{
delete itemsList [itemId];
itemsList .erase(items.begin()+itemId);
for(std::vector<Item*>::iterator it = itemsList .begin()+itemId; it != itemsList .end(); ++it)
(*it)->ChangeId(itemId++);
RebuildSizer();
}
```
Also what's the best way to lay out the contents of each box? I was thinking of using a 2 by 2 grid sizer but I'm not sure how to make the text boxes to expand to be as wide as possible while making the labels stay as small as possible (but also maintaining the alignment between the 2 text boxes)?
|
"If theres too many to fit in the containing panel a vertical scroll bar is also required."
You could have a look at wxScrolledWindow.
"additional added items are just a small box in the top left of the main panel"
I am not sure, but, maybe a call to wxSizer::Layout() will help.
"Also whats the best way to lay out the contents of each box?"
Have a look at [this sizerdemo](http://neume.sourceforge.net/sizerdemo/). If it is not mandatory, that the labels stay as small as possible, you could give the labels a fixed width and only let the text boxes grow. If you want to adapt the size when adding or removing new boxes, you could implement the OnSize() event handler.
|
269,390 |
<p>At the moment I have setup a custom ok cancel dialog with a drop down in c#. The ok and cancel buttons use the DialogResult property so no code behind it. What I now need to do is validate the drop down to check it isn't left empty before posting back a dialogresult.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 269396,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 3,
"selected": true,
"text": "<p>From <a href=\"http://www.functionx.com/vcsharp2003/Lesson06.htm\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Double-click the Closing field, and implement it as follows:</p>\n\n<pre><code>private void Second_Closing(object sender, \n System.ComponentModel.CancelEventArgs e)\n{\n // When the user attempts to close the form, don't close it...\n e.Cancel = (dropdown.selecteditemindex >= 0);\n}\n</code></pre>\n"
},
{
"answer_id": 269400,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>If you want check for something, you allways need some code behind the designer.\nFor your case, you can use a \"Closing\" event in the form, check what you need and if you want, set \"e.Cancel = true;\" - then form will not be closed.</p>\n"
},
{
"answer_id": 269415,
"author": "Nathen Silver",
"author_id": 6136,
"author_profile": "https://Stackoverflow.com/users/6136",
"pm_score": 1,
"selected": false,
"text": "<p>What I have done for this is to not set the DialogResult on the OK button, but put some code behind the button.</p>\n\n<pre><code>private void OkButton_Clicked(object sender, EventArgs e)\n{\n this.DialogResult = ValueComboBox.SelectedIndex >= 0\n ? DialogResult.Ok\n : DialogResult.None;\n}\n</code></pre>\n"
},
{
"answer_id": 269419,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 1,
"selected": false,
"text": "<p>Disable your OK button until the combobox is changed to a valid value.</p>\n"
},
{
"answer_id": 14145823,
"author": "Anders Carstensen",
"author_id": 1492977,
"author_profile": "https://Stackoverflow.com/users/1492977",
"pm_score": 1,
"selected": false,
"text": "<p>You can keep using the OK and Cancel button functionality of dialogs, and then put this code in the Clicked handler for the OK button:</p>\n\n<pre><code>private void OkButton_Clicked(object sender, EventArgs e)\n{\n if (!IsValid()) {\n this.DialogResult = System.Windows.Forms.DialogResult.None;\n }\n}\n</code></pre>\n\n<p>In the code above, <code>IsValid()</code> is a method you have to implement, that validates the input fields on the dialog.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
At the moment I have setup a custom ok cancel dialog with a drop down in c#. The ok and cancel buttons use the DialogResult property so no code behind it. What I now need to do is validate the drop down to check it isn't left empty before posting back a dialogresult.
Is this possible?
|
From [here](http://www.functionx.com/vcsharp2003/Lesson06.htm)
Double-click the Closing field, and implement it as follows:
```
private void Second_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
// When the user attempts to close the form, don't close it...
e.Cancel = (dropdown.selecteditemindex >= 0);
}
```
|
269,402 |
<p>I've been asked to add Google e-commerce tracking into my site. This tracking involves inserting some javascript on your receipt page and then calling it's functions. From my asp.net receipt page, I need to call one function (_addTrans) for the transaction info and then another (_addItem) for each item on the order. An example of what they want is <a href="http://www.google.com/support/analytics/bin/answer.py?answer=55528" rel="nofollow noreferrer">here</a></p>
<p>This is for a 1.1 site. Can anybody give me a jumpstart on calling these two functions from my c# code-behind? I can't imagine that I'm alone out there in needing to call Google e-commerce tracking, so I'm hopeful.</p>
|
[
{
"answer_id": 269472,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 4,
"selected": true,
"text": "<p>Probably the easiest way is to build up the required Javascript as a string with something like </p>\n\n<pre><code>StringBuilder sb = new StringBuilder()\nsb.AppendLine( \"<script>\" );\nsb.AppendLine( \"var pageTracker = _gat._getTracker('UA-XXXXX-1');\" );\nsb.AppendLine( \"pageTracker._trackPageview();\" );\nsb.AppendFormat( \"pageTracker._addTrans('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}' );\\n\", orderId, affiliation, total, tax, shipping, city, state, country );\nsb.AppendFormat( \"pageTracker._addItem('{0}','{1}','{2}','{3}','{4}','{5}');\\n\", itemNumber, sku, productName, category, price, quantity );\nsb.AppendLine(\"pageTracker._trackTrans();\");\nsb.AppendLine( \"</script>\" );\n</code></pre>\n\n<p>Then register it to appear in the page with</p>\n\n<pre><code>Page.RegisterStartupScript(\"someKey\", sb.ToString());\n</code></pre>\n"
},
{
"answer_id": 271626,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Here i just wrote an Google Analytics E-Commerce class to dynamically add analytics transactions.</p>\n\n<p><a href=\"http://www.sarin.mobi/2008/11/generate-google-analytics-e-commerce-code-from-c/\" rel=\"noreferrer\">http://www.sarin.mobi/2008/11/generate-google-analytics-e-commerce-code-from-c/</a></p>\n\n<p>Hope this hope.</p>\n"
},
{
"answer_id": 420561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>In response to stevemegson (first answer) - shouldn't the first parameter into the pageTracker._addItem method be the OrderID, not the itemNumber?</p>\n"
},
{
"answer_id": 3225700,
"author": "Doug",
"author_id": 115749,
"author_profile": "https://Stackoverflow.com/users/115749",
"pm_score": 1,
"selected": false,
"text": "<p>A project i have released allows for easy integration with Google Analytics to fire page views and events through native .net code.</p>\n\n<p>This way you can simply call a method that will log either and event or a page view for you.</p>\n\n<p>I am planning on supporting transaction logging as well over the next few weeks.</p>\n\n<p>It's called GaDotNet and can be found here: <a href=\"http://www.diaryofaninja.com/projects/details/ga-dot-net\" rel=\"nofollow noreferrer\">http://www.diaryofaninja.com/projects/details/ga-dot-net</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
I've been asked to add Google e-commerce tracking into my site. This tracking involves inserting some javascript on your receipt page and then calling it's functions. From my asp.net receipt page, I need to call one function (\_addTrans) for the transaction info and then another (\_addItem) for each item on the order. An example of what they want is [here](http://www.google.com/support/analytics/bin/answer.py?answer=55528)
This is for a 1.1 site. Can anybody give me a jumpstart on calling these two functions from my c# code-behind? I can't imagine that I'm alone out there in needing to call Google e-commerce tracking, so I'm hopeful.
|
Probably the easiest way is to build up the required Javascript as a string with something like
```
StringBuilder sb = new StringBuilder()
sb.AppendLine( "<script>" );
sb.AppendLine( "var pageTracker = _gat._getTracker('UA-XXXXX-1');" );
sb.AppendLine( "pageTracker._trackPageview();" );
sb.AppendFormat( "pageTracker._addTrans('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}' );\n", orderId, affiliation, total, tax, shipping, city, state, country );
sb.AppendFormat( "pageTracker._addItem('{0}','{1}','{2}','{3}','{4}','{5}');\n", itemNumber, sku, productName, category, price, quantity );
sb.AppendLine("pageTracker._trackTrans();");
sb.AppendLine( "</script>" );
```
Then register it to appear in the page with
```
Page.RegisterStartupScript("someKey", sb.ToString());
```
|
269,404 |
<p>I have been reading about the differences between Table Variables and Temp Tables and stumbled upon the following issue with the Table Variable. I did not see this issue mentioned in the articles I pursued. </p>
<p>I pass in a series of PKs via a XML data type and successfully create the records in both temp table structures. When I attempt to update further fields in the temp tables the Table Variable fails but the Temp Table has no problem with the Update Statement. What do need to do different? I would like to take advantage of the speed boost that Table Variables promise…</p>
<p>Here are the SP snippets and Results:</p>
<pre><code>CREATE PROCEDURE ExpenseReport_AssignApprover
(
@ExpenseReportIDs XML
)
AS
DECLARE @ERTableVariable TABLE ( ExpenseReportID INT,
ExpenseReportProjectID INT,
ApproverID INT)
CREATE TABLE #ERTempTable
(
ExpenseReportID INT,
ExpenseReportProjectID INT,
ApproverID INT
)
INSERT INTO @ERTableVariable (ExpenseReportID)
SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @ExpenseReportIDs.nodes('/Root/ExpenseReportID') as ParamValues(ID)
INSERT INTO #ERTempTable (ExpenseReportID)
SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @ExpenseReportIDs.nodes('/Root/ExpenseReportID') as ParamValues(ID)
UPDATE #ERTempTable
SET ExpenseReportProjectID = ( SELECT TOP 1 ExpenseReportProjectID
FROM ExpenseReportItem
WHERE(ExpenseReportID = #ERTempTable.ExpenseReportID))
UPDATE @ERTableVariable
SET ExpenseReportProjectID = ( SELECT TOP 1 ExpenseReportProjectID
FROM ExpenseReportItem
WHERE(ExpenseReportID = @ERTableVariable.ExpenseReportID))
</code></pre>
<p>Error when last update statement in there :
Must declare the scalar variable "@ERTableVariable".</p>
<p>ExpenseReportProjectID is updated in #ERTempTable when the last update is commented out:</p>
|
[
{
"answer_id": 269418,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>CREATE PROCEDURE ExpenseReport_AssignApprover\n(\n @ExpenseReportIDs XML\n)\nAS BEGIN\n\n\nDECLARE @ERTableVariable TABLE ( ExpenseReportID INT,\n ExpenseReportProjectID INT,\n ApproverID INT)\n\n\nCREATE TABLE #ERTempTable\n(\n ExpenseReportID INT,\n ExpenseReportProjectID INT,\n ApproverID INT\n)\n\nINSERT INTO @ERTableVariable (ExpenseReportID)\nSELECT ParamValues.ID.value('.','VARCHAR(20)')\nFROM @ExpenseReportIDs.nodes('/Root/ExpenseReportID') as ParamValues(ID)\n\nINSERT INTO #ERTempTable (ExpenseReportID)\nSELECT ParamValues.ID.value('.','VARCHAR(20)')\nFROM @ExpenseReportIDs.nodes('/Root/ExpenseReportID') as ParamValues(ID)\n\nUPDATE #ERTempTable\nSET ExpenseReportProjectID = ( SELECT TOP 1 ExpenseReportProjectID \n FROM ExpenseReportItem \n WHERE(ExpenseReportID = #ERTempTable.ExpenseReportID))\n\nUPDATE @ERTableVariable\nSET ExpenseReportProjectID = ( SELECT TOP 1 ExpenseReportProjectID \n FROM ExpenseReportItem \n WHERE(ExpenseReportID = @ERTableVariable.ExpenseReportID))\n\nEND\n</code></pre>\n"
},
{
"answer_id": 269994,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 5,
"selected": true,
"text": "<p>A quick test works when I literalize the table var reference in the last update:</p>\n\n<pre><code>UPDATE @ERTableVariable\n SET ExpenseReportProjectID = ( \n SELECT TOP 1 ExpenseReportProjectID\n FROM ExpenseReportItem \n WHERE ExpenseReportID = [@ERTableVariable].ExpenseReportID\n )\n</code></pre>\n\n<p>You could also use an 'update from':</p>\n\n<pre><code>UPDATE er SET \n ExpenseReportProjectID = ExpenseReportItem.ExpenseReportProjectID\nFROM @ERTableVariable er\nINNER JOIN ExpenseReportItem ON \n ExpenseReportItem.ExpenseReportID = er.ExpenseReportID\n</code></pre>\n\n<p>The join might return multiple rows but only one will 'stick'. Kind of a non-deterministic update like 'TOP 1'.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30934/"
] |
I have been reading about the differences between Table Variables and Temp Tables and stumbled upon the following issue with the Table Variable. I did not see this issue mentioned in the articles I pursued.
I pass in a series of PKs via a XML data type and successfully create the records in both temp table structures. When I attempt to update further fields in the temp tables the Table Variable fails but the Temp Table has no problem with the Update Statement. What do need to do different? I would like to take advantage of the speed boost that Table Variables promise…
Here are the SP snippets and Results:
```
CREATE PROCEDURE ExpenseReport_AssignApprover
(
@ExpenseReportIDs XML
)
AS
DECLARE @ERTableVariable TABLE ( ExpenseReportID INT,
ExpenseReportProjectID INT,
ApproverID INT)
CREATE TABLE #ERTempTable
(
ExpenseReportID INT,
ExpenseReportProjectID INT,
ApproverID INT
)
INSERT INTO @ERTableVariable (ExpenseReportID)
SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @ExpenseReportIDs.nodes('/Root/ExpenseReportID') as ParamValues(ID)
INSERT INTO #ERTempTable (ExpenseReportID)
SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @ExpenseReportIDs.nodes('/Root/ExpenseReportID') as ParamValues(ID)
UPDATE #ERTempTable
SET ExpenseReportProjectID = ( SELECT TOP 1 ExpenseReportProjectID
FROM ExpenseReportItem
WHERE(ExpenseReportID = #ERTempTable.ExpenseReportID))
UPDATE @ERTableVariable
SET ExpenseReportProjectID = ( SELECT TOP 1 ExpenseReportProjectID
FROM ExpenseReportItem
WHERE(ExpenseReportID = @ERTableVariable.ExpenseReportID))
```
Error when last update statement in there :
Must declare the scalar variable "@ERTableVariable".
ExpenseReportProjectID is updated in #ERTempTable when the last update is commented out:
|
A quick test works when I literalize the table var reference in the last update:
```
UPDATE @ERTableVariable
SET ExpenseReportProjectID = (
SELECT TOP 1 ExpenseReportProjectID
FROM ExpenseReportItem
WHERE ExpenseReportID = [@ERTableVariable].ExpenseReportID
)
```
You could also use an 'update from':
```
UPDATE er SET
ExpenseReportProjectID = ExpenseReportItem.ExpenseReportProjectID
FROM @ERTableVariable er
INNER JOIN ExpenseReportItem ON
ExpenseReportItem.ExpenseReportID = er.ExpenseReportID
```
The join might return multiple rows but only one will 'stick'. Kind of a non-deterministic update like 'TOP 1'.
|
269,423 |
<p><strong>Is there a tool to generate WiX XML given a .reg file?</strong></p>
<hr>
<p>In 2.0, you were supposed to be able to run tallow to generate registry XML:</p>
<pre><code>tallow -r my.reg
</code></pre>
<p>For what it's worth, the version of tallow I have is producing empty XML.</p>
<p>In 3.0, tallow has been replaced with heat, but I can't figure out how to get it to produce output from a .reg file.</p>
<p>Is there a way to do this in 3.0?</p>
|
[
{
"answer_id": 270442,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 5,
"selected": true,
"text": "<p>I couldn't find a tool, so I made one.</p>\n\n<p>The source code may not be elegant, but it seems to work:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing System.Xml;\nusing System.Text.RegularExpressions;\n\nnamespace Reg2Wix\n{\n class Program\n {\n static void PrintUsage()\n {\n Console.WriteLine(\"reg2wix <input file> <output file>\");\n }\n\n /// <summary>\n /// Parse the hive out of a registry key\n /// </summary>\n /// <param name=\"keyWithHive\"></param>\n /// <param name=\"hive\"></param>\n /// <param name=\"key\"></param>\n static void ParseKey(string keyWithHive, out string hive, out string key)\n {\n if (keyWithHive == null)\n {\n throw new ArgumentNullException(\"keyWithHive\");\n }\n if (keyWithHive.StartsWith(\"HKEY_LOCAL_MACHINE\\\\\"))\n {\n hive = \"HKLM\";\n key = keyWithHive.Substring(19);\n }\n else if (keyWithHive.StartsWith(\"HKEY_CLASSES_ROOT\\\\\"))\n {\n hive = \"HKCR\";\n key = keyWithHive.Substring(18);\n }\n else if (keyWithHive.StartsWith(\"HKEY_USERS\\\\\"))\n {\n hive = \"HKU\";\n key = keyWithHive.Substring(11);\n }\n else if (keyWithHive.StartsWith(\"HKEY_CURRENT_USER\\\\\"))\n {\n hive = \"HKCU\";\n key = keyWithHive.Substring(18);\n }\n else\n {\n throw new ArgumentException();\n } \n }\n\n /// <summary>\n /// Write a WiX RegistryValue element for the specified key, name, and value\n /// </summary>\n /// <param name=\"writer\"></param>\n /// <param name=\"key\"></param>\n /// <param name=\"name\"></param>\n /// <param name=\"value\"></param>\n static void WriteRegistryValue(XmlWriter writer, string key, string name, string value)\n {\n if (writer == null)\n {\n throw new ArgumentNullException(\"writer\");\n }\n if (key == null)\n {\n throw new ArgumentNullException(\"key\");\n }\n if (value == null)\n {\n throw new ArgumentNullException(\"value\");\n }\n\n string hive;\n string keyPart;\n ParseKey(key, out hive, out keyPart);\n\n writer.WriteStartElement(\"RegistryValue\");\n\n writer.WriteAttributeString(\"Root\", hive);\n writer.WriteAttributeString(\"Key\", keyPart);\n if (!String.IsNullOrEmpty(name))\n {\n writer.WriteAttributeString(\"Name\", name);\n }\n writer.WriteAttributeString(\"Value\", value);\n writer.WriteAttributeString(\"Type\", \"string\");\n writer.WriteAttributeString(\"Action\", \"write\");\n\n writer.WriteEndElement();\n }\n\n /// <summary>\n /// Convert a .reg file into an XML document\n /// </summary>\n /// <param name=\"inputReader\"></param>\n /// <param name=\"xml\"></param>\n static void RegistryFileToWix(TextReader inputReader, XmlWriter xml)\n {\n Regex regexKey = new Regex(\"^\\\\[([^\\\\]]+)\\\\]$\");\n Regex regexValue = new Regex(\"^\\\"([^\\\"]+)\\\"=\\\"([^\\\"]*)\\\"$\");\n Regex regexDefaultValue = new Regex(\"@=\\\"([^\\\"]+)\\\"$\");\n\n string currentKey = null;\n\n string line;\n while ((line = inputReader.ReadLine()) != null)\n {\n line = line.Trim();\n Match match = regexKey.Match(line); \n if (match.Success)\n {\n //key track of the current key\n currentKey = match.Groups[1].Value;\n }\n else \n {\n //if we have a current key\n if (currentKey != null)\n {\n //see if this is an acceptable name=value pair\n match = regexValue.Match(line);\n if (match.Success)\n {\n WriteRegistryValue(xml, currentKey, match.Groups[1].Value, match.Groups[2].Value);\n }\n else\n {\n //see if this is an acceptable default value (starts with @)\n match = regexDefaultValue.Match(line);\n if (match.Success)\n {\n WriteRegistryValue(xml, currentKey, (string)null, match.Groups[1].Value);\n }\n }\n }\n }\n }\n }\n\n /// <summary>\n /// Convert a .reg file into a .wsx file\n /// </summary>\n /// <param name=\"inputPath\"></param>\n /// <param name=\"outputPath\"></param>\n static void RegistryFileToWix(string inputPath, string outputPath)\n {\n using (StreamReader reader = new StreamReader(inputPath))\n {\n using (XmlTextWriter writer = new XmlTextWriter(outputPath, Encoding.UTF8))\n {\n writer.Formatting = Formatting.Indented;\n writer.Indentation = 3;\n writer.IndentChar = ' ';\n writer.WriteStartDocument();\n writer.WriteStartElement(\"Component\");\n RegistryFileToWix(reader, writer);\n writer.WriteEndElement();\n writer.WriteEndDocument();\n }\n }\n }\n\n static void Main(string[] args)\n {\n if (args.Length != 2)\n {\n PrintUsage();\n return;\n }\n RegistryFileToWix(args[0], args[1]);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 739604,
"author": "YONDERBOI",
"author_id": 88919,
"author_profile": "https://Stackoverflow.com/users/88919",
"pm_score": 1,
"selected": false,
"text": "<p>I've tried <strong>tallow.exe (version 2.0.5805)</strong> from the latest stable <strong>Wix 2</strong> release and it worked fine for me.</p>\n\n<pre><code>tallow -reg my.reg\n</code></pre>\n\n<p>This will generate the markup using Wix 2 <strong>\"Registry\"</strong> tag that was <strong>deprecated in Wix 3</strong>. Then you have to copy the output into a wix source file and execute <strong>WixCop</strong> utility to convert Wix 2 markup to Wix 3:</p>\n\n<pre><code>wixcop my.wxs -f\n</code></pre>\n"
},
{
"answer_id": 739612,
"author": "YONDERBOI",
"author_id": 88919,
"author_profile": "https://Stackoverflow.com/users/88919",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the source code of the utility that generates Wix 3 markup (including binary, dword and multi-string registry values):</p>\n\n<pre><code>using System;\nusing System.Globalization;\nusing System.IO;\nusing System.Reflection;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Xml;\n\nnamespace AbsReg2Wix\n{\n public class Program\n {\n #region Constants\n\n private const string NS_URI = \"http://schemas.microsoft.com/wix/2006/wi\";\n private const string RegEditorVersionPattern = @\"Windows\\sRegistry\\sEditor\\sVersion\\s(?<RegEditorVersion>.*)\";\n private const string RegKeyPattern = @\"\\[(?<RegistryHive>[^\\\\]*)\\\\(?<RegistryKey>.*)\\]\";\n private const string RegNameValuePattern = \"\\\\\\\"(?<Name>.*)\\\\\\\"=(?<Value>\\\\\\\"?[^\\\\\\\\\\\\\\\"]*)(?<MultiLine>\\\\\\\\?)\";\n private const RegexOptions DefaultRegexOptions = RegexOptions.Multiline |\n RegexOptions.IgnorePatternWhitespace |\n RegexOptions.CultureInvariant;\n #endregion\n\n #region Methods\n\n /// <summary>\n /// Main applciation entry point\n /// </summary>\n /// <param name=\"args\">The args.</param>\n private static void Main(string[] args)\n {\n if (args.Length != 4)\n {\n PrintUsageInstructions();\n return;\n }\n\n if (File.Exists(args[1]))\n {\n ConvertRegistryFileToWix(args[1], args[3]);\n\n Console.WriteLine(\"Successfully completed conversion.\");\n Console.WriteLine(\"Press any key to continue...\");\n Console.ReadKey();\n }\n else\n {\n Console.WriteLine(@\"Input file {0} not found.\", args[1]);\n }\n }\n\n /// <summary>\n /// Prints the usage instructions.\n /// </summary>\n private static void PrintUsageInstructions()\n {\n Console.WriteLine(\"Syntax: AbsReg2Wix.exe /in <Input File (.reg)> /out <Output File>\");\n }\n\n /// <summary>\n /// Convert a .reg file into a .wsx file\n /// </summary>\n /// <param name=\"inputPath\">The input path.</param>\n /// <param name=\"outputPath\">The output path.</param>\n private static void ConvertRegistryFileToWix(string inputPath, string outputPath)\n {\n try\n {\n using (var reader = new StreamReader(inputPath))\n {\n string regEditorVersion = string.Empty;\n bool isRegEditorVersionFound = false;\n\n // Initialize Regex \n var regEditorVersionRegex = new Regex(RegEditorVersionPattern, DefaultRegexOptions);\n var regKeyRegex = new Regex(RegKeyPattern, DefaultRegexOptions);\n var regNameValueRegex = new Regex(RegNameValuePattern, DefaultRegexOptions);\n\n // Create xml document for output\n var xDoc = new XmlDocument();\n xDoc.AppendChild(xDoc.CreateProcessingInstruction(\"xml\", \"version=\\\"1.0\\\" encoding=\\\"utf-8\\\"\"));\n xDoc.AppendChild(xDoc.CreateComment(\n string.Format(\n \"{0}Following code was generated by AbsReg2Wix tool.{0}Tool Version: {1}{0}Date: {2}{0}Command Line: {3}\\n\",\n \"\\n\\t\", Assembly.GetExecutingAssembly().GetName().Version,\n DateTime.Now.ToString(\"F\"),\n Environment.CommandLine)));\n\n XmlElement includeElement = xDoc.CreateElement(\"Include\", NS_URI);\n XmlElement componentElement = null,\n regKeyElement = null,\n registryValueElement = null;\n\n bool multiLine = false;\n var rawValueBuilder = new StringBuilder();\n\n while (!reader.EndOfStream)\n {\n string regFileLine = reader.ReadLine().Trim();\n\n if (!isRegEditorVersionFound)\n {\n var regEditorVersionMatch = regEditorVersionRegex.Match(regFileLine);\n\n if (regEditorVersionMatch.Success)\n {\n regEditorVersion = regEditorVersionMatch.Groups[\"RegEditorVersion\"].Value;\n includeElement.AppendChild(\n xDoc.CreateComment(\"Registry Editor Version: \" + regEditorVersion));\n isRegEditorVersionFound = true;\n }\n }\n\n var regKeyMatch = regKeyRegex.Match(regFileLine);\n\n // Registry Key line found\n if (regKeyMatch.Success)\n {\n if (componentElement != null)\n {\n componentElement.AppendChild(regKeyElement);\n includeElement.AppendChild(componentElement);\n }\n\n componentElement = xDoc.CreateElement(\"Component\", NS_URI);\n\n var idAttr = xDoc.CreateAttribute(\"Id\");\n idAttr.Value = \"Comp_\" + GetMD5HashForString(regFileLine);\n componentElement.Attributes.Append(idAttr);\n\n var guidAttr = xDoc.CreateAttribute(\"Guid\");\n guidAttr.Value = Guid.NewGuid().ToString();\n componentElement.Attributes.Append(guidAttr);\n\n regKeyElement = xDoc.CreateElement(\"RegistryKey\", NS_URI);\n\n var hiveAttr = xDoc.CreateAttribute(\"Root\");\n hiveAttr.Value = GetShortHiveName(regKeyMatch.Groups[\"RegistryHive\"].Value);\n regKeyElement.Attributes.Append(hiveAttr);\n\n var keyAttr = xDoc.CreateAttribute(\"Key\");\n keyAttr.Value = regKeyMatch.Groups[\"RegistryKey\"].Value;\n regKeyElement.Attributes.Append(keyAttr);\n\n var actionAttr = xDoc.CreateAttribute(\"Action\");\n actionAttr.Value = \"createAndRemoveOnUninstall\";\n regKeyElement.Attributes.Append(actionAttr);\n }\n\n var regNameValueMatch = regNameValueRegex.Match(regFileLine);\n\n // Registry Name/Value pair line found\n if (regNameValueMatch.Success)\n {\n registryValueElement = xDoc.CreateElement(\"RegistryValue\", NS_URI);\n\n var nameAttr = xDoc.CreateAttribute(\"Name\");\n nameAttr.Value = regNameValueMatch.Groups[\"Name\"].Value;\n registryValueElement.Attributes.Append(nameAttr);\n\n var actionAttr = xDoc.CreateAttribute(\"Action\");\n actionAttr.Value = \"write\";\n registryValueElement.Attributes.Append(actionAttr);\n\n if (string.IsNullOrEmpty(regNameValueMatch.Groups[\"MultiLine\"].Value))\n {\n string valueType, actualValue;\n\n ParseRegistryValue(regNameValueMatch.Groups[\"Value\"].Value, out valueType,\n out actualValue);\n\n var typeAttr = xDoc.CreateAttribute(\"Type\");\n typeAttr.Value = valueType;\n registryValueElement.Attributes.Append(typeAttr);\n\n var valueAttr = xDoc.CreateAttribute(\"Value\");\n valueAttr.Value = actualValue;\n registryValueElement.Attributes.Append(valueAttr);\n regKeyElement.AppendChild(registryValueElement);\n }\n else\n {\n multiLine = true;\n rawValueBuilder.Append(regNameValueMatch.Groups[\"Value\"].Value\n .Replace(\"\\\\\", string.Empty));\n }\n }\n else if (multiLine)\n {\n if (regFileLine.IndexOf(\"\\\\\") != -1)\n {\n rawValueBuilder.Append(regFileLine.Replace(\"\\\\\", string.Empty));\n }\n else\n {\n rawValueBuilder.Append(regFileLine);\n\n string valueType, actualValue;\n ParseRegistryValue(rawValueBuilder.ToString(), out valueType, out actualValue);\n\n var typeAttr = xDoc.CreateAttribute(\"Type\");\n typeAttr.Value = valueType;\n registryValueElement.Attributes.Append(typeAttr);\n\n var valueAttr = xDoc.CreateAttribute(\"Value\");\n valueAttr.Value = actualValue;\n registryValueElement.Attributes.Append(valueAttr);\n regKeyElement.AppendChild(registryValueElement);\n\n rawValueBuilder.Remove(0, rawValueBuilder.Length);\n multiLine = false;\n }\n }\n }\n\n if (componentElement != null)\n {\n componentElement.AppendChild(regKeyElement);\n includeElement.AppendChild(componentElement);\n }\n\n xDoc.AppendChild(includeElement);\n xDoc.Save(outputPath);\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n }\n\n /// <summary>\n /// Parses the registry value.\n /// </summary>\n /// <param name=\"rawValue\">The raw value.</param>\n /// <param name=\"valueType\">Type of the value.</param>\n /// <param name=\"actualValue\">The actual value.</param>\n private static void ParseRegistryValue(string rawValue, out string valueType, out string actualValue)\n {\n if (rawValue.IndexOf(\"\\\"\") != -1)\n {\n valueType = \"string\";\n actualValue = rawValue.Substring(1, rawValue.Length - 2);\n }\n else if (rawValue.IndexOf(\"dword:\") != -1)\n {\n valueType = \"integer\";\n actualValue = rawValue.Replace(\"dword:\", string.Empty);\n }\n else if (rawValue.IndexOf(\"hex:\") != -1)\n {\n valueType = \"binary\";\n actualValue = rawValue.Replace(\"hex:\", string.Empty)\n .Replace(\",\", string.Empty)\n .ToUpper();\n }\n else if (rawValue.IndexOf(\"hex(7):\") != -1)\n {\n valueType = \"multiString\";\n\n string[] hexStrings = rawValue.Replace(\"hex(7):\", string.Empty).Split(',');\n var bytes = new byte[hexStrings.Length];\n\n for (int i = 0; i < hexStrings.Length; i++)\n {\n bytes[i] = byte.Parse(hexStrings[i], NumberStyles.HexNumber);\n }\n\n actualValue = Encoding.Unicode.GetString(bytes).Replace(\"\\0\", \"[~]\");\n }\n else\n {\n valueType = \"string\";\n actualValue = rawValue;\n }\n }\n\n /// <summary>\n /// Gets the short name of the registry hive.\n /// </summary>\n /// <param name=\"fullHiveName\">Full name of the hive.</param>\n /// <returns></returns>\n private static string GetShortHiveName(string fullHiveName)\n {\n switch (fullHiveName)\n {\n case \"HKEY_LOCAL_MACHINE\":\n return \"HKLM\";\n case \"HKEY_CLASSES_ROOT\":\n return \"HKCR\";\n case \"HKEY_USERS\":\n return \"HKU\";\n case \"HKEY_CURRENT_USER\":\n return \"HKCU\";\n default:\n throw new ArgumentException(string.Format(\"Registry Hive unsupported by Wix: {0}.\",\n fullHiveName));\n }\n }\n\n /// <summary>\n /// Gets the MD5 hash for string.\n /// </summary>\n /// <param name=\"inputString\">The input string.</param>\n /// <returns></returns>\n private static string GetMD5HashForString(string inputString)\n {\n MD5 hashAlg = MD5.Create();\n byte[] originalInBytes = Encoding.ASCII.GetBytes(inputString);\n byte[] hashedOriginal = hashAlg.ComputeHash(originalInBytes);\n\n String outputString = Convert.ToBase64String(hashedOriginal)\n .Replace(\"/\", \"aa\")\n .Replace(\"+\", \"bb\")\n .Replace(\"=\", \"cc\");\n\n return outputString;\n }\n\n #endregion\n }\n}\n</code></pre>\n"
},
{
"answer_id": 970732,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This code works well, but if you have a an empty string value in the registry file you are importing, an exception error gets thrown. You may want to update the ParseRegistryValue section accordingly. </p>\n\n<pre><code> if (rawValue.IndexOf(\"\\\"\") != -1)\n {\n valueType = \"string\";\n if (rawValue.Length > 1)\n {\n actualValue = rawValue.Substring(1, rawValue.Length - 2);\n }\n else\n {\n actualValue = \"\";\n }\n }\n</code></pre>\n"
},
{
"answer_id": 12844011,
"author": "Ujjwal Singh",
"author_id": 483588,
"author_profile": "https://Stackoverflow.com/users/483588",
"pm_score": 3,
"selected": false,
"text": "<p>Now it's built into Wix : <code>Heat.exe</code> - Harvesting tool. </p>\n\n<blockquote>\n <p><a href=\"https://stackoverflow.com/a/11988983/483588\">https://stackoverflow.com/a/11988983/483588</a></p>\n</blockquote>\n"
},
{
"answer_id": 50223070,
"author": "Malcolm McCaffery",
"author_id": 941548,
"author_profile": "https://Stackoverflow.com/users/941548",
"pm_score": 1,
"selected": false,
"text": "<p>From Wix 4.0</p>\n\n<pre><code>C:\\Program Files (x86)\\WiX Toolset v4.0\\bin>heat /? | find /i \"reg\"\n reg harvest a .reg file\n -sreg suppress registry harvesting\n</code></pre>\n\n<p>To use, where regfile.reg is the registry input file and fragment.xml is the output file to generate.</p>\n\n<pre><code>heat reg regfile.reg -o fragment.xml\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
**Is there a tool to generate WiX XML given a .reg file?**
---
In 2.0, you were supposed to be able to run tallow to generate registry XML:
```
tallow -r my.reg
```
For what it's worth, the version of tallow I have is producing empty XML.
In 3.0, tallow has been replaced with heat, but I can't figure out how to get it to produce output from a .reg file.
Is there a way to do this in 3.0?
|
I couldn't find a tool, so I made one.
The source code may not be elegant, but it seems to work:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
namespace Reg2Wix
{
class Program
{
static void PrintUsage()
{
Console.WriteLine("reg2wix <input file> <output file>");
}
/// <summary>
/// Parse the hive out of a registry key
/// </summary>
/// <param name="keyWithHive"></param>
/// <param name="hive"></param>
/// <param name="key"></param>
static void ParseKey(string keyWithHive, out string hive, out string key)
{
if (keyWithHive == null)
{
throw new ArgumentNullException("keyWithHive");
}
if (keyWithHive.StartsWith("HKEY_LOCAL_MACHINE\\"))
{
hive = "HKLM";
key = keyWithHive.Substring(19);
}
else if (keyWithHive.StartsWith("HKEY_CLASSES_ROOT\\"))
{
hive = "HKCR";
key = keyWithHive.Substring(18);
}
else if (keyWithHive.StartsWith("HKEY_USERS\\"))
{
hive = "HKU";
key = keyWithHive.Substring(11);
}
else if (keyWithHive.StartsWith("HKEY_CURRENT_USER\\"))
{
hive = "HKCU";
key = keyWithHive.Substring(18);
}
else
{
throw new ArgumentException();
}
}
/// <summary>
/// Write a WiX RegistryValue element for the specified key, name, and value
/// </summary>
/// <param name="writer"></param>
/// <param name="key"></param>
/// <param name="name"></param>
/// <param name="value"></param>
static void WriteRegistryValue(XmlWriter writer, string key, string name, string value)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (key == null)
{
throw new ArgumentNullException("key");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
string hive;
string keyPart;
ParseKey(key, out hive, out keyPart);
writer.WriteStartElement("RegistryValue");
writer.WriteAttributeString("Root", hive);
writer.WriteAttributeString("Key", keyPart);
if (!String.IsNullOrEmpty(name))
{
writer.WriteAttributeString("Name", name);
}
writer.WriteAttributeString("Value", value);
writer.WriteAttributeString("Type", "string");
writer.WriteAttributeString("Action", "write");
writer.WriteEndElement();
}
/// <summary>
/// Convert a .reg file into an XML document
/// </summary>
/// <param name="inputReader"></param>
/// <param name="xml"></param>
static void RegistryFileToWix(TextReader inputReader, XmlWriter xml)
{
Regex regexKey = new Regex("^\\[([^\\]]+)\\]$");
Regex regexValue = new Regex("^\"([^\"]+)\"=\"([^\"]*)\"$");
Regex regexDefaultValue = new Regex("@=\"([^\"]+)\"$");
string currentKey = null;
string line;
while ((line = inputReader.ReadLine()) != null)
{
line = line.Trim();
Match match = regexKey.Match(line);
if (match.Success)
{
//key track of the current key
currentKey = match.Groups[1].Value;
}
else
{
//if we have a current key
if (currentKey != null)
{
//see if this is an acceptable name=value pair
match = regexValue.Match(line);
if (match.Success)
{
WriteRegistryValue(xml, currentKey, match.Groups[1].Value, match.Groups[2].Value);
}
else
{
//see if this is an acceptable default value (starts with @)
match = regexDefaultValue.Match(line);
if (match.Success)
{
WriteRegistryValue(xml, currentKey, (string)null, match.Groups[1].Value);
}
}
}
}
}
}
/// <summary>
/// Convert a .reg file into a .wsx file
/// </summary>
/// <param name="inputPath"></param>
/// <param name="outputPath"></param>
static void RegistryFileToWix(string inputPath, string outputPath)
{
using (StreamReader reader = new StreamReader(inputPath))
{
using (XmlTextWriter writer = new XmlTextWriter(outputPath, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 3;
writer.IndentChar = ' ';
writer.WriteStartDocument();
writer.WriteStartElement("Component");
RegistryFileToWix(reader, writer);
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
static void Main(string[] args)
{
if (args.Length != 2)
{
PrintUsage();
return;
}
RegistryFileToWix(args[0], args[1]);
}
}
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.