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
|
---|---|---|---|---|---|---|
284,336 |
<p>My colleague has written a DLL which drives Excel.<br />
When I reference his DLL in my .NET app, I get a warning:</p>
<pre><code>The dependency 'Microsoft.Office.Interop.Excel' could not be found.
</code></pre>
<p>My app will compile.<br />
However, when I get to the bit that uses my colleague's DLL to access Excel, an exception is thrown, with the message above.</p>
<p>We should have identical setups: <strong>Windows XP Pro SP3, VS2003, .NET 1.1, Office 2003</strong></p>
<p>My problem seems similar to <a href="https://stackoverflow.com/questions/224181/net-microsoftofficeinteropexcel-and-interopexcel-dll">this question</a>, but I don't know if it's the same.</p>
<p>Any help or suggestions gratefully received!</p>
<h2>Update:</h2>
<p>Thanks for answers so far!</p>
<p>I have not added an explicit reference to <code>Microsoft.Office.Interop.Excel</code>.<br />
Surely I shouldn't have to?<br />
<strong>However</strong>: When I tried to add this reference, I cannot find <code>Microsoft.Office.Interop.Excel</code> in the Add Reference dialog.</p>
<p>Presumably this means that I am missing a DLL?<br />
... But I don't understand how that could happen?!</p>
<h2>Update (fixed):</h2>
<p>@ConcernedOfTunbridgeWells has the answer that fixed this for me: installing the Primary Interop Assemblies.</p>
|
[
{
"answer_id": 284355,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Have you explicitly added a reference to <code>Microsoft.Office.Interop.Excel</code> in your project?</p>\n"
},
{
"answer_id": 284387,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 2,
"selected": false,
"text": "<p>Ask your colleague to send you the Interop.Excel.dll file that he has in his bin folder. Alternatively as Jon has suggested above you can add a reference to Microsoft Excel library from the COM tab of the Add Reference dialog.</p>\n"
},
{
"answer_id": 284546,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 5,
"selected": true,
"text": "<p>You may need to install the <a href=\"https://msdn.microsoft.com/en-us/library/aa302338.aspx\" rel=\"nofollow noreferrer\">Primary Interop Assemblies</a> for Office, which can be downloaded from <a href=\"https://www.microsoft.com/en-us/download/details.aspx?id=3508\" rel=\"nofollow noreferrer\">Here.</a> Depending on the order that you install Visual Studio and Office they may not be installed by default.</p>\n"
},
{
"answer_id": 3836021,
"author": "nathanchere",
"author_id": 243557,
"author_profile": "https://Stackoverflow.com/users/243557",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem trying to run the \"official\" F# samples on CodePlex.\nProjects were referencing interop V11.\nI removed the references and went to add them again, noticing I had V9, V12 and V14.\nI added V12 and everything worked fine without any further changes.</p>\n\n<p>Something you might want to try before installing yet another interop version.</p>\n"
},
{
"answer_id": 25736743,
"author": "Emmanuel",
"author_id": 4021473,
"author_profile": "https://Stackoverflow.com/users/4021473",
"pm_score": 0,
"selected": false,
"text": "<p>I just solved it as follows: </p>\n\n<ul>\n<li>First I go to Add Reference</li>\n<li>Click COM on the top left part of Add Reference window.</li>\n<li>Find Microsoft Excel 15.0 Object Library.</li>\n<li>Or maybe it may not be 15.0, just object library.</li>\n</ul>\n\n<p>I am using Microsoft Office 2013 and Microsoft Visual Studio 2012.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
My colleague has written a DLL which drives Excel.
When I reference his DLL in my .NET app, I get a warning:
```
The dependency 'Microsoft.Office.Interop.Excel' could not be found.
```
My app will compile.
However, when I get to the bit that uses my colleague's DLL to access Excel, an exception is thrown, with the message above.
We should have identical setups: **Windows XP Pro SP3, VS2003, .NET 1.1, Office 2003**
My problem seems similar to [this question](https://stackoverflow.com/questions/224181/net-microsoftofficeinteropexcel-and-interopexcel-dll), but I don't know if it's the same.
Any help or suggestions gratefully received!
Update:
-------
Thanks for answers so far!
I have not added an explicit reference to `Microsoft.Office.Interop.Excel`.
Surely I shouldn't have to?
**However**: When I tried to add this reference, I cannot find `Microsoft.Office.Interop.Excel` in the Add Reference dialog.
Presumably this means that I am missing a DLL?
... But I don't understand how that could happen?!
Update (fixed):
---------------
@ConcernedOfTunbridgeWells has the answer that fixed this for me: installing the Primary Interop Assemblies.
|
You may need to install the [Primary Interop Assemblies](https://msdn.microsoft.com/en-us/library/aa302338.aspx) for Office, which can be downloaded from [Here.](https://www.microsoft.com/en-us/download/details.aspx?id=3508) Depending on the order that you install Visual Studio and Office they may not be installed by default.
|
284,358 |
<p>When serializing/de-serializing certain classes I've come across the need to flag or mark certain properties as CDATA elements (due to their content). I am currently handling this like so:</p>
<pre><code> <XmlElement("MessageText")> _
Public Property XmlContentLeft() As XmlCDataSection
Get
Dim doc As New XmlDataDocument()
Dim cd As XmlCDataSection = doc.CreateCDataSection(Me.MessageText)
Return cd
End Get
Set(ByVal value As XmlCDataSection)
Me.MessageText = value.Value
End Set
End Property
<XmlIgnore()> _
Public Property MessageText() As String
Get
Return _messageText
End Get
Set(ByVal value As String)
_messageText= value
End Set
End Property
</code></pre>
<p>Now while this works great it has drawbacks -- I now have duplicate properties for anything I want to be a CDATA element and I have to write extra code for these properties.</p>
<p>So my question is whether or not there is a better way to do this? I don't want to have to write custom schemas or serialization routines for each class. In an ideal scenario I'd be able to add an attribute to these properties so they are automatically treated as CDATA elements. </p>
|
[
{
"answer_id": 284456,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": true,
"text": "<p>Two things:</p>\n\n<p>1) You can simplify your existing CDATA code like this:</p>\n\n<pre><code><XmlElement(\"MessageText\")> _\nPublic Property XmlContentLeft() As XmlCDataSection\n Get\n return GetCData(Me.MessageText)\n End Get\n Set(ByVal value As XmlCDataSection)\n Me.MessageText = value.Value\n End Set\nEnd Property\n\n' this method is re-usable by any property that needs CData\nPrivate Function GetCData(ByVal value As String) As XmlCDataSection\n Static doc As New XmlDataDocument() \n return doc.CreateCDataSection(value)\nEnd Function\n\n<XmlIgnore()> _\nPublic Property MessageText() As String\n Get\n Return _messageText\n End Get\n Set(ByVal value As String)\n _messageText= value\n End Set\nEnd Property\n</code></pre>\n\n<p>Of course that's actually more code than you posted, but note that your CData property is now much simpler. Also, my use of <code>Static</code> isn't a typo or C# mistake. VB.Net has a little-known <code>Static</code> keyword for creating members in functions. This way the XmlDataDocument is only created once for the entire class and doesn't pollute your class's private namespace.</p>\n\n<p>2) The serializer should already properly escapes character data. Do you really need it to be CData? Anything you serialize should be properly deserialized to match the original, even things like code strings. The only case I can thing where you might <em>need</em> a CDATA section is if you have to conform to a schema that's expecting it.</p>\n"
},
{
"answer_id": 3890019,
"author": "James Close",
"author_id": 470183,
"author_profile": "https://Stackoverflow.com/users/470183",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem - a client needed XML from a webservice with strings wrapped in horrible CData tags, this is totally unneccessary but they didn't want to recode their client so I had to make my XML conform.</p>\n\n<p>The way I worked it was to retype the (string) properties I wanted to appear as CDATA to my own custom type \"XmlCDataString\".</p>\n\n<p>I then implemented IXmlSerializable on that type and shoved a couple of Narrowing and Widening conversion operator overloads in so that the properties still work as much like Strings as possible.</p>\n\n<pre><code>Imports System.Xml.Serialization\nImports System.Xml\n<Serializable()> _\nPublic Class XmlCDataString\n Implements IXmlSerializable\n\n Private _strValue As String = Nothing\n\n Public Sub New()\n\n End Sub\n\n Public Sub New(ByVal strValue As String)\n _strValue = strValue\n End Sub\n\n Public Property StringValue() As String\n Get\n Return _strValue\n End Get\n Set(ByVal value As String)\n _strValue = value\n End Set\n End Property\n\n Public Shared Widening Operator CType(ByVal strValue As String) As XmlCDataString\n Return New XmlCDataString(strValue)\n End Operator\n\n Public Shared Narrowing Operator CType(ByVal cdata As XmlCDataString) As String\n Return cdata.StringValue\n End Operator\n\n Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema\n Throw New NotImplementedException\n End Function\n\n Public Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements System.Xml.Serialization.IXmlSerializable.ReadXml\n ' TODO\n End Sub\n\n Public Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements System.Xml.Serialization.IXmlSerializable.WriteXml\n Dim doc As XmlDocument\n Dim xmlCData As XmlCDataSection\n Dim serializer As XmlSerializer\n\n doc = New XmlDataDocument()\n xmlCData = doc.CreateCDataSection(_strValue)\n serializer = New XmlSerializer(GetType(XmlCDataSection))\n serializer.Serialize(writer, xmlCData)\n\n End Sub\nEnd Class\n</code></pre>\n\n<p>The properties I am then serializing to CData I have to retype as follows (using your example):</p>\n\n<pre><code>Private _messageText As XmlCDataString \n\nPublic Property MessageText() As XmlCDataString \n Get \n Return _messageText \n End Get \n Set(ByVal value As XmlCDataString) \n _messageText= value \n End Set \nEnd Property \n</code></pre>\n\n<p>That worked for me!</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
] |
When serializing/de-serializing certain classes I've come across the need to flag or mark certain properties as CDATA elements (due to their content). I am currently handling this like so:
```
<XmlElement("MessageText")> _
Public Property XmlContentLeft() As XmlCDataSection
Get
Dim doc As New XmlDataDocument()
Dim cd As XmlCDataSection = doc.CreateCDataSection(Me.MessageText)
Return cd
End Get
Set(ByVal value As XmlCDataSection)
Me.MessageText = value.Value
End Set
End Property
<XmlIgnore()> _
Public Property MessageText() As String
Get
Return _messageText
End Get
Set(ByVal value As String)
_messageText= value
End Set
End Property
```
Now while this works great it has drawbacks -- I now have duplicate properties for anything I want to be a CDATA element and I have to write extra code for these properties.
So my question is whether or not there is a better way to do this? I don't want to have to write custom schemas or serialization routines for each class. In an ideal scenario I'd be able to add an attribute to these properties so they are automatically treated as CDATA elements.
|
Two things:
1) You can simplify your existing CDATA code like this:
```
<XmlElement("MessageText")> _
Public Property XmlContentLeft() As XmlCDataSection
Get
return GetCData(Me.MessageText)
End Get
Set(ByVal value As XmlCDataSection)
Me.MessageText = value.Value
End Set
End Property
' this method is re-usable by any property that needs CData
Private Function GetCData(ByVal value As String) As XmlCDataSection
Static doc As New XmlDataDocument()
return doc.CreateCDataSection(value)
End Function
<XmlIgnore()> _
Public Property MessageText() As String
Get
Return _messageText
End Get
Set(ByVal value As String)
_messageText= value
End Set
End Property
```
Of course that's actually more code than you posted, but note that your CData property is now much simpler. Also, my use of `Static` isn't a typo or C# mistake. VB.Net has a little-known `Static` keyword for creating members in functions. This way the XmlDataDocument is only created once for the entire class and doesn't pollute your class's private namespace.
2) The serializer should already properly escapes character data. Do you really need it to be CData? Anything you serialize should be properly deserialized to match the original, even things like code strings. The only case I can thing where you might *need* a CDATA section is if you have to conform to a schema that's expecting it.
|
284,364 |
<p>What's the easiest and most robust way of altering the .NET DateTimePicker control, to allow users to enter <code>null</code> values?</p>
|
[
{
"answer_id": 284372,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<p>Placing an additional checkbox labeled something like \"enable notification\" that enables / disables the DateTimePicker.</p>\n"
},
{
"answer_id": 284386,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 4,
"selected": true,
"text": "<p>Here's an approach from this CodeProject article on creating a <a href=\"http://www.codeproject.com/KB/selection/Nullable_DateTimePicker.aspx\" rel=\"nofollow noreferrer\">Nullable DateTimePicker</a>. </p>\n\n<blockquote>\n <p>I have overridden the <code>Value</code> property to accept <code>Null</code> value as <code>DateTime.MinValue</code>, while maintaining the validation of <code>MinValue</code> and <code>MaxValue</code> of the standard control.</p>\n</blockquote>\n\n<p>Here's a version of the custom class component from the article</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker\n{\n private DateTimePickerFormat originalFormat = DateTimePickerFormat.Short;\n private string originalCustomFormat;\n private bool isNull;\n\n public new DateTime Value\n {\n get => isNull ? DateTime.MinValue : base.Value;\n set\n {\n // incoming value is set to min date\n if (value == DateTime.MinValue)\n {\n // if set to min and not previously null, preserve original formatting\n if (!isNull)\n {\n originalFormat = this.Format;\n originalCustomFormat = this.CustomFormat;\n isNull = true;\n }\n\n this.Format = DateTimePickerFormat.Custom;\n this.CustomFormat = \" \";\n }\n else // incoming value is real date\n {\n // if set to real date and previously null, restore original formatting\n if (isNull)\n {\n this.Format = originalFormat;\n this.CustomFormat = originalCustomFormat;\n isNull = false;\n }\n\n base.Value = value;\n }\n }\n }\n\n protected override void OnCloseUp(EventArgs eventargs)\n {\n // on keyboard close, restore format\n if (Control.MouseButtons == MouseButtons.None)\n {\n if (isNull)\n {\n this.Format = originalFormat;\n this.CustomFormat = originalCustomFormat;\n isNull = false;\n }\n }\n base.OnCloseUp(eventargs);\n }\n\n protected override void OnKeyDown(KeyEventArgs e)\n {\n base.OnKeyDown(e);\n\n // on delete key press, set to min value (null)\n if (e.KeyCode == Keys.Delete)\n {\n this.Value = DateTime.MinValue;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 352770,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Tri's solution did not quite cut it for me and so thought Mr. Grazioli and he did something about it: <a href=\"http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c9645\" rel=\"nofollow noreferrer\" title=\"Yet Another Nullable DateTimePicker\">http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c9645</a> </p>\n"
},
{
"answer_id": 1762980,
"author": "Jan Obrestad",
"author_id": 214557,
"author_profile": "https://Stackoverflow.com/users/214557",
"pm_score": 6,
"selected": false,
"text": "<p>You don't need to modify it to do this. </p>\n\n<p>The <code>DateTimePicker</code> in .net actually has a checkbox built-in. </p>\n\n<p>Set the <code>ShowCheckBox</code> property to <code>true</code>.</p>\n\n<p>Then you can use the <code>Checked</code> property to see if the user has entered a value. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.showcheckbox(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.showcheckbox(VS.80).aspx</a></p>\n"
},
{
"answer_id": 8615591,
"author": "quickdraw",
"author_id": 1082591,
"author_profile": "https://Stackoverflow.com/users/1082591",
"pm_score": 0,
"selected": false,
"text": "<p>I posted my long way around solution, which has some findings in the code comments about the peculiar issues with this control:</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/forums/en-US/winforms/thread/f1f8cc0a-0ac9-4a3e-9ba4-9af495e8ff58/\" rel=\"nofollow\">DateTime Picker null value</a></p>\n"
},
{
"answer_id": 33031322,
"author": "Eduard",
"author_id": 5421874,
"author_profile": "https://Stackoverflow.com/users/5421874",
"pm_score": 0,
"selected": false,
"text": "<p>Set the <code>ShowCheckBox</code> property to <code>true</code>.</p>\n\n<p>Then you can use the Checked property as follows:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private void dateTimePicker1_ValueChanged(object sender, EventArgs e)\n{\n DateTimePicker thisDateTimePicker = (DateTimePicker)sender;\n if (thisDateTimePicker.Checked == false)\n {\n thisDateTimePicker.CustomFormat = @\" \"; //space\n thisDateTimePicker.Format = DateTimePickerFormat.Custom;\n }\n else\n {\n thisDateTimePicker.Format = DateTimePickerFormat.Short;\n }\n}\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18071/"
] |
What's the easiest and most robust way of altering the .NET DateTimePicker control, to allow users to enter `null` values?
|
Here's an approach from this CodeProject article on creating a [Nullable DateTimePicker](http://www.codeproject.com/KB/selection/Nullable_DateTimePicker.aspx).
>
> I have overridden the `Value` property to accept `Null` value as `DateTime.MinValue`, while maintaining the validation of `MinValue` and `MaxValue` of the standard control.
>
>
>
Here's a version of the custom class component from the article
```cs
public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker
{
private DateTimePickerFormat originalFormat = DateTimePickerFormat.Short;
private string originalCustomFormat;
private bool isNull;
public new DateTime Value
{
get => isNull ? DateTime.MinValue : base.Value;
set
{
// incoming value is set to min date
if (value == DateTime.MinValue)
{
// if set to min and not previously null, preserve original formatting
if (!isNull)
{
originalFormat = this.Format;
originalCustomFormat = this.CustomFormat;
isNull = true;
}
this.Format = DateTimePickerFormat.Custom;
this.CustomFormat = " ";
}
else // incoming value is real date
{
// if set to real date and previously null, restore original formatting
if (isNull)
{
this.Format = originalFormat;
this.CustomFormat = originalCustomFormat;
isNull = false;
}
base.Value = value;
}
}
}
protected override void OnCloseUp(EventArgs eventargs)
{
// on keyboard close, restore format
if (Control.MouseButtons == MouseButtons.None)
{
if (isNull)
{
this.Format = originalFormat;
this.CustomFormat = originalCustomFormat;
isNull = false;
}
}
base.OnCloseUp(eventargs);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
// on delete key press, set to min value (null)
if (e.KeyCode == Keys.Delete)
{
this.Value = DateTime.MinValue;
}
}
}
```
|
284,365 |
<p>I'm trying to determine what situations MySQL updates an index. Say I have the following table:</p>
<pre><code>CREATE TABLE MyTable (
ID INT NOT NULL AUTO_INCREMENT,
MyIndexedColumn VARCHAR NOT NULL,
MyNonIndexedColumn VARCHAR,
PRIMARY KEY (ID),
INDEX MyNewIndex(MyIndexedColumn)
)
</code></pre>
<p>Then I run the following SQL to insert a row:</p>
<pre><code>INSERT INTO MyTable (MyIndexedColumn, MyNonIndexedColumn)
VALUES ('MyTestValue', 'MyTestValue');
</code></pre>
<p>I understand that this query will add some sort of hash key to a B-Tree index in MySQL for the value 'MyTestValue'.</p>
<p>Now, if I run the following statement, will that force that B-Tree index to be updated, even if I haven't changed the value of the column?</p>
<pre><code>UPDATE MyTable SET MyIndexedColumn = 'MyTestValue',
MyNonIndexedColumn = 'A New Value' WHERE ID = 1;
</code></pre>
<p>Is MySQL smart enough to determine that? Or by just making that column part of the update statement, am I telling MySQL that possibly something has changed, and it should do the work to update the index?</p>
|
[
{
"answer_id": 284376,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "<p>If you run that query in the MySQL client, you'll see something like </p>\n\n<blockquote>\n <p>Rows matches: 1, Rows Updated: 0</p>\n</blockquote>\n\n<p>So MySQL definitely knows when a row has changed or not - I'd assume from there that they're smart enough not to update the index from there.</p>\n"
},
{
"answer_id": 284378,
"author": "Ciaran McNulty",
"author_id": 34024,
"author_profile": "https://Stackoverflow.com/users/34024",
"pm_score": 1,
"selected": false,
"text": "<p>When you perform an UPDATE MySQL reports the number of rows matched and the number changed. Running your example query gives the output:</p>\n\n<p>Query OK, 0 rows affected (0.00 sec)\nRows matched: 1 Changed: 0 Warnings: 0</p>\n\n<p>I would be very surprised if MySQL didn't then use that information to determine whether to update the index.</p>\n"
},
{
"answer_id": 284383,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "<p>Not only is MySQL smart enough to not update the index if the value hasn't changed, it is smart enough to not rewrite the column value with the same value.</p>\n"
},
{
"answer_id": 287880,
"author": "Ezran",
"author_id": 32883,
"author_profile": "https://Stackoverflow.com/users/32883",
"pm_score": 3,
"selected": false,
"text": "<p>I did some testing on this, with mysql 5.0.41, comparing updates against two identical innodb tables (7 cols, all integers), except that one table had 5 indexes (a couple of which were 2-column), and the other table had no indexes. (Each table had its primary key index, though.)</p>\n\n<p>Here's what I ended up with (the table without indexes is A, the table with indexes is B):</p>\n\n<pre><code>10k updates of an indexed column with a new value:\nA: 76.8 seconds\nB: 126.7 seconds\n\n10k updates of a non-indexed column with a new value:\nA: 27.6 seconds\nB: 22.0 seconds\n\n10k updates of a random column with its same value:\nA: 1.4 seconds\nB: 1.2 seconds\n\n10k updates of a random column with an incremented value:\nA: 12.2 seconds\nB: 50.0 seconds\n\n10k updates of an indexed column=>same value, non-indexed column=>new value:\nA: 7.0 seconds\nB: 10.5 seconds\n</code></pre>\n\n<p>I'm assuming that part of the reason the same/incremented value ones are faster is because I had to look up the row before doing the update, so it'd be cached in some form in mysql.</p>\n\n<p>This all pretty much plays out what the others are saying, but gives some perspective on how much things are affected by the indexes. However, in the specific case Jim asked about, it looks like it might be as much as 50% slower.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650/"
] |
I'm trying to determine what situations MySQL updates an index. Say I have the following table:
```
CREATE TABLE MyTable (
ID INT NOT NULL AUTO_INCREMENT,
MyIndexedColumn VARCHAR NOT NULL,
MyNonIndexedColumn VARCHAR,
PRIMARY KEY (ID),
INDEX MyNewIndex(MyIndexedColumn)
)
```
Then I run the following SQL to insert a row:
```
INSERT INTO MyTable (MyIndexedColumn, MyNonIndexedColumn)
VALUES ('MyTestValue', 'MyTestValue');
```
I understand that this query will add some sort of hash key to a B-Tree index in MySQL for the value 'MyTestValue'.
Now, if I run the following statement, will that force that B-Tree index to be updated, even if I haven't changed the value of the column?
```
UPDATE MyTable SET MyIndexedColumn = 'MyTestValue',
MyNonIndexedColumn = 'A New Value' WHERE ID = 1;
```
Is MySQL smart enough to determine that? Or by just making that column part of the update statement, am I telling MySQL that possibly something has changed, and it should do the work to update the index?
|
If you run that query in the MySQL client, you'll see something like
>
> Rows matches: 1, Rows Updated: 0
>
>
>
So MySQL definitely knows when a row has changed or not - I'd assume from there that they're smart enough not to update the index from there.
|
284,368 |
<p>I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like</p>
<pre><code> <c:forEach items="${m.items}" var="i" varStatus="itemsRow">
<form:input path="items[${itemsRow.index}]"/>
</c:forEach>
<form:errors path="items" />
</code></pre>
<p>would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.</p>
<p>Is there something in Spring that works out of the box with Sets?</p>
|
[
{
"answer_id": 284513,
"author": "Jacob Mattison",
"author_id": 1237,
"author_profile": "https://Stackoverflow.com/users/1237",
"pm_score": 3,
"selected": false,
"text": "<p>I think it has to be an ordered collection. For example,there's <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/validation.html\" rel=\"noreferrer\">a chart</a> in the Spring reference that talks about how to reference properties. It says:</p>\n\n<blockquote>\n <p>account[2] Indicates the third element\n of the indexed property account.\n Indexed properties can be of type\n array, list or other <em>naturally ordered</em>\n collection (emphasis theirs)</p>\n</blockquote>\n\n<p>Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.</p>\n"
},
{
"answer_id": 284549,
"author": "zmf",
"author_id": 13285,
"author_profile": "https://Stackoverflow.com/users/13285",
"pm_score": 1,
"selected": false,
"text": "<p>I am not crystal clear on how exactly this gets bound, but it works for my purposes.</p>\n\n<pre><code> <c:forEach items=\"${items}\" var=\"i\" varStatus=\"itemsRow\">\n <input name=\"items[${itemsRow.index}].fieldName\" type=\"text\"/>\n </c:forEach>\n <form:errors path=\"items\" />\n</code></pre>\n"
},
{
"answer_id": 331233,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I think the reason that it doesn't work with a Set is because a the order of a Set is not guaranteed. When you try to bind to the first object on post, it may not have been the first object in that list to render out. For example, items[0] may not be the same between the GET and the POST.</p>\n\n<p>So it should work fine if you use an implementation of Set that is ordered, such as a SortedSet or TreeSet.</p>\n"
},
{
"answer_id": 334483,
"author": "Alex Marshall",
"author_id": 32232,
"author_profile": "https://Stackoverflow.com/users/32232",
"pm_score": 1,
"selected": false,
"text": "<p>You could try writing your own custom Editor to do the job, and then registering the editor with the controller for the form. You wouldn't have to bother with indexing the elements in the Set that way. And as previously mentioned, if there's a way of sorting the elements, you could ensure their order in the set using SortedSet.</p>\n"
},
{
"answer_id": 5732918,
"author": "Deejay",
"author_id": 534804,
"author_profile": "https://Stackoverflow.com/users/534804",
"pm_score": -1,
"selected": false,
"text": "<p>You can use a semi-colon-delimited list if you're using numeric references to the IDs of objects, and an appropriate Converter implementation registered.</p>\n\n<p>POST data\n leaderboards=1,2</p>\n\n<p>Converter implementation (ignore the JSON stuff)</p>\n\n<pre><code> public final class LeaderboardConverter extends JsonDeserializer<Leaderboard> implements Converter<String, Leaderboard>\n {\n public Leaderboard convert(String source) throws IllegalArgumentException\n {\n Leaderboard activity = new Leaderboard();\n activity.setId(new Integer(source));\n return activity;\n }\n\n\n public Leaderboard deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException\n {\n return convert(jp.getText());\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 13084828,
"author": "sab",
"author_id": 218480,
"author_profile": "https://Stackoverflow.com/users/218480",
"pm_score": 2,
"selected": false,
"text": "<p>found perfect solution here: <a href=\"http://forum.springsource.org/showthread.php?45312-Submitting-arrays\" rel=\"nofollow\">http://forum.springsource.org/showthread.php?45312-Submitting-arrays</a> </p>\n\n<p>general idea - using commons-collections methods to init list:</p>\n\n<pre><code>private List someList = LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(com.abc.xyz.SomeClass.class));\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6069/"
] |
I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like
```
<c:forEach items="${m.items}" var="i" varStatus="itemsRow">
<form:input path="items[${itemsRow.index}]"/>
</c:forEach>
<form:errors path="items" />
```
would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.
Is there something in Spring that works out of the box with Sets?
|
I think it has to be an ordered collection. For example,there's [a chart](http://static.springframework.org/spring/docs/2.5.x/reference/validation.html) in the Spring reference that talks about how to reference properties. It says:
>
> account[2] Indicates the third element
> of the indexed property account.
> Indexed properties can be of type
> array, list or other *naturally ordered*
> collection (emphasis theirs)
>
>
>
Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.
|
284,370 |
<p>I'm trying to return all the child nodes of a set of navigation nodes in sharepoint, the SDK implies I should be doing something like this:</p>
<pre><code>NodeColl = objSite.Navigation.TopNavigationBar
Dim Node as SPNavigationNode
For Each Node In NodeColl
if Node.IsVisible then
Response.Write("<siteMapNode url=""" & Node.Url & """ title=""" & Node.Title & """ description=""" & Node.Title & """ >" & Environment.NewLine)
Dim SubChildNodes as SPNavigationNodeCollection = Node.Children
Response.Write(SubChildNodes.Count) 'returns 0 always even though I know theres over 20 nodes in some of the sections
Dim ChildNode as SPNavigationNode
For Each ChildNode in SubChildNodes
if ChildNode.IsVisible then
Response.Write("<siteMapNode url=""" & ChildNode.Url & """ title=""" & ChildNode.Title & """ description=""" & ChildNode.Title & """ />" & Environment.NewLine)
End if
Next
Response.Write("</siteMapNode>" & Environment.NewLine)
End If
Next
</code></pre>
<p>however whenever I do, it lists the top level navigation nodes but I cannot get the children to be displayed.</p>
|
[
{
"answer_id": 284513,
"author": "Jacob Mattison",
"author_id": 1237,
"author_profile": "https://Stackoverflow.com/users/1237",
"pm_score": 3,
"selected": false,
"text": "<p>I think it has to be an ordered collection. For example,there's <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/validation.html\" rel=\"noreferrer\">a chart</a> in the Spring reference that talks about how to reference properties. It says:</p>\n\n<blockquote>\n <p>account[2] Indicates the third element\n of the indexed property account.\n Indexed properties can be of type\n array, list or other <em>naturally ordered</em>\n collection (emphasis theirs)</p>\n</blockquote>\n\n<p>Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.</p>\n"
},
{
"answer_id": 284549,
"author": "zmf",
"author_id": 13285,
"author_profile": "https://Stackoverflow.com/users/13285",
"pm_score": 1,
"selected": false,
"text": "<p>I am not crystal clear on how exactly this gets bound, but it works for my purposes.</p>\n\n<pre><code> <c:forEach items=\"${items}\" var=\"i\" varStatus=\"itemsRow\">\n <input name=\"items[${itemsRow.index}].fieldName\" type=\"text\"/>\n </c:forEach>\n <form:errors path=\"items\" />\n</code></pre>\n"
},
{
"answer_id": 331233,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I think the reason that it doesn't work with a Set is because a the order of a Set is not guaranteed. When you try to bind to the first object on post, it may not have been the first object in that list to render out. For example, items[0] may not be the same between the GET and the POST.</p>\n\n<p>So it should work fine if you use an implementation of Set that is ordered, such as a SortedSet or TreeSet.</p>\n"
},
{
"answer_id": 334483,
"author": "Alex Marshall",
"author_id": 32232,
"author_profile": "https://Stackoverflow.com/users/32232",
"pm_score": 1,
"selected": false,
"text": "<p>You could try writing your own custom Editor to do the job, and then registering the editor with the controller for the form. You wouldn't have to bother with indexing the elements in the Set that way. And as previously mentioned, if there's a way of sorting the elements, you could ensure their order in the set using SortedSet.</p>\n"
},
{
"answer_id": 5732918,
"author": "Deejay",
"author_id": 534804,
"author_profile": "https://Stackoverflow.com/users/534804",
"pm_score": -1,
"selected": false,
"text": "<p>You can use a semi-colon-delimited list if you're using numeric references to the IDs of objects, and an appropriate Converter implementation registered.</p>\n\n<p>POST data\n leaderboards=1,2</p>\n\n<p>Converter implementation (ignore the JSON stuff)</p>\n\n<pre><code> public final class LeaderboardConverter extends JsonDeserializer<Leaderboard> implements Converter<String, Leaderboard>\n {\n public Leaderboard convert(String source) throws IllegalArgumentException\n {\n Leaderboard activity = new Leaderboard();\n activity.setId(new Integer(source));\n return activity;\n }\n\n\n public Leaderboard deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException\n {\n return convert(jp.getText());\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 13084828,
"author": "sab",
"author_id": 218480,
"author_profile": "https://Stackoverflow.com/users/218480",
"pm_score": 2,
"selected": false,
"text": "<p>found perfect solution here: <a href=\"http://forum.springsource.org/showthread.php?45312-Submitting-arrays\" rel=\"nofollow\">http://forum.springsource.org/showthread.php?45312-Submitting-arrays</a> </p>\n\n<p>general idea - using commons-collections methods to init list:</p>\n\n<pre><code>private List someList = LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(com.abc.xyz.SomeClass.class));\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2208/"
] |
I'm trying to return all the child nodes of a set of navigation nodes in sharepoint, the SDK implies I should be doing something like this:
```
NodeColl = objSite.Navigation.TopNavigationBar
Dim Node as SPNavigationNode
For Each Node In NodeColl
if Node.IsVisible then
Response.Write("<siteMapNode url=""" & Node.Url & """ title=""" & Node.Title & """ description=""" & Node.Title & """ >" & Environment.NewLine)
Dim SubChildNodes as SPNavigationNodeCollection = Node.Children
Response.Write(SubChildNodes.Count) 'returns 0 always even though I know theres over 20 nodes in some of the sections
Dim ChildNode as SPNavigationNode
For Each ChildNode in SubChildNodes
if ChildNode.IsVisible then
Response.Write("<siteMapNode url=""" & ChildNode.Url & """ title=""" & ChildNode.Title & """ description=""" & ChildNode.Title & """ />" & Environment.NewLine)
End if
Next
Response.Write("</siteMapNode>" & Environment.NewLine)
End If
Next
```
however whenever I do, it lists the top level navigation nodes but I cannot get the children to be displayed.
|
I think it has to be an ordered collection. For example,there's [a chart](http://static.springframework.org/spring/docs/2.5.x/reference/validation.html) in the Spring reference that talks about how to reference properties. It says:
>
> account[2] Indicates the third element
> of the indexed property account.
> Indexed properties can be of type
> array, list or other *naturally ordered*
> collection (emphasis theirs)
>
>
>
Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.
|
284,382 |
<p>G'day!</p>
<p>I have one million different words which I'd like to query for in a table with 15 million rows. The result of synonyms together with the word is getting processed after each query.</p>
<p>table looks like this:</p>
<pre><code> synonym word
---------------------
ancient old
anile old
centenarian old
darkened old
distant far
remote far
calm gentle
quite gentle
</code></pre>
<p>This is how it is done in Java currently:</p>
<pre><code>....
PreparedStatement stmt;
ResultSet wordList;
ResultSet syns;
...
stmt = conn.prepareStatement("select distinct word from table");
wordList = stmt.executeQuery();
while (wordList.next()) {
stmt = conn.prepareStatement("select synonym from table where word=?");
stmt.setString(1, wordList.getString(1));
syns = stmt.executeQuery();
process(syns, wordList.getString(1));
}
...
</code></pre>
<p>This is incredible slow. What's the fastest way to do stuff like this?</p>
<p>Cheers,
Chris</p>
|
[
{
"answer_id": 284399,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": true,
"text": "<p>Two ideas:</p>\n\n<p>a) How about making it one query:</p>\n\n<pre><code>select synonym from table where word in (select distinct word from table)\n</code></pre>\n\n<p>b) Or, if you <code>process</code> method needs to deal with them as a set of synonyms of one word, why not sort them by <code>word</code> and start <code>process</code> anew each time <code>word</code> is different? That query would be:</p>\n\n<pre><code>select word, synonym \nfrom table \norder by word\n</code></pre>\n"
},
{
"answer_id": 284413,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>Ensure that there is an index on the 'word' column.</p></li>\n<li><p>Move the second prepareStatement outside the word loop. Each time you create a new statement, the database compiles and optimizes the query - but in this case the query is the same, so this is unnecessary.</p></li>\n<li><p>Combine the statements as <a href=\"https://stackoverflow.com/questions/284382/best-way-to-select-out-of-millions-of-rows-in-an-oracle-db#284399\">sblundy</a> above has done.</p></li>\n</ol>\n"
},
{
"answer_id": 284416,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "<p>Why are you querying the synonyms inside the loop if you're querying all of them anyway? You should use a single <code>select word, synonym from table order by word</code>, and then split by words in the Java code.</p>\n"
},
{
"answer_id": 284424,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "<pre><code>PreparedStatement stmt;\nResultSet syns;\n...\n\nstmt = conn.prepareStatement(\"select distinct \" + \n \" sy.synonm \" + \n \"from \" +\n \" table sy \" +\n \" table wd \" +\n \"where sy.word = wd.word\");\nsyns = stmt.executeQuery();\nprocess(syns);\n</code></pre>\n"
},
{
"answer_id": 284520,
"author": "chris",
"author_id": 36942,
"author_profile": "https://Stackoverflow.com/users/36942",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is solved. The important point is, that the table can be sorted by word. Therefore, I can easily iterate through the whole table. Like this:</p>\n\n<pre><code>....\nStatement stmt;\nResultSet rs;\nString currentWord;\nHashSet<String> syns = new HashSet<String>();\n...\n\nstmt = conn.createStatement();\nrs = stmt.executeQuery(select word, synonym from table order by word);\n\nrs.next();\ncurrentWord = rs.getString(1);\nsyns.add(rs.getString(2));\n\nwhile (rs.next()) {\n if (rs.getString(1) != currentWord) {\n process(syns, currentWord);\n syns.clear();\n currentWord = rs.getString(1);\n }\n syns.add(rs.getString(2));\n}\n...\n</code></pre>\n"
},
{
"answer_id": 285096,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 1,
"selected": false,
"text": "<p>related but unrelated:</p>\n\n<pre><code>while (wordList.next()) {\n stmt = conn.prepareStatement(\"select synonym from table where word=?\");\n stmt.setString(1, wordList.getString(1));\n syns = stmt.executeQuery();\n\n process(syns, wordList.getString(1));\n}\n</code></pre>\n\n<p>You should move that preparestatement call outside the loop:</p>\n\n<pre><code>stmt = conn.prepareStatement(\"select synonym from table where word=?\");\nwhile (wordList.next()) {\n stmt.setString(1, wordList.getString(1));\n syns = stmt.executeQuery();\n\n process(syns, wordList.getString(1));\n}\n</code></pre>\n\n<p>The whole point of preparing a statement is for the db to compile/cache/etc because you're going to use the statement repeatedly. You also may need to clean up your result sets explicitly if you're going to do that many queries, to ensure that you don't run out of cursors.</p>\n"
},
{
"answer_id": 807002,
"author": "user55904",
"author_id": 55904,
"author_profile": "https://Stackoverflow.com/users/55904",
"pm_score": 1,
"selected": false,
"text": "<p>You should also consider utilizing the statement object's setFetchSize method to reduce the context switches between your application and the database. If you know you are going to process a million records, you should use setFetchSize(someRelativelyHighNumberLike1000). This tells java to grab up to 1000 records each time it needs more from Oracle [instead of grabbing them one at a time, which is a worst-case-scenario for this kind of batch processing operation]. This will improve the speed of your program. You should also consider refactoring and doing batch processing of your word/synonyms, as </p>\n\n<ol>\n<li>fetch 1 </li>\n<li>process 1</li>\n<li>repeat</li>\n</ol>\n\n<p>is slower than</p>\n\n<ol>\n<li>fetch 50/100/1000</li>\n<li>process 50/100/1000</li>\n<li>repeat</li>\n</ol>\n\n<p>just hold the 50/100/1000 [or however many you retrieve at once] in some array structure until you process them.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36942/"
] |
G'day!
I have one million different words which I'd like to query for in a table with 15 million rows. The result of synonyms together with the word is getting processed after each query.
table looks like this:
```
synonym word
---------------------
ancient old
anile old
centenarian old
darkened old
distant far
remote far
calm gentle
quite gentle
```
This is how it is done in Java currently:
```
....
PreparedStatement stmt;
ResultSet wordList;
ResultSet syns;
...
stmt = conn.prepareStatement("select distinct word from table");
wordList = stmt.executeQuery();
while (wordList.next()) {
stmt = conn.prepareStatement("select synonym from table where word=?");
stmt.setString(1, wordList.getString(1));
syns = stmt.executeQuery();
process(syns, wordList.getString(1));
}
...
```
This is incredible slow. What's the fastest way to do stuff like this?
Cheers,
Chris
|
Two ideas:
a) How about making it one query:
```
select synonym from table where word in (select distinct word from table)
```
b) Or, if you `process` method needs to deal with them as a set of synonyms of one word, why not sort them by `word` and start `process` anew each time `word` is different? That query would be:
```
select word, synonym
from table
order by word
```
|
284,385 |
<p>I wrote a small PHP application that I'd like to distribute. I'm looking for best practices so that it can be installed on most webhosts with minimal hassle.</p>
<p>Briefly: It's simple tool that lets people download files once they login with a password.</p>
<p>So my questions are:</p>
<p>1) How should I handle configuration values? I'm not using a database, so a configuration file seems appropriate. I know that other php apps (e.g. Wordpress) use defines, but they are global and there is potential that the names will conflict. (Global variables also have the same problem, obviously.) I looked at the "ini" file mechanism built into PHP. It only allows comments at the top - so you can't annotate each setting easily - and you can't validate syntax with "php -f". Other options?</p>
<p>2) How to handle templating? The application needs to pump out a form. Possibly with an error message. (e.g. "Sorry, wrong password.") I've have a class variable with the HTML form, but also allow an external template file to be used instead (specified in the config). I do some trivial search and replace - e.g. %SCRIPT% to the name of the script, %STATUS% to hold the error message. This feels a bit like reinventing the wheel, but including a templating system like Smarty is overkill. (Plus they may already have a templating system.) Other options?</p>
<p>3) i18n - There are only 3 message strings, and gettext doesn't seem to be universally installed. Is it such a bad idea just to make these three strings parameters in the config file?</p>
<p>4) How to best integrate with other frameworks? My app is a single class. So, I thought I could just include a php script that showed how the class was called. It would be a starting point for people who had to integrate it into another framework, but also be fine as-is for those not interested in customizing. Reasonable?</p>
<p>5) GET/POST parameters - Is it bad form for a class to be looking at $_GET and $_POST? Should all values be passed into my class during construction?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 284481,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>Can config be local to class instances? Or could you create a little class that you could create an instance of to query for config values? Also prepending any global vars with you application's name should go some way to stop clashes.</p></li>\n<li><p>If your templating is really simple, just write a short templater. It'll be easier than trying to fend off problems people get with any 3rd party templater. It might also simplify licensing issues. If you start worrying about what they already have, you'll never release anything. There are too many combinations.</p></li>\n<li><p>For 3 strings? Yeah do those the same way you're handling config.</p></li>\n<li><p>Good comments throughout with an intro explaining how you use the class.</p></li>\n<li><p>I don't think so. If it bothers you, you could use default arguments to use given arguments first, then search for GET/POST values if none are provided (though that might be a security risk)</p></li>\n</ol>\n\n<p>There are other things to take into consideration. Lots of people are on shared hosts and as a result, don't have control over their php.ini or their php version. You need to make sure you're only using features that are as commonplace as possible. </p>\n\n<p>One example is that shorttags aren't enabled on some hosts (you have to use <code><?php ... ?></code> and <code><?php echo \"...\"?></code> instead of <code><? ... ?></code> or <code><?= \"...\" ?></code>) which can be a royal PITA.</p>\n"
},
{
"answer_id": 284533,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<h1>Configuration</h1>\n\n<p>You can use a php file like this:</p>\n\n<pre><code><?php\nreturn array(\n 'option1' =&gt; 'foobar',\n 'option2' =&gt; 123,\n //and so on...\n );\n?>\n</code></pre>\n\n<p>And in the main class just use:</p>\n\n<pre><code>$config = (array) include 'path/to/config/file';\n</code></pre>\n\n<p>And if you plan to mostly distribute your class as a component in other applications, then simply put config array/object as a parameter in your class' constructor and leave the details to the user.</p>\n\n<h1>Templating</h1>\n\n<p>For such simple application the method your described should be enough. Remember that one can always extend your class and overload your outputting method with his own.</p>\n\n<h1>I10N</h1>\n\n<p>As mentioned before, for 3 variables anything more than storing them as config is just overkill.</p>\n\n<h1>Integration</h1>\n\n<p>Comment each public method (or even better also protected and private ones) with explanations what do they do and what parameters are needed. If you combine that with an example, it should be enough for most users.</p>\n\n<h1>GET vs POST</h1>\n\n<p>Your class uses passwords and you even think of sending them via GET? ;)\nThink of browser history, referer headers etc - your users' passwords would be visible there.</p>\n"
},
{
"answer_id": 285797,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to Krzysztof's good advice:</p>\n\n<ul>\n<li>Use <code><?php</code> only</li>\n<li>If you use functions that can be disabled, use <code>function_exists()</code> to ensure they're available. <code>@missing_function()</code> makes PHP die silently without any error logged.</li>\n<li>You can't rely on things that can be disabled/changed via <code>php.ini</code>. Use <code>ini_get()</code> to adapt to different settings.</li>\n<li>If <code>magic_quotes</code> are enabled, strip slashes only on from your copy of input – don't modify global arrays! Security of some lame code may rely on these slashes being present.</li>\n<li>Expect that users will mindlessly copy&paste code from your documentation/website.</li>\n</ul>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18158/"
] |
I wrote a small PHP application that I'd like to distribute. I'm looking for best practices so that it can be installed on most webhosts with minimal hassle.
Briefly: It's simple tool that lets people download files once they login with a password.
So my questions are:
1) How should I handle configuration values? I'm not using a database, so a configuration file seems appropriate. I know that other php apps (e.g. Wordpress) use defines, but they are global and there is potential that the names will conflict. (Global variables also have the same problem, obviously.) I looked at the "ini" file mechanism built into PHP. It only allows comments at the top - so you can't annotate each setting easily - and you can't validate syntax with "php -f". Other options?
2) How to handle templating? The application needs to pump out a form. Possibly with an error message. (e.g. "Sorry, wrong password.") I've have a class variable with the HTML form, but also allow an external template file to be used instead (specified in the config). I do some trivial search and replace - e.g. %SCRIPT% to the name of the script, %STATUS% to hold the error message. This feels a bit like reinventing the wheel, but including a templating system like Smarty is overkill. (Plus they may already have a templating system.) Other options?
3) i18n - There are only 3 message strings, and gettext doesn't seem to be universally installed. Is it such a bad idea just to make these three strings parameters in the config file?
4) How to best integrate with other frameworks? My app is a single class. So, I thought I could just include a php script that showed how the class was called. It would be a starting point for people who had to integrate it into another framework, but also be fine as-is for those not interested in customizing. Reasonable?
5) GET/POST parameters - Is it bad form for a class to be looking at $\_GET and $\_POST? Should all values be passed into my class during construction?
Thanks.
|
Configuration
=============
You can use a php file like this:
```
<?php
return array(
'option1' => 'foobar',
'option2' => 123,
//and so on...
);
?>
```
And in the main class just use:
```
$config = (array) include 'path/to/config/file';
```
And if you plan to mostly distribute your class as a component in other applications, then simply put config array/object as a parameter in your class' constructor and leave the details to the user.
Templating
==========
For such simple application the method your described should be enough. Remember that one can always extend your class and overload your outputting method with his own.
I10N
====
As mentioned before, for 3 variables anything more than storing them as config is just overkill.
Integration
===========
Comment each public method (or even better also protected and private ones) with explanations what do they do and what parameters are needed. If you combine that with an example, it should be enough for most users.
GET vs POST
===========
Your class uses passwords and you even think of sending them via GET? ;)
Think of browser history, referer headers etc - your users' passwords would be visible there.
|
284,389 |
<p>I'm using <a href="http://sourceforge.net/projects/nusoap/" rel="nofollow noreferrer">nusoap</a> to connect to a soap webservice. The xml that the class sends to the service is constructed from an array, ie:</p>
<pre><code>$params = array("param1" => "value1", "param2" => "value1");
$client->call('HelloWorld', $params, 'namespace', 'SOAPAction');
</code></pre>
<p>This works fine. A multidimensional array also constructs a nice nested xml message. </p>
<p>I encounter a problem when i need two tags with the same name:</p>
<pre><code><items>
<item>value 1</item>
<item>value 2</item>
</item>
$params = array("items" => array("item" => "value 1", "item" => "value 2"));
</code></pre>
<p>The second item in the array overwrites the first which results in:</p>
<pre><code><items>
<item>value 2</item>
</item>
</code></pre>
<p>How can achieve this?</p>
|
[
{
"answer_id": 284436,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is with the inner array()</p>\n\n<pre><code>$test_array = array(\"item\" => \"value 1\", \"item\" => \"value 2\");\n</code></pre>\n\n<p>creates an array with a single key (\"item\").</p>\n\n<p>Try this and see if it works:</p>\n\n<pre><code>$params = array(\"items\" => array(\"item\" => array(\"value 1\", \"value 2\")));\n</code></pre>\n\n<p>No guarantees, though... I haven't used nusoap in a <strong>long</strong> time and don't have PHP installed here to test it.</p>\n"
},
{
"answer_id": 284492,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "<p>Your core problem is you're writing invalid PHP code</p>\n\n<pre><code>$x = array(\"items\" => array(\"item\" => \"value 1\", \"item\" => \"value 2\")); \nvar_dump($x);\n\narray(1) {\n [\"items\"]=>\n array(1) {\n [\"item\"]=>\n string(7) \"value 2\"\n }\n}\n</code></pre>\n\n<p>Which of course wont work, as its synonymous with </p>\n\n<pre><code> $x = array(); \n $x['items'] = array(); \n $x['items']['item']='value 1'; \n $x['items']['item']='value 2'; \n</code></pre>\n\n<p>which of course won't work. </p>\n\n<p>Your best bets are with</p>\n\n<pre><code> array(\"items\"=>array( \"value1\",\"value2\") ); \n</code></pre>\n\n<p>and hoping the numeric keys will \"work\" \n or </p>\n\n<pre><code> array(\"items\"=>array(\"item\"=>array(\"value1\",\"value2\"))) \n</code></pre>\n\n<p>in the event it is so inclined. </p>\n\n<p><H3>Additionally</h3>\nLooking through the examples on sourceforge, it would appear this is valid syntax: </p>\n\n<pre><code>$params = '<person xsi:type=\"tns:Person\"><firstname xsi:type=\"xsd:string\">Willi</firstname><age xsi:type=\"xsd:int\">22</age><gender xsi:type=\"xsd:string\">male</gender></person>';\n$result = $client->call('hello', $params);\n</code></pre>\n\n<p><a href=\"http://nusoap.cvs.sourceforge.net/viewvc/*checkout*/nusoap/samples/wsdlclient3b.php\" rel=\"nofollow noreferrer\">http://nusoap.cvs.sourceforge.net/viewvc/<em>checkout</em>/nusoap/samples/wsdlclient3b.php</a></p>\n\n<p>This one shows using an un-keyed ( ie: numeric ) array as an input source: \n<a href=\"http://nusoap.cvs.sourceforge.net/viewvc/*checkout*/nusoap/samples/wsdlclient4.php\" rel=\"nofollow noreferrer\">http://nusoap.cvs.sourceforge.net/viewvc/<em>checkout</em>/nusoap/samples/wsdlclient4.php</a></p>\n"
},
{
"answer_id": 406356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This is strange because, method:</p>\n\n<pre><code>$params = array('items' => array('item' => array('value1', 'value2')))\n$client->call( 'action', $params );\n</code></pre>\n\n<p>works form me. As explained \n<a href=\"http://osdir.com/ml/php.nusoap.general/2008-02/msg00015.html\" rel=\"nofollow noreferrer\">in this link</a></p>\n\n<p>Maybe you need newer version of nusoap?</p>\n"
},
{
"answer_id": 9176668,
"author": "harry",
"author_id": 1194696,
"author_profile": "https://Stackoverflow.com/users/1194696",
"pm_score": 1,
"selected": false,
"text": "<p>we have solved this problem by passing string instead of array to nusoap call function.\nplease check link below\n<a href=\"http://fundaa.com/php/solved-duplicate-tags-in-nusoap/\" rel=\"nofollow\">http://fundaa.com/php/solved-duplicate-tags-in-nusoap/</a></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
I'm using [nusoap](http://sourceforge.net/projects/nusoap/) to connect to a soap webservice. The xml that the class sends to the service is constructed from an array, ie:
```
$params = array("param1" => "value1", "param2" => "value1");
$client->call('HelloWorld', $params, 'namespace', 'SOAPAction');
```
This works fine. A multidimensional array also constructs a nice nested xml message.
I encounter a problem when i need two tags with the same name:
```
<items>
<item>value 1</item>
<item>value 2</item>
</item>
$params = array("items" => array("item" => "value 1", "item" => "value 2"));
```
The second item in the array overwrites the first which results in:
```
<items>
<item>value 2</item>
</item>
```
How can achieve this?
|
The problem is with the inner array()
```
$test_array = array("item" => "value 1", "item" => "value 2");
```
creates an array with a single key ("item").
Try this and see if it works:
```
$params = array("items" => array("item" => array("value 1", "value 2")));
```
No guarantees, though... I haven't used nusoap in a **long** time and don't have PHP installed here to test it.
|
284,394 |
<p>I am opening a XML file using .NET XmlReader and saving the file in another filename and it seems that the DOCTYPE declaration changes between the two files. While the newly saved file is still valid XML, I was wondering why it insisted on changing original tags.</p>
<pre><code>Dim oXmlSettings As Xml.XmlReaderSettings = New Xml.XmlReaderSettings()
oXmlSettings.XmlResolver = Nothing
oXmlSettings.CheckCharacters = False
oXmlSettings.ProhibitDtd = False
oXmlSettings.IgnoreWhitespace = True
Dim oXmlDoc As XmlReader = XmlReader.Create(pathToOriginalXml, oXmlSettings)
Dim oDoc As XmlDocument = New XmlDocument()
oDoc.Load(oXmlDoc)
oDoc.Save(pathToNewXml)
</code></pre>
<p>The following (in the original document):</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
</code></pre>
<p>becomes (notice the [ ] characters at the end): </p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"[]>
</code></pre>
|
[
{
"answer_id": 286074,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": true,
"text": "<p>Probably the library parses the DOCTYPE element into an internal structure and then converts the structure back to text. It doesn't store the original string form.</p>\n"
},
{
"answer_id": 1070268,
"author": "Maurice Flanagan",
"author_id": 38791,
"author_profile": "https://Stackoverflow.com/users/38791",
"pm_score": 3,
"selected": false,
"text": "<p>There is a bug in System.Xml when you set XmlDocument.XmlResolver = null. The workaround is to create a custom XmlTextWriter:</p>\n\n<pre><code> private class NullSubsetXmlTextWriter : XmlTextWriter\n {\n public NullSubsetXmlTextWriter(String inputFileName, Encoding encoding)\n : base(inputFileName, encoding)\n {\n }\n public override void WriteDocType(string name, string pubid, string sysid, string subset)\n {\n if (subset == String.Empty)\n {\n subset = null;\n }\n base.WriteDocType(name, pubid, sysid, subset);\n }\n }\n</code></pre>\n\n<p>In your code, create a new NullSubsetXmlTextWriter(pathToNewXml, Encoding.UTF8) and pass that object to the oDoc.Save() method.</p>\n\n<p>Here is the <a href=\"http://www.vistax64.com/net-general/215921-xmldocument-save-null-xmlresolver-modifies-doctype-tag.html\" rel=\"noreferrer\">Microsoft support case</a> where you can read about the workaround (it describes the workaround but doesn't provide the code).</p>\n"
},
{
"answer_id": 58549158,
"author": "parvez",
"author_id": 12271066,
"author_profile": "https://Stackoverflow.com/users/12271066",
"pm_score": 0,
"selected": false,
"text": "<p>This is best solution for you:</p>\n\n<pre><code>writer.WriteDocType(\"Name\", Nothing, \n \"http://xml.cxml.org/schemas/cXML/1.2.033/Fulfill.dtd\", Nothing) \n</code></pre>\n\n<p>If you use <code>Nothing</code> you will not get [] or \"\" etc</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] |
I am opening a XML file using .NET XmlReader and saving the file in another filename and it seems that the DOCTYPE declaration changes between the two files. While the newly saved file is still valid XML, I was wondering why it insisted on changing original tags.
```
Dim oXmlSettings As Xml.XmlReaderSettings = New Xml.XmlReaderSettings()
oXmlSettings.XmlResolver = Nothing
oXmlSettings.CheckCharacters = False
oXmlSettings.ProhibitDtd = False
oXmlSettings.IgnoreWhitespace = True
Dim oXmlDoc As XmlReader = XmlReader.Create(pathToOriginalXml, oXmlSettings)
Dim oDoc As XmlDocument = New XmlDocument()
oDoc.Load(oXmlDoc)
oDoc.Save(pathToNewXml)
```
The following (in the original document):
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
```
becomes (notice the [ ] characters at the end):
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"[]>
```
|
Probably the library parses the DOCTYPE element into an internal structure and then converts the structure back to text. It doesn't store the original string form.
|
284,398 |
<p>i've found how to bind an asp:Menu to XML. i've found how to bind an asp:Menu to a site map (which is really binding it to XML). How do you bind an asp:Menu to a database?</p>
<p>The .NET Framework provides multiple data sources:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.hierarchicaldatasourcecontrol.aspx" rel="noreferrer">HierarchicalDataSourceControl</a></li>
<li><ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.xmldatasource.aspx" rel="noreferrer">XmlDataSource</a></li>
</ul></li>
<li><ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemapdatasource.aspx" rel="noreferrer">SiteMapDataSource</a></li>
</ul></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.datasourcecontrol.aspx" rel="noreferrer">DataSourceControl</a></li>
<li><ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.aspx" rel="noreferrer">SqlDataSource</a></li>
</ul></li>
<li><ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.accessdatasource.aspx" rel="noreferrer">AccessDataSource</a></li>
</ul></li>
<li><ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.aspx" rel="noreferrer">LinqDataSource</a></li>
</ul></li>
</ul>
<p>i want to use one that represents data from an SQL Server table. The data is stored in the standard <a href="http://www.answers.com/hierarchical" rel="noreferrer">hierarchical</a> format that everyone uses:</p>
<pre><code>NodeID ParentNodeID Caption Url
======== ============== ========= =================
{3234... {3632... stackoverflow http://stackov...
{3632... (null) Questions ~/questions.aspx
{3233... (null) Tags ~/tags.aspx
{3235... {3632... google http://www.goo...
</code></pre>
<p>And the query to return all the rows would be:</p>
<pre><code>SELECT * FROM Nodes
</code></pre>
<p>What is the secret method that Microsoft intended me to use to mash that data into an asp:Menu?</p>
<hr>
<p><strong>Update:</strong> There is a good article on aspalliance.com: <a href="http://aspalliance.com/822" rel="noreferrer">Building a Database Driven Hierarchical Menu using ASP.NET 2.0</a>. Unfortunatly it describes how to perform XML data binding; while i'm interested in database binding.</p>
|
[
{
"answer_id": 284410,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "<p>There is a good article on aspalliance.com: <a href=\"http://aspalliance.com/822\" rel=\"noreferrer\"><strong>Building a Database Driven Hierarchical Menu using ASP.NET 2.0</strong></a>. Each step is explained and nicely illustrated.</p>\n\n<p><em>\"In this article, Michael demonstrates how to create a database driven hierarchical menu with only a few lines of code using ASP.NET 2.0. This is a must read tutorial for everyone who needs a professional menu that is powerful and flexible with simplistic design.\"</em></p>\n\n<p>The code for could be:</p>\n\n<pre><code>protected void LoadData()\n{\n DataSet ds = new DataSet();\n string connStr = YOUR_CONNECTION_STRING_HERE;\n using(SqlConnection conn = newSqlConnection(connStr))\n {\n string sql = \"Select NodeID, Caption, Url, ParentID from Menu\";\n SqlDataAdapter da = newSqlDataAdapter(sql, conn);\n da.Fill(ds);\n da.Dispose();\n }\n ds.DataSetName = \"Menus\";\n ds.Tables[0].TableName = \"Menu\";\n DataRelation relation = newDataRelation(\"ParentChild\",\n ds.Tables[\"Menu\"].Columns[\"NodeID\"],\n ds.Tables[\"Menu\"].Columns[\"ParentID\"], true);\n\n relation.Nested = true;\n ds.Relations.Add(relation);\n\n xmlDataSource.Data = ds.GetXml();\n}\n</code></pre>\n"
},
{
"answer_id": 288766,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 3,
"selected": true,
"text": "<p>The menu does not support binding to SqlDataSource because it is a HierarchicalDataBoundControl - only hierarchical datasources are supported. You should implement your own HierarchicalDataSourceControl. Check <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.ihierarchicaldatasource.aspx\" rel=\"nofollow noreferrer\">here</a> for an example. Alternatively you could create a custom sitemap provider and use the SiteMapDataSource as demonstrated <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163657.aspx\" rel=\"nofollow noreferrer\">here</a>. Finally you can use <a href=\"http://demos.telerik.com/aspnet/prometheus/Menu/Examples/Programming/DeclarativeDataSources/DefaultCS.aspx\" rel=\"nofollow noreferrer\">a 3'rd party control</a> which can bind to SqlDataSource.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
i've found how to bind an asp:Menu to XML. i've found how to bind an asp:Menu to a site map (which is really binding it to XML). How do you bind an asp:Menu to a database?
The .NET Framework provides multiple data sources:
* [HierarchicalDataSourceControl](http://msdn.microsoft.com/en-us/library/system.web.ui.hierarchicaldatasourcecontrol.aspx)
* + [XmlDataSource](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.xmldatasource.aspx)
* + [SiteMapDataSource](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemapdatasource.aspx)
* [DataSourceControl](http://msdn.microsoft.com/en-us/library/system.web.ui.datasourcecontrol.aspx)
* + [SqlDataSource](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.aspx)
* + [AccessDataSource](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.accessdatasource.aspx)
* + [LinqDataSource](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.aspx)
i want to use one that represents data from an SQL Server table. The data is stored in the standard [hierarchical](http://www.answers.com/hierarchical) format that everyone uses:
```
NodeID ParentNodeID Caption Url
======== ============== ========= =================
{3234... {3632... stackoverflow http://stackov...
{3632... (null) Questions ~/questions.aspx
{3233... (null) Tags ~/tags.aspx
{3235... {3632... google http://www.goo...
```
And the query to return all the rows would be:
```
SELECT * FROM Nodes
```
What is the secret method that Microsoft intended me to use to mash that data into an asp:Menu?
---
**Update:** There is a good article on aspalliance.com: [Building a Database Driven Hierarchical Menu using ASP.NET 2.0](http://aspalliance.com/822). Unfortunatly it describes how to perform XML data binding; while i'm interested in database binding.
|
The menu does not support binding to SqlDataSource because it is a HierarchicalDataBoundControl - only hierarchical datasources are supported. You should implement your own HierarchicalDataSourceControl. Check [here](http://msdn.microsoft.com/en-us/library/system.web.ui.ihierarchicaldatasource.aspx) for an example. Alternatively you could create a custom sitemap provider and use the SiteMapDataSource as demonstrated [here](http://msdn.microsoft.com/en-us/magazine/cc163657.aspx). Finally you can use [a 3'rd party control](http://demos.telerik.com/aspnet/prometheus/Menu/Examples/Programming/DeclarativeDataSources/DefaultCS.aspx) which can bind to SqlDataSource.
|
284,418 |
<p>I'm using system catalog views such as SYS.ALL_ OBJECTS, SYS.FOREIGN_KEYS etc. to get information about my database structure in MS SQL 2005. </p>
<p>Are there equivalent functions/views for MySQL (v. 5) servers? </p>
|
[
{
"answer_id": 284535,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm, I haven't studied everything it contains, but there's a good deal of information in the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/information-schema.html\" rel=\"nofollow noreferrer\">information_schema</a>. There's also the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show.html\" rel=\"nofollow noreferrer\">show</a> command.</p>\n\n<p>Still, I don't see a single command to show all the foreign keys in there.</p>\n"
},
{
"answer_id": 284589,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 4,
"selected": true,
"text": "<p>For the schema (All objects);</p>\n\n<pre><code>SELECT * FROM information_schema.SCHEMATA S;\n</code></pre>\n\n<p>For constraints and foreign keys also;</p>\n\n<pre><code>SELECT * FROM information_schema.TABLE_CONSTRAINTS T;\n</code></pre>\n\n<p>For everything else check this queries;</p>\n\n<pre><code>SELECT * FROM information_schema.CHARACTER_SETS C;\nSELECT * FROM information_schema.COLLATION_CHARACTER_SET_APPLICABILITY C;\nSELECT * FROM information_schema.COLLATIONS C;\nSELECT * FROM information_schema.COLUMN_PRIVILEGES C;\nSELECT * FROM information_schema.`COLUMNS` C;\nSELECT * FROM information_schema.KEY_COLUMN_USAGE K;\nSELECT * FROM information_schema.PROFILING P;\nSELECT * FROM information_schema.ROUTINES R;\nSELECT * FROM information_schema.SCHEMA_PRIVILEGES S; \nSELECT * FROM information_schema.STATISTICS S;\nSELECT * FROM information_schema.TABLE_PRIVILEGES T;\nSELECT * FROM information_schema.`TABLES` T;\nSELECT * FROM information_schema.TRIGGERS T;\nSELECT * FROM information_schema.USER_PRIVILEGES U;\nSELECT * FROM information_schema.VIEWS V;\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2899/"
] |
I'm using system catalog views such as SYS.ALL\_ OBJECTS, SYS.FOREIGN\_KEYS etc. to get information about my database structure in MS SQL 2005.
Are there equivalent functions/views for MySQL (v. 5) servers?
|
For the schema (All objects);
```
SELECT * FROM information_schema.SCHEMATA S;
```
For constraints and foreign keys also;
```
SELECT * FROM information_schema.TABLE_CONSTRAINTS T;
```
For everything else check this queries;
```
SELECT * FROM information_schema.CHARACTER_SETS C;
SELECT * FROM information_schema.COLLATION_CHARACTER_SET_APPLICABILITY C;
SELECT * FROM information_schema.COLLATIONS C;
SELECT * FROM information_schema.COLUMN_PRIVILEGES C;
SELECT * FROM information_schema.`COLUMNS` C;
SELECT * FROM information_schema.KEY_COLUMN_USAGE K;
SELECT * FROM information_schema.PROFILING P;
SELECT * FROM information_schema.ROUTINES R;
SELECT * FROM information_schema.SCHEMA_PRIVILEGES S;
SELECT * FROM information_schema.STATISTICS S;
SELECT * FROM information_schema.TABLE_PRIVILEGES T;
SELECT * FROM information_schema.`TABLES` T;
SELECT * FROM information_schema.TRIGGERS T;
SELECT * FROM information_schema.USER_PRIVILEGES U;
SELECT * FROM information_schema.VIEWS V;
```
|
284,420 |
<p>I would like to add a backcolor for specific line depending of a Property of the object binded.</p>
<p>The solution I have (and it works) is to use the Event <code>DataBindingComplete</code> but I do not think it's the best solution.</p>
<p>Here is the event:</p>
<pre><code> private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < this.myGrid.Rows.Count; i++)
{
if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
{
this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
}
}
}
</code></pre>
<p>Any other option that would be better?</p>
|
[
{
"answer_id": 284470,
"author": "John",
"author_id": 30006,
"author_profile": "https://Stackoverflow.com/users/30006",
"pm_score": 1,
"selected": false,
"text": "<p>I don't really work with WinForms that much, but in ASP you would use the 'ItemDataBound' method. Is there something similar in windows forms for a DataGrid?</p>\n\n<p>If so, in that method, the event arguments would contain the item that was databound, along with the DataGrid row. So the general code would look something like this (syntax is probably off):</p>\n\n<pre><code>if(((MyObject)e.Item.DataItem).Special)\n e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);\n</code></pre>\n"
},
{
"answer_id": 284672,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 4,
"selected": true,
"text": "<p>You can also attach an event handler to RowPostPaint:</p>\n\n<pre><code>dataGridView1.RowPostPaint += OnRowPostPaint;\n\nvoid OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)\n{\n MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;\n DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;\n\n // Do whatever you want with style and value\n ....\n}\n</code></pre>\n"
},
{
"answer_id": 285272,
"author": "mson",
"author_id": 36902,
"author_profile": "https://Stackoverflow.com/users/36902",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest a few things:</p>\n\n<ul>\n<li>look at modifying your rows at _OnRowDatabound</li>\n<li>Do not set color in your code!!! This would be a big mistake. Use the attributes property and set the cssclass. Wag of the finger to people still doing this.</li>\n</ul>\n\n<p>Let me know if you struggle with the implementation and i'll post a snippet.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
I would like to add a backcolor for specific line depending of a Property of the object binded.
The solution I have (and it works) is to use the Event `DataBindingComplete` but I do not think it's the best solution.
Here is the event:
```
private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < this.myGrid.Rows.Count; i++)
{
if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
{
this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
}
}
}
```
Any other option that would be better?
|
You can also attach an event handler to RowPostPaint:
```
dataGridView1.RowPostPaint += OnRowPostPaint;
void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;
DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;
// Do whatever you want with style and value
....
}
```
|
284,428 |
<p>Objective-C 2.0 gave us @properties.</p>
<ul>
<li>They allow for introspection.</li>
<li>They allow for declarative programming.</li>
<li>The @synthesize and @dynamic mechanisms relieve use from having to write repetitive, stock accessors.</li>
<li>Finally, there is the ‘dot’ property syntax, which some love, and some hate.</li>
</ul>
<p>That isn't what I'm hear to ask. Like any new feature, there is an initially tendency to want to use @property everywhere. So where is property use appropriate?</p>
<p>Clearly in model objects, attributes and relationships are good fodder for properties.</p>
<pre><code>@property(...) NSString *firstName;
@property(...) NSString *lastName;
@property(...) Person *parent;
</code></pre>
<p>Even synthesized/computed attributes seem like a good use case for properties.</p>
<pre><code>@property(...) NSString *fullName;
</code></pre>
<p>Where else have you used properties? Where have you used them, then later decided it was an inappropriate use of the feature?</p>
<p>Do you use properties for your private object attributes?</p>
<p>Can you think of any examples of things which aren't properties in Cocoa, which at first look, seem like they might want to be properties, but after closer inspection, are actual an example of abuse or property-itis?</p>
|
[
{
"answer_id": 284689,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 3,
"selected": false,
"text": "<p>My recommendation to people is to use property's wherever possible. If you are working in a framework, the ability to use non-fragile instance variables in the modern runtime is a huge bonus and if you aren't, properties make it clear how your ivars are to be managed (assigned vs retained vs copied). There isn't an inherent performance loss from declaring a property other than the time it takes to write the line of code (I actually use a TextExpander snippet to do this for me) but the potential for preventing bugs is large enough that it becomes a fantastic best-practice. If you do plan to user properties for private ivars, you can do so inside your implementation file via an <code>@interface</code> block. For example</p>\n\n<pre><code>@interface MyObject()\n\n@property(retain) NSArray *myArray;\n\n@end\n</code></pre>\n"
},
{
"answer_id": 284818,
"author": "benzado",
"author_id": 10947,
"author_profile": "https://Stackoverflow.com/users/10947",
"pm_score": 3,
"selected": false,
"text": "<p>If I had to think of a reason to avoid them, I'd say don't use it for computed attributes where the computation involved is significant. Properties encourage code like:</p>\n\n<pre><code>if (foobar.weight > 100) {\n goober.capacity = foobar.weight;\n}\n</code></pre>\n\n<p>In this example, <code>foobar.weight</code> is called twice. If it's just returning a cached value, no problem. But if it needs to block the thread while it deploys a robot to manually weigh the foobar each time, the above snipped of code would waste two robot deployments when only one is needed.</p>\n\n<p>In such cases, I'd recommend NOT using a property, and also naming the method differently, so that the code would look more like:</p>\n\n<pre><code>int w = [foobar computeWeight];\nif (w > 100) {\n goober.capacity = w;\n}\n</code></pre>\n\n<p>With a name like <code>computeWeight</code> it is easier to remember that it is a long running operation.</p>\n"
},
{
"answer_id": 298767,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 0,
"selected": false,
"text": "<p>I would avoid using properties if the accessor method does something non-obvious to the object, like setting an unrelated instance variable. Also if the property being returned doesn't really \"belong\" to the object. For instance, in one of my projects I have a <code>stringValue</code> method that I decided not to make a property for this reason. This is really more a matter of style though.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Objective-C 2.0 gave us @properties.
* They allow for introspection.
* They allow for declarative programming.
* The @synthesize and @dynamic mechanisms relieve use from having to write repetitive, stock accessors.
* Finally, there is the ‘dot’ property syntax, which some love, and some hate.
That isn't what I'm hear to ask. Like any new feature, there is an initially tendency to want to use @property everywhere. So where is property use appropriate?
Clearly in model objects, attributes and relationships are good fodder for properties.
```
@property(...) NSString *firstName;
@property(...) NSString *lastName;
@property(...) Person *parent;
```
Even synthesized/computed attributes seem like a good use case for properties.
```
@property(...) NSString *fullName;
```
Where else have you used properties? Where have you used them, then later decided it was an inappropriate use of the feature?
Do you use properties for your private object attributes?
Can you think of any examples of things which aren't properties in Cocoa, which at first look, seem like they might want to be properties, but after closer inspection, are actual an example of abuse or property-itis?
|
My recommendation to people is to use property's wherever possible. If you are working in a framework, the ability to use non-fragile instance variables in the modern runtime is a huge bonus and if you aren't, properties make it clear how your ivars are to be managed (assigned vs retained vs copied). There isn't an inherent performance loss from declaring a property other than the time it takes to write the line of code (I actually use a TextExpander snippet to do this for me) but the potential for preventing bugs is large enough that it becomes a fantastic best-practice. If you do plan to user properties for private ivars, you can do so inside your implementation file via an `@interface` block. For example
```
@interface MyObject()
@property(retain) NSArray *myArray;
@end
```
|
284,433 |
<p>The type 'x' is defined in an assembly that is not referenced. You must add a reference to assembly 'abc123'.</p>
<p>I have a .NET 2.0 web application that references my assembly 'abc123'. The assembly exists in the GAC and I've verified that it is the correct(same) version. The rest of application has no issues except for one .aspx page. The page in question has a repeater that displays a user control as one of its "fields". Upon binding a list of type y to the repeater I pass the user control a list of type x (a property of y) as shown here:</p>
<pre><code><uc1:usercontrol id="ucusercontrol " runat="server" myPublicUserControlProperty='<%#Eval("CollectionOfX") %>'/>
</code></pre>
<p>On the user control's property set, I bind the list of type x to a gridview in the user control.</p>
<p>One strange thing to note is that this report works fine on my development pc but not on any servers once I deploy. My pc is Windows XP, IIS6, VS2005. The servers are Windows Server 2003, IIS6.</p>
<p>I hope I explained that well enough. Thanks in advance for any insight you can provide.</p>
|
[
{
"answer_id": 284494,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 2,
"selected": false,
"text": "<p>When troubleshooting these types of problems, the <a href=\"http://msdn.microsoft.com/en-us/library/e74a18c4(VS.71).aspx\" rel=\"nofollow noreferrer\">Fusion Log Viewer</a> has always been a great help.</p>\n"
},
{
"answer_id": 285059,
"author": "Aaron Daniels",
"author_id": 37064,
"author_profile": "https://Stackoverflow.com/users/37064",
"pm_score": 6,
"selected": true,
"text": "<p>I'm Mike's coworker, and we worked out a solution.</p>\n\n<p>The type X is defined in his assembly, that is only in the GAC. Even though his ASP.NET web appplication did have a reference, it was failing to load from the GAC only for this UserControl. The rest of the application worked as expected. We confirmed the failed loading by placing a copy of the assembly in the bin directory, and everything worked. We removed the assembly, and the problem came back. </p>\n\n<p>Our solution was to manually add an entry to the web.config in the assemblies section to point ASP.NET to the GAC. </p>\n\n<p>It looks like any time you reference a type in the page (not the code-behind), you need the assembly information defined in the web.config file or in a page directive.</p>\n\n<pre><code><assemblies>\n <add assembly=\"MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[MyPublicKeyToken]\"/> \n</assemblies>\n</code></pre>\n"
},
{
"answer_id": 539682,
"author": "Tom Lianza",
"author_id": 26624,
"author_profile": "https://Stackoverflow.com/users/26624",
"pm_score": 2,
"selected": false,
"text": "<p>There's also a bug that can manifest itself with similar symptoms, described <a href=\"http://codebetter.com/brendantompkins/2006/11/15/fix-for-asp-net-could-not-load-file-or-assembly-app_web-error/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>The workaround is to delete everything in the C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files\\ directory, and it only seems to manifest itself in debug mode.</p>\n"
},
{
"answer_id": 5017139,
"author": "Dan",
"author_id": 619732,
"author_profile": "https://Stackoverflow.com/users/619732",
"pm_score": 0,
"selected": false,
"text": "<p>I had the exact same error, but I had a <strong>public</strong> constructor in my class that used as a parameter, an object from another project.</p>\n\n<p>I resolved the problem by making that constructor internal.</p>\n"
},
{
"answer_id": 5215052,
"author": "Lav G",
"author_id": 184347,
"author_profile": "https://Stackoverflow.com/users/184347",
"pm_score": 0,
"selected": false,
"text": "<p>More often than not, it is because of the cached assemblies. One way resolve this issue is by making the \"strong reference\" in the proj or config file. Refer this blog <a href=\"http://lavbox.blogspot.com/2011/03/type-systemxmlixmllineinfo-is-defined.html\" rel=\"nofollow\">post</a></p>\n"
},
{
"answer_id": 9532190,
"author": "Charbarred",
"author_id": 1223918,
"author_profile": "https://Stackoverflow.com/users/1223918",
"pm_score": 1,
"selected": false,
"text": "<p>I found that if <code>type x</code> is actually a class in your <code>App_Code</code>, dirtying it and re-saving often forces the web app to recompile and solves the problem.</p>\n"
},
{
"answer_id": 50205638,
"author": "Max Izrin",
"author_id": 3249250,
"author_profile": "https://Stackoverflow.com/users/3249250",
"pm_score": 0,
"selected": false,
"text": "<p>For me it was a version control pull problem. </p>\n\n<p>In Visual studio, open \"References\" in your Solution explorer, and scroll through it. </p>\n\n<p>If anything has a yellow warning triangle on it, remember the name, remove it, and add it back again (or have ReSharper do it for you). </p>\n\n<p>Happened to me several times after pulling a project when a co-worker added a new package and references.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36970/"
] |
The type 'x' is defined in an assembly that is not referenced. You must add a reference to assembly 'abc123'.
I have a .NET 2.0 web application that references my assembly 'abc123'. The assembly exists in the GAC and I've verified that it is the correct(same) version. The rest of application has no issues except for one .aspx page. The page in question has a repeater that displays a user control as one of its "fields". Upon binding a list of type y to the repeater I pass the user control a list of type x (a property of y) as shown here:
```
<uc1:usercontrol id="ucusercontrol " runat="server" myPublicUserControlProperty='<%#Eval("CollectionOfX") %>'/>
```
On the user control's property set, I bind the list of type x to a gridview in the user control.
One strange thing to note is that this report works fine on my development pc but not on any servers once I deploy. My pc is Windows XP, IIS6, VS2005. The servers are Windows Server 2003, IIS6.
I hope I explained that well enough. Thanks in advance for any insight you can provide.
|
I'm Mike's coworker, and we worked out a solution.
The type X is defined in his assembly, that is only in the GAC. Even though his ASP.NET web appplication did have a reference, it was failing to load from the GAC only for this UserControl. The rest of the application worked as expected. We confirmed the failed loading by placing a copy of the assembly in the bin directory, and everything worked. We removed the assembly, and the problem came back.
Our solution was to manually add an entry to the web.config in the assemblies section to point ASP.NET to the GAC.
It looks like any time you reference a type in the page (not the code-behind), you need the assembly information defined in the web.config file or in a page directive.
```
<assemblies>
<add assembly="MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[MyPublicKeyToken]"/>
</assemblies>
```
|
284,468 |
<p>How come the following doesn't work?</p>
<pre><code>CREATE FUNCTION Test (@top integer)
RETURNS TABLE
AS
RETURN
SELECT TOP @top * FROM SomeTable
GO
</code></pre>
<p>I just want to be able to be able to specify the number of results to be returned. [SQL Server 2000.]</p>
<p>Thanks!</p>
|
[
{
"answer_id": 284487,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Support for this was added to SQL Server 2005, but it's not available in 2000. You'd have to use (shudder) dynamic sql or some other number trick instead.</p>\n"
},
{
"answer_id": 284501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>CREATE FUNCTION Test (@top integer)</p>\n\n<p>RETURNS TABLE</p>\n\n<p>AS</p>\n\n<p>RETURN </p>\n\n<p>SELECT TOP (@top) * FROM SomeTable</p>\n\n<p>GO</p>\n\n<p>However without an ORDER BY clause it is not very meaningful (the order of the results is not guaranteed).</p>\n"
},
{
"answer_id": 284509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Oops a variable TOP is not available in SQL Server 2000. Nor is Dynamic SQL supported in any version.</p>\n"
},
{
"answer_id": 284561,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>For MS SQL 2000, you can use:</p>\n\n<pre><code>CREATE FUNCTION Test (@top integer)\n\nRETURNS TABLE\n\nAS\n\nSET ROWCOUNT @top\n\nRETURN SELECT * FROM SomeTable\n</code></pre>\n"
},
{
"answer_id": 284563,
"author": "Jason Slocomb",
"author_id": 34895,
"author_profile": "https://Stackoverflow.com/users/34895",
"pm_score": 0,
"selected": false,
"text": "<p>Jake, try setting the rowcount to your function parameter and then doing your select. I have not tried this, YMMV.</p>\n\n<p><em>From: <a href=\"http://msdn.microsoft.com/en-us/library/aa259189(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa259189(SQL.80).aspx</a></em></p>\n\n<p>Syntax</p>\n\n<pre><code>SET ROWCOUNT { number | @number_var }\nArguments\n\nnumber | @number_var\n</code></pre>\n\n<p>Is the number (an integer) of rows to be processed before stopping the given query.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
How come the following doesn't work?
```
CREATE FUNCTION Test (@top integer)
RETURNS TABLE
AS
RETURN
SELECT TOP @top * FROM SomeTable
GO
```
I just want to be able to be able to specify the number of results to be returned. [SQL Server 2000.]
Thanks!
|
For MS SQL 2000, you can use:
```
CREATE FUNCTION Test (@top integer)
RETURNS TABLE
AS
SET ROWCOUNT @top
RETURN SELECT * FROM SomeTable
```
|
284,472 |
<p>I have a base page, BasePage, that raises an event that displays messages to the user. Works great on all pages derived from BasePage. I want to do the same thing from user controls, but they don't inherit from BasePage. </p>
<p>What I want is a central place that I can call from anywhere and in that code it will raise an event. Where is a good place to put this code:</p>
<pre><code> public void DisplayMessage(string message)
{
RaiseEvent(new MessageNotificationEventArgs(MessageNotificationEvent, message));
}
</code></pre>
<p>so that I can call it from anywhere? RaiseEvent is in the UIElement class, so it needs to go somewhere that is a UIElement.</p>
|
[
{
"answer_id": 284487,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Support for this was added to SQL Server 2005, but it's not available in 2000. You'd have to use (shudder) dynamic sql or some other number trick instead.</p>\n"
},
{
"answer_id": 284501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>CREATE FUNCTION Test (@top integer)</p>\n\n<p>RETURNS TABLE</p>\n\n<p>AS</p>\n\n<p>RETURN </p>\n\n<p>SELECT TOP (@top) * FROM SomeTable</p>\n\n<p>GO</p>\n\n<p>However without an ORDER BY clause it is not very meaningful (the order of the results is not guaranteed).</p>\n"
},
{
"answer_id": 284509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Oops a variable TOP is not available in SQL Server 2000. Nor is Dynamic SQL supported in any version.</p>\n"
},
{
"answer_id": 284561,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>For MS SQL 2000, you can use:</p>\n\n<pre><code>CREATE FUNCTION Test (@top integer)\n\nRETURNS TABLE\n\nAS\n\nSET ROWCOUNT @top\n\nRETURN SELECT * FROM SomeTable\n</code></pre>\n"
},
{
"answer_id": 284563,
"author": "Jason Slocomb",
"author_id": 34895,
"author_profile": "https://Stackoverflow.com/users/34895",
"pm_score": 0,
"selected": false,
"text": "<p>Jake, try setting the rowcount to your function parameter and then doing your select. I have not tried this, YMMV.</p>\n\n<p><em>From: <a href=\"http://msdn.microsoft.com/en-us/library/aa259189(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa259189(SQL.80).aspx</a></em></p>\n\n<p>Syntax</p>\n\n<pre><code>SET ROWCOUNT { number | @number_var }\nArguments\n\nnumber | @number_var\n</code></pre>\n\n<p>Is the number (an integer) of rows to be processed before stopping the given query.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
I have a base page, BasePage, that raises an event that displays messages to the user. Works great on all pages derived from BasePage. I want to do the same thing from user controls, but they don't inherit from BasePage.
What I want is a central place that I can call from anywhere and in that code it will raise an event. Where is a good place to put this code:
```
public void DisplayMessage(string message)
{
RaiseEvent(new MessageNotificationEventArgs(MessageNotificationEvent, message));
}
```
so that I can call it from anywhere? RaiseEvent is in the UIElement class, so it needs to go somewhere that is a UIElement.
|
For MS SQL 2000, you can use:
```
CREATE FUNCTION Test (@top integer)
RETURNS TABLE
AS
SET ROWCOUNT @top
RETURN SELECT * FROM SomeTable
```
|
284,500 |
<p>So here's my current code:</p>
<pre><code>List<string> rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value);
bool found = false;
System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
foreach (string group in rowGroups)
{
if (p.IsInRole(group))
{
found = true;
break;
}
}
</code></pre>
<p>This was done a couple of months ago by someone and I'm having difficulty grasping why its not working. The company has recently just moved from one domain name to another. So I was curious to what domain controller the p.IsInRole("String") function will use. I'm assuming its going to use the default DC by whatever the computer is using.</p>
<p>The odd item is that the computers in the office where this is running could be on 2 seperate domains. In the <code>List<string></code> object, i've got both domains possible. so it could contain items such as "domainA\groupA", "domainA\userB", domainB\groupC", and/or "domainB\userD".</p>
<p>So my major problem is that the IsInRole function is never returning true. i know it should, i even tested it with domainA\Domain users and still get a false returned.</p>
<p>Any ideas? changing the code is possible, but not wanted. i'm not 100% i can even compile it...</p>
|
[
{
"answer_id": 284504,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "<p>Static classes exist once per application domain. In your case, it would depend on whether the adapter is using multiple threads in the same application domain (thus sharing a single instance of the static class) or using multiple processes (thus having separate instances of the static class).</p>\n"
},
{
"answer_id": 284505,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (<code>Monitor</code> or <code>lock</code> your properties).</p>\n\n<p>However, multiple <em>processes</em> should be in separate AppDomains and therefore each have their own instance.</p>\n"
},
{
"answer_id": 284507,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 2,
"selected": false,
"text": "<p>The scope of a static class is limited to the application domain. Each app domain will have its own copy of any static variables you might have. If your \"processes\" are threads within the same app domain, then they will share the static values. But if they are actual separate Windows processes, then they will have different app domains and hence separate copies. </p>\n"
},
{
"answer_id": 284508,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 3,
"selected": false,
"text": "<p><em>\"I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same \"instance\" of that class?\"</em></p>\n\n<p>No, they all have separate instances.</p>\n\n<p><em>\"Since the processes are separate, would these be running under difference Application Domains, hence have the static \"instances\" separate?\"</em></p>\n\n<p>Yes.</p>\n"
},
{
"answer_id": 285324,
"author": "mson",
"author_id": 36902,
"author_profile": "https://Stackoverflow.com/users/36902",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to look at the Singleton pattern. The gist seems to be you want to control the number of service instances. </p>\n\n<p>I'm guessing that you want a separate dll/project servicing all the client requests. You could use static class/singleton/multiton to implement the desired functionality. It really depends on what you are trying to accomplish.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
So here's my current code:
```
List<string> rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value);
bool found = false;
System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
foreach (string group in rowGroups)
{
if (p.IsInRole(group))
{
found = true;
break;
}
}
```
This was done a couple of months ago by someone and I'm having difficulty grasping why its not working. The company has recently just moved from one domain name to another. So I was curious to what domain controller the p.IsInRole("String") function will use. I'm assuming its going to use the default DC by whatever the computer is using.
The odd item is that the computers in the office where this is running could be on 2 seperate domains. In the `List<string>` object, i've got both domains possible. so it could contain items such as "domainA\groupA", "domainA\userB", domainB\groupC", and/or "domainB\userD".
So my major problem is that the IsInRole function is never returning true. i know it should, i even tested it with domainA\Domain users and still get a false returned.
Any ideas? changing the code is possible, but not wanted. i'm not 100% i can even compile it...
|
Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (`Monitor` or `lock` your properties).
However, multiple *processes* should be in separate AppDomains and therefore each have their own instance.
|
284,511 |
<p>When trying to invoke a method on an external webservice (over the Internet) it throws me
"The remote server returned an error: (407) Proxy Authentication Required."</p>
<p>To solve this, I used the following code to set the proxy we use in the office:</p>
<pre><code>//Set the system proxy with valid server address or IP and port.
System.Net.WebProxy pry = new System.Net.WebProxy("MyHost", 8080);
//The DefaultCredentials automically get username and password.
pry.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Net.WebRequest.DefaultWebProxy = pry;
</code></pre>
<p>That works fine, but now... I need to do that "less harcoded" trying to get the information from my system instead of setting that manually. </p>
|
[
{
"answer_id": 284527,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 0,
"selected": false,
"text": "<p>System.Net.WebProxy.GetDefaultProxy() although VS cautions its been deprecated.</p>\n"
},
{
"answer_id": 284544,
"author": "John",
"author_id": 30006,
"author_profile": "https://Stackoverflow.com/users/30006",
"pm_score": 2,
"selected": true,
"text": "<p>This will use whatever the default proxy is for IE I believe (not deprecated):</p>\n\n<pre><code>Services.MyService service = new Services.MyService();\nservice.UseDefaultCredentials = true;\nservice.Proxy = new System.Net.WebProxy();\nservice.Proxy.Credentials = service.Credentials;\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720/"
] |
When trying to invoke a method on an external webservice (over the Internet) it throws me
"The remote server returned an error: (407) Proxy Authentication Required."
To solve this, I used the following code to set the proxy we use in the office:
```
//Set the system proxy with valid server address or IP and port.
System.Net.WebProxy pry = new System.Net.WebProxy("MyHost", 8080);
//The DefaultCredentials automically get username and password.
pry.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Net.WebRequest.DefaultWebProxy = pry;
```
That works fine, but now... I need to do that "less harcoded" trying to get the information from my system instead of setting that manually.
|
This will use whatever the default proxy is for IE I believe (not deprecated):
```
Services.MyService service = new Services.MyService();
service.UseDefaultCredentials = true;
service.Proxy = new System.Net.WebProxy();
service.Proxy.Credentials = service.Credentials;
```
|
284,519 |
<p>I am trying to store a large amount of boolean information that is determined at run-time. I was wondering what the best method might be.</p>
<p>I have currently been trying to allocate the memory using: </p>
<p><code>pStatus = malloc((<number of data points>/8) + 1);</code> </p>
<p>thinking that this will give me enough bits to work with. I could then reference each boolean value using the pointer in array notation:</p>
<p><code>pStatus[element]</code></p>
<p>Unfortunately this does not seem to be working very well. First, I am having difficulty initializing the memory to the integer value <code>0</code>. Can this be done using <code>memset()</code>? Still, I don't think that is impacting why I crash when trying to access <code>pStatus[element]</code>. </p>
<p>I am also not entirely convinced that this approach is the best one to be using. What I really want is essentially a giant bitmask that reflects the status of the boolean values. Have I missed something?</p>
|
[
{
"answer_id": 284534,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>pStatus[element] does not address the bit. The exact byte it gets is dependent on the type of pStatus -- I assume char* or equivalent -- so pStatus[element] gets you the element'th byte.</p>\n\n<p>You could memset to set to 0, yes.</p>\n"
},
{
"answer_id": 284536,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 3,
"selected": false,
"text": "<p><em>...thinking that this will give me enough bits to work with. I could then reference each boolean value using the pointer in array notation:</em></p>\n\n<pre><code>pStatus[element]\n</code></pre>\n\n<p>element is addressing <em>bytes</em>, not bits. You want something like:</p>\n\n<pre><code>pStatus[element/8] & (1 << (element % 8))\n</code></pre>\n"
},
{
"answer_id": 284541,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<pre><code> pStatus = malloc((<number of data points>/8) + 1);\n</code></pre>\n\n<p>That part's fine.</p>\n\n<pre><code> pStatus[element]\n</code></pre>\n\n<p>here's where you have trouble. You are address bytes, when you want to address bits.</p>\n\n<pre><code> pStatus[element / 8 ] \n</code></pre>\n\n<p>will get you the right byte in the array.</p>\n"
},
{
"answer_id": 284542,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 2,
"selected": false,
"text": "<p>Well, the simplest answer would be to use calloc instead of malloc.</p>\n\n<p>It is defined to initialize the memory it allocates to zero, and can often do it by using page mapping tricks.</p>\n\n<p>That will take care of your memory initialization problem. The other dozen posts here seem to adequately address the indexing problem and the fact that you occasionally allocate an extra byte (oh the horror!), so I won't repeat their content here.</p>\n"
},
{
"answer_id": 284547,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>pStatus[element] will give you an entire byte at that address.</p>\n\n<p>To set a particular element you would do something like:</p>\n\n<pre><code>pStatus[element >> 3] |= 1 << (element & 7);\n</code></pre>\n\n<p>To reset an element:</p>\n\n<pre><code>pStatus[element >> 3] &= ~1 << (element & 7);\n</code></pre>\n\n<p>and to test an element:</p>\n\n<pre><code>if (pStatus[element >> 3] & (1 << (element & 7)) != 0)\n</code></pre>\n\n<p>the initial allocation should be</p>\n\n<pre><code>pstatus = malloc((<number of data points> + 7) / 8)\n</code></pre>\n\n<p>what you had will work but wastes a byte occasionally</p>\n"
},
{
"answer_id": 284548,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 6,
"selected": true,
"text": "<pre><code>pStatus = malloc((<number of data points>/8) + 1);\n</code></pre>\n\n<p>This does allocate enough bytes for your bits. However,</p>\n\n<pre><code>pStatus[element]\n</code></pre>\n\n<p>This accesses the element'th <em>byte</em>, not bit. So when element is more than one-eighth of the total number of bits, you're accessing off the end of the array allocated.</p>\n\n<p>I would define a few helper functions</p>\n\n<pre><code>int get_bit(int element)\n{\n uint byte_index = element/8;\n uint bit_index = element % 8;\n uint bit_mask = ( 1 << bit_index);\n\n return ((pStatus[byte_index] & bit_mask) != 0);\n}\n\nvoid set_bit (int element)\n{\n uint byte_index = element/8;\n uint bit_index = element % 8;\n uint bit_mask = ( 1 << bit_index);\n\n pStatus[byte_index] |= bit_mask);\n}\n\nvoid clear_bit (int element)\n{\n uint byte_index = element/8;\n uint bit_index = element % 8;\n uint bit_mask = ( 1 << bit_index);\n\n pStatus[byte_index] &= ~bit_mask;\n}\n</code></pre>\n\n<p>(error checking on range of element left out for clarity. You could make this macros, too)</p>\n"
},
{
"answer_id": 284550,
"author": "Rhythmic Fistman",
"author_id": 22147,
"author_profile": "https://Stackoverflow.com/users/22147",
"pm_score": 0,
"selected": false,
"text": "<p>You need to allocate <code>c = malloc((N+7)/8)</code> bytes, and you can set the nth with</p>\n\n<pre><code> c[n/8]=((c[n/8] & ~(0x80 >> (n%8))) | (0x80>>(n%8)));\n</code></pre>\n\n<p>clear with</p>\n\n<pre><code> c[n/8] &= ~(0x80 >> (n%8));\n</code></pre>\n\n<p>and test with</p>\n\n<pre><code> if(c[n/8] & (0x80 >> (n%8))) blah();\n</code></pre>\n"
},
{
"answer_id": 284559,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": -1,
"selected": false,
"text": "<p>You allocation code is correct, see the <code>set_bit()</code> and <code>get_bit()</code> functions given in <a href=\"https://stackoverflow.com/questions/177054/is-there-a-practical-limit-to-the-size-of-bit-masks#177092\">this answer</a> to access the boolean. </p>\n"
},
{
"answer_id": 284596,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "<p>Make yourself happier and define a type and functions to operate on that type. That way if you discover that bit accesses are too slow, you can change the unit of memory per boolean to a byte/word/long or adopt sparse/dynamic data structures if memory is really an issue (ie, if your sets are mostly zeros, you could just keep a list with the coordinates of the 1's.</p>\n\n<p>You can write your code to be completely immune to changes to the implementation of your bit vector.</p>\n"
},
{
"answer_id": 284658,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": -1,
"selected": false,
"text": "<p>The boolean is \"never\" a separate value in C. So a struct might be in order to get you going.</p>\n\n<p>It is true that you do not initialize the mem area so you need to do that individually.</p>\n\n<p>Here is a simple example of how you could do it with unions structs and enums</p>\n\n<pre><code>typedef unsigned char BYTE;\ntypedef unsigned short WORD;\ntypedef unsigned long int DWORD;\ntypedef unsigned long long int DDWORD;\nenum STATUS\n{\n status0 = 0x01,\n status1 = 0x02,\n status2 = 0x04,\n status3 = 0x08,\n status4 = 0x10,\n status5 = 0x20,\n status6 = 0x40,\n status7 = 0x80,\nstatus_group = status0 + status1 +status4\n};\n#define GET_STATUS( S ) ( ((status.DDBuf&(DDWORD)S)==(DDWORD)S) ? 1 : 0 )\n#define SET_STATUS( S ) ( (status.DDBuf|= (DDWORD)S) )\n#define CLR_STATUS( S ) ( (status.DDBuf&= ~(DDWORD)S) )\nstatic union {\n BYTE BBuf[8];\n WORD WWBuf[4];\n DWORD DWBuf[2];\n DDWORD DDBuf;\n}status;\n\nint main(void)\n{\n // Reset status bits\n status.BBuf[0] = 0;\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n\n SET_STATUS( status0 );\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n\n CLR_STATUS(status0);\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n SET_STATUS( status_group );\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n system( \"pause\" );\n return 0;\n}\n</code></pre>\n\n<p>Hope this helps. This example can handle up until 64 status booleans and could be easy extended.</p>\n\n<p>This exapmle is based on Char = 8 bits int = 16 bits long int = 32 bits and long long int = 64 bits</p>\n\n<p>I have now also added support for status groups.</p>\n"
},
{
"answer_id": 284674,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't mind having to write wrappers, you could also use either bit_set or bit_vector from C++'s STL, seems like they (especially the latter) have exactly what you need, already coded, tested and packaged (and plenty of bells and whistles).</p>\n\n<p>It's a real shame we lack a straight forward way to use C++ code in C applications (no, creating a wrapper isn't straight-forward to me, nor fun, and means more work in the long term).</p>\n"
},
{
"answer_id": 286567,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": -1,
"selected": false,
"text": "<p>If you are limited to just a few bits you can instead of eaanon01 solution also use the c builtin facility of bitfield (there are very few occasion where you could use them, but this would be one)</p>\n\n<p>For this bit banging stuff I can recommendate:\nHerny Warrens \"Hacker Delight\"</p>\n"
},
{
"answer_id": 287442,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>I can't help but notice that all replies in C here seem to assume that a byte is 8 bits. This is not necessarily true in C (although it will of course be true on most mainstream hardware), so making this assumption in code is rather bad form.</p>\n\n<p>The proper way to write architecture-neutral code is to</p>\n\n<pre><code>#include <limits.h>\n</code></pre>\n\n<p>and then use the <code>CHAR_BIT</code> macro wherever you need \"the number of bits in a <code>char</code>\".</p>\n"
},
{
"answer_id": 287514,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 3,
"selected": false,
"text": "<p>Small point: to get enough memory to store N bits, (N/8) + 1 bytes is imprecise (can be one too many).</p>\n\n<p>(N+7)/8 is always the minimum number, though.</p>\n"
},
{
"answer_id": 307177,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 0,
"selected": false,
"text": "<p>What would be wrong with <code>std::vector<bool></code>?</p>\n"
},
{
"answer_id": 817764,
"author": "tpdi",
"author_id": 85931,
"author_profile": "https://Stackoverflow.com/users/85931",
"pm_score": 0,
"selected": false,
"text": "<p>It amazes me that only one answer here mentions CHAR_BIT. A byte is often 8 bits, but not always.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35767/"
] |
I am trying to store a large amount of boolean information that is determined at run-time. I was wondering what the best method might be.
I have currently been trying to allocate the memory using:
`pStatus = malloc((<number of data points>/8) + 1);`
thinking that this will give me enough bits to work with. I could then reference each boolean value using the pointer in array notation:
`pStatus[element]`
Unfortunately this does not seem to be working very well. First, I am having difficulty initializing the memory to the integer value `0`. Can this be done using `memset()`? Still, I don't think that is impacting why I crash when trying to access `pStatus[element]`.
I am also not entirely convinced that this approach is the best one to be using. What I really want is essentially a giant bitmask that reflects the status of the boolean values. Have I missed something?
|
```
pStatus = malloc((<number of data points>/8) + 1);
```
This does allocate enough bytes for your bits. However,
```
pStatus[element]
```
This accesses the element'th *byte*, not bit. So when element is more than one-eighth of the total number of bits, you're accessing off the end of the array allocated.
I would define a few helper functions
```
int get_bit(int element)
{
uint byte_index = element/8;
uint bit_index = element % 8;
uint bit_mask = ( 1 << bit_index);
return ((pStatus[byte_index] & bit_mask) != 0);
}
void set_bit (int element)
{
uint byte_index = element/8;
uint bit_index = element % 8;
uint bit_mask = ( 1 << bit_index);
pStatus[byte_index] |= bit_mask);
}
void clear_bit (int element)
{
uint byte_index = element/8;
uint bit_index = element % 8;
uint bit_mask = ( 1 << bit_index);
pStatus[byte_index] &= ~bit_mask;
}
```
(error checking on range of element left out for clarity. You could make this macros, too)
|
284,530 |
<p>I am a newbie at Flex, and I don't like the way you have to write the namespace mx: for every control declaration you write. It makes the code cluttery. I would like to write:</p>
<pre><code><Panel ...
</code></pre>
<p>rather than</p>
<pre><code><mx:Panel ...
</code></pre>
<p>I tried writing</p>
<pre><code>xmlns="http://www.adobe.com/2006/mxml"
</code></pre>
<p>for the top level element instead of </p>
<pre><code>xmlns:mx="http://www.adobe.com/2006/mxml"
</code></pre>
<p>In the top level declaration. This work to an extent, but broke some existing code. For one, XML data that are defined in the document are all appended with aaa: as the namespace during runtime. I've also noticed other issues in my very small sample program.</p>
<p>Is there a way to do this that works, or is this a lost cause? And some background information on why would be appreciated.</p>
<p><em>Update: Thanks all for the replies, but I would like to have heard from someone who actually tried this and thought it was important. Although most of you told me it was a bad idea, I was not discouraged. I got a couple of programs working this way smoothly now. And plan to do this in all my flex apps. One trick seemed to work for me although I can't claim it'll work universally. If you need separate namespaces within your doc, take, HTTPService parameters for example, you could create a namespace within that element like so:</em></p>
<pre>
<HTTPService id="service" url="http://blah.com"
method="POST" result="gotResult(event)">
<request xmlns:p="*">
<p:param1>p1</p:param1>
<p:param2>p2</p:param2>
</request>
</HTTPService>
</pre>
<p><em>Hope this helps someone. I am very happy with how clean my code is now, almost as clean as a normal html file. As for people who think writing mx: throughout your code is clearer and what not, I disagree completely. I think languages that require you to repeat the same character sequence excessively in your code - which you should consider a document - have design flaws. Here's an analogy for you: how would you like it if you were reading an article on Barack Obama, and every single sentence contained the words 'Barack Obama', that would get pretty tiresome wouldn't it?</em></p>
|
[
{
"answer_id": 284639,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 2,
"selected": false,
"text": "<p>You need the mx or some xmls:[SOMETHING HERE] because that's the XML namespace that refers to the definition of the controls. It's like using namespaces in normal code.</p>\n\n<p>Just writing Panel is ambiguous and could possibly conflict with another person's implementation of Panel. So we declare to Flex what namespace Panel belongs to (<a href=\"http://www.adobe.com/2006/mxml\" rel=\"nofollow noreferrer\">http://www.adobe.com/2006/mxml</a>) and we alias it with mx. </p>\n\n<p>Microsoft's WPF XAML requires this as well.</p>\n"
},
{
"answer_id": 284648,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 3,
"selected": false,
"text": "<p>I think that removing the mx namespace will almost certainly cause you trouble with name conflicts as your project gets larger.</p>\n\n<p>Personally I think the mx namespace makes the code clearer rather than more cluttered, especially if you have component based flex development or a lot of your own controls. Having owned a large flex code base for the last two years I find the mx namespace unobtrusive, especially when you have custom objects embedded inline such as item renderers.</p>\n\n<p>My recommendation (unscientifically asserted) is to put up with it, especially if you are finding issues when removing it. I bet you'll stop noticing it after a while.</p>\n"
},
{
"answer_id": 288937,
"author": "Paul Mignard",
"author_id": 3435,
"author_profile": "https://Stackoverflow.com/users/3435",
"pm_score": 2,
"selected": false,
"text": "<p>Just to be the voice of dissension...</p>\n\n<p>In digging through <a href=\"http://www.quietlyscheming.com/blog/\" rel=\"nofollow noreferrer\">Ely Greenfields</a> code he does that a lot - I'm not sure if the other developers on the Flex SDK team do that but it does lend some credence to the argument for doing it...right? </p>\n"
},
{
"answer_id": 303331,
"author": "Ryan Guill",
"author_id": 7186,
"author_profile": "https://Stackoverflow.com/users/7186",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with the majority of other answers here, it is best to leave it. Eventually you will be wanting to use other namespaces for things such as custom components and you will need a namespace then for making the distinction. Then you will have some with a namespace and some without. </p>\n\n<p>I would say if for no other reason, you should leave it because someday someone else might have to look at your code and they are probably going to find it much more readable with the mx than without. </p>\n"
},
{
"answer_id": 814796,
"author": "Aethex",
"author_id": 99012,
"author_profile": "https://Stackoverflow.com/users/99012",
"pm_score": 0,
"selected": false,
"text": "<p>The mx: is just a way to tell Flex that the Panel (along with any other component) is a part of the Flex framework, that it, built-in in Flex. This helps Flex to know where to look for the Panel, and will make your compiling process faster.</p>\n\n<p>You can also use local: to access components that YOU created. Example: If I want to add some functionality to my Panel, I would type some code, and save it as a customized Panel, dubbed MyPanel. Them, I can use to tell Flex that MyPanel is my component, and it can find if somewhere in my project. Of course, you can name it anything you want :-)</p>\n\n<p>I agree with you that the mx: looks unsightly at first, especially when you already have a strong background in HTML or XML, but you'll get used to it.</p>\n"
},
{
"answer_id": 11162103,
"author": "Sean Nell",
"author_id": 453870,
"author_profile": "https://Stackoverflow.com/users/453870",
"pm_score": 0,
"selected": false,
"text": "<p>Keep in mind that if you are developing applications that should run on all kinds of platforms including mobile devices it is best to stick with pure spark as far as possible as it is supported on most mobile devices these days. There are cases where one is forced to use an mx control like an Accordion for instance. In this case if you do have time to implement it, it is wise to use tools or the basic controls in spark to create these more advanced or complicated controls to use instead.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] |
I am a newbie at Flex, and I don't like the way you have to write the namespace mx: for every control declaration you write. It makes the code cluttery. I would like to write:
```
<Panel ...
```
rather than
```
<mx:Panel ...
```
I tried writing
```
xmlns="http://www.adobe.com/2006/mxml"
```
for the top level element instead of
```
xmlns:mx="http://www.adobe.com/2006/mxml"
```
In the top level declaration. This work to an extent, but broke some existing code. For one, XML data that are defined in the document are all appended with aaa: as the namespace during runtime. I've also noticed other issues in my very small sample program.
Is there a way to do this that works, or is this a lost cause? And some background information on why would be appreciated.
*Update: Thanks all for the replies, but I would like to have heard from someone who actually tried this and thought it was important. Although most of you told me it was a bad idea, I was not discouraged. I got a couple of programs working this way smoothly now. And plan to do this in all my flex apps. One trick seemed to work for me although I can't claim it'll work universally. If you need separate namespaces within your doc, take, HTTPService parameters for example, you could create a namespace within that element like so:*
```
<HTTPService id="service" url="http://blah.com"
method="POST" result="gotResult(event)">
<request xmlns:p="*">
<p:param1>p1</p:param1>
<p:param2>p2</p:param2>
</request>
</HTTPService>
```
*Hope this helps someone. I am very happy with how clean my code is now, almost as clean as a normal html file. As for people who think writing mx: throughout your code is clearer and what not, I disagree completely. I think languages that require you to repeat the same character sequence excessively in your code - which you should consider a document - have design flaws. Here's an analogy for you: how would you like it if you were reading an article on Barack Obama, and every single sentence contained the words 'Barack Obama', that would get pretty tiresome wouldn't it?*
|
I think that removing the mx namespace will almost certainly cause you trouble with name conflicts as your project gets larger.
Personally I think the mx namespace makes the code clearer rather than more cluttered, especially if you have component based flex development or a lot of your own controls. Having owned a large flex code base for the last two years I find the mx namespace unobtrusive, especially when you have custom objects embedded inline such as item renderers.
My recommendation (unscientifically asserted) is to put up with it, especially if you are finding issues when removing it. I bet you'll stop noticing it after a while.
|
284,538 |
<p>I am trying to access my WCF service on a server from my client console application for testing. I am getting the following error: </p>
<blockquote>
<p>The caller was not authenticated by
the service</p>
</blockquote>
<p>I am using <code>wsHttpBinding</code>. I'm not sure what kind of authentication the service is expecting?</p>
<p>
<br>
<br>
</p>
<pre><code><behaviors>
<serviceBehaviors>
<behavior name="MyTrakerService.MyTrakerServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</code></pre>
<p></p>
<p><b>Update</b>
It works if I change my binding to <code><endpoint "basicHttpBinding" ... /></code> (from wsHttpBinding)
on the IIS 7.0 hosted, windows 2008 server</p>
|
[
{
"answer_id": 284777,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.</p>\n"
},
{
"answer_id": 285062,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 5,
"selected": false,
"text": "<p>If you use basicHttpBinding, configure the endpoint security to \"None\" and transport clientCredintialType to \"None.\"</p>\n\n<pre><code><bindings>\n <basicHttpBinding>\n <binding name=\"MyBasicHttpBinding\">\n <security mode=\"None\">\n <transport clientCredentialType=\"None\" />\n </security>\n </binding>\n </basicHttpBinding>\n</bindings>\n<services>\n <service behaviorConfiguration=\"MyServiceBehavior\" name=\"MyService\">\n <endpoint \n binding=\"basicHttpBinding\" \n bindingConfiguration=\"MyBasicHttpBinding\"\n name=\"basicEndPoint\" \n contract=\"IMyService\" \n />\n</service>\n</code></pre>\n\n<p>Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access</p>\n"
},
{
"answer_id": 588440,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I got it.</p>\n\n<p>If you want to use wshttpbinding, u need to add windows credentials as below.</p>\n\n<pre><code>svc.ClientCredentials.Windows.ClientCredential.UserName = \"abc\";\nsvc.ClientCredentials.Windows.ClientCredential.Password = \"xxx\";\n</code></pre>\n\n<p>thanks</p>\n"
},
{
"answer_id": 1599200,
"author": "kishore",
"author_id": 193626,
"author_profile": "https://Stackoverflow.com/users/193626",
"pm_score": 2,
"selected": false,
"text": "<p>set anonymous access in your virtual directory</p>\n\n<p>write following credentials to your service </p>\n\n<pre><code>ADTService.ServiceClient adtService = new ADTService.ServiceClient();\nadtService.ClientCredentials.Windows.ClientCredential.UserName=\"windowsuseraccountname\";\nadtService.ClientCredentials.Windows.ClientCredential.Password=\"windowsuseraccountpassword\";\nadtService.ClientCredentials.Windows.ClientCredential.Domain=\"windowspcname\";\n</code></pre>\n\n<p>after that you call your webservice methods.</p>\n"
},
{
"answer_id": 1665583,
"author": "Can Bilgin",
"author_id": 201432,
"author_profile": "https://Stackoverflow.com/users/201432",
"pm_score": -1,
"selected": false,
"text": "<p>Why can't you just remove the security setting altogether for wsHttpBinding (\"none\" instead of \"message\" or \"transport\")?</p>\n"
},
{
"answer_id": 19769280,
"author": "Brian",
"author_id": 1794167,
"author_profile": "https://Stackoverflow.com/users/1794167",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using a self hosted site like me, the way to avoid this problem (as described above) is to stipulate on both the host and client side that the wsHttpBinding security mode = NONE. </p>\n\n<p>When creating the binding, both on the client and the host, you can use this code: </p>\n\n<pre><code> Dim binding as System.ServiceModel.WSHttpBinding \n binding= New System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None)\n</code></pre>\n\n<p>or</p>\n\n<pre><code> System.ServiceModel.WSHttpBinding binding\n binding = new System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None);\n</code></pre>\n"
},
{
"answer_id": 35668305,
"author": "farhang67",
"author_id": 2386925,
"author_profile": "https://Stackoverflow.com/users/2386925",
"pm_score": 0,
"selected": false,
"text": "<p>if needed to specify domain(which authecticates username and password that client uses) in webconfig you can put this in system.serviceModel services service section:</p>\n\n<pre><code><identity> \n<servicePrincipalName value=\"example.com\" />\n</identity>\n</code></pre>\n\n<p>and in client specify domain and username and password:</p>\n\n<pre><code> client.ClientCredentials.Windows.ClientCredential.Domain = \"example.com\";\n client.ClientCredentials.Windows.ClientCredential.UserName = \"UserName \";\n client.ClientCredentials.Windows.ClientCredential.Password = \"Password\";\n</code></pre>\n"
},
{
"answer_id": 36488130,
"author": "Ajay Shankar",
"author_id": 6172795,
"author_profile": "https://Stackoverflow.com/users/6172795",
"pm_score": 1,
"selected": false,
"text": "<p>I was able to resolve the shared issue by following below steps:</p>\n\n<ol>\n<li>Go to IIS--><strong>Sites</strong>--><strong>Your Site</strong>--></li>\n<li>Features View Pane--><strong>Authentication</strong></li>\n<li>Set <strong>Anonymous Authentication</strong> to <strong>Disabled</strong> </li>\n<li>Set <strong>Windows Authentication</strong> to <strong>Enabled</strong></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/2OCHn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2OCHn.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 37267074,
"author": "yiannis",
"author_id": 562748,
"author_profile": "https://Stackoverflow.com/users/562748",
"pm_score": 0,
"selected": false,
"text": "<p>This can be caused if the client is in a different domain than the server.</p>\n\n<p>I encountered this when testing one of my applications from my PC(client) to my (cloud) testing server and the simplest solution i could think of was setting up a vpn. </p>\n"
},
{
"answer_id": 51415733,
"author": "Nani",
"author_id": 2617906,
"author_profile": "https://Stackoverflow.com/users/2617906",
"pm_score": 0,
"selected": false,
"text": "<p>I also had the same problem in <code>wsHtppBinding</code>. And I just had to add <code>security</code> mode pointing to <code>none</code>, that solved my problem and no need to switch to <code>basicHttpBinding</code>. <a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/271b1816-173c-4c76-a4c4-fd9fda4b5e91/how-to-disable-wcf-security?forum=wcf\" rel=\"nofollow noreferrer\">Check Here</a> and check how to disable WCF security. Check the below config change for reference:</p>\n\n<pre><code><wsHttpBinding>\n <binding name=\"soapBinding\">\n <security mode=\"None\">\n <transport clientCredentialType=\"None\" />\n <message establishSecurityContext=\"false\" />\n </security>\n </binding>\n</wsHttpBinding>\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to access my WCF service on a server from my client console application for testing. I am getting the following error:
>
> The caller was not authenticated by
> the service
>
>
>
I am using `wsHttpBinding`. I'm not sure what kind of authentication the service is expecting?
```
<behaviors>
<serviceBehaviors>
<behavior name="MyTrakerService.MyTrakerServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
```
**Update**
It works if I change my binding to `<endpoint "basicHttpBinding" ... />` (from wsHttpBinding)
on the IIS 7.0 hosted, windows 2008 server
|
If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."
```
<bindings>
<basicHttpBinding>
<binding name="MyBasicHttpBinding">
<security mode="None">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="MyService">
<endpoint
binding="basicHttpBinding"
bindingConfiguration="MyBasicHttpBinding"
name="basicEndPoint"
contract="IMyService"
/>
</service>
```
Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access
|
284,556 |
<p>I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do </p>
<pre><code>Obj *obj = libname_newDevice();
</code></pre>
<p>Now, should I use delete or should I do <code>obj->deleteMe();</code>? I ask because I am not exactly doing new so I shouldn't be doing the delete?</p>
<p>I have <code>obj->create(theType);</code> which returns a class with the Obj interface.
My real question is do I need a <code>libname_deleteDevice();</code> or is <code>obj->deleteMe()</code> fine since I have a deleteMe in the interface?</p>
|
[
{
"answer_id": 284565,
"author": "Jaywalker",
"author_id": 382974,
"author_profile": "https://Stackoverflow.com/users/382974",
"pm_score": 4,
"selected": false,
"text": "<p>Since you are abstracting the creation inside <code>libname_newDevice()</code> (which I have to say isn't a good approach), you should destroy using something like <code>libname_destroyDevice (obj)</code>.</p>\n\n<p>And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.</p>\n"
},
{
"answer_id": 284584,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 2,
"selected": false,
"text": "<p>Please try to clarify your question. It's totally unclear to me.</p>\n\n<ul>\n<li>Why do you speak of a graphical back end? Is it relevant to the question?</li>\n<li>Are you asking how you should design your library or how you should use it?</li>\n</ul>\n\n<p>It's good practice to have an object factory to create the object. I assume this is the role of <code>libname_newDevice()</code>.</p>\n\n<p>The library should also provide a way to delete the object (such as <code>obj->DeleteMe()</code> or <code>libname_Delete(obj)</code> ).</p>\n\n<p>Don't rely on C++'s <code>delete</code>: caller and library might have been compiled with different version of the compiler, which would do different things regarding memory and resources allocation. It's therefore safer if your lib deletes the object it created.</p>\n"
},
{
"answer_id": 284645,
"author": "Charles Anderson",
"author_id": 11677,
"author_profile": "https://Stackoverflow.com/users/11677",
"pm_score": 0,
"selected": false,
"text": "<p>You definitely don't want to implement Obj::deleteMe(). It would have to do something like: </p>\n\n<pre><code>delete this;\n</code></pre>\n\n<p>while you were still inside this->deleteMe(). Follow Jaywalker's suggestion and make the destroy function take an Obj* as a parameter.</p>\n"
},
{
"answer_id": 284655,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 1,
"selected": false,
"text": "<p>I think the best way would be to honor <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow noreferrer\">RAII</a> and have some reference counting wrapper object (you can even use <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\">shared_ptr</a> with a custom deallocator).</p>\n"
},
{
"answer_id": 284663,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": true,
"text": "<p>I would take one step further.<br>\nIf you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.</p>\n\n<pre><code>class ObjWrap\n{\n public:\n ObjWrap()\n :obj(libname_newDevice())\n {}\n ~ObjWrap()\n { libname_deleteDevice(obj);}\n private:\n ObjWrap(ObjWrap const&); // Dont copy\n void operator=(ObjWrap const&); // Dont copy\n Obj* obj;\n}; // If you want to copy then you need to extra work on ref counting\n // This may need some form of smart pointer.\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do
```
Obj *obj = libname_newDevice();
```
Now, should I use delete or should I do `obj->deleteMe();`? I ask because I am not exactly doing new so I shouldn't be doing the delete?
I have `obj->create(theType);` which returns a class with the Obj interface.
My real question is do I need a `libname_deleteDevice();` or is `obj->deleteMe()` fine since I have a deleteMe in the interface?
|
I would take one step further.
If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.
```
class ObjWrap
{
public:
ObjWrap()
:obj(libname_newDevice())
{}
~ObjWrap()
{ libname_deleteDevice(obj);}
private:
ObjWrap(ObjWrap const&); // Dont copy
void operator=(ObjWrap const&); // Dont copy
Obj* obj;
}; // If you want to copy then you need to extra work on ref counting
// This may need some form of smart pointer.
```
|
284,558 |
<p>I have an existing Stored Procedure which I am trying to now call with LINQ to SQL, here is the stored procedure:</p>
<pre><code>ALTER procedure [dbo].[sp_SELECT_Security_ALL] (
@UID Varchar(15)
)
as
DECLARE @A_ID int
If ISNULL(@UID,'') = ''
SELECT DISTINCT
App_ID,
App_Name,
App_Description,
DB,
DBNameApp_ID,
For_One_EVA_List_Ind
From v_Security_ALL
ELSE
BEGIN
Select @A_ID = (Select Assignee_ID From NEO.dbo.v_Assignees Where USER_ID = @UID and Inactive_Ind = 0)
SELECT DISTINCT
Security_User_ID,
Security_Company,
Security_MailCode,
Security_Last_Name,
Security_First_Name,
Security_User_Name,
Security_User_Info,
Security_User_CO_MC,
Security_Email_Addr,
Security_Phone,
Security_Security_Level,
Security_Security_Desc,
Security_Security_Comment,
Security_Security_Inactive_Ind,
App_ID,
App_Name,
App_Description,
DB,
DBNameApp_ID,
For_One_EVA_List_Ind,
@A_ID as Assignee_ID
From v_Security_ALL
Where Security_User_ID = @UID
END
</code></pre>
<p>My problem is that the intellsense only sees the first set of return values in the IF statement and I can not access anything from the "else" part of my stored procedure. so when I try to do this:</p>
<pre><code> var apps = dataContext.sp_SELECT_Security_ALL(userId);
foreach (var app in apps)
{
string i = app.
}
</code></pre>
<p>On the app. part the only available values I have there is the results of the the first Select distinct above.</p>
<p>Is it possible to use LINQ with this type of stored procedure?</p>
|
[
{
"answer_id": 284565,
"author": "Jaywalker",
"author_id": 382974,
"author_profile": "https://Stackoverflow.com/users/382974",
"pm_score": 4,
"selected": false,
"text": "<p>Since you are abstracting the creation inside <code>libname_newDevice()</code> (which I have to say isn't a good approach), you should destroy using something like <code>libname_destroyDevice (obj)</code>.</p>\n\n<p>And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.</p>\n"
},
{
"answer_id": 284584,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 2,
"selected": false,
"text": "<p>Please try to clarify your question. It's totally unclear to me.</p>\n\n<ul>\n<li>Why do you speak of a graphical back end? Is it relevant to the question?</li>\n<li>Are you asking how you should design your library or how you should use it?</li>\n</ul>\n\n<p>It's good practice to have an object factory to create the object. I assume this is the role of <code>libname_newDevice()</code>.</p>\n\n<p>The library should also provide a way to delete the object (such as <code>obj->DeleteMe()</code> or <code>libname_Delete(obj)</code> ).</p>\n\n<p>Don't rely on C++'s <code>delete</code>: caller and library might have been compiled with different version of the compiler, which would do different things regarding memory and resources allocation. It's therefore safer if your lib deletes the object it created.</p>\n"
},
{
"answer_id": 284645,
"author": "Charles Anderson",
"author_id": 11677,
"author_profile": "https://Stackoverflow.com/users/11677",
"pm_score": 0,
"selected": false,
"text": "<p>You definitely don't want to implement Obj::deleteMe(). It would have to do something like: </p>\n\n<pre><code>delete this;\n</code></pre>\n\n<p>while you were still inside this->deleteMe(). Follow Jaywalker's suggestion and make the destroy function take an Obj* as a parameter.</p>\n"
},
{
"answer_id": 284655,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 1,
"selected": false,
"text": "<p>I think the best way would be to honor <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow noreferrer\">RAII</a> and have some reference counting wrapper object (you can even use <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\">shared_ptr</a> with a custom deallocator).</p>\n"
},
{
"answer_id": 284663,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": true,
"text": "<p>I would take one step further.<br>\nIf you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.</p>\n\n<pre><code>class ObjWrap\n{\n public:\n ObjWrap()\n :obj(libname_newDevice())\n {}\n ~ObjWrap()\n { libname_deleteDevice(obj);}\n private:\n ObjWrap(ObjWrap const&); // Dont copy\n void operator=(ObjWrap const&); // Dont copy\n Obj* obj;\n}; // If you want to copy then you need to extra work on ref counting\n // This may need some form of smart pointer.\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20748/"
] |
I have an existing Stored Procedure which I am trying to now call with LINQ to SQL, here is the stored procedure:
```
ALTER procedure [dbo].[sp_SELECT_Security_ALL] (
@UID Varchar(15)
)
as
DECLARE @A_ID int
If ISNULL(@UID,'') = ''
SELECT DISTINCT
App_ID,
App_Name,
App_Description,
DB,
DBNameApp_ID,
For_One_EVA_List_Ind
From v_Security_ALL
ELSE
BEGIN
Select @A_ID = (Select Assignee_ID From NEO.dbo.v_Assignees Where USER_ID = @UID and Inactive_Ind = 0)
SELECT DISTINCT
Security_User_ID,
Security_Company,
Security_MailCode,
Security_Last_Name,
Security_First_Name,
Security_User_Name,
Security_User_Info,
Security_User_CO_MC,
Security_Email_Addr,
Security_Phone,
Security_Security_Level,
Security_Security_Desc,
Security_Security_Comment,
Security_Security_Inactive_Ind,
App_ID,
App_Name,
App_Description,
DB,
DBNameApp_ID,
For_One_EVA_List_Ind,
@A_ID as Assignee_ID
From v_Security_ALL
Where Security_User_ID = @UID
END
```
My problem is that the intellsense only sees the first set of return values in the IF statement and I can not access anything from the "else" part of my stored procedure. so when I try to do this:
```
var apps = dataContext.sp_SELECT_Security_ALL(userId);
foreach (var app in apps)
{
string i = app.
}
```
On the app. part the only available values I have there is the results of the the first Select distinct above.
Is it possible to use LINQ with this type of stored procedure?
|
I would take one step further.
If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.
```
class ObjWrap
{
public:
ObjWrap()
:obj(libname_newDevice())
{}
~ObjWrap()
{ libname_deleteDevice(obj);}
private:
ObjWrap(ObjWrap const&); // Dont copy
void operator=(ObjWrap const&); // Dont copy
Obj* obj;
}; // If you want to copy then you need to extra work on ref counting
// This may need some form of smart pointer.
```
|
284,566 |
<p>I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler?</p>
<pre><code>struct InterfaceWrapper {
InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){};
int someElement(void) const { return m_internal.someElement; };
private:
InterfaceWrapper(){} // initialize m_internal
SomeHugeStructure& m_internal;
};
</code></pre>
|
[
{
"answer_id": 284605,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 2,
"selected": false,
"text": "<p>If you really need to construct the class without having an element, a reference is not the way to go.</p>\n\n<p>If your only reason to use a reference is to avoid copying, I'd suggest using a pointer.\nYou can simply take the address of the passed reference in you regular constructor, and initialize it to NULL in the private constructor. When the object's lifetime ends the pointer will be a dangling pointer, but the same is true for references...</p>\n\n<p>Alternatively, have the public constructor take a smart pointer and use such a smart pointer as member too, if you're concerned about lifetimes.</p>\n\n<p>And of course, cope with the pointer possibly being NULL in the remainder of the class' code. (but you had to cope with the member possible being a stub in the reference case too, so that's not really an issue)</p>\n"
},
{
"answer_id": 284612,
"author": "Chris Morley",
"author_id": 36034,
"author_profile": "https://Stackoverflow.com/users/36034",
"pm_score": 1,
"selected": false,
"text": "<p>What is the point of the private ctor? If m_internal is not referencing a valid object, how can it be useful?</p>\n\n<p>Also the m_internal-> won't compile. That is pointer syntax, not ref.</p>\n"
},
{
"answer_id": 284618,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>If you are making the default ctor private to prevent anyone from using it, then just leave off the body:</p>\n\n<pre><code>private:\n InterfaceWrapper();\n SomeHugeStructure& m_internal;\n</code></pre>\n\n<p>The compiler will think it's defined elsewhere, and the linker won't mind that it's not unless someone tries to use it.</p>\n"
},
{
"answer_id": 284720,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 3,
"selected": true,
"text": "<p>As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you.</p>\n\n<p>If the purpose is to limit access to friends of the class, then you would probably be best having a pointer (prefereably a smart pointer) member, and setting it to NULL.</p>\n\n<p>--</p>\n\n<p>Also, I'm not sure why you made this a struct rather than a class. In general making something a struct makes sense when you're exposing data members as public, similar to C. In this case, it looks like you have a conventional class, in which case the C++ convention would be to make it a class.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16496/"
] |
I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler?
```
struct InterfaceWrapper {
InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){};
int someElement(void) const { return m_internal.someElement; };
private:
InterfaceWrapper(){} // initialize m_internal
SomeHugeStructure& m_internal;
};
```
|
As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you.
If the purpose is to limit access to friends of the class, then you would probably be best having a pointer (prefereably a smart pointer) member, and setting it to NULL.
--
Also, I'm not sure why you made this a struct rather than a class. In general making something a struct makes sense when you're exposing data members as public, similar to C. In this case, it looks like you have a conventional class, in which case the C++ convention would be to make it a class.
|
284,581 |
<p>I've got a timer running in my Delphi MDI application and I'd like to use it to pop up a message if something changes in the background. But I don't want that message to pop up when the the application has a modal dialog in the foreground because the user couldn't do anything about it. </p>
<p>So what I'd like to know is how can I check for the existence of a modal dialog in my application?</p>
|
[
{
"answer_id": 284621,
"author": "mghie",
"author_id": 30568,
"author_profile": "https://Stackoverflow.com/users/30568",
"pm_score": 5,
"selected": true,
"text": "<p>You could try with this code:</p>\n\n<pre><code>var\n ActForm: TCustomForm;\nbegin\n ActForm := Screen.ActiveForm;\n if (ActForm = nil) or not (fsModal in ActForm.FormState) then begin\n\n end;\nend;\n</code></pre>\n\n<p>I tested with Delphi 4, works for me.</p>\n\n<p>[EDIT]: But you should really think about whether popping up a form and stealing focus is a good idea. It depends on your application, but if a user is currently entering something into an edit field, or doing something with the mouse, then this might break their workflow.</p>\n"
},
{
"answer_id": 284703,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps the solution is to actually pop up a hint which doesn't steal focus. A clickable hint somewhere visible, but not too invasive. Thus, if the user wants to take action they can, or they can finish off what they were doing, then take action. Or perhaps ignore it altogether.</p>\n"
},
{
"answer_id": 286511,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 3,
"selected": false,
"text": "<p>Since Delphi 2005 you have a <a href=\"http://docwiki.embarcadero.com/Libraries/Seattle/en/Vcl.Forms.TApplication.ModalLevel\" rel=\"nofollow noreferrer\">ModalLevel</a> property on TApplication. It counts the number of Modal forms opened in the application.</p>\n"
},
{
"answer_id": 3306738,
"author": "Jeroen Wiert Pluimers",
"author_id": 29290,
"author_profile": "https://Stackoverflow.com/users/29290",
"pm_score": 1,
"selected": false,
"text": "<p>Today user <a href=\"https://stackoverflow.com/users/180353/histrio\">histrio</a> correctly answered in <a href=\"https://stackoverflow.com/questions/3306260/delphi-detecting-if-my-app-has-a-modal-dialog-open\">another thread</a> that just monitoring modal Delphi forms is not enough; Windows can also have modal dialogs.</p>\n\n<p>His <a href=\"https://stackoverflow.com/questions/3306260/delphi-detecting-if-my-app-has-a-modal-dialog-open/3306514#3306514\">answer in another thread</a> shows you how to check for that.</p>\n\n<p>--jeroen</p>\n"
},
{
"answer_id": 3306844,
"author": "histrio",
"author_id": 180353,
"author_profile": "https://Stackoverflow.com/users/180353",
"pm_score": 2,
"selected": false,
"text": "<p>use <a href=\"http://msdn.microsoft.com/en-us/library/ms632670(VS.85).aspx\" rel=\"nofollow noreferrer\">AnyPopup</a>() function</p>\n\n<p>About <a href=\"http://msdn.microsoft.com/en-us/library/ms633507(VS.85).aspx\" rel=\"nofollow noreferrer\">GetLastActivePopup</a>(). It may return value is the same as the hWnd parameter when</p>\n\n<ul>\n<li>The window identified by hWnd was most recently active.</li>\n<li>The window identified by hWnd does not own any pop-up windows.</li>\n<li>The window identifies by hWnd is not a top-level window, or it is owned by another window.</li>\n</ul>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
I've got a timer running in my Delphi MDI application and I'd like to use it to pop up a message if something changes in the background. But I don't want that message to pop up when the the application has a modal dialog in the foreground because the user couldn't do anything about it.
So what I'd like to know is how can I check for the existence of a modal dialog in my application?
|
You could try with this code:
```
var
ActForm: TCustomForm;
begin
ActForm := Screen.ActiveForm;
if (ActForm = nil) or not (fsModal in ActForm.FormState) then begin
end;
end;
```
I tested with Delphi 4, works for me.
[EDIT]: But you should really think about whether popping up a form and stealing focus is a good idea. It depends on your application, but if a user is currently entering something into an edit field, or doing something with the mouse, then this might break their workflow.
|
284,608 |
<p>I need more than the default diff! I have recently purchased "Beyond Compare" and I'd like to integrate it with svn, so its launched when I type:</p>
<p>svn diff foo.c</p>
<p>How do I do this?</p>
|
[
{
"answer_id": 284613,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 4,
"selected": false,
"text": "<p>Look at svn --diff-cmd.</p>\n"
},
{
"answer_id": 284666,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 6,
"selected": true,
"text": "<p>From a <a href=\"http://www.scootersoftware.com/vbulletin/showthread.php?t=41520\" rel=\"noreferrer\">Beyond Compare forum post</a>:</p>\n\n<p>/usr/bin/bcompare_svn:</p>\n\n<pre><code>#!/bin/bash\n/usr/bin/bcompare $6 $7 &\nexit 0\n</code></pre>\n\n<p>The invocation of bcompare is obvious but I had to add \"exit 0\" so that svn would open more than one file at a time.</p>\n\n<p>To make svn invoke my script, I added the following line in the [helpers] section in ~/.subversion/config</p>\n\n<pre><code>diff-cmd=/usr/bin/bcompare_svn\n</code></pre>\n"
},
{
"answer_id": 285316,
"author": "shank",
"author_id": 24697,
"author_profile": "https://Stackoverflow.com/users/24697",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to add a comment to Andy Lester's answer but I don't have a big enough reputation. However, I can answer the question, I guess.</p>\n\n<p>Anyways... as Andy already noted run \"svn help diff\" but to just give you the answer...</p>\n\n<p>svn diff --diff-cmd <diff-cmd> --extensions <diff-cmd options></p>\n\n<p>svn diff --diff-cmd /usr/bin/diff --extensions \"-bca\" <filename(s)></p>\n"
},
{
"answer_id": 358044,
"author": "Chris",
"author_id": 45179,
"author_profile": "https://Stackoverflow.com/users/45179",
"pm_score": 2,
"selected": false,
"text": "<p>I recently added instructions for Subversion on Linux to our <a href=\"http://www.scootersoftware.com/support.php?zz=kb_vcs.php\" rel=\"nofollow noreferrer\">Using Beyond Compare With Version Control Systems</a> web page. Once you follow the steps at the above link it should launch Beyond Compare 3 for Linux when you run \"svn diff\".</p>\n"
},
{
"answer_id": 14249596,
"author": "David Wu",
"author_id": 1965237,
"author_profile": "https://Stackoverflow.com/users/1965237",
"pm_score": 2,
"selected": false,
"text": "<p>In latest Subversion, the script /usr/bin/bcompare_svn should be like this:</p>\n\n<pre><code>#!/bin/bash\ncp $6 $6.save\ncp $7 $7.save\n{\n /usr/bin/bcompare $6.save $7.save \n rm $6.save $7.save\n} &\nexit 0\n</code></pre>\n\n<p>or (untested code)</p>\n\n<pre><code>#!/bin/bash\nbase=`echo $3 | sed -r \"s/^([^\\(]+)[ \\t]+\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\ncurrent=`echo $5 | sed -r \"s/^([^\\(]+)[ \\t]\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\n\nmv \"$6\" \"/tmp/$base\"\nmv \"$7\" \"/tmp/$current\"\n{\n /usr/local/bcompare/bin/bcompare \"/tmp/$base\" \"/tmp/$current\"\n rm \"/tmp/$base\" \"/tmp/$current\"\n} &\nexit 0\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3886/"
] |
I need more than the default diff! I have recently purchased "Beyond Compare" and I'd like to integrate it with svn, so its launched when I type:
svn diff foo.c
How do I do this?
|
From a [Beyond Compare forum post](http://www.scootersoftware.com/vbulletin/showthread.php?t=41520):
/usr/bin/bcompare\_svn:
```
#!/bin/bash
/usr/bin/bcompare $6 $7 &
exit 0
```
The invocation of bcompare is obvious but I had to add "exit 0" so that svn would open more than one file at a time.
To make svn invoke my script, I added the following line in the [helpers] section in ~/.subversion/config
```
diff-cmd=/usr/bin/bcompare_svn
```
|
284,609 |
<p>I have a SQL Mobile database with one table. It has several columns with useful, often queried data and one column that stores a relatively large string per record (1000+ characters) that is not queried often.</p>
<p>Imagine this fake schema, the "lifeStory" field is the large one.</p>
<pre><code>table1
String firstName
String lastName
String address
String lifeStory
</code></pre>
<p>A representative query would be</p>
<pre><code>SELECT firstName, lastName, address FROM table1 WHERE firstName = :p1
</code></pre>
<p>Does anyone know of any performance concerns leaving that large, infrequently queried column in this table?</p>
|
[
{
"answer_id": 284613,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 4,
"selected": false,
"text": "<p>Look at svn --diff-cmd.</p>\n"
},
{
"answer_id": 284666,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 6,
"selected": true,
"text": "<p>From a <a href=\"http://www.scootersoftware.com/vbulletin/showthread.php?t=41520\" rel=\"noreferrer\">Beyond Compare forum post</a>:</p>\n\n<p>/usr/bin/bcompare_svn:</p>\n\n<pre><code>#!/bin/bash\n/usr/bin/bcompare $6 $7 &\nexit 0\n</code></pre>\n\n<p>The invocation of bcompare is obvious but I had to add \"exit 0\" so that svn would open more than one file at a time.</p>\n\n<p>To make svn invoke my script, I added the following line in the [helpers] section in ~/.subversion/config</p>\n\n<pre><code>diff-cmd=/usr/bin/bcompare_svn\n</code></pre>\n"
},
{
"answer_id": 285316,
"author": "shank",
"author_id": 24697,
"author_profile": "https://Stackoverflow.com/users/24697",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to add a comment to Andy Lester's answer but I don't have a big enough reputation. However, I can answer the question, I guess.</p>\n\n<p>Anyways... as Andy already noted run \"svn help diff\" but to just give you the answer...</p>\n\n<p>svn diff --diff-cmd <diff-cmd> --extensions <diff-cmd options></p>\n\n<p>svn diff --diff-cmd /usr/bin/diff --extensions \"-bca\" <filename(s)></p>\n"
},
{
"answer_id": 358044,
"author": "Chris",
"author_id": 45179,
"author_profile": "https://Stackoverflow.com/users/45179",
"pm_score": 2,
"selected": false,
"text": "<p>I recently added instructions for Subversion on Linux to our <a href=\"http://www.scootersoftware.com/support.php?zz=kb_vcs.php\" rel=\"nofollow noreferrer\">Using Beyond Compare With Version Control Systems</a> web page. Once you follow the steps at the above link it should launch Beyond Compare 3 for Linux when you run \"svn diff\".</p>\n"
},
{
"answer_id": 14249596,
"author": "David Wu",
"author_id": 1965237,
"author_profile": "https://Stackoverflow.com/users/1965237",
"pm_score": 2,
"selected": false,
"text": "<p>In latest Subversion, the script /usr/bin/bcompare_svn should be like this:</p>\n\n<pre><code>#!/bin/bash\ncp $6 $6.save\ncp $7 $7.save\n{\n /usr/bin/bcompare $6.save $7.save \n rm $6.save $7.save\n} &\nexit 0\n</code></pre>\n\n<p>or (untested code)</p>\n\n<pre><code>#!/bin/bash\nbase=`echo $3 | sed -r \"s/^([^\\(]+)[ \\t]+\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\ncurrent=`echo $5 | sed -r \"s/^([^\\(]+)[ \\t]\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\n\nmv \"$6\" \"/tmp/$base\"\nmv \"$7\" \"/tmp/$current\"\n{\n /usr/local/bcompare/bin/bcompare \"/tmp/$base\" \"/tmp/$current\"\n rm \"/tmp/$base\" \"/tmp/$current\"\n} &\nexit 0\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] |
I have a SQL Mobile database with one table. It has several columns with useful, often queried data and one column that stores a relatively large string per record (1000+ characters) that is not queried often.
Imagine this fake schema, the "lifeStory" field is the large one.
```
table1
String firstName
String lastName
String address
String lifeStory
```
A representative query would be
```
SELECT firstName, lastName, address FROM table1 WHERE firstName = :p1
```
Does anyone know of any performance concerns leaving that large, infrequently queried column in this table?
|
From a [Beyond Compare forum post](http://www.scootersoftware.com/vbulletin/showthread.php?t=41520):
/usr/bin/bcompare\_svn:
```
#!/bin/bash
/usr/bin/bcompare $6 $7 &
exit 0
```
The invocation of bcompare is obvious but I had to add "exit 0" so that svn would open more than one file at a time.
To make svn invoke my script, I added the following line in the [helpers] section in ~/.subversion/config
```
diff-cmd=/usr/bin/bcompare_svn
```
|
284,610 |
<p>You get a compilation error if you define the string parameter to have a size greater than 8000</p>
<p>e.g. </p>
<pre><code>The size (9000) given to the type 'varchar' exceeds the maximum allowed for any data type (8000).
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 284620,
"author": "Chris Conway",
"author_id": 2849,
"author_profile": "https://Stackoverflow.com/users/2849",
"pm_score": 4,
"selected": true,
"text": "<p>you need to store it as TEXT instead of varchar for string larger than 8000 in sql 2000</p>\n"
},
{
"answer_id": 284623,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 1,
"selected": false,
"text": "<p>You can't do that in SQL 2000, use the \"text\" data type instead.</p>\n\n<p><a href=\"http://www.mssqlcity.com/Articles/General/choose_data_type.htm\" rel=\"nofollow noreferrer\">Choose SQL 2000 Data Types</a></p>\n"
},
{
"answer_id": 284773,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": -1,
"selected": false,
"text": "<p>You can't use text as a parameter value for a stored proc in SQL 2000, so usually the technique is to break up the information into chunks of 8000 characters or less and reassemble in the proc.</p>\n"
},
{
"answer_id": 285008,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>You can't use text as a parameter value for a stored proc in SQL 2000<<\n Sure you can.</p>\n </blockquote>\n</blockquote>\n\n<p>What you cannot do is define a local variable as text</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
You get a compilation error if you define the string parameter to have a size greater than 8000
e.g.
```
The size (9000) given to the type 'varchar' exceeds the maximum allowed for any data type (8000).
```
Any ideas?
|
you need to store it as TEXT instead of varchar for string larger than 8000 in sql 2000
|
284,619 |
<p>i need write the code that runs when DllRegisterServer is called. i.e. when someone calls:</p>
<pre><code>regsvr32 myActiveX.ocx
</code></pre>
<p>i'm trying to find the definitive list of required registry entries (rather than just what i can cobble together by spellunking through the registry).</p>
<p>So far my expeditions have found:</p>
<pre><code>HKEY_CLASSES_ROOT
\MyCoolLibrary.MyCoolControl
\Clsid
(default) = "{myClassId}"
\CLSID
\{myClassId}
\Control
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
\MiscStatus
\1
(default) = 205201
\ProgID
(default) = "MyCoolLibrary.MyCoolControl"
\ToolboxBitmap32
(default) = "c:\foo\myActiveX.ocx,1"
\TypeLib
(default) = "{myTypeLibraryGuid}"
\Verb
\0
(default) = "Properties,0,2"
\Version
(default) = "1.0"
\TypeLib
\{myTypeLibraryGuid}
\1.0
(default) = "MyCoolLibrary.MyCoolControl"
</code></pre>
<p>Now, the concerns:
- what does the Control folder contain? Is it's presence indicate a control?
- what's a MiscStatus of 205201 do? What would 205202 do instead?
- What's the verb "Properties,0,2"? Where's "Properties,0,0" and "Properties,0,1"?</p>
<p>In other words, i'm looking for the docs.</p>
|
[
{
"answer_id": 284638,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "<p>Larry Osterman provides a good jumping-off point:</p>\n\n<blockquote>\n <p>A large part of the \"cargo cult\"\n nature of this is the fact that there\n are a bewildering set of registry\n settings that can be set for COM\n objects, and it's not clear which, if\n any apply. So I'm attempting to lay\n out a series of articles that can help\n people determine what they need to\n set.</p>\n</blockquote>\n\n<p>-- <a href=\"http://blogs.msdn.com/larryosterman/archive/2006/01/11/511647.aspx\" rel=\"noreferrer\">What registry entries are needed to register a COM object.</a></p>\n\n<p>Summary: it depends on what scenarios you need your object to be used in. The most basic, absolutely-necessary settings are the default value and ThreadingModel in <code>HKEY_CLASSES_ROOT\\CLSID\\<clsid>\\</code>, but most of the time you'll want ProgIDs and AppIDs as well.</p>\n"
},
{
"answer_id": 284643,
"author": "Stu Mackellar",
"author_id": 28591,
"author_profile": "https://Stackoverflow.com/users/28591",
"pm_score": 2,
"selected": false,
"text": "<p>It's not exhaustive, but try <a href=\"http://support.microsoft.com/kb/183771\" rel=\"nofollow noreferrer\">this</a> MS knowledge base article.</p>\n\n<p>Also, <a href=\"http://blogs.msdn.com/larryosterman/default.aspx\" rel=\"nofollow noreferrer\">Larry Osterman</a> has a useful blog post <a href=\"http://blogs.msdn.com/larryosterman/archive/2006/01/11/511647.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<hr>\n\n<p>It occurs to me that another approach would be to use a tool like <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896652.aspx\" rel=\"nofollow noreferrer\">RegMon</a> and directly monitor what registry changes are made when your DllRegisterServer method is called.</p>\n"
},
{
"answer_id": 284647,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 0,
"selected": false,
"text": "<p>By all means, go with the Larry Osterman article linked.</p>\n\n<p>Additionally, a good starting point are the ATL registrar scripts generated by the MSVC ATL COM object wizard. You can play with different options and see how they affect the output.</p>\n"
},
{
"answer_id": 284652,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": false,
"text": "<p>Find/borrow/steal a copy of Inside OLE 2, by Kraig Brockenschmidt. It's old like the world (and dates me as well :-))</p>\n\n<p>Here's also <a href=\"http://msdn.microsoft.com/en-us/library/ms695220(VS.85).aspx\" rel=\"noreferrer\">a high-level overview</a> of the registry entries mentioned above.</p>\n\n<p>Read Larry Osterman's <a href=\"http://blogs.msdn.com/larryosterman/archive/2006/01/11/511647.aspx\" rel=\"noreferrer\">blog post</a> for more pointers.</p>\n\n<p>Look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms221669.aspx\" rel=\"noreferrer\">MSDN ActiveX</a> samples.</p>\n\n<p>Also, you are missing entries under the HKCR\\Interfaces for all custom interfaces and event interfaces your control implements.</p>\n"
},
{
"answer_id": 284763,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Side note if you want to see experimentally what keys are created: use Sysinternals' <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\" title=\"Process Monitor\">Process Monitor</a>, it will capture in real time the activity on the registry when you register the control.</p>\n"
},
{
"answer_id": 285060,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 4,
"selected": false,
"text": "<p>What i know so far. COM creates an object based on it's <em>clsid</em>. This is a guid that uniquely identifies that class. </p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n</code></pre>\n\n<p>That class is then used to create objects. COM now needs to know where the DLL is that holds that COM Object. In my particular case, the \"server\" that exposes the COM object is a DLL, and will be \"in process\". We then point COM to that \"in-process\" dll by adding:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n</code></pre>\n\n<p>COM also needs to know the threading model that the COM server object supports. The simplest, most common, and the one used in this example is the \"Apartment\" threading model:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n</code></pre>\n\n<p>Next is the ProgID. This is similar to how DNS is used to turn a friendly name into an IP. Here we turn a friendly name <code>\"MyCoolLibrary.MyCoolControl\"</code> into the ugly clsid <code>\"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"</code></p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\n</code></pre>\n\n<p>Now someone can ask for </p>\n\n<pre><code>MyCoolLibrary.MyCoolControl\n</code></pre>\n\n<p>and COM can turn that into the ClassID </p>\n\n<pre><code>{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n</code></pre>\n\n<p>Once COM has the clasid, it can then look in the registry under <code>HKCR\\Clsid\\{AE8530CF-D204-4877-9CAB-F052BF1F661F}</code> to find the real information.</p>\n\n<p>For fun, the ProgID is added to the Clsid section, just so people can have some idea what this class is:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \\ProgID\n (default) = \"MyCoolLibrary.MyCoolControl\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\n</code></pre>\n\n<p>Next is the type library. This is mostly <em>un</em>important for anything in-process, but if the COM object is in another \"apartment\", then function parameters need to be marshalled. COM does this automatically for you if it has a type library that defines all the classes methods. </p>\n\n<p>The clsid section is pointed to the appropriate type library with the addition of a TypeLib key:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \\ProgID\n (default) = \"MyCoolLibrary.MyCoolControl\"\n \\TypeLib \n (default) = \"{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\n</code></pre>\n\n<p>Information about this type library is also stored in the registry, but adding these keys is done for us with a call to <a href=\"http://msdn.microsoft.com/en-us/library/ms221570.aspx\" rel=\"noreferrer\">RegisterTypeLib</a>. But it will add keys for us similar to:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \\ProgID\n (default) = \"MyCoolLibrary.MyCoolControl\"\n \\TypeLib \n (default) = \"{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\nHKEY_CLASSES_ROOT\n \\TypeLib\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\1.0\n (default) = \"My Cool ActiveX Library\"\n ...\n</code></pre>\n\n<p>Now we get into the tricky stuff, stuff that is needed to <em>hopefully</em> make an ActiveX control work.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms221150.aspx\" rel=\"noreferrer\">An MSDN article states</a> that you must add a dummy <strong>Programmable</strong> key to indicate that it is an ActiveX control:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\Programmable\n</code></pre>\n\n<p>But <a href=\"http://msdn.microsoft.com/en-us/library/ms691424(VS.85).aspx\" rel=\"noreferrer\">this MSDN Library page</a> says the keyword is <strong>Control</strong>, and not <strong>Programmable</strong> - and there is no Programmable key.</p>\n\n<p>But that doesn't stop some ActiveX's from using Control, some using Programmable, and some using both.</p>\n\n<p>i cannot find anything mentioning anything else being required.</p>\n\n<p>So, can anyone find some definitive documentation?</p>\n"
},
{
"answer_id": 15499780,
"author": "Bagelzone Ha'bonè",
"author_id": 738862,
"author_profile": "https://Stackoverflow.com/users/738862",
"pm_score": -1,
"selected": false,
"text": "<p>Are you working on a 64 bit OS?</p>\n\n<p>If so, instead of writing to<br>\nHKEY_CLASSES_ROOT\\CLSID\\<br>\nyou should write to<br>\nHKEY_CLASSES_ROOT\\Wow6432Node\\CLSID\\</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
i need write the code that runs when DllRegisterServer is called. i.e. when someone calls:
```
regsvr32 myActiveX.ocx
```
i'm trying to find the definitive list of required registry entries (rather than just what i can cobble together by spellunking through the registry).
So far my expeditions have found:
```
HKEY_CLASSES_ROOT
\MyCoolLibrary.MyCoolControl
\Clsid
(default) = "{myClassId}"
\CLSID
\{myClassId}
\Control
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
\MiscStatus
\1
(default) = 205201
\ProgID
(default) = "MyCoolLibrary.MyCoolControl"
\ToolboxBitmap32
(default) = "c:\foo\myActiveX.ocx,1"
\TypeLib
(default) = "{myTypeLibraryGuid}"
\Verb
\0
(default) = "Properties,0,2"
\Version
(default) = "1.0"
\TypeLib
\{myTypeLibraryGuid}
\1.0
(default) = "MyCoolLibrary.MyCoolControl"
```
Now, the concerns:
- what does the Control folder contain? Is it's presence indicate a control?
- what's a MiscStatus of 205201 do? What would 205202 do instead?
- What's the verb "Properties,0,2"? Where's "Properties,0,0" and "Properties,0,1"?
In other words, i'm looking for the docs.
|
What i know so far. COM creates an object based on it's *clsid*. This is a guid that uniquely identifies that class.
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
```
That class is then used to create objects. COM now needs to know where the DLL is that holds that COM Object. In my particular case, the "server" that exposes the COM object is a DLL, and will be "in process". We then point COM to that "in-process" dll by adding:
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
```
COM also needs to know the threading model that the COM server object supports. The simplest, most common, and the one used in this example is the "Apartment" threading model:
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
```
Next is the ProgID. This is similar to how DNS is used to turn a friendly name into an IP. Here we turn a friendly name `"MyCoolLibrary.MyCoolControl"` into the ugly clsid `"{AE8530CF-D204-4877-9CAB-F052BF1F661F}"`
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
HKEY_CLASSES_ROOT
\MyCoolLibrary.MyCoolControl
\Clsid
(default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}"
```
Now someone can ask for
```
MyCoolLibrary.MyCoolControl
```
and COM can turn that into the ClassID
```
{AE8530CF-D204-4877-9CAB-F052BF1F661F}
```
Once COM has the clasid, it can then look in the registry under `HKCR\Clsid\{AE8530CF-D204-4877-9CAB-F052BF1F661F}` to find the real information.
For fun, the ProgID is added to the Clsid section, just so people can have some idea what this class is:
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
\ProgID
(default) = "MyCoolLibrary.MyCoolControl"
HKEY_CLASSES_ROOT
\MyCoolLibrary.MyCoolControl
\Clsid
(default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}"
```
Next is the type library. This is mostly *un*important for anything in-process, but if the COM object is in another "apartment", then function parameters need to be marshalled. COM does this automatically for you if it has a type library that defines all the classes methods.
The clsid section is pointed to the appropriate type library with the addition of a TypeLib key:
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
\ProgID
(default) = "MyCoolLibrary.MyCoolControl"
\TypeLib
(default) = "{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}"
HKEY_CLASSES_ROOT
\MyCoolLibrary.MyCoolControl
\Clsid
(default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}"
```
Information about this type library is also stored in the registry, but adding these keys is done for us with a call to [RegisterTypeLib](http://msdn.microsoft.com/en-us/library/ms221570.aspx). But it will add keys for us similar to:
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\InprocServer32
(default) = "c:\foo\myActiveX.ocx"
ThreadingModel = "Apartment"
\ProgID
(default) = "MyCoolLibrary.MyCoolControl"
\TypeLib
(default) = "{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}"
HKEY_CLASSES_ROOT
\MyCoolLibrary.MyCoolControl
\Clsid
(default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}"
HKEY_CLASSES_ROOT
\TypeLib
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\1.0
(default) = "My Cool ActiveX Library"
...
```
Now we get into the tricky stuff, stuff that is needed to *hopefully* make an ActiveX control work.
[An MSDN article states](http://msdn.microsoft.com/en-us/library/ms221150.aspx) that you must add a dummy **Programmable** key to indicate that it is an ActiveX control:
```
HKEY_CLASSES_ROOT
\Clsid
\{AE8530CF-D204-4877-9CAB-F052BF1F661F}
\Programmable
```
But [this MSDN Library page](http://msdn.microsoft.com/en-us/library/ms691424(VS.85).aspx) says the keyword is **Control**, and not **Programmable** - and there is no Programmable key.
But that doesn't stop some ActiveX's from using Control, some using Programmable, and some using both.
i cannot find anything mentioning anything else being required.
So, can anyone find some definitive documentation?
|
284,637 |
<p>Into some view data i have put the result of an anonymous type:</p>
<pre><code> var projectData = from p in db.Projects
orderby p.title
select new
{
Title = p.title,
DevURL = p.devURL ?? "N/A",
QAURL = p.qaURL ?? "N/A",
LiveURL = p.liveURL ?? "N/A",
Users = p.GetUsers().MakeUserList()
};
ViewData["ProjectSummary"] = projectData;
</code></pre>
<p>How do I iterate through this view data in the MVC view on the front end to say, make a table of results?</p>
|
[
{
"answer_id": 284646,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is not that it's an anonymous type. The problem is that it's merely a lazy-evaluated IQueryable<> object, and it hasn't been evaluated yet.</p>\n\n<p>I can't answer for ASP.NET MVC, but in the very similar Monorail, you would have to convert it from an iterator into an actual collection:</p>\n\n<pre><code> var projectData = (from p in db.Projects\n orderby p.title\n select new\n {\n Title = p.title,\n DevURL = p.devURL ?? \"N/A\",\n QAURL = p.qaURL ?? \"N/A\",\n LiveURL = p.liveURL ?? \"N/A\",\n Users = p.GetUsers().MakeUserList()\n }).ToList();\n</code></pre>\n"
},
{
"answer_id": 284665,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>In your case it would be much simpler to create a model to hold your data rather than using an anonymous type. </p>\n\n<p>The issue you're having is that your anonymous type is cast to an object when its stored within the ViewData. On the UI side, when you get that object out, the only way to access its properties is to use reflection. You do NOT want to do this in your UI. It will be highly ugly. Instead, just add the following class to your Models:</p>\n\n<pre><code>public class Project{\n\npublic string Title {get;set;}\npublic string DevUrl {get;set;}\npublic string QAUrl {get;set;}\npublic string LiveUrl {get;set;}\npublic IEnumerable<User> Users {get;set;}\n\npublic static IEnumerable<Project> RetrieveAllProjects()\n{\n return from p in db.Projects\n orderby p.title\n select new Project\n {\n Title = p.title,\n DevURL = p.devURL ?? \"N/A\",\n QAURL = p.qaURL ?? \"N/A\",\n LiveURL = p.liveURL ?? \"N/A\",\n Users = p.GetUsers().MakeUserList()\n };\n}\n</code></pre>\n\n<p>In your controller do this:</p>\n\n<pre><code>public ActionResult Index()\n{\n return View(\"Index\", Project.RetrieveAllProjects());\n}\n</code></pre>\n\n<p>and in your view's codebehind, strongly type it thusly:</p>\n\n<pre><code>//snip\npublic partial class Index : ViewPage<IEnumerable<Project>>\n{\n//snip\n</code></pre>\n\n<p>You might think its a bit wasteful to have all these models laying around, but its much easier to understand, and makes your UI code much slimmer, if you use your models wisely.</p>\n\n<p>Also, a model is a great place (and, in fact, should be where you do it) to place the logic for loading your data and constructing the models themselves. Think ActiveRecord. And, while you're coding all this, realize that projects like SubSonic create your models for you without any muss or fuss. </p>\n"
},
{
"answer_id": 312950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Not tried this with an anonymous type but this is how i do it by passing a <code>List<T></code> object to <code>ViewData</code></p>\n\n<pre><code><% foreach (Project p in (IEnumerable<Project>)ViewData[\"ProjectSummary\"]) { %>\n <%= Html.Encode(p.Title) %>\n<% } %>\n</code></pre>\n\n<p>Hope this is what your looking for.</p>\n\n<p>Mark </p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] |
Into some view data i have put the result of an anonymous type:
```
var projectData = from p in db.Projects
orderby p.title
select new
{
Title = p.title,
DevURL = p.devURL ?? "N/A",
QAURL = p.qaURL ?? "N/A",
LiveURL = p.liveURL ?? "N/A",
Users = p.GetUsers().MakeUserList()
};
ViewData["ProjectSummary"] = projectData;
```
How do I iterate through this view data in the MVC view on the front end to say, make a table of results?
|
In your case it would be much simpler to create a model to hold your data rather than using an anonymous type.
The issue you're having is that your anonymous type is cast to an object when its stored within the ViewData. On the UI side, when you get that object out, the only way to access its properties is to use reflection. You do NOT want to do this in your UI. It will be highly ugly. Instead, just add the following class to your Models:
```
public class Project{
public string Title {get;set;}
public string DevUrl {get;set;}
public string QAUrl {get;set;}
public string LiveUrl {get;set;}
public IEnumerable<User> Users {get;set;}
public static IEnumerable<Project> RetrieveAllProjects()
{
return from p in db.Projects
orderby p.title
select new Project
{
Title = p.title,
DevURL = p.devURL ?? "N/A",
QAURL = p.qaURL ?? "N/A",
LiveURL = p.liveURL ?? "N/A",
Users = p.GetUsers().MakeUserList()
};
}
```
In your controller do this:
```
public ActionResult Index()
{
return View("Index", Project.RetrieveAllProjects());
}
```
and in your view's codebehind, strongly type it thusly:
```
//snip
public partial class Index : ViewPage<IEnumerable<Project>>
{
//snip
```
You might think its a bit wasteful to have all these models laying around, but its much easier to understand, and makes your UI code much slimmer, if you use your models wisely.
Also, a model is a great place (and, in fact, should be where you do it) to place the logic for loading your data and constructing the models themselves. Think ActiveRecord. And, while you're coding all this, realize that projects like SubSonic create your models for you without any muss or fuss.
|
284,653 |
<p>I've just wasted the past two hours of my life trying to create a table with an auto incrementing primary key bases on <a href="http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment-columns-in-oracle/" rel="nofollow noreferrer">this tutorial</a>, The tutorial is great the issue I've been encountering is that the Create Target fails if I have a column which is a timestamp and a table that is called timestamp in the same table...</p>
<p>Why doesn't oracle flag this as being an issue when I create the table?</p>
<p>Here is the Sequence of commands I enter:</p>
<ol>
<li><p>Creating the Table:</p>
<pre><code>CREATE TABLE myTable
(id NUMBER PRIMARY KEY,
field1 TIMESTAMP(6),
timeStamp NUMBER,
);
</code></pre></li>
<li><p>Creating the Sequence:</p>
<pre><code>CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
</code></pre></li>
<li><p>Creating the trigger:</p>
<pre><code>CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON myTable
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;
/
</code></pre></li>
</ol>
<p>Here is the error message I get:</p>
<pre><code>ORA-06552: PL/SQL: Compilation unit analysis terminated
ORA-06553: PLS-320: the declaration of the type of this expression is incomplete or malformed
</code></pre>
<p>Any combination that does not have the two lines with a the word "timestamp" in them works fine. I would have thought the syntax would be enough to differentiate between the keyword and a column name. </p>
<p>As I've said I don't understand why the table is created fine but oracle falls over when I try to create the trigger...</p>
<p><strong>CLARIFICATION</strong></p>
<p>I know that the issue is that there is a column called timestamp which may or may not be a keyword. MY issue is why it barfed when I tried to create a trigger and not when I created the table, I would have at least expected a warning.</p>
<p>That said having used Oracle for a few hours, it seems a lot less verbose in it's error reporting, Maybe just because I'm using the express version though.</p>
<p>If this is a bug in Oracle how would one who doesn't have a support contract go about reporting it? I'm just playing around with the express version because I have to migrate some code from MySQL to Oracle.</p>
|
[
{
"answer_id": 284701,
"author": "Alexandre",
"author_id": 9025,
"author_profile": "https://Stackoverflow.com/users/9025",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I'm not totally sure about it, but I think this happens because the SQL code used to manipulate and access database objects is interpreted by some interpreter different form the one used to interpret PL/SQL code.</p>\n\n<p>Have in mind that SQL an PL/SQL are different things, and so they are processed differently. So, I think there is some error in one interpreter, just not sure which one is.</p>\n"
},
{
"answer_id": 284715,
"author": "tragomaskhalos",
"author_id": 31140,
"author_profile": "https://Stackoverflow.com/users/31140",
"pm_score": 1,
"selected": false,
"text": "<p>You've hinted at the answer yourself. You're using <code>timestamp</code> as a column name but it's also a keyword. Change the column name to something else (eg <code>xtimestamp</code>) and the trigger compiles.</p>\n"
},
{
"answer_id": 285356,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>TIMESTAMP is not listed in the Oracle docs as a reserved word (which is surprising).</p>\n\n<p>It is listed in the V$RESERVED_WORDS data dictionary view, but its RESERVED flag is set to 'N'.</p>\n\n<p>It might be a bug in the trigger processing. I would say this is a good one for Oracle support.</p>\n"
},
{
"answer_id": 287012,
"author": "pablo",
"author_id": 16112,
"author_profile": "https://Stackoverflow.com/users/16112",
"pm_score": 4,
"selected": true,
"text": "<p>There is a note on metalink about this (227615.1) extract below:</p>\n\n<pre><code># symptom: Creating Trigger fails\n# symptom: Compiling a procedure fails\n# symptom: ORA-06552: PL/SQL: %s\n# symptom: ORA-06553: PLS-%s: %s \n# symptom: PLS-320: the declaration of the type of this expression is incomplete or malformed\n # cause: One of the tables being references was created with a column name that is one of the datatypes (reserved key word). Even though the field is not referenced in the PL/SQL SQL statements, this error will still be produced.\n\n fix:\n\n Workaround:\n\n 1. Rename the column to a non-reserved word.\n 2. Create a view and alias the column to a different name.\n</code></pre>\n"
},
{
"answer_id": 5330532,
"author": "Java-Oracle-Expert",
"author_id": 663117,
"author_profile": "https://Stackoverflow.com/users/663117",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of having Oracle maintain a view, use EXECUTE IMMEDIATE (i.e. if 'Rename the column to a non-reserved word' is not an option.</p>\n"
},
{
"answer_id": 34798467,
"author": "Diogo Maschio",
"author_id": 3961267,
"author_profile": "https://Stackoverflow.com/users/3961267",
"pm_score": 0,
"selected": false,
"text": "<p>You can execute via EXECUTE IMMEDIATE. IT's not better way but work's and avoid column rename. </p>\n\n<p>In my case rename column will be a caotic way</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
I've just wasted the past two hours of my life trying to create a table with an auto incrementing primary key bases on [this tutorial](http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment-columns-in-oracle/), The tutorial is great the issue I've been encountering is that the Create Target fails if I have a column which is a timestamp and a table that is called timestamp in the same table...
Why doesn't oracle flag this as being an issue when I create the table?
Here is the Sequence of commands I enter:
1. Creating the Table:
```
CREATE TABLE myTable
(id NUMBER PRIMARY KEY,
field1 TIMESTAMP(6),
timeStamp NUMBER,
);
```
2. Creating the Sequence:
```
CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
```
3. Creating the trigger:
```
CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON myTable
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;
/
```
Here is the error message I get:
```
ORA-06552: PL/SQL: Compilation unit analysis terminated
ORA-06553: PLS-320: the declaration of the type of this expression is incomplete or malformed
```
Any combination that does not have the two lines with a the word "timestamp" in them works fine. I would have thought the syntax would be enough to differentiate between the keyword and a column name.
As I've said I don't understand why the table is created fine but oracle falls over when I try to create the trigger...
**CLARIFICATION**
I know that the issue is that there is a column called timestamp which may or may not be a keyword. MY issue is why it barfed when I tried to create a trigger and not when I created the table, I would have at least expected a warning.
That said having used Oracle for a few hours, it seems a lot less verbose in it's error reporting, Maybe just because I'm using the express version though.
If this is a bug in Oracle how would one who doesn't have a support contract go about reporting it? I'm just playing around with the express version because I have to migrate some code from MySQL to Oracle.
|
There is a note on metalink about this (227615.1) extract below:
```
# symptom: Creating Trigger fails
# symptom: Compiling a procedure fails
# symptom: ORA-06552: PL/SQL: %s
# symptom: ORA-06553: PLS-%s: %s
# symptom: PLS-320: the declaration of the type of this expression is incomplete or malformed
# cause: One of the tables being references was created with a column name that is one of the datatypes (reserved key word). Even though the field is not referenced in the PL/SQL SQL statements, this error will still be produced.
fix:
Workaround:
1. Rename the column to a non-reserved word.
2. Create a view and alias the column to a different name.
```
|
284,662 |
<p>I want to transform <code>/foo/bar/..</code> to <code>/foo</code></p>
<p>Is there a bash command which does this?</p>
<hr>
<p>Edit: in my practical case, the directory does exist.</p>
|
[
{
"answer_id": 284664,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 6,
"selected": false,
"text": "<p>Try <code>realpath</code>. Below is the source in its entirety, hereby donated to the public domain.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>// realpath.c: display the absolute path to a file or directory.\n// Adam Liss, August, 2007\n// This program is provided \"as-is\" to the public domain, without express or\n// implied warranty, for any non-profit use, provided this notice is maintained.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libgen.h> \n#include <limits.h>\n\nstatic char *s_pMyName;\nvoid usage(void);\n\nint main(int argc, char *argv[])\n{\n char\n sPath[PATH_MAX];\n\n\n s_pMyName = strdup(basename(argv[0]));\n\n if (argc < 2)\n usage();\n\n printf(\"%s\\n\", realpath(argv[1], sPath));\n return 0;\n} \n\nvoid usage(void)\n{\n fprintf(stderr, \"usage: %s PATH\\n\", s_pMyName);\n exit(1);\n}\n</code></pre>\n"
},
{
"answer_id": 284667,
"author": "Tim Whitcomb",
"author_id": 24895,
"author_profile": "https://Stackoverflow.com/users/24895",
"pm_score": 7,
"selected": false,
"text": "<p>I don't know if there is a direct bash command to do this, but I usually do</p>\n\n<pre><code>normalDir=\"`cd \"${dirToNormalize}\";pwd`\"\necho \"${normalDir}\"\n</code></pre>\n\n<p>and it works well.</p>\n"
},
{
"answer_id": 284671,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 9,
"selected": true,
"text": "<p>if you're wanting to chomp part of a filename from the path, \"dirname\" and \"basename\" are your friends, and \"realpath\" is handy too. </p>\n\n<pre><code>dirname /foo/bar/baz \n# /foo/bar \nbasename /foo/bar/baz\n# baz\ndirname $( dirname /foo/bar/baz ) \n# /foo \nrealpath ../foo\n# ../foo: No such file or directory\nrealpath /tmp/../tmp/../tmp\n# /tmp\n</code></pre>\n\n<p><b><code>realpath</code> alternatives</b></p>\n\n<p>If <code>realpath</code> is not supported by your shell, you can try </p>\n\n<pre><code>readlink -f /path/here/.. \n</code></pre>\n\n<p>Also</p>\n\n<pre><code>readlink -m /path/there/../../ \n</code></pre>\n\n<p>Works the same as </p>\n\n<pre><code>realpath -s /path/here/../../\n</code></pre>\n\n<p>in that the path doesn't need to exist to be normalized. </p>\n"
},
{
"answer_id": 1708397,
"author": "alhernau",
"author_id": 207845,
"author_profile": "https://Stackoverflow.com/users/207845",
"pm_score": 2,
"selected": false,
"text": "<p>Talkative, and a bit late answer. I need to write one since I'm stuck on older RHEL4/5.\nI handles absolute and relative links, and simplifies //, /./ and somedir/../ entries.</p>\n\n<pre><code>test -x /usr/bin/readlink || readlink () {\n echo $(/bin/ls -l $1 | /bin/cut -d'>' -f 2)\n }\n\n\ntest -x /usr/bin/realpath || realpath () {\n local PATH=/bin:/usr/bin\n local inputpath=$1\n local changemade=1\n while [ $changemade -ne 0 ]\n do\n changemade=0\n local realpath=\"\"\n local token=\n for token in ${inputpath//\\// }\n do \n case $token in\n \"\"|\".\") # noop\n ;;\n \"..\") # up one directory\n changemade=1\n realpath=$(dirname $realpath)\n ;;\n *)\n if [ -h $realpath/$token ] \n then\n changemade=1\n target=`readlink $realpath/$token`\n if [ \"${target:0:1}\" = '/' ]\n then\n realpath=$target\n else\n realpath=\"$realpath/$target\"\n fi\n else\n realpath=\"$realpath/$token\"\n fi\n ;;\n esac\n done\n inputpath=$realpath\n done\n echo $realpath\n}\n\nmkdir -p /tmp/bar\n(cd /tmp ; ln -s /tmp/bar foo; ln -s ../.././usr /tmp/bar/link2usr)\necho `realpath /tmp/foo`\n</code></pre>\n"
},
{
"answer_id": 3339768,
"author": "mattalxndr",
"author_id": 334966,
"author_profile": "https://Stackoverflow.com/users/334966",
"pm_score": 5,
"selected": false,
"text": "<p>Use the readlink utility from the coreutils package.</p>\n\n<pre><code>MY_PATH=$(readlink -f \"$0\")\n</code></pre>\n"
},
{
"answer_id": 3373298,
"author": "loevborg",
"author_id": 239678,
"author_profile": "https://Stackoverflow.com/users/239678",
"pm_score": 6,
"selected": false,
"text": "<p>A portable and reliable solution is to use python, which is preinstalled pretty much everywhere (including Darwin). You have two options:</p>\n\n<ol>\n<li><p><code>abspath</code> returns an absolute path but does not resolve symlinks:</p>\n\n<p><code>python -c \"import os,sys; print(os.path.abspath(sys.argv[1]))\" path/to/file</code></p></li>\n<li><p><code>realpath</code> returns an absolute path and in doing so resolves symlinks, generating a canonical path:</p>\n\n<p><code>python -c \"import os,sys; print(os.path.realpath(sys.argv[1]))\" path/to/file</code></p></li>\n</ol>\n\n<p>In each case, <code>path/to/file</code> can be either a relative or absolute path.</p>\n"
},
{
"answer_id": 6393490,
"author": "Jeet",
"author_id": 268330,
"author_profile": "https://Stackoverflow.com/users/268330",
"pm_score": 3,
"selected": false,
"text": "<p>As Adam Liss noted <code>realpath</code> is not bundled with every distribution. Which is a shame, because it is the best solution. The provided source code is great, and I will probably start using it now. Here is what I have been using until now, which I share here just for completeness:</p>\n\n<pre><code>get_abs_path() {\n local PARENT_DIR=$(dirname \"$1\")\n cd \"$PARENT_DIR\"\n local ABS_PATH=\"$(pwd)\"/\"$(basename \"$1\")\"\n cd - >/dev/null\n echo \"$ABS_PATH\"\n} \n</code></pre>\n\n<p>If you want it to resolve symlinks, just replace <code>pwd</code> with <code>pwd -P</code>.</p>\n"
},
{
"answer_id": 7717841,
"author": "schmunk",
"author_id": 291573,
"author_profile": "https://Stackoverflow.com/users/291573",
"pm_score": 3,
"selected": false,
"text": "<p>My recent solution was:</p>\n\n<pre><code>pushd foo/bar/..\ndir=`pwd`\npopd\n</code></pre>\n\n<p>Based on the answer of Tim Whitcomb.</p>\n"
},
{
"answer_id": 10808025,
"author": "Jesse Glick",
"author_id": 12916,
"author_profile": "https://Stackoverflow.com/users/12916",
"pm_score": 3,
"selected": false,
"text": "<p>Not exactly an answer but perhaps a follow-up question (original question was not explicit):</p>\n\n<p><code>readlink</code> is fine if you actually want to follow symlinks. But there is also a use case for merely normalizing <code>./</code> and <code>../</code> and <code>//</code> sequences, which can be done purely syntactically, <em>without</em> canonicalizing symlinks. <code>readlink</code> is no good for this, and neither is <code>realpath</code>.</p>\n\n<pre><code>for f in $paths; do (cd $f; pwd); done\n</code></pre>\n\n<p>works for existing paths, but breaks for others.</p>\n\n<p>A <code>sed</code> script would seem to be a good bet, except that you cannot iteratively replace sequences (<code>/foo/bar/baz/../..</code> -> <code>/foo/bar/..</code> -> <code>/foo</code>) without using something like Perl, which is not safe to assume on all systems, or using some ugly loop to compare the output of <code>sed</code> to its input.</p>\n\n<p>FWIW, a one-liner using Java (JDK 6+):</p>\n\n<pre><code>jrunscript -e 'for (var i = 0; i < arguments.length; i++) {println(new java.io.File(new java.io.File(arguments[i]).toURI().normalize()))}' $paths\n</code></pre>\n"
},
{
"answer_id": 18420863,
"author": "apottere",
"author_id": 1628477,
"author_profile": "https://Stackoverflow.com/users/1628477",
"pm_score": 3,
"selected": false,
"text": "<p>I'm late to the party, but this is the solution I've crafted after reading a bunch of threads like this:</p>\n\n<pre><code>resolve_dir() {\n (builtin cd `dirname \"${1/#~/$HOME}\"`'/'`basename \"${1/#~/$HOME}\"` 2>/dev/null; if [ $? -eq 0 ]; then pwd; fi)\n}\n</code></pre>\n\n<p>This will resolve the absolute path of $1, play nice with ~, keep symlinks in the path where they are, and it won't mess with your directory stack. It returns the full path or nothing if it doesn't exist. It expects $1 to be a directory and will probably fail if it's not, but that's an easy check to do yourself.</p>\n"
},
{
"answer_id": 19141198,
"author": "AsymLabs",
"author_id": 2839332,
"author_profile": "https://Stackoverflow.com/users/2839332",
"pm_score": 2,
"selected": false,
"text": "<p>Try our new Bash library product <a href=\"http://asymlabs.github.io/realpath-lib/\" rel=\"nofollow\">realpath-lib</a> that we have placed on GitHub for free and unencumbered use. It's thoroughly documented and makes a great learning tool. </p>\n\n<p>It resolves local, relative and absolute paths and doesn't have any dependencies except Bash 4+; so it should work just about anywhere. It's free, clean, simple and instructive.</p>\n\n<p>You can do:</p>\n\n<pre><code>get_realpath <absolute|relative|symlink|local file path>\n</code></pre>\n\n<p>This function is the core of the library:</p>\n\n<pre><code>function get_realpath() {\n\nif [[ -f \"$1\" ]]\nthen \n # file *must* exist\n if cd \"$(echo \"${1%/*}\")\" &>/dev/null\n then \n # file *may* not be local\n # exception is ./file.ext\n # try 'cd .; cd -;' *works!*\n local tmppwd=\"$PWD\"\n cd - &>/dev/null\n else \n # file *must* be local\n local tmppwd=\"$PWD\"\n fi\nelse \n # file *cannot* exist\n return 1 # failure\nfi\n\n# reassemble realpath\necho \"$tmppwd\"/\"${1##*/}\"\nreturn 0 # success\n\n}\n</code></pre>\n\n<p>It also contains functions to get_dirname, get_filename, get_ stemname and validate_path. Try it across platforms, and help to improve it.</p>\n"
},
{
"answer_id": 19147630,
"author": "Craig",
"author_id": 1489354,
"author_profile": "https://Stackoverflow.com/users/1489354",
"pm_score": 4,
"selected": false,
"text": "<p><code>readlink</code> is the bash standard for obtaining the absolute path. It also has the advantage of returning empty strings if paths or a path doesn't exist (given the flags to do so).</p>\n\n<p>To get the absolute path to a directory that may or may not exist, but who's parents do exist, use:</p>\n\n<pre><code>abspath=$(readlink -f $path)\n</code></pre>\n\n<p>To get the absolute path to a directory that must exist along with all parents:</p>\n\n<pre><code>abspath=$(readlink -e $path)\n</code></pre>\n\n<p>To canonicalise the given path and follow symlinks if they happen to exist, but otherwise ignore missing directories and just return the path anyway, it's:</p>\n\n<pre><code>abspath=$(readlink -m $path)\n</code></pre>\n\n<p>The only downside is that readlink will follow links. If you do not want to follow links, you can use this alternative convention:</p>\n\n<pre><code>abspath=$(cd ${path%/*} && echo $PWD/${path##*/})\n</code></pre>\n\n<p>That will chdir to the directory part of $path and print the current directory along with the file part of $path. If it fails to chdir, you get an empty string and an error on stderr.</p>\n"
},
{
"answer_id": 23945431,
"author": "coldlogic",
"author_id": 3689603,
"author_profile": "https://Stackoverflow.com/users/3689603",
"pm_score": -1,
"selected": false,
"text": "<p>I discovered today that you can use the <code>stat</code> command to resolve paths.</p>\n\n<p>So for a directory like \"~/Documents\":</p>\n\n<p>You can run this:</p>\n\n<p><code>stat -f %N ~/Documents</code></p>\n\n<p>To get the full path:</p>\n\n<p><code>/Users/me/Documents</code></p>\n\n<p>For symlinks, you can use the %Y format option:</p>\n\n<p><code>stat -f %Y example_symlink</code></p>\n\n<p>Which might return a result like:</p>\n\n<p><code>/usr/local/sbin/example_symlink</code></p>\n\n<p>The formatting options might be different on other versions of *NIX but these worked for me on OSX.</p>\n"
},
{
"answer_id": 29256624,
"author": "André Anjos",
"author_id": 712525,
"author_profile": "https://Stackoverflow.com/users/712525",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with <code>realpath</code> is that it is not available on BSD (or OSX for that matter). Here is a simple recipe extracted from <a href=\"http://www.linuxjournal.com/content/normalizing-path-names-bash\" rel=\"nofollow\">a rather old (2009) article from Linux Journal</a>, that is quite portable:</p>\n\n<pre><code>function normpath() {\n # Remove all /./ sequences.\n local path=${1//\\/.\\//\\/}\n\n # Remove dir/.. sequences.\n while [[ $path =~ ([^/][^/]*/\\.\\./) ]]; do\n path=${path/${BASH_REMATCH[0]}/}\n done\n echo $path\n}\n</code></pre>\n\n<p>Notice this variant also does <strong>not</strong> require the path to exist.</p>\n"
},
{
"answer_id": 31086901,
"author": "ϹοδεMεδιϲ",
"author_id": 83005,
"author_profile": "https://Stackoverflow.com/users/83005",
"pm_score": 2,
"selected": false,
"text": "<p>Based on @Andre's answer, I might have a slightly better version, in case someone is after a loop-free, completely string-manipulation based solution. It is also useful for those who don't want to dereference any symlinks, which is the downside of using <code>realpath</code> or <code>readlink -f</code>.</p>\n\n<p>It works on bash versions 3.2.25 and higher.</p>\n\n<pre><code>shopt -s extglob\n\nnormalise_path() {\n local path=\"$1\"\n # get rid of /../ example: /one/../two to /two\n path=\"${path//\\/*([!\\/])\\/\\.\\./}\"\n # get rid of /./ and //* example: /one/.///two to /one/two\n path=\"${path//@(\\/\\.\\/|\\/+(\\/))//}\"\n # remove the last '/.'\n echo \"${path%%/.}\"\n}\n\n$ normalise_path /home/codemedic/../codemedic////.config\n/home/codemedic/.config\n</code></pre>\n"
},
{
"answer_id": 34754899,
"author": "Artisan72",
"author_id": 3862511,
"author_profile": "https://Stackoverflow.com/users/3862511",
"pm_score": -1,
"selected": false,
"text": "<p>A simple solution using <code>node.js</code>:</p>\n\n<pre><code>#!/usr/bin/env node\nprocess.stdout.write(require('path').resolve(process.argv[2]));\n</code></pre>\n"
},
{
"answer_id": 35996728,
"author": "Gilbert",
"author_id": 693294,
"author_profile": "https://Stackoverflow.com/users/693294",
"pm_score": 4,
"selected": false,
"text": "<p>Old question, but there is much simpler way <i>if you are dealing with full path names</i> at the shell level:</p>\n\n<pre> abspath=\"$( cd \"$path\" && pwd )\"</pre>\n\n<p>As the cd happens in a subshell it does not impact the main script.</p>\n\n<p>Two variations, supposing your shell built-in commands accept -L and -P, are:</p>\n\n<pre>\n abspath=\"$( cd -P \"$path\" && pwd -P )\" #physical path with resolved symlinks\n abspath=\"$( cd -L \"$path\" && pwd -L )\" #logical path preserving symlinks\n</pre>\n\n<p>Personally, I rarely need this later approach unless I'm fascinated with symbolic links for some reason.</p>\n\n<p>FYI: variation on obtaining the starting directory of a script which works even if the script changes it's current directory later on.</p>\n\n<pre>name0=\"$(basename \"$0\")\"; #base name of script\ndir0=\"$( cd \"$( dirname \"$0\" )\" && pwd )\"; #absolute starting dir</pre>\n\n<p>The use of CD assures you always have the absolute directory, even if the script is run by commands such as ./script.sh which, without the cd/pwd, often gives just .. Useless if the script does a cd later on. </p>\n"
},
{
"answer_id": 36045150,
"author": "Edward Falk",
"author_id": 338479,
"author_profile": "https://Stackoverflow.com/users/338479",
"pm_score": 0,
"selected": false,
"text": "<p>Based on loveborg's excellent python snippet, I wrote this:</p>\n\n<pre><code>#!/bin/sh\n\n# Version of readlink that follows links to the end; good for Mac OS X\n\nfor file in \"$@\"; do\n while [ -h \"$file\" ]; do\n l=`readlink $file`\n case \"$l\" in\n /*) file=\"$l\";;\n *) file=`dirname \"$file\"`/\"$l\"\n esac\n done\n #echo $file\n python -c \"import os,sys; print os.path.abspath(sys.argv[1])\" \"$file\"\ndone\n</code></pre>\n"
},
{
"answer_id": 48794465,
"author": "user240515",
"author_id": 240515,
"author_profile": "https://Stackoverflow.com/users/240515",
"pm_score": 0,
"selected": false,
"text": "<pre><code>FILEPATH=\"file.txt\"\necho $(realpath $(dirname $FILEPATH))/$(basename $FILEPATH)\n</code></pre>\n\n<p>This works even if the file doesn't exist. It does require the directory containing the file to exist.</p>\n"
},
{
"answer_id": 49208182,
"author": "bestOfSong",
"author_id": 5010054,
"author_profile": "https://Stackoverflow.com/users/5010054",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an ancient question. I'm still offering an alternative. Recently I met the same issue and found no existing and portable command to do that. So I wrote the following shell script which includes a function that can do the trick.</p>\n\n<pre><code>#! /bin/sh \n\nfunction normalize {\n local rc=0\n local ret\n\n if [ $# -gt 0 ] ; then\n # invalid\n if [ \"x`echo $1 | grep -E '^/\\.\\.'`\" != \"x\" ] ; then\n echo $1\n return -1\n fi\n\n # convert to absolute path\n if [ \"x`echo $1 | grep -E '^\\/'`\" == \"x\" ] ; then\n normalize \"`pwd`/$1\"\n return $?\n fi\n\n ret=`echo $1 | sed 's;/\\.\\($\\|/\\);/;g' | sed 's;/[^/]*[^/.]\\+[^/]*/\\.\\.\\($\\|/\\);/;g'`\n else\n read line\n normalize \"$line\"\n return $?\n fi\n\n if [ \"x`echo $ret | grep -E '/\\.\\.?(/|$)'`\" != \"x\" ] ; then\n ret=`normalize \"$ret\"`\n rc=$?\n fi\n\n echo \"$ret\"\n return $rc\n}\n</code></pre>\n\n<p><a href=\"https://gist.github.com/bestofsong/8830bdf3e5eb9461d27313c3c282868c\" rel=\"nofollow noreferrer\">https://gist.github.com/bestofsong/8830bdf3e5eb9461d27313c3c282868c</a></p>\n"
},
{
"answer_id": 50361385,
"author": "David Blevins",
"author_id": 190816,
"author_profile": "https://Stackoverflow.com/users/190816",
"pm_score": 1,
"selected": false,
"text": "<p>I needed a solution that would do all three:</p>\n\n<ul>\n<li>Work on a stock Mac. <code>realpath</code> and <code>readlink -f</code> are addons</li>\n<li>Resolve symlinks</li>\n<li>Have error handling</li>\n</ul>\n\n<p>None of the answers had both #1 and #2. I added #3 to save others any further yak-shaving.</p>\n\n<pre><code>#!/bin/bash\n\nP=\"${1?Specify a file path}\"\n\n[ -e \"$P\" ] || { echo \"File does not exist: $P\"; exit 1; }\n\nwhile [ -h \"$P\" ] ; do\n ls=\"$(ls -ld \"$P\")\"\n link=\"$(expr \"$ls\" : '.*-> \\(.*\\)$')\"\n expr \"$link\" : '/.*' > /dev/null &&\n P=\"$link\" ||\n P=\"$(dirname \"$P\")/$link\"\ndone\necho \"$(cd \"$(dirname \"$P\")\"; pwd)/$(basename \"$P\")\"\n</code></pre>\n\n<p>Here is a short test case with some twisted spaces in the paths to fully exercise the quoting</p>\n\n<pre><code>mkdir -p \"/tmp/test/ first path \"\nmkdir -p \"/tmp/test/ second path \"\necho \"hello\" > \"/tmp/test/ first path / red .txt \"\nln -s \"/tmp/test/ first path / red .txt \" \"/tmp/test/ second path / green .txt \"\n\ncd \"/tmp/test/ second path \"\nfullpath \" green .txt \"\ncat \" green .txt \"\n</code></pre>\n"
},
{
"answer_id": 61632893,
"author": "Jeffrey Cash",
"author_id": 6232717,
"author_profile": "https://Stackoverflow.com/users/6232717",
"pm_score": 2,
"selected": false,
"text": "<p>I made a builtin-only function to handle this with a focus on highest possible performance (for fun). It does not resolve symlinks, so it is basically the same as <code>realpath -sm</code>.</p>\n\n<pre><code>## A bash-only mimic of `realpath -sm`. \n## Give it path[s] as argument[s] and it will convert them to clean absolute paths\nabspath () { \n ${*+false} && { >&2 echo $FUNCNAME: missing operand; return 1; };\n local c s p IFS='/'; ## path chunk, absolute path, input path, IFS for splitting paths into chunks\n local -i r=0; ## return value\n\n for p in \"$@\"; do\n case \"$p\" in ## Check for leading backslashes, identify relative/absolute path\n '') ((r|=1)); continue;;\n //[!/]*) >&2 echo \"paths =~ ^//[^/]* are impl-defined; not my problem\"; ((r|=2)); continue;;\n /*) ;;\n *) p=\"$PWD/$p\";; ## Prepend the current directory to form an absolute path\n esac\n\n s='';\n for c in $p; do ## Let IFS split the path at '/'s\n case $c in ### NOTE: IFS is '/'; so no quotes needed here\n ''|.) ;; ## Skip duplicate '/'s and '/./'s\n ..) s=\"${s%/*}\";; ## Trim the previous addition to the absolute path string\n *) s+=/$c;; ### NOTE: No quotes here intentionally. They make no difference, it seems\n esac;\n done;\n\n echo \"${s:-/}\"; ## If xpg_echo is set, use `echo -E` or `printf $'%s\\n'` instead\n done\n return $r;\n}\n</code></pre>\n\n<p>Note: This function does not handle paths starting with <code>//</code>, as exactly two double slashes at the start of a path are implementation-defined behavior. However, it handles <code>/</code>, <code>///</code>, and so on just fine.</p>\n\n<p>This function seems to handle all edge cases properly, but there might still be some out there that I haven't dealt with. </p>\n\n<p>Performance Note: when called with thousands of arguments, <code>abspath</code> runs about 10x slower than <code>realpath -sm</code>; when called with a single argument, <code>abspath</code> runs >110x faster than <code>realpath -sm</code> on my machine, mostly due to not needing to execute a new program every time.</p>\n"
},
{
"answer_id": 66468913,
"author": "David Pi",
"author_id": 14500150,
"author_profile": "https://Stackoverflow.com/users/14500150",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want to normalize a path, existed or not existed, without touching the file system, without resolving any links, and without external utils, here is a pure <strong>Bash</strong> function translated from Python's <code>posixpath.normpath</code>.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env bash\n\n# Normalize path, eliminating double slashes, etc.\n# Usage: new_path="$(normpath "${old_path}")"\n# Translated from Python's posixpath.normpath:\n# https://github.com/python/cpython/blob/master/Lib/posixpath.py#L337\nnormpath() {\n local IFS=/ initial_slashes='' comp comps=()\n if [[ $1 == /* ]]; then\n initial_slashes='/'\n [[ $1 == //* && $1 != ///* ]] && initial_slashes='//'\n fi\n for comp in $1; do\n [[ -z ${comp} || ${comp} == '.' ]] && continue\n if [[ ${comp} != '..' || (-z ${initial_slashes} && ${#comps[@]} -eq 0) || (\\\n ${#comps[@]} -gt 0 && ${comps[-1]} == '..') ]]; then\n comps+=("${comp}")\n elif ((${#comps[@]})); then\n unset 'comps[-1]'\n fi\n done\n comp="${initial_slashes}${comps[*]}"\n printf '%s\\n' "${comp:-.}"\n}\n</code></pre>\n<p>Examples:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>new_path="$(normpath '/foo/bar/..')"\necho "${new_path}"\n# /foo\n\nnormpath "relative/path/with trailing slashs////"\n# relative/path/with trailing slashs\n\nnormpath "////a/../lot/././/mess////./here/./../"\n# /lot/mess\n\nnormpath ""\n# .\n# (empty path resolved to dot)\n</code></pre>\n<p>Personally, I cannot understand why Shell, a language often used for manipulating files, doesn't offer basic functions to deal with paths. In python, we have nice libraries like os.path or pathlib, which offers a whole bunch of tools to extract filename, extension, basename, path segments, split or join paths, to get absolute or normalized paths, to determine relations between paths, to do everything without much brain. And they take care of edge cases, and they're reliable. In Shell, to do any of these, either we call external executables, or we have to reinvent wheels with these extremely rudimentary and arcane syntaxes...</p>\n"
},
{
"answer_id": 70291479,
"author": "Fabian Lehmann",
"author_id": 17636526,
"author_profile": "https://Stackoverflow.com/users/17636526",
"pm_score": 0,
"selected": false,
"text": "<p>Since none of the presented solutions worked for me, in the case where a file does not exist, I implemented my idea.\nThe solution of André Anjos had the problem that paths beginning with ../../ were resolved wrongly. For example ../../a/b/ became a/b/.</p>\n<pre><code>function normalize_rel_path(){\n local path=$1\n result=""\n IFS='/' read -r -a array <<< "$path"\n i=0\n for (( idx=${#array[@]}-1 ; idx>=0 ; idx-- )) ; do\n c="${array[idx]}"\n if [ -z "$c" ] || [[ "$c" == "." ]];\n then\n continue\n fi\n if [[ "$c" == ".." ]]\n then\n i=$((i+1))\n elif [ "$i" -gt "0" ];\n then\n i=$((i-1))\n else\n if [ -z "$result" ];\n then\n result=$c\n else\n result=$c/$result\n fi\n fi\n done\n while [ "$i" -gt "0" ]; do\n i=$((i-1))\n result="../"$result\n done \n unset IFS\n echo $result\n}\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21132/"
] |
I want to transform `/foo/bar/..` to `/foo`
Is there a bash command which does this?
---
Edit: in my practical case, the directory does exist.
|
if you're wanting to chomp part of a filename from the path, "dirname" and "basename" are your friends, and "realpath" is handy too.
```
dirname /foo/bar/baz
# /foo/bar
basename /foo/bar/baz
# baz
dirname $( dirname /foo/bar/baz )
# /foo
realpath ../foo
# ../foo: No such file or directory
realpath /tmp/../tmp/../tmp
# /tmp
```
**`realpath` alternatives**
If `realpath` is not supported by your shell, you can try
```
readlink -f /path/here/..
```
Also
```
readlink -m /path/there/../../
```
Works the same as
```
realpath -s /path/here/../../
```
in that the path doesn't need to exist to be normalized.
|
284,678 |
<p>I have an application where every now and then I'm getting a strange error.
This is the piece of code:</p>
<pre><code>Dim XMLWriter As New System.Xml.XmlTextWriter(Me.Context.Response.OutputStream, Encoding.UTF8)
XMLWriter.WriteStartDocument()
XMLWriter.WriteStartElement("Status")
Message.SerializeToXML(XMLWriter)
XMLWriter.WriteEndElement()
XMLWriter.WriteEndDocument()
XMLWriter.Flush()
XMLWriter.Close()
</code></pre>
<p>The error i'm getting is:
Message: Object reference not set to an instance of an object.</p>
<p>on line XMLWriter.Flush();</p>
<p>To make things more fun, this is absolutely non-reproducible. It just happens every now and then....</p>
<p>Since it's happening when flushing the XML i'm guessing the Object that is now null has to be the Response.OutputStream.</p>
<p>This is the relevant part of the stack trace:</p>
<pre><code>Description:
An unhandled exception occurred and the process was terminated.
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
StackTrace: at System.Web.HttpWriter.BufferData(Byte[] data, Int32 offset, Int32 size, Boolean needToCopyData)
at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.Xml.XmlTextWriter.Flush()
at RequestData.CompleteRequest(MessageBase Message) in RequestData.vb:line 142
</code></pre>
<p>My question is, in what cases could this be happening?
This server is a long-polling server, so the client asks for something, and I may not answer for 30 seconds...
Is it possible that this Stream will become Null if the client disconnects (ie. closes the browser window)?</p>
<p>Any other ideas? (any pointers appreciated)</p>
|
[
{
"answer_id": 284687,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 0,
"selected": false,
"text": "<p>No, if it happens when you call Flush, that's way later than the only time <code>Context.Response.OutputStream</code> is actually referenced. The value is fetched in the call to the <code>XmlTextWriter</code> constructor, and then not looked at again.</p>\n\n<p>Do you have any more information from the stack trace?</p>\n"
},
{
"answer_id": 320185,
"author": "Generic Error",
"author_id": 40944,
"author_profile": "https://Stackoverflow.com/users/40944",
"pm_score": 0,
"selected": false,
"text": "<p>The call to Flush is what will cause anything cached in memory to be written out to the stream and ultimately the client so yes, it may be the problem.</p>\n\n<p>You mentioned that the request is expected to take a long time to execute so it may be possible that ASP.Net or IIS are timing you out too early. I would suggest having a look at the <a href=\"http://msdn.microsoft.com/en-us/library/e1f13641.aspx\" rel=\"nofollow noreferrer\">executionTimeout property in the web.config</a> and similar settings.</p>\n"
},
{
"answer_id": 344439,
"author": "Brian Rudolph",
"author_id": 33114,
"author_profile": "https://Stackoverflow.com/users/33114",
"pm_score": 2,
"selected": true,
"text": "<p>Reflector gives this:</p>\n\n<pre><code>private void BufferData(byte[] data, int offset, int size, bool needToCopyData)\n{\n int num;\n if (this._lastBuffer != null)\n {\n num = this._lastBuffer.Append(data, offset, size);\n size -= num;\n offset += num;\n }\n else if ((!needToCopyData && (offset == 0)) && !this._responseBufferingOn)\n {\n this._buffers.Add(new HttpResponseBufferElement(data, size));\n return;\n }\n while (size > 0)\n {\n this._lastBuffer = this.CreateNewMemoryBufferElement();\n this._buffers.Add(this._lastBuffer);\n num = this._lastBuffer.Append(data, offset, size);\n offset += num;\n size -= num;\n }\n}\n</code></pre>\n\n<p>The only object that is not null checked, initialized or referenced through another method(which would show in the stack trace) is this._buffers. The only place it is set to null in that class is in RecycleBufferElements() which if you dig deeper can occur when the client disconnects.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
I have an application where every now and then I'm getting a strange error.
This is the piece of code:
```
Dim XMLWriter As New System.Xml.XmlTextWriter(Me.Context.Response.OutputStream, Encoding.UTF8)
XMLWriter.WriteStartDocument()
XMLWriter.WriteStartElement("Status")
Message.SerializeToXML(XMLWriter)
XMLWriter.WriteEndElement()
XMLWriter.WriteEndDocument()
XMLWriter.Flush()
XMLWriter.Close()
```
The error i'm getting is:
Message: Object reference not set to an instance of an object.
on line XMLWriter.Flush();
To make things more fun, this is absolutely non-reproducible. It just happens every now and then....
Since it's happening when flushing the XML i'm guessing the Object that is now null has to be the Response.OutputStream.
This is the relevant part of the stack trace:
```
Description:
An unhandled exception occurred and the process was terminated.
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
StackTrace: at System.Web.HttpWriter.BufferData(Byte[] data, Int32 offset, Int32 size, Boolean needToCopyData)
at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.Xml.XmlTextWriter.Flush()
at RequestData.CompleteRequest(MessageBase Message) in RequestData.vb:line 142
```
My question is, in what cases could this be happening?
This server is a long-polling server, so the client asks for something, and I may not answer for 30 seconds...
Is it possible that this Stream will become Null if the client disconnects (ie. closes the browser window)?
Any other ideas? (any pointers appreciated)
|
Reflector gives this:
```
private void BufferData(byte[] data, int offset, int size, bool needToCopyData)
{
int num;
if (this._lastBuffer != null)
{
num = this._lastBuffer.Append(data, offset, size);
size -= num;
offset += num;
}
else if ((!needToCopyData && (offset == 0)) && !this._responseBufferingOn)
{
this._buffers.Add(new HttpResponseBufferElement(data, size));
return;
}
while (size > 0)
{
this._lastBuffer = this.CreateNewMemoryBufferElement();
this._buffers.Add(this._lastBuffer);
num = this._lastBuffer.Append(data, offset, size);
offset += num;
size -= num;
}
}
```
The only object that is not null checked, initialized or referenced through another method(which would show in the stack trace) is this.\_buffers. The only place it is set to null in that class is in RecycleBufferElements() which if you dig deeper can occur when the client disconnects.
|
284,679 |
<p>What's the easiest way to get the data for a single table, delete a single table or break up the whole dump file into files each containing individual tables? I usually end up doing a lot of vi regex munging, but I bet there are easier ways to do these things with awk/perl, etc. The first page of Google results brings back a bunch of non-working perl scripts.</p>
|
[
{
"answer_id": 284702,
"author": "J.D. Fitz.Gerald",
"author_id": 11542,
"author_profile": "https://Stackoverflow.com/users/11542",
"pm_score": 3,
"selected": false,
"text": "<p>Save yourself a lot of hassle and use <code>mysqldump -T</code> if you can.</p>\n\n<p>From the <a href=\"http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_tab\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>--tab=path, -T path</p>\n \n <p>Produce tab-separated data files. For each dumped table, mysqldump\n creates a tbl_name.sql file that contains the CREATE TABLE statement\n that creates the table, and a tbl_name.txt file that contains its\n data. The option value is the directory in which to write the files.</p>\n \n <p>By default, the .txt data files are formatted using tab characters\n between column values and a newline at the end of each line. The\n format can be specified explicitly using the --fields-xxx and\n --lines-terminated-by options.</p>\n \n <p>Note<br> This option should be used only when mysqldump is run on the\n same machine as the mysqld server. You must have the FILE privilege,\n and the server must have permission to write files in the directory\n that you specify.</p>\n</blockquote>\n"
},
{
"answer_id": 285089,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 4,
"selected": false,
"text": "<p>When I need to pull a single table from an sql dump, I use a combination of grep, head and tail.</p>\n\n<p>Eg:</p>\n\n<pre><code>grep -n \"CREATE TABLE\" dump.sql\n</code></pre>\n\n<p>This then gives you the line numbers for each one, so if your table is on line 200 and the one after is on line 269, I do:</p>\n\n<pre><code>head -n 268 dump.sql > tophalf.sql\ntail -n 69 tophalf.sql > yourtable.sql\n</code></pre>\n\n<p>I would imagine you could extend upon those principles to knock up a script that would split the whole thing down into one file per table.</p>\n\n<p>Anyone want a go doing it here?</p>\n\n<p>Another bit that might help start a bash loop going:</p>\n\n<pre><code>grep -n \"CREATE TABLE \" dump.sql | tr ':`(' ' ' | awk '{print $1, $4}'\n</code></pre>\n\n<p>That gives you a nice list of line numbers and table names like:</p>\n\n<pre><code>200 FooTable\n269 BarTable\n</code></pre>\n"
},
{
"answer_id": 1593161,
"author": "elhoim",
"author_id": 171469,
"author_profile": "https://Stackoverflow.com/users/171469",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.maatkit.org/\" rel=\"nofollow noreferrer\">Maatkit</a> seems quite appropriate for this with <a href=\"http://www.maatkit.org/doc/mk-parallel-dump.html\" rel=\"nofollow noreferrer\">mk-parallel-dump</a> and <a href=\"http://www.maatkit.org/doc/mk-parallel-restore.html\" rel=\"nofollow noreferrer\">mk-parallel-restore</a>.</p>\n"
},
{
"answer_id": 2242970,
"author": "kv.",
"author_id": 260731,
"author_profile": "https://Stackoverflow.com/users/260731",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://kedar.nitty-witty.com/blog/mydumpsplitter-extract-tables-from-mysql-dump-shell-script/\" rel=\"nofollow noreferrer\">This shell script</a> will grab the tables you want and pass them to <code>splitted.sql</code>.</p>\n\n<p>It’s capable of understanding regular expressions as I’ve added a <code>sed -r</code> option.</p>\n\n<p>Also MyDumpSplitter can split the dump into individual table dumps.</p>\n"
},
{
"answer_id": 17317357,
"author": "jodu",
"author_id": 1758422,
"author_profile": "https://Stackoverflow.com/users/1758422",
"pm_score": 0,
"selected": false,
"text": "<p>I am a bit late on that one, but if it can help anyone, I had to split a huge SQL dump file in order to import the data to another Mysql server.\nwhat I ended up doing was splitting the dump file using the system command. </p>\n\n<p><strong>split -l 1000 import.sql splited_file</strong></p>\n\n<p>The above will split the sql file every 1000 lines.</p>\n\n<p>Hope this helps someone</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
What's the easiest way to get the data for a single table, delete a single table or break up the whole dump file into files each containing individual tables? I usually end up doing a lot of vi regex munging, but I bet there are easier ways to do these things with awk/perl, etc. The first page of Google results brings back a bunch of non-working perl scripts.
|
When I need to pull a single table from an sql dump, I use a combination of grep, head and tail.
Eg:
```
grep -n "CREATE TABLE" dump.sql
```
This then gives you the line numbers for each one, so if your table is on line 200 and the one after is on line 269, I do:
```
head -n 268 dump.sql > tophalf.sql
tail -n 69 tophalf.sql > yourtable.sql
```
I would imagine you could extend upon those principles to knock up a script that would split the whole thing down into one file per table.
Anyone want a go doing it here?
Another bit that might help start a bash loop going:
```
grep -n "CREATE TABLE " dump.sql | tr ':`(' ' ' | awk '{print $1, $4}'
```
That gives you a nice list of line numbers and table names like:
```
200 FooTable
269 BarTable
```
|
284,716 |
<p>I am working on an automated testing app, and am currently in the process of writing a function that compares values between two XML files that should be identical, but may not be. Here is a sample of the XML I'm trying to process:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<report xmlns="http://www.**.com/**">
<subreport name="RBDReport">
<record rowNumber="1">
<field name="Time">
<value>0</value>
</field>
<field name="Reliability">
<value>1.000000</value>
</field>
<field name="Unreliability">
<value>0.000000</value>
</field>
<field name="Availability">
<value> </value>
</field>
<field name="Unavailability">
<value> </value>
</field>
<field name="Failure Rate">
<value>N/A</value>
</field>
<field name="Number of Failures">
<value> </value>
</field>
<field name="Total Downtime">
<value> </value>
</field>
</record>
</code></pre>
<p>(Note there may be multiple <code><subreport></code> elements and within those, multiple <code><record></code> elements.)</p>
<p>What I'd like is to extract the <code><value></code> tags of two documents and then compare their values. That part I know how to do. The problem is the extraction itself.</p>
<p>Since I'm stuck in C++, I'm using MSXML, and have written a wrapper to allow my app to abstract away the actual XML manipulation, in case I ever decide to change my data format.</p>
<p>That wrapper, CSimpleXMLParser, loads an XML document and sets its "top record" to the document element of the XML document. (CRecord being an abstract class with CXMLRecord one of its subclasses, and which gives access to child records singularly or by group, and also allowing access to the "value" of the Record (values for child elements or attributes, in the case of CXMLRecord.) A CXMLRecord contains an MSXML::MSXMLDOMNodePtr and a pointer to an instance of a CSimpleXMLParser.) The wrapper also contains utility functions for returning children, which the CXMLRecord uses to return its child records.</p>
<p>In my code, I do the following (trying to return all <code><subreport></code> nodes just to see if it works):</p>
<pre><code>CSimpleXMLParser parserReportData;
parserReportData.OpenXMLDocument(strPathToXML);
bool bGetChildrenSuccess = parserReportData.GetFirstRecord()->GetChildRecords(listpChildren, _T("subreport"));
</code></pre>
<p>This is always returning false. The meat of the implementation of CXMLRecord::GetChildRecords() is basically</p>
<pre><code>MSXML2::IXMLDOMNodeListPtr pListChildren = m_pParser->SelectNodes(strPath, m_pXMLNode);
if (pListChildren->Getlength() == 0)
{
return false;
}
for (long l = 0; l < pListChildren->Getlength(); ++l)
{
listRecords.push_back(new CXMLRecord(pListChildren->Getitem(l), m_pParser));
}
return true;
</code></pre>
<p>And CSimpleXMLParser::SelectNodes() is:</p>
<pre><code>MSXML2::IXMLDOMNodeListPtr CSimpleXMLParser::SelectNodes(LPCTSTR strXPathFilter, MSXML2::IXMLDOMNodePtr pXMLNode)
{
return pXMLNode->selectNodes(_bstr_t(strXPathFilter));
}
</code></pre>
<p>When run, the top record is definitely being set to the <code><report></code> element properly. I can do all sorts of things with it, like getting its child nodes (through the MSXML interface, not through my wrapper) or its name, etc. I know that my wrapper <em>can</em> work, because I use it elsewhere in the app for parsing an XML configuration file, and that works flawlessly.</p>
<p>I thought maybe I was doing something faulty with the XPath query expression, but every permutation I could think of gives no joy. The <code>MSXML::IXMLDOMNodeListPtr</code> returned by <code>IXMLDOMNodePtr::SelectNodes()</code> is always of length 0 when I try to deal with this XML file.</p>
<p>This is driving me crazy.</p>
|
[
{
"answer_id": 284723,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 0,
"selected": false,
"text": "<p>I see no reference to a namespace when you're selecting nodes. I'd expect this to be the fundamental problem.</p>\n"
},
{
"answer_id": 284734,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>I'm used to doing this with .NET's XmlDocument objects, but I think the effect is the same here:</p>\n\n<p>If the XML document includes a namespace -- even an unnamed one -- then the Xpath query has to use one as well. So, you'll have to add the namespace to the XMLDoument which you might as well give a name in the code, and the include the prefix in the XPATH query (it doesn't matter that the prefixes are different between the xml document and the xpath, as long as the namespaces sort it out)</p>\n\n<p>SO, while you are using an XPath like <code>/report/subreport/record/field/value</code>, you actually need to first set the namespace of your document:</p>\n\n<pre><code> pXMLDoc->setProperty(_bstr_t(\"SelectionNamespaces\"),\n _bstr_t(\"xmlns:r=\"http://www.**.com/**\"));\n</code></pre>\n\n<p>and then <code>selectNodes()</code> using <code>/r:report/r:subreport/r:record/r:field/r:value</code></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24529/"
] |
I am working on an automated testing app, and am currently in the process of writing a function that compares values between two XML files that should be identical, but may not be. Here is a sample of the XML I'm trying to process:
```
<?xml version="1.0" encoding="utf-8"?>
<report xmlns="http://www.**.com/**">
<subreport name="RBDReport">
<record rowNumber="1">
<field name="Time">
<value>0</value>
</field>
<field name="Reliability">
<value>1.000000</value>
</field>
<field name="Unreliability">
<value>0.000000</value>
</field>
<field name="Availability">
<value> </value>
</field>
<field name="Unavailability">
<value> </value>
</field>
<field name="Failure Rate">
<value>N/A</value>
</field>
<field name="Number of Failures">
<value> </value>
</field>
<field name="Total Downtime">
<value> </value>
</field>
</record>
```
(Note there may be multiple `<subreport>` elements and within those, multiple `<record>` elements.)
What I'd like is to extract the `<value>` tags of two documents and then compare their values. That part I know how to do. The problem is the extraction itself.
Since I'm stuck in C++, I'm using MSXML, and have written a wrapper to allow my app to abstract away the actual XML manipulation, in case I ever decide to change my data format.
That wrapper, CSimpleXMLParser, loads an XML document and sets its "top record" to the document element of the XML document. (CRecord being an abstract class with CXMLRecord one of its subclasses, and which gives access to child records singularly or by group, and also allowing access to the "value" of the Record (values for child elements or attributes, in the case of CXMLRecord.) A CXMLRecord contains an MSXML::MSXMLDOMNodePtr and a pointer to an instance of a CSimpleXMLParser.) The wrapper also contains utility functions for returning children, which the CXMLRecord uses to return its child records.
In my code, I do the following (trying to return all `<subreport>` nodes just to see if it works):
```
CSimpleXMLParser parserReportData;
parserReportData.OpenXMLDocument(strPathToXML);
bool bGetChildrenSuccess = parserReportData.GetFirstRecord()->GetChildRecords(listpChildren, _T("subreport"));
```
This is always returning false. The meat of the implementation of CXMLRecord::GetChildRecords() is basically
```
MSXML2::IXMLDOMNodeListPtr pListChildren = m_pParser->SelectNodes(strPath, m_pXMLNode);
if (pListChildren->Getlength() == 0)
{
return false;
}
for (long l = 0; l < pListChildren->Getlength(); ++l)
{
listRecords.push_back(new CXMLRecord(pListChildren->Getitem(l), m_pParser));
}
return true;
```
And CSimpleXMLParser::SelectNodes() is:
```
MSXML2::IXMLDOMNodeListPtr CSimpleXMLParser::SelectNodes(LPCTSTR strXPathFilter, MSXML2::IXMLDOMNodePtr pXMLNode)
{
return pXMLNode->selectNodes(_bstr_t(strXPathFilter));
}
```
When run, the top record is definitely being set to the `<report>` element properly. I can do all sorts of things with it, like getting its child nodes (through the MSXML interface, not through my wrapper) or its name, etc. I know that my wrapper *can* work, because I use it elsewhere in the app for parsing an XML configuration file, and that works flawlessly.
I thought maybe I was doing something faulty with the XPath query expression, but every permutation I could think of gives no joy. The `MSXML::IXMLDOMNodeListPtr` returned by `IXMLDOMNodePtr::SelectNodes()` is always of length 0 when I try to deal with this XML file.
This is driving me crazy.
|
I'm used to doing this with .NET's XmlDocument objects, but I think the effect is the same here:
If the XML document includes a namespace -- even an unnamed one -- then the Xpath query has to use one as well. So, you'll have to add the namespace to the XMLDoument which you might as well give a name in the code, and the include the prefix in the XPATH query (it doesn't matter that the prefixes are different between the xml document and the xpath, as long as the namespaces sort it out)
SO, while you are using an XPath like `/report/subreport/record/field/value`, you actually need to first set the namespace of your document:
```
pXMLDoc->setProperty(_bstr_t("SelectionNamespaces"),
_bstr_t("xmlns:r="http://www.**.com/**"));
```
and then `selectNodes()` using `/r:report/r:subreport/r:record/r:field/r:value`
|
284,722 |
<p>I'm trying to insert a comment character into a string something similar to this:</p>
<pre><code>-CreateVideoTracker VT1 "vt name"
</code></pre>
<p>becomes</p>
<pre><code>-CreateVideoTracker VT1 # "vt name"
</code></pre>
<p>The VT1 word can actually be anything, so I'm using the regex</p>
<pre><code>$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g;
</code></pre>
<p>which gives me the result:</p>
<pre><code>-CreateVideoTracker w #T1 "vt name"
</code></pre>
<p>Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?</p>
|
[
{
"answer_id": 284739,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": true,
"text": "<pre><code>$line =~ s/^(\\-CreateVideoTracker)\\s+(\\w+)/$1 $2 #/;\n</code></pre>\n\n<p>The bracketed expressions (known as \"capture buffers\") in the first half of the regexp are referenced as <code>$1</code>, <code>$2</code>. etc in the second half.</p>\n"
},
{
"answer_id": 285921,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the <code>\\K</code> feature of Perl 5.10 regexs;</p>\n\n<pre><code>$line=~s/^\\-CreateVideoTracker\\s+\\w+\\K/ #/;\n</code></pre>\n"
},
{
"answer_id": 286390,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>You have two problems in:</p>\n\n<pre><code>$line =~ s/\\-CreateVideoTracker \\w/\\-CreateVideoTracker \\w # /g;\n</code></pre>\n\n<p>First, you want to match multiple character words, so in the left side, \\w should be \\w+.\nSecond, you can't use patterns like \\w on the right side; instead capture what you want on the left with () and put it on the right with $1, $2, etc.:</p>\n\n<pre><code>$line =~ s/\\-CreateVideoTracker (\\w+)/\\-CreateVideoTracker $1 # /g;\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23504/"
] |
I'm trying to insert a comment character into a string something similar to this:
```
-CreateVideoTracker VT1 "vt name"
```
becomes
```
-CreateVideoTracker VT1 # "vt name"
```
The VT1 word can actually be anything, so I'm using the regex
```
$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g;
```
which gives me the result:
```
-CreateVideoTracker w #T1 "vt name"
```
Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?
|
```
$line =~ s/^(\-CreateVideoTracker)\s+(\w+)/$1 $2 #/;
```
The bracketed expressions (known as "capture buffers") in the first half of the regexp are referenced as `$1`, `$2`. etc in the second half.
|
284,740 |
<p>What is the preferred way to insert strings that can contain both single and double quotes (",') into MySql using DBI? For example, <code>$val1</code> and <code>$val2</code> can contain quotes:</p>
<pre><code>my $dbh = DBI->connect( ... );
my $sql = "insert into tbl_name(col_one,col_two) values($val1, $val2)";
my $sth = $dbh->prepare($sql);
$sth->execute();
</code></pre>
|
[
{
"answer_id": 284758,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 6,
"selected": true,
"text": "<p>Use a bound query using </p>\n\n<pre><code>$sth = $dbh->prepare(\"insert into tbl_name(col_one,col_two) values(?,?)\");\n$sth->execute($val1, $val2);\n</code></pre>\n\n<p>If you use bound variables, everything is escaped for you.</p>\n\n<p>Update: Changed my example to correspond with the example edited into the question.</p>\n\n<p>Update: I don't know why Adam deleted his answer, but if for some reason you can't use bound variables (aka \"placeholders\"), you can also use <code>$dbh->quote($var)</code> on the variable. For example:</p>\n\n<pre><code>$sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(q(\"Don't\"));\n</code></pre>\n"
},
{
"answer_id": 284762,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>quote()</code> method. It will intelligently handle the quoting for you. Example from the <a href=\"http://search.cpan.org/~timb/DBI/DBI.pm#quote\" rel=\"nofollow noreferrer\">docs</a>:</p>\n\n<pre><code>$sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(\"Don't\");\n</code></pre>\n\n<p>Slightly modified to have both types of quotes:</p>\n\n<pre><code>$sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(q(\"Don't\"));\n</code></pre>\n"
},
{
"answer_id": 287516,
"author": "Aquatoad",
"author_id": 34229,
"author_profile": "https://Stackoverflow.com/users/34229",
"pm_score": 2,
"selected": false,
"text": "<p>One small caveat on the bound placeholders, I build a rather large database-loading script that initially used bound placeholders in an older version of Perl/DBI and found what appears to be a memory leak in the placeholder implementation, so if you're looking at using them in a persistent process/daemon or in a high-volume context you may want to make sure process size doesn't become an issue. Switching over to building the query strings using the quote() method eliminated the issue for me.</p>\n"
},
{
"answer_id": 50491382,
"author": "jjohn",
"author_id": 16513,
"author_profile": "https://Stackoverflow.com/users/16513",
"pm_score": 2,
"selected": false,
"text": "<p>DBI placeholders are awesome. They shine when you need to execute the same query in a loop. Consider this:</p>\n\n<pre><code> my $dbh = DBI->connect(...);\n my $name_pairs = get_csv_data(\"data.csv\");\n my $sth = $dbh->prepare(\"INSERT INTO t1 (first_name, last_name) VALUES (?,?)\");\n for my $pair (@$name_pairs) {\n unless ($sth->execute(@$pair)) {\n warn($sth->errstr);\n }\n }\n</code></pre>\n\n<p>In this case, having the prepared statement handle is, er, handy.</p>\n\n<p>However, barring this sort of tight-loop cases, I like to see the actual statement that was sent to the server. This is where I lean heavily on quote and frankly sprintf.</p>\n\n<pre><code> # Here, I am confident about the hash keys, less so about the values\n $sql = sprintf(\"INSERT INTO t1 (%s) VALUES (%s)\",\n join(\",\", keys(%hash)),\n join(\",\" map { $dbh->quote($_) } values(%hash))\n );\n $sth = $dbh->prepare($sql);\n unless ($sth->execute) {\n warn($sth->{Statement});\n }\n</code></pre>\n\n<p>Note that you do have to set RaiseError => 0 on $dbh so that you can see the SQL that failed, but this has helped me a great deal in the past. </p>\n\n<p>Cheers.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What is the preferred way to insert strings that can contain both single and double quotes (",') into MySql using DBI? For example, `$val1` and `$val2` can contain quotes:
```
my $dbh = DBI->connect( ... );
my $sql = "insert into tbl_name(col_one,col_two) values($val1, $val2)";
my $sth = $dbh->prepare($sql);
$sth->execute();
```
|
Use a bound query using
```
$sth = $dbh->prepare("insert into tbl_name(col_one,col_two) values(?,?)");
$sth->execute($val1, $val2);
```
If you use bound variables, everything is escaped for you.
Update: Changed my example to correspond with the example edited into the question.
Update: I don't know why Adam deleted his answer, but if for some reason you can't use bound variables (aka "placeholders"), you can also use `$dbh->quote($var)` on the variable. For example:
```
$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
$dbh->quote(q("Don't"));
```
|
284,741 |
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p>
<p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p>
<p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
|
[
{
"answer_id": 284752,
"author": "chews",
"author_id": 33966,
"author_profile": "https://Stackoverflow.com/users/33966",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say use the twisted framework for building your http listener.\nTwisted supports chunked encoding.</p>\n\n<p><a href=\"http://python.net/crew/mwh/apidocs/twisted.web.http._ChunkedTransferEncoding.html\" rel=\"nofollow noreferrer\">http://python.net/crew/mwh/apidocs/twisted.web.http._ChunkedTransferEncoding.html</a></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 284857,
"author": "Sam Corder",
"author_id": 2351,
"author_profile": "https://Stackoverflow.com/users/2351",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe it is a configuration issue? Django can be fronted with Apache by mod_python, WSGI and FastCGI and it can accept file uploads. </p>\n"
},
{
"answer_id": 284869,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "<p>Apache 2.2 mod_cgi works fine for me, Apache transparently unchunks the request as it is passed to the CGI application.</p>\n\n<p>WSGI currently disallows chunked requests, and mod_wsgi does indeed block them with a 411 response. It's on the drawing board for WSGI 2.0. But congratulations on finding something that does chunk requests, I've never seen one before!</p>\n"
},
{
"answer_id": 1187738,
"author": "Nathan de Vries",
"author_id": 11109,
"author_profile": "https://Stackoverflow.com/users/11109",
"pm_score": 3,
"selected": false,
"text": "<p>I had the exact same problem a year ago with a J2ME client talking to a Python/Ruby backend. The only solution I found which <em>doesn't</em> require application or infrastructure level changes was to use a relatively unknown feature of mod_proxy.</p>\n\n<p>Mod_proxy has the ability to buffer incoming (chunked) requests, and then rewrite them as a single request with a Content-Length header before passing them on to a proxy backend. The neat trick is that you can create a tiny proxy configuration which passes the request back to the same Apache server. i.e. Take an incoming chunked request on port 80, \"dechunk\" it, and then pass it on to your non-HTTP 1.1 compliant server on port 81.</p>\n\n<p>I used this configuration in production for a little over a year with no problems. It looks a little something like this:</p>\n\n<pre><code>ProxyRequests Off\n\n<Proxy http://example.com:81>\n Order deny,allow\n Allow from all\n</Proxy>\n\n<VirtualHost *:80>\n SetEnv proxy-sendcl 1\n ProxyPass / http://example.com:81/\n ProxyPassReverse / http://example.com:81/\n ProxyPreserveHost On\n ProxyVia Full\n\n <Directory proxy:*>\n Order deny,allow\n Allow from all\n </Directory>\n\n</VirtualHost>\n\nListen 81\n\n<VirtualHost *:81>\n ServerName example.com\n # Your Python application configuration goes here\n</VirtualHost>\n</code></pre>\n\n<p>I've also got a full writeup of the problem and my solution detailed <a href=\"http://www.atnan.com/2008/8/8/transfer-encoding-chunked-chunky-http\" rel=\"noreferrer\">on my blog</a>.</p>\n"
},
{
"answer_id": 1197441,
"author": "Graham Dumpleton",
"author_id": 128141,
"author_profile": "https://Stackoverflow.com/users/128141",
"pm_score": 2,
"selected": false,
"text": "<p>You can't do what you want with mod_python. You can do it with mod_wsgi if you are using version 3.0. You do however have to step outside of the WSGI 1.0 specification as WSGI effectively prohibits chunked request content.</p>\n\n<p>Search for WSGIChunkedRequest in <a href=\"http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300\" rel=\"nofollow noreferrer\">http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300</a> for what is required.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5695/"
] |
I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod\_python, WSGI and FastCGI are no go too.
I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.
I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.
|
I had the exact same problem a year ago with a J2ME client talking to a Python/Ruby backend. The only solution I found which *doesn't* require application or infrastructure level changes was to use a relatively unknown feature of mod\_proxy.
Mod\_proxy has the ability to buffer incoming (chunked) requests, and then rewrite them as a single request with a Content-Length header before passing them on to a proxy backend. The neat trick is that you can create a tiny proxy configuration which passes the request back to the same Apache server. i.e. Take an incoming chunked request on port 80, "dechunk" it, and then pass it on to your non-HTTP 1.1 compliant server on port 81.
I used this configuration in production for a little over a year with no problems. It looks a little something like this:
```
ProxyRequests Off
<Proxy http://example.com:81>
Order deny,allow
Allow from all
</Proxy>
<VirtualHost *:80>
SetEnv proxy-sendcl 1
ProxyPass / http://example.com:81/
ProxyPassReverse / http://example.com:81/
ProxyPreserveHost On
ProxyVia Full
<Directory proxy:*>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
Listen 81
<VirtualHost *:81>
ServerName example.com
# Your Python application configuration goes here
</VirtualHost>
```
I've also got a full writeup of the problem and my solution detailed [on my blog](http://www.atnan.com/2008/8/8/transfer-encoding-chunked-chunky-http).
|
284,744 |
<p>I'm creating a control and need to pass it the current logon user as a parameter (declaratively)</p>
<p>I tried this but didn't work (I got "<%= User.Identity.Name %>" as value):</p>
<pre><code><cc1:MyControl id="myid" runat="server" User="<%= User.Identity.Name %>" />
</code></pre>
<p>Is there a way to do it?</p>
|
[
{
"answer_id": 284747,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Try using:</p>\n\n<pre><code>User=\"<%= User.Identity.Name %>\"\n</code></pre>\n\n<p>%= is for output</p>\n\n<p>%# is for databinding.</p>\n"
},
{
"answer_id": 284749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try changing the double quotes in the User attribute to single quotes. I've seen that work in the past...</p>\n"
},
{
"answer_id": 284755,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 1,
"selected": false,
"text": "<p>Inside that control, you will have access to this.Page.User, so that's one way.\nAnother is to use HttpContext.Current.User.</p>\n"
},
{
"answer_id": 284760,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 3,
"selected": true,
"text": "<p>Why do you need to pass it at all?. The user control can access the User.Identity.Name property directly.</p>\n"
},
{
"answer_id": 284767,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this in the codebehind:</p>\n\n<pre><code>myid.User = User.Identity.Name\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
I'm creating a control and need to pass it the current logon user as a parameter (declaratively)
I tried this but didn't work (I got "<%= User.Identity.Name %>" as value):
```
<cc1:MyControl id="myid" runat="server" User="<%= User.Identity.Name %>" />
```
Is there a way to do it?
|
Why do you need to pass it at all?. The user control can access the User.Identity.Name property directly.
|
284,761 |
<p>I have an implementation of default handler. When it gets to a in the character data it stops parsing. Is there any reason that it is doing this? Are there additional properties that I need to set in order for it to deal with &nbsp?</p>
|
[
{
"answer_id": 285075,
"author": "Ben Noland",
"author_id": 32899,
"author_profile": "https://Stackoverflow.com/users/32899",
"pm_score": 0,
"selected": false,
"text": "<p><code>&nbsp;</code> is not a valid xml entity. You might try replacing it with <code>&#160;</code> instead, it does the same thing (non-breaking space).</p>\n"
},
{
"answer_id": 335689,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 3,
"selected": true,
"text": "<p>This breaks because the XML entity is not defined. You could add</p>\n\n<pre><code><!DOCTYPE document SYSTEM \"document.dtd\" [ \n<!ENTITY nbsp \"&#160;\"> \n]>\n</code></pre>\n\n<p>Or just use <code>&#160;</code> instead. (Note the \";\" at the end)</p>\n\n<p>Also see <a href=\"http://www.dpawson.co.uk/xsl/characters.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35140/"
] |
I have an implementation of default handler. When it gets to a in the character data it stops parsing. Is there any reason that it is doing this? Are there additional properties that I need to set in order for it to deal with  ?
|
This breaks because the XML entity is not defined. You could add
```
<!DOCTYPE document SYSTEM "document.dtd" [
<!ENTITY nbsp " ">
]>
```
Or just use ` ` instead. (Note the ";" at the end)
Also see [here](http://www.dpawson.co.uk/xsl/characters.html).
|
284,766 |
<p>If I have a DrawingVisual in WPF with Opacity=0, is that enough for it not to be drawn? We have hundreds of DrawingVisuals on a Canvas, and are currently setting Opacity=0 on the visuals that are not to be displayed, and I wanted to make sure there is no rendering performance hit for rendering a DrawingVisual with Opacity=0.</p>
<p>UPDATE: I have discovered through testing that there IS overhead when Opacity=0, but since DrawingVisual doesn't have a Visibility property, I don't know how else you would tell it to not be displayed unless you actualy remove it from the visual tree, so any suggestions are welcome. </p>
|
[
{
"answer_id": 289699,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 2,
"selected": false,
"text": "<p>The best way to check would be to instead set the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.uielement.visibility.aspx\" rel=\"nofollow noreferrer\">Visibility</a> to Visibility.Colapsed, and see if there's any drawing performance differences. </p>\n\n<p>Visibility.Colapsed ensures that the element is not visible but also that it will not participate in the Arrange, Measure and Render passes of the UI, while an element with Opacity=0 might participate in all passes.</p>\n"
},
{
"answer_id": 716469,
"author": "eesh",
"author_id": 85666,
"author_profile": "https://Stackoverflow.com/users/85666",
"pm_score": 2,
"selected": false,
"text": "<p>I solved a very similar problem by using a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawinggroup\" rel=\"nofollow noreferrer\"><code>DrawingGroup</code></a> and adding or removing <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawing\" rel=\"nofollow noreferrer\"><code>Drawing</code></a> objects from the <code>DrawingGroup</code> as they either needed to be displayed or hidden. The key is to organize your <code>Drawing</code> objects in such a way that they are easy to manage and to understand how to add and remove them from the <code>DrawingGroup</code>.</p>\n\n<p>Remember that you want to add and remove the <code>Drawing</code> objects from the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawinggroup.children\" rel=\"nofollow noreferrer\"><code>DrawingCollection</code></a> exposed by the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawingcollection\" rel=\"nofollow noreferrer\"><code>DrawingGroup.Children</code></a> property. So use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawingcollection.add\" rel=\"nofollow noreferrer\"><code>DrawingGroup.Children.Add()</code></a> or the other <code>DrawingCollection</code> methods: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawingcollection.insert\" rel=\"nofollow noreferrer\"><code>Insert</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawingcollection.remove\" rel=\"nofollow noreferrer\"><code>Remove</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawingcollection.removeat\" rel=\"nofollow noreferrer\"><code>RemoveAt</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.drawingcollection.clear\" rel=\"nofollow noreferrer\"><code>Clear</code></a>. You will need to keep an external list of the <code>Drawing</code> objects you add/remove to the <code>DrawingGroup</code> to do this successfully.</p>\n\n<p>I used this technique to great effect by drawing an Image (bitmap) into the first child in my instance of <code>DrawingGroup</code> and then adding and removing <code>Drawing</code> objects to this instance of <code>DrawingGroup</code> in order to layer polygons, paths, text, etc on top of the drawing. </p>\n\n<p>I \"draw\" or \"erase\" on the image by adding or removing <code>Drawing</code> objects to the instance of the <code>DrawingGroup</code>. The <code>DrawingGroup</code> is treated as a single <code>Drawing</code> and so any scaling, panning, or other manipulations will affect all <code>Drawing</code> objects within the <code>DrawingGroup</code>. </p>\n"
},
{
"answer_id": 919540,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Why not simply remove the visual from the visual children list? When it needs to be visible you add it back.</p>\n"
},
{
"answer_id": 11899486,
"author": "keft",
"author_id": 762979,
"author_profile": "https://Stackoverflow.com/users/762979",
"pm_score": 2,
"selected": true,
"text": "<p>The most efficient seems to be setting the opacity in my tests. Another simple approach is to redraw the visuals that are affected.</p>\n\n<pre><code>using (DrawingContext dc = RenderOpen()) {} //Hide this visual\n</code></pre>\n\n<p>And then redraw when they become visible again.</p>\n\n<p>Rendering a blank drawingcontext seems to be very quick. But if you have complicated visuals it could take time to rerender them when they become visible.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18967/"
] |
If I have a DrawingVisual in WPF with Opacity=0, is that enough for it not to be drawn? We have hundreds of DrawingVisuals on a Canvas, and are currently setting Opacity=0 on the visuals that are not to be displayed, and I wanted to make sure there is no rendering performance hit for rendering a DrawingVisual with Opacity=0.
UPDATE: I have discovered through testing that there IS overhead when Opacity=0, but since DrawingVisual doesn't have a Visibility property, I don't know how else you would tell it to not be displayed unless you actualy remove it from the visual tree, so any suggestions are welcome.
|
The most efficient seems to be setting the opacity in my tests. Another simple approach is to redraw the visuals that are affected.
```
using (DrawingContext dc = RenderOpen()) {} //Hide this visual
```
And then redraw when they become visible again.
Rendering a blank drawingcontext seems to be very quick. But if you have complicated visuals it could take time to rerender them when they become visible.
|
284,775 |
<p>How do I convert a DateTime structure to its equivalent <a href="http://www.w3.org/Protocols/rfc822/#z28" rel="noreferrer">RFC 822 date-time</a> formatted string representation <strong>and</strong> parse this string representation back to a DateTime structure in .NET? The RFC-822 date-time format is used in a number of specifications such as the <a href="http://www.rssboard.org/rss-specification" rel="noreferrer">RSS Syndication Format</a>.</p>
|
[
{
"answer_id": 284785,
"author": "Oppositional",
"author_id": 2029,
"author_profile": "https://Stackoverflow.com/users/2029",
"pm_score": 6,
"selected": true,
"text": "<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-822 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC). I agree that this is not very elegant code, but it does the job.</p>\n\n<pre><code>/// <summary>\n/// Provides methods for converting <see cref=\"DateTime\"/> structures \n/// to and from the equivalent <a href=\"http://www.w3.org/Protocols/rfc822/#z28\">RFC 822</a> \n/// string representation.\n/// </summary>\npublic class Rfc822DateTime\n{\n //============================================================\n // Private members\n //============================================================\n #region Private Members\n /// <summary>\n /// Private member to hold array of formats that RFC 822 date-time representations conform to.\n /// </summary>\n private static string[] formats = new string[0];\n /// <summary>\n /// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format.\n /// </summary>\n private const string format = \"ddd, dd MMM yyyy HH:mm:ss K\";\n #endregion\n\n //============================================================\n // Public Properties\n //============================================================\n #region Rfc822DateTimeFormat\n /// <summary>\n /// Gets the custom format specifier that may be used to represent a <see cref=\"DateTime\"/> in the RFC 822 format.\n /// </summary>\n /// <value>A <i>DateTime format string</i> that may be used to represent a <see cref=\"DateTime\"/> in the RFC 822 format.</value>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of a <see cref=\"DateTime\"/> that utilizes the time zone \n /// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes. \n /// The <see cref=\"Rfc822DateTimeFormat\"/> is a valid date-time format string for use \n /// in the <see cref=\"DateTime.ToString(String, IFormatProvider)\"/> method.\n /// </para>\n /// <para>\n /// The <a href=\"http://www.w3.org/Protocols/rfc822/#z28\">RFC 822</a> Date and Time specification \n /// specifies that the year will be represented as a two-digit value, but the \n /// <a href=\"http://www.rssboard.org/rss-profile#data-types-datetime\">RSS Profile</a> recommends that \n /// all date-time values should use a four-digit year. The <see cref=\"Rfc822DateTime\"/> class \n /// follows the RSS Profile recommendation when converting a <see cref=\"DateTime\"/> to the equivalent \n /// RFC 822 string representation.\n /// </para>\n /// </remarks>\n public static string Rfc822DateTimeFormat\n {\n get\n {\n return format;\n }\n }\n #endregion\n\n #region Rfc822DateTimePatterns\n /// <summary>\n /// Gets an array of the expected formats for RFC 822 date-time string representations.\n /// </summary>\n /// <value>\n /// An array of the expected formats for RFC 822 date-time string representations \n /// that may used in the <see cref=\"DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)\"/> method.\n /// </value>\n /// <remarks>\n /// The array of the expected formats that is returned assumes that the RFC 822 time zone \n /// is represented as or converted to a local differential representation.\n /// </remarks>\n /// <seealso cref=\"ConvertZoneToLocalDifferential(String)\"/>\n public static string[] Rfc822DateTimePatterns\n {\n get\n {\n if (formats.Length > 0)\n {\n return formats;\n }\n else\n {\n formats = new string[35];\n\n // two-digit day, four-digit year patterns\n formats[0] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[1] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[2] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[3] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[4] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[5] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[6] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[7] = \"ddd',' dd MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[8] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[9] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[10] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[11] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[12] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[13] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[14] = \"ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[15] = \"ddd',' dd MMM yy HH':'mm':'ss zzzz\";\n\n // one-digit day, four-digit year patterns\n formats[16] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[17] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[18] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[19] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[20] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[21] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[22] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[23] = \"ddd',' d MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[24] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[25] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[26] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[27] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[28] = \"ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[29] = \"ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[30] = \"ddd',' d MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[31] = \"ddd',' d MMM yy HH':'mm':'ss zzzz\";\n\n // Fall back patterns\n formats[32] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\"; // RoundtripDateTimePattern\n formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n return formats;\n }\n }\n }\n #endregion\n\n //============================================================\n // Public Methods\n //============================================================\n #region Parse(string s)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <returns>\n /// A <see cref=\"DateTime\"/> equivalent to the date and time contained in <paramref name=\"s\"/>, \n /// expressed as <i>Coordinated Universal Time (UTC)</i>.\n /// </returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is an empty string.</exception>\n /// <exception cref=\"FormatException\"><paramref name=\"s\"/> does not contain a valid RFC 822 string representation of a date and time.</exception>\n public static DateTime Parse(string s)\n {\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n if (String.IsNullOrEmpty(s))\n {\n throw new ArgumentNullException(\"s\");\n }\n\n DateTime result;\n if (Rfc822DateTime.TryParse(s, out result))\n {\n return result;\n }\n else\n {\n throw new FormatException(String.Format(null, \"{0} is not a valid RFC 822 string representation of a date and time.\", s));\n }\n }\n #endregion\n\n #region ConvertZoneToLocalDifferential(string s)\n /// <summary>\n /// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset).\n /// </summary>\n /// <param name=\"s\">A string containing an RFC 822 date and time to convert.</param>\n /// <returns>A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in <paramref name=\"s\"/>.</returns>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is an empty string.</exception>\n public static string ConvertZoneToLocalDifferential(string s)\n {\n string zoneRepresentedAsLocalDifferential = String.Empty;\n\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n if (String.IsNullOrEmpty(s))\n {\n throw new ArgumentNullException(\"s\");\n }\n\n if(s.EndsWith(\" UT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" UT\") + 1) ), \"+00:00\");\n }\n else if (s.EndsWith(\" GMT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" GMT\") + 1 ) ), \"+00:00\");\n }\n else if (s.EndsWith(\" EST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EST\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" EDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EDT\") + 1)), \"-04:00\");\n }\n else if (s.EndsWith(\" CST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CST\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" CDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CDT\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" MST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MST\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" MDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MDT\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" PST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PST\") + 1)), \"-08:00\");\n }\n else if (s.EndsWith(\" PDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PDT\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" Z\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Z\") + 1)), \"+00:00\");\n }\n else if (s.EndsWith(\" A\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" A\") + 1)), \"-01:00\");\n }\n else if (s.EndsWith(\" M\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" M\") + 1)), \"-12:00\");\n }\n else if (s.EndsWith(\" N\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" N\") + 1)), \"+01:00\");\n }\n else if (s.EndsWith(\" Y\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Y\") + 1)), \"+12:00\");\n }\n else\n {\n zoneRepresentedAsLocalDifferential = s;\n }\n\n return zoneRepresentedAsLocalDifferential;\n }\n #endregion\n\n #region ToString(DateTime utcDateTime)\n /// <summary>\n /// Converts the value of the specified <see cref=\"DateTime\"/> object to its equivalent string representation.\n /// </summary>\n /// <param name=\"utcDateTime\">The Coordinated Universal Time (UTC) <see cref=\"DateTime\"/> to convert.</param>\n /// <returns>A RFC 822 string representation of the value of the <paramref name=\"utcDateTime\"/>.</returns>\n /// <exception cref=\"ArgumentException\">The specified <paramref name=\"utcDateTime\"/> object does not represent a <see cref=\"DateTimeKind.Utc\">Coordinated Universal Time (UTC)</see> value.</exception>\n public static string ToString(DateTime utcDateTime)\n {\n if (utcDateTime.Kind != DateTimeKind.Utc)\n {\n throw new ArgumentException(\"utcDateTime\");\n }\n\n return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n }\n #endregion\n\n #region TryParse(string s, out DateTime result)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <param name=\"result\">\n /// When this method returns, contains the <see cref=\"DateTime\"/> value equivalent to the date and time \n /// contained in <paramref name=\"s\"/>, expressed as <i>Coordinated Universal Time (UTC)</i>, \n /// if the conversion succeeded, or <see cref=\"DateTime.MinValue\">MinValue</see> if the conversion failed. \n /// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic), \n /// or does not contain a valid string representation of a date and time. \n /// This parameter is passed uninitialized.\n /// </param>\n /// <returns><b>true</b> if the <paramref name=\"s\"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object. \n /// </remarks>\n public static bool TryParse(string s, out DateTime result)\n {\n //------------------------------------------------------------\n // Attempt to convert string representation\n //------------------------------------------------------------\n bool wasConverted = false;\n result = DateTime.MinValue;\n\n if (!String.IsNullOrEmpty(s))\n {\n DateTime parseResult;\n if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n {\n result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n wasConverted = true;\n }\n }\n\n return wasConverted;\n }\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 554093,
"author": "Jeff Woodman",
"author_id": 42689,
"author_profile": "https://Stackoverflow.com/users/42689",
"pm_score": 6,
"selected": false,
"text": "<p>Try this: </p>\n\n<pre><code> DateTime today = DateTime.Now;\n String rfc822 = today.ToString(\"r\");\n Console.WriteLine(\"RFC-822 date: {0}\", rfc822);\n\n DateTime parsedRFC822 = DateTime.Parse(rfc822);\n Console.WriteLine(\"Date: {0}\", parsedRFC822);\n</code></pre>\n\n<p>The \"r\" format specifier passed into DateTime's ToString() method actually yields an RFC-1123-formatted datetime string, but passes as an RFC-822 date as well, based on reading the specification found at <a href=\"http://www.w3.org/Protocols/rfc822/#z28\" rel=\"noreferrer\">http://www.w3.org/Protocols/rfc822/#z28</a>. I've used this method in creating RSS feeds, and they pass validation based on the validator available at <a href=\"http://validator.w3.org/feed/check.cgi\" rel=\"noreferrer\">http://validator.w3.org/feed/check.cgi</a>. </p>\n\n<p>The downside is that, in the conversion, it converts the datetime to GMT. To convert back to local time you would need to apply your local timezone offset. For that, you might use the TimeZone class to get your current timezone offset, and replace \"GMT\" with a timezone offset string:</p>\n\n<pre><code>TimeZone tz = TimeZone.CurrentTimeZone;\n\nString offset = tz.GetUtcOffset().ToString();\n// My locale is Mountain time; offset is set to \"-07:00:00\"\n// if local time is behind utc time, offset should start with \"-\".\n// otherwise, add a plus sign to the beginning of the string.\nif (!offset.StartsWith(\"-\"))\n offset = \"+\" + offset; // Add a (+) if it's a UTC+ timezone\noffset = offset.Substring(0,6); // only want the first 6 chars.\noffset = offset.Replace(\":\", \"\"); // remove colons.\n// offset now looks something like \"-0700\".\nrfc822 = rfc822.Replace(\"GMT\", offset);\n// The rfc822 string can now be parsed back to a DateTime object,\n// with the local time accounted for.\nDateTime new = DateTime.Parse(rfc822);\n</code></pre>\n"
},
{
"answer_id": 2465945,
"author": "Kirk Liemohn",
"author_id": 74276,
"author_profile": "https://Stackoverflow.com/users/74276",
"pm_score": 2,
"selected": false,
"text": "<p>Here is how Microsoft does it in the Rss20FeedFormatter. Oppositional's code doesn't get rid of the \":\" in the GMT offset portion. Jeff Woodman's appears to do this. The code below does this as well (if not using Atom10FeedFormatter.zeroOffset).</p>\n\n<pre><code>private string AsString(DateTimeOffset dateTime)\n{\n if (dateTime.Offset == Atom10FeedFormatter.zeroOffset)\n {\n return dateTime.ToUniversalTime().ToString(\"ddd, dd MMM yyyy HH:mm:ss Z\", CultureInfo.InvariantCulture);\n }\n StringBuilder builder = new StringBuilder(dateTime.T)oString(\"ddd, dd MMM yyyy HH:mm:ss zzz\", CultureInfo.InvariantCulture));\n builder.Remove(builder.Length - 3, 1);\n return builder.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 10426999,
"author": "Eric Boumendil",
"author_id": 249742,
"author_profile": "https://Stackoverflow.com/users/249742",
"pm_score": 1,
"selected": false,
"text": "<p>Based on the answer of Kirk Liemohn, I used this method with success:</p>\n<pre><code>private DateTimeOffset? ParseDate(string date)\n {\n const string FORMAT = "ddd, d MMM yyyy HH:mm:ss zzz";\n const string FORMAT2 = "ddd, dd MMM yyyy HH:mm:ss zzz";\n const string FORMAT3 = "dd MMM yyyy HH:mm:ss zzz";\n const string FORMAT4 = "d MMM yyyy HH:mm:ss zzz";\n DateTimeOffset d;\n if (DateTimeOffset.TryParseExact(date, new string[] { FORMAT, FORMAT2, FORMAT3, FORMAT4 }, CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out d))\n return d;\n return null;\n }\n</code></pre>\n<p>Example:</p>\n<pre><code>DateTimeOffset? date = ParseDate("Thu, 5 Apr 2012 23:47:37 +0200");\nConsole.WriteLine(date.ToString());\n// => 05/04/2012 23:47:37 +02:00\n</code></pre>\n<p>It does not respect full spec of RFC but it works for my use cases.</p>\n<p>Specifically, it does not work with timezone express like : "GMT", "CST", etc. (see <a href=\"https://www.rfc-editor.org/rfc/rfc822#section-5.1\" rel=\"nofollow noreferrer\">"zone" in RFC822 Section 5.1</a>). See the <a href=\"https://stackoverflow.com/a/37550344/249742\">better answer of Oleksandr Pshenychnyy</a>.</p>\n"
},
{
"answer_id": 12691951,
"author": "Raymond Powell",
"author_id": 1714561,
"author_profile": "https://Stackoverflow.com/users/1714561",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my implementation using an extension method:</p>\n\n<pre><code>namespace MyNamespace\n{\n public static partial class ExtensionMethods\n {\n public static string ToRFC822String(this DateTime timestamp)\n {\n return timestamp.ToString(\"ddd',' d MMM yyyy HH':'mm':'ss\")\n + \" \"\n + timestamp.ToString(\"zzzz\").Replace(\":\", \"\");\n }\n }\n }\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code> using MyNamespace;\n\n ....\n\n string MyRFC822String = DateTime.Now.ToRFC822String();\n</code></pre>\n"
},
{
"answer_id": 37550344,
"author": "Sasha",
"author_id": 543591,
"author_profile": "https://Stackoverflow.com/users/543591",
"pm_score": 2,
"selected": false,
"text": "<p>Following Kirk's idea, I decompiled sources for <code>System.ServiceModel.Syndication.Rss20FeedFormatter</code> class (<em>System.ServiceModel.dll</em>) and here is <strong>Microsoft internal parser for RFC 822 dates format</strong> (I slightly simplified their exception handling logic to reduce dependencies):</p>\n\n<pre><code>public static class DateTimeParser\n{\n public static DateTimeOffset ParseDateTimeRFC822(string dateTimeString)\n {\n StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim());\n if (dateTimeStringBuilder.Length < 18)\n {\n throw new FormatException(\"Invalid date format. Expected date in RFC 822 format\");\n }\n if (dateTimeStringBuilder[3] == ',')\n {\n // There is a leading (e.g.) \"Tue, \", strip it off\n dateTimeStringBuilder.Remove(0, 4);\n // There's supposed to be a space here but some implementations dont have one\n RemoveExtraWhiteSpaceAtStart(dateTimeStringBuilder);\n }\n ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(dateTimeStringBuilder);\n if (char.IsDigit(dateTimeStringBuilder[1]))\n {\n // two-digit day, we are good\n }\n else\n {\n dateTimeStringBuilder.Insert(0, '0');\n }\n if (dateTimeStringBuilder.Length < 19)\n {\n throw new FormatException(\"Invalid date format. Expected date in RFC 822 format\");\n }\n bool thereAreSeconds = (dateTimeStringBuilder[17] == ':');\n int timeZoneStartIndex;\n if (thereAreSeconds)\n {\n timeZoneStartIndex = 21;\n }\n else\n {\n timeZoneStartIndex = 18;\n }\n string timeZoneSuffix = dateTimeStringBuilder.ToString().Substring(timeZoneStartIndex);\n dateTimeStringBuilder.Remove(timeZoneStartIndex, dateTimeStringBuilder.Length - timeZoneStartIndex);\n bool isUtc;\n dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc));\n string wellFormattedString = dateTimeStringBuilder.ToString();\n\n DateTimeOffset theTime;\n string parseFormat;\n if (thereAreSeconds)\n {\n parseFormat = \"dd MMM yyyy HH:mm:ss zzz\";\n }\n else\n {\n parseFormat = \"dd MMM yyyy HH:mm zzz\";\n }\n if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat,\n CultureInfo.InvariantCulture.DateTimeFormat,\n (isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime))\n {\n return theTime;\n }\n throw new FormatException(\"Invalid date format. Expected date in RFC 822 format\");\n }\n\n static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc)\n {\n isUtc = false;\n // return a string in \"-08:00\" format\n if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-')\n {\n // the time zone is supposed to be 4 digits but some feeds omit the initial 0\n StringBuilder result = new StringBuilder(rfc822TimeZone);\n if (result.Length == 4)\n {\n // the timezone is +/-HMM. Convert to +/-HHMM\n result.Insert(1, '0');\n }\n result.Insert(3, ':');\n return result.ToString();\n }\n switch (rfc822TimeZone)\n {\n case \"UT\":\n case \"Z\":\n isUtc = true;\n return \"-00:00\";\n case \"GMT\":\n return \"-00:00\";\n case \"A\":\n return \"-01:00\";\n case \"B\":\n return \"-02:00\";\n case \"C\":\n return \"-03:00\";\n case \"D\":\n case \"EDT\":\n return \"-04:00\";\n case \"E\":\n case \"EST\":\n case \"CDT\":\n return \"-05:00\";\n case \"F\":\n case \"CST\":\n case \"MDT\":\n return \"-06:00\";\n case \"G\":\n case \"MST\":\n case \"PDT\":\n return \"-07:00\";\n case \"H\":\n case \"PST\":\n return \"-08:00\";\n case \"I\":\n return \"-09:00\";\n case \"K\":\n return \"-10:00\";\n case \"L\":\n return \"-11:00\";\n case \"M\":\n return \"-12:00\";\n case \"N\":\n return \"+01:00\";\n case \"O\":\n return \"+02:00\";\n case \"P\":\n return \"+03:00\";\n case \"Q\":\n return \"+04:00\";\n case \"R\":\n return \"+05:00\";\n case \"S\":\n return \"+06:00\";\n case \"T\":\n return \"+07:00\";\n case \"U\":\n return \"+08:00\";\n case \"V\":\n return \"+09:00\";\n case \"W\":\n return \"+10:00\";\n case \"X\":\n return \"+11:00\";\n case \"Y\":\n return \"+12:00\";\n default:\n return \"\";\n }\n }\n\n static void RemoveExtraWhiteSpaceAtStart(StringBuilder stringBuilder)\n {\n int i = 0;\n while (i < stringBuilder.Length)\n {\n if (!char.IsWhiteSpace(stringBuilder[i]))\n {\n break;\n }\n ++i;\n }\n if (i > 0)\n {\n stringBuilder.Remove(0, i);\n }\n }\n\n static void ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(StringBuilder builder)\n {\n int index = 0;\n int whiteSpaceStart = -1;\n while (index < builder.Length)\n {\n if (char.IsWhiteSpace(builder[index]))\n {\n if (whiteSpaceStart < 0)\n {\n whiteSpaceStart = index;\n // normalize all white spaces to be ' ' so that the date time parsing works\n builder[index] = ' ';\n }\n }\n else if (whiteSpaceStart >= 0)\n {\n if (index > whiteSpaceStart + 1)\n {\n // there are at least 2 spaces... replace by 1\n builder.Remove(whiteSpaceStart, index - whiteSpaceStart - 1);\n index = whiteSpaceStart + 1;\n }\n whiteSpaceStart = -1;\n }\n ++index;\n }\n // we have already trimmed the start and end so there cannot be a trail of white spaces in the end\n Debug.Assert(builder.Length == 0 || builder[builder.Length - 1] != ' ', \"The string builder doesnt end in a white space\");\n }\n}\n</code></pre>\n\n<p>The first thing which may look unusual is that they return <code>[DateTimeOffset][1]</code> class instead of <code>DateTime</code>. But when we read more about it, it appears to be completely logical - <code>DateTimeOffset</code> stores <strong>date, time and timezone</strong> info (exactly as string in RFC 822 format). <strong>If you were returning just DateTime object, which timezone it would be in</strong>: UTC, local, or the one specified in parsed string - any answer would be wrong for some cases. So <code>DateTimeOffset</code> solves an important uncertainty problem. And you can convert it to timezone you need later using methods <code>DateTimeOffset.ToUniversalTime()</code>, <code>DateTimeOffset.ToLocalTime()</code>.</p>\n\n<p>I tested it on few cases and it seems it does the job perfectly.</p>\n\n<p>I'm not sure though, why Microsoft decided to make this implementation private - it doesn't seem to require a lot of support.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029/"
] |
How do I convert a DateTime structure to its equivalent [RFC 822 date-time](http://www.w3.org/Protocols/rfc822/#z28) formatted string representation **and** parse this string representation back to a DateTime structure in .NET? The RFC-822 date-time format is used in a number of specifications such as the [RSS Syndication Format](http://www.rssboard.org/rss-specification).
|
This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-822 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC). I agree that this is not very elegant code, but it does the job.
```
/// <summary>
/// Provides methods for converting <see cref="DateTime"/> structures
/// to and from the equivalent <a href="http://www.w3.org/Protocols/rfc822/#z28">RFC 822</a>
/// string representation.
/// </summary>
public class Rfc822DateTime
{
//============================================================
// Private members
//============================================================
#region Private Members
/// <summary>
/// Private member to hold array of formats that RFC 822 date-time representations conform to.
/// </summary>
private static string[] formats = new string[0];
/// <summary>
/// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format.
/// </summary>
private const string format = "ddd, dd MMM yyyy HH:mm:ss K";
#endregion
//============================================================
// Public Properties
//============================================================
#region Rfc822DateTimeFormat
/// <summary>
/// Gets the custom format specifier that may be used to represent a <see cref="DateTime"/> in the RFC 822 format.
/// </summary>
/// <value>A <i>DateTime format string</i> that may be used to represent a <see cref="DateTime"/> in the RFC 822 format.</value>
/// <remarks>
/// <para>
/// This method returns a string representation of a <see cref="DateTime"/> that utilizes the time zone
/// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes.
/// The <see cref="Rfc822DateTimeFormat"/> is a valid date-time format string for use
/// in the <see cref="DateTime.ToString(String, IFormatProvider)"/> method.
/// </para>
/// <para>
/// The <a href="http://www.w3.org/Protocols/rfc822/#z28">RFC 822</a> Date and Time specification
/// specifies that the year will be represented as a two-digit value, but the
/// <a href="http://www.rssboard.org/rss-profile#data-types-datetime">RSS Profile</a> recommends that
/// all date-time values should use a four-digit year. The <see cref="Rfc822DateTime"/> class
/// follows the RSS Profile recommendation when converting a <see cref="DateTime"/> to the equivalent
/// RFC 822 string representation.
/// </para>
/// </remarks>
public static string Rfc822DateTimeFormat
{
get
{
return format;
}
}
#endregion
#region Rfc822DateTimePatterns
/// <summary>
/// Gets an array of the expected formats for RFC 822 date-time string representations.
/// </summary>
/// <value>
/// An array of the expected formats for RFC 822 date-time string representations
/// that may used in the <see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/> method.
/// </value>
/// <remarks>
/// The array of the expected formats that is returned assumes that the RFC 822 time zone
/// is represented as or converted to a local differential representation.
/// </remarks>
/// <seealso cref="ConvertZoneToLocalDifferential(String)"/>
public static string[] Rfc822DateTimePatterns
{
get
{
if (formats.Length > 0)
{
return formats;
}
else
{
formats = new string[35];
// two-digit day, four-digit year patterns
formats[0] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz";
formats[1] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz";
formats[2] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz";
formats[3] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz";
formats[4] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz";
formats[5] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz";
formats[6] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz";
formats[7] = "ddd',' dd MMM yyyy HH':'mm':'ss zzzz";
// two-digit day, two-digit year patterns
formats[8] = "ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz";
formats[9] = "ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz";
formats[10] = "ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz";
formats[11] = "ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz";
formats[12] = "ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz";
formats[13] = "ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz";
formats[14] = "ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz";
formats[15] = "ddd',' dd MMM yy HH':'mm':'ss zzzz";
// one-digit day, four-digit year patterns
formats[16] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz";
formats[17] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz";
formats[18] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz";
formats[19] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz";
formats[20] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz";
formats[21] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz";
formats[22] = "ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz";
formats[23] = "ddd',' d MMM yyyy HH':'mm':'ss zzzz";
// two-digit day, two-digit year patterns
formats[24] = "ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz";
formats[25] = "ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz";
formats[26] = "ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz";
formats[27] = "ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz";
formats[28] = "ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz";
formats[29] = "ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz";
formats[30] = "ddd',' d MMM yy HH':'mm':'ss'.'f zzzz";
formats[31] = "ddd',' d MMM yy HH':'mm':'ss zzzz";
// Fall back patterns
formats[32] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern
formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;
formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;
return formats;
}
}
}
#endregion
//============================================================
// Public Methods
//============================================================
#region Parse(string s)
/// <summary>
/// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
/// </summary>
/// <param name="s">A string containing a date and time to convert.</param>
/// <returns>
/// A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>,
/// expressed as <i>Coordinated Universal Time (UTC)</i>.
/// </returns>
/// <remarks>
/// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is an empty string.</exception>
/// <exception cref="FormatException"><paramref name="s"/> does not contain a valid RFC 822 string representation of a date and time.</exception>
public static DateTime Parse(string s)
{
//------------------------------------------------------------
// Validate parameter
//------------------------------------------------------------
if (String.IsNullOrEmpty(s))
{
throw new ArgumentNullException("s");
}
DateTime result;
if (Rfc822DateTime.TryParse(s, out result))
{
return result;
}
else
{
throw new FormatException(String.Format(null, "{0} is not a valid RFC 822 string representation of a date and time.", s));
}
}
#endregion
#region ConvertZoneToLocalDifferential(string s)
/// <summary>
/// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset).
/// </summary>
/// <param name="s">A string containing an RFC 822 date and time to convert.</param>
/// <returns>A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in <paramref name="s"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is an empty string.</exception>
public static string ConvertZoneToLocalDifferential(string s)
{
string zoneRepresentedAsLocalDifferential = String.Empty;
//------------------------------------------------------------
// Validate parameter
//------------------------------------------------------------
if (String.IsNullOrEmpty(s))
{
throw new ArgumentNullException("s");
}
if(s.EndsWith(" UT", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" UT") + 1) ), "+00:00");
}
else if (s.EndsWith(" GMT", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" GMT") + 1 ) ), "+00:00");
}
else if (s.EndsWith(" EST", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" EST") + 1)), "-05:00");
}
else if (s.EndsWith(" EDT", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" EDT") + 1)), "-04:00");
}
else if (s.EndsWith(" CST", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" CST") + 1)), "-06:00");
}
else if (s.EndsWith(" CDT", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" CDT") + 1)), "-05:00");
}
else if (s.EndsWith(" MST", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" MST") + 1)), "-07:00");
}
else if (s.EndsWith(" MDT", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" MDT") + 1)), "-06:00");
}
else if (s.EndsWith(" PST", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" PST") + 1)), "-08:00");
}
else if (s.EndsWith(" PDT", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" PDT") + 1)), "-07:00");
}
else if (s.EndsWith(" Z", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" Z") + 1)), "+00:00");
}
else if (s.EndsWith(" A", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" A") + 1)), "-01:00");
}
else if (s.EndsWith(" M", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" M") + 1)), "-12:00");
}
else if (s.EndsWith(" N", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" N") + 1)), "+01:00");
}
else if (s.EndsWith(" Y", StringComparison.OrdinalIgnoreCase))
{
zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" Y") + 1)), "+12:00");
}
else
{
zoneRepresentedAsLocalDifferential = s;
}
return zoneRepresentedAsLocalDifferential;
}
#endregion
#region ToString(DateTime utcDateTime)
/// <summary>
/// Converts the value of the specified <see cref="DateTime"/> object to its equivalent string representation.
/// </summary>
/// <param name="utcDateTime">The Coordinated Universal Time (UTC) <see cref="DateTime"/> to convert.</param>
/// <returns>A RFC 822 string representation of the value of the <paramref name="utcDateTime"/>.</returns>
/// <exception cref="ArgumentException">The specified <paramref name="utcDateTime"/> object does not represent a <see cref="DateTimeKind.Utc">Coordinated Universal Time (UTC)</see> value.</exception>
public static string ToString(DateTime utcDateTime)
{
if (utcDateTime.Kind != DateTimeKind.Utc)
{
throw new ArgumentException("utcDateTime");
}
return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo);
}
#endregion
#region TryParse(string s, out DateTime result)
/// <summary>
/// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
/// </summary>
/// <param name="s">A string containing a date and time to convert.</param>
/// <param name="result">
/// When this method returns, contains the <see cref="DateTime"/> value equivalent to the date and time
/// contained in <paramref name="s"/>, expressed as <i>Coordinated Universal Time (UTC)</i>,
/// if the conversion succeeded, or <see cref="DateTime.MinValue">MinValue</see> if the conversion failed.
/// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic),
/// or does not contain a valid string representation of a date and time.
/// This parameter is passed uninitialized.
/// </param>
/// <returns><b>true</b> if the <paramref name="s"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>
/// <remarks>
/// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
/// </remarks>
public static bool TryParse(string s, out DateTime result)
{
//------------------------------------------------------------
// Attempt to convert string representation
//------------------------------------------------------------
bool wasConverted = false;
result = DateTime.MinValue;
if (!String.IsNullOrEmpty(s))
{
DateTime parseResult;
if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))
{
result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);
wasConverted = true;
}
}
return wasConverted;
}
#endregion
}
```
|
284,776 |
<p>I'm automating some source control software functionality using a dot bat script but given that our svn repos are hosted in a *NIX box, I'm facing the eternal case problem between these two worlds.</p>
<p>Is there any cmd.exe function to convert the value of the Windows system variable %USERNAME% to lower case?</p>
<p>Thanks much in advance!</p>
|
[
{
"answer_id": 284834,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 4,
"selected": true,
"text": "<p>a quick google found <a href=\"http://cwashington.netreach.net/depo/view.asp?Index=780\" rel=\"noreferrer\">this</a>... </p>\n\n<pre><code>@echo off\ngoto :end_remarks\n*************************************************************************************\n*\n*\n* authored:Sam Wofford\n* Returns lowercase of a string\n* 12:13 PM 11/13/02\n**************************************************************************************\n:end_remarks\nsetlocal\nset errorlevel=-1\nif {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit\nif {%1}=={/?} call :Help &goto :endit\ncall :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z\n\n:start\nset input=%1\nset input=%input:\"=%\nset totparams=0\ncall :COUNT_PARAMS %input%\ncall :MAKE_LOWERCASE %input%\nset errorlevel=\necho %convertedstring%\nendlocal\ngoto :eof\n:endit\necho %errorlevel%\nendlocal\ngoto :eof\n\n:MAKE_LOWERCASE\n:nextstring\nif {%1}=={} goto :eof\nset string=%1\nset /a params+=1\nset STRINGCONVERTED=\nset pos=0\n:NEXT_CHAR\nset onechar=%%string^:^~%pos%,1%%\nfor /f \"tokens=1,2 delims==\" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c\nif not defined STRINGCONVERTED goto :NEXT_CHAR\nshift /1\nif %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end\ngoto :nextstring\ngoto :eof\n\n:Help\necho USAGE:%~n0 string OR %~n0 \"with spaces\"\necho function returns the lowercase of the string or -1 (error)\necho strings with embedded spaces needs to be in quotes Ex. \"lower case\"\necho in a batch NTscript \"for /f %%%%A in ('lcase STRING') do set var=%%%%A\"\nset errorlevel=\ngoto :eof\n\n:checkit\nset LCFOUND=\nif /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof\nset char=%1\nfor /f \"tokens=2 delims=_=\" %%A in ('set LCASE_') do call :findit %%A %char%\n:skipit\nif defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)\nset /a pos+=1\ngoto :eof\n\n:set_LCASE_array\n:setit\nif {%1}=={} goto :eof\nset LCASE_%1_=%1\nSHIFT /1\ngoto :setit\n\n:findit\nif defined LCFOUND goto :eof\nset ucletter=%1\nset lcchar=%2\nif /i {%ucletter%}=={%lcchar%} set LCFOUND=yes\ngoto :eof\n\n:COUNT_PARAMS\n:COUNTPARAMS\nif {%1}=={} goto :eof\nset /a totparams+=1\nshift /1\ngoto :COUNTPARAMS \n</code></pre>\n\n<p>add that as a file (lowercase.cmd) to your path and you should be able to call it as \"Lowercase.cmd %Username%\", you could pipe it into another command if needed.</p>\n"
},
{
"answer_id": 285405,
"author": "SumoRunner",
"author_id": 18975,
"author_profile": "https://Stackoverflow.com/users/18975",
"pm_score": 3,
"selected": false,
"text": "<p>download some unix utilities for DOS from <a href=\"http://short.stop.home.att.net/freesoft/unix.htm\" rel=\"nofollow noreferrer\">http://short.stop.home.att.net/freesoft/unix.htm</a>\nand use tr.exe (translate characters)</p>\n\n<pre><code>echo %USERNAME% | tr \"[A-Z]\" \"[a-z]\" \n</code></pre>\n\n<p>I also use a DOS extended cmd replacement named 4NT which has a built in command @lower</p>\n\n<pre><code>echo %@lower[%USERNAME%]\n</code></pre>\n"
},
{
"answer_id": 23806517,
"author": "Dharma Leonardi",
"author_id": 2099456,
"author_profile": "https://Stackoverflow.com/users/2099456",
"pm_score": 4,
"selected": false,
"text": "<p>Well, I was browsing for some syntax and stumbled upon this page. I know its old but I thought I'd take a break and give the brain a little kick.</p>\n\n<p>Here's something a little shorter and manageable. This just \"brute forces\" all uppercase letters to lowercase letters without regards to whether the actual letter exists in the string or not. Thus the functional loop runs exactly 26 times no matter the length of the string.</p>\n\n<p>Hope this helps someone.</p>\n\n<pre><code>@echo off\ncls\nsetlocal enabledelayedexpansion\n\nREM ***** Modify as necessary for the string source. *****\nset \"_STRING=%*\"\nif not defined _STRING set \"_STRING=%USERNAME%\"\nset _STRING\nREM ***** Modify as necessary for the string source. *****\n\nset \"_UCASE=ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nset \"_LCASE=abcdefghijklmnopqrstuvwxyz\"\n\nfor /l %%a in (0,1,25) do (\n call set \"_FROM=%%_UCASE:~%%a,1%%\n call set \"_TO=%%_LCASE:~%%a,1%%\n call set \"_STRING=%%_STRING:!_FROM!=!_TO!%%\n)\n\nset _STRING\nendlocal\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>E:\\OS.ADMIN>LCASE.BAT The Quick Fox Jumps Over The Brown Fence.\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>_STRING=The Quick Fox Jumps Over The Brown Fence.\n_STRING=the quick fox jumps over the brown fence.\n</code></pre>\n"
},
{
"answer_id": 26182749,
"author": "Adolfo",
"author_id": 3075331,
"author_profile": "https://Stackoverflow.com/users/3075331",
"pm_score": 2,
"selected": false,
"text": "<pre><code>:: UPcase.bat ==> Store in environment variable _UPcase_ the upper case of %1\n:: -> Use quotes \"\" when the first argument has blanks or special characteres\n::\n:: Adapted from -> http://www.netikka.net/tsneti/info/tscmd039.htm\n::\n:: Note that the substitution method is case insensitive, which means that\n:: while working for this application, it is not useful for all character\n:: substitution tasks.\n::\n:: More concisely, one can capitalize (if you pardon the pun) on the fact\n:: that in for and the substitution lower and upper case source are\n:: equivalent.\n@echo off\n\n:: %~1 -> removes quotes from the first command line argument\n:: http://steve-jansen.github.io/guides/windows-batch-scripting/part-2-variables.html\n@echo off\n::setlocal EnableExtensions\n :: echo %_UPcase_%\n call :ToUpcaseWithFor \"%~1\" _UPcase_\n :: echo %_UPcase_% _doit_1_\n::endlocal & goto :EOF\ngoto :EOF\n::\n:: ======================\n:ToUpcaseWithFor\nsetlocal EnableExtensions EnableDelayedExpansion\n set var_=%~1\n for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (\n set var_=!var_:%%c=%%c!\n )\nendlocal & set %2=%var_%& goto :EOF\n\n:EOF\n:: UPcase.bat ==> EOF\n</code></pre>\n"
},
{
"answer_id": 29118785,
"author": "StackFi Neon",
"author_id": 4680735,
"author_profile": "https://Stackoverflow.com/users/4680735",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.dzone.com/snippets/lowercasing-string-bat-files\" rel=\"noreferrer\">http://www.dzone.com/snippets/lowercasing-string-bat-files</a></p>\n\n<p>lower.bat</p>\n\n<pre><code>echo>%1\ndir /b/l %1>lower.tmp\nset /p result=<lower.tmp\necho %result%\n</code></pre>\n\n<p>cmd</p>\n\n<pre><code>lower \"Mein BinnenMajuskel\"\n</code></pre>\n\n<p>result</p>\n\n<pre><code>mein binnenmajuskel\n</code></pre>\n\n<p>CAUTION: Quick & dirty, but also insecure and dangerous variant. Because you create two files. One called like the given string and another called lower.tmp, which contains the lowered string. What happens if you execute <code>lower \"UserName\"</code> in a directory, where this file or directory already exists? Especially if you delete this files afterwards ...</p>\n\n<p>Improved version:</p>\n\n<pre><code>echo>%Temp%\\%1\ndir /b/l %Temp%\\%1>%Temp%\\lower.tmp\nset /p result=<%Temp%\\lower.tmp\ndel %Temp%\\%1\ndel %Temp%\\lower.tmp\n</code></pre>\n"
},
{
"answer_id": 34085640,
"author": "LukStorms",
"author_id": 4003419,
"author_profile": "https://Stackoverflow.com/users/4003419",
"pm_score": 3,
"selected": false,
"text": "<p>When a scripting language is installed then that can be used with a <code>FOR</code> to set a variable.</p>\n<pre><code>@FOR /F "delims=" %%s IN ('<<some script oneliner>>') DO @set MYVARIABLE=%%s\n</code></pre>\n<p>Reference: <a href=\"https://ss64.com/nt/for_f.html\" rel=\"nofollow noreferrer\">For F Loop</a></p>\n<p>Any scripting language can be used if it can convert a string to lowercase and output the result.</p>\n<p><strong>An example using Perl 5 :</strong></p>\n<pre><code>@FOR /F "delims=" %%s IN ('perl -e "print lc(pop)" %USERNAME%') DO @set USERNAME=%%s\n</code></pre>\n<p><strong>An example using PowerShell :</strong></p>\n<pre><code>@FOR /F "delims=" %%s IN ('powershell -command "(get-item env:'USERNAME').Value.ToLower()"') DO @set USERNAME=%%s\n</code></pre>\n<p>These days, odds are that PowerShell is already installed by default.</p>\n"
},
{
"answer_id": 57327366,
"author": "Victor Mendonça Nogueira",
"author_id": 11841859,
"author_profile": "https://Stackoverflow.com/users/11841859",
"pm_score": 3,
"selected": false,
"text": "<p>In my batch file I'm doing a comparsion between %USERNAME% and a CSV file.</p>\n\n<p>The program would not work if user was logged in UperCase username.</p>\n\n<p>Ex: <br>\nLogin : GB2NOGU // Won't work <br>\nLogin : gb2nogu // Works </p>\n\n<p>Here I could solve my problem doing a insensitive comparison.</p>\n\n<pre><code>if /i %USERNAME%==gb2nogu (\n // Code here\n)\n</code></pre>\n\n<p>The parameter /i tells the cmd to do a insensitive case comparison, so it'll ignore the difference between lowercase and uppercase letters.</p>\n"
},
{
"answer_id": 60063730,
"author": "Io-oI",
"author_id": 8177207,
"author_profile": "https://Stackoverflow.com/users/8177207",
"pm_score": 0,
"selected": false,
"text": " \n\n<p>This is the same answer /by <a href=\"https://stackoverflow.com/users/8177207/it-wasnt-me?tab=profile\">@It Wasn't Me</a> <a href=\"https://superuser.com/a/1522183/969781\">here</a></p>\n\n<hr>\n\n<p>For a predictive character set, this substring <strong><code>Set !var:A=a!</code></strong> works, and only working with <strong>predefined substring</strong> in <strong><a href=\"/questions/tagged/bat\" class=\"post-tag\" title=\"show questions tagged 'bat'\" rel=\"tag\">bat</a>/<a href=\"/questions/tagged/cmd\" class=\"post-tag\" title=\"show questions tagged 'cmd'\" rel=\"tag\">cmd</a></strong>.</p>\n\n<p>For this type of task, why not get a little help with <strong><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a></strong>, which can make it possible to work with unconventional accents and consonants <strong>è, È, ä, Ä, ñ, Ñ, ç, Ç etc.</strong></p>\n\n<p>Where the <strong><a href=\"/questions/tagged/bat\" class=\"post-tag\" title=\"show questions tagged 'bat'\" rel=\"tag\">bat</a>/<a href=\"/questions/tagged/cmd\" class=\"post-tag\" title=\"show questions tagged 'cmd'\" rel=\"tag\">cmd</a></strong> will generate <strong><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a></strong> code, it will be compiled and executed at run time ....</p>\n\n<p>Which solves possible user inputs, in which the sequence comes with accents and the vowels/consonants are different from the conventional ones <strong>[a-z]</strong> and/or <strong>[A_Z]</strong></p>\n\n<hr>\n\n<pre class=\"lang-bat prettyprint-override\"><code>@echo off & setlocal EnableDelayedExpansion \n\ncd /d \"%~dp0\" && title <nul && title ...\\%~dpnx0 /// !time:~0,8! !date!\n\nif exist \"%tmp%\\ToUpLower.cs\" 2>nul >nul del /q /f \"%tmp%\\ToUpLower.cs\" \nset \"_where=%__appdir__%where.exe\" && set \"_csc=%windir%\\Microsoft.NET\"\n>\"%temp%\\ToUpLower.cs\" ( \necho= using System; namespace SUQ1522019 ^{class Program ^{static void Main(string[] args^) ^{\necho= if (args.Length==2 ^&^& args[0].ToLower(^)==\"-l\"^) ^{Console.WriteLine(args[1].ToLower(^)^);^} \necho= if (args.Length==2 ^&^& args[0].ToLower(^)==\"-u\"^) ^{Console.WriteLine(args[1].ToUpper(^)^);^}^}^}^}\n)\n\nset \"_arg=/t:exe /out:\"%tmp%\\ToUpLower.exe\" \"%tmp%\\ToUpLower.cs\" /platform:anycpu \"\nfor /f tokens^=* %%i in ('!_where! /r \"!_csc!\" \"csc.exe\"^|findstr /lic:\"k\\v2\\.\" \n')do \"%%~i\" !_arg! /unsafe+ /w:0 /o /nologo\n\nfor /f tokens^=* %%U in ('\"%tmp%\\ToUpLower.exe\" -u %USERNAME%')do set \"_up_case=%%U\"\nfor /f tokens^=* %%l in ('\"%tmp%\\ToUpLower.exe\" -l %USERNAME%')do set \"_low_case=%%l\"\n\necho/ Your username upcase is: !_up_case!\necho/ Your username lowcase is: !_low_case!\n\necho/ >nul 2>nul copy \"%tmp%\\ToUpLower.exe\" \".\" \ndel /q /f \"%tmp%\\ToUpLower.*\" >nul 2>nul && endlocal & goto :EOF\n</code></pre>\n\n<hr>\n\n<ul>\n<li>Outputs for <strong><code>%USERNAME%</code></strong>\n\n<hr></li>\n</ul>\n\n<pre class=\"lang-bat prettyprint-override\"><code> Your username upcase is: USERNAME\nYour username lowcase is: username\n</code></pre>\n\n<hr>\n\n<p>The <strong><code>ToUpLower.cs</code></strong> <strong><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a></strong> code with no escaping: </p>\n\n<hr>\n\n<pre class=\"lang-bat prettyprint-override\"><code> using System; namespace SUQ1522019 {class Program {static void Main(string[] args) {\n if (args.Length==2 && args[0].ToLower()==\"-l\") {Console.WriteLine(args[1].ToLower());} \n if (args.Length==2 && args[0].ToLower()==\"-u\") {Console.WriteLine(args[1].ToUpper());}}}}\n</code></pre>\n\n<hr>\n\n<p>The <strong><code>ToUpLower.cs</code></strong> <strong><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a></strong> code with no escaping and indented: </p>\n\n<hr>\n\n<pre class=\"lang-bat prettyprint-override\"><code>using System\nnamespace SUQ1522019 \n{\n class Program \n {\n static void Main(string[] args)\n {\n if (args.Length==2 && args[0].ToLower()==\"-l\") \n {\n Console.WriteLine(args[1].ToLower());\n } \n\n if (args.Length==2 && args[0].ToLower()==\"-u\") \n {\n Console.WriteLine(args[1].ToUpper());\n }\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<ul>\n<li>This <strong><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a></strong> code was <strong>compiled/tested</strong> on <strong><code>csc.exe</code></strong> versions:</li>\n</ul>\n\n<pre class=\"lang-bat prettyprint-override\"><code>c:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework\\v3.5\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework64\\v3.5\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe\n</code></pre>\n\n<hr>\n\n<ul>\n<li>This is the <strong>command line</strong> used to <strong>compile</strong> the <strong><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a></strong> code:\n\n<hr></li>\n</ul>\n\n<pre class=\"lang-bat prettyprint-override\"><code>c:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\csc.exe /t:exe /out:\"%tmp%\\ToUpLower.exe\" \"%tmp%\\ToUpLower.cs\" /platform:anycpu /unsafe+ /w:0 /o /nologo \n</code></pre>\n\n<hr>\n\n<ul>\n<li><strong><code>ToUpLower.exe</code> usage</strong> UPPER to -> lower \n<strong>\n\n<hr></li>\n</ul>\n\n<pre class=\"lang-bat prettyprint-override\"><code>ToUpLower.exe -l STRING \n\n:: or ..\n\nToUpLower.exe -L STRING\n</code></pre>\n\n<p></strong></p>\n\n<hr>\n\n<ul>\n<li><strong><code>ToUpLower.exe</code> usage</strong> lower to -> UPPER </li>\n</ul>\n\n<hr>\n\n<p><strong></p>\n\n<pre class=\"lang-bat prettyprint-override\"><code>ToUpLower.exe -u string\n\n:: or ..\n\nToUpLower.exe -U string\n</code></pre>\n\n<p></strong></p>\n\n<hr>\n\n<p>To keep <strong><code>ToUpLower.exe</code></strong>, remove <strong><code>echo/</code></strong> from <strong><code>copy</code></strong> <strong>command</strong>:</p>\n\n<hr>\n\n<pre><strike><strong>echo/</strike></strong> >nul 2>nul copy \"%tmp%\\ToUpLower.exe\" \".\" </pre>\n\n<p>This command line will copy <strong><code>ToUpLower.exe</code></strong> from <strong><code>%temp%</code></strong> to same the same folder where your bat is running.</p>\n\n<hr>\n\n<p>Programming Guide C#:</p>\n\n<ul>\n<li><p><strong><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments\" rel=\"nofollow noreferrer\">Args</a></strong></p></li>\n<li><p><strong><a href=\"https://superuser.com/a/1522183/969781\">ToLower</a></strong></p></li>\n<li><p><strong><a href=\"https://stackoverflow.com/users/8177207/it-wasnt-me?tab=profile\">ToUpper</a></strong></p></li>\n</ul>\n\n<hr>\n\n<p><sub> Sorry my limited <strong>English</strong></sub></p>\n"
},
{
"answer_id": 62028288,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 3,
"selected": false,
"text": "<p>Probably this is the fastest way to convert a string to lowercase in batch file as it uses <a href=\"https://ss64.com/nt/syntax-macros.html\" rel=\"noreferrer\">macro</a> and there are no temp files (it saves the produced string in variable called <code>result</code>):</p>\n\n<pre><code>@echo off\n\nset LowerCaseMacro=for /L %%n in (1 1 2) do if %%n==2 (for %%# in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do set \"result=!result:%%#=%%#!\") else setlocal enableDelayedExpansion ^& set result=\n\nset \"string=SOme STrinG WiTH lowerCAse letterS and UPCase leTTErs\"\n%LowerCaseMacro%%string%\n\necho %result%\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
I'm automating some source control software functionality using a dot bat script but given that our svn repos are hosted in a \*NIX box, I'm facing the eternal case problem between these two worlds.
Is there any cmd.exe function to convert the value of the Windows system variable %USERNAME% to lower case?
Thanks much in advance!
|
a quick google found [this](http://cwashington.netreach.net/depo/view.asp?Index=780)...
```
@echo off
goto :end_remarks
*************************************************************************************
*
*
* authored:Sam Wofford
* Returns lowercase of a string
* 12:13 PM 11/13/02
**************************************************************************************
:end_remarks
setlocal
set errorlevel=-1
if {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit
if {%1}=={/?} call :Help &goto :endit
call :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z
:start
set input=%1
set input=%input:"=%
set totparams=0
call :COUNT_PARAMS %input%
call :MAKE_LOWERCASE %input%
set errorlevel=
echo %convertedstring%
endlocal
goto :eof
:endit
echo %errorlevel%
endlocal
goto :eof
:MAKE_LOWERCASE
:nextstring
if {%1}=={} goto :eof
set string=%1
set /a params+=1
set STRINGCONVERTED=
set pos=0
:NEXT_CHAR
set onechar=%%string^:^~%pos%,1%%
for /f "tokens=1,2 delims==" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c
if not defined STRINGCONVERTED goto :NEXT_CHAR
shift /1
if %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end
goto :nextstring
goto :eof
:Help
echo USAGE:%~n0 string OR %~n0 "with spaces"
echo function returns the lowercase of the string or -1 (error)
echo strings with embedded spaces needs to be in quotes Ex. "lower case"
echo in a batch NTscript "for /f %%%%A in ('lcase STRING') do set var=%%%%A"
set errorlevel=
goto :eof
:checkit
set LCFOUND=
if /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof
set char=%1
for /f "tokens=2 delims=_=" %%A in ('set LCASE_') do call :findit %%A %char%
:skipit
if defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)
set /a pos+=1
goto :eof
:set_LCASE_array
:setit
if {%1}=={} goto :eof
set LCASE_%1_=%1
SHIFT /1
goto :setit
:findit
if defined LCFOUND goto :eof
set ucletter=%1
set lcchar=%2
if /i {%ucletter%}=={%lcchar%} set LCFOUND=yes
goto :eof
:COUNT_PARAMS
:COUNTPARAMS
if {%1}=={} goto :eof
set /a totparams+=1
shift /1
goto :COUNTPARAMS
```
add that as a file (lowercase.cmd) to your path and you should be able to call it as "Lowercase.cmd %Username%", you could pipe it into another command if needed.
|
284,784 |
<p>Some databases support commands such as:</p>
<pre><code>SELECT TOP 10 START AT 10 * FROM <TABLE>
</code></pre>
<p>Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc. Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'.</p>
|
[
{
"answer_id": 284789,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT Top 10 * \nFROM Table \nWHERE <primary key> Not IN (\n SELECT Top 10 <primaryKey> \n FROM Table \n ORDER BY <primary Key> ASC) \nORDER BY <primary Key> ASC\n</code></pre>\n"
},
{
"answer_id": 284790,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "<p>Which version of SQL Server?</p>\n\n<p>In SQL Server 2000 this is a real pain (though possible using ugly tricks like that posted by stingyjack). </p>\n\n<p>In 2005 and later it's a little easier- look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms186734.aspx\" rel=\"nofollow noreferrer\">Row_Number()</a> function.</p>\n\n<p>And, depending on your client application it may not even be that hard. Some of the ASP.Net grid controls have support for automatic paging.</p>\n"
},
{
"answer_id": 284840,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to be compatible with SQL Server 2000 you could use</p>\n\n<pre><code>SELECT * FROM\n(\n SELECT TOP 10 FROM\n (\n SELECT TOP (n * 10) FROM <table> ORDER BY (column) ASC\n ) AS t1 ORDER BY (column) DESC\n) AS t2 ORDER BY (column) ASC\n</code></pre>\n\n<p>In SQL Server 2005 there is a new function Row_Number(). You could use it this way:</p>\n\n<pre><code>WITH Orders AS \n(\n SELECT SalesOrderID, OrderDate, \n ROW_NUMBER() OVER (order by OrderDate) AS 'RowNumber' \n FROM SalesOrder\n) \nSELECT * \nFROM Orders \nWHERE RowNumber between 10 and 19;\n</code></pre>\n"
},
{
"answer_id": 8832334,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 3,
"selected": false,
"text": "<p>For <a href=\"http://msdn.microsoft.com/en-us/library/ms188385%28v=SQL.110%29.aspx\">SQL Server 2012</a></p>\n\n<pre><code>SELECT * \nFROM <TABLE>\nORDER BY <SomeCol>\nOFFSET 10 ROWS\nFETCH NEXT 10 ROWS ONLY;\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678/"
] |
Some databases support commands such as:
```
SELECT TOP 10 START AT 10 * FROM <TABLE>
```
Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc. Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'.
|
Which version of SQL Server?
In SQL Server 2000 this is a real pain (though possible using ugly tricks like that posted by stingyjack).
In 2005 and later it's a little easier- look at the [Row\_Number()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) function.
And, depending on your client application it may not even be that hard. Some of the ASP.Net grid controls have support for automatic paging.
|
284,826 |
<p>I'm on a beginner level course in prolog, doing a map colouring problem. Here's my code.</p>
<pre><code>col(Colors,Map,Coloring) :-
checkMap(Colors,Map,Coloring).
checkMap(Colors,[Country1:Country2],Coloring) :-
goodColor(Country1:Country2,Coloring,Colors).
checkMap(Colors,[Country1:Country2|Rest],Coloring) :-
goodColor(Country1:Country2,Coloring,Colors),
checkMap(Colors,Rest,Coloring).
goodColor(Country1:Country2,Coloring,Colors) :-
mem(Country1:Color1,Coloring),!,
mem(Country2:Color2,Coloring),!,
mem(Color1,Colors), mem(Color2,Colors),
not(Color1=Color2).
mem(Var,[Var|_]).
mem(Var,[_|Rest]) :-
mem(Var,Rest).
</code></pre>
<p>My output looks like this:</p>
<pre><code>?- col([a,b,c],[1:2,1:3,2:3],X).
X = [1:a, 2:b, 3:c|_G332] ;
X = [1:a, 2:c, 3:b|_G332] ;
X = [1:b, 2:a, 3:c|_G332] ;
X = [1:b, 2:c, 3:a|_G332] ;
X = [1:c, 2:a, 3:b|_G332] ;
X = [1:c, 2:b, 3:a|_G332] ;
fail.
</code></pre>
<p>Anyone know how I can get rid of the trailing variable? I know it's mostly cosmetic, but I don't see why it's there.</p>
|
[
{
"answer_id": 285001,
"author": "Nelson",
"author_id": 27366,
"author_profile": "https://Stackoverflow.com/users/27366",
"pm_score": 1,
"selected": false,
"text": "<p>Using an incomplete data structure is a valid Prolog programming technique. If your intention is to use an incomplete data structure then one solution is:</p>\n\n<pre><code>ground_terms([H|T1],[H|T2]) :- ground(H), !, ground_terms(T1,T2).\nground_terms(_,[]).\n</code></pre>\n\n<p>and change col as follows:</p>\n\n<pre><code>col(Colors,Map,Coloring) :-\n checkMap(Colors,Map,Coloring1),\n ground_terms(Coloring1,Coloring).\n</code></pre>\n"
},
{
"answer_id": 287788,
"author": "tonys",
"author_id": 35439,
"author_profile": "https://Stackoverflow.com/users/35439",
"pm_score": 0,
"selected": false,
"text": "<p>The trailing variable is there because <code>mem(Var,[Var|_])</code> binds the unbound <code>Coloring</code> variable to <code>[Var|_]</code>.</p>\n\n<p>One way to avoid it is to accumulate the map coloring e.g (very quick and extremely dirty):</p>\n\n<pre><code>col(Colors,Map,Coloring) :-\n check(Colors,Map,[],Coloring).\n\ncheck(Colors,[],Coloring,Coloring).\n\ncheck(Colors,[Country1:Country2 | T],[],L) :-\n member(Color1,Colors),\n member(Color2,Colors),\n Color1 \\== Color2,\n check(Colors,T,[Country1:Color1,Country2:Color2],L).\n\ncheck(Colors,[Country1:Country2 | T],Coloring,L) :-\n member(Country1:Color1,Coloring),\n member(Country2:Color2,Coloring),!,\n check(Colors,T,Coloring,L).\n\ncheck(Colors,[Country1:Country2 | T],Coloring,L) :-\n member(Country1:Color1,Coloring),!,\n member(Color2,Colors),\n not(member(_:Color2,Coloring)),\n check(Colors,T,[Country2:Color2|Coloring],L).\n\ncheck(Colors,[Country1:Country2 | T],Coloring,L) :-\n member(Country2:Color2,Coloring),!,\n member(Color1,Colors),\n not(member(_:Color1,Coloring)),\n check(Colors,T,[Country1:Color1|Coloring],L).\n</code></pre>\n\n<p>Its a much more 'procedural' approach than yours though :-(. There's probably a more elegant way...</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36990/"
] |
I'm on a beginner level course in prolog, doing a map colouring problem. Here's my code.
```
col(Colors,Map,Coloring) :-
checkMap(Colors,Map,Coloring).
checkMap(Colors,[Country1:Country2],Coloring) :-
goodColor(Country1:Country2,Coloring,Colors).
checkMap(Colors,[Country1:Country2|Rest],Coloring) :-
goodColor(Country1:Country2,Coloring,Colors),
checkMap(Colors,Rest,Coloring).
goodColor(Country1:Country2,Coloring,Colors) :-
mem(Country1:Color1,Coloring),!,
mem(Country2:Color2,Coloring),!,
mem(Color1,Colors), mem(Color2,Colors),
not(Color1=Color2).
mem(Var,[Var|_]).
mem(Var,[_|Rest]) :-
mem(Var,Rest).
```
My output looks like this:
```
?- col([a,b,c],[1:2,1:3,2:3],X).
X = [1:a, 2:b, 3:c|_G332] ;
X = [1:a, 2:c, 3:b|_G332] ;
X = [1:b, 2:a, 3:c|_G332] ;
X = [1:b, 2:c, 3:a|_G332] ;
X = [1:c, 2:a, 3:b|_G332] ;
X = [1:c, 2:b, 3:a|_G332] ;
fail.
```
Anyone know how I can get rid of the trailing variable? I know it's mostly cosmetic, but I don't see why it's there.
|
Using an incomplete data structure is a valid Prolog programming technique. If your intention is to use an incomplete data structure then one solution is:
```
ground_terms([H|T1],[H|T2]) :- ground(H), !, ground_terms(T1,T2).
ground_terms(_,[]).
```
and change col as follows:
```
col(Colors,Map,Coloring) :-
checkMap(Colors,Map,Coloring1),
ground_terms(Coloring1,Coloring).
```
|
284,832 |
<pre><code>For Each line As String In System.IO.File.ReadAllLines("file.txt")
'Do Something'
Next
</code></pre>
<p>and</p>
<pre><code>Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine
'put you line processing code here
End While
End Using
End Using
</code></pre>
<p>are both showing as mostly red, I'm running a clean install of MS VS2005 and these codes were both recomended to me, am I missing something else I need to install or declare?</p>
|
[
{
"answer_id": 284866,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": false,
"text": "<p>FROM Msdn you should do the following to read all lines</p>\n\n<pre><code>Dim Lines As String()\nLines = System.IO.File.ReadAllLines(\"file.txt\")\n</code></pre>\n\n<p>For the second example something like this might work</p>\n\n<pre><code>Dim sr as New StreamReader(\"somefile.txt\")\nDim line as String = sr.ReadLine()\nDo While Not line is Nothing\n line = sr.ReadLine()\n 'do something else\nLoop\n</code></pre>\n\n<p>I just created the following VB.Net Console app and it works fine:</p>\n\n<pre><code>Imports System.IO\n\nModule Module1\n\nSub Main()\n Dim sr As New StreamReader(\"somefile.txt\")\n Dim line As String = sr.ReadLine()\n Do While Not line Is Nothing\n line = sr.ReadLine()\n 'do something else\n Loop\n\nEnd Sub\n\nEnd Module\n</code></pre>\n"
},
{
"answer_id": 284880,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 1,
"selected": false,
"text": "<p>Do you have your code surrounded by a class and method?</p>\n\n<pre><code>Public class CodeClass\n Public Sub CodeMethod\n\n Using f As System.IO.FileStream = System.IO.File.OpenRead(\"somefile.txt\")\n Using s As System.IO.StreamReader = New System.IO.StreamReader(f)\n While Not s.EndOfStream\n Dim line As String = s.ReadLine\n\n //Non-vb comment for easier to read SO code\n End While\n End Using\n End Using\n\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 284955,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": true,
"text": "<p>for vb6.0 you need</p>\n\n<pre><code>Dim value As String = My.Computer.FileSystem.ReadAllText(file)\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
For Each line As String In System.IO.File.ReadAllLines("file.txt")
'Do Something'
Next
```
and
```
Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine
'put you line processing code here
End While
End Using
End Using
```
are both showing as mostly red, I'm running a clean install of MS VS2005 and these codes were both recomended to me, am I missing something else I need to install or declare?
|
for vb6.0 you need
```
Dim value As String = My.Computer.FileSystem.ReadAllText(file)
```
|
284,833 |
<p>This is related to some other questions, such as: <a href="https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c">this</a>, and some of my other questions.</p>
<p>In <a href="https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c">this question</a>, and others, we see we can declare and initialise string arrays in one nice step, for example:</p>
<pre><code>const char* const list[] = {"zip", "zam", "bam"}; //from other question
</code></pre>
<p>This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.</p>
<p>What I want to do is to have an array like this as as member of a class I am using, something like this:</p>
<pre><code>class DataProvider : public SomethingElse
{
const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
public:
DataProvider();
~DataProvider();
char* GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
</code></pre>
<p>But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?</p>
|
[
{
"answer_id": 284843,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>This is not possible in C++. You cannot directly initialize the array. Instead you have to give it the size it will have (4 in your case), and you have to initialize the array in the constructor of DataProvider:</p>\n\n<pre><code>class DataProvider {\n enum { SIZEOF_VALUES = 4 };\n const char * values[SIZEOF_VALUES];\n\n public:\n DataProvider() {\n const char * const v[SIZEOF_VALUES] = { \n \"one\", \"two\", \"three\", \"four\" \n };\n std::copy(v, v + SIZEOF_VALUES, values);\n }\n};\n</code></pre>\n\n<p>Note that you have to give up on the const-ness of the pointers in the array, since you cannot directly initialize the array. But you need to later set the pointers to the right values, and thus the pointers need to be modifiable. </p>\n\n<p>If your values in the array are const nevertheless, the only way is to use a static array:</p>\n\n<pre><code>/* in the header file */\nclass DataProvider {\n enum { SIZEOF_VALUES = 4 };\n static const char * const values[SIZEOF_VALUES];\n};\n\n/* in cpp file: */\n\nconst char * const DataProvider::values[SIZEOF_VALUES] = \n { \"one\", \"two\", \"three\", \"four\" };\n</code></pre>\n\n<p>Having the static array means all objects will share that array. Thus you will have saved memory too.</p>\n"
},
{
"answer_id": 284845,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 2,
"selected": false,
"text": "<p>The reason you can't declare your array like that (const char* []) is that:</p>\n\n<ul>\n<li>you can't have initializers in the class declaration, and so</li>\n<li>the syntax <code>const char* []</code> does not state how much space the compiler needs to allocate for each instance (your array is declared as instance variable).</li>\n</ul>\n\n<p>Besides, you probably want to make that array static, since it is in essence a constant value.</p>\n"
},
{
"answer_id": 284859,
"author": "Stefan Rådström",
"author_id": 19981,
"author_profile": "https://Stackoverflow.com/users/19981",
"pm_score": 5,
"selected": true,
"text": "<p>Use the keyword static and external initialization to make the array a static member of the class:</p>\n\n<p>In the header file:</p>\n\n<pre><code>class DataProvider : public SomethingElse\n{\n static const char* const mStringData[];\n\npublic:\n DataProvider();\n ~DataProvider();\n\n const char* const GetData()\n {\n int index = GetCurrentIndex(); //work out the index based on some other data\n return mStringData[index]; //error checking and what have you omitted\n }\n\n};\n</code></pre>\n\n<p>In the .cpp file:</p>\n\n<pre><code>const char* const DataProvider::mStringData[] = {\"Name1\", \"Name2\", \"Name3\", ... \"NameX\"};\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15667/"
] |
This is related to some other questions, such as: [this](https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c), and some of my other questions.
In [this question](https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c), and others, we see we can declare and initialise string arrays in one nice step, for example:
```
const char* const list[] = {"zip", "zam", "bam"}; //from other question
```
This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.
What I want to do is to have an array like this as as member of a class I am using, something like this:
```
class DataProvider : public SomethingElse
{
const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
public:
DataProvider();
~DataProvider();
char* GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
```
But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?
|
Use the keyword static and external initialization to make the array a static member of the class:
In the header file:
```
class DataProvider : public SomethingElse
{
static const char* const mStringData[];
public:
DataProvider();
~DataProvider();
const char* const GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
```
In the .cpp file:
```
const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
```
|
284,858 |
<p>My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.</p>
<p>I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.</p>
<p>I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?</p>
<pre><code>MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...
</code></pre>
|
[
{
"answer_id": 284881,
"author": "Jb Evain",
"author_id": 36702,
"author_profile": "https://Stackoverflow.com/users/36702",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know of any builtin class to parse ini file. I've used <a href=\"http://sourceforge.net/projects/nini\" rel=\"noreferrer\">nini</a> when needed to do so. It's licensed under the MIT/X11 license, so doesn't have any issue to be included in a closed source program.</p>\n\n<p>It's very to use. So if you have a Settings.ini file formatted this way:</p>\n\n<pre><code>[Configuration]\nName = Jb Evain\nPhone = +330101010101\n</code></pre>\n\n<p>Using it would be as simple as:</p>\n\n<pre><code>var source = new IniConfigSource (\"Settings.ini\");\nvar config = source.Configs [\"Configuration\"];\n\nstring name = config.Get (\"Name\");\nstring phone = config.Get (\"Phone\");\n</code></pre>\n"
},
{
"answer_id": 284882,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 0,
"selected": false,
"text": "<p>Format the file this way:</p>\n\n<pre><code>key1=value1\nkey2=value2\n</code></pre>\n\n<p>Read the entire file into a string (there is a simple convenience function that does that, maybe in the File or string class), and call string.Split('='). Make sure you also call string.Trim() on each key and value as you traverse the list and pop each pair into a hashtable or dictionary.</p>\n"
},
{
"answer_id": 284892,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 4,
"selected": true,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx\" rel=\"noreferrer\">KeyValuePair</a> class for you Key and Value, then just serialize a <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"noreferrer\">List</a> to disk with an <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx\" rel=\"noreferrer\">XMLSerializer</a>. </p>\n\n<p>That would be the simplest approach I feel. You wouldn't have to worry about traversing nodes. Calling the Deserialize function will do that for you. The user could edit the values in the file if they wish also.</p>\n"
},
{
"answer_id": 284903,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>if you want the user to be able to read and modify the file, i suggest a comma-delimited pair, one per line</p>\n\n<pre><code>key1,value1\nkey2,value2\n...\n</code></pre>\n\n<p>parsing is simple: read the file, split at newline or comma, then take the elements in pairs</p>\n"
},
{
"answer_id": 27532519,
"author": "Kyght",
"author_id": 1636133,
"author_profile": "https://Stackoverflow.com/users/1636133",
"pm_score": 3,
"selected": false,
"text": "<p>If you're looking for a quick easy function and don't want to use .Net app\\user config setting files or worry about serialization issues that sometimes occur of time. </p>\n\n<p>The following static function can load a file formatted like <code>KEY=VALUE</code>. </p>\n\n<pre><code>public static Dictionary<string, string> LoadConfig(string settingfile)\n{\n var dic = new Dictionary<string, string>();\n\n if (File.Exists(settingfile))\n {\n var settingdata = File.ReadAllLines(settingfile);\n for (var i = 0; i < settingdata.Length; i++)\n {\n var setting = settingdata[i];\n var sidx = setting.IndexOf(\"=\");\n if (sidx >= 0)\n {\n var skey = setting.Substring(0, sidx);\n var svalue = setting.Substring(sidx+1);\n if (!dic.ContainsKey(skey))\n {\n dic.Add(skey, svalue);\n }\n }\n }\n }\n\n return dic;\n}\n</code></pre>\n\n<p><em>Note: I'm using a Dictionary so keys must be unique, which is usually that case with setting.</em> </p>\n\n<p>USAGE:</p>\n\n<pre><code>var settingfile = AssemblyDirectory + \"\\\\mycustom.setting\";\nvar settingdata = LoadConfig(settingfile);\nif (settingdata.ContainsKey(\"lastrundate\"))\n{\n DateTime lout;\n string svalue;\n if (settingdata.TryGetValue(\"lastrundate\", out svalue))\n {\n DateTime.TryParse(svalue, out lout);\n lastrun = lout;\n }\n}\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29442/"
] |
My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.
I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.
I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?
```
MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...
```
|
Use the [KeyValuePair](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class for you Key and Value, then just serialize a [List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) to disk with an [XMLSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx).
That would be the simplest approach I feel. You wouldn't have to worry about traversing nodes. Calling the Deserialize function will do that for you. The user could edit the values in the file if they wish also.
|
284,867 |
<p>I'm trying to dynamically generate a gif image of a specified size and color in an HttpHandler. For some reason, the image is being generated with a dithered color pattern rather than the solid color I expected the <strong><em>SolidBrush</em></strong> to create. The following code is the simplest I could find that exposes the problem.</p>
<pre><code>private void GenerateSquareImage(String filename, String color, Int32 width)
{
Bitmap img = new Bitmap(width, width);
Graphics g = Graphics.FromImage(img);
SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml("#" + color));
g.FillRectangle(brush, 0, 0, width, width);
img.Save(filename, System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
brush.Dispose();
g.Dispose();
}
</code></pre>
<p>Here is a sample of the results I'm getting when passing "415976" in the color parameter:</p>
<p><a href="http://img148.imageshack.us/img148/8936/colorcb5.png" rel="nofollow noreferrer">imageshack http://img148.imageshack.us/img148/8936/colorcb5.png</a></p>
<p>(The block on the left is an HTML SPAN with background-color set to #415976. The block on the right is my graphic, where you can see the dithered colors.)</p>
<p>The result is the same if I use this code:</p>
<pre><code>g.Clear(ColorTranslator.FromHtml("#" + color));
</code></pre>
<p>in place of the g.FillRectangle call in the method above.</p>
<p><strong>UPDATE:</strong> By default, GDI+ saves GIFs with the <a href="http://oreilly.com/catalog/wdnut/excerpt/web_palette.html" rel="nofollow noreferrer">web safe palette</a> if any programmatic changes are made to the Bitmap. This is what was causing my non safe palette color to be dithered. I was able to modify the code referenced in Marco's post below (<a href="http://msdn.microsoft.com/en-us/library/aa479306.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa479306.aspx</a>) to modify the palette on my freshly created image so that my color was respected.</p>
|
[
{
"answer_id": 284893,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>IIRC GIF's are limited to a specific pallete on .NET. There are workarounds, but they were above my understanding.</p>\n"
},
{
"answer_id": 285189,
"author": "Marco M.",
"author_id": 28375,
"author_profile": "https://Stackoverflow.com/users/28375",
"pm_score": 3,
"selected": true,
"text": "<p>GIF files are limited to 256 colors as far as I know, so it resorts to dithering.\nPNG is probably the format you need.</p>\n\n<p>Or you can look <a href=\"http://www.glennjones.net/Post/799/Highqualitydynamicallyresizedimageswithnet.htm\" rel=\"nofollow noreferrer\">here</a> for a solution using a complex quantizer to build a custom palette (I don't take responsibility for the code in the link, never tried myself). </p>\n\n<p>This <a href=\"http://msdn.microsoft.com/en-us/library/aa479306.aspx\" rel=\"nofollow noreferrer\">other link from Microsoft</a> has an in-depth analysis of the problem.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5420/"
] |
I'm trying to dynamically generate a gif image of a specified size and color in an HttpHandler. For some reason, the image is being generated with a dithered color pattern rather than the solid color I expected the ***SolidBrush*** to create. The following code is the simplest I could find that exposes the problem.
```
private void GenerateSquareImage(String filename, String color, Int32 width)
{
Bitmap img = new Bitmap(width, width);
Graphics g = Graphics.FromImage(img);
SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml("#" + color));
g.FillRectangle(brush, 0, 0, width, width);
img.Save(filename, System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
brush.Dispose();
g.Dispose();
}
```
Here is a sample of the results I'm getting when passing "415976" in the color parameter:
[imageshack http://img148.imageshack.us/img148/8936/colorcb5.png](http://img148.imageshack.us/img148/8936/colorcb5.png)
(The block on the left is an HTML SPAN with background-color set to #415976. The block on the right is my graphic, where you can see the dithered colors.)
The result is the same if I use this code:
```
g.Clear(ColorTranslator.FromHtml("#" + color));
```
in place of the g.FillRectangle call in the method above.
**UPDATE:** By default, GDI+ saves GIFs with the [web safe palette](http://oreilly.com/catalog/wdnut/excerpt/web_palette.html) if any programmatic changes are made to the Bitmap. This is what was causing my non safe palette color to be dithered. I was able to modify the code referenced in Marco's post below (<http://msdn.microsoft.com/en-us/library/aa479306.aspx>) to modify the palette on my freshly created image so that my color was respected.
|
GIF files are limited to 256 colors as far as I know, so it resorts to dithering.
PNG is probably the format you need.
Or you can look [here](http://www.glennjones.net/Post/799/Highqualitydynamicallyresizedimageswithnet.htm) for a solution using a complex quantizer to build a custom palette (I don't take responsibility for the code in the link, never tried myself).
This [other link from Microsoft](http://msdn.microsoft.com/en-us/library/aa479306.aspx) has an in-depth analysis of the problem.
Hope this helps.
|
284,868 |
<p>I am writing event data to a log file in an asp.net httphandler by using the File.AppendAllText method. I am concerned with what will happen when multiple requests are received simultaneously. Does AppendAllText lock the file it's writing to?</p>
|
[
{
"answer_id": 284894,
"author": "DCNYAM",
"author_id": 30419,
"author_profile": "https://Stackoverflow.com/users/30419",
"pm_score": 2,
"selected": false,
"text": "<p>You can use My.Log to write to log files. </p>\n\n<p>Edit: If you use the FileLogTraceListener, that listener is thread-safe.</p>\n\n<p>Doing this also allows you to control and configure the logging through the web.config file.</p>\n"
},
{
"answer_id": 284897,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 4,
"selected": true,
"text": "<p>no, you should have a static lock object guarding the log-file write, e.g.</p>\n\n<pre><code>public static object LockingTarget = new object();\n\npublic void LogToFile(string msg)\n{\n lock(LockingTarget)\n {\n //append to file here as fast as possible\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1097693,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": false,
"text": "<p>I recommend using the <code>TextWriterTraceListener</code> instead of trying to manage this your self.</p>\n\n<p>It is very simple to setup and use:</p>\n\n<pre><code>TextWriterTraceListener logListener = new TextWriterTraceListener(\"C:\\log.txt\", \"My Log Name\");\nTrace.Listeners.Add(logListener);\n</code></pre>\n\n<p>And then to log something:</p>\n\n<pre><code>Trace.WriteLine(\"Log this text\");\n</code></pre>\n\n<p>It is very simple to use and also there are many different types of listeners for SQL, Event Log, text file, etc. So you won't have to adjust your code if you want to change out the listener.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am writing event data to a log file in an asp.net httphandler by using the File.AppendAllText method. I am concerned with what will happen when multiple requests are received simultaneously. Does AppendAllText lock the file it's writing to?
|
no, you should have a static lock object guarding the log-file write, e.g.
```
public static object LockingTarget = new object();
public void LogToFile(string msg)
{
lock(LockingTarget)
{
//append to file here as fast as possible
}
}
```
|
284,885 |
<p>I am trying to gain a better understanding of tcp/ip sockets in c#, as i want to challenge myself to see if i can create a working MMO infrastructure (game world, map, players, etc) purely for educational purposes as i have no intention of being another one of those "OMGZ iz gonna make my r0x0r MMORPG that will be better than WoW!!!", you know what im talking about.</p>
<p>Anyway, i was wondering if anyone can shed some light as to how one might approach designing this kind of system and what kinds of things are required, and what i should watch out for?</p>
<p>My initial idea was to break up the system into seperate client/server connections with each connection (on its own port) performing a specific task, such as updating player/monster positions, sending and receiving chat messages, etc. which to me would make processing the data easier because you wouldn't always need to put a header on the data to know what information the packet contains. </p>
<p>Does that make sense and is useful or am i just way over complicating things?</p>
<p>your responses are very much appreciated.</p>
|
[
{
"answer_id": 284943,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 1,
"selected": false,
"text": "<p>I would advise against multiple connections for the different information. I would design some protocol that contains a header with information to be processed. Use as little resources as possible. Also, you may not want to send updates for various positions and stats from the client to the server. Otherwise you may end up in a situation where a user can modify their data being sent back to the server.</p>\n\n<p>Say a user falsifies a monster's location to get past something. I would only update the user's position vector, and actions. Let the rest of the information be processed and validated by the server.</p>\n"
},
{
"answer_id": 284956,
"author": "Jason Miesionczek",
"author_id": 18811,
"author_profile": "https://Stackoverflow.com/users/18811",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah i think you're right about the single connection, and of course the client wouldnt be sending any actual data to the server, more like just simple commands like 'move forward', 'turn left', etc. and the server would move the character on the map and send the new co-ordinates back to the client. </p>\n"
},
{
"answer_id": 285188,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to crawl before you walk and before you run. First get the design of the framework and connections right, then worry about scalability. If your goal is to learn C# and tcp/ip programming, then don't make this harder on yourself. </p>\n\n<p>Go ahead with your initial thoughts and keep the data streams separate. </p>\n\n<p>have fun and good luck</p>\n"
},
{
"answer_id": 285986,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 6,
"selected": true,
"text": "<p>If you are doing socket level programming, then regardless of how many ports you open for each message type, you still need to have a header of some sort. Even if it is just the length of the rest of the message. Having said that it is easy to add a simple header and tail structure to a message. I would think it is easier to only have to deal with one port on the client side.</p>\n\n<p>I believe the modern MMORPGs (and maybe even the old ones) had two levels of servers. The login servers which verify you as a paying client. Once verified these pass you off to the game server which contain all the game world information. Even so this still only requires the client to have one socket open, but does not disallow having more.</p>\n\n<p>Additionally most MMORPGS also encrypt all their data. If you are writing this as an exercise for fun, then this will not matter so much.</p>\n\n<p>For designing/writing protocols in general here are the things I worry about:<BR></p>\n\n<p><strong>Endianess</strong></p>\n\n<p>Are the client and server always guaranteed to have the same endianess. If not I need to handle that in my serialization code. There are multiple ways to handle endianess.</p>\n\n<ol>\n<li>Ignore it - Obviously a bad choice</li>\n<li>Specify the endianness of the protocol. This is what the older protocols did/do hence the term network order which was always big endian. It doesn't actually matter which endianess you specify just that you specify one or the other. Some crusty old network programmers will get up in arms if you don't use big endianess, but if your servers and most clients are little endian you really aren't buying yourself anything other than extra work by making the protocol big endian.</li>\n<li>Mark the Endianess in each header - You can add a cookie which will tell you the endianess of the client/server and let each message be converted accordingly as needed. Extra work!</li>\n<li>Make your protocol agnostic - If you send everything as ASCII strings, then endianess is irrelevant, but also a lot more inefficient.</li>\n</ol>\n\n<p>Of the 4 I would usually choose 2, and specify the endianess to be that of the majority of the clients, which now days will be little endian.</p>\n\n<p><strong>Forwards and Backwards Compatibility</strong></p>\n\n<p>Does the protocol need to be forwards and backwards compatible. The answer should almost always be yes. In which case this will determine how I design the over all protocol in terms of versioning, and how each individual message is created to handle minor changes that really shouldn't be part of the versioning. You can punt on this and use XML, but you lose a lot of efficiency. </p>\n\n<p>For the overall versioning I usually design something simple. The client sends a versioning message specifying that it speaks version X.Y, as long as the server can support that version it sends back a message acknowledging the version of the client and everything proceeds forward. Otherwise it nacks the client and terminates the connection.</p>\n\n<p>For each message you have something like the following:</p>\n\n<pre><code>+-------------------------+-------------------+-----------------+------------------------+\n| Length of Msg (4 bytes) | MsgType (2 bytes) | Flags (4 bytes) | Msg (length - 6 bytes) |\n+-------------------------+-------------------+-----------------+------------------------+\n</code></pre>\n\n<p>The length obviously tells you how long the message is, not including the length itself. The MsgType is the type of the message. Only two bytes for this, since 65356 is plenty of messages types for applications. The flags are there to let you know what is serialized in the message. This field combined with the length is what gives you your forwards and backwards compatibility.</p>\n\n<pre><code>const uint32_t FLAG_0 = (1 << 0);\nconst uint32_t FLAG_1 = (1 << 1);\nconst uint32_t FLAG_2 = (1 << 2);\n...\nconst uint32_t RESERVED_32 = (1 << 31);\n</code></pre>\n\n<p>Then your deserialization code can do something like the following:</p>\n\n<pre><code>uint32 length = MessageBuffer.ReadUint32();\nuint32 start = MessageBuffer.CurrentOffset();\nuint16 msgType = MessageBuffer.ReadUint16();\nuint32 flags = MessageBuffer.ReadUint32();\n\nif (flags & FLAG_0)\n{\n // Read out whatever FLAG_0 represents.\n // Single or multiple fields\n}\n// ...\n// read out the other flags\n// ...\n\nMessageBuffer.AdvanceToOffset(start + length);\n</code></pre>\n\n<p>This allows you to <strong>add</strong> new fields <strong>to the end</strong> of the messages without having to revision the entire protocol. It also ensures that old servers and clients will ignore flags they don't know about. If they have to use the new flags and fields, then you simply change the overall protocol version.</p>\n\n<p><strong>Use a Frame Work or Not</strong></p>\n\n<p>There are various network frameworks I would consider using for a business application. Unless I had a specific need to scratch I would go with a standard framework. In your case you want to learn socket level programming, so this is a question already answered for you.</p>\n\n<p>If one does use a framework make sure it addresses the two concerns above, or at least does not get in your way if you need to customize it in those areas.</p>\n\n<p><strong>Am I dealing with a third party</strong></p>\n\n<p>In many cases you may be dealing with a third party server/client you need to communicate with. This implies a few scenarios:</p>\n\n<ul>\n<li>They already have a protocol defined - Simply use their protocol.</li>\n<li>You already have a protocol defined (and they are willing to use it) - again simple use the defined protocol</li>\n<li>They use a standard Framework (WSDL based, etc) - Use the framework.</li>\n<li>Neither party has a protocol defined - Try to determing the best solution based on all the factors at hand (all the ones I mentioned here), as well as their level of competencey (at least as far as you can tell). Regardless make sure both sides agree on and understand the protocol. From experience this can be painful or pleasant. It depends on who you are working with.</li>\n</ul>\n\n<p>In either case you will not be working with a third party, so this is really just added for completeness.</p>\n\n<p>I feel as if I could write much more about this, but it is already rather lengthy. I hopes this helps and if you have any specific questions just ask on Stackoverflow.</p>\n\n<p><strong>An edit to answer knoopx's question:</strong></p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Protocol_Buffers\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Protocol_Buffers</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Thrift_%28protocol%29\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Thrift_(protocol)</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Etch_%28protocol%29\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Etch_(protocol)</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Adaptive_Communication_Environment\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Adaptive_Communication_Environment</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/CORBA\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/CORBA</a></li>\n<li>And many more</li>\n</ul>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
I am trying to gain a better understanding of tcp/ip sockets in c#, as i want to challenge myself to see if i can create a working MMO infrastructure (game world, map, players, etc) purely for educational purposes as i have no intention of being another one of those "OMGZ iz gonna make my r0x0r MMORPG that will be better than WoW!!!", you know what im talking about.
Anyway, i was wondering if anyone can shed some light as to how one might approach designing this kind of system and what kinds of things are required, and what i should watch out for?
My initial idea was to break up the system into seperate client/server connections with each connection (on its own port) performing a specific task, such as updating player/monster positions, sending and receiving chat messages, etc. which to me would make processing the data easier because you wouldn't always need to put a header on the data to know what information the packet contains.
Does that make sense and is useful or am i just way over complicating things?
your responses are very much appreciated.
|
If you are doing socket level programming, then regardless of how many ports you open for each message type, you still need to have a header of some sort. Even if it is just the length of the rest of the message. Having said that it is easy to add a simple header and tail structure to a message. I would think it is easier to only have to deal with one port on the client side.
I believe the modern MMORPGs (and maybe even the old ones) had two levels of servers. The login servers which verify you as a paying client. Once verified these pass you off to the game server which contain all the game world information. Even so this still only requires the client to have one socket open, but does not disallow having more.
Additionally most MMORPGS also encrypt all their data. If you are writing this as an exercise for fun, then this will not matter so much.
For designing/writing protocols in general here are the things I worry about:
**Endianess**
Are the client and server always guaranteed to have the same endianess. If not I need to handle that in my serialization code. There are multiple ways to handle endianess.
1. Ignore it - Obviously a bad choice
2. Specify the endianness of the protocol. This is what the older protocols did/do hence the term network order which was always big endian. It doesn't actually matter which endianess you specify just that you specify one or the other. Some crusty old network programmers will get up in arms if you don't use big endianess, but if your servers and most clients are little endian you really aren't buying yourself anything other than extra work by making the protocol big endian.
3. Mark the Endianess in each header - You can add a cookie which will tell you the endianess of the client/server and let each message be converted accordingly as needed. Extra work!
4. Make your protocol agnostic - If you send everything as ASCII strings, then endianess is irrelevant, but also a lot more inefficient.
Of the 4 I would usually choose 2, and specify the endianess to be that of the majority of the clients, which now days will be little endian.
**Forwards and Backwards Compatibility**
Does the protocol need to be forwards and backwards compatible. The answer should almost always be yes. In which case this will determine how I design the over all protocol in terms of versioning, and how each individual message is created to handle minor changes that really shouldn't be part of the versioning. You can punt on this and use XML, but you lose a lot of efficiency.
For the overall versioning I usually design something simple. The client sends a versioning message specifying that it speaks version X.Y, as long as the server can support that version it sends back a message acknowledging the version of the client and everything proceeds forward. Otherwise it nacks the client and terminates the connection.
For each message you have something like the following:
```
+-------------------------+-------------------+-----------------+------------------------+
| Length of Msg (4 bytes) | MsgType (2 bytes) | Flags (4 bytes) | Msg (length - 6 bytes) |
+-------------------------+-------------------+-----------------+------------------------+
```
The length obviously tells you how long the message is, not including the length itself. The MsgType is the type of the message. Only two bytes for this, since 65356 is plenty of messages types for applications. The flags are there to let you know what is serialized in the message. This field combined with the length is what gives you your forwards and backwards compatibility.
```
const uint32_t FLAG_0 = (1 << 0);
const uint32_t FLAG_1 = (1 << 1);
const uint32_t FLAG_2 = (1 << 2);
...
const uint32_t RESERVED_32 = (1 << 31);
```
Then your deserialization code can do something like the following:
```
uint32 length = MessageBuffer.ReadUint32();
uint32 start = MessageBuffer.CurrentOffset();
uint16 msgType = MessageBuffer.ReadUint16();
uint32 flags = MessageBuffer.ReadUint32();
if (flags & FLAG_0)
{
// Read out whatever FLAG_0 represents.
// Single or multiple fields
}
// ...
// read out the other flags
// ...
MessageBuffer.AdvanceToOffset(start + length);
```
This allows you to **add** new fields **to the end** of the messages without having to revision the entire protocol. It also ensures that old servers and clients will ignore flags they don't know about. If they have to use the new flags and fields, then you simply change the overall protocol version.
**Use a Frame Work or Not**
There are various network frameworks I would consider using for a business application. Unless I had a specific need to scratch I would go with a standard framework. In your case you want to learn socket level programming, so this is a question already answered for you.
If one does use a framework make sure it addresses the two concerns above, or at least does not get in your way if you need to customize it in those areas.
**Am I dealing with a third party**
In many cases you may be dealing with a third party server/client you need to communicate with. This implies a few scenarios:
* They already have a protocol defined - Simply use their protocol.
* You already have a protocol defined (and they are willing to use it) - again simple use the defined protocol
* They use a standard Framework (WSDL based, etc) - Use the framework.
* Neither party has a protocol defined - Try to determing the best solution based on all the factors at hand (all the ones I mentioned here), as well as their level of competencey (at least as far as you can tell). Regardless make sure both sides agree on and understand the protocol. From experience this can be painful or pleasant. It depends on who you are working with.
In either case you will not be working with a third party, so this is really just added for completeness.
I feel as if I could write much more about this, but it is already rather lengthy. I hopes this helps and if you have any specific questions just ask on Stackoverflow.
**An edit to answer knoopx's question:**
* <http://en.wikipedia.org/wiki/Protocol_Buffers>
* [http://en.wikipedia.org/wiki/Thrift\_(protocol)](http://en.wikipedia.org/wiki/Thrift_%28protocol%29)
* [http://en.wikipedia.org/wiki/Etch\_(protocol)](http://en.wikipedia.org/wiki/Etch_%28protocol%29)
* <http://en.wikipedia.org/wiki/Adaptive_Communication_Environment>
* <http://en.wikipedia.org/wiki/CORBA>
* And many more
|
284,889 |
<p>I am about to embark on a rewrite of a VB6 application in .NET 3.5sp1. The VB6 app is pretty well written and the data layer is completely based on stored procedures. I'd like to go with something automated like Linq2SQL/Entity Framework/NHibernate/SubSonic. Admittedly, I haven't used any of these tools in anything other than throwaway projects. </p>
<p>The potential problem I fear I might have with all these choices is speed. For instance, right now to retrieve a single row (or the entire list), I use the following sproc:</p>
<pre><code>ALTER PROCEDURE [dbo].[lst_Customers]
@intID INT = NULL
,@chvName VARCHAR(100) = NULL
AS
SELECT Customer_id, Name
FROM dbo.Customer
WHERE (@intID IS NULL OR @intID = Customer_id)
AND (@chvName IS NULL OR Name like ('%' + @chvName + '%'))
ORDER BY name
</code></pre>
<p>To retrieve a single row in Linq2SQL/Entity Framework/NHibernate/SubSonic, would these solutions have to bring the entire list down to the client and find the row that I need?</p>
<p>So, what's the consensus for the data access strategy for an application with a large data domain?</p>
|
[
{
"answer_id": 285030,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "<p>I can't speak on Linq-to-SQL, Entity Framework, nor NHibernate, but I am in love with SubSonic. My experience with it has been overwhelmingly positive.</p>\n\n<p>The way these tools work, in general, is that they build parameterized queries for you in managed code, encapsulate that access in classes, then expose those classes to your apps. Fully generated DALs rock.</p>\n\n<p>By using the parameterized queries, your concern that they might \"have to bring the entire list down to the client and find the row that I need\" is handled. They support <code>where</code> clauses and other filtering to get just the row(s) you need. You can do the equivalent of <code>select * from foo</code>, but you're not stuck in that mode.</p>\n\n<p>That said, SubSonic does -- when used out of box for direct table/view access -- bring down entire rows, which <em>could</em> be a downside in some scenarios. However, your access via stored procs is not an issue -- I can't speak to the others, but SubSonic helpfully creates an <code>SPs</code> class encapsulating all your procs, allowing you to call them as methods, and returning the appropriate <code>DataTable</code>s, which you can then parse manually as needed. There are also ways to initialize lists of DAL classes from procs, so if the proc returns a dataset which matches a table/view directly, you can still have the cleaner syntax without manual processing.</p>\n\n<p>(SubSonic, by the way, cured me of \"procs for everything.\" I now, typically, spend almost no time doing CRUD procs as I did in the past, and only wind up using them for complicated reporting. But your mileage may, and in fact will, vary.)</p>\n"
},
{
"answer_id": 285054,
"author": "Brian C",
"author_id": 34243,
"author_profile": "https://Stackoverflow.com/users/34243",
"pm_score": 0,
"selected": false,
"text": "<p>SubSonic, even according to Rob Connery, one of the authors, is written more to support rapid application development and less about large applications. I'd say go with NHibernate as you'll find the most support from the community as well as tried and true tested framework. You can get good information from www.dimecasts.net on setting up your NHibernate stuff.</p>\n"
},
{
"answer_id": 285067,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend using SubSonic to generate all the code to access your existing stored procs, this way you reduce the chances of regression because of a new data access layer. Any new features can be then accessed via using the ActiveRecord classes that are generated by SubSonic. This seems to me to be the safest and fastest approach to proceed,</p>\n\n<p>I don't agree with the NHibernate recommendation because it's not really well suited for working with stored procedures.</p>\n"
},
{
"answer_id": 285159,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 4,
"selected": true,
"text": "<p>I'm going to play devil's advocate and recommend you at least consider sticking with the stored procedures. These represent a chunk of code that you do not have to re-write and debug. <a href=\"http://www.joelonsoftware.com/printerFriendly/articles/fog0000000069.html\" rel=\"nofollow noreferrer\">This article</a> from our Very Own [tm] Joel Spolsky gives a coherent argument for avoiding complete re-writes.</p>\n\n<p>Given a 'greenfield' project you can use what you want, and an O/R mapper might well be a good choice. However, you've already stated that the VB6 app is well written. If the sprocs are well written, then you get some of your app for free and it comes already debugged, plus you get to recycle the database schema and avoid most of the pain from data migration.</p>\n\n<p>Fowler's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321127420\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Patterns of Enterprise Application Architecture</a> should give you some good pointers for designing a data access layer that will play nicely with the stored procedures without causing maintenance issues.</p>\n\n<p>This is done quite commonly on Oracle/Java apps. Many legacy Oracle apps have large bodies of stored procedure code in PL/SQL - this was a standard architecture back in the client-server days of Oracle Forms. It is common practice to write a wrapper for the sprocs in Java and build the user interface on top of the wrapper.</p>\n\n<p>One of the other posters mentioned that Subsonic can generate wrappers for the sprocs. </p>\n\n<p>Once upon a time I had occasion to do a data dictionary hack that generated a proof-of-concept Java/JDBC wrapper for PL/SQL sprocs - IIRC it only took a day or so. Given that it's not that hard to do, I'd be surprised to find that there isn't quite a bit of choice in things you can get off the shelf to do this. In a pinch, writing your own isn't all that hard either.</p>\n"
},
{
"answer_id": 285219,
"author": "NotDan",
"author_id": 3291,
"author_profile": "https://Stackoverflow.com/users/3291",
"pm_score": 1,
"selected": false,
"text": "<p>We tried to use entity framework as an orm and ran into multiple issues when trying to use it with Domain Driven Development. Linq to Sql also has some limitations and Microsoft is going to stop supporting it in the next release, I believe.</p>\n"
},
{
"answer_id": 285340,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 1,
"selected": false,
"text": "<p>If the queries are in stored procedures, there's a pretty good chance they've already been well-optimized. And probably they make liberal use of SQL expressions for JOINS, subqueries, etc.</p>\n\n<p>Duplicating that kind of efficiency and expressiveness, <em>accurately</em>, with an ORM-type abstraction layer would I expect be a challenge - especially if you're not totally familiar with the tools.</p>\n\n<p>You can always refactor the queries after you get the rest of the app straight. And the ORM world is changing fast enough that the options will certainly be different when you get there.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
I am about to embark on a rewrite of a VB6 application in .NET 3.5sp1. The VB6 app is pretty well written and the data layer is completely based on stored procedures. I'd like to go with something automated like Linq2SQL/Entity Framework/NHibernate/SubSonic. Admittedly, I haven't used any of these tools in anything other than throwaway projects.
The potential problem I fear I might have with all these choices is speed. For instance, right now to retrieve a single row (or the entire list), I use the following sproc:
```
ALTER PROCEDURE [dbo].[lst_Customers]
@intID INT = NULL
,@chvName VARCHAR(100) = NULL
AS
SELECT Customer_id, Name
FROM dbo.Customer
WHERE (@intID IS NULL OR @intID = Customer_id)
AND (@chvName IS NULL OR Name like ('%' + @chvName + '%'))
ORDER BY name
```
To retrieve a single row in Linq2SQL/Entity Framework/NHibernate/SubSonic, would these solutions have to bring the entire list down to the client and find the row that I need?
So, what's the consensus for the data access strategy for an application with a large data domain?
|
I'm going to play devil's advocate and recommend you at least consider sticking with the stored procedures. These represent a chunk of code that you do not have to re-write and debug. [This article](http://www.joelonsoftware.com/printerFriendly/articles/fog0000000069.html) from our Very Own [tm] Joel Spolsky gives a coherent argument for avoiding complete re-writes.
Given a 'greenfield' project you can use what you want, and an O/R mapper might well be a good choice. However, you've already stated that the VB6 app is well written. If the sprocs are well written, then you get some of your app for free and it comes already debugged, plus you get to recycle the database schema and avoid most of the pain from data migration.
Fowler's [Patterns of Enterprise Application Architecture](https://rads.stackoverflow.com/amzn/click/com/0321127420) should give you some good pointers for designing a data access layer that will play nicely with the stored procedures without causing maintenance issues.
This is done quite commonly on Oracle/Java apps. Many legacy Oracle apps have large bodies of stored procedure code in PL/SQL - this was a standard architecture back in the client-server days of Oracle Forms. It is common practice to write a wrapper for the sprocs in Java and build the user interface on top of the wrapper.
One of the other posters mentioned that Subsonic can generate wrappers for the sprocs.
Once upon a time I had occasion to do a data dictionary hack that generated a proof-of-concept Java/JDBC wrapper for PL/SQL sprocs - IIRC it only took a day or so. Given that it's not that hard to do, I'd be surprised to find that there isn't quite a bit of choice in things you can get off the shelf to do this. In a pinch, writing your own isn't all that hard either.
|
284,896 |
<p>Is it a good idea (from a design POV) to nest constructor calls for overloaded New or Factory style methods? This is mostly for simple constructors, where each overload builds on the previous one. </p>
<pre><code>MyClass( arg1 ) {
_arg1 = arg1;
_otherField = true;
_color="Blue"
}
MyClass( arg1, arg2) : this(arg1) {
_arg2 = arg2
}
MyClass( arg1, arg2, arg3) : this(arg1, ar2) {
_arg3 = arg3;
}
</code></pre>
<p>Or with factory methods:</p>
<pre><code>static NewInstance(arg1 ) {
_arg1 = arg1;
}
static NewInstance(arg1, arg2) {
f = NewInstance(arg1);
f._arg2 = arg2;
}
//... and so on
</code></pre>
<p>I can see a few drawbacks on both sides</p>
<ul>
<li>Nesting hides what the constructor is doing</li>
<li>Not nesting duplicates all the functionality</li>
</ul>
<p>So, is doing this a good idea, or does it set me up for something I'm just not seeing as a problem. For some reason I feel uneasy doing it, mostly because it divides up the responsibility for initializing.</p>
<p>Edit:
<strong>@Jon Skeet</strong>: I see now why this was bothering me so much. I was doing it backwards! I wrote the whole thing and didn't even notice, it just smelled. Most other cases I have (that I wrote), do it the way you recommend, but this certainly isn't the only one that I have done like this. I do notice that the more complicated ones I did properly, but the simple ones I seem to have gone sloppy.
<em>I love micro edits. I also like acronymns!</em></p>
|
[
{
"answer_id": 284905,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>I think it's reasonable to chain constructors together, but I do it the other way - the version with fewer parameters calls the version with more parameters. That way it makes it very clear what's happening, and all the real \"logic\" (beyond the default values) is in a single place. For example:</p>\n\n<pre><code>public Foo(int x, int y)\n{\n this.x = x;\n this.y = y;\n precomputedValue = x * y;\n}\n\nprivate static int DefaultY\n{\n get { return DateTime.Now.Minute; }\n}\n\npublic Foo(int x) : this(x, DefaultY)\n{\n}\n\npublic Foo() : this(1, DefaultY)\n{\n}\n</code></pre>\n\n<p>Note that if you have lots of constructor overloads, you may wish to move to static factory methods instead - that usually makes the code clearer, as well as allowing multiple methods to take the same set of parameters, e.g.</p>\n\n<pre><code>public static XmlDocument FromText(string xml)\n\npublic static XmlDocument FromFile(string filename)\n</code></pre>\n"
},
{
"answer_id": 285129,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": -1,
"selected": false,
"text": "<p><strong>2016 Edit</strong>: Still ahead of the time, C# is radically cutting back or eliminating its records support and default constructor support for C# 7, maybe C# 8 <em>finally</em>.</p>\n\n<p><strong>2015 Edit</strong>: I was far ahead of the time. C#6 and C#7 are removing the need for constructors. </p>\n\n<p>If you're developing in .Net 3.5 I recommend never using constructors. The only exception I leave for this is if you are using an injection constructor for dependency injection. With .Net 3.5 they created object initializers which allow you to do</p>\n\n<pre><code>var myclass = New MyClass { arg1 = \"lala\", arg2 =\"foo\" }\n</code></pre>\n\n<p>This will initalize the class with values assigned for arg1 and arg2 while leaving arg3 as </p>\n\n<pre><code>default(typeof(arg3)).\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15127/"
] |
Is it a good idea (from a design POV) to nest constructor calls for overloaded New or Factory style methods? This is mostly for simple constructors, where each overload builds on the previous one.
```
MyClass( arg1 ) {
_arg1 = arg1;
_otherField = true;
_color="Blue"
}
MyClass( arg1, arg2) : this(arg1) {
_arg2 = arg2
}
MyClass( arg1, arg2, arg3) : this(arg1, ar2) {
_arg3 = arg3;
}
```
Or with factory methods:
```
static NewInstance(arg1 ) {
_arg1 = arg1;
}
static NewInstance(arg1, arg2) {
f = NewInstance(arg1);
f._arg2 = arg2;
}
//... and so on
```
I can see a few drawbacks on both sides
* Nesting hides what the constructor is doing
* Not nesting duplicates all the functionality
So, is doing this a good idea, or does it set me up for something I'm just not seeing as a problem. For some reason I feel uneasy doing it, mostly because it divides up the responsibility for initializing.
Edit:
**@Jon Skeet**: I see now why this was bothering me so much. I was doing it backwards! I wrote the whole thing and didn't even notice, it just smelled. Most other cases I have (that I wrote), do it the way you recommend, but this certainly isn't the only one that I have done like this. I do notice that the more complicated ones I did properly, but the simple ones I seem to have gone sloppy.
*I love micro edits. I also like acronymns!*
|
I think it's reasonable to chain constructors together, but I do it the other way - the version with fewer parameters calls the version with more parameters. That way it makes it very clear what's happening, and all the real "logic" (beyond the default values) is in a single place. For example:
```
public Foo(int x, int y)
{
this.x = x;
this.y = y;
precomputedValue = x * y;
}
private static int DefaultY
{
get { return DateTime.Now.Minute; }
}
public Foo(int x) : this(x, DefaultY)
{
}
public Foo() : this(1, DefaultY)
{
}
```
Note that if you have lots of constructor overloads, you may wish to move to static factory methods instead - that usually makes the code clearer, as well as allowing multiple methods to take the same set of parameters, e.g.
```
public static XmlDocument FromText(string xml)
public static XmlDocument FromFile(string filename)
```
|
284,899 |
<pre><code>private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
</code></pre>
<p>How do I add action listeners to these buttons, so that from a main method I can call <code>actionperformed</code> on them, so when they are clicked I can call them in my program?</p>
|
[
{
"answer_id": 284925,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 3,
"selected": false,
"text": "<p>Your best bet is to review the <a href=\"http://java.sun.com/docs/books/tutorial/ui/index.html\" rel=\"noreferrer\">Java Swing tutorials</a>, specifically the <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/components/button.html\" rel=\"noreferrer\">tutorial on Buttons</a>.</p>\n\n<p>The short code snippet is:</p>\n\n<pre><code>jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );\n</code></pre>\n"
},
{
"answer_id": 284930,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 0,
"selected": false,
"text": "<p>To add an action listener, you just call <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/AbstractButton.html#addActionListener(java.awt.event.ActionListener)\" rel=\"nofollow noreferrer\">addActionListener</a> from Abstract Button.</p>\n"
},
{
"answer_id": 284934,
"author": "David Koelle",
"author_id": 2197,
"author_profile": "https://Stackoverflow.com/users/2197",
"pm_score": 6,
"selected": false,
"text": "<p>Two ways:</p>\n<p><b>1.</b> Implement ActionListener in your class, then use <code>jBtnSelection.addActionListener(this);</code> Later, you'll have to define a menthod, <code>public void actionPerformed(ActionEvent e)</code>. However, doing this for multiple buttons can be confusing, because the <code>actionPerformed</code> method will have to check the source of each event (<code>e.getSource()</code>) to see which button it came from.</p>\n<p><b>2.</b> Use anonymous inner classes:</p>\n<pre><code>jBtnSelection.addActionListener(new ActionListener() { \n public void actionPerformed(ActionEvent e) { \n selectionButtonPressed();\n } \n} );</code></pre>\n<p>Later, you'll have to define <code>selectionButtonPressed()</code>.\nThis works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.</p>\n<p><strong>2, Updated.</strong> Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:</p>\n<pre><code>jBtnSelection.addActionListener(e -> selectionButtonPressed());\n</code></pre>\n<p>In this case, <code>e</code> is the ActionEvent. This works because the ActionListener interface has only one method, <code>actionPerformed(ActionEvent e)</code>.</p>\n<p>The second method also allows you to call the <code>selectionButtonPressed</code> method directly. In this case, you could call <code>selectionButtonPressed()</code> if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe <code>selectionChanged()</code>).</p>\n"
},
{
"answer_id": 53247880,
"author": "Ronald Ortiz",
"author_id": 9815517,
"author_profile": "https://Stackoverflow.com/users/9815517",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if this works but I made the variable names</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class beep implements ActionListener {\n public static void main(String[] args) {\n JFrame f = new JFrame(\"beeper\");\n JButton button = new JButton(\"Beep me\");\n f.setVisible(true);\n f.setSize(300, 200);\n f.add(button);\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n // Insert code here\n }\n });\n }\n}\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37037/"
] |
```
private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
```
How do I add action listeners to these buttons, so that from a main method I can call `actionperformed` on them, so when they are clicked I can call them in my program?
|
Two ways:
**1.** Implement ActionListener in your class, then use `jBtnSelection.addActionListener(this);` Later, you'll have to define a menthod, `public void actionPerformed(ActionEvent e)`. However, doing this for multiple buttons can be confusing, because the `actionPerformed` method will have to check the source of each event (`e.getSource()`) to see which button it came from.
**2.** Use anonymous inner classes:
```
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
```
Later, you'll have to define `selectionButtonPressed()`.
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
**2, Updated.** Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:
```
jBtnSelection.addActionListener(e -> selectionButtonPressed());
```
In this case, `e` is the ActionEvent. This works because the ActionListener interface has only one method, `actionPerformed(ActionEvent e)`.
The second method also allows you to call the `selectionButtonPressed` method directly. In this case, you could call `selectionButtonPressed()` if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe `selectionChanged()`).
|
284,921 |
<p>I want to start using dependency injection in my WPF application, largely for better unit testability. My app is mostly constructed along the M-V-VM pattern.
I'm looking at <a href="https://code.google.com/p/autofac/" rel="nofollow noreferrer">Autofac</a> for my IoC container, but I don't think that matters too much for this discussion.</p>
<p>Injecting a service into the start window seems straightforward, as I can create the container and resolve from it in App.xaml.cs.</p>
<p>What I'm struggling with is how I can DI ViewModels and Services into User Controls? The user controls are instantiated via XAML markup, so there's no opportunity to <code>Resolve()</code> them.</p>
<p>The best I can think of is to place the container in a Singleton, and have the user controls resolve their ViewModels from the global container. This feels like a half-way solution, at best, as it still required my components to have a dependency on a ServiceLocator.</p>
<p>Is full IoC possible with WPF?</p>
<p>[edit] - Prism has been suggested, but even evaluating Prism seems like a big investment. I'm hoping for something smaller.</p>
<p>[edit] here's a code fragment where I'm stopped</p>
<pre class="lang-cs prettyprint-override"><code>//setup IoC container (in app.xaml.cs)
var builder = new ContainerBuilder();
builder.Register<NewsSource>().As<INewsSource>();
builder.Register<AViewModel>().FactoryScoped();
var container = builder.Build();
// in user control ctor -
// this doesn't work, where do I get the container from
VM = container.Resolve<AViewModel>();
// in app.xaml.cs
// this compiles, but I can't use this uc,
//as the one I want in created via xaml in the primary window
SomeUserControl uc = new SomeUserControl();
uc.VM = container.Resolve<AViewModel>();
</code></pre>
|
[
{
"answer_id": 284981,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, we do it all the time. You can \"inject\" your ViewModel into the DataContext of the control.</p>\n\n<p>I actually find WPF being even easier to use with DI. Even the dependency objects and properties work with it seamlessly.</p>\n"
},
{
"answer_id": 286024,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>We are experiencing a similar issue. We are looking forward for a solution that will provide Design time support under Expression Blend 2.0 (Strong Type). Plus we are looking forward for a solution to have some Mock+Auto-Generated data sample available under Expression Blend.</p>\n<p>Of course, we are looking also to have all those thing work using an IOC pattern.</p>\n<p>Paul Stovell as an interesting article to start with:\n<a href=\"http://www.paulstovell.com/blog/wpf-dependency-injection-in-xaml\" rel=\"nofollow noreferrer\">http://www.paulstovell.com/blog/wpf-dependency-injection-in-xaml</a></p>\n<p>So I try a couple thing to add more valuable design time support for Binding and mocking object at Design time, right now I’m having most of my problem related to get a strong typed connection made between the View (code) to the ModelView(Xaml), I tried a couple scenario:</p>\n<p>Solution 1 : Using Generic to create the View</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class MyDotNetcomponent<T> : SomeDotNetcomponent \n{\n // Inversion of Control Loader…\n // Next step add the Inversion of control manager plus\n // some MockObject feature to work under design time\n public T View {Get;}\n}\n</code></pre>\n<p>This solution does not work since Blend does not support Generic inside is design surface but Xaml do have some, well work at runtime but not at design;</p>\n<p>Solution 2: ObjectDataProvider</p>\n<pre class=\"lang-xml prettyprint-override\"><code><ObjectDataProvider ObjectType="{x:Type CP:IFooView}" />\n<!-- Work in Blend -->\n<!—- IOC Issue: we need to use a concrete type and/or static Method there no way to achive a load on demande feature in a easy way -->\n</code></pre>\n<p>Solution 3: Inherit ObjectDataProvider</p>\n<pre class=\"lang-xml prettyprint-override\"><code><CWD:ServiceObjectDataProvider ObjectType="{x:Type CP:IFooView}" />\n<!-- Cannot inherit from ObjectDataProvider to achive the right behavior everything is private-->\n</code></pre>\n<p>Solution 4: Create a mock ObjectDataProvider from scratch to the job</p>\n<pre class=\"lang-xml prettyprint-override\"><code><CWD:ServiceObjectDataProvider ObjectType="{x:Type CP:IFooView }" />\n<!-- Not working in Blend, quite obvious-->\n</code></pre>\n<p>Solution 5: Create a Markup Extension (Paul Stovell)</p>\n<pre class=\"lang-xml prettyprint-override\"><code><CWM:ServiceMarkup MetaView="{x:Type CP:IFooView}"/>\n<!-- Not working in Blend -->\n</code></pre>\n<p>Just to clear one point. When I said “not working in blend”, I mean that the Binding dialog is not usable and the designer needs to handwrite the XAML by itself.</p>\n<p>Our next step will probably be to take the time to evaluate the ability to create a plug-in for Expression Blend.</p>\n"
},
{
"answer_id": 292281,
"author": "Glenn Block",
"author_id": 18419,
"author_profile": "https://Stackoverflow.com/users/18419",
"pm_score": 4,
"selected": false,
"text": "<p>It's actually very easy to do. We have examples of this in Prism as jedidja mentioned. You can either have the ViewModel get injected with the View or the View get injected with the ViewModel. In the Prism StockTraderRI, you will see that we inject the View into the ViewModel. Essentially, what happens is that the View (and View interface) has a Model property. That property is implemented in the code-behind to set the DataContext to the value, for example: <code>this.DataContext = value;</code>. In the constructor of the ViewModel, the View gets injected. It then sets <code>View.Model = this;</code> which will pass itself as the DataContext.</p>\n<p>You can also easily do the reverse and have the ViewModel injected into the View. I actually prefer this because it means that the ViewModel no longer has any back reference to the view at all. This means when unit-testing the ViewModel, you don't have a view to even Mock. Additionally, it makes the code cleaner, in that in the constructor of the View, it simply sets the DataContext to the ViewModel that was injected.</p>\n<p>I talk a bit more about this in the video recording of the Separated Presentation Patterns talk that Jeremy Miller and I gave at Kaizenconf. The first part of which can be found here <a href=\"https://vimeo.com/2189854\" rel=\"nofollow noreferrer\">https://vimeo.com/2189854</a>.</p>\n"
},
{
"answer_id": 311560,
"author": "user30493",
"author_id": 30493,
"author_profile": "https://Stackoverflow.com/users/30493",
"pm_score": 3,
"selected": false,
"text": "<p>I think you've hit on the issue. The controls need to be injected into their parent rather than created declaratively through XAML.</p>\n<p>For DI to work, a DI container should create the class that is accepting dependencies. This means that the parent will not have any instances of the child controls at design time and look something like a shell in the designer. This is <em>probably</em> the recommended approach.</p>\n<p>The other "alternative" is to have a global static container called from the control's constructor, or something similar. There is a common pattern in which two constructors are declared, one with a parameter list for constructor injection and the other without parameters that delegates:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// For WPF\npublic Foo() : this(Global.Container.Resolve&lt;IBar&gt;()) {}\n\n// For the rest of the world\npublic Foo(IBar bar) { .. }\n</code></pre>\n<p>I would almost call this an antipattern but for the fact that some frameworks leave no other choice.</p>\n<p>I'm not even half an expert in WPF, so I'm expecting a healthy serving of downmod here :) but hope this helps. The Autofac group (linked from the homepage) might be another place to ask this question. The Prism or MEF sample apps (which include some WPF examples) should give you an idea of what is possible.</p>\n"
},
{
"answer_id": 336915,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 2,
"selected": false,
"text": "<p>You should take a look at <a href=\"http://www.codeplex.com/caliburn\" rel=\"nofollow noreferrer\">Caliburn</a> - it's a simple WPF/Silverlight MVC framework with support for full DI. It looks really cool and it lets you use any IoC container you want. There are a couple of examples on the <a href=\"http://www.codeplex.com/caliburn/Wiki/View.aspx?title=Table%20Of%20Contents&referringTitle=Home\" rel=\"nofollow noreferrer\">documentation wiki</a></p>\n"
},
{
"answer_id": 5296394,
"author": "satish",
"author_id": 329845,
"author_profile": "https://Stackoverflow.com/users/329845",
"pm_score": 0,
"selected": false,
"text": "<p>I think You have to Decide on View First or Viewmodel First then as given the other answer it Can be decide.. There are several open source framework does it same . I use Caliburn where ViewModel first is taken and its really good approach</p>\n"
},
{
"answer_id": 15277471,
"author": "Clay Ver Valen",
"author_id": 2145349,
"author_profile": "https://Stackoverflow.com/users/2145349",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote an very light framework where a ViewModel is resolved at runtime by using a IoC (Unity) as a markup extension.</p>\n\n<p>The framework allows for writing XAML without a code behind but still lets you have routed commands, data binding, and event handlers.</p>\n\n<p>In any case, I don't think you need the loose XAML in your case, but if you look at the code (<a href=\"http://xtrememvvm.codeplex.com\" rel=\"nofollow\">http://xtrememvvm.codeplex.com</a>), it might turn out that you can use some of the code to solve your own issues with injecting View Models and Services.</p>\n"
},
{
"answer_id": 19664136,
"author": "Ben Stabile",
"author_id": 2892067,
"author_profile": "https://Stackoverflow.com/users/2892067",
"pm_score": 1,
"selected": false,
"text": "<p>Glen Block (see above) mentions that a common approach is to design your <strong>MVVM</strong> solution to use the <strong>DataContext</strong> as the place where you can \"resolve\" your View Model in the View. Then you can use design extensions from expression blend 2008 (note that you don't need to be using the expression blend design tools to take advantage of this). For example:</p>\n\n<pre><code>xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \nxmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\nmc:Ignorable=\"d\" \nd:DataContext=\"{d:DesignInstance Type=local:MyViewModelMock, IsDesignTimeCreatable=True}\"\n</code></pre>\n\n<p>In your view you can have a property getter that casts your <strong>DataContext</strong> to the type that you expect (just to make it easier to consume in the code-behind).</p>\n\n<pre><code>private IMyViewModel ViewModel { get { return (IMyViewModel) DataContext; } }\n</code></pre>\n\n<p>Don't forget to use an <strong>interface</strong> so that your views are easier to test, or to help you inject different runtime implementations.</p>\n\n<p>In general, you should not be resolving things from the container all over the place in your solution. It is actually considered bad practice to pass your container around in every constructor, or to make it globally accessible. (You should look up discussions of why \"Service Locator\" strategies constitute an \"Anti-Pattern\"). </p>\n\n<p>Create a public View constructor with explicit dependencies that the container (e.g. Prism Unity or MEF) can resolve. </p>\n\n<p>If necessary, you could also create an <strong>internal</strong> default constructor to create a mock of your view model (or a real one for that matter). This protects against inadvertent use of this \"<strong>design constructor</strong>\" externally (in your \"Shell\" or wherever). Your test projects can also use such constructors using the \"<strong>InternalsVisibleToAttribute</strong>\" in \"<strong>AssemblyInfo</strong>\". But of course, that usually isn't necessary since you can inject your mocks using the full dependency constructors anyway, and because the majority of your tests should be focusing on the <strong>ViewModel</strong> in the first place. Any code in the <strong>View</strong> should ideally be quite trivial. <em>(If your View requires a lot of testing, then you might want to ask yourself why!)</em></p>\n\n<p>Glen also mentions that you can inject <strong>Views into View Models</strong>, or <strong>View Models into Views</strong>. I much prefer the latter because there are perfectly good techniques for decoupling everything (use of Declarative Binding, Commanding, Event Aggregation, Mediator patterns, etc.). The <strong>View Model</strong> is where all the heavy lifting will be done to orchestrate core business logic. If all of the necessary \"binding\" points are provided by the <strong>View Model</strong>, it really shouldn't need to know <strong>ANYTHING</strong> about the <strong>View</strong> (which can mostly be wired up to it declaratively in the XAML).</p>\n\n<p>If we make the View Model agnostic to the source of user-interaction, that makes it much easier to test (preferably first). And it also means that you can easily plug in ANY view (WPF, Silverlight, ASP.NET, Console, etc.). In fact, to ensure that appropriate decoupling has been achieved, we can ask ourselves if a \"MVM\" (Model-ViewModel) architecture could work in the context of, say, a Workflow service. When you stop to think about it, most of your unit tests will probably be designed on that premise. </p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25201/"
] |
I want to start using dependency injection in my WPF application, largely for better unit testability. My app is mostly constructed along the M-V-VM pattern.
I'm looking at [Autofac](https://code.google.com/p/autofac/) for my IoC container, but I don't think that matters too much for this discussion.
Injecting a service into the start window seems straightforward, as I can create the container and resolve from it in App.xaml.cs.
What I'm struggling with is how I can DI ViewModels and Services into User Controls? The user controls are instantiated via XAML markup, so there's no opportunity to `Resolve()` them.
The best I can think of is to place the container in a Singleton, and have the user controls resolve their ViewModels from the global container. This feels like a half-way solution, at best, as it still required my components to have a dependency on a ServiceLocator.
Is full IoC possible with WPF?
[edit] - Prism has been suggested, but even evaluating Prism seems like a big investment. I'm hoping for something smaller.
[edit] here's a code fragment where I'm stopped
```cs
//setup IoC container (in app.xaml.cs)
var builder = new ContainerBuilder();
builder.Register<NewsSource>().As<INewsSource>();
builder.Register<AViewModel>().FactoryScoped();
var container = builder.Build();
// in user control ctor -
// this doesn't work, where do I get the container from
VM = container.Resolve<AViewModel>();
// in app.xaml.cs
// this compiles, but I can't use this uc,
//as the one I want in created via xaml in the primary window
SomeUserControl uc = new SomeUserControl();
uc.VM = container.Resolve<AViewModel>();
```
|
It's actually very easy to do. We have examples of this in Prism as jedidja mentioned. You can either have the ViewModel get injected with the View or the View get injected with the ViewModel. In the Prism StockTraderRI, you will see that we inject the View into the ViewModel. Essentially, what happens is that the View (and View interface) has a Model property. That property is implemented in the code-behind to set the DataContext to the value, for example: `this.DataContext = value;`. In the constructor of the ViewModel, the View gets injected. It then sets `View.Model = this;` which will pass itself as the DataContext.
You can also easily do the reverse and have the ViewModel injected into the View. I actually prefer this because it means that the ViewModel no longer has any back reference to the view at all. This means when unit-testing the ViewModel, you don't have a view to even Mock. Additionally, it makes the code cleaner, in that in the constructor of the View, it simply sets the DataContext to the ViewModel that was injected.
I talk a bit more about this in the video recording of the Separated Presentation Patterns talk that Jeremy Miller and I gave at Kaizenconf. The first part of which can be found here <https://vimeo.com/2189854>.
|
284,938 |
<p>If I were writing my own HTML and placing the values in the table I would use css and style the borders using something like:</p>
<pre><code>td{
border-left : solid gray 1px;
}
</code></pre>
|
[
{
"answer_id": 284946,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>if you put that css style into your web page, you'll find that your datagrid will use it, since the datagrid control just generates a html table!</p>\n\n<p>of course, you can set the CssClass of the datagrid and make a style just for it as well; you can also fiddle with the row-style properties of the datagridview but css styling is much easier to change/skin later</p>\n"
},
{
"answer_id": 286338,
"author": "deadbug",
"author_id": 4646,
"author_profile": "https://Stackoverflow.com/users/4646",
"pm_score": 1,
"selected": false,
"text": "<p>You might try using the gridrowstyle & alternatinggridrowstyle properties of the datagrid. i would suggest setting them to a CSS class as Steven suggests.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
If I were writing my own HTML and placing the values in the table I would use css and style the borders using something like:
```
td{
border-left : solid gray 1px;
}
```
|
if you put that css style into your web page, you'll find that your datagrid will use it, since the datagrid control just generates a html table!
of course, you can set the CssClass of the datagrid and make a style just for it as well; you can also fiddle with the row-style properties of the datagridview but css styling is much easier to change/skin later
|
284,939 |
<h1>UPDATE</h1>
<p>So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D</p>
<hr>
<p>I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (<strong><code>default.aspx</code></strong>):</p>
<pre><code><HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
</code></pre>
<p>When my <strong><code>default.aspx</code></strong> page gets loaded up, it calls the following function:</p>
<pre><code>Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
</code></pre>
<p>Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.</p>
<p>EDIT: Is there something I need to configure in my <strong><code>web.config</code></strong> file to make this work properly? Request.Params("<code><param name></code>") does not work.</p>
|
[
{
"answer_id": 285243,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>That HTML is just on the user's harddrive? Maybe the browser security won't let that POST because it's deemed to be a risk.</p>\n\n<p>As a test -- take that exact HTML file and put it on your webserver and then browse to it. If it works, might be the browser refusing to send the data. You could check with Fiddler (for IE) or Firebug in FireFox.</p>\n"
},
{
"answer_id": 285528,
"author": "Moose",
"author_id": 19032,
"author_profile": "https://Stackoverflow.com/users/19032",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use System.Net.WebClient?</p>\n\n<p>Some sample code (sorry, it's C#. Looks like your looking for VB. I can't translate quickly.)</p>\n\n<pre><code>System.Net.WebClient wc = new System.Net.WebClient();\nbyte[] b;\nbyte[] res;\nstring formdata = \"text=test text&password=secret&checkbox=on&textarea=a longer text sentence&submit=submit\";\n\n// encode the form data string into a byte array \nb = System.Text.Encoding.ASCII.GetBytes(formdata);\n\n// set the content type for a form \nwc.Headers.Add(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n// POST and get data\nres = wc.UploadData(\"http://localhost:51816/gs_ontheweb/default.aspx\", b);\n\n//convert the return page from byte[] to ascii\nstring s = System.Text.Encoding.ASCII.GetString(res);\n</code></pre>\n"
},
{
"answer_id": 286003,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": true,
"text": "<p>Your issue is the \"Target\" property on the Form. Why is this here?</p>\n\n<p>(I also took the liberty of cleaning your HTML up a little)</p>\n\n<pre><code><html>\n <head>\n <title>Test JS Post</title>\n <script type=\"text/javascript\" language=\"javascript\">\n <!--\n function OnLoad(){\n try\n {\n alert(\"Posting...\");\n document.form1.submit();\n }\n catch(e)\n {\n alert(\"ERROR!\");\n alert(e);\n }\n }\n //-->\n </script>\n</head>\n<body onload=\"OnLoad()\">\n\n <form action=\"http://localhost:49684/Default.aspx\" method=\"post\" name=\"form1\">\n\n <input type=\"hidden\" name=\"ClientID\" value=\"123456\" />\n <input type=\"hidden\" name=\"Password\" value=\"2830088828\" />\n <input type=\"hidden\" name=\"PracType\" value=\"051\" />\n <input type=\"hidden\" name=\"Encrypt\" value=\"12345620081111\" />\n\n <h1>This is in the form. Submit me here:</h1><input type=\"submit\" value=\"foo\" />\n\n </form>\n\n</body>\n</html>\n</code></pre>\n\n<p>In the code behind of <code>Default.aspx</code>:</p>\n\n<pre><code>Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n\n For Each value As String In Request.Form.Keys\n Debug.WriteLine(String.Format(\"{0} = \"\"{1}\"\"\", value, Request.Form.Item(value)))\n Next\n\nEnd Sub\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
UPDATE
======
So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D
---
I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (**`default.aspx`**):
```
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
```
When my **`default.aspx`** page gets loaded up, it calls the following function:
```
Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
```
Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.
EDIT: Is there something I need to configure in my **`web.config`** file to make this work properly? Request.Params("`<param name>`") does not work.
|
Your issue is the "Target" property on the Form. Why is this here?
(I also took the liberty of cleaning your HTML up a little)
```
<html>
<head>
<title>Test JS Post</title>
<script type="text/javascript" language="javascript">
<!--
function OnLoad(){
try
{
alert("Posting...");
document.form1.submit();
}
catch(e)
{
alert("ERROR!");
alert(e);
}
}
//-->
</script>
</head>
<body onload="OnLoad()">
<form action="http://localhost:49684/Default.aspx" method="post" name="form1">
<input type="hidden" name="ClientID" value="123456" />
<input type="hidden" name="Password" value="2830088828" />
<input type="hidden" name="PracType" value="051" />
<input type="hidden" name="Encrypt" value="12345620081111" />
<h1>This is in the form. Submit me here:</h1><input type="submit" value="foo" />
</form>
</body>
</html>
```
In the code behind of `Default.aspx`:
```
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each value As String In Request.Form.Keys
Debug.WriteLine(String.Format("{0} = ""{1}""", value, Request.Form.Item(value)))
Next
End Sub
```
|
284,952 |
<p>I am working on an embedded application where the device is controlled through a command interface. I mocked the command dispatcher in VC and had it working to my satisfaction; but when I then moved the code over to the embedded environment, I found out that the compiler has a broken implementation of pointer-to-func's.</p>
<p>Here's how I originally implemented the code (in VC):</p>
<pre><code>/* Relevant parts of header file */
typedef struct command {
const char *code;
void *set_dispatcher;
void *get_dispatcher;
const char *_description;
} command_t;
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, &set_##dispatcher, &get_##dispatcher, (const char*)description}
/* Dispatcher data structure in the C file */
const command_t commands[] = {
COMMAND_ENTRY("DH", Dhcp, "DHCP (0=off, 1=on)"),
COMMAND_ENTRY("IP", Ip, "IP Address (192.168.1.205)"),
COMMAND_ENTRY("SM", Subnet, "Subunet Mask (255.255.255.0)"),
COMMAND_ENTRY("DR", DefaultRoute, "Default router (192.168.1.1)"),
COMMAND_ENTRY("UN", Username, "Web username"),
COMMAND_ENTRY("PW", Password, "Web password"),
...
}
/* After matching the received command string to the command "label", the command is dispatched */
if (pc->isGetter)
return ((get_fn_t)(commands[i].get_dispatcher))(pc);
else
return ((set_fn_t)(commands[i].set_dispatcher))(pc);
}
</code></pre>
<p>Without the use of function pointers, it seems like my only hope is to use switch()/case statements to call functions. But I'd like to avoid having to manually maintain a large switch() statement. </p>
<p>What I was thinking of doing is moving all the COMMAND_ENTRY lines into a separate include file. Then wraps that include file with varying #define and #undefines. Something like:</p>
<pre><code>/* Create enum's labels */
#define COMMAND_ENTRY(label,dispatcher,description) SET_##dispatcher, GET_##dispatcher
typedef enum command_labels = {
#include "entries.cinc"
DUMMY_ENUM_ENTRY} command_labels_t;
#undefine COMMAND_ENTRY
/* Create command mapping table */
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, SET_##dispatcher, GET_##dispatcher, (const char*)description}
const command_t commands[] = {
#include "entries.cinc"
NULL /* dummy */ };
#undefine COMMAND_ENTRY
/*...*/
int command_dispatcher(command_labels_t dispatcher_id) {
/* Create dispatcher switch statement */
#define COMMAND_ENTRY(label,dispatcher,description) case SET_##dispatcher: return set_##dispatcher(pc); case GET_##dispatcher: return get_##dispatcher(pc);
switch(dispatcher_id) {
#include "entries.cinc"
default:
return NOT_FOUND;
}
#undefine COMMAND_ENTRY
}
</code></pre>
<p>Does anyone see a better way to handle this situation? Sadly, 'get another compiler' is not a viable option. :(</p>
<p>--- Edit to add:
Just to clarify, the particular embedded environment is broken in that the compiler is <em>supposed</em> to create a "function-pointer table" which is then used by the compiler to resolve calls to functions through a pointer. Unfortunately, the compiler is broken and doesn't generate a correct function-table.</p>
<p>So I don't have an easy way to extract the func address to invoke it.</p>
<p>--- Edit #2:
Ah, yes, the use of void *(set|get)_dispatcher was my attempt to see if the problem was with the typedefine of the func pointers. Originally, I had</p>
<pre><code>typedef int (*set_fn_t)(cmdContext_t *pCmdCtx);
typedef int (*get_fn_t)(cmdContext_t *pCmdCtx);
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
</code></pre>
|
[
{
"answer_id": 284980,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 0,
"selected": false,
"text": "<p>try this syntax:</p>\n\n<p>return (*((get_fn_t)commands[i].get_dispatcher))(pc);</p>\n\n<p>It's been awhile since I've done C & function pointers, but I believe the original C syntax required the * when dereferencing function pointers but most compilers would let you get away without it.</p>\n"
},
{
"answer_id": 284987,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "<p>To what extent is the pointer-to-function broken? </p>\n\n<p>If the compiler allows you to get the address of a function (I'm from C++, but <code>&getenv</code> is what I mean), you could wrap the calling convention stuff into assembler.</p>\n\n<p>As said, I'm a C++ssie, but something in the way of</p>\n\n<pre><code>; function call\npush [arg1]\npush [arg2]\ncall [command+8] ; at the 4th location, the setter is stored\nret\n</code></pre>\n\n<p>If even that is broken, you could define an array of <code>extern void*</code> pointers which you define, again, in assembly.</p>\n"
},
{
"answer_id": 284992,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "<p>You should try changing your <code>struct command</code> so the function pointers have the actual type:</p>\n\n<pre><code>typedef struct command {\n const char *code;\n set_fn_t set_dispatcher;\n get_fn_t get_dispatcher;\n const char *_description;\n} command_t;\n</code></pre>\n\n<p>Unfortunately, function pointers are not guaranteed to be able to convert to/from void pointers (that applies only to pointers to objects). </p>\n\n<p>What's the embedded environment?</p>\n\n<hr>\n\n<p>Given the information posted in the updates to the question, I see that it's really a bugged compiler.</p>\n\n<p>I think that your proposed solution seems pretty reasonable - it's probably similar to what I would have come up with.</p>\n"
},
{
"answer_id": 284995,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "<p>A function pointer isn't actually required to fit in a void*. You could check to make sure that the value you're calling is actually the address of the function. If not, use a function pointer type in the struct: either get_fn_t, or IIRC void(*)(void) is guaranteed to be compatible with any function pointer type.</p>\n\n<p>Edit: OK, assuming that calling by value can't be made to work, I can't think of a neater way to do what you need than auto-generating the switch statement. You could maybe use an off-the-shelf ASP-style preprocessor mode for ruby/python/perl/php/whatever prior to the C preprocessor. Something like this:</p>\n\n<pre><code>switch(dispatcher_id) {\n<% for c in commands %>\n case SET_<% c.dispatcher %>: return set_<% c.dispatcher %>(pc); \n case GET_<% c.dispatcher %>: return get_<% c.dispatcher %>(pc);\n<% end %>\ndefault:\n return NOT_FOUND;\n}\n</code></pre>\n\n<p>might be a bit more readable than the macro/include trick, but introducing a new tool and setting up the makefiles is probably not worth it for such a small amount of code. And the line numbers in the debug info won't relate to the file you think of as the source file unless you do extra work in your preprocessor to specify them.</p>\n"
},
{
"answer_id": 284998,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>Can you get the vendor to fix the compiler?</p>\n"
},
{
"answer_id": 285759,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have access to the link map?\nIf so, maybe you can hack your way around the wonky function-pointer table:</p>\n\n<pre><code>unsigned long addr_get_dhcp = 0x1111111;\nunsigned long addr_set_dhcp = 0x2222222; //make these unique numbers.\n\n/* Relevant parts of header file */\ntypedef struct command {\n const char *code;\n unsigned long set_dispatcher;\n unsigned long get_dispatcher;\n const char *_description;\n} command_t;\n\n#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, \n addr_set_##dispatcher, addr_get_##dispatcher, (const char*)description} \n</code></pre>\n\n<p>Now compile, grab the relevant addresses from the link map, replace the constants, and recompile. Nothing should move, so the map ought to stay the same. (Making the original constants unique should prevent the compiler from collapsing identical values into one storage location. You may need a long long, depending on the architecture) </p>\n\n<p>If the concept works, you could probably add a post-link step running a script to do the replacement automagically. Of course, this is just a theory, it may fail miserably.</p>\n"
},
{
"answer_id": 337948,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe, you need to look into the structure again:</p>\n\n<pre><code>typedef struct command {\n const char *code;\n void *set_dispatcher; //IMO, it does not look like a function pointer...\n void *get_dispatcher; //more like a pointer to void\n const char *_description;\n} command_t;\n</code></pre>\n\n<p>Let say your dispatchers have the following similar function definition:</p>\n\n<pre><code>//a function pointer type definition\ntypedef int (*genericDispatcher)(int data);\n</code></pre>\n\n<p>Assume that the dispatchers are like below:</p>\n\n<pre><code>int set_DhcpDispatcher(int data) { return data; }\nint get_DhcpDispatcher(int data) { return 2*data; }\n</code></pre>\n\n<p>So, the revised structure will be:</p>\n\n<pre><code>typedef struct command {\n const char *code;\n genericDispatcher set_dispatcher; \n genericDispatcher get_dispatcher; \n const char *_description;\n} command_t;\n</code></pre>\n\n<p>Your macro will be:</p>\n\n<pre><code>#define COMMAND_ENTRY(label,dispatcher,description) \\\n{ (const char*)label, \\\n set_##dispatcher##Dispatcher, \\\n get_##dispatcher##Dispatcher, \\\n (const char*)description } \n</code></pre>\n\n<p>Then, you can set your array as usual:</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n int value1 = 0, value2 = 0;\n\n const command_t commands[] = {\n COMMAND_ENTRY(\"DH\", Dhcp, \"DHCP (0=off, 1=on)\")\n };\n\n value1 = commands[0].set_dispatcher(1);\n value2 = commands[0].get_dispatcher(2);\n\n printf(\"value1 = %d, value2 = %d\", value1, value2);\n\n return 0;\n}\n</code></pre>\n\n<p>Correct me, if I am wrong somewhere... ;)</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22329/"
] |
I am working on an embedded application where the device is controlled through a command interface. I mocked the command dispatcher in VC and had it working to my satisfaction; but when I then moved the code over to the embedded environment, I found out that the compiler has a broken implementation of pointer-to-func's.
Here's how I originally implemented the code (in VC):
```
/* Relevant parts of header file */
typedef struct command {
const char *code;
void *set_dispatcher;
void *get_dispatcher;
const char *_description;
} command_t;
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, &set_##dispatcher, &get_##dispatcher, (const char*)description}
/* Dispatcher data structure in the C file */
const command_t commands[] = {
COMMAND_ENTRY("DH", Dhcp, "DHCP (0=off, 1=on)"),
COMMAND_ENTRY("IP", Ip, "IP Address (192.168.1.205)"),
COMMAND_ENTRY("SM", Subnet, "Subunet Mask (255.255.255.0)"),
COMMAND_ENTRY("DR", DefaultRoute, "Default router (192.168.1.1)"),
COMMAND_ENTRY("UN", Username, "Web username"),
COMMAND_ENTRY("PW", Password, "Web password"),
...
}
/* After matching the received command string to the command "label", the command is dispatched */
if (pc->isGetter)
return ((get_fn_t)(commands[i].get_dispatcher))(pc);
else
return ((set_fn_t)(commands[i].set_dispatcher))(pc);
}
```
Without the use of function pointers, it seems like my only hope is to use switch()/case statements to call functions. But I'd like to avoid having to manually maintain a large switch() statement.
What I was thinking of doing is moving all the COMMAND\_ENTRY lines into a separate include file. Then wraps that include file with varying #define and #undefines. Something like:
```
/* Create enum's labels */
#define COMMAND_ENTRY(label,dispatcher,description) SET_##dispatcher, GET_##dispatcher
typedef enum command_labels = {
#include "entries.cinc"
DUMMY_ENUM_ENTRY} command_labels_t;
#undefine COMMAND_ENTRY
/* Create command mapping table */
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, SET_##dispatcher, GET_##dispatcher, (const char*)description}
const command_t commands[] = {
#include "entries.cinc"
NULL /* dummy */ };
#undefine COMMAND_ENTRY
/*...*/
int command_dispatcher(command_labels_t dispatcher_id) {
/* Create dispatcher switch statement */
#define COMMAND_ENTRY(label,dispatcher,description) case SET_##dispatcher: return set_##dispatcher(pc); case GET_##dispatcher: return get_##dispatcher(pc);
switch(dispatcher_id) {
#include "entries.cinc"
default:
return NOT_FOUND;
}
#undefine COMMAND_ENTRY
}
```
Does anyone see a better way to handle this situation? Sadly, 'get another compiler' is not a viable option. :(
--- Edit to add:
Just to clarify, the particular embedded environment is broken in that the compiler is *supposed* to create a "function-pointer table" which is then used by the compiler to resolve calls to functions through a pointer. Unfortunately, the compiler is broken and doesn't generate a correct function-table.
So I don't have an easy way to extract the func address to invoke it.
--- Edit #2:
Ah, yes, the use of void \*(set|get)\_dispatcher was my attempt to see if the problem was with the typedefine of the func pointers. Originally, I had
```
typedef int (*set_fn_t)(cmdContext_t *pCmdCtx);
typedef int (*get_fn_t)(cmdContext_t *pCmdCtx);
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
```
|
You should try changing your `struct command` so the function pointers have the actual type:
```
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
```
Unfortunately, function pointers are not guaranteed to be able to convert to/from void pointers (that applies only to pointers to objects).
What's the embedded environment?
---
Given the information posted in the updates to the question, I see that it's really a bugged compiler.
I think that your proposed solution seems pretty reasonable - it's probably similar to what I would have come up with.
|
284,962 |
<p>I want to write a small program that should print something like</p>
<blockquote>
<p>testing CPU... done<br>
testing RAM... done</p>
</blockquote>
<p>and so on.</p>
<p>I wrote the following program in C:</p>
<pre><code>printf( "testing RAM...\t\t" );
sleep( sleep_time );
printf( "done\n\n" );
printf( "testing HDD...\t\t" );
sleep( sleep_time );
printf( "done\n\n" );
</code></pre>
<p>where <code>sleep_time</code> is 2.</p>
<p>However, instead of printing "testing CPU..." first, then waiting, then printing "done", it first waits, then prints the whole line, which is not exactly what I had in mind.</p>
<p>I suppose this has something to do with automatic optimization by the compiler.<br>
Anyway, what can I do to get the desired output?</p>
<p>I am using XCode 3.1 on OSX 10.5.6</p>
<p>Thank you,<br>
Bastian</p>
|
[
{
"answer_id": 284969,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "<p>The issue is that your printings are buffered. immediately before sleeping, call fflush(stdout); to flush the buffer</p>\n"
},
{
"answer_id": 287020,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 2,
"selected": false,
"text": "<p>compiler can not reorder prints and sleeps, for they are \"externally observable behavior\" of the C abstract machine.</p>\n\n<p>What you get is due to stdout buffering. You can use fflush or print to stderr, which is not buffered.</p>\n"
},
{
"answer_id": 832761,
"author": "Aditya Sehgal",
"author_id": 95321,
"author_profile": "https://Stackoverflow.com/users/95321",
"pm_score": 0,
"selected": false,
"text": "<p>Just using \\n or an endl at the end of the first printf should suffice</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1034/"
] |
I want to write a small program that should print something like
>
> testing CPU... done
>
> testing RAM... done
>
>
>
and so on.
I wrote the following program in C:
```
printf( "testing RAM...\t\t" );
sleep( sleep_time );
printf( "done\n\n" );
printf( "testing HDD...\t\t" );
sleep( sleep_time );
printf( "done\n\n" );
```
where `sleep_time` is 2.
However, instead of printing "testing CPU..." first, then waiting, then printing "done", it first waits, then prints the whole line, which is not exactly what I had in mind.
I suppose this has something to do with automatic optimization by the compiler.
Anyway, what can I do to get the desired output?
I am using XCode 3.1 on OSX 10.5.6
Thank you,
Bastian
|
The issue is that your printings are buffered. immediately before sleeping, call fflush(stdout); to flush the buffer
|
284,984 |
<p>Let's say we have these tables;</p>
<p>table user:<br>
- id<br>
- username<br>
- email</p>
<p>table user2group:<br>
- userid<br>
- groupid</p>
<p>table group:<br>
- id<br>
- groupname</p>
<p>How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)</p>
|
[
{
"answer_id": 284988,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select u.id, u.username, u.email, g.groupid, g.groupname\nfrom user u \njoin user2group ug on u.userid=ug.userid\njoin group g on g.groupid=ug.groupid\norder by u.userid\n</code></pre>\n\n<p>As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.</p>\n"
},
{
"answer_id": 285183,
"author": "ichiban",
"author_id": 37081,
"author_profile": "https://Stackoverflow.com/users/37081",
"pm_score": 2,
"selected": false,
"text": "<p>Eric's answer is great, but I would use a LEFT JOIN instead of an INNER to get users that do not belong to any group as well.</p>\n\n<pre><code>SELECT \n u.id, \n u.username, \n u.email, \n g.groupid, \n g.groupname\nFROM \n user u \n LEFT JOIN user2group ug ON u.userid = ug.userid\n LEFT JOIN group g ON g.groupid = ug.groupid\nORDER BY \n u.userid\n</code></pre>\n"
},
{
"answer_id": 285240,
"author": "devzero",
"author_id": 37083,
"author_profile": "https://Stackoverflow.com/users/37083",
"pm_score": 0,
"selected": false,
"text": "<p>Both of the above are more or less correct (deepends if each user has a group or not). But they will also both give a result set with several entries for each user.</p>\n\n<p>There are ways of concatenating every group member into one comma separated string, I'd suggest you read about it here: \n<a href=\"http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/\" rel=\"nofollow noreferrer\">http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/</a></p>\n\n<p>Another method I personally like is to use bit values instead of the relational table user2group</p>\n\n<p>table user then gets a int (or bigint) field group, and each group ID is assigned one bit value (ie: 1,2,4,8,16 and so on) The value of the user table's group field is then the sum of the groupID it's assigned to. To query if its got a group you do: \nwhere (group AND groupID = groupID)</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Let's say we have these tables;
table user:
- id
- username
- email
table user2group:
- userid
- groupid
table group:
- id
- groupname
How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)
|
```
select u.id, u.username, u.email, g.groupid, g.groupname
from user u
join user2group ug on u.userid=ug.userid
join group g on g.groupid=ug.groupid
order by u.userid
```
As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.
|
284,985 |
<p>I would like to do something like add a nice-to-Excel-functions <code>Name</code> property to the <code>WorkBook</code> class. Is there a good way to do this?</p>
<p>More detailed problem: In VBA you can assign a formula to a range in an Excel worksheet. I want to do so, and I want my formula to refer to a second workbook, which is an object called <code>wb</code> in my code. I then use <code>wb.Name</code> in assigning a formula to a range. </p>
<p>The problem arises when <code>wb.Name</code> has a single-quote in it. Then you wind up with something like this:</p>
<pre><code>=MONTH('[Ryan's WB]Sheet1'A1)
</code></pre>
<p>in the spreadsheet, which fails because the single-quote in the workbook name matches to the first single-quote.</p>
<p>What I would like is a <code>FunName</code> property for the <code>WorkBook</code> class that replaces all single-quotes in the <code>Name</code> property with two single-quotes and returns that. Then the above formula would properly wind up looking like</p>
<pre><code>=MONTH('[Ryan''s WB]Sheet1'A1)
</code></pre>
|
[
{
"answer_id": 285069,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 1,
"selected": false,
"text": "<p>Just do a replace to double up the single quotes</p>\n\n<pre><code>WorksheetName = Replace(WB.Name, \"'\", \"''\")\n</code></pre>\n"
},
{
"answer_id": 285615,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 1,
"selected": false,
"text": "<p>What you need is a Class which extends the Workbook object. Insert a class module, then try the following code</p>\n\n<pre><code>Dim WithEvents WB As Workbook\n\nPublic Sub SetWB(W As Workbook)\n Set WB = W\nEnd Sub\n\nPublic Property Get FunName() As String\n FunName = Replace(WB.Name, \"'\", \"''\")\nEnd Property\n\nPrivate Sub WB_SheetCalculate(ByVal Sh As Object)\n 'this runs when WB calculates\nEnd Sub\n</code></pre>\n\n<p>'use it like this</p>\n\n<pre><code>Dim WB As New wbClass\nWB.SetWB ActiveWorkbook\nCleanedName = WB.FunName\n</code></pre>\n\n<p>Note that as a bonus, I've put WithEvents in the line that Dims WB at the top of the class. This allows you to trap all the events that happen to WB, and I included the Calculate event as a demo above. If you are in the class code and click the objects dropdown at top left of the code pane, you'll see the WB object, and if you click this, the right hand list box will give you all the events to choose from.</p>\n"
},
{
"answer_id": 285761,
"author": "Ryan Shannon",
"author_id": 15041,
"author_profile": "https://Stackoverflow.com/users/15041",
"pm_score": 1,
"selected": false,
"text": "<p>The final answer appears to be that the WorkBook class can be extended to include a name property that is nice to Excel formulas. This can be done using the method provided by dbb. However, since VBA does not support inheritance, objects of the extended class will have only the properties you define for them.</p>\n\n<p>Therefore, it really makes more sense to just use a function. Here's what I'm going to use:</p>\n\n<pre><code>Function FormulaWorkName(ByVal aName As String) As String\n FormulaWorkName = Replace(aName, \"'\", \"''\")\nEnd Function\n</code></pre>\n\n<p>Which I will apply to both worksheet names and workbook names.</p>\n"
},
{
"answer_id": 382437,
"author": "Dick Kusleika",
"author_id": 4280,
"author_profile": "https://Stackoverflow.com/users/4280",
"pm_score": 3,
"selected": true,
"text": "<p>You don't need to make a separate class to extend the workbook class. You can add properties to the existing ThisWorkbook class module, like this:</p>\n\n<pre><code>Public Property Get FunName() As String\n\n FunName = Replace(Me.Name, \"'\", \"''\")\n\nEnd Property\n</code></pre>\n\n<p>Then you call <code>ThisWorkbook.FunName</code> to get your cleaned up name. However, this code has to exist in the workbook at hand. If you want it to work on <em>any</em> workbook, your function is the way to go.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/284985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15041/"
] |
I would like to do something like add a nice-to-Excel-functions `Name` property to the `WorkBook` class. Is there a good way to do this?
More detailed problem: In VBA you can assign a formula to a range in an Excel worksheet. I want to do so, and I want my formula to refer to a second workbook, which is an object called `wb` in my code. I then use `wb.Name` in assigning a formula to a range.
The problem arises when `wb.Name` has a single-quote in it. Then you wind up with something like this:
```
=MONTH('[Ryan's WB]Sheet1'A1)
```
in the spreadsheet, which fails because the single-quote in the workbook name matches to the first single-quote.
What I would like is a `FunName` property for the `WorkBook` class that replaces all single-quotes in the `Name` property with two single-quotes and returns that. Then the above formula would properly wind up looking like
```
=MONTH('[Ryan''s WB]Sheet1'A1)
```
|
You don't need to make a separate class to extend the workbook class. You can add properties to the existing ThisWorkbook class module, like this:
```
Public Property Get FunName() As String
FunName = Replace(Me.Name, "'", "''")
End Property
```
Then you call `ThisWorkbook.FunName` to get your cleaned up name. However, this code has to exist in the workbook at hand. If you want it to work on *any* workbook, your function is the way to go.
|
285,005 |
<p>I have to sort a number of integers, which can have values between 30.000.000 and 350.000.000. There will be between 0 and 65.535 integers, with the average count being 20.000. RAM usage is irrelevant and speed only is important.</p>
<p>Later on i will also have to split them into groups, with the divide always being set whenever the gap between two of these values is >65.535, which is what i need the algorithm for.</p>
<p>If it makes any difference, the algorithm will be used in a Perl script.</p>
<p>Edit: After thinking it over and reading the answers i've come to realize something: I don't actually care about the data itself. As i really only want to find the start and end values of groups with small gaps, the sorting only needs to create buckets and can discard the data.</p>
<p>Edit2: After some testing and trying out the answers provided, the fastest way i found was this:</p>
<pre><code>my @sort = sort {$a <=> $b} @item_offsets;
my @buckets;
my $start = shift @sort;
push @buckets, [$start,$start];
for my $item ( @sort ) {
if ( $item < $buckets[$#buckets][1]+$gap ) {
$buckets[$#buckets][1] = $item;
}
else {
push @buckets, [$item,$item];
}
}
say $#buckets;
</code></pre>
|
[
{
"answer_id": 285012,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>I'd use a radix sort, since you need to group the output.</p>\n"
},
{
"answer_id": 285023,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 3,
"selected": false,
"text": "<p>I was just going to say radix sort, <a href=\"http://en.wikipedia.org/wiki/Radix_sort\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Radix_sort</a> however that could be a bit above what you were looking to implement, Introsort is generally the accepted sorting solution for data <a href=\"http://en.wikipedia.org/wiki/Introsort\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Introsort</a>, it's a variation of quicksort that switches to heapsort when it reaches smaller sets as it's faster on smaller sets than quicksort.</p>\n"
},
{
"answer_id": 285025,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "<p>If you use the number as an index to an array, and then increment the count of that position, you've \"grouped\" them, and done it in one pass.</p>\n\n<p>in pseudocode:</p>\n\n<pre><code>while(morenumbers)\n sorted[[unsorted[number]]++\n number++\n</code></pre>\n\n<p>If the range is known ahead of time, you can reduce index the values (for example, the value-30000 to bring it into the right range).</p>\n"
},
{
"answer_id": 285038,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 4,
"selected": false,
"text": "<p>It's unlikely that you'll be able to write a sort algorithm in Perl that will perform better than Perl's builtin <code>sort</code> function:</p>\n\n<pre><code>@numbers = sort {$a <=> $b} @numbers;\n</code></pre>\n\n<p>You can experiment with the sort pragma to see if a particular algorithm is better:</p>\n\n<pre><code>use sort '_quicksort';\nuse sort '_mergesort';\n</code></pre>\n\n<p>Since your cutpoints will vary depending on the data distribution, I think you need to sort the entire list first then loop over it to do the cutting.</p>\n\n<pre><code>my $prev = shift @numbers; # already sorted\nmy @group = [$prev];\nmy $i = 0;\n\nforeach my $n (@numbers) {\n $i++ if ($n - $prev > 65535);\n push @{$group[$i]}, $n;\n $prev = $n;\n}\n</code></pre>\n"
},
{
"answer_id": 285110,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 1,
"selected": false,
"text": "<p>I would try this:</p>\n\n<pre><code>my @sorted = map { unpack \"N\" } sort map { pack \"N\" } @unsorted;\n</code></pre>\n"
},
{
"answer_id": 285112,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 5,
"selected": true,
"text": "<p>I'd just make an array of buckets before running the algorithm, one for each group of 65536 consecutive values. The buckets will contain a min and max value of their contents, but won't store the contents themselves. After running the algorithm, do a single pass over the buckets. If there are two consecutive non-empty buckets with min(bucket2)-max(bucket1) < 65536, combine them. Combining will not happen until the algorithm finishes running. Discard any empty buckets. This algorithm is linear time.</p>\n\n<p>Take note of <a href=\"http://en.wikipedia.org/wiki/Bucket_sort\" rel=\"nofollow noreferrer\">Bucket Sort</a>.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145119/"
] |
I have to sort a number of integers, which can have values between 30.000.000 and 350.000.000. There will be between 0 and 65.535 integers, with the average count being 20.000. RAM usage is irrelevant and speed only is important.
Later on i will also have to split them into groups, with the divide always being set whenever the gap between two of these values is >65.535, which is what i need the algorithm for.
If it makes any difference, the algorithm will be used in a Perl script.
Edit: After thinking it over and reading the answers i've come to realize something: I don't actually care about the data itself. As i really only want to find the start and end values of groups with small gaps, the sorting only needs to create buckets and can discard the data.
Edit2: After some testing and trying out the answers provided, the fastest way i found was this:
```
my @sort = sort {$a <=> $b} @item_offsets;
my @buckets;
my $start = shift @sort;
push @buckets, [$start,$start];
for my $item ( @sort ) {
if ( $item < $buckets[$#buckets][1]+$gap ) {
$buckets[$#buckets][1] = $item;
}
else {
push @buckets, [$item,$item];
}
}
say $#buckets;
```
|
I'd just make an array of buckets before running the algorithm, one for each group of 65536 consecutive values. The buckets will contain a min and max value of their contents, but won't store the contents themselves. After running the algorithm, do a single pass over the buckets. If there are two consecutive non-empty buckets with min(bucket2)-max(bucket1) < 65536, combine them. Combining will not happen until the algorithm finishes running. Discard any empty buckets. This algorithm is linear time.
Take note of [Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort).
|
285,042 |
<p>I'm trying to copy both an image from a file and text from a file to the clipboard. My intention is to then open a word document or an outlook email and paste both the text and the image in one standard paste command (CTRL-V for example). I can do both separately easily enough, but doing them both in one operation doesn't seem to work.</p>
<p>This is how I've got the two working as separate operations (only relevant code lines of course, with try/catch stripped out etc.):</p>
<p>Add Image to Clipboard:</p>
<p>...</p>
<pre><code>Bitmap imageToAdd = new Bitmap(imageFilePath);
Clipboard.SetImage(imageToAdd);
</code></pre>
<p>...</p>
<p>Add Text to Clipboard:</p>
<p>...</p>
<pre><code>StreamReader rdr = new StreamReader(textFilePath);
string text = rdr.ReadToEnd();
Clipboard.SetText(text);
</code></pre>
<p>...</p>
<p>I'm using c# and .net 2.0 framework and targeting Windows XP (and likely Vista in the near future).</p>
<p>TIA</p>
|
[
{
"answer_id": 285434,
"author": "GurdeepS",
"author_id": 32484,
"author_profile": "https://Stackoverflow.com/users/32484",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you could use SetDataObject which requires an Object parameter, you could use an object array?</p>\n\n<p>The object array could hold your required data.</p>\n\n<p>See this link:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/5b8kt5z4.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/5b8kt5z4.aspx</a></p>\n"
},
{
"answer_id": 307268,
"author": "GurdeepS",
"author_id": 32484,
"author_profile": "https://Stackoverflow.com/users/32484",
"pm_score": 2,
"selected": true,
"text": "<p>I noticed only an object can be passed in.</p>\n\n<p>In that case, when the user presses the command to paste, your code could execute two functions, or one function recursively, and each time get the data you want and paste it in.</p>\n\n<p>So, look at looping or recursion.</p>\n"
},
{
"answer_id": 4330393,
"author": "Chris Thornton",
"author_id": 289135,
"author_profile": "https://Stackoverflow.com/users/289135",
"pm_score": 3,
"selected": false,
"text": "<p>You could use RTF, which could combine text and graphics. Note that you CAN have CF_BITMAP and CF_TEXT on the clipboard at the same time. But it's not useful. You'd get the text when you paste into notepad, you'd get the bitmap when you paste into Paint, and most other apps would pick one or the other, but never both. So it's merely academic. Kind of neat, in the way that transporter malfunctions on Star Trek were neat. But also messy.</p>\n"
},
{
"answer_id": 61739796,
"author": "Markus",
"author_id": 1332129,
"author_profile": "https://Stackoverflow.com/users/1332129",
"pm_score": 0,
"selected": false,
"text": "<p>Adding specific code implementation; </p>\n\n<pre><code>// Load a bitmap without locking it.\nprivate Bitmap LoadBitmapUnlocked(string path)\n{\n using (Bitmap bm = new Bitmap(path))\n {\n return new Bitmap(bm);\n }\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>string path = \n@\"C:\\Windows\\Web\\Wallpaper\\Architecture\\img13.jpg\"; \nDataObject dataObj = new DataObject();\ndataObj.SetData(DataFormats.Bitmap, true, LoadBitmapUnlocked(path));\ndataObj.SetData(DataFormats.UnicodeText, path);\nClipboard.SetDataObject(dataObj);\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9732/"
] |
I'm trying to copy both an image from a file and text from a file to the clipboard. My intention is to then open a word document or an outlook email and paste both the text and the image in one standard paste command (CTRL-V for example). I can do both separately easily enough, but doing them both in one operation doesn't seem to work.
This is how I've got the two working as separate operations (only relevant code lines of course, with try/catch stripped out etc.):
Add Image to Clipboard:
...
```
Bitmap imageToAdd = new Bitmap(imageFilePath);
Clipboard.SetImage(imageToAdd);
```
...
Add Text to Clipboard:
...
```
StreamReader rdr = new StreamReader(textFilePath);
string text = rdr.ReadToEnd();
Clipboard.SetText(text);
```
...
I'm using c# and .net 2.0 framework and targeting Windows XP (and likely Vista in the near future).
TIA
|
I noticed only an object can be passed in.
In that case, when the user presses the command to paste, your code could execute two functions, or one function recursively, and each time get the data you want and paste it in.
So, look at looping or recursion.
|
285,061 |
<p>Suppose I have a python object <code>x</code> and a string <code>s</code>, how do I set the attribute <code>s</code> on <code>x</code>? So:</p>
<pre><code>>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'
</code></pre>
<p>What's the magic? The goal of this, incidentally, is to cache calls to <code>x.__getattr__()</code>. </p>
|
[
{
"answer_id": 285076,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 10,
"selected": true,
"text": "<pre><code>setattr(x, attr, 'magic')\n</code></pre>\n<p>For help on it:</p>\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(setattr)\nHelp on built-in function setattr in module __builtin__:\n\nsetattr(...)\n setattr(object, name, value)\n \n Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n ``x.y = v''.\n</code></pre>\n<p>However, you should note that you can't do that to a "pure" instance of <code>object</code>. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.</p>\n"
},
{
"answer_id": 285086,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": false,
"text": "<p>Usually, we define classes for this.</p>\n\n<pre><code>class XClass( object ):\n def __init__( self ):\n self.myAttr= None\n\nx= XClass()\nx.myAttr= 'magic'\nx.myAttr\n</code></pre>\n\n<p>However, you can, to an extent, do this with the <code>setattr</code> and <code>getattr</code> built-in functions. However, they don't work on instances of <code>object</code> directly. </p>\n\n<pre><code>>>> a= object()\n>>> setattr( a, 'hi', 'mom' )\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'object' object has no attribute 'hi'\n</code></pre>\n\n<p>They do, however, work on all kinds of simple classes.</p>\n\n<pre><code>class YClass( object ):\n pass\n\ny= YClass()\nsetattr( y, 'myAttr', 'magic' )\ny.myAttr\n</code></pre>\n"
},
{
"answer_id": 19637635,
"author": "vijay shanker",
"author_id": 1906494,
"author_profile": "https://Stackoverflow.com/users/1906494",
"pm_score": 5,
"selected": false,
"text": "<p>let x be an object then you can do it two ways</p>\n\n<pre><code>x.attr_name = s \nsetattr(x, 'attr_name', s)\n</code></pre>\n"
},
{
"answer_id": 63630201,
"author": "d.raev",
"author_id": 1621821,
"author_profile": "https://Stackoverflow.com/users/1621821",
"pm_score": 2,
"selected": false,
"text": "<p>Also works fine within a class:</p>\n<pre><code>def update_property(self, property, value):\n setattr(self, property, value)\n</code></pre>\n"
},
{
"answer_id": 73149871,
"author": "Coder100",
"author_id": 19502453,
"author_profile": "https://Stackoverflow.com/users/19502453",
"pm_score": -1,
"selected": false,
"text": "<p>If you want a filename from an argument:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\n\nfilename = sys.argv[1]\n\nfile = open(filename, 'r')\n\ncontents = file.read()\n</code></pre>\n<p>If you want an argument to show on your terminal (using <code>print()</code>):</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\n\narg = sys.argv[1]\n\narg1config = print(arg1config)\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
] |
Suppose I have a python object `x` and a string `s`, how do I set the attribute `s` on `x`? So:
```
>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'
```
What's the magic? The goal of this, incidentally, is to cache calls to `x.__getattr__()`.
|
```
setattr(x, attr, 'magic')
```
For help on it:
```none
>>> help(setattr)
Help on built-in function setattr in module __builtin__:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
```
However, you should note that you can't do that to a "pure" instance of `object`. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
|
285,074 |
<p>I'm using the <a href="http://docs.jquery.com/UI/Sortables" rel="noreferrer">jQuery UI sortables</a> plugin to allow re-ordering of some list items. Inside each list item, I've got a couple of radio buttons which allow the item to be enabled or disabled.</p>
<p>When the item is dragged, both radio buttons get deselected, which doesn't seem like it should be happening. Is this correct behavior, and if not, what is the best way to work around this?</p>
<p>Here is a code sample demonstrating this problem:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>jQuery Sortables Problem</title>
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<style type="text/css">
.items
{
margin-top: 30px;
margin-left: 0px;
padding-left: 25px;
cursor: move;
}
.items li
{
padding: 10px;
font-size: 15px;
border: 1px solid #666;
background: #eee;
width: 400px;
margin-bottom: 15px;
float: left;
clear:both;
}
</style>
</head>
<body>
<ol id="itemlist" class="items">
<li id="1" class="item">
Item 1
<input name="status_1" type="radio" value="1" checked="checked" />enabled
<input name="status_1" type="radio" value="0" />disabled
</li>
<li id="2" class="item">
Item 2
<input name="status_2" type="radio" value="1" checked="checked" />enabled
<input name="status_2" type="radio" value="0" />disabled
</li>
<li id="3" class="item">
Item 3
<input name="status_3" type="radio" value="1" checked="checked" />enabled
<input name="status_3" type="radio" value="0" />disabled
</li>
<li id="4" class="item">
Item 4
<input name="status_4" type="radio" value="1" checked="checked" />enabled
<input name="status_4" type="radio" value="0" />disabled
</li>
</ol>
<script type="text/javascript">
$('#itemlist').sortable();
</script>
</body>
</html>
</code></pre>
<p>As soon as a list item is grabbed with the mouse, both the radio buttons get deselected.</p>
<p>If this is a bug, one workaround would be to automatically select the 'enabled' radio button when the item is moved, so any advice on how to achieve this would also be most appreciated.</p>
<p>Update: I've tested this in FireFox 3, Internet Explorer 7, Opera 9.5, and Safari 3.1.2, all on Windows XP x64, and this issue occurs in all of them.</p>
|
[
{
"answer_id": 285404,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>Is this in Internet Explorer? IE is known to lose the selection of checkboxes and radios when copied/moved.</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/11/bug-299-setattribute-checked-does-not.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/11/bug-299-setattribute-checked-does-not.html</a></p>\n\n<p>defaultChecked needs to be reset for IE to behave</p>\n"
},
{
"answer_id": 290738,
"author": "Ben Koehler",
"author_id": 11996,
"author_profile": "https://Stackoverflow.com/users/11996",
"pm_score": 1,
"selected": false,
"text": "<p>It may not be exactly what you're looking for, but changing</p>\n\n<pre><code>$('#itemlist').sortable();\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$('#itemlist').sortable({placeholder: \".items li\"});\n</code></pre>\n\n<p>keeps the radio button selections.</p>\n"
},
{
"answer_id": 295153,
"author": "Serxipc",
"author_id": 34009,
"author_profile": "https://Stackoverflow.com/users/34009",
"pm_score": 1,
"selected": false,
"text": "<p>UPDATE: This applies for jQuery.ui 1.5.2. If you are using 1.6rc2 try Ben Koehler solution.</p>\n\n<hr>\n\n<p>It seems that the sortables plugin clones the node being moved. If we clone the nodes using <code>$('#itemlist li').clone().appendTo(\"#itemlist\");</code> we'll see a similar behavior, because now there are 4 radio buttons with the same name, instead of two.</p>\n\n<p>You can override the way the sortables plugin works with the helper option. Try this:</p>\n\n<pre><code>$('#itemlist').sortable({helper: function(){\n return $(\"<li>\").css({border: \"1px solid red\", background: \"transparent\"}).appendTo(\"#itemlist\")[0];\n}});\n</code></pre>\n\n<p>We are creating a new node without radio buttons and appending it to the list. This new node will be the one that is animated.<br>\nThis code works fine in FF3 and Chrome, but IE7 keeps reseting the radio buttons to its default state.</p>\n"
},
{
"answer_id": 6800800,
"author": "CommentLuv",
"author_id": 371225,
"author_profile": "https://Stackoverflow.com/users/371225",
"pm_score": 0,
"selected": false,
"text": "<p>some sort of answer to radio buttons losing their status is here\n<a href=\"http://core.trac.wordpress.org/ticket/16972#comment:4\" rel=\"nofollow\">http://core.trac.wordpress.org/ticket/16972#comment:4</a></p>\n\n<p>it's a bit of long way around but only way I could find to re do radio buttons status after being dragged somewhere</p>\n"
},
{
"answer_id": 26284023,
"author": "Randy Shelford",
"author_id": 1845994,
"author_profile": "https://Stackoverflow.com/users/1845994",
"pm_score": 0,
"selected": false,
"text": "<p>I was having a lot of the same problems, but I found a solution here :\n<a href=\"http://fiddyp.co.uk/how-to-fix-radio-inputs-losing-focus-when-dragging-a-jquery-ui-sortable-div/\" rel=\"nofollow\">http://fiddyp.co.uk/how-to-fix-radio-inputs-losing-focus-when-dragging-a-jquery-ui-sortable-div/</a> This seems to allow me to drag and drop the table rows, and the radio buttons stay in place correctly.</p>\n\n<pre><code>// global script for commentluv premium settings pages\n// workaround for bug that causes radio inputs to lose settings when meta box is dragged.\n// http://core.trac.wordpress.org/ticket/16972\njQuery(document).ready(function(){\n // listen for drag drop of metaboxes , bind mousedown to .hndle so it only fires when starting to drag\n jQuery('.hndle').mousedown(function(){\n // set event listener for mouse up on the content .wrap and wait a tick to give the dragged div time to settle before firing the reclick function\n jQuery('.wrap').mouseup(function(){store_radio(); setTimeout('reclick_radio();',50);});\n })\n});\n/**\n* stores object of all radio buttons that are checked for entire form\n*/\nfunction store_radio(){\n var radioshack = {};\n jQuery('input[type=\"radio\"]').each(function(){\n if(jQuery(this).is(':checked')){\n radioshack[jQuery(this).attr('name')] = jQuery(this).val();\n }\n jQuery(document).data('radioshack',radioshack);\n });\n}\n/**\n* detect mouseup and restore all radio buttons that were checked\n*/\nfunction reclick_radio(){\n // get object of checked radio button names and values\n var radios = jQuery(document).data('radioshack');\n //step thru each object element and trigger a click on it's corresponding radio button\n for(key in radios){\n jQuery('input[name=\"'+key+'\"]').filter('[value=\"'+radios[key]+'\"]').trigger('click');\n }\n // unbind the event listener on .wrap (prevents clicks on inputs from triggering function)\n jQuery('.wrap').unbind('mouseup');\n}\n</code></pre>\n"
},
{
"answer_id": 40921771,
"author": "Rodrigo",
"author_id": 3178803,
"author_profile": "https://Stackoverflow.com/users/3178803",
"pm_score": 0,
"selected": false,
"text": "<p>As Randy, the best solution I found was to store the checked property in another attribute and then, after the move return the checked property to the radio input. I did that in a simpler way, using the sortable start and stop parameters, as it follows.</p>\n\n<pre><code>// First, create a function to store the properties.\n\n// Store the checked radio properties\n function gravaSelecoes() {\n $(\"tbody.linhasConf\").find(\"input:radio\").each(function () {\n if ($(this).prop(\"checked\"))\n $(this).attr(\"data-checked\", \"true\");\n else\n $(this).attr(\"data-checked\", \"false\");\n });\n }\n\n// Then, create a function that restore the properties\n\n// Restore the checked radio properties\n function atualizaSelecoes() {\n $(\"tbody.linhasConf\").find(\"input:radio\").each(function () {\n if ($(this).attr(\"data-checked\") == \"true\")\n $(this).prop(\"checked\", true);\n else\n $(this).prop(\"checked\", false);\n });\n }\n\n// And when declaring sortables, refer to those functions\n\n $('tbody.linhasConf').sortable({\n start: gravaSelecoes,\n stop: atualizaSelecoes\n }).disableSelection();\n</code></pre>\n\n<p>Rodrigo</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775/"
] |
I'm using the [jQuery UI sortables](http://docs.jquery.com/UI/Sortables) plugin to allow re-ordering of some list items. Inside each list item, I've got a couple of radio buttons which allow the item to be enabled or disabled.
When the item is dragged, both radio buttons get deselected, which doesn't seem like it should be happening. Is this correct behavior, and if not, what is the best way to work around this?
Here is a code sample demonstrating this problem:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>jQuery Sortables Problem</title>
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<style type="text/css">
.items
{
margin-top: 30px;
margin-left: 0px;
padding-left: 25px;
cursor: move;
}
.items li
{
padding: 10px;
font-size: 15px;
border: 1px solid #666;
background: #eee;
width: 400px;
margin-bottom: 15px;
float: left;
clear:both;
}
</style>
</head>
<body>
<ol id="itemlist" class="items">
<li id="1" class="item">
Item 1
<input name="status_1" type="radio" value="1" checked="checked" />enabled
<input name="status_1" type="radio" value="0" />disabled
</li>
<li id="2" class="item">
Item 2
<input name="status_2" type="radio" value="1" checked="checked" />enabled
<input name="status_2" type="radio" value="0" />disabled
</li>
<li id="3" class="item">
Item 3
<input name="status_3" type="radio" value="1" checked="checked" />enabled
<input name="status_3" type="radio" value="0" />disabled
</li>
<li id="4" class="item">
Item 4
<input name="status_4" type="radio" value="1" checked="checked" />enabled
<input name="status_4" type="radio" value="0" />disabled
</li>
</ol>
<script type="text/javascript">
$('#itemlist').sortable();
</script>
</body>
</html>
```
As soon as a list item is grabbed with the mouse, both the radio buttons get deselected.
If this is a bug, one workaround would be to automatically select the 'enabled' radio button when the item is moved, so any advice on how to achieve this would also be most appreciated.
Update: I've tested this in FireFox 3, Internet Explorer 7, Opera 9.5, and Safari 3.1.2, all on Windows XP x64, and this issue occurs in all of them.
|
It may not be exactly what you're looking for, but changing
```
$('#itemlist').sortable();
```
to
```
$('#itemlist').sortable({placeholder: ".items li"});
```
keeps the radio button selections.
|
285,083 |
<p>I'm writing a custom JSP tag using the JSP 2 tag files. Inside my tag I would like to know which page called the tag in order to construct URLs. Is this possible with out passing it through an attribute?</p>
|
[
{
"answer_id": 286199,
"author": "Yoni",
"author_id": 36071,
"author_profile": "https://Stackoverflow.com/users/36071",
"pm_score": 1,
"selected": false,
"text": "<p>I think that within the tag code, you can examine the request object and its url, and determine the page from that.</p>\n"
},
{
"answer_id": 288438,
"author": "timdisney",
"author_id": 14481,
"author_profile": "https://Stackoverflow.com/users/14481",
"pm_score": 2,
"selected": false,
"text": "<p>Turns out that the request object actually is available, but only in the EL portion of a tag. So this would work:</p>\n\n<pre><code><form action=\"${pageContext.request.requestURI}\">\n</code></pre>\n\n<p>But not this:</p>\n\n<pre><code><form action=\"<%=request.requestURI%>\">\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code><form action=\"<%=pageContext.request.requestURI%>\">\n</code></pre>\n"
},
{
"answer_id": 288516,
"author": "Johann Zacharee",
"author_id": 24290,
"author_profile": "https://Stackoverflow.com/users/24290",
"pm_score": 1,
"selected": false,
"text": "<p>It is possible to access the request from within the tag file, via the <code>pageContext</code> member variable.</p>\n\n<pre><code>public class YourTag extends TagSupport {\n public int doStartTag() throws JspException {\n HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();\n String pathInfo = req.getPathInfo();\n</code></pre>\n"
},
{
"answer_id": 289328,
"author": "Yoni",
"author_id": 36071,
"author_profile": "https://Stackoverflow.com/users/36071",
"pm_score": 0,
"selected": false,
"text": "<p>The request object is available in the tag. It doesn't matter if you use a class or a tag file. In tag files, it is available in Java scriptlets as well as in EL.\nHowever, it is available as a ServletRequest object and not an HttpServletRequest object (in EL the class of the object doesn't matter, but it does in scriptlets).</p>\n\n<p>In addition, in your scriptlets you need to access the full method, not just a property name. So your code is supposed to be:</p>\n\n<pre><code><form action=\"<%= pageContext.getRequest().getRequestURI() %>\">\n</code></pre>\n\n<p>but even that won't work because getRequestURI() is a method of HttpServletRequest [1], not of ServletRequest. So either use EL, or use longer scriptlets in your tag file and cast the request object.</p>\n\n<p>[1] <a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getRequestURI()\" rel=\"nofollow noreferrer\">http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getRequestURI()</a></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14481/"
] |
I'm writing a custom JSP tag using the JSP 2 tag files. Inside my tag I would like to know which page called the tag in order to construct URLs. Is this possible with out passing it through an attribute?
|
Turns out that the request object actually is available, but only in the EL portion of a tag. So this would work:
```
<form action="${pageContext.request.requestURI}">
```
But not this:
```
<form action="<%=request.requestURI%>">
```
Or this:
```
<form action="<%=pageContext.request.requestURI%>">
```
|
285,095 |
<p>Given a week-day (1-7), how can I calculate what that week-day's last date was?</p>
<p><strong>Example:</strong> Today is <strong>Wednesday</strong>, 2008/11/12, and I want to know what last <strong>Friday's</strong> date was.</p>
|
[
{
"answer_id": 285113,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": true,
"text": "<p>If <code>today</code> is the current day of the week, then you can use something like:</p>\n\n<pre><code>days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7\n</code></pre>\n\n<p>This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract <code>days_since_friday</code> from the current date, and you'll get the date of the end of last week.</p>\n\n<p>The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:</p>\n\n<pre><code>days_since_friday = ((today + 7) - 5) % 7\n</code></pre>\n\n<p>or</p>\n\n<pre><code>days_since_friday = (today + 2) % 7\n</code></pre>\n"
},
{
"answer_id": 285117,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>In general? See <a href=\"http://emr.cs.uiuc.edu/home/reingold/calendar-book/index.shtml\" rel=\"nofollow noreferrer\">Calendrical Calculations</a>.</p>\n\n<p>In this narrower case of within the previous week? Find the difference in days (Friday = 5, Wednesday = 3). Find differences in weeks (last week = -7 days). When you've found the offset in days+weeks, apply that offset to the calendar date.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
Given a week-day (1-7), how can I calculate what that week-day's last date was?
**Example:** Today is **Wednesday**, 2008/11/12, and I want to know what last **Friday's** date was.
|
If `today` is the current day of the week, then you can use something like:
```
days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7
```
This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract `days_since_friday` from the current date, and you'll get the date of the end of last week.
The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:
```
days_since_friday = ((today + 7) - 5) % 7
```
or
```
days_since_friday = (today + 2) % 7
```
|
285,104 |
<p>For some reason sql server 2008 is not allowing me to add columns to an existing table.</p>
<p>The table is empty btw.</p>
<p>Is there a setting that prevents modifying tables in sql 2008?</p>
|
[
{
"answer_id": 285113,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": true,
"text": "<p>If <code>today</code> is the current day of the week, then you can use something like:</p>\n\n<pre><code>days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7\n</code></pre>\n\n<p>This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract <code>days_since_friday</code> from the current date, and you'll get the date of the end of last week.</p>\n\n<p>The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:</p>\n\n<pre><code>days_since_friday = ((today + 7) - 5) % 7\n</code></pre>\n\n<p>or</p>\n\n<pre><code>days_since_friday = (today + 2) % 7\n</code></pre>\n"
},
{
"answer_id": 285117,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>In general? See <a href=\"http://emr.cs.uiuc.edu/home/reingold/calendar-book/index.shtml\" rel=\"nofollow noreferrer\">Calendrical Calculations</a>.</p>\n\n<p>In this narrower case of within the previous week? Find the difference in days (Friday = 5, Wednesday = 3). Find differences in weeks (last week = -7 days). When you've found the offset in days+weeks, apply that offset to the calendar date.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
For some reason sql server 2008 is not allowing me to add columns to an existing table.
The table is empty btw.
Is there a setting that prevents modifying tables in sql 2008?
|
If `today` is the current day of the week, then you can use something like:
```
days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7
```
This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract `days_since_friday` from the current date, and you'll get the date of the end of last week.
The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:
```
days_since_friday = ((today + 7) - 5) % 7
```
or
```
days_since_friday = (today + 2) % 7
```
|
285,107 |
<p>Trying to create several layers of folders at once C:\pie\applepie\recipies\
without using several different commands, is there an easy way similar to Directory.CreateDirectory()</p>
|
[
{
"answer_id": 285131,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 4,
"selected": true,
"text": "<p>Here's some code I used in one of my projects. It requires a reference be added to the project for the file system object.</p>\n\n<p>First, click Project -> References, scroll down to \"Microsoft Scripting Runtime\" and select it. Then you can use this function:</p>\n\n<pre><code>Public Sub MakePath(ByVal Folder As String)\n\n Dim arTemp() As String\n Dim i As Long\n Dim FSO As Scripting.FileSystemObject\n Dim cFolder As String\n\n Set FSO = New Scripting.FileSystemObject\n\n arTemp = Split(Folder, \"\\\")\n For i = LBound(arTemp) To UBound(arTemp)\n cFolder = cFolder & arTemp(i) & \"\\\"\n If Not FSO.FolderExists(cFolder) Then\n Call FSO.CreateFolder(cFolder)\n End If\n Next\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 290691,
"author": "jac",
"author_id": 17776,
"author_profile": "https://Stackoverflow.com/users/17776",
"pm_score": 0,
"selected": false,
"text": "<p>As an alternative, here is a function I wrote that takes a complete path including a drive letter if needed as a parameter. It then walks the path and traps the VB error number 76 (path not found). When the error handler traps an error 76 it creates the folder that caused the error and resumes walking the path.</p>\n\n<pre>\n Public Function Check_Path(rsPath As String) As Boolean\n Dim dPath As String\n Dim i As Integer\n Dim sProductName As String\n\n On Error GoTo Check_Path_Error\n\n If Left$(UCase$(rsPath), 2) Left$(UCase$(CurDir), 2) Then\n ChDrive Left$(rsPath, 2)\n End If\n\n i = 3\n Do While InStr(i + 1, rsPath, \"\\\") > 0\n dPath = Left$(rsPath, InStr(i + 1, rsPath, \"\\\") - 1)\n i = InStr(i + 1, rsPath, \"\\\")\n ChDir dPath\n Loop\n dPath = rsPath\n ChDir dPath\n\n Check_Path = True\n\n Exit Function\n\n Check_Path_Error:\n If Err.Number = 76 Then 'path not found'\n MkDir dPath 'create the folder'\n Resume\n Else\n sProductName = IIf(Len(App.ProductName) = 0, App.EXEName, App.ProductName)\n MsgBox \"There was an unexpected error while verifying/creating directories.\" _\n & vbCrLf & vbCrLf & \"Error: \" & CStr(Err.Number) & \", \" & Err.Description & \".\", _\n vbOKOnly + vbCritical, sProductName & \" - Error Creating File\"\n Check_Path = False\n End If\n\n End Function\n</pre>\n"
},
{
"answer_id": 28992846,
"author": "Rui Manso",
"author_id": 4565386,
"author_profile": "https://Stackoverflow.com/users/4565386",
"pm_score": 2,
"selected": false,
"text": "<p>'Without the need to reference FileSystemObject</p>\n\n<pre><code>Public Sub MkPath(ByVal sPath As String)\n Dim Splits() As String, CurFolder As String\n Dim i As Long\n Splits = Split(sPath, \"\\\")\n For i = LBound(Splits) To UBound(Splits)\n CurFolder = CurFolder & Splits(i) & \"\\\"\n If Dir(CurFolder, vbDirectory) = \"\" Then MkDir CurFolder\n Next i\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 65372524,
"author": "Rui Manso",
"author_id": 4565386,
"author_profile": "https://Stackoverflow.com/users/4565386",
"pm_score": 0,
"selected": false,
"text": "<p>Yet, another simple way to do it:</p>\n<pre><code>Public Sub MakePath(ByVal Path As String)\n On Error Resume Next\n Shell "cmd /c mkdir """ & Path & """"\nEnd Sub\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Trying to create several layers of folders at once C:\pie\applepie\recipies\
without using several different commands, is there an easy way similar to Directory.CreateDirectory()
|
Here's some code I used in one of my projects. It requires a reference be added to the project for the file system object.
First, click Project -> References, scroll down to "Microsoft Scripting Runtime" and select it. Then you can use this function:
```
Public Sub MakePath(ByVal Folder As String)
Dim arTemp() As String
Dim i As Long
Dim FSO As Scripting.FileSystemObject
Dim cFolder As String
Set FSO = New Scripting.FileSystemObject
arTemp = Split(Folder, "\")
For i = LBound(arTemp) To UBound(arTemp)
cFolder = cFolder & arTemp(i) & "\"
If Not FSO.FolderExists(cFolder) Then
Call FSO.CreateFolder(cFolder)
End If
Next
End Sub
```
|
285,139 |
<p>I'm trying to duplicate the effect used in the Firefox search box where, if the search field does not have focus ( the user has not clicked inside of it ), it just says <i>Google</i> in gray text. Then, when the user clicks in the box, the text is removed and they can fill in their search term.</p>
<p>I want to use this to provide example field data for a web form.</p>
<p>JQuery syntax would be preferable to plain javascript, but plain JS would be fine too.</p>
<p>Thanks SO Hive Mind!</p>
|
[
{
"answer_id": 285157,
"author": "Leanan",
"author_id": 22390,
"author_profile": "https://Stackoverflow.com/users/22390",
"pm_score": -1,
"selected": false,
"text": "<pre>\n $(selector).text('Google'); \n $(selector).click(function(){\n $(this).text('');\n });\n</pre>\n\n<p>There's probably a more elegant way to do it, but this assumes your box has no text in it at page load. If it does you can remove the first line.</p>\n\n<p>I haven't tested this, but it should work.</p>\n"
},
{
"answer_id": 285173,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<pre><code><style type='text/css'>\n input #ghost { color: #CCC; }\n input #normal { color: #OOO; }\n</style>\n\n<script type='text/javascript'> \n function addTextHint(elem, hintText)\n { \n if (elem.value == '') \n { \n elem.value = hintText;\n elem.style.className = 'ghost';\n }\n\n elem.onfocus = function ()\n { \n if (elem.value == hintText) \n {\n elem.value = '';\n elem.className = 'normal';\n }\n }\n\n elem.onblur = function ()\n {\n if (elem.value == '')\n {\n elem.value = hintText;\n elem.className = 'ghost';\n }\n } \n }\n\n addTextHint(document.getElementById('foobar'),'Google');\n</script>\n</code></pre>\n\n<p>Just whipped this up for you. jQuery would make it smaller I'm sure, but I don't use it.</p>\n"
},
{
"answer_id": 285191,
"author": "Nick",
"author_id": 26161,
"author_profile": "https://Stackoverflow.com/users/26161",
"pm_score": 2,
"selected": false,
"text": "<p>Another way is to use some CSS, create an image with the background text you want, and set that as the background image of the text box, then when the text box get's focus you could switch styles to remove that background image.</p>\n"
},
{
"answer_id": 4751150,
"author": "kprevas",
"author_id": 173421,
"author_profile": "https://Stackoverflow.com/users/173421",
"pm_score": 0,
"selected": false,
"text": "<p>Why roll your own? Use <a href=\"http://plugins.jquery.com/project/updnWatermark\" rel=\"nofollow\">this plugin</a>.</p>\n"
},
{
"answer_id": 12960470,
"author": "mikeswright49",
"author_id": 1747217,
"author_profile": "https://Stackoverflow.com/users/1747217",
"pm_score": 2,
"selected": false,
"text": "<p>JQuery Implementation</p>\n\n<pre><code><input type=\"text\" id = \"textField\" value=\"Google\" class=\"RegularText GhostText\" />\n\n<style>\n.GhostText{color:#DDD}\n.RegularText{color:#CCC}\n</style>\n\n<script type=\"text/javascript\" language=\"javascript\">\n$(\"#textField\").blur(function(e){\n if ($.trim(e.target.value) == \"\") {\n e.target.value = e.target.defaultValue;\n e.target.toggleClass(\"GhostText\");\n }\n});\n$(\"#textField\").focus(function(e){\n if ($.trim(e.target.value) == e.target.defaultValue) {\n e.target.value = \"\";\n e.target.toggleClass(\"GhostText\");\n }\n});\n</script>\n</code></pre>\n"
},
{
"answer_id": 21551754,
"author": "zah",
"author_id": 35511,
"author_profile": "https://Stackoverflow.com/users/35511",
"pm_score": 2,
"selected": false,
"text": "<p>This technique is so commonly used that it's now explicitly supported in the HTML spec through the placeholder attribute of the input tag: <br />\n<a href=\"http://www.w3schools.com/tags/att_input_placeholder.asp\" rel=\"nofollow\">HTML placeholder Attribute</a></p>\n\n<p><a href=\"http://caniuse.com/input-placeholder\" rel=\"nofollow\">It's already supported in most browsers</a> and for older ones there is a jquery plugin providing shim implementation that can be found <a href=\"https://github.com/mathiasbynens/jquery-placeholder\" rel=\"nofollow\">here</a>.</p>\n\n<p>For styling the placeholder text, refer to this (live examples included): <br />\n<a href=\"http://davidwalsh.name/html5-placeholder-css\" rel=\"nofollow\">HTML5 Placeholder Styling with CSS</a></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to duplicate the effect used in the Firefox search box where, if the search field does not have focus ( the user has not clicked inside of it ), it just says *Google* in gray text. Then, when the user clicks in the box, the text is removed and they can fill in their search term.
I want to use this to provide example field data for a web form.
JQuery syntax would be preferable to plain javascript, but plain JS would be fine too.
Thanks SO Hive Mind!
|
```
<style type='text/css'>
input #ghost { color: #CCC; }
input #normal { color: #OOO; }
</style>
<script type='text/javascript'>
function addTextHint(elem, hintText)
{
if (elem.value == '')
{
elem.value = hintText;
elem.style.className = 'ghost';
}
elem.onfocus = function ()
{
if (elem.value == hintText)
{
elem.value = '';
elem.className = 'normal';
}
}
elem.onblur = function ()
{
if (elem.value == '')
{
elem.value = hintText;
elem.className = 'ghost';
}
}
}
addTextHint(document.getElementById('foobar'),'Google');
</script>
```
Just whipped this up for you. jQuery would make it smaller I'm sure, but I don't use it.
|
285,148 |
<p>I've written a rails app that follows the regular directory structure (model code in models, controller code in controllers).</p>
<p>But I'm now working on a new feature and for that I have written some (what I would call) "service" code.<br>
The new feature is to import some data into the system, at the moment it's two classes to do the importing but could expand to more.</p>
<p>I don't believe the new code belongs in model as it's not modelling any object (it's not directly related to any single object either.
I certainly don't think it belongs in controller either as it's not presentation logic.</p>
<p>So, I've created a "app/services" directory and put it in there.
I've also created a "test/services" directory where I have put my tests.</p>
<p>All well and good I thought but when I run 'rake:test' or 'autotest' my new services tests are not run.<br>
Now I expect there is a way to make rake pick them up but is this a warning flag that I have done something wrong?<br>
Is there some other place the code should live or am I somehow not doing things "the Rails way"?</p>
<p>Generally whenever I've hit a problem like this before I've usually found that rails had a solution already, but I was not aware of the convention.
Is this one of those cases?</p>
|
[
{
"answer_id": 285152,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 6,
"selected": true,
"text": "<p>This is what the 'lib' folder is for.</p>\n\n<p>The lib folder is in the automatically looked up path, so you can have</p>\n\n<pre><code>class MyFoo\nend\n</code></pre>\n\n<p>in <code>lib/my_foo.rb</code> and then just by calling</p>\n\n<pre><code>MyFoo.new\n</code></pre>\n\n<p>from a controller the code will be loaded without you needing a <code>require 'my_foo'</code></p>\n"
},
{
"answer_id": 285163,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 1,
"selected": false,
"text": "<p>./lib is definitely the place to go.</p>\n\n<p>Another place to put this is in the initializers directory under config, depending on what it is your doing. You might also consider making the whole thing into a plugin, but if it's a small amount of functionality, it probably isn't worth it.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151/"
] |
I've written a rails app that follows the regular directory structure (model code in models, controller code in controllers).
But I'm now working on a new feature and for that I have written some (what I would call) "service" code.
The new feature is to import some data into the system, at the moment it's two classes to do the importing but could expand to more.
I don't believe the new code belongs in model as it's not modelling any object (it's not directly related to any single object either.
I certainly don't think it belongs in controller either as it's not presentation logic.
So, I've created a "app/services" directory and put it in there.
I've also created a "test/services" directory where I have put my tests.
All well and good I thought but when I run 'rake:test' or 'autotest' my new services tests are not run.
Now I expect there is a way to make rake pick them up but is this a warning flag that I have done something wrong?
Is there some other place the code should live or am I somehow not doing things "the Rails way"?
Generally whenever I've hit a problem like this before I've usually found that rails had a solution already, but I was not aware of the convention.
Is this one of those cases?
|
This is what the 'lib' folder is for.
The lib folder is in the automatically looked up path, so you can have
```
class MyFoo
end
```
in `lib/my_foo.rb` and then just by calling
```
MyFoo.new
```
from a controller the code will be loaded without you needing a `require 'my_foo'`
|
285,154 |
<p>How can I access options that I set in a jQuery Datepicker?</p>
<pre><code>$("#testDatePicker").datepicker({
minDate: new Date(2005, 0, 26),
showOn: 'button',
buttonImage: 'js/themes/default/images/calendar.gif',
buttonImageOnly: true
});
var minDate = $("#testDatePicker").?????;
</code></pre>
|
[
{
"answer_id": 285172,
"author": "Leanan",
"author_id": 22390,
"author_profile": "https://Stackoverflow.com/users/22390",
"pm_score": 0,
"selected": false,
"text": "<p>I'd take a look at the code. Most plugins I've looked at have either a option or config var that they extend with what you pass in.</p>\n\n<p>You could check real quick and try to do something like $.datepicker.buttonImageOnly = false; and then see if that actually changed anything. </p>\n\n<p>Of course this may not work. I haven't looked at the plugin. I'm just operating off of what I see as typical behavior of plugins I've worked with (tablesorter, etc)</p>\n"
},
{
"answer_id": 285302,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 2,
"selected": true,
"text": "<p>What about storing the options in a named var instead of an anonymous object?</p>\n\n<pre><code>var dpOptions = {minDate: new Date(2005, 0, 26), ...};\n$('#testDatePicker').datepicker(dpOptions);\n.\n.\n.\nvar minDate = dpOptions.minDate;\n</code></pre>\n"
},
{
"answer_id": 287589,
"author": "Serxipc",
"author_id": 34009,
"author_profile": "https://Stackoverflow.com/users/34009",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't have enough with @mausch solution the settings are stored here:</p>\n\n<pre><code> $.data($('#testDatePicker')[0], 'datepicker').settings\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10976/"
] |
How can I access options that I set in a jQuery Datepicker?
```
$("#testDatePicker").datepicker({
minDate: new Date(2005, 0, 26),
showOn: 'button',
buttonImage: 'js/themes/default/images/calendar.gif',
buttonImageOnly: true
});
var minDate = $("#testDatePicker").?????;
```
|
What about storing the options in a named var instead of an anonymous object?
```
var dpOptions = {minDate: new Date(2005, 0, 26), ...};
$('#testDatePicker').datepicker(dpOptions);
.
.
.
var minDate = dpOptions.minDate;
```
|
285,177 |
<p>Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?</p>
|
[
{
"answer_id": 285184,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 13,
"selected": true,
"text": "<p>Yes, it is possible:</p>\n\n<pre><code>public class Foo {\n private int x;\n\n public Foo() {\n this(1);\n }\n\n public Foo(int x) {\n this.x = x;\n }\n}\n</code></pre>\n\n<p>To chain to a particular superclass constructor instead of one in the same class, use <code>super</code> instead of <code>this</code>. Note that <strong>you can only chain to one constructor</strong>, and <strong>it has to be the first statement in your constructor body</strong>.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/284896\">this related question</a>, which is about C# but where the same principles apply.</p>\n"
},
{
"answer_id": 285187,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 8,
"selected": false,
"text": "<p>Using <code>this(args)</code>. The preferred pattern is to work from the smallest constructor to the largest.</p>\n\n<pre><code>public class Cons {\n\n public Cons() {\n // A no arguments constructor that sends default values to the largest\n this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);\n }\n\n public Cons(int arg1, int arg2) {\n // An example of a partial constructor that uses the passed in arguments\n // and sends a hidden default value to the largest\n this(arg1,arg2, madeUpArg3Value);\n }\n\n // Largest constructor that does the work\n public Cons(int arg1, int arg2, int arg3) {\n this.arg1 = arg1;\n this.arg2 = arg2;\n this.arg3 = arg3;\n }\n}\n</code></pre>\n\n<p>You can also use a more recently advocated approach of valueOf or just \"of\":</p>\n\n<pre><code>public class Cons {\n public static Cons newCons(int arg1,...) {\n // This function is commonly called valueOf, like Integer.valueOf(..)\n // More recently called \"of\", like EnumSet.of(..)\n Cons c = new Cons(...);\n c.setArg1(....);\n return c;\n }\n} \n</code></pre>\n\n<p>To call a super class, use <code>super(someValue)</code>. The call to super must be the first call in the constructor or you will get a compiler error.</p>\n"
},
{
"answer_id": 15348070,
"author": "Christian Fries",
"author_id": 231397,
"author_profile": "https://Stackoverflow.com/users/231397",
"pm_score": 8,
"selected": false,
"text": "<p>[<em>Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).</em>]</p>\n\n<p>In Java another constructor of the same class can be called from a constructor via <code>this()</code>. Note however that <code>this</code> has to be on the first line.</p>\n\n<pre><code>public class MyClass {\n\n public MyClass(double argument1, double argument2) {\n this(argument1, argument2, 0.0);\n }\n\n public MyClass(double argument1, double argument2, double argument3) {\n this.argument1 = argument1;\n this.argument2 = argument2;\n this.argument3 = argument3;\n }\n}\n</code></pre>\n\n<p>That <code>this</code> has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:</p>\n\n<pre><code>public class MyClass {\n\n public MyClass(double argument1, double argument2) {\n this(argument1, argument2, getDefaultArg3(argument1, argument2));\n }\n\n public MyClass(double argument1, double argument2, double argument3) {\n this.argument1 = argument1;\n this.argument2 = argument2;\n this.argument3 = argument3;\n }\n\n private static double getDefaultArg3(double argument1, double argument2) {\n double argument3 = 0;\n\n // Calculate argument3 here if you like.\n\n return argument3;\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 16180692,
"author": "Kaamel",
"author_id": 2295938,
"author_profile": "https://Stackoverflow.com/users/2295938",
"pm_score": 5,
"selected": false,
"text": "<p>When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:</p>\n\n<pre><code>class MyClass {\n int field;\n\n\n MyClass() {\n init(0);\n } \n MyClass(int value) {\n if (value<0) {\n init(0);\n } \n else { \n init(value);\n }\n }\n void init(int x) {\n field = x;\n }\n}\n</code></pre>\n\n<p>But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example</p>\n\n<pre><code>class MyClass {\n int field;\n\n MyClass(int value) {\n if (value<0)\n field = 0;\n else\n field = value;\n }\n MyClass() {\n this(0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30112975,
"author": "olovb",
"author_id": 147808,
"author_profile": "https://Stackoverflow.com/users/147808",
"pm_score": 4,
"selected": false,
"text": "<p>As everybody already have said, you use <code>this(…)</code>, which is called an <em>explicit constructor invocation</em>.</p>\n\n<p><strong>However, keep in mind that</strong> within such an explicit constructor invocation statement <strong>you may not refer to</strong></p>\n\n<ul>\n<li>any <em>instance variables</em> or </li>\n<li>any <em>instance methods</em> or </li>\n<li>any <em>inner classes</em> declared in this class or any superclass, or </li>\n<li><code>this</code> or </li>\n<li><code>super</code>.</li>\n</ul>\n\n<p>As stated in JLS (§8.8.7.1).</p>\n"
},
{
"answer_id": 30462394,
"author": "amila isura",
"author_id": 4395148,
"author_profile": "https://Stackoverflow.com/users/4395148",
"pm_score": 5,
"selected": false,
"text": "<p>Within a constructor, you can use the <code>this</code> keyword to invoke another constructor in the same class. Doing so is called an <strong>explicit constructor invocation</strong>. </p>\n\n<p>Here's another Rectangle class, with a different implementation from the one in the Objects section.</p>\n\n<pre><code>public class Rectangle {\n private int x, y;\n private int width, height;\n\n public Rectangle() {\n this(1, 1);\n }\n public Rectangle(int width, int height) {\n this( 0,0,width, height);\n }\n public Rectangle(int x, int y, int width, int height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n\n}\n</code></pre>\n\n<p>This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.</p>\n"
},
{
"answer_id": 33963435,
"author": "ABHISHEK RANA",
"author_id": 5182313,
"author_profile": "https://Stackoverflow.com/users/5182313",
"pm_score": 3,
"selected": false,
"text": "<p>You can a constructor from another constructor of same class by using \"this\" keyword.\nExample -</p>\n\n<pre><code>class This1\n{\n This1()\n {\n this(\"Hello\");\n System.out.println(\"Default constructor..\");\n }\n This1(int a)\n {\n this();\n System.out.println(\"int as arg constructor..\"); \n }\n This1(String s)\n {\n System.out.println(\"string as arg constructor..\"); \n }\n\n public static void main(String args[])\n {\n new This1(100);\n }\n}\n</code></pre>\n\n<p>Output -\nstring as arg constructor..\nDefault constructor..\nint as arg constructor..</p>\n"
},
{
"answer_id": 39462961,
"author": "Akash Manngroliya",
"author_id": 5089473,
"author_profile": "https://Stackoverflow.com/users/5089473",
"pm_score": 3,
"selected": false,
"text": "<p>Yes it is possible to call one constructor from another with use of <code>this()</code></p>\n\n<pre><code>class Example{\n private int a = 1;\n Example(){\n this(5); //here another constructor called based on constructor argument\n System.out.println(\"number a is \"+a); \n }\n Example(int b){\n System.out.println(\"number b is \"+b);\n }\n</code></pre>\n"
},
{
"answer_id": 40637000,
"author": "Utsav",
"author_id": 2106934,
"author_profile": "https://Stackoverflow.com/users/2106934",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, any number of constructors can be present in a class and they can be called by another constructor using <code>this()</code> [Please do not confuse <code>this()</code> constructor call with <code>this</code> keyword]. <code>this()</code> or <code>this(args)</code> should be the first line in the constructor.</p>\n\n<p>Example:</p>\n\n<pre><code>Class Test {\n Test() {\n this(10); // calls the constructor with integer args, Test(int a)\n }\n Test(int a) {\n this(10.5); // call the constructor with double arg, Test(double a)\n }\n Test(double a) {\n System.out.println(\"I am a double arg constructor\");\n }\n}\n</code></pre>\n\n<p>This is known as constructor overloading.<br>\nPlease note that for constructor, only overloading concept is applicable and not inheritance or overriding.</p>\n"
},
{
"answer_id": 40721089,
"author": "Py-Coder",
"author_id": 5340833,
"author_profile": "https://Stackoverflow.com/users/5340833",
"pm_score": 3,
"selected": false,
"text": "<p><strong>I will tell you an easy way</strong></p>\n\n<p>There are <strong>two</strong> types of constructors:</p>\n\n<ol>\n<li><strong>Default constructor</strong></li>\n<li><strong>Parameterized constructor</strong></li>\n</ol>\n\n<p>I will explain in one Example</p>\n\n<pre><code>class ConstructorDemo \n{\n ConstructorDemo()//Default Constructor\n {\n System.out.println(\"D.constructor \");\n }\n\n ConstructorDemo(int k)//Parameterized constructor\n {\n this();//-------------(1)\n System.out.println(\"P.Constructor =\"+k); \n }\n\n public static void main(String[] args) \n {\n //this(); error because \"must be first statement in constructor\n new ConstructorDemo();//-------(2)\n ConstructorDemo g=new ConstructorDemo(3);---(3) \n }\n } \n</code></pre>\n\n<p>In the above example I showed 3 types of calling</p>\n\n<ol>\n<li>this() call to this must be first statement in constructor</li>\n<li>This is Name less Object. this automatically calls the default constructor.\n3.This calls the Parameterized constructor.</li>\n</ol>\n\n<p>Note:\n<strong>this must be the first statement in the constructor.</strong></p>\n"
},
{
"answer_id": 41521892,
"author": "S R Chaitanya",
"author_id": 4543733,
"author_profile": "https://Stackoverflow.com/users/4543733",
"pm_score": 4,
"selected": false,
"text": "<p>Yes it is possible to call one constructor from another. But there is a rule to it. If a call is made from one constructor to another, then </p>\n\n<blockquote>\n <p><em>that new constructor call must be the first statement in the current constructor</em></p>\n</blockquote>\n\n<pre><code>public class Product {\n private int productId;\n private String productName;\n private double productPrice;\n private String category;\n\n public Product(int id, String name) {\n this(id,name,1.0);\n }\n\n public Product(int id, String name, double price) {\n this(id,name,price,\"DEFAULT\");\n }\n\n public Product(int id,String name,double price, String category){\n this.productId=id;\n this.productName=name;\n this.productPrice=price;\n this.category=category;\n }\n}\n</code></pre>\n\n<p>So, something like below will not work.</p>\n\n<pre><code>public Product(int id, String name, double price) {\n System.out.println(\"Calling constructor with price\");\n this(id,name,price,\"DEFAULT\");\n}\n</code></pre>\n\n<p>Also, in the case of inheritance, when sub-class's object is created, the super class constructor is first called.</p>\n\n<pre><code>public class SuperClass {\n public SuperClass() {\n System.out.println(\"Inside super class constructor\");\n }\n}\npublic class SubClass extends SuperClass {\n public SubClass () {\n //Even if we do not add, Java adds the call to super class's constructor like \n // super();\n System.out.println(\"Inside sub class constructor\");\n }\n}\n</code></pre>\n\n<p>Thus, in this case also another constructor call is first declared before any other statements.</p>\n"
},
{
"answer_id": 42575098,
"author": "Akshay Gaikwad",
"author_id": 6069781,
"author_profile": "https://Stackoverflow.com/users/6069781",
"pm_score": 3,
"selected": false,
"text": "<p>Calling constructor from another constructor</p>\n\n<pre><code>class MyConstructorDemo extends ConstructorDemo\n{\n MyConstructorDemo()\n {\n this(\"calling another constructor\");\n }\n MyConstructorDemo(String arg)\n {\n System.out.print(\"This is passed String by another constructor :\"+arg);\n }\n}\n</code></pre>\n\n<p>Also you can call parent constructor by using <code>super()</code> call</p>\n"
},
{
"answer_id": 42798699,
"author": "S. Mayol",
"author_id": 4066742,
"author_profile": "https://Stackoverflow.com/users/4066742",
"pm_score": 3,
"selected": false,
"text": "<p>The keyword <strong><em>this</em></strong> can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.</p>\n\n<p>Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/19359548/setter-methods-or-constructors/42798426#42798426\">Setter methods or constructors</a></p>\n"
},
{
"answer_id": 47274985,
"author": "Rodney P. Barbati",
"author_id": 1588303,
"author_profile": "https://Stackoverflow.com/users/1588303",
"pm_score": 3,
"selected": false,
"text": "<p>There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.</p>\n\n<p>With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.</p>\n\n<pre><code>class LambdaInitedClass {\n\n public LamdaInitedClass(Consumer<LambdaInitedClass> init) {\n init.accept(this);\n }\n}\n</code></pre>\n\n<p>Call it with...</p>\n\n<pre><code> new LambdaInitedClass(l -> { // init l any way you want });\n</code></pre>\n"
},
{
"answer_id": 47414995,
"author": "GetBackerZ",
"author_id": 2576702,
"author_profile": "https://Stackoverflow.com/users/2576702",
"pm_score": 3,
"selected": false,
"text": "<p>Pretty simple </p>\n\n<pre><code>public class SomeClass{\n\n private int number;\n private String someString;\n\n public SomeClass(){\n number = 0;\n someString = new String();\n }\n\n public SomeClass(int number){\n this(); //set the class to 0\n this.setNumber(number); \n }\n\n public SomeClass(int number, String someString){\n this(number); //call public SomeClass( int number )\n this.setString(someString);\n }\n\n public void setNumber(int number){\n this.number = number;\n }\n public void setString(String someString){\n this.someString = someString;\n }\n //.... add some accessors\n}\n</code></pre>\n\n<p>now here is some small extra credit:</p>\n\n<pre><code>public SomeOtherClass extends SomeClass {\n public SomeOtherClass(int number, String someString){\n super(number, someString); //calls public SomeClass(int number, String someString)\n }\n //.... Some other code.\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 48415573,
"author": "Negi Rox",
"author_id": 5483580,
"author_profile": "https://Stackoverflow.com/users/5483580",
"pm_score": 2,
"selected": false,
"text": "<p>I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.</p>\n\n<pre><code> import java.util.*;\n import java.lang.*;\n\n class Test\n { \n public static void main(String args[])\n {\n Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.\n Dog cs = new Dog(\"Bite\"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.\n\n // You need to Explicitly tell the java compiler to use Argument constructor so you need to use \"super\" key word\n System.out.println(\"------------------------------\");\n Cat c = new Cat();\n Cat caty = new Cat(\"10\");\n\n System.out.println(\"------------------------------\");\n // Self s = new Self();\n Self ss = new Self(\"self\");\n }\n }\n\n class Animal\n {\n String i;\n\n public Animal()\n {\n i = \"10\";\n System.out.println(\"Animal Constructor :\" +i);\n }\n public Animal(String h)\n {\n i = \"20\";\n System.out.println(\"Animal Constructor Habit :\"+ i);\n }\n }\n\n class Dog extends Animal\n {\n public Dog()\n {\n System.out.println(\"Dog Constructor\");\n }\n public Dog(String h)\n {\n System.out.println(\"Dog Constructor with habit\");\n }\n }\n\n class Cat extends Animal\n {\n public Cat()\n {\n System.out.println(\"Cat Constructor\");\n }\n public Cat(String i)\n {\n super(i); // Calling Super Class Paremetrize Constructor.\n System.out.println(\"Cat Constructor with habit\");\n }\n }\n\n class Self\n {\n public Self()\n {\n System.out.println(\"Self Constructor\");\n }\n public Self(String h)\n {\n this(); // Explicitly calling 0 args constructor. \n System.out.println(\"Slef Constructor with value\");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 50728250,
"author": "Omar Faroque Anik",
"author_id": 3254692,
"author_profile": "https://Stackoverflow.com/users/3254692",
"pm_score": 2,
"selected": false,
"text": "<p>It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example: </p>\n\n<pre><code> public Omar(){};\n public Omar(a){};\n public Omar(a,b){};\n public Omar(a,b,c){};\n public Omar(a,b,c,d){};\n ...\n</code></pre>\n\n<p>You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful\n<a href=\"https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e\" rel=\"nofollow noreferrer\">https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e</a></p>\n"
},
{
"answer_id": 51576459,
"author": "John McClane",
"author_id": 9772691,
"author_profile": "https://Stackoverflow.com/users/9772691",
"pm_score": 3,
"selected": false,
"text": "<p>You can call another constructor via the <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html\" rel=\"noreferrer\"><code>this(...)</code></a> keyword (when you need to call a constructor from the same class) or the <a href=\"https://docs.oracle.com/javase/tutorial/java/IandI/super.html\" rel=\"noreferrer\"><code>super(...)</code></a> keyword\n(when you need to call a constructor from a superclass).</p>\n\n<p>However, such a call must be the <strong>first</strong> statement of your constructor. To <strong>overcome</strong> this limitation, use <a href=\"https://stackoverflow.com/a/51571736/9772691\">this answer</a>.</p>\n"
},
{
"answer_id": 55583536,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 1,
"selected": false,
"text": "<p>Originally from an anser by Mirko Klemm, slightly modified to address the question:</p>\n\n<p>Just for completeness: There is also the <a href=\"https://stackoverflow.com/questions/3987428/what-is-an-initialization-block\">Instance initialization block</a> that gets executed always and before any other constructor is called. It consists simply of a block of statements \"{ ... }\" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like \"shared constructor\" code if you want to reuse some code across constructors, similar to calling methods.</p>\n\n<p>So in your case</p>\n\n<pre><code>{ \n System.out.println(\"this is shared constructor code executed before the constructor\");\n field1 = 3;\n}\n</code></pre>\n\n<p>There is also a \"static\" version of this to initialize static members: \"static { ... }\"</p>\n"
},
{
"answer_id": 56663443,
"author": "ansh sachdeva",
"author_id": 7500651,
"author_profile": "https://Stackoverflow.com/users/7500651",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer this way: </p>\n\n<pre><code> class User {\n private long id;\n private String username;\n private int imageRes;\n\n public User() {\n init(defaultID,defaultUsername,defaultRes);\n }\n public User(String username) {\n init(defaultID,username, defaultRes());\n }\n\n public User(String username, int imageRes) {\n init(defaultID,username, imageRes);\n }\n\n public User(long id, String username, int imageRes) {\n init(id,username, imageRes);\n\n }\n\n private void init(long id, String username, int imageRes) {\n this.id=id;\n this.username = username;\n this.imageRes = imageRes;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 57314267,
"author": "Soni K",
"author_id": 6505685,
"author_profile": "https://Stackoverflow.com/users/6505685",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, you can call constructors from another constructor. For example:</p>\n<pre><code>public class Animal {\n private int animalType;\n\n public Animal() {\n this(1); //here this(1) internally make call to Animal(1);\n }\n\n public Animal(int animalType) {\n this.animalType = animalType;\n }\n}\n</code></pre>\n<p>you can also read in details from\n<a href=\"https://beginnersbook.com/2013/12/java-constructor-chaining-with-example/\" rel=\"nofollow noreferrer\">Constructor Chaining in Java</a></p>\n"
},
{
"answer_id": 65745848,
"author": "Anil Nivargi",
"author_id": 8450064,
"author_profile": "https://Stackoverflow.com/users/8450064",
"pm_score": 4,
"selected": false,
"text": "<p>Using this keyword we can call one constructor in another constructor within same class.</p>\n<p>Example :-</p>\n<pre><code> public class Example {\n \n private String name;\n \n public Example() {\n this("Mahesh");\n }\n\n public Example(String name) {\n this.name = name;\n }\n\n }\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?
|
Yes, it is possible:
```
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
```
To chain to a particular superclass constructor instead of one in the same class, use `super` instead of `this`. Note that **you can only chain to one constructor**, and **it has to be the first statement in your constructor body**.
See also [this related question](https://stackoverflow.com/questions/284896), which is about C# but where the same principles apply.
|
285,238 |
<p>Firstly I'm extending an existing class structure and cannot alter the original, with that caveat:</p>
<p>I would like to do this:</p>
<pre><code>class a
{
int val;
... // usual constructor, etc...
public int displayAlteredValue(int inp)
{
return (val*inp);
}
}
class b extends a
{
... // usual constructor, etc...
public in displayAlteredValue(int inp1, int inp2)
{
return (val*inp1*inp2);
}
}
</code></pre>
<p>As I said before I cannot alter <code>class a</code> and I want to maintain the function name <code>displayAlteredValue</code> rather than making a new function.
If this can be done I only have to change a few instantiations of <code>a</code> to instantiations of <code>b</code>. I don't want to spend a lot of time replacing the many function calls to <code>displayAlteredValue</code>. (And yes I do realise there are such things as search and replace however for other reasons, doing that would be problematic).</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 285258,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 1,
"selected": false,
"text": "<p>what if you add this to your derived class</p>\n\n<pre><code>public int displayAlteredValue(int inp)\n{\n return super.displayAlteredValue(inp);\n}\n</code></pre>\n"
},
{
"answer_id": 285295,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 2,
"selected": false,
"text": "<p>You can overload a function in a derived class. So what you have specified above should work. Just wrote a quick test and it worked.</p>\n\n<pre><code>public class DerivedOverload {\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n A classA = new A(); \n\n B classB = new B();\n\n System.out.println(\"DerivedOverload.main() classA.displayAlteredValue(2) : \" + classA.displayAlteredValue(2));\n\n System.out.println(\"DerivedOverload.main() classA.displayAlteredValue(2) : \" + classB.displayAlteredValue(2,2));\n }\n\n\n\n}\n\n\nclass A\n{\n int val = 2;\n\n A(){\n\n }\n\n public int displayAlteredValue(int inp)\n {\n return (val*inp);\n }\n}\n\nclass B extends A\n{\n B(){\n\n }\n\n public int displayAlteredValue(int inp1, int inp2)\n {\n return (val*inp1*inp2);\n }\n}\n</code></pre>\n\n<p>System out.\nDerivedOverload.main() classA.displayAlteredValue(2) : 4\nDerivedOverload.main() classA.displayAlteredValue(2) : 8</p>\n"
},
{
"answer_id": 285300,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>The code you've written compiles as-is. You've basically just overloaded the method. What does the code you posted not accomplish, that you <em>want</em> to accomplish? Are you trying to stop people from calling b.displayAlteredValue with a single argument? If so, you can't do that (at compile time) as it would violate Liskov's Substitutability Principle.</p>\n\n<p>You could throw an exception, but that wouldn't be terribly nice.</p>\n\n<p>Alternatively, you could use composition instead of inheritance - but really we'd need to know more about the situation to know whether that was suitable.</p>\n"
},
{
"answer_id": 285301,
"author": "Clayton",
"author_id": 22201,
"author_profile": "https://Stackoverflow.com/users/22201",
"pm_score": 1,
"selected": false,
"text": "<p>What you have looks fine to me.</p>\n\n<p>Instances of class b will have access to both versions of the method. Calls to the 1-argument version will be automatically routed to class a. Calls to the 2-arg version will go to class b.</p>\n\n<p>Instances of class a will only have access to the 1-arg version though, but I don't think there's a way around that.</p>\n"
},
{
"answer_id": 285303,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not clear what the issue is. You absolutely can create a subclass b which has a method of the same name but different signature.</p>\n\n<p>One possible issue you might be running into is that the compiler needs to know that the type of the object is b, not a, in order to call the method that only exists in b.</p>\n\n<p>So code like this won't work:</p>\n\n<pre><code>// this works because b is a subclass of a\na anObject = new b();\n\n// this will not compile because the declared type of anObject is a\nint x = anObject.getValue( 1, 2 );\n</code></pre>\n\n<p>You would have to either change the declaration of the variable to type b, or cast it to b whenever you want to call the 2-argument method.</p>\n"
},
{
"answer_id": 285346,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": "<p>You could write the code in class B as follows:</p>\n\n<pre><code>public int displayAlteredValue(int inp) \n{\n return -1;\n}\n</code></pre>\n\n<p>and indicate on the function that -1 is an error return. For int this doesn't really work, but if you returned a class, you could return null if they call the single parameter version of the method.</p>\n"
},
{
"answer_id": 285373,
"author": "Clay",
"author_id": 37104,
"author_profile": "https://Stackoverflow.com/users/37104",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively, you could consider favoring composition over inheritance since the class you are extending comes from a different package.</p>\n\n<p><a href=\"http://www.artima.com/lejava/articles/designprinciples4.html\" rel=\"nofollow noreferrer\">http://www.artima.com/lejava/articles/designprinciples4.html</a></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Firstly I'm extending an existing class structure and cannot alter the original, with that caveat:
I would like to do this:
```
class a
{
int val;
... // usual constructor, etc...
public int displayAlteredValue(int inp)
{
return (val*inp);
}
}
class b extends a
{
... // usual constructor, etc...
public in displayAlteredValue(int inp1, int inp2)
{
return (val*inp1*inp2);
}
}
```
As I said before I cannot alter `class a` and I want to maintain the function name `displayAlteredValue` rather than making a new function.
If this can be done I only have to change a few instantiations of `a` to instantiations of `b`. I don't want to spend a lot of time replacing the many function calls to `displayAlteredValue`. (And yes I do realise there are such things as search and replace however for other reasons, doing that would be problematic).
Any ideas?
|
You can overload a function in a derived class. So what you have specified above should work. Just wrote a quick test and it worked.
```
public class DerivedOverload {
/**
* @param args
*/
public static void main(String[] args) {
A classA = new A();
B classB = new B();
System.out.println("DerivedOverload.main() classA.displayAlteredValue(2) : " + classA.displayAlteredValue(2));
System.out.println("DerivedOverload.main() classA.displayAlteredValue(2) : " + classB.displayAlteredValue(2,2));
}
}
class A
{
int val = 2;
A(){
}
public int displayAlteredValue(int inp)
{
return (val*inp);
}
}
class B extends A
{
B(){
}
public int displayAlteredValue(int inp1, int inp2)
{
return (val*inp1*inp2);
}
}
```
System out.
DerivedOverload.main() classA.displayAlteredValue(2) : 4
DerivedOverload.main() classA.displayAlteredValue(2) : 8
|
285,251 |
<p>I maintain the build system at my company, which is currently using CVS. This build system is used across multiple projects and multiple CVS repositories.</p>
<p>Whenever we have a release milestone, we create a tag. In CVS, this is easy:</p>
<pre><code>$ cvs tag TAG_NAME
</code></pre>
<p>That command works regardless of the CVS module or repository, as long as it is executed in a CVS working directory.</p>
<p>In order to do the same thing in subversion though, it looks like I will first have to parse the output of <code>svn info</code> to get the repository root. Then I can create the tag with:</p>
<pre><code>svn cp . $REPO_ROOT/tags/TAG_NAME -m"Created tag TAG_NAME"
</code></pre>
<p>This of course assumes that the svn repository has the recommended "trunk, tags, branches" directory structure. So to be safe I'll probably need to verify this first.</p>
<p>That seems like a lot of work just to map a revision number to a symbolic name. Is there a better way?</p>
|
[
{
"answer_id": 285331,
"author": "Davide",
"author_id": 25891,
"author_profile": "https://Stackoverflow.com/users/25891",
"pm_score": 2,
"selected": false,
"text": "<p>Unlike CVS, tags are more than just a symbolic name in subversions, that's the point. We you create a tag, you are actually creating a branch. I recommend to read this, if you haven't already: <a href=\"http://svnbook.red-bean.com/\" rel=\"nofollow noreferrer\">http://svnbook.red-bean.com/</a></p>\n"
},
{
"answer_id": 285411,
"author": "bendin",
"author_id": 33412,
"author_profile": "https://Stackoverflow.com/users/33412",
"pm_score": 3,
"selected": false,
"text": "<p>I use svn from the command line almost exclusively and0t I quickly tired of typing in monster URLs. I finally wrote a script <code>svnurl</code>, which I use from the shell. It operates on the assumption that an \"project\" hast the form:</p>\n\n<pre><code>.../PROJECTNAME/trunk\n tags\n branches\n</code></pre>\n\n<p>Let's assume you are somewhere in a working copy of PROJECTNAME/branches/foo:</p>\n\n<pre><code>svnurl -tl # gives a list of tags for the current project \nsvnurl -tlu # the same as full urls\nsvnurl -t 1.1 # the url for the tag 1.1 of the current project\n# analagous functions for branches\nsvnurl -ru # the url of the \"root\" of the current working copy\n # eg svn://.../PROJECTNAME/branches/foo\nsvnurl -T # the url of the trunk of the current project\nsvnurl -pn # the name of the current project, `PROJECTNAME`\n# ...\n</code></pre>\n\n<p>Usage looks something like this:</p>\n\n<pre><code>$ svn cp $(svnurl -T) $(svnurl -t 1.1.1) # tag trunk as 1.1.1\n</code></pre>\n\n<p>The code isn't beautiful, but it has saved me many keystrokes and been useful in ways I hadn't expected. I'd be willing to share it if you are interested.</p>\n"
},
{
"answer_id": 285627,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 3,
"selected": false,
"text": "<p>You're missing a core principle of Subversion: the revision number <em>is</em> the tag. When you \"tag\" it with svn cp, you're just making a copy of that particular revision with a longer name. And unlike a CVS tag, you (or other developers) could continue doing ongoing development on that \"tag\". It isn't a static entity like a CVS tag is (well, to be fair, you can move a tag on individual CVS files which effectively \"changes\" it).</p>\n\n<p>Most svn users treat tags the way CVS presented them. And (under Apache, at least) you can configure the DAV server to not permit writes/check-ins under any tag directory. I haven't tried this, and it might prevent you using http URLs for creating the tags (you'd have to use file paths from a shell on the hosting machine). But for all practical purposes, your release process should be more interested in the specific revision number, than in some arbitrary text-string. The latter can be altered after the release; the former should[*] always give you access to the exact same set of files every time you check it out.</p>\n\n<p>[*] There's always a way to fiddle around with files behind the scenes, after the fact... I used to hand-edit RCS and CVS files with vi when I needed to fix a comment, etc. But without some serious svn-cleverness, a given revision number should be pretty constant.</p>\n"
},
{
"answer_id": 344722,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 4,
"selected": true,
"text": "<p>Here is how I implemented this, in case anyone is curious:</p>\n\n<pre><code><!-- First, we need to get the svn repository root URL by parsing\nthe output of 'svn info'. -->\n<exec executable=\"svn\" failonerror=\"yes\">\n <arg line=\"info\"/>\n\n <redirector outputproperty=\"svninfo.out\" errorproperty=\"svninfo.err\">\n <outputfilterchain>\n <linecontains>\n <contains value=\"Repository Root: \"/>\n </linecontains>\n\n <tokenfilter>\n <replacestring from=\"Repository Root: \" to=\"\"/>\n </tokenfilter>\n </outputfilterchain>\n </redirector>\n</exec>\n\n<echo level=\"verbose\" message=\"Root from svn info: ${svninfo.out}\"/>\n\n<!-- Set the svn.root property from the svn info output, and append\nthe module prefix if it exists. The module prefix allows multiple\nprojects to use the same repository root. -->\n<condition property=\"svn.root\" value=\"${svninfo.out}/${svn.module.prefix}\">\n <isset property=\"svn.module.prefix\"/>\n</condition>\n<!-- Note that the next line will have no effect if the property was\nset in the condition above, since ant properties are immutable. The\neffect is an \"else\", if the condition above is NOT true. -->\n<property name=\"svn.root\" value=\"${svninfo.out}\"/>\n<echo level=\"verbose\" message=\"Root: ${svn.root}\"/>\n\n<!-- Verify the tags directory exists. -->\n<exec executable=\"svn\"\n failonerror=\"no\"\n outputproperty=\"null\"\n errorproperty=\"svn.ls.error\">\n <arg line=\"ls ${svn.root}/tags\"/>\n</exec>\n<fail>\nCannot find 'tags' subdirectory.\n\n${svn.ls.error}\n\nThe subversion repository is expected to have 'trunk', 'branches', and 'tags'\nsubdirectories. The tag '${tag}' will need to be manually created.\n <condition>\n <not>\n <equals arg1=\"${svn.ls.error}\" arg2=\"\" trim=\"yes\"/>\n </not>\n </condition>\n</fail>\n\n<!-- Finally, do the actual tag (copy in subversion). -->\n<exec executable=\"svn\" failonerror=\"yes\">\n <arg line=\"cp . ${svn.root}/tags/${tag} -m 'Created tag ${tag}'\"/>\n</exec>\n</code></pre>\n\n<p>I also want to point out that I am aware of the differences between CVS and subversion with respect to tagging, and that the subversion revision is, for all practical purposes, equivalent to the tag. Unfortunately, that is not really relevant; my users want a symbolic name composed of the module name and a (different) version number.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737/"
] |
I maintain the build system at my company, which is currently using CVS. This build system is used across multiple projects and multiple CVS repositories.
Whenever we have a release milestone, we create a tag. In CVS, this is easy:
```
$ cvs tag TAG_NAME
```
That command works regardless of the CVS module or repository, as long as it is executed in a CVS working directory.
In order to do the same thing in subversion though, it looks like I will first have to parse the output of `svn info` to get the repository root. Then I can create the tag with:
```
svn cp . $REPO_ROOT/tags/TAG_NAME -m"Created tag TAG_NAME"
```
This of course assumes that the svn repository has the recommended "trunk, tags, branches" directory structure. So to be safe I'll probably need to verify this first.
That seems like a lot of work just to map a revision number to a symbolic name. Is there a better way?
|
Here is how I implemented this, in case anyone is curious:
```
<!-- First, we need to get the svn repository root URL by parsing
the output of 'svn info'. -->
<exec executable="svn" failonerror="yes">
<arg line="info"/>
<redirector outputproperty="svninfo.out" errorproperty="svninfo.err">
<outputfilterchain>
<linecontains>
<contains value="Repository Root: "/>
</linecontains>
<tokenfilter>
<replacestring from="Repository Root: " to=""/>
</tokenfilter>
</outputfilterchain>
</redirector>
</exec>
<echo level="verbose" message="Root from svn info: ${svninfo.out}"/>
<!-- Set the svn.root property from the svn info output, and append
the module prefix if it exists. The module prefix allows multiple
projects to use the same repository root. -->
<condition property="svn.root" value="${svninfo.out}/${svn.module.prefix}">
<isset property="svn.module.prefix"/>
</condition>
<!-- Note that the next line will have no effect if the property was
set in the condition above, since ant properties are immutable. The
effect is an "else", if the condition above is NOT true. -->
<property name="svn.root" value="${svninfo.out}"/>
<echo level="verbose" message="Root: ${svn.root}"/>
<!-- Verify the tags directory exists. -->
<exec executable="svn"
failonerror="no"
outputproperty="null"
errorproperty="svn.ls.error">
<arg line="ls ${svn.root}/tags"/>
</exec>
<fail>
Cannot find 'tags' subdirectory.
${svn.ls.error}
The subversion repository is expected to have 'trunk', 'branches', and 'tags'
subdirectories. The tag '${tag}' will need to be manually created.
<condition>
<not>
<equals arg1="${svn.ls.error}" arg2="" trim="yes"/>
</not>
</condition>
</fail>
<!-- Finally, do the actual tag (copy in subversion). -->
<exec executable="svn" failonerror="yes">
<arg line="cp . ${svn.root}/tags/${tag} -m 'Created tag ${tag}'"/>
</exec>
```
I also want to point out that I am aware of the differences between CVS and subversion with respect to tagging, and that the subversion revision is, for all practical purposes, equivalent to the tag. Unfortunately, that is not really relevant; my users want a symbolic name composed of the module name and a (different) version number.
|
285,276 |
<p>SAP HR apparently has several models for describing the relationship between Position (S), Job (C), Organization (O) and Person (P) objects that the Organizational Management (OM) module is used to maintain.</p>
<p>P (Person) objects are usually Holders of Positions (S).</p>
<p>There is the S-S relationship model, which I am told is called Supervisory model. That is each Position reports to another position, and one of the positions is considered a manager.</p>
<p>There is another model whose name I am trying to locate, where the structure of Organizational reporting is between O objects first, in a tree structure. At each node, the S objects belong to the O object, with one of them flagged as the Manager. </p>
<p>No doubt there are other models, and if you know what they are called, and how they work, that would be very useful! </p>
<p>My perspective on this question is while trying to implement a Novell Identity Manager driver from SAP HR into an eDirectory identity vault, from there to provision users into Active Directory and Lotus Notes.</p>
<p>One of the key drivers for the project is the manager and directReports structure, so that Managers can all be identified, and the reporting structure visualized. Thus the importance of the SAP HR relationship modelling.</p>
|
[
{
"answer_id": 397516,
"author": "PATRY Guillaume",
"author_id": 49804,
"author_profile": "https://Stackoverflow.com/users/49804",
"pm_score": 4,
"selected": true,
"text": "<p>There is no fixed model of organisation, as you can create your own objects and/or relations between objects. OM is a module by itself, so informations given here will be just a really short introduction.</p>\n\n<p>The most simple org model is a O-O-S-P :</p>\n\n<ul>\n<li>the O-O relation (A/B 002) is a hierarchical one for strutural unit</li>\n<li>the O-S relation is either\n\n<ul>\n<li>A/B 003 (belongs to), for standard position</li>\n<li>A/B 012 (manage) for the unit manager's position\n(who can also have a B003 to the unit or another unit)</li>\n</ul></li>\n<li>the S-P relation is (A/B 008) is the holder(<strong>s</strong>) of the position</li>\n</ul>\n\n<p>These relations are the standard ones, and have been used by all clients I've worked for/with. However, depending on the needs, other objects (F : function, T : task) can be used, with other relations. As already said, it is event possible to create new object type or new relations. The only way i know to get a quick look at the relations used for an organisation is to check the tables :</p>\n\n<p>Objects are present in the HRP1000 table (basic informations on objects). The objects Id linked to a given person can easily be found in the infotype 0001 (transaction pa20) : id of object O is PA0001-ORGEH, S is PA0001-PLANS, F is PA0001-STELL. Of course P is PA0001-PERNR (employee Id).</p>\n\n<p>Relations between objects are in the HRP1001 table. To search for a given relations you need to give the (relation) source Id and type, as well as the destination type and id.\nfor example, to get all position managing a unit (ie all manager position) you may do</p>\n\n<pre><code>SELECT * from HRP1001 where OTYPE = 'S' \n AND RELAT = '012' \n and RSIGN = 'A' \n and begda <= sy-datum \n and endda >= sy-datum \n and sclass = 'O'.\n...\n</code></pre>\n\n<p>fields OBJID and SOBID will then contains ther id of positions and units.</p>\n\n<p>transaction <strong>ooaw</strong> allows the management of evaluation-path, that is a set of relations to be followed recursively to get a set of objects. you can use them with the function \n<code>'RH_STRUC_GET'</code>(field wegid is the evaluation-path). This may be easier than using a set of select. Thus if you want to get all the units and person under a given unit, you could use the \"O_S_P\" evaluation-path with a depth of 0 (ie, all the way down), or \"ORGCHART\" if you also wants the functionw (description) of the positions. </p>\n\n<p>Hope this help you.\nRegards</p>\n"
},
{
"answer_id": 590982,
"author": "Cantillon",
"author_id": 71366,
"author_profile": "https://Stackoverflow.com/users/71366",
"pm_score": 2,
"selected": false,
"text": "<p>The relationships used in the HRP1001 table (HRP1001-RELAT) are stored in table T778V. Their texts are stored in table T777V.</p>\n\n<pre>RELAT RTEXT RINVT\n 001 Is a subdivision of Is subdivided into\n 002 Reports (line) to Is line supervisor of\n 003 Belongs to Incorporates\n</pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32247/"
] |
SAP HR apparently has several models for describing the relationship between Position (S), Job (C), Organization (O) and Person (P) objects that the Organizational Management (OM) module is used to maintain.
P (Person) objects are usually Holders of Positions (S).
There is the S-S relationship model, which I am told is called Supervisory model. That is each Position reports to another position, and one of the positions is considered a manager.
There is another model whose name I am trying to locate, where the structure of Organizational reporting is between O objects first, in a tree structure. At each node, the S objects belong to the O object, with one of them flagged as the Manager.
No doubt there are other models, and if you know what they are called, and how they work, that would be very useful!
My perspective on this question is while trying to implement a Novell Identity Manager driver from SAP HR into an eDirectory identity vault, from there to provision users into Active Directory and Lotus Notes.
One of the key drivers for the project is the manager and directReports structure, so that Managers can all be identified, and the reporting structure visualized. Thus the importance of the SAP HR relationship modelling.
|
There is no fixed model of organisation, as you can create your own objects and/or relations between objects. OM is a module by itself, so informations given here will be just a really short introduction.
The most simple org model is a O-O-S-P :
* the O-O relation (A/B 002) is a hierarchical one for strutural unit
* the O-S relation is either
+ A/B 003 (belongs to), for standard position
+ A/B 012 (manage) for the unit manager's position
(who can also have a B003 to the unit or another unit)
* the S-P relation is (A/B 008) is the holder(**s**) of the position
These relations are the standard ones, and have been used by all clients I've worked for/with. However, depending on the needs, other objects (F : function, T : task) can be used, with other relations. As already said, it is event possible to create new object type or new relations. The only way i know to get a quick look at the relations used for an organisation is to check the tables :
Objects are present in the HRP1000 table (basic informations on objects). The objects Id linked to a given person can easily be found in the infotype 0001 (transaction pa20) : id of object O is PA0001-ORGEH, S is PA0001-PLANS, F is PA0001-STELL. Of course P is PA0001-PERNR (employee Id).
Relations between objects are in the HRP1001 table. To search for a given relations you need to give the (relation) source Id and type, as well as the destination type and id.
for example, to get all position managing a unit (ie all manager position) you may do
```
SELECT * from HRP1001 where OTYPE = 'S'
AND RELAT = '012'
and RSIGN = 'A'
and begda <= sy-datum
and endda >= sy-datum
and sclass = 'O'.
...
```
fields OBJID and SOBID will then contains ther id of positions and units.
transaction **ooaw** allows the management of evaluation-path, that is a set of relations to be followed recursively to get a set of objects. you can use them with the function
`'RH_STRUC_GET'`(field wegid is the evaluation-path). This may be easier than using a set of select. Thus if you want to get all the units and person under a given unit, you could use the "O\_S\_P" evaluation-path with a depth of 0 (ie, all the way down), or "ORGCHART" if you also wants the functionw (description) of the positions.
Hope this help you.
Regards
|
285,286 |
<p>I have a number of string arrays. The string in every array are ordered the same way, according the same criteria. However, some string may be missing from some arrays, and there may be no array that has a complete set of strings. Moreover, the criteria used to compare the strings is not available to me: outside of the context of the array, I cannot tell which string should precede another.</p>
<p>I need a way to produce a complete set of strings, properly ordered. Or fail when the arrays do not have enough information for me to do so.</p>
<p>Is anyone familiar with this kind of problem? What is the proper algorithm?</p>
<p>Examples:</p>
<pre><code>A B D
A C D
</code></pre>
<p>Can't order correctly, can't decide the order of B and C </p>
<pre><code>A B D
A B C
A C D
</code></pre>
<p>This has enough information to order ABCD correctly.</p>
|
[
{
"answer_id": 285357,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 0,
"selected": false,
"text": "<p>How many sets will you have? Something that might work if they aren't too sparse is:</p>\n\n<ol>\n<li>Iterate over the first element of\nall arrays counting how common each\nstring is. </li>\n<li>Whichever element is the most common\nis selected.</li>\n<li>Check each element of all\narrays for said string. </li>\n<li>If it exists in any element other than the first of an array, the first element of\nits parent array is selected and goto step 3. </li>\n<li>Remove the selected element from the\nfirst element of all arrays/trees\nand add it to the end of your output\nlist.</li>\n<li>Goto 1 until all elements are\nremoved.</li>\n</ol>\n\n<p>If you dumped the arrays into <a href=\"http://en.wikipedia.org/wiki/B-tree\" rel=\"nofollow noreferrer\">b-trees</a> the element search could be pretty fast. You may also be able to further speed up step 3 by playing with the order of the arrays. I'm still thinking about that.</p>\n\n<p>If the arrays are very sparse the only thing I can think of is to use some kind of supervised machine learning to try to determine the proper method for ordering. </p>\n"
},
{
"answer_id": 285393,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 0,
"selected": false,
"text": "<p>How does this differ from a classic <a href=\"http://en.wikipedia.org/wiki/Diff\" rel=\"nofollow noreferrer\">diff/merge algorithm</a>? As long as both arrays are \"sorted\", regardless of the mechanism that they are sorted. They are sorted compared to each other, so you should be able to use the similarities to merge the differences. After that, it's basically arbitrary.</p>\n\n<p>If you want to merge [A] with [B, C, D], then you don't have any idea where A will go (front? end? Between C and D? You don't know). In those cases you'll just have to come up with a convention (always in front, always at end, something like that).</p>\n\n<p>If you want to merge [Q, X, Y, A, B] with [Q, X, W, B, D], You'll need to decide if the \"W\" comes in front of or behind the \"Y, A\". So, is [Q, X, Y, A, W, B, D] correct or is [Q, X, W, Y, A, B, D] correct. That you'll just have to make a call on and roll with it, frankly. Simply not enough information.</p>\n"
},
{
"answer_id": 285414,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": -1,
"selected": false,
"text": "<p>Partial solution:</p>\n\n<p>You need to determine an ordering. You could do that by asking you data to \"vote\" on how many times one symbol is preceding another. You will need a square matrix with the size equal to the number of symbols. Initialize it to all zeros, then scan all your input strings, adding 1 to M(a,b) for each successive pair (a,b). Then, you need to clean out this data, so you get an ordering that is transitive (if A comes before B and be comes before C, A must also come before C). For this, you need to iterate through all triplets of distinct symbols, and \"harmonize\" the respective triplets of inequalities, so they respect the transitivity.</p>\n\n<p>If your data is not too noisy, this should take only one pass. If the data is too noisy, you might need to run multiple passes until convergence, or to employ some greedy approach: instead of iterating over all symbols in a random order, iterate over all triplets of inequalities in the order of the decreasing number of votes.</p>\n"
},
{
"answer_id": 285447,
"author": "FallenAvatar",
"author_id": 36965,
"author_profile": "https://Stackoverflow.com/users/36965",
"pm_score": 3,
"selected": false,
"text": "<p>One possible way I can think of, though probably not the most efficient:</p>\n\n<p>Im going to use your example to explain:</p>\n\n<pre><code>A B D\nA B C\nA C D\n</code></pre>\n\n<p>create a an array of the unique characters, so you would get (for example):</p>\n\n<pre><code>A B D C\n</code></pre>\n\n<p>Also you should probably have a enum to describe the possible relationships</p>\n\n<pre><code>enum Type\n{\n Unknown = 0,\n Greater = 1,\n Equal = 2,\n Less = 3,\n}\n</code></pre>\n\n<p>now, create a square matrix whose dimensions are the same as the above array, default everything to Type.Unknown.</p>\n\n<pre><code>0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\n</code></pre>\n\n<p>Your array will serve as an index into the matrix when you are figuring out the ordering. To see what i mean, look here:</p>\n\n<pre><code> A B D C\nA 0 0 0 0\nB 0 0 0 0\nD 0 0 0 0\nC 0 0 0 0\n</code></pre>\n\n<p>Go through and make the diagonal as Type.Equal</p>\n\n<pre><code>2 0 0 0\n0 2 0 0\n0 0 2 0\n0 0 0 2\n</code></pre>\n\n<p>Now you need to populate the matrix, loop through each input array and get each character and the one after it. Use these 2 characters, find the index in the matrix for each (using your array) and update the matrix.</p>\n\n<pre><code>for(int i=0; i<len(arr)-1; i++)\n{\n char c1 = arr[i], c2 = arr[i+1];\n int i1,i2;\n //get indices of characters in array and put in i1, and i2 respectively\n matrix[i1][i2] = Type.Less;\n matrix[i2][i1] = Type.Greater\n}\n</code></pre>\n\n<p>you assign 2 locations in the grid everytime, because when one char is less than another, it also means the second char is greater than the first.</p>\n\n<p>Now you would simply insert the chars into an array one at a time (Linked List would be the easiest, you will see why in a second)</p>\n\n<p>Each time you insert a char, you would start at the begining of your return array, and iterate through, looking up the indexes in the first array, and checking the matrix for a Type.Greater or a Type.Less (Depends on which way you are comparing, curr char to array, or array to current char) and insert it if you encounter a value different than what you expected.</p>\n\n<p>If you hit a Type.Unknown in the matix during your insertion, you know you don't have enough info to sort these arrays, if you hit a Type.Equal, you can ignore inserting this char (assuming you don't want duplicates in your result.)</p>\n\n<p>And then you would output your return array</p>\n"
},
{
"answer_id": 285460,
"author": "Jay Kominek",
"author_id": 32878,
"author_profile": "https://Stackoverflow.com/users/32878",
"pm_score": 0,
"selected": false,
"text": "<p>The main issue is that, given some data, you need to determine the ordering function. After that it is just list sort.</p>\n\n<p>Produce a list of the first elements of all of your arrays. Remove duplicates. So this:</p>\n\n<pre><code>A B\nA C\nB C\nC C\nC D\n</code></pre>\n\n<p>becomes (A, B, C). We then want a set of pairs that represents every value we know to be less than something else. ((A,B),(A,C),(B,C)) for this example.</p>\n\n<p>Now, for each value we can find at the beginning of an array, take all the arrays that begin with that value as a group. Remove their first elements. That gets us:</p>\n\n<pre><code>B\nC\n</code></pre>\n\n<p>,</p>\n\n<pre><code>C\n</code></pre>\n\n<p>and</p>\n\n<pre><code>C\nD\n</code></pre>\n\n<p>Recurse on each of these lists of arrays.</p>\n\n<p>Once we've finished recursing on all our subsets, we merge the pairs that are produced into what we came up with initially. We should end up with ((A,B),(A,C),(B,C),(C,D)). Depending on the properties of your values, you could expand this out into ((A,B), (A,C), (A,D), (B,C), (B,D), (C,D)).</p>\n\n<p>Your less than function now just looks to see if the values it is to compare are in this set. If so, true. Otherwise, false.</p>\n"
},
{
"answer_id": 285462,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 3,
"selected": true,
"text": "<p>This sounds like a special case of the <a href=\"http://en.wikipedia.org/wiki/Topological_sort\" rel=\"nofollow noreferrer\">topological sorting</a> problem.</p>\n"
},
{
"answer_id": 285499,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "<p>1) tsort the data. If the partial orderings are inconsistent, then there will be a loop and the tsort will fail. Otherwise you have a sequence s(0) ... s(n-1).</p>\n\n<p>2) For each pair s(i), s(i+1), search in the partial sequences for the same pair appearing adjacent to one another. If you find it in one of them, then keep going for the next i. If you don't find it, then fail, because the partial sequences don't order s(i) and s(i+1).</p>\n\n<p>Why not? Because if they did order them, but they don't appear next to each other, then there must be something \"in between them\". But if there's something in between them in the partial sequences but not in the full sequence you got out of the tsort, then that interloper must in the full sequence be either before s(i), or after s(i+1). That contradicts the consistency of the full sequence with the partial sequences, which tsort already proved. </p>\n\n<p>Step 2 is O(n*m), where n is the number of elements to order, and m is the total length of all the partial sequences. You might be able to do better, but this is pretty simple because you can grab a tsort off the shelf for step 1, and step 2 is an obvious bunch of nested loops. Note that you can stop searching each partial sequence if you find s(i) (or s(i+1) for that matter), because it sure can't occur again.</p>\n"
},
{
"answer_id": 285518,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 0,
"selected": false,
"text": "<p>Doug McClean wins. The phrase that leapt into my mind was stratification, and this led to dead ends in a web search. (For example, in logic programming, it is useful to speak of stratified programs; these are programs which you can visualize as a stack of layers, each layer containing one or more predicates, and each predicate being extensional (the bottom layer) or following only from predicates in layers beneath it. You ideally want a form of this where every layer has one string at most.)</p>\n\n<p>Your variation of the toposort algorithm would have you build a DAG (you imply that acyclicity is guaranteed), perhaps tracking nodes with zero incoming edges as you go (an easy optimization). If, when done, you have more than one \"root\" node, you're done, as you know you have no first node. Otherwise, you have exactly one; remove it from the DAG, checking whether each of its child nodes is now a \"root\" node; and keep going until you get more than one root node (failure) or you run out of nodes (success).</p>\n\n<p>The algorithm I sketched above should be linear in the number of strings (basically, two iterations through them). It's arguably proportional to the square of the number of strings, if each node has many children, implying that each string appears many, many times in your list of lists, each with a different string immediately following it.</p>\n"
},
{
"answer_id": 285652,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I am tempted to say that in order to have enough information to complete the merge, every pair of x,y that ends up next to each other in the final merged array has to be present somewhere in the input arrays. In other words, transitivity may not come into the picture at all. Can someone produce a counterexample?</p>\n\n<p>You can do it right here in the answer if you so prefer.</p>\n"
},
{
"answer_id": 285814,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>How about a simple recursive routine?</p>\n\n<p>Using your second example:</p>\n\n<pre><code>A B D\nA B C\nA C D\n</code></pre>\n\n<p>Create a hash table of all the unique orderings:</p>\n\n<pre><code>table = {A -> B, C\n B -> C, D\n C -> D}\n</code></pre>\n\n<p>Count up all of the unique values</p>\n\n<pre><code>countUnique = 4\n</code></pre>\n\n<p>Using a stack, calculate all the possible paths. You know you've got a solution when the stack length matches the number of unique strings. If you find more than one solution, then you have a circular reference somewhere. <em>Please excuse my questionable pseudocode.</em></p>\n\n<pre><code>main()\n{\n foreach (s in table.keys)\n {\n stack.push(s)\n searchForPath()\n stack.pop()\n }\n}\n\nsearchForPath()\n{\n if (table.hasKey(stack.peek))\n {\n // we're not at the end yet\n foreach (s in table[stack.peek])\n {\n // avoid infinite recursion\n if (stack.contains(s)\n continue\n\n stack.push(s)\n searchForPath()\n stack.pop()\n }\n }\n else\n {\n if (stack.size == countUnique)\n {\n // solution found\n captureSolution()\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a number of string arrays. The string in every array are ordered the same way, according the same criteria. However, some string may be missing from some arrays, and there may be no array that has a complete set of strings. Moreover, the criteria used to compare the strings is not available to me: outside of the context of the array, I cannot tell which string should precede another.
I need a way to produce a complete set of strings, properly ordered. Or fail when the arrays do not have enough information for me to do so.
Is anyone familiar with this kind of problem? What is the proper algorithm?
Examples:
```
A B D
A C D
```
Can't order correctly, can't decide the order of B and C
```
A B D
A B C
A C D
```
This has enough information to order ABCD correctly.
|
This sounds like a special case of the [topological sorting](http://en.wikipedia.org/wiki/Topological_sort) problem.
|
285,290 |
<p>I'm having trouble sending out a simple HTTP request using Actionscript 3's Socket() object. My onConnect listener is below:</p>
<pre><code>function sConnect(e:Event):void {
trace('connected');
s.writeUTFBytes('GET /outernet/client/rss/reddit-feeds HTTP/1.1\r\n');
s.writeUTFBytes('Host: 208.43.71.50:8080\r\n');
s.writeUTFBytes('Connection: Keep-alive\r\n');
s.flush();
}
</code></pre>
<p>Using a packet sniffer, I can see the request does indeed get sent to the server, but the packet sniffer doesn't identify the protocol as HTTP like it does with other HTTP services. When I run this, the server just eventually disconnects me. I have tried to connect to other simple Apache Servers and just get a malformed request error.</p>
<p>What am I missing here?</p>
|
[
{
"answer_id": 285296,
"author": "Brian",
"author_id": 16457,
"author_profile": "https://Stackoverflow.com/users/16457",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using UTF, try with ANSI/ASCII. The encoding may be the cause of the issue.</p>\n"
},
{
"answer_id": 285347,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 5,
"selected": true,
"text": "<p>You have to write another \"\\r\\n\" to the stream before the flush to tell the HTTP server that you're finished sending the headers.</p>\n"
},
{
"answer_id": 285350,
"author": "Mike Keen",
"author_id": 14182,
"author_profile": "https://Stackoverflow.com/users/14182",
"pm_score": 1,
"selected": false,
"text": "<p>Turns out I wasn't sending a blank line to the HTTP server after my request. The following minor tweak from the original works:</p>\n\n<pre><code>function sConnect(e:Event):void {\n trace('connected');\n s.writeUTFBytes('GET /outernet/client/rss/reddit-feeds HTTP/1.1\\r\\n');\n s.writeUTFBytes('Host: 208.43.71.50:8080\\r\\n');\n s.writeUTFBytes('Connection: Keep-alive\\r\\n\\r\\n');\n s.flush();\n}\n</code></pre>\n\n<p>Note the extra \\r\\n after the last writeUTFBytes. Thanks anyway Brian.</p>\n\n<p>Edit: Thanks Graeme.</p>\n"
},
{
"answer_id": 411346,
"author": "Mitch Haile",
"author_id": 28807,
"author_profile": "https://Stackoverflow.com/users/28807",
"pm_score": 0,
"selected": false,
"text": "<p>I just wasted a lot of time tracking down what is apparently a serious bug in some combinations of Flash 10 and Linux with writeMultiByte(). I would be very dubious about using writeMultiByte().</p>\n\n<p>I hope this helps you.</p>\n"
},
{
"answer_id": 3177873,
"author": "aleks_raiden",
"author_id": 383466,
"author_profile": "https://Stackoverflow.com/users/383466",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe wrong, 'ascii' encoding not supported (see <a href=\"http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/charset-codes.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/charset-codes.html</a>) - use 'us-ascii'</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14182/"
] |
I'm having trouble sending out a simple HTTP request using Actionscript 3's Socket() object. My onConnect listener is below:
```
function sConnect(e:Event):void {
trace('connected');
s.writeUTFBytes('GET /outernet/client/rss/reddit-feeds HTTP/1.1\r\n');
s.writeUTFBytes('Host: 208.43.71.50:8080\r\n');
s.writeUTFBytes('Connection: Keep-alive\r\n');
s.flush();
}
```
Using a packet sniffer, I can see the request does indeed get sent to the server, but the packet sniffer doesn't identify the protocol as HTTP like it does with other HTTP services. When I run this, the server just eventually disconnects me. I have tried to connect to other simple Apache Servers and just get a malformed request error.
What am I missing here?
|
You have to write another "\r\n" to the stream before the flush to tell the HTTP server that you're finished sending the headers.
|
285,292 |
<p>I have just started to look at .NET 3.5 so please forgive me if this type of question have been asked before. I am struggling with a decent usage for extension methods, in that I have just downloaded suteki shop an MVC ecommerce offering. In this project there is a pretty standard Repository pattern that extends IRepository. </p>
<p>In order to extend the basic functionality exposed by this interface, extention methods are used i.e.:</p>
<pre><code>public static class CategoryRepositoryExtensions
{
public static Category GetRootCategory(this IRepository<Category> categoryRepository)
{
return categoryRepository.GetById(1);
}
}
</code></pre>
<p>Now this is all well and good, but Interfaces, as far as I am concerned act as contracts to the objects that implement them. </p>
<p>The fact that the repository has been interfaced out suggests an attempt at a data layer agnostic approach. That said, if I were to create my own data layer I would be confused as to what extension methods I would have to create to ensure I have fulfilled the contractual requirement I have to the classes that implement my repository classes.</p>
<p>It seems that the older way of creating an IRepository and then extending that allows a much better visibility of what is required e.g.</p>
<pre><code>ICategoryRepoitory : IRepository<Category>
{
Category GetRootCategory();
}
</code></pre>
<p>So I guess my question is does this use of Extention methods seem wrong to anyone else? If not, why? Should I not be moaning about this?</p>
<p>EDIT:</p>
<p>The above example does seem to be a good example of why extention methods can be very helpful. </p>
<p>I suppose my issue is if data access specific implementations were stuck in the extention method in the data access mechanisms assembly. </p>
<p>That way if I were to swap it out for another mechanism I would have to create a similar extention method in that assembly. </p>
|
[
{
"answer_id": 285368,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>The point is that if you've implemented all of <code>IRepository<T></code> appropriately, you (as the data layer implementor) don't have to know about root categories at all. For the scope of this extension method, it is assumed that any <em>repository</em> of categories will have a root category of ID 1. That may well be a perfectly reasonable assumption, and a useful one: no-one has to build a derived class (which may well be impractical - the data layer may have factories etc which make it tricky to derive from the implementations).</p>\n\n<p>Now, the extension method is only applicable if its scope is appropriate - if it's in a namespace (or closely related one) where that assumption about root categories will be valid.</p>\n\n<p>I don't think the \"older\" way would really be an interface extending <code>IRepository<Category></code> - it would be a normal static method taking <code>IRepository<Category></code>. That's where extension methods just make life more pleasant. If you really would have used inheritance instead, it may well be appropriate to do so now as well. Unfortunately we don't know enough about the architecture of your system to say that for sure.</p>\n"
},
{
"answer_id": 285375,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 1,
"selected": false,
"text": "<p>It's not the same thing. An extension method is a syntactic convenience, nothing more, and certainly not a contractual requirement. You don't \"implement\" them on your own classes. For your example above:</p>\n\n<pre><code>using CategoryRepositoryExtensions;\n...\nCategory c = r.GetRootCategory();\n</code></pre>\n\n<p>is <em>exactly</em> the same as:</p>\n\n<pre><code>Category c = CategoryRepositoryExtensions.GetRootCategory(r);\n</code></pre>\n\n<p>and therefore there is no additional requirement on the implementer of the interface.</p>\n"
},
{
"answer_id": 285450,
"author": "user35559",
"author_id": 35559,
"author_profile": "https://Stackoverflow.com/users/35559",
"pm_score": 0,
"selected": false,
"text": "<p>Yes in the example you mentioned it does seem counter-intuitive and the reason is because you are working with a single object at a single level. I find that extension methods are most useful when you are working with IQueryable / IEnumerable collections.</p>\n\n<p>For eg. lets consider 2 scenarios:</p>\n\n<ul>\n<li><p>Scenario 1: get list of all orders which contain product x</p></li>\n<li><p>Scenario 2: get list of all orders which contain product x and have been shipped to zipcode y</p></li>\n</ul>\n\n<p>If you were using the traditional/interface driven approach you might define 2 be tempted to define 2 different interfaces. If you use extension methods, you could use something like the following</p>\n\n<p>Scenario 1</p>\n\n<pre><code><IEnumerable> orders1Enumerable = OrderRepository.GetAllOrders()\n .ContainingProductCode(x);\n</code></pre>\n\n<p>Scenario 2</p>\n\n<pre><code><IEnumerable> orders2Enumerable = OrderRepository.GetAllOrders()\n .ContainingProductCode(x)\n .WithShippingZipCode(y);\n</code></pre>\n\n<p>When you do this, the framework creates the appropriate SQL on the fly by chaining these extension methods</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 1542268,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Extension methods concept is just syntactic sugar as some authors call it. It makes the code more readable though less understandable. Ultimately extension methods are just static ones which are the heritage of the procedural paradigm. They make the code tightly-coupled and less cohesive, harder to test and reuse.</p>\n\n<p>I am biased against this tendency of the C# programming language. This feature is attractive but it doesn't bring any benefits, quite the contrary it increases the complexity of the code.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425/"
] |
I have just started to look at .NET 3.5 so please forgive me if this type of question have been asked before. I am struggling with a decent usage for extension methods, in that I have just downloaded suteki shop an MVC ecommerce offering. In this project there is a pretty standard Repository pattern that extends IRepository.
In order to extend the basic functionality exposed by this interface, extention methods are used i.e.:
```
public static class CategoryRepositoryExtensions
{
public static Category GetRootCategory(this IRepository<Category> categoryRepository)
{
return categoryRepository.GetById(1);
}
}
```
Now this is all well and good, but Interfaces, as far as I am concerned act as contracts to the objects that implement them.
The fact that the repository has been interfaced out suggests an attempt at a data layer agnostic approach. That said, if I were to create my own data layer I would be confused as to what extension methods I would have to create to ensure I have fulfilled the contractual requirement I have to the classes that implement my repository classes.
It seems that the older way of creating an IRepository and then extending that allows a much better visibility of what is required e.g.
```
ICategoryRepoitory : IRepository<Category>
{
Category GetRootCategory();
}
```
So I guess my question is does this use of Extention methods seem wrong to anyone else? If not, why? Should I not be moaning about this?
EDIT:
The above example does seem to be a good example of why extention methods can be very helpful.
I suppose my issue is if data access specific implementations were stuck in the extention method in the data access mechanisms assembly.
That way if I were to swap it out for another mechanism I would have to create a similar extention method in that assembly.
|
The point is that if you've implemented all of `IRepository<T>` appropriately, you (as the data layer implementor) don't have to know about root categories at all. For the scope of this extension method, it is assumed that any *repository* of categories will have a root category of ID 1. That may well be a perfectly reasonable assumption, and a useful one: no-one has to build a derived class (which may well be impractical - the data layer may have factories etc which make it tricky to derive from the implementations).
Now, the extension method is only applicable if its scope is appropriate - if it's in a namespace (or closely related one) where that assumption about root categories will be valid.
I don't think the "older" way would really be an interface extending `IRepository<Category>` - it would be a normal static method taking `IRepository<Category>`. That's where extension methods just make life more pleasant. If you really would have used inheritance instead, it may well be appropriate to do so now as well. Unfortunately we don't know enough about the architecture of your system to say that for sure.
|
285,314 |
<p>I'm building a tool that automates a process then runs some tests on it's own results then goes to do some other stuff.</p>
<p>In trying to clean up my code I have created a separate file that just has the test cases class. Now before I can run these tests, I have to pass the class a couple of parameters/objects before they can be run. Now the problem is that I can't seem to find a way to pass a parameter/object to the test class.</p>
<p>Right now I am thinking to generate a Yaml file and read it in the test class but it feels "wrong" to use a temporary file for this. If anyone has a nicer solution that would be great!</p>
<p>**************Edit************</p>
<p>Example Code of what I am doing right now:</p>
<pre><code>#!/usr/bin/ruby
require 'test/unit/ui/console/testrunner'
require 'yaml'
require 'TS_SampleTestSuite'
automatingSomething()
importantInfo = getImportantInfo()
File.open('filename.yml', 'w') do |f|
f.puts importantInfo.to_yaml
end
Test::Unit::UI::Console::TestRunner.run(TS_SampleTestSuite)
</code></pre>
<p>Now in the example above TS_SampleTestSuite needs importantInfo, so the first "test case" is a method that just reads in the information from the Yaml file filname.yml. </p>
<p>I hope that clears up some confusion.</p>
|
[
{
"answer_id": 285336,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 0,
"selected": false,
"text": "<p>From what you say, it doesn't sound like an index is necessary. Rule of thumb is index fields that are being used in SELECTS a lot to speed up the searching, which in turn (can) slows down INSERTS and UPDATES.</p>\n\n<p>On a recordset as small as yours, I don't think you will see much of a real world hit either way. </p>\n"
},
{
"answer_id": 285337,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 1,
"selected": false,
"text": "<p>That's not very many records at all; I wouldn't bother making any indexes on that table. The relative uniqueness of the field is irrelevant - even on years-old commodity hardware I'd expect a query on that table to take a fraction of a second.</p>\n"
},
{
"answer_id": 285339,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 1,
"selected": false,
"text": "<p>you can use the general rule of thumb: optimize when it becomes a problem. Just don't use an index until you notice you need one.</p>\n"
},
{
"answer_id": 285342,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<p>I think the 'nearly unique' is probably a red herring. The data is either unique, or it's not, but that doesn't determine whether you would want to index it for performance reasons.</p>\n\n<h3>Answer:</h3>\n\n<p>5000 records is really not many at all, and regardless of whether you have an index, searches will still be fast. At that rate of inserts, it'll take you 3 years to get to 10000 records, which is still also not many.<br>\nI personally wouldn't bother with adding an index, but it wouldn't matter if you did.</p>\n\n<h3>Explanation:</h3>\n\n<p>What you have to think about when deciding to add an index is the trade-off between insertion speed, and selection speed.</p>\n\n<p>Without an index, doing a <code>select</code> on that field means MySQL has to walk over every single row and read every single field. Adding an index prevents this.</p>\n\n<p>The downside of the index is that each time data gets inserted, the DB has to update the index in addition to adding the data. This is usually a small overhead, but you'd really notice it if you had loads of indexes, and were doing a lot of writes. </p>\n\n<p>By the time you get this many rows in your database, you'd want an index anyway as otherwise your selects would take all day, but it's just something to be aware about so that you don't end up adding indexes on fields \"just in case I need it\"</p>\n"
},
{
"answer_id": 285344,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you'll only be doing searches on it twice a month and its that few rows then I would say don't index it. Its all but useless. </p>\n"
},
{
"answer_id": 285348,
"author": "Clayton",
"author_id": 22201,
"author_profile": "https://Stackoverflow.com/users/22201",
"pm_score": 0,
"selected": false,
"text": "<p>It's really a judgement call. With such a small table you can search reasonably quickly without an index, so you could get by without it.</p>\n\n<p>On the other hand, the cost of creating an index you don't really need is pretty low, so you're not saving yourself much by not doing it.</p>\n\n<p>Also, if you do create the index, you're covered for the future if you suddenly start getting 1000 new records/week. Possibly you know enough about the situation to say for certain that that will never happen, but requirements do have a way of changing when you least expect.</p>\n\n<p>EDIT: As far as changing requirements, the thing to consider is this: If the DB does grow and you find out later that you do need an index, can you simply create the index and be done? Or will you also need to change lots of code to make use of the new index?</p>\n"
},
{
"answer_id": 285349,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>No. There aren't many records and it's not going to be frequently queried. No need to index.</p>\n"
},
{
"answer_id": 287055,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 0,
"selected": false,
"text": "<p>It depends. As others have responded, there's a trade off between table update speed and selection speed. Table update includes inserts, updates, and deletes on the table.</p>\n\n<p>One question you didn't address. Does the table have a primary key, and a corresponding index? A table with no indexes usually benefits form having at least one index. The most common way of getting that index is to declare a primary key, and rely on the DBMS to generate an index accordingly.</p>\n\n<p>If a table has no candidates for primary key, that usually indicates a serious flaw in table design. That's a separate issue and should get a spearate discussion.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37080/"
] |
I'm building a tool that automates a process then runs some tests on it's own results then goes to do some other stuff.
In trying to clean up my code I have created a separate file that just has the test cases class. Now before I can run these tests, I have to pass the class a couple of parameters/objects before they can be run. Now the problem is that I can't seem to find a way to pass a parameter/object to the test class.
Right now I am thinking to generate a Yaml file and read it in the test class but it feels "wrong" to use a temporary file for this. If anyone has a nicer solution that would be great!
\*\*\*\*\*\*\*\*\*\*\*\*\*\*Edit\*\*\*\*\*\*\*\*\*\*\*\*
Example Code of what I am doing right now:
```
#!/usr/bin/ruby
require 'test/unit/ui/console/testrunner'
require 'yaml'
require 'TS_SampleTestSuite'
automatingSomething()
importantInfo = getImportantInfo()
File.open('filename.yml', 'w') do |f|
f.puts importantInfo.to_yaml
end
Test::Unit::UI::Console::TestRunner.run(TS_SampleTestSuite)
```
Now in the example above TS\_SampleTestSuite needs importantInfo, so the first "test case" is a method that just reads in the information from the Yaml file filname.yml.
I hope that clears up some confusion.
|
I think the 'nearly unique' is probably a red herring. The data is either unique, or it's not, but that doesn't determine whether you would want to index it for performance reasons.
### Answer:
5000 records is really not many at all, and regardless of whether you have an index, searches will still be fast. At that rate of inserts, it'll take you 3 years to get to 10000 records, which is still also not many.
I personally wouldn't bother with adding an index, but it wouldn't matter if you did.
### Explanation:
What you have to think about when deciding to add an index is the trade-off between insertion speed, and selection speed.
Without an index, doing a `select` on that field means MySQL has to walk over every single row and read every single field. Adding an index prevents this.
The downside of the index is that each time data gets inserted, the DB has to update the index in addition to adding the data. This is usually a small overhead, but you'd really notice it if you had loads of indexes, and were doing a lot of writes.
By the time you get this many rows in your database, you'd want an index anyway as otherwise your selects would take all day, but it's just something to be aware about so that you don't end up adding indexes on fields "just in case I need it"
|
285,320 |
<p>I need your advice with converting plain text to an URL.</p>
<p>The scenario will be this: The user will select some entry and then click a "convert to link" button. </p>
<p>The entry text the user selected will convert to <code>(link: selected_text)</code>. I do it with JavaScript. And after that, when he clicks the Save button to save all his entry, I don't know how to store <code>(link: selected_text)</code> in tha database.</p>
<p>The URL will be like this: <code>www.mysite.aspx?t=selected_text</code>. </p>
<p>I can convert <code>(link: selected_text)</code> by using replace function in code-behind. But then I don't know how to show user as clickable and also by not showing <code><a href="www.mysite.aspx?t=selected_text"></code></p>
<p>It can be difficult to understand therefore I will show some of my codes to explain.</p>
<pre><code>Private Sub Save(ByVal Entry As String) ' Entry Comes from entry textbox '
Dim elected As String
selected = Entry.Replace("(link: ", "<a href http://www.mysite.com?link=")
selected = Entry.Replace(")", ">")
' then here starts save but not necessary to show '
End Sub
</code></pre>
|
[
{
"answer_id": 285493,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>To store in database, you'll have to track the changes separately somehow and post them back to the server. I'd suggest a HiddenInput control.</p>\n"
},
{
"answer_id": 286452,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 0,
"selected": false,
"text": "<p>Do not save it as www.mysite.com?t=here. Just save the entry as the user types it. While showing it to user later, convert the \"(link: here)\" to link and show that.</p>\n"
},
{
"answer_id": 286456,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 1,
"selected": false,
"text": "<p>If you must save processed input for some reason</p>\n\n<pre><code>(link: here)\n</code></pre>\n\n<p>must be converted to</p>\n\n<pre><code>(link: <a href=\"http://www.mysite.com?t=here\">here</a>)\n</code></pre>\n"
},
{
"answer_id": 286458,
"author": "Mikael Söderström",
"author_id": 36944,
"author_profile": "https://Stackoverflow.com/users/36944",
"pm_score": 0,
"selected": false,
"text": "<p>Save the post as the user wrote it. This will make it easier to allow editing of the post later. When you render the message you should use a regular expression to replace it with a real link. You should never replace all \")\" with \">\". What happends if i write \"hello (world)\"?</p>\n\n<p>The result:\nHello (world></p>\n\n<p>You can find great regular expressions here:\n<a href=\"http://regexlib.com\" rel=\"nofollow noreferrer\">http://regexlib.com</a></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need your advice with converting plain text to an URL.
The scenario will be this: The user will select some entry and then click a "convert to link" button.
The entry text the user selected will convert to `(link: selected_text)`. I do it with JavaScript. And after that, when he clicks the Save button to save all his entry, I don't know how to store `(link: selected_text)` in tha database.
The URL will be like this: `www.mysite.aspx?t=selected_text`.
I can convert `(link: selected_text)` by using replace function in code-behind. But then I don't know how to show user as clickable and also by not showing `<a href="www.mysite.aspx?t=selected_text">`
It can be difficult to understand therefore I will show some of my codes to explain.
```
Private Sub Save(ByVal Entry As String) ' Entry Comes from entry textbox '
Dim elected As String
selected = Entry.Replace("(link: ", "<a href http://www.mysite.com?link=")
selected = Entry.Replace(")", ">")
' then here starts save but not necessary to show '
End Sub
```
|
If you must save processed input for some reason
```
(link: here)
```
must be converted to
```
(link: <a href="http://www.mysite.com?t=here">here</a>)
```
|
285,323 |
<p>I have an <code>ICollection<T></code> called <code>foos</code> in my class which I want to expose as read-only (see <a href="https://stackoverflow.com/questions/284090/how-to-get-a-readonlycollectiont-of-the-keys-in-a-dictionaryt-s">this question</a>). I see that the interface defines a property <code>.IsReadOnly</code>, which seems appropriate... My question is this: how do I make it obvious to the consumer of the class that <code>foos</code> is read-only? </p>
<p>I don't want to rely on them remembering to query <code>.IsReadOnly</code> before trying a not-implemented method such as <code>.Add()</code>. Ideally, I would like to expose <code>foos</code> as a <code>ReadOnlyCollection<T></code>, but it does not implement <code>IList<T></code>. Should I expose <code>foo</code> via a method called, for example, <code>GetReadOnlyFooCollection</code> rather than via a property? If so, would this not confuse someone who then expects a <code>ReadOnlyCollection<T></code>? </p>
<p>This is C# 2.0, so extension methods like <code>ToList()</code> are not available...</p>
|
[
{
"answer_id": 285360,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 4,
"selected": false,
"text": "<p>You can make \"foos\" a ReadOnlyCollection like this:</p>\n\n<pre><code>ReadOnlyCollection<T> readOnlyCollection = foos.ToList<T>().AsReadOnly();\n</code></pre>\n\n<p>Then you can expose it as a property of your class.</p>\n\n<p>EDIT:</p>\n\n<pre><code> class FooContainer\n {\n private ICollection<Foo> foos;\n public ReadOnlyCollection<Foo> ReadOnlyFoos { get { return foos.ToList<Foo>().AsReadOnly();} }\n\n }\n</code></pre>\n\n<p>Note: You should remember that once you get the ReadOnlyFoos collection is no longer \"synchronized\" with your foos ICollection. See the <a href=\"https://stackoverflow.com/questions/284090/how-to-get-a-readonlycollectiont-of-the-keys-in-a-dictionaryt-s\">thread you referenced</a>.</p>\n"
},
{
"answer_id": 285363,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "<p>My recommendation is to return use a ReadOnlyCollection<T> for the scenario directly. This makes the usage explicit to the calling user.</p>\n\n<p>Normally I would suggest using the appropriate interface. But given that the .NET Framework does not currently have a suitable IReadOnlyCollection, you must go with the ReadOnlyCollection type.</p>\n\n<p>Also you must be aware when using ReadOnlyCollection, because it is not actually read-only: <a href=\"http://blogs.msdn.com/jaredpar/archive/2008/04/22/api-design-readonlycollection-t.aspx\" rel=\"nofollow noreferrer\">Immutability and ReadOnlyCollection</a></p>\n"
},
{
"answer_id": 285389,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": -1,
"selected": false,
"text": "<p>Return a T[]:</p>\n\n<pre><code>private ICollection<T> items;\n\npublic T[] Items\n{\n get { return new List<T>(items).ToArray(); }\n}\n</code></pre>\n"
},
{
"answer_id": 538677,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes you may want to use an interface, perhaps because you want to mock the collection during unit testing. Please see my <a href=\"http://nicksdotnet.blogspot.com/2009/01/interfacing-readonlycollection.html\" rel=\"nofollow noreferrer\">blog entry</a> for adding your own interface to ReadonlyCollection by using an adapter.</p>\n"
},
{
"answer_id": 538731,
"author": "AwesomeTown",
"author_id": 59397,
"author_profile": "https://Stackoverflow.com/users/59397",
"pm_score": 0,
"selected": false,
"text": "<p>I typically return an <code>IEnumerable<T></code>.</p>\n\n<p>Once you make a collection readonly (so methods like <code>Add</code>, <code>Remove</code> and <code>Clear</code> no longer work) there's not much left that a collection supports that an enumerable doesn't - just <code>Count</code> and <code>Contains</code>, I believe.</p>\n\n<p>If consumers of your class really need to treat elements like they're in a collection, it's easy enough to pass an <code>IEnumerable</code> to <code>List<T></code>'s constructor.</p>\n"
},
{
"answer_id": 1204866,
"author": "Mank",
"author_id": 23217,
"author_profile": "https://Stackoverflow.com/users/23217",
"pm_score": 1,
"selected": true,
"text": "<p>I seem to have settled on returning IEnumerable <strong>with the objects cloned.</strong></p>\n\n<pre><code>public IEnumerable<Foose> GetFooseList() {\n foreach(var foos in Collection) {\n yield return foos.Clone();\n }\n}\n</code></pre>\n\n<ul>\n<li>requires a Clone method on Foos.</li>\n</ul>\n\n<p>This allows no changes in the collection. Remember that ReadonlyCollection is \"leaky\" since the objects inside it can be changed as mentioned in a link in another post.</p>\n"
},
{
"answer_id": 25952559,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>Since the question was written, .NET 4.0 has added an <code>IReadOnlyCollection<T></code> interface; it would probably be good to use that as the declared return type.</p>\n\n<p>That does, however, leave open the question of what type of <em>instance</em> to return. One approach would be to clone all the items in the original collection. Another would be to always return a read-only wrapper. A third would be to return the original collection if it implements <code>IReadOnlyCollection<T></code>. Each approach will be the best one in certain contexts, but will be less than ideal (or perhaps downright dreadful) in others. Unfortunately, Microsoft provides no standard means by which a question can be asked two very important questions:</p>\n\n<ol>\n<li><p>Do you promise to always and forevermore contain the same items as you do right now?</p></li>\n<li><p>Can you safely be exposed directly to code which is not supposed to modify your contents.</p></li>\n</ol>\n\n<p>Which style of wrapping is appropriate would depend upon what the client code is expecting to do with the thing it receives. Some scenarios to be avoided:</p>\n\n<ol>\n<li><p>An object was supplied of a type that the client would recognize as immutable, but rather than being returned directly it is duplicated, using a type that the client doesn't recognize as immutable. Consequently, the client is compelled to duplicate the collection again.</p></li>\n<li><p>An object was supplied of a type that the client would recognize as immutable, but before being returned it is wrapped in such a fashion that the client can't tell whether the collection is immutable or not, and thus is compelled to duplicate.</p></li>\n<li><p>An object of mutable type which is not supposed to be mutated is supplied by a client (cast to a read-only interface). It is then exposed directly to another client which determines that it is a mutable type and proceeds to modify it.</p></li>\n<li><p>A reference to a mutable collection is received and is encapsulated in a read-only wrapper before being returned to a client that needs an immutable object. The method that returned the collection promised that it is immutable, and thus the client declined to make its own defensive copy. The client is then ill-prepared for the possibility that the collection might change.</p></li>\n</ol>\n\n<p>There isn't really any particularly \"safe\" course of action an object can take with collections that it receives from some clients and needs to expose to others. Always duplicating everything is in many circumstances the safest course of action, but it can easily result in situations where a collection which shouldn't need to be duplicated at all ends up getting duplicated hundreds or thousands of times. Returning references as received can often be the most efficient approach, but it can also be semantically dangerous.</p>\n\n<p>I wish Microsoft would add a standard means by which collections could be asked the above questions or, better yet, be asked to produce an immutable snapshot of their current state. An immutable collection could return an immutable snapshot of its current state very cheaply (just return itself) and even some mutable collection types could return an immutable snapshot at a cost far below the cost of a full enumeration (e.g. a <code>List<T></code> might be backed by two <code>T[][]</code> arrays, one of which holds references to sharable immutable arrays of 256 items, and the other of which holds references to unsharable mutable arrays of 256 items. Making a snapshot of a list would require cloning only the inner arrays containing items that have been modified since the last snapshot--potentially much cheaper than cloning the whole list. Unfortunately, since there's no standard \"make an immutable snapshot\" interface [note that <code>ICloneable</code> doesn't count, since a clone of a mutable list would be mutable; while one could make an immutable snapshot by encapsulating a mutable clone in a read-only wrapper, that would only work for things which are cloneable, and even types which aren't cloneable should still support a \"mutable snapshot\" function.]</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
] |
I have an `ICollection<T>` called `foos` in my class which I want to expose as read-only (see [this question](https://stackoverflow.com/questions/284090/how-to-get-a-readonlycollectiont-of-the-keys-in-a-dictionaryt-s)). I see that the interface defines a property `.IsReadOnly`, which seems appropriate... My question is this: how do I make it obvious to the consumer of the class that `foos` is read-only?
I don't want to rely on them remembering to query `.IsReadOnly` before trying a not-implemented method such as `.Add()`. Ideally, I would like to expose `foos` as a `ReadOnlyCollection<T>`, but it does not implement `IList<T>`. Should I expose `foo` via a method called, for example, `GetReadOnlyFooCollection` rather than via a property? If so, would this not confuse someone who then expects a `ReadOnlyCollection<T>`?
This is C# 2.0, so extension methods like `ToList()` are not available...
|
I seem to have settled on returning IEnumerable **with the objects cloned.**
```
public IEnumerable<Foose> GetFooseList() {
foreach(var foos in Collection) {
yield return foos.Clone();
}
}
```
* requires a Clone method on Foos.
This allows no changes in the collection. Remember that ReadonlyCollection is "leaky" since the objects inside it can be changed as mentioned in a link in another post.
|
285,343 |
<p>I've got an SQL query that looks like this:</p>
<pre><code>INSERT INTO DB..incident
(
incident_number --nvarchar(10)
)
VALUES
(
N'I?'
)
</code></pre>
<p>What does the ? do in the value statement?</p>
<p>EDIT:: Turns out there's some funny business via triggers and custom datatypes that occur on insert (we've got a bit of a messed up DB.) Given normal settings I've marked the answer appropriately.</p>
|
[
{
"answer_id": 285366,
"author": "TGnat",
"author_id": 25121,
"author_profile": "https://Stackoverflow.com/users/25121",
"pm_score": 4,
"selected": true,
"text": "<p>At the risk of sounding flippant... Nothing... It puts an I? into the field... Try this... </p>\n\n<pre><code>DECLARE @TestTable TABLE (test NVARCHAR(10))\n\nINSERT INTO @TestTable (\n test\n) VALUES ( \n N'I?' ) \n\n\nSELECT * \nFROM @TestTable\n</code></pre>\n"
},
{
"answer_id": 285399,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "<p>The question in my mind when I read this was, what does the N do?</p>\n\n<p>In Oracle, N before a character string literal indicates that the string should be encoded in the national (i.e. localized) character set rather than the default character set for the database.</p>\n\n<p>So as the others have said, you're inserting the string 'I?' into the column. However, it may be encoded using a different character set (although since these characters are in the standard ASCII range the result will probably be the same).</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33226/"
] |
I've got an SQL query that looks like this:
```
INSERT INTO DB..incident
(
incident_number --nvarchar(10)
)
VALUES
(
N'I?'
)
```
What does the ? do in the value statement?
EDIT:: Turns out there's some funny business via triggers and custom datatypes that occur on insert (we've got a bit of a messed up DB.) Given normal settings I've marked the answer appropriately.
|
At the risk of sounding flippant... Nothing... It puts an I? into the field... Try this...
```
DECLARE @TestTable TABLE (test NVARCHAR(10))
INSERT INTO @TestTable (
test
) VALUES (
N'I?' )
SELECT *
FROM @TestTable
```
|
285,345 |
<p>This exception is consistently thrown on a SOAP Request which takes almost three minutes to receive and is 2.25 megs in size. </p>
<p>When scouring the web I find all sorts of posts which all seem to be about setting headers on the Request, some want me to not send the "Expect:" header, some want me to send the "Keep-Alive:" header, but irregardless of the headers I send I still get this pesky error. I don't believe that setting any headers is my answer, because <em>I can recreate the exact same request using "curl" and a response does eventually come back with no problems what-so-ever</em>. </p>
<p>My <code><httpRuntime maxRequestLength="409600" executionTimeout="900"/></code>. </p>
<p>I feel as if I'm running out of options. If anyone can provide any assistance I would be most grateful. A few other things to note would be that the server I'm Requesting data from is out of my hands, also these requests are over https and other requests with smaller responses work flawlessly.</p>
<p>Thanks</p>
|
[
{
"answer_id": 285378,
"author": "mkoeller",
"author_id": 33433,
"author_profile": "https://Stackoverflow.com/users/33433",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried the sugestion of <a href=\"http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx\" rel=\"nofollow noreferrer\">this Blog Post</a>? The problem will most probably lie in the TCP/HTTP stack implementation of .NET .</p>\n"
},
{
"answer_id": 285542,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 4,
"selected": false,
"text": "<p>You tagged the post as .NET35, so are you using WCF? </p>\n\n<p>If so, here is an example of the App.config we use for large data sets:</p>\n\n<pre><code><system.serviceModel>\n <bindings>\n <basicHttpBinding>\n <binding name=\"BasicHttpBinding\" maxBufferSize=\"2147483647\" maxReceivedMessageSize=\"2147483647\">\n <readerQuotas maxDepth=\"32\" maxStringContentLength=\"8388608\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" />\n </binding>\n </basicHttpBinding>\n </bindings>\n <client>\n <endpoint address=\"http://localhost:1602/EndPoint.svc\" binding=\"basicHttpBinding\" bindingConfiguration=\"BasicHttpBinding\" contract=\"IEndPointContract\" name=\"EndPoint\" behaviorConfiguration=\"EndpointBehaviour\" /> \n </client>\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"EndpointBehaviour\">\n <dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n </behavior>\n </endpointBehaviors>\n </behaviors>\n </system.serviceModel>\n</code></pre>\n"
},
{
"answer_id": 1003930,
"author": "Boris Modylevsky",
"author_id": 91714,
"author_profile": "https://Stackoverflow.com/users/91714",
"pm_score": 3,
"selected": false,
"text": "<p>I hope it's not too late for answering this question.</p>\n\n<p>Try adding the following attribute on the definition of your contract interface: <pre><code>[ServiceKnownType(typeof(ReturnClass))]</code></pre></p>\n\n<p>For more generic solution that allows returning polymorphic classes please refer to this post:\n<a href=\"http://www.goeleven.com/blog/entryDetail.aspx?entry=45\" rel=\"noreferrer\"> <a href=\"http://www.goeleven.com/blog/entryDetail.aspx?entry=45\" rel=\"noreferrer\">http://www.goeleven.com/blog/entryDetail.aspx?entry=45</a></a></p>\n"
},
{
"answer_id": 3386430,
"author": "Ahmad Th",
"author_id": 372032,
"author_profile": "https://Stackoverflow.com/users/372032",
"pm_score": 2,
"selected": false,
"text": "<p>I've got the same issue, and after deep investigations I found this article:</p>\n\n<p><a href=\"http://consultingblogs.emc.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx\" rel=\"nofollow noreferrer\">Merrick Chaffer's Blog</a></p>\n\n<p>It was all related to setting the \"dataContractSerializer\" for both client and server.\nHope this to be helpful.</p>\n"
},
{
"answer_id": 7482121,
"author": "Isaac",
"author_id": 928394,
"author_profile": "https://Stackoverflow.com/users/928394",
"pm_score": 2,
"selected": false,
"text": "<p>I have added another field, but didn't have a set on the property.\nThat was my solution for the same error.</p>\n\n<pre><code>[DataMember]\npublic bool HasValue\n{\n get { return true; }\n set { }//adding this line made the solution.\n}\n</code></pre>\n"
},
{
"answer_id": 8193055,
"author": "sharmaja",
"author_id": 1055124,
"author_profile": "https://Stackoverflow.com/users/1055124",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using dbml instead of edmx you will get this( The underlying connection was closed: The connection was closed unexpectedly.) as dbml will not return serialisable data it needs datacontract so go to properties of dbml file and change the Serialization mode to unidirectional.</p>\n"
},
{
"answer_id": 8862879,
"author": "aatdark",
"author_id": 539654,
"author_profile": "https://Stackoverflow.com/users/539654",
"pm_score": 2,
"selected": false,
"text": "<p>i got this error because my datatransfereobjects refered to each other in an recursive manner.</p>\n\n<p>For example:</p>\n\n<p>Customer-> (has) -> Rating\nRating-> (belong to) -> Customer</p>\n\n<p>so you have to remove cycles.</p>\n\n<pre><code>[DataContract]\npublic class Rating\n{\n private Customer _customer;\n //[DataMember] // <- EITHER HERE \n public Customer Customer\n {\n get { return _customer; }\n set { _customer = value; }\n }\n}\n\n\n[DataContract]\npublic class Customer\n{\n private long _customerID;\n [DataMember]\n public long CustomerID\n {\n get { return _customerID; }\n set { _customerID = value; }\n }\n\n [DataMember] // <- OR HERE\n public Rating Rating\n {\n get { return _rating; }\n set { _rating = value; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17321145,
"author": "SyntaxError",
"author_id": 1430942,
"author_profile": "https://Stackoverflow.com/users/1430942",
"pm_score": 2,
"selected": false,
"text": "<p>Tried several ways to get rid of this error message until I found this solution:\n<a href=\"http://kiranpatils.wordpress.com/2008/09/22/the-underlying-connection-was-closed-the-connection-was-closed-unexpectedly-while-returning-data-table-from-wcf-service/\" rel=\"nofollow\">http://kiranpatils.wordpress.com/2008/09/22/the-underlying-connection-was-closed-the-connection-was-closed-unexpectedly-while-returning-data-table-from-wcf-service/</a></p>\n\n<p>You may change your List<> to DataSet. I suspect DataSet can handle much amount of data than the List<>.</p>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 20250712,
"author": "Roath So",
"author_id": 3043131,
"author_profile": "https://Stackoverflow.com/users/3043131",
"pm_score": 0,
"selected": false,
"text": "<p>For WCF with EF, just add the following code in the context class.</p>\n\n<p>base.Configuration.ProxyCreationEnabled = false;</p>\n"
},
{
"answer_id": 24757394,
"author": "Justin Clarke",
"author_id": 590533,
"author_profile": "https://Stackoverflow.com/users/590533",
"pm_score": 1,
"selected": false,
"text": "<p>This is a generic error raised if there is an internal error.</p>\n\n<p>Try adding tracing here: <a href=\"http://msdn.microsoft.com/en-us/library/ms732023(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms732023(v=vs.110).aspx</a></p>\n\n<p>You will see the full log then.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21909/"
] |
This exception is consistently thrown on a SOAP Request which takes almost three minutes to receive and is 2.25 megs in size.
When scouring the web I find all sorts of posts which all seem to be about setting headers on the Request, some want me to not send the "Expect:" header, some want me to send the "Keep-Alive:" header, but irregardless of the headers I send I still get this pesky error. I don't believe that setting any headers is my answer, because *I can recreate the exact same request using "curl" and a response does eventually come back with no problems what-so-ever*.
My `<httpRuntime maxRequestLength="409600" executionTimeout="900"/>`.
I feel as if I'm running out of options. If anyone can provide any assistance I would be most grateful. A few other things to note would be that the server I'm Requesting data from is out of my hands, also these requests are over https and other requests with smaller responses work flawlessly.
Thanks
|
You tagged the post as .NET35, so are you using WCF?
If so, here is an example of the App.config we use for large data sets:
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1602/EndPoint.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding" contract="IEndPointContract" name="EndPoint" behaviorConfiguration="EndpointBehaviour" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="EndpointBehaviour">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
```
|
285,372 |
<p>Is there a way to have the compile deduce the template parameter automatically?</p>
<pre><code>template<class T>
struct TestA
{
TestA(T v) {}
};
template<class T>
void TestB(T v)
{
}
int main()
{
TestB (5);
}
</code></pre>
<p>Test B works fine, however when i change it to TestA it will not compile with the error " use of class template requires template argument list"</p>
|
[
{
"answer_id": 285380,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 5,
"selected": true,
"text": "<p>No, there isn't. Class templates are never deduced. The usual pattern is to have a <code>make_</code> free function:</p>\n\n<pre><code>template<class T> TestA<T> make_TestA(T v)\n{\n return TestA<T>(v);\n}\n</code></pre>\n\n<p>See <code>std::pair</code> and <code>std::make_pair</code>, for example.</p>\n\n<p>In C++0x you will be able to do</p>\n\n<pre><code>auto someVariable = make_TestA(5);\n</code></pre>\n\n<p>to avoid having to specify the type for local variables.</p>\n"
},
{
"answer_id": 285533,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>Sunlight is right, but if I may ask you a question: is that really a problem in your code. I mean:</p>\n\n<pre><code>TestA(5);\n</code></pre>\n\n<p>Would become</p>\n\n<pre><code>TestA<int>(5);\n</code></pre>\n\n<p>As long as it's only one template argument, it's not that bad, IMHO. It's not like you can get around typing the type once in most cases.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there a way to have the compile deduce the template parameter automatically?
```
template<class T>
struct TestA
{
TestA(T v) {}
};
template<class T>
void TestB(T v)
{
}
int main()
{
TestB (5);
}
```
Test B works fine, however when i change it to TestA it will not compile with the error " use of class template requires template argument list"
|
No, there isn't. Class templates are never deduced. The usual pattern is to have a `make_` free function:
```
template<class T> TestA<T> make_TestA(T v)
{
return TestA<T>(v);
}
```
See `std::pair` and `std::make_pair`, for example.
In C++0x you will be able to do
```
auto someVariable = make_TestA(5);
```
to avoid having to specify the type for local variables.
|
285,383 |
<p>Given my current .htaccess file, how would I modify it to check for an additional URL path like '/src/pub/<em>' and rewrite it to '/</em>' without affecting the current rewrite?</p>
<p>Here's the original .htaccess file:</p>
<pre><code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
</code></pre>
<p>and here's my recent attempt (which doesn't work):</p>
<pre><code>RewriteEngine on
RewriteRule ^/src/pub/(.*)$ /$1 [R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
</code></pre>
<p><strong>Edit:</strong> Here are some examples of what I want to accomplish:</p>
<p>New Additional Rule:</p>
<pre><code>From: http://www.mysite.com/src/pub/validfile.php
To: http://www.mysite.com/validfile.php
From: http://www.mysite.com/src/pub/user/detail/testuser
To: http://www.mysite.com/user/detail/testuser
</code></pre>
<p>Existing Rule (already working):</p>
<pre><code>From: http://www.mysite.com/user/detail/testuser
To: http://www.mysite.com/index.php?route=user/detail/testuser
</code></pre>
|
[
{
"answer_id": 285420,
"author": "TimB",
"author_id": 4193,
"author_profile": "https://Stackoverflow.com/users/4193",
"pm_score": 4,
"selected": true,
"text": "<p>I'm guessing that the problem is that the URL is being rewritten by the first rule, and then rewritten again by the second.</p>\n\n<p>The solution to that is to add the \"last\" flag to the first rule, like this:</p>\n\n<pre><code>RewriteRule ^/src/pub/(.*)$ /$1 [R,L]\n</code></pre>\n"
},
{
"answer_id": 285433,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<p>within a .htaccess file, use this instead:</p>\n\n<pre><code>RewriteRule ^src/pub/(.*)$ /$1 [R]\n</code></pre>\n\n<p>the leading \"/\" <strong>will not</strong> match within .htaccess, only within <code>httpd.conf</code> (<a href=\"http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule\" rel=\"nofollow noreferrer\">src</a> - bottom of page) if you wish for processing of further rules to stop, then add the <code>L</code> flag:</p>\n\n<pre><code>RewriteRule ^src/pub/(.*)$ /$1 [L,R]\n</code></pre>\n\n<p>rewrite log comparison (.htaccess context):</p>\n\n<pre><code>// using ^/src/pub/(.*)$ - leading slash will not work in .htaccess context!\n(1) pass through /home/test/src\n\n// using ^src/pub/(.*)$\n(2) rewrite 'src/pub/testme' -> '/testme'\n(2) explicitly forcing redirect with http://test/testme\n(1) escaping http://test/testme for redirect\n(1) redirect to http://test/testme [REDIRECT/302]\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
Given my current .htaccess file, how would I modify it to check for an additional URL path like '/src/pub/*' and rewrite it to '/*' without affecting the current rewrite?
Here's the original .htaccess file:
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
```
and here's my recent attempt (which doesn't work):
```
RewriteEngine on
RewriteRule ^/src/pub/(.*)$ /$1 [R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
```
**Edit:** Here are some examples of what I want to accomplish:
New Additional Rule:
```
From: http://www.mysite.com/src/pub/validfile.php
To: http://www.mysite.com/validfile.php
From: http://www.mysite.com/src/pub/user/detail/testuser
To: http://www.mysite.com/user/detail/testuser
```
Existing Rule (already working):
```
From: http://www.mysite.com/user/detail/testuser
To: http://www.mysite.com/index.php?route=user/detail/testuser
```
|
I'm guessing that the problem is that the URL is being rewritten by the first rule, and then rewritten again by the second.
The solution to that is to add the "last" flag to the first rule, like this:
```
RewriteRule ^/src/pub/(.*)$ /$1 [R,L]
```
|
285,400 |
<p>The Win32 API call <a href="http://msdn.microsoft.com/en-us/library/ms221570.aspx" rel="noreferrer">RegisterTypeLib()</a> is used to create the registry keys necessary to register a type library.</p>
<p>Unfortunatly, on Windows XP, it tries to write those registry key entries to </p>
<pre><code>HKEY_CLASSES_ROOT\TypeLib
</code></pre>
<p>rather than </p>
<pre><code>HKEY_CURRENT_USER\Software\Classes\TypeLib
</code></pre>
<p>Meaning that a standard user will not be able to run an ActiveX.</p>
<p>In May 2008 Microsoft released a <a href="http://support.microsoft.com/kb/935200" rel="noreferrer">hotfix for Vista</a> to correct this issue - but the problem remains on Windows XP.</p>
<p>What's a standard-user friendly developer to do?</p>
<hr>
<h2>Answer 1</h2>
<p>Use the API call that is designed for it:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms221504.aspx" rel="noreferrer">RegisterTypeLibraryForUser()</a></p>
<h2>Answer 2</h2>
<p>If you can't fix it, hack it:</p>
<pre><code>//begin hack
HKEY key;
RegOpenKeyW(HKEY_CURRENT_USER, @"Software\Classes", out key);
RegOverridePredefKey(HKEY_CLASSES_ROOT, key);
//do original work
RegisterTypeLibrary(...)
//stop hacking
RegOverridePredefKey(HKEY_CLASSES_ROOT, null);
RegCloseKey(key);
</code></pre>
|
[
{
"answer_id": 285453,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at this blog entry I wrote. It will registry ATL COM objects into HKCU instead of HKCR using RegOverridePredefKey. You can use the same technique to call RegisterTypeLib and have it properly register under HKCU</p>\n\n<p><a href=\"http://blogs.msdn.com/jaredpar/archive/2005/05/29/423000.aspx\" rel=\"noreferrer\">Register ATL as Normal User</a></p>\n"
},
{
"answer_id": 285454,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "<p>You can use the <code>RegOverridePredefKey()</code> API to map the <code>HKEY_CLASSES_ROOT</code> regtree to <code>HKEY_CURRENT_USER\\Software\\Classes</code>:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms724901.aspx\" rel=\"noreferrer\"><code>http://msdn.microsoft.com/en-us/library/ms724901.aspx</code></a></li>\n</ul>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
The Win32 API call [RegisterTypeLib()](http://msdn.microsoft.com/en-us/library/ms221570.aspx) is used to create the registry keys necessary to register a type library.
Unfortunatly, on Windows XP, it tries to write those registry key entries to
```
HKEY_CLASSES_ROOT\TypeLib
```
rather than
```
HKEY_CURRENT_USER\Software\Classes\TypeLib
```
Meaning that a standard user will not be able to run an ActiveX.
In May 2008 Microsoft released a [hotfix for Vista](http://support.microsoft.com/kb/935200) to correct this issue - but the problem remains on Windows XP.
What's a standard-user friendly developer to do?
---
Answer 1
--------
Use the API call that is designed for it:
[RegisterTypeLibraryForUser()](http://msdn.microsoft.com/en-us/library/ms221504.aspx)
Answer 2
--------
If you can't fix it, hack it:
```
//begin hack
HKEY key;
RegOpenKeyW(HKEY_CURRENT_USER, @"Software\Classes", out key);
RegOverridePredefKey(HKEY_CLASSES_ROOT, key);
//do original work
RegisterTypeLibrary(...)
//stop hacking
RegOverridePredefKey(HKEY_CLASSES_ROOT, null);
RegCloseKey(key);
```
|
You can use the `RegOverridePredefKey()` API to map the `HKEY_CLASSES_ROOT` regtree to `HKEY_CURRENT_USER\Software\Classes`:
* [`http://msdn.microsoft.com/en-us/library/ms724901.aspx`](http://msdn.microsoft.com/en-us/library/ms724901.aspx)
|
285,408 |
<p>I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like <a href="http://search.cpan.org/~sartak/Date-Extract-0.03/lib/Date/Extract.pm" rel="noreferrer">Date::Extract</a> in Perl</p>
<p>Thank you in advance.</p>
|
[
{
"answer_id": 285677,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>The nearest equivalent is probably the <a href=\"http://labix.org/python-dateutil\" rel=\"noreferrer\">dateutil</a> module. Usage is:</p>\n\n<pre><code>>>> from dateutil.parser import parse\n>>> parse(\"Wed, Nov 12\")\ndatetime.datetime(2008, 11, 12, 0, 0)\n</code></pre>\n\n<p>Using the fuzzy parameter should ignore extraneous text. ie</p>\n\n<pre><code>>>> parse(\"the date was the 1st of December 2006 2:30pm\", fuzzy=True)\ndatetime.datetime(2006, 12, 1, 14, 30)\n</code></pre>\n"
},
{
"answer_id": 285726,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 3,
"selected": false,
"text": "<p>Why no give <a href=\"http://code.google.com/p/parsedatetime/\" rel=\"nofollow noreferrer\">parsedatetime</a> a try?</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37089/"
] |
I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like [Date::Extract](http://search.cpan.org/~sartak/Date-Extract-0.03/lib/Date/Extract.pm) in Perl
Thank you in advance.
|
The nearest equivalent is probably the [dateutil](http://labix.org/python-dateutil) module. Usage is:
```
>>> from dateutil.parser import parse
>>> parse("Wed, Nov 12")
datetime.datetime(2008, 11, 12, 0, 0)
```
Using the fuzzy parameter should ignore extraneous text. ie
```
>>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)
datetime.datetime(2006, 12, 1, 14, 30)
```
|
285,421 |
<p>I've asked a few <a href="https://stackoverflow.com/questions/150513/html-input-style-to-hide-the-box-but-show-the-contents">other questions</a> here about this system, so I'll try to avoid repeating a lot of detail.</p>
<p>The short version is that I have many html pages, each with a form that accepts input, but never saves the input anywhere- they are only ever printed out for mailing. A previously developer who had never heard of <code>@media print</code> did the initial work on most of them, and so he came up with some... <em>odd</em> solutions to hide the ugly text boxes on the printed page, usually resulting in two completely separate copies of nearly the same html. Unfortunately, that broke the back button in many cases, and so now I must go back and fix them. </p>
<hr>
<p>In some cases, these html forms really are form letters, with text inputs in the middle of the text. I can style the text inputs so that the box doesn't show, but they are still the wrong size. This results in a bunch of extra ugly whitespace where it doesn't belong. How can make the inputs fit the text entered by the user?</p>
<p>The best I can come up with at the moment is to have a hidden <span> next to each input that is styled to show instead of the input when printing, and use javascript to keep it in sync. But this is ugly. I'm looking for something better.</p>
<p><strong>Update:</strong><br>
Most of our users are still in IE6, but we have some IE7 and firefox out there.</p>
<p><strong>Update2:</strong><br>
I re-thought this a little to use a label rather than a span. I'll maintain the relationship using the label's <code>for</code> attribute. See <a href="https://stackoverflow.com/questions/285522/find-html-label-associated-with-a-given-input">this question</a> for my final code.</p>
|
[
{
"answer_id": 285677,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>The nearest equivalent is probably the <a href=\"http://labix.org/python-dateutil\" rel=\"noreferrer\">dateutil</a> module. Usage is:</p>\n\n<pre><code>>>> from dateutil.parser import parse\n>>> parse(\"Wed, Nov 12\")\ndatetime.datetime(2008, 11, 12, 0, 0)\n</code></pre>\n\n<p>Using the fuzzy parameter should ignore extraneous text. ie</p>\n\n<pre><code>>>> parse(\"the date was the 1st of December 2006 2:30pm\", fuzzy=True)\ndatetime.datetime(2006, 12, 1, 14, 30)\n</code></pre>\n"
},
{
"answer_id": 285726,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 3,
"selected": false,
"text": "<p>Why no give <a href=\"http://code.google.com/p/parsedatetime/\" rel=\"nofollow noreferrer\">parsedatetime</a> a try?</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
I've asked a few [other questions](https://stackoverflow.com/questions/150513/html-input-style-to-hide-the-box-but-show-the-contents) here about this system, so I'll try to avoid repeating a lot of detail.
The short version is that I have many html pages, each with a form that accepts input, but never saves the input anywhere- they are only ever printed out for mailing. A previously developer who had never heard of `@media print` did the initial work on most of them, and so he came up with some... *odd* solutions to hide the ugly text boxes on the printed page, usually resulting in two completely separate copies of nearly the same html. Unfortunately, that broke the back button in many cases, and so now I must go back and fix them.
---
In some cases, these html forms really are form letters, with text inputs in the middle of the text. I can style the text inputs so that the box doesn't show, but they are still the wrong size. This results in a bunch of extra ugly whitespace where it doesn't belong. How can make the inputs fit the text entered by the user?
The best I can come up with at the moment is to have a hidden <span> next to each input that is styled to show instead of the input when printing, and use javascript to keep it in sync. But this is ugly. I'm looking for something better.
**Update:**
Most of our users are still in IE6, but we have some IE7 and firefox out there.
**Update2:**
I re-thought this a little to use a label rather than a span. I'll maintain the relationship using the label's `for` attribute. See [this question](https://stackoverflow.com/questions/285522/find-html-label-associated-with-a-given-input) for my final code.
|
The nearest equivalent is probably the [dateutil](http://labix.org/python-dateutil) module. Usage is:
```
>>> from dateutil.parser import parse
>>> parse("Wed, Nov 12")
datetime.datetime(2008, 11, 12, 0, 0)
```
Using the fuzzy parameter should ignore extraneous text. ie
```
>>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)
datetime.datetime(2006, 12, 1, 14, 30)
```
|
285,428 |
<p>I am trying to make the <a href="http://docs.jquery.com/Plugins/Validation" rel="nofollow noreferrer">Validation plugin</a> work. It works fine for individual fields, but when I try to include the demo code for the error container that contains all of the errors, I have an issue. The problem is that it shows the container with all errors when I am in all fields, but I would like to display the error container only when the user presses the submit button (but still show inline errors beside the control when losing focus).</p>
<p>The problem is the message in the container. When I took off the code as mentioned in the answer below for the container, the container output just displays the number of errors in plain text. </p>
<p>What is the trick to get a list of detailed error messages? What I would like is to display "ERROR" next to the control in error when the user presses the tab button, and to have a summary of everything at the end when he presses submit. Is that possible?</p>
<p><strong>Code with all input from here:</strong></p>
<pre><code> $().ready(function() {
var container = $('div.containererreurtotal');
// validate signup form on keyup and submit
$("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
var err = validator.numberOfInvalids();
if (err) {
container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
container.show();
} else {
container.hide();
}
}).validate({
rules: {
nickname_in: {
required: true,
minLength: 4
},
prenom_in: {
required: true,
minLength: 4
},
nom_in: {
required: true,
minLength: 4
},
password_in: {
required: true,
minLength: 4
},
courriel_in: {
required: true,
email: true
},
userdigit: {
required: true
}
},
messages: {
nickname_in: "ERROR",
prenom_in: "ERROR",
nom_in: "ERROR",
password_in: "ERROR",
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorPlacement: function(error, element){
container.append(error.clone());
error.insertAfter(element);
}
});
});
</code></pre>
|
[
{
"answer_id": 285799,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I don't know if the validation plugin provides an option for this, but you can probably use standard jQuery to achieve what you want. Make sure you're container is initially hidden, by setting the display style to none:</p>\n\n<pre><code><div id=\"container\" style=\"display:none;\"></div>\n</code></pre>\n\n<p>Then you can hookup an onsubmit event to the form which will make the container visible as soon as an attempt is made to submit the form:</p>\n\n<pre><code>jQuery('#formId').onsubmit(function() {\n // This will be called before the form is submitted\n jQuery('#container').show();\n});\n</code></pre>\n\n<p>Hopefully combining that with your existing code should do the trick.</p>\n"
},
{
"answer_id": 286032,
"author": "user19264",
"author_id": 19264,
"author_profile": "https://Stackoverflow.com/users/19264",
"pm_score": 3,
"selected": false,
"text": "<p>I would remove the errorContainer and then intercept the validation on postback and in there add a container-error manually like this:</p>\n\n<pre><code>$(\"#frmEnregistrer\").bind(\"invalid-form.validate\", function(e, validator) {\n var err = validator.numberOfInvalids();\n if (err) {\n container.html(\"THERE ARE \"+ err + \" ERRORS IN THE FORM\")\n container.show();\n } else {\n container.hide();\n }\n}).validate({ ... })\n</code></pre>\n"
},
{
"answer_id": 286788,
"author": "Serxipc",
"author_id": 34009,
"author_profile": "https://Stackoverflow.com/users/34009",
"pm_score": 5,
"selected": true,
"text": "<p>You will find the documentation for the meta option in <a href=\"http://docs.jquery.com/Plugins/Validation/validate#toptions\" rel=\"noreferrer\">http://docs.jquery.com/Plugins/Validation/validate#toptions</a></p>\n\n<p>If you want to display the errors beside the inputs <strong>AND</strong> in a separate error container you will need to override the <code>errorPlacement</code> callback.</p>\n\n<p>From your example:</p>\n\n<pre><code>...\n courriel_in: \"ERROR\",\n userdigit: \"ERROR\"\n }\n ,errorContainer: container\n\n ,errorPlacement: function(error, element){\n var errorClone = error.clone();\n container.append(errorClone);\n error.insertAfter(element) \n }\n\n // We don't need this options\n //,errorLabelContainer: $(\"ol\", container)\n //,wrapper: 'li'\n //,meta: \"validate\"\n });\n ...\n</code></pre>\n\n<p>The <code>error</code> parameter is a jQuery object containing a <code><label></code> tag. The <code>element</code> parameter is the input that has failed validation.</p>\n\n<h1>Update to comments</h1>\n\n<p>With the above code the error container will not clear errors because it contains a cloned copy. It's easy to solve this if jQuery gives a \"hide\" event, but it doesn't exist. Let's add a hide event!</p>\n\n<ol>\n<li>First we need the <a href=\"http://plugins.jquery.com/project/AOP\" rel=\"noreferrer\">AOP plugin</a></li>\n<li><p>We add an advice for the hide method: </p>\n\n<pre><code> jQuery.aop.before({target: jQuery.fn, method: \"hide\"},\n function(){\n this.trigger(\"hide\");\n });\n</code></pre></li>\n<li><p>We bind the hide event to hide the cloned error:</p>\n\n<pre><code> ...\n ,errorPlacement: function(error, element){\n var errorClone = error.clone();\n container.append(errorClone);\n error.insertAfter(element).bind(\"hide\", function(){\n errorClone.hide();\n });\n }\n ...\n</code></pre></li>\n</ol>\n\n<p>Give it a try</p>\n"
},
{
"answer_id": 953434,
"author": "FerrousOxide",
"author_id": 65717,
"author_profile": "https://Stackoverflow.com/users/65717",
"pm_score": 4,
"selected": false,
"text": "<p>First your container should be using an ID instead of a class.. (I'm going to assume that ID is 'containererreurtotal')</p>\n\n<p>Then Try this..</p>\n\n<pre><code> $().ready(function() {\n\n $('div#containererreurtotal').hide();\n\n // validate signup form on keyup and submit\n $(\"#frmEnregistrer\").validate({\n errorLabelContainer: \"#containererreurtotal\",\n wrapper: \"p\",\n errorClass: \"error\",\n rules: {\n nickname_in: { required: true, minLength: 4 },\n prenom_in: { required: true, minLength: 4 },\n nom_in: { required: true, minLength: 4 },\n password_in: { required: true, minLength: 4 },\n courriel_in: { required: true, email: true },\n userdigit: { required: true }\n },\n messages: { \n nickname_in: { required: \"Nickname required!\", minLength: \"Nickname too short!\" },\n prenom_in: { required: \"Prenom required!\", minLength: \"Prenom too short!\" },\n nom_in: { required: \"Nom required!\", minLength: \"Nom too short!\" },\n password_in: { required: \"Password required!\", minLength: \"Password too short!\" },\n courriel_in: { required: \"Courriel required!\", email: \"Courriel must be an Email\" },\n userdigit: { required: \"UserDigit required!\" }\n },\n invalidHandler: function(form, validator) {\n $(\"#containererreurtotal\").show();\n },\n unhighlight: function(element, errorClass) {\n if (this.numberOfInvalids() == 0) {\n $(\"#containererreurtotal\").hide();\n }\n $(element).removeClass(errorClass);\n } \n\n });\n });\n</code></pre>\n\n<p>I am assuming here that you want a <p> tag around each of the individual errors. Typically I use a <ul> container for the actual container (instead of the div you used called 'containererreurtotal') and a <li> for each error (this element is specified in the \"wrapper\" line) </p>\n\n<p>If you specify #containererreurtotal as display: none; in your CSS, then you dont need the first line in the ready function ( $('div#containererreurtotal').hide(); ) </p>\n"
},
{
"answer_id": 5339599,
"author": "user664378",
"author_id": 664378,
"author_profile": "https://Stackoverflow.com/users/664378",
"pm_score": 2,
"selected": false,
"text": "<p>I have a slightly different solution:</p>\n\n<pre><code>jQuery(document).ready(function() {\n var submitted = false;\n var validator = jQuery(\"#emailForm\").validate({ \n showErrors: function(errorMap, errorList) {\n if (submitted) {\n var summary = \"\";\n jQuery.each(errorList, function() {\n summary += \"<li><label for='\"+ this.element.name;\n summery += \"' class='formError'>\" + this.message + \"</label></li>\"; });\n jQuery(\"#errorMessageHeader\").show();\n jQuery(\"#errorMessageHeader\").children().after().html(summary);\n submitted = false;\n }\n this.defaultShowErrors();\n }, \n invalidHandler: function(form, validator) { submitted = true; },\n onfocusout: function(element) { this.element(element); },\n errorClass: \"formError\",\n rules: { \n //some validation rules \n },\n messages: { \n //error messages to be displayed\n } \n }); \n}); \n</code></pre>\n"
},
{
"answer_id": 13659556,
"author": "Oliver Krah",
"author_id": 1868643,
"author_profile": "https://Stackoverflow.com/users/1868643",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this problem with the following short code:</p>\n\n<pre><code>errorElement: \"td\",\nerrorPlacement: function (error, element) {\n error.insertAfter(element.parent());\n} \n</code></pre>\n\n<p>My structure is the following:</p>\n\n<pre><code><table>\n <tr>\n <td>Name:</td>\n <td><input type=\"text\" name=\"name\"></td>\n </tr>\n</table>\n</code></pre>\n\n<p>So my errors will now shown directly in a <code><td></code> behind my <code><input></code></p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
I am trying to make the [Validation plugin](http://docs.jquery.com/Plugins/Validation) work. It works fine for individual fields, but when I try to include the demo code for the error container that contains all of the errors, I have an issue. The problem is that it shows the container with all errors when I am in all fields, but I would like to display the error container only when the user presses the submit button (but still show inline errors beside the control when losing focus).
The problem is the message in the container. When I took off the code as mentioned in the answer below for the container, the container output just displays the number of errors in plain text.
What is the trick to get a list of detailed error messages? What I would like is to display "ERROR" next to the control in error when the user presses the tab button, and to have a summary of everything at the end when he presses submit. Is that possible?
**Code with all input from here:**
```
$().ready(function() {
var container = $('div.containererreurtotal');
// validate signup form on keyup and submit
$("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
var err = validator.numberOfInvalids();
if (err) {
container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
container.show();
} else {
container.hide();
}
}).validate({
rules: {
nickname_in: {
required: true,
minLength: 4
},
prenom_in: {
required: true,
minLength: 4
},
nom_in: {
required: true,
minLength: 4
},
password_in: {
required: true,
minLength: 4
},
courriel_in: {
required: true,
email: true
},
userdigit: {
required: true
}
},
messages: {
nickname_in: "ERROR",
prenom_in: "ERROR",
nom_in: "ERROR",
password_in: "ERROR",
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorPlacement: function(error, element){
container.append(error.clone());
error.insertAfter(element);
}
});
});
```
|
You will find the documentation for the meta option in <http://docs.jquery.com/Plugins/Validation/validate#toptions>
If you want to display the errors beside the inputs **AND** in a separate error container you will need to override the `errorPlacement` callback.
From your example:
```
...
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorContainer: container
,errorPlacement: function(error, element){
var errorClone = error.clone();
container.append(errorClone);
error.insertAfter(element)
}
// We don't need this options
//,errorLabelContainer: $("ol", container)
//,wrapper: 'li'
//,meta: "validate"
});
...
```
The `error` parameter is a jQuery object containing a `<label>` tag. The `element` parameter is the input that has failed validation.
Update to comments
==================
With the above code the error container will not clear errors because it contains a cloned copy. It's easy to solve this if jQuery gives a "hide" event, but it doesn't exist. Let's add a hide event!
1. First we need the [AOP plugin](http://plugins.jquery.com/project/AOP)
2. We add an advice for the hide method:
```
jQuery.aop.before({target: jQuery.fn, method: "hide"},
function(){
this.trigger("hide");
});
```
3. We bind the hide event to hide the cloned error:
```
...
,errorPlacement: function(error, element){
var errorClone = error.clone();
container.append(errorClone);
error.insertAfter(element).bind("hide", function(){
errorClone.hide();
});
}
...
```
Give it a try
|
285,446 |
<p>I've got a Windows Forms application with two ListBox controls on the same form.
They both have their SelectionMode set to 'MultiExtended'. </p>
<p>When I change the selection of one the selection of the other changes.</p>
<p>Now I thought I'd done something stupid with my SelectedIndexChanged handlers so I removed them and re-wrote them from scratch, and got the problem.</p>
<p>So I created a brand new WinForms app and dragged two ListBoxes onto the forms surface.</p>
<p>In the constructor I populated them both with the following.</p>
<pre><code>List<Thing> data = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data.Add(temp);
}
listBox1.DataSource = data;
listBox1.DisplayMember = "Letters";
listBox1.ValueMember = "Id";
List<Thing> data2 = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data2.Add(temp);
}
listBox2.DataSource = data2;
listBox2.DisplayMember = "Letters";
listBox2.ValueMember = "Id";
</code></pre>
<p>And then I built and ran the app.</p>
<p>Started selecting some values to see if the symptoms were present.
And they were!</p>
<p>This is literally all the code I added to the form,I had not added any event handlers, I have tried it with the SelectionMode set to 'One' and 'MultiExtended'.</p>
<p>Can anyone give me a clue as to why this is happening.</p>
<p>Cheers</p>
|
[
{
"answer_id": 285466,
"author": "sindre j",
"author_id": 37119,
"author_profile": "https://Stackoverflow.com/users/37119",
"pm_score": 1,
"selected": false,
"text": "<p>I experienced the same when I used the same datasource on both listboxes, but creating two equal datasources solved the problem for me. I can see nothing wrong with your code. Anything particular with the Thing class ? Or does it just contain the two members Letters and Id ?</p>\n"
},
{
"answer_id": 285469,
"author": "Matt Brunell",
"author_id": 24970,
"author_profile": "https://Stackoverflow.com/users/24970",
"pm_score": 2,
"selected": false,
"text": "<p>I believe that your two controls are sharing a CurrencyManager. I'm not sure exactly why.<br>\nAs a workaround, you could try just populating your listboxes with simple strings. Or you may want to try creating separate instances of the BindingSource component, and bind to those.</p>\n"
},
{
"answer_id": 285488,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 0,
"selected": false,
"text": "<p>I created a new win forms app with two list boxes on it. They behave as I would expect. Can you post the complete code? Here is my code. </p>\n\n<pre><code>public partial class Form1 : Form\n{\npublic Form1()\n{\n InitializeComponent();\n}\n\nprivate class Thing\n{\n public String Letters { get; set; }\n public Int32 Id { get; set; }\n}\nprivate void Form1_Load(object sender, EventArgs e)\n{\n List<Thing> data = new List<Thing>();\n\n for (int i = 0; i < 50; i++)\n {\n Thing temp = new Thing();\n temp.Letters = \"abc \" + i.ToString();\n temp.Id = i;\n data.Add(temp);\n }\n\n listBox1.DataSource = data;\n listBox1.DisplayMember = \"Letters\";\n listBox1.ValueMember = \"Id\";\n\n\n List<Thing> data2 = new List<Thing>();\n\n for (int i = 0; i < 50; i++)\n {\n Thing temp = new Thing();\n temp.Letters = \"abc \" + i.ToString();\n temp.Id = i;\n data2.Add(temp);\n }\n\n listBox2.DataSource = data2;\n listBox2.DisplayMember = \"Letters\";\n listBox2.ValueMember = \"Id\";\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 285616,
"author": "Josh",
"author_id": 1481717,
"author_profile": "https://Stackoverflow.com/users/1481717",
"pm_score": 0,
"selected": false,
"text": "<p>I tried to duplicate this behavior on my own machine and was unable to do so running just the code your provided.</p>\n"
},
{
"answer_id": 285663,
"author": "Greg B",
"author_id": 1741868,
"author_profile": "https://Stackoverflow.com/users/1741868",
"pm_score": 0,
"selected": false,
"text": "<p>I stand corrected.</p>\n\n<p>In another instance of VS in a brand new solution, this works as expected.</p>\n\n<p>God only know's what i've done to make it do what it's doing</p>\n"
},
{
"answer_id": 289562,
"author": "Greg B",
"author_id": 1741868,
"author_profile": "https://Stackoverflow.com/users/1741868",
"pm_score": 1,
"selected": false,
"text": "<p>And more...</p>\n\n<p>I finally got ot the bottom of it.</p>\n\n<p>I was binding the two ListBoxes to the same List. by changing the code to </p>\n\n<pre><code>theListBox.DataSource = _contacts.Take(_contacts.Count).ToList();\n</code></pre>\n\n<p>the issue was curcumvented.</p>\n\n<p>It seems that the reference to the List that it stored also caries any binding or selection information over to the other ListBox.</p>\n\n<p>be careful. ;)</p>\n"
},
{
"answer_id": 289571,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>It isn't the <em>list</em> that stores the current position - it is the <code>CurrencyManager</code>. Any controls (with the same <code>BindingContext</code>) with the <em>same reference</em> as a <code>DataSource</code> will share a <code>CurrencyManager</code>. By using different list instances you get different <code>CurrencyManager</code> instances, and thus separate position.</p>\n\n<p>You could achieve the same simply by using <code>.ToList()</code>, or creating a new <code>List<T></code> with the same contents (as per your original post), or by assigning a new <code>BindingContext</code> to one of the controls:</p>\n\n<pre><code>control.BindingContext = new BindingContext();\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1741868/"
] |
I've got a Windows Forms application with two ListBox controls on the same form.
They both have their SelectionMode set to 'MultiExtended'.
When I change the selection of one the selection of the other changes.
Now I thought I'd done something stupid with my SelectedIndexChanged handlers so I removed them and re-wrote them from scratch, and got the problem.
So I created a brand new WinForms app and dragged two ListBoxes onto the forms surface.
In the constructor I populated them both with the following.
```
List<Thing> data = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data.Add(temp);
}
listBox1.DataSource = data;
listBox1.DisplayMember = "Letters";
listBox1.ValueMember = "Id";
List<Thing> data2 = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data2.Add(temp);
}
listBox2.DataSource = data2;
listBox2.DisplayMember = "Letters";
listBox2.ValueMember = "Id";
```
And then I built and ran the app.
Started selecting some values to see if the symptoms were present.
And they were!
This is literally all the code I added to the form,I had not added any event handlers, I have tried it with the SelectionMode set to 'One' and 'MultiExtended'.
Can anyone give me a clue as to why this is happening.
Cheers
|
It isn't the *list* that stores the current position - it is the `CurrencyManager`. Any controls (with the same `BindingContext`) with the *same reference* as a `DataSource` will share a `CurrencyManager`. By using different list instances you get different `CurrencyManager` instances, and thus separate position.
You could achieve the same simply by using `.ToList()`, or creating a new `List<T>` with the same contents (as per your original post), or by assigning a new `BindingContext` to one of the controls:
```
control.BindingContext = new BindingContext();
```
|
285,455 |
<p>I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?</p>
<p>I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.</p>
|
[
{
"answer_id": 285498,
"author": "Sherm Pendley",
"author_id": 27631,
"author_profile": "https://Stackoverflow.com/users/27631",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not a python guru, but I found this question interesting so I googled around. <a href=\"https://mail.python.org/pipermail/python-list/2007-September/427041.html\" rel=\"nofollow noreferrer\">This</a> was the first hit on \"python embedding API\" - does it help?</p>\n\n<blockquote>\n <p>If the attributes belong to the global\n scope of a module, then you can use\n \"PyImport_AddModule\" to get a handle\n to the module object. For example, if\n you wanted to get the value of an\n integer in the <strong>main</strong> module named\n \"foobar\", you would do the following:</p>\n\n<pre><code>PyObject *m = PyImport_AddModule(\"__main__\");\nPyObject *v = PyObject_GetAttrString(m,\"foobar\");\n\nint foobar = PyInt_AsLong(v);\n\nPy_DECREF(v);\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 285606,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend using <a href=\"http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/\" rel=\"nofollow noreferrer\"><code>pyrex</code></a> to make an extension module you can store the values in in python, and cdef a bunch of functions which can be called from C to return the values there.</p>\n\n<p>Otherwise, much depends on the type of values you're trying to transmit.</p>\n"
},
{
"answer_id": 287695,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 0,
"selected": false,
"text": "<p>Are you willing to modify the API a <em>little bit</em>?</p>\n\n<ul>\n<li><p>You can make the C function return the new value for the global, and then call it like this:</p>\n\n<p><code>my_global = my_c_func(...)</code></p></li>\n<li><p>If you're using <a href=\"http://robin.python-hosting.com/\" rel=\"nofollow noreferrer\">Robin</a> or the Python C API directly, you can pass the globals dictionary as an additional parameter and modify it</p></li>\n<li>If your global is always in the same module, Sherm's solution looks great</li>\n</ul>\n"
},
{
"answer_id": 25907027,
"author": "Praxeolitic",
"author_id": 1128289,
"author_profile": "https://Stackoverflow.com/users/1128289",
"pm_score": 3,
"selected": false,
"text": "<p>For anyone coming here from Google, here's the direct method:</p>\n\n<pre><code>PyObject* PyEval_GetGlobals()\n</code></pre>\n\n<p><a href=\"https://docs.python.org/2/c-api/reflection.html\" rel=\"noreferrer\">https://docs.python.org/2/c-api/reflection.html</a></p>\n\n<p><a href=\"https://docs.python.org/3/c-api/reflection.html\" rel=\"noreferrer\">https://docs.python.org/3/c-api/reflection.html</a></p>\n\n<p>The return value is accessed as a dictionary.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22517/"
] |
I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?
I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.
|
I'm not a python guru, but I found this question interesting so I googled around. [This](https://mail.python.org/pipermail/python-list/2007-September/427041.html) was the first hit on "python embedding API" - does it help?
>
> If the attributes belong to the global
> scope of a module, then you can use
> "PyImport\_AddModule" to get a handle
> to the module object. For example, if
> you wanted to get the value of an
> integer in the **main** module named
> "foobar", you would do the following:
>
>
>
> ```
> PyObject *m = PyImport_AddModule("__main__");
> PyObject *v = PyObject_GetAttrString(m,"foobar");
>
> int foobar = PyInt_AsLong(v);
>
> Py_DECREF(v);
>
> ```
>
>
|
285,456 |
<p>Given the following, how could I insert rows in my db? (Or what should I correct in my schema?)</p>
<p>Models:</p>
<pre><code>class Item < ActiveRecord::Base
has_many :tran_items
has_many :transactions, :through => :tran_items
end
class TranItem < ActiveRecord::Base
belongs_to :item
belongs_to :transaction
end
class Transaction < ActiveRecord::Base #answer: rename Transaction
has_many :tran_items
has_many :items, :through => :tran_items
end
</code></pre>
<p>Schema:</p>
<pre><code>create_table :items do |t|
t.references :tran_items #answer: remove this line
t.string :name
end
create_table :tran_items do |t|
t.belongs_to :items, :transactions, :null => false #answer: unpluralize
t.integer :quantity
end
create_table :transactions do |t|
t.references :tran_items #answer: remove this line
t.decimal :profit
end
</code></pre>
<p>I lost a few hours trying to insert records, using the rails console to test things out.</p>
|
[
{
"answer_id": 285471,
"author": "tamersalama",
"author_id": 7693,
"author_profile": "https://Stackoverflow.com/users/7693",
"pm_score": 1,
"selected": false,
"text": "<p>If I understood correctly.</p>\n\n<pre><code>item = Item.new(:name => \"item\")\nitem.transactions.build(:name => \"transaction\")\nitem.save!\n</code></pre>\n"
},
{
"answer_id": 285883,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 4,
"selected": true,
"text": "<p>(edit: the model name \"Transaction\" may cause you some problems due to ActiveRecord::Transactions. <a href=\"https://rails.lighthouseapp.com/projects/8994/tickets/993-having-column-named-transaction-in-a-model-leads-to-weird-behavior\" rel=\"nofollow noreferrer\">There is a lighthouse ticket</a>.)</p>\n\n<p>Your schema is not set up correctly. \"references\" is an alias to \"belongs_to\". Item and Transaction don't <strong>belong_to</strong> trans_items, they each <strong>has_many</strong> trans_items (according to your models)</p>\n\n<pre><code>create_table :items do |t|\n t.string :name\nend\ncreate_table :tran_items do |t|\n t.belongs_to :item, :transaction, :null => false\n t.integer :quantity\nend\ncreate_table :transactions do |t|\n t.decimal :profit, :default => 0\nend\n</code></pre>\n\n<p>(edit: make belongs_to singular)</p>\n\n<p>Did you drop the db and re-run the migrations to build the new schema? </p>\n\n<p>rake db:drop && rake db:create && rake db:migrate</p>\n\n<p>Here is what I get in the console:</p>\n\n<pre><code>>> i = Item.create(:name => 'My Item') \n=> #<Item id: 2, name: \"My Item\">\n>> t = Transaction.create(:profit => 100)\n=> #<Transaction id: 2, profit: #<BigDecimal:2411d2c,'0.1E3',4(8)>>\n>> t.tran_items.create(:item => i)\n=> #<TranItem id: nil, item_id: 2, transaction_id: 2, quantity: nil>\n</code></pre>\n"
},
{
"answer_id": 288069,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 2,
"selected": false,
"text": "<p>This schema should give you the results you are looking for:</p>\n\n<pre><code> create_table :items do |t|\n t.string :name\n end\n create_table :purchase_items do |t|\n t.belongs_to :item, :purchase, :null => false\n t.integer :quantity\n end\n create_table :purchases do |t|\n t.decimal :profit, :default => 0\n end\n</code></pre>\n\n<p>Here are the models:</p>\n\n<pre><code>class Purchase < ActiveRecord::Base\n has_many :purchase_items\n has_many :items, :through => :purchase_items\nend \n\nclass Item < ActiveRecord::Base\n has_many :purchase_items\n has_many :purchases, :through => :purchase_items\nend\n\nclass PurchaseItem < ActiveRecord::Base\n belongs_to :item\n belongs_to :purchase\nend\n</code></pre>\n\n<p>Now using the console:</p>\n\n<pre><code>>> i = Item.create(:name => 'Item One')\n=> #<Item id: 1, name: \"Item One\">\n>> p = Purchase.create(:profit => 100)\n=> #<Purchase id: 1, profit: #<BigDecimal:2458cf4,'0.1E3',4(8)>>\n>> p.purchase_items.create(:item => i)\n=> #<PurchaseItem id: 1, item_id: 1, purchase_id: 1, quantity: nil>\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25167/"
] |
Given the following, how could I insert rows in my db? (Or what should I correct in my schema?)
Models:
```
class Item < ActiveRecord::Base
has_many :tran_items
has_many :transactions, :through => :tran_items
end
class TranItem < ActiveRecord::Base
belongs_to :item
belongs_to :transaction
end
class Transaction < ActiveRecord::Base #answer: rename Transaction
has_many :tran_items
has_many :items, :through => :tran_items
end
```
Schema:
```
create_table :items do |t|
t.references :tran_items #answer: remove this line
t.string :name
end
create_table :tran_items do |t|
t.belongs_to :items, :transactions, :null => false #answer: unpluralize
t.integer :quantity
end
create_table :transactions do |t|
t.references :tran_items #answer: remove this line
t.decimal :profit
end
```
I lost a few hours trying to insert records, using the rails console to test things out.
|
(edit: the model name "Transaction" may cause you some problems due to ActiveRecord::Transactions. [There is a lighthouse ticket](https://rails.lighthouseapp.com/projects/8994/tickets/993-having-column-named-transaction-in-a-model-leads-to-weird-behavior).)
Your schema is not set up correctly. "references" is an alias to "belongs\_to". Item and Transaction don't **belong\_to** trans\_items, they each **has\_many** trans\_items (according to your models)
```
create_table :items do |t|
t.string :name
end
create_table :tran_items do |t|
t.belongs_to :item, :transaction, :null => false
t.integer :quantity
end
create_table :transactions do |t|
t.decimal :profit, :default => 0
end
```
(edit: make belongs\_to singular)
Did you drop the db and re-run the migrations to build the new schema?
rake db:drop && rake db:create && rake db:migrate
Here is what I get in the console:
```
>> i = Item.create(:name => 'My Item')
=> #<Item id: 2, name: "My Item">
>> t = Transaction.create(:profit => 100)
=> #<Transaction id: 2, profit: #<BigDecimal:2411d2c,'0.1E3',4(8)>>
>> t.tran_items.create(:item => i)
=> #<TranItem id: nil, item_id: 2, transaction_id: 2, quantity: nil>
```
|
285,465 |
<p>Hi Guys I'm very new to regex, can you help me with this.</p>
<p>I have a string like this <code>"<input attribute='value' >"</code> where <code>attribute='value'</code> could be anything and I want to get do a <code>preg_replace</code> to get just <code><input /></code></p>
<p>How do I specify a wildcard to replace any number of any characters in a srting?</p>
<p>like this? <code>preg_replace("/<input.*>/",$replacement,$string);</code></p>
<p>Many thanks</p>
|
[
{
"answer_id": 285479,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<p>What you have: </p>\n\n<pre><code>.*\n</code></pre>\n\n<p>will match \"any character, and as many as possible. </p>\n\n<p>what you <em>mean</em> is </p>\n\n<pre><code>[^>]+\n</code></pre>\n\n<p>which translates to \"any character, thats not a \">\", and there must be at least one </p>\n\n<p>or altertaively, </p>\n\n<pre><code>.*?\n</code></pre>\n\n<p>which means\n\"any character, but only enough to make this rule work\"</p>\n\n<h1>BUT DONT</h1>\n\n<p>Parsing HTML with regexps is <strong>Bad</strong></p>\n\n<p>use any of the existing html parsers, DOM librarys, anything, Just NOT NAïVE REGEX </p>\n\n<p>For example: </p>\n\n<pre><code> <foo attr=\">\"> \n</code></pre>\n\n<p>Will get grabbed wrongly by regex as </p>\n\n<pre><code>'<foo attr=\" ' with following text of '\">' \n</code></pre>\n\n<p>Which will lead you to this regex: </p>\n\n<pre><code> `<[a-zA-Z]+( [a-zA-Z]+=['\"][^\"']['\"])*)> etc etc \n</code></pre>\n\n<p>at which point you'll discover this lovely gem: </p>\n\n<pre><code> <foo attr=\"'>\\'\\\"\">\n</code></pre>\n\n<p>and your head will explode. </p>\n\n<p>( the syntax highlighter verifies my point, and incorrectly matches thinking i've ended the tag. ) </p>\n"
},
{
"answer_id": 285483,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<pre><code>preg_replace(\"<input[^>]*>\", $replacement, $string); \n// [^>] means \"any character except the greater than symbol / right tag bracket\"\n</code></pre>\n\n<p>This is really <em>basic</em> stuff, you should <a href=\"http://www.regular-expressions.info/php.html\" rel=\"nofollow noreferrer\">catch up with some reading</a>. :-)</p>\n"
},
{
"answer_id": 285634,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 1,
"selected": false,
"text": "<p>Some people were close... but not 100%:</p>\n\n<p>This:</p>\n\n<pre><code>preg_replace(\"<input[^>]*>\", $replacement, $string);\n</code></pre>\n\n<p>should be this:</p>\n\n<pre><code>preg_replace(\"<input[^>]*?>\", $replacement, $string);\n</code></pre>\n\n<p>You don't want that to be a greedy match.</p>\n"
},
{
"answer_id": 287505,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand the question correctly, you have the code:</p>\n\n<pre><code>preg_replace(\"/<input.*>/\",$replacement,$string);\n</code></pre>\n\n<p>and you want us to tell you what you should use for $replacement to delete what was matched by .*</p>\n\n<p>You have to go about this the other way around. Use capturing groups to capture what you want to keep, and reinsert that into the replacement. E.g.:</p>\n\n<pre><code>preg_replace(\"/(<input).*(>)/\",\"$1$2\",$string);\n</code></pre>\n\n<p>Of course, you don't really need capturing groups here, as you're only reinserting literal text. Bet the above shows the technique, in case you want to do this in a situation where the tag can vary. This is a better solution:</p>\n\n<pre><code>preg_replace(\"/<input [^>]*>/\",\"<input />\",$string);\n</code></pre>\n\n<p>The negated character class is more specific than the dot. This regex will work if there are two HTML tags in the string. Your original regex won't.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Hi Guys I'm very new to regex, can you help me with this.
I have a string like this `"<input attribute='value' >"` where `attribute='value'` could be anything and I want to get do a `preg_replace` to get just `<input />`
How do I specify a wildcard to replace any number of any characters in a srting?
like this? `preg_replace("/<input.*>/",$replacement,$string);`
Many thanks
|
What you have:
```
.*
```
will match "any character, and as many as possible.
what you *mean* is
```
[^>]+
```
which translates to "any character, thats not a ">", and there must be at least one
or altertaively,
```
.*?
```
which means
"any character, but only enough to make this rule work"
BUT DONT
========
Parsing HTML with regexps is **Bad**
use any of the existing html parsers, DOM librarys, anything, Just NOT NAïVE REGEX
For example:
```
<foo attr=">">
```
Will get grabbed wrongly by regex as
```
'<foo attr=" ' with following text of '">'
```
Which will lead you to this regex:
```
`<[a-zA-Z]+( [a-zA-Z]+=['"][^"']['"])*)> etc etc
```
at which point you'll discover this lovely gem:
```
<foo attr="'>\'\"">
```
and your head will explode.
( the syntax highlighter verifies my point, and incorrectly matches thinking i've ended the tag. )
|
285,474 |
<p>If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do:</p>
<pre><code> dtOne.Merge(dtTwo);
</code></pre>
<p>Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?</p>
<p>I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:</p>
<pre><code>//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);
</code></pre>
|
[
{
"answer_id": 285500,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 8,
"selected": true,
"text": "<p>The <code>Merge</code> method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.</p>\n\n<p>If you want to preserve both of the original tables, you could copy the original first, then merge:</p>\n\n<pre><code>dtAll = dtOne.Copy();\ndtAll.Merge(dtTwo);\n</code></pre>\n"
},
{
"answer_id": 454453,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>dtAll = dtOne.Copy();\ndtAll.Merge(dtTwo,true);\n</code></pre>\n\n<p>The parameter TRUE preserve the changes.</p>\n\n<p>For more details refer to <a href=\"http://msdn.microsoft.com/en-us/library/wkk7s5zk.aspx\" rel=\"nofollow noreferrer\">MSDN</a>.</p>\n"
},
{
"answer_id": 4659253,
"author": "rami220",
"author_id": 571454,
"author_profile": "https://Stackoverflow.com/users/571454",
"pm_score": 1,
"selected": false,
"text": "<pre><code>DataTable dtAll = new DataTable();\nDataTable dt= new DataTable();\nforeach (int id in lst)\n{\n dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable\n}\ndtAll = dt;\n</code></pre>\n"
},
{
"answer_id": 14397873,
"author": "SNag",
"author_id": 979621,
"author_profile": "https://Stackoverflow.com/users/979621",
"pm_score": 5,
"selected": false,
"text": "<p>Instead of <code>dtAll = dtOne.Copy();</code> in <a href=\"https://stackoverflow.com/a/285500/979621\">Jeromy Irvine's answer</a> you can start with an empty <code>DataTable</code> and merge one-by-one iteratively:</p>\n<pre><code>dtAll = new DataTable();\n...\ndtAll.Merge(dtOne);\ndtAll.Merge(dtTwo);\ndtAll.Merge(dtThree);\n...\n</code></pre>\n<p>and so on.</p>\n<p>This technique is useful in a loop where you want to iteratively merge data tables:</p>\n<pre><code>DataTable dtAllItems = new DataTable();\n\nforeach(var item in items)\n{\n DataTable dtItem = getDataTable(item); // some function that returns a data table\n dtAllItems.Merge(dtItem);\n}\n</code></pre>\n"
},
{
"answer_id": 39221823,
"author": "anandd360",
"author_id": 4575768,
"author_profile": "https://Stackoverflow.com/users/4575768",
"pm_score": 0,
"selected": false,
"text": "<p>This is what i did for merging two datatables and bind the final result to the gridview</p>\n\n<pre><code> DataTable dtTemp=new DataTable();\n for (int k = 0; k < GridView2.Rows.Count; k++)\n {\n string roomno = GridView2.Rows[k].Cells[1].Text;\n DataTable dtx = GetRoomDetails(chk, roomno, out msg);\n if (dtx.Rows.Count > 0)\n {\n dtTemp.Merge(dtx);\n dtTemp.AcceptChanges();\n\n }\n }\n</code></pre>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
] |
If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do:
```
dtOne.Merge(dtTwo);
```
Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?
I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:
```
//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);
```
|
The `Merge` method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.
If you want to preserve both of the original tables, you could copy the original first, then merge:
```
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);
```
|
285,477 |
<p>This is something that comes up so often I almost stopped thinking about it but I'm almost certain that I'm not doing this the best way.</p>
<p>The question: Suppose you have the following table</p>
<pre><code>CREATE TABLE TEST_TABLE
(
ID INTEGER,
TEST_VALUE NUMBER,
UPDATED DATE,
FOREIGN_KEY INTEGER
);
</code></pre>
<p>What is the best way to select the TEST_VALUE associated with the most recently updated row where FOREIGN_KEY = 10?</p>
<p><strong>EDIT:</strong> Let's make this more interesting as the answers below simply go with my method of sorting and then selecting the top row. Not bad but for large returns the order by would kill performance. So bonus points: how to do it in a scalable manner (ie without the unnecessary order by).</p>
|
[
{
"answer_id": 285485,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 1,
"selected": false,
"text": "<p>The probably inferior way that I currently go about doing something like this is</p>\n\n<pre><code>SELECT TEST_VALUE\nFROM TEST_TABLE\nWHERE ID = (\n SELECT ID\n FROM (\n SELECT ID\n FROM TEST_TABLE\n WHERE FOREIGN_KEY = 10\n ORDER BY UPDATED DESC\n )\n WHERE ROWNUM = 1\n)\n</code></pre>\n\n<p>but please StackOverflow Geniuses, teach me some tricks</p>\n"
},
{
"answer_id": 285489,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>Either use a sub-query</p>\n\n<pre><code>WHERE updated = (SELECT MAX(updated) ...)\n</code></pre>\n\n<p>or select the TOP 1 record with </p>\n\n<pre><code>ORDER BY updated DESC\n</code></pre>\n\n<p>In Oracle syntax this would be:</p>\n\n<pre><code>SELECT \n * \nFROM \n(\n SELECT * FROM test_table\n ORDER BY updated DESC\n)\nWHERE \n ROWNUM = 1\n</code></pre>\n"
},
{
"answer_id": 285509,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": -1,
"selected": false,
"text": "<pre><code>select test_value\nfrom\n(\n select test_value \n from test_table\n where foreign_key=10\n order by updated desc\n)\nwhere rownum = 1\n</code></pre>\n\n<p>Oracle is smart enough to realize it only needs a single row from the inner select and it will do this efficiently.</p>\n"
},
{
"answer_id": 285519,
"author": "FallenAvatar",
"author_id": 36965,
"author_profile": "https://Stackoverflow.com/users/36965",
"pm_score": -1,
"selected": false,
"text": "<p>wouldn't this work:</p>\n\n<pre><code>SELECT TOP 1 ID\nFROM test_table\nWHERE FOREIGN_KEY = 10\nORDER BY UPDATED DESC\n</code></pre>\n\n<p>no need for a subquery...</p>\n"
},
{
"answer_id": 285577,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 5,
"selected": true,
"text": "<p>Analytic functions are your friends</p>\n\n<pre><code>SQL> select * from test_table;\n\n ID TEST_VALUE UPDATED FOREIGN_KEY\n---------- ---------- --------- -----------\n 1 10 12-NOV-08 10\n 2 20 11-NOV-08 10\n\nSQL> ed\nWrote file afiedt.buf\n\n 1* select * from test_table\nSQL> ed\nWrote file afiedt.buf\n\n 1 select max( test_value ) keep (dense_rank last order by updated)\n 2 from test_table\n 3* where foreign_key = 10\nSQL> /\n\nMAX(TEST_VALUE)KEEP(DENSE_RANKLASTORDERBYUPDATED)\n-------------------------------------------------\n 10\n</code></pre>\n\n<p>You can also extend that to get the information for the entire row</p>\n\n<pre><code>SQL> ed\nWrote file afiedt.buf\n\n 1 select max( id ) keep (dense_rank last order by updated) id,\n 2 max( test_value ) keep (dense_rank last order by updated) test_value\n,\n 3 max( updated) keep (dense_rank last order by updated) updated\n 4 from test_table\n 5* where foreign_key = 10\nSQL> /\n\n ID TEST_VALUE UPDATED\n---------- ---------- ---------\n 1 10 12-NOV-08\n</code></pre>\n\n<p>And analytic approaches are generally pretty darned efficient.</p>\n\n<p>I should also point out that analytic functions are relatively new, so if you are on something earlier than 9.0.1, this may not work. That's not a huge population any more, but there are always a few folks stuck on old versions.</p>\n"
},
{
"answer_id": 285805,
"author": "Gary Myers",
"author_id": 25714,
"author_profile": "https://Stackoverflow.com/users/25714",
"pm_score": 2,
"selected": false,
"text": "<p>Firstly, you will always need to look at all the rows with that foreign key, and find the one with the highest UPDATED value...which means a MAX or ORDER BY.\nThe efficiency of the comparison is partly up to the optimizer, so will depend on your Oracle version. Your data structures may have a greater impact on actual performance though. An index on FOREIGN_KEY, UPDATED DESC, TEST_VALUE would probably give the most scalable solution for querying as Oracle will normally be able to give the answer just accessing a single leaf block. There may be a detrimental impact on inserts as new records have to be inserted into that structure.</p>\n"
},
{
"answer_id": 285858,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 0,
"selected": false,
"text": "<p>Performance will depend on what is indexed.\nHere is a method.</p>\n\n<pre><code>WITH \nten AS\n(\n SELECT *\n FROM TEST_TABLE\n WHERE FOREIGH_KEY = 10\n)\nSELECT TEST_VALUE \nFROM ten\nWHERE UPDATED = \n(\n SELECT MAX(DATE)\n FROM ten\n)\n</code></pre>\n"
},
{
"answer_id": 285875,
"author": "Jason Slocomb",
"author_id": 34895,
"author_profile": "https://Stackoverflow.com/users/34895",
"pm_score": 0,
"selected": false,
"text": "<p>There is an oracle SQL faq here that may help you:</p>\n\n<p><a href=\"http://www.orafaq.com/wiki/SQL_FAQ\" rel=\"nofollow noreferrer\">http://www.orafaq.com/wiki/SQL_FAQ</a></p>\n"
},
{
"answer_id": 287729,
"author": "Paul Morgan",
"author_id": 16322,
"author_profile": "https://Stackoverflow.com/users/16322",
"pm_score": 1,
"selected": false,
"text": "<pre>SELECT TEST_VALUE\n FROM TEST_TABLE\n WHERE UPDATED = ( SELECT MAX(UPDATED)\n FROM TEST_TABLE\n WHERE FOREIGN_KEY = 10 )\n AND FOREIGN-KEY = 10\n AND ROWNUM = 1 -- Just in case records have the same UPDATED date\n</pre>\n\n<p>Rather that take the first record you could break a tie with the hightest ID or maybe least/largest TEST_VALUE.</p>\n\n<p>An index of FOREIGN_KEY, UPDATED would help query performace. </p>\n"
},
{
"answer_id": 28374340,
"author": "aaaantoine",
"author_id": 3466101,
"author_profile": "https://Stackoverflow.com/users/3466101",
"pm_score": 1,
"selected": false,
"text": "<p>Up until I read Justin Cave's answer, I've used the following pattern to grab the most recent records en masse.</p>\n\n<pre><code>WITH test_table_ranked AS (\n SELECT\n test_table.*,\n ROW_NUMBER() OVER (\n PARTITION BY foreign_key ORDER BY updated DESC\n ) AS most_recent\n FROM\n test_table\n)\nSELECT *\nFROM test_table_ranked\nWHERE most_recent = 1\n-- AND foreign_key = 10\n</code></pre>\n\n<p>This query finds the most recent updates for each foreign key in the table. Although Justin's answer is faster when the key is known, this query also works in SQL Server.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
This is something that comes up so often I almost stopped thinking about it but I'm almost certain that I'm not doing this the best way.
The question: Suppose you have the following table
```
CREATE TABLE TEST_TABLE
(
ID INTEGER,
TEST_VALUE NUMBER,
UPDATED DATE,
FOREIGN_KEY INTEGER
);
```
What is the best way to select the TEST\_VALUE associated with the most recently updated row where FOREIGN\_KEY = 10?
**EDIT:** Let's make this more interesting as the answers below simply go with my method of sorting and then selecting the top row. Not bad but for large returns the order by would kill performance. So bonus points: how to do it in a scalable manner (ie without the unnecessary order by).
|
Analytic functions are your friends
```
SQL> select * from test_table;
ID TEST_VALUE UPDATED FOREIGN_KEY
---------- ---------- --------- -----------
1 10 12-NOV-08 10
2 20 11-NOV-08 10
SQL> ed
Wrote file afiedt.buf
1* select * from test_table
SQL> ed
Wrote file afiedt.buf
1 select max( test_value ) keep (dense_rank last order by updated)
2 from test_table
3* where foreign_key = 10
SQL> /
MAX(TEST_VALUE)KEEP(DENSE_RANKLASTORDERBYUPDATED)
-------------------------------------------------
10
```
You can also extend that to get the information for the entire row
```
SQL> ed
Wrote file afiedt.buf
1 select max( id ) keep (dense_rank last order by updated) id,
2 max( test_value ) keep (dense_rank last order by updated) test_value
,
3 max( updated) keep (dense_rank last order by updated) updated
4 from test_table
5* where foreign_key = 10
SQL> /
ID TEST_VALUE UPDATED
---------- ---------- ---------
1 10 12-NOV-08
```
And analytic approaches are generally pretty darned efficient.
I should also point out that analytic functions are relatively new, so if you are on something earlier than 9.0.1, this may not work. That's not a huge population any more, but there are always a few folks stuck on old versions.
|
285,495 |
<p>I am binding an SPGridView to a SPList. As code samples suggest, I am using the following code to create a dataview based on the list. </p>
<pre><code>dim data as DataView = myList.Items.GetDataTable.DefaultView
grid.DataSource = data
etc...
</code></pre>
<p>What I am finding is that the column names in the resulting dataview do not always match the source fields defined in the SPList. For example I have columns named </p>
<ul>
<li>Description </li>
<li>ReportItem</li>
<li><p>ReportStatus</p>
<p>these show up in the resulting dataview with column names like </p></li>
<li>ReportType0</li>
<li>ReportStatus1</li>
</ul>
<p>This leads me to think that I have duplicate field names defined, but that does not seem to be the case.</p>
<p>Seems like I am missing something fundamental here?
Thanks.</p>
|
[
{
"answer_id": 285590,
"author": "Abs",
"author_id": 1245,
"author_profile": "https://Stackoverflow.com/users/1245",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>GetDataTable</code> method is returning the <code>internalName</code> (or <code>staticName</code> -- I can't remember for sure which but they are frequently the same) representation of the columns, rather than the <code>Title</code> representation, which is what you see in the Web interface. I believe <code>GetDataTable</code> does a CAML query under the covers, and you have to use that <code>internalName</code> for field references in CAML.</p>\n\n<p>This <a href=\"http://blog.thekid.me.uk/archive/2007/03/12/wss-columns-specify-internal-name.aspx\" rel=\"nofollow noreferrer\">blog</a> talks about it in a little more detail.</p>\n"
},
{
"answer_id": 470181,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>So I posted about this on my blog, but I wrote a little utility method that you can use, right after you get the data table it basically remaps the column names in the DataTable to their friendly names.</p>\n\n<pre><code>DataTable table = list.GetItems(list.DefaultView).GetDataTable();\nforeach(DataColumn column in table.Columns)\n{\n column.ColumnName = list.Fields.GetFieldByInternalName(column.ColumnName).Title;\n}\n</code></pre>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 843316,
"author": "Johan Leino",
"author_id": 83283,
"author_profile": "https://Stackoverflow.com/users/83283",
"pm_score": 0,
"selected": false,
"text": "<p>What you also could do (if you´re using .NET 3.5) is to use an anonymous type and bind against that. If you´re doing this you might wanna go with a Linq DataSource as well.\nI have made a post that explains this <a href=\"http://johanleino.spaces.live.com/blog/cns!6BE273C70C45B5D1!328.entry\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10552/"
] |
I am binding an SPGridView to a SPList. As code samples suggest, I am using the following code to create a dataview based on the list.
```
dim data as DataView = myList.Items.GetDataTable.DefaultView
grid.DataSource = data
etc...
```
What I am finding is that the column names in the resulting dataview do not always match the source fields defined in the SPList. For example I have columns named
* Description
* ReportItem
* ReportStatus
these show up in the resulting dataview with column names like
* ReportType0
* ReportStatus1
This leads me to think that I have duplicate field names defined, but that does not seem to be the case.
Seems like I am missing something fundamental here?
Thanks.
|
The `GetDataTable` method is returning the `internalName` (or `staticName` -- I can't remember for sure which but they are frequently the same) representation of the columns, rather than the `Title` representation, which is what you see in the Web interface. I believe `GetDataTable` does a CAML query under the covers, and you have to use that `internalName` for field references in CAML.
This [blog](http://blog.thekid.me.uk/archive/2007/03/12/wss-columns-specify-internal-name.aspx) talks about it in a little more detail.
|
285,502 |
<p>This code works in Firefox, Internet Explorer, not in Safari/Chrome:</p>
<pre><code><head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script>
function newDiv() {
var div = $('<div id="divNew" style="width: 50px; height: 50px; border: solid 1px; background: Red"></div>');
$('#divParent').append(div);
div.draggable(
{
containment: 'parent'
});
}
</script>
</head>
<body>
<a href="javascript:;" onclick="newDiv()">new div</a>
<div id="divParent" style="width: 500px; height: 500px; border: solid 1px;"></div>
</body>
</code></pre>
<p>In Safari/Chrome, the divNew can only be moved vertically. jQuery's this feature is currently incompatible? I am using 1.5.2 stable version.It can be found here <a href="http://jquery-ui.googlecode.com/files/jquery.ui-1.5.2.zip" rel="nofollow noreferrer">jQuery 1.5.2</a></p>
|
[
{
"answer_id": 303022,
"author": "Bryan A",
"author_id": 29707,
"author_profile": "https://Stackoverflow.com/users/29707",
"pm_score": 1,
"selected": false,
"text": "<p>Try replacing 'parent' with a dom object... ie, $(\"#divParent\") and see if that works. </p>\n"
},
{
"answer_id": 474619,
"author": "jacobangel",
"author_id": 31318,
"author_profile": "https://Stackoverflow.com/users/31318",
"pm_score": 2,
"selected": false,
"text": "<p>Try wrapping the divParent div with another div,and then setting containment to the div wrapping divParent while injecting it into divParent. This worked for me:</p>\n\n<pre><code> <script>\n function newDiv() {\n var divs = \n $(unescape('%3Cdiv class=\"divNew\" style=\"\"%3E&nbsp;%3C/div%3E'));\n divs.draggable(\n {\n containment: $('#a')\n });\n $('#divParent').append(divs);\n }\n </script>\n</head>\n<body>\n <style>\n .divNew {width: 50px; height: 50px;border: solid 1px; background: Red;}\n #divParent {width: 500px; height: 500px; border: solid 1px;};\n </style>\n <a href=\"javascript:;\" onclick=\"newDiv()\">new div</a>\n <div id=\"a\">\n <div id=\"divParent\" style=\"\"> <!--<div class=\"divNew\"></div>-->\n </div> \n </div>\n</body>\n</code></pre>\n\n<p><strong>EDIT: I just realized this doesn't work completely. You should include a check to see if the browser is webkit based, and then set the container to 1000px instead of 500px. The bug seems to be, obviously, related to calculating the width properly.</strong></p>\n"
},
{
"answer_id": 1328770,
"author": "user162806",
"author_id": 162806,
"author_profile": "https://Stackoverflow.com/users/162806",
"pm_score": 2,
"selected": false,
"text": "<p>I had some kind of similar problem, where my draggable elements were absolutely positionned, and became relatively positionned in Chrome and Safari.\nAdding !important to the style position:absolute made the trick.</p>\n"
},
{
"answer_id": 3864912,
"author": "Marcus",
"author_id": 466973,
"author_profile": "https://Stackoverflow.com/users/466973",
"pm_score": 0,
"selected": false,
"text": "<p>To resolve this problem, you must define WMODE diferent to transparent. I just set the wmode=window and this works fine in all browsers.</p>\n"
},
{
"answer_id": 4332107,
"author": "Anes",
"author_id": 401973,
"author_profile": "https://Stackoverflow.com/users/401973",
"pm_score": 1,
"selected": false,
"text": "<p>Jquery UI Draggable method will not Work in Safari and MAC OS X environment any way. So when write code consider same like:</p>\n\n<pre><code>if(!($browser.safari && navigator.appVersion.indexOf('Mac')!= -1)) {\n $('div.urid').draggable({\n helper: 'clone',\n opacity: 0.4\n });\n}\n</code></pre>\n\n<p>When you implement Drag and Drop pls consider same...</p>\n"
},
{
"answer_id": 5282093,
"author": "anjalis",
"author_id": 656501,
"author_profile": "https://Stackoverflow.com/users/656501",
"pm_score": 4,
"selected": false,
"text": "<p>the solution i found is to set the element <code>position: absolute !important</code>, :))</p>\n"
},
{
"answer_id": 10066296,
"author": "nathanlampe",
"author_id": 1133695,
"author_profile": "https://Stackoverflow.com/users/1133695",
"pm_score": 2,
"selected": false,
"text": "<p>anjalis was right,</p>\n\n<pre><code>position: absolute !important;\n</code></pre>\n\n<p>worked perfectly for me. I was having a small issues of the draggable element slightly popping out of the container when you released and click on the element. it would offset slight. with <code>position: absolute !important</code> and the parent element <code>position: relative;</code> it worked like a charm.</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37122/"
] |
This code works in Firefox, Internet Explorer, not in Safari/Chrome:
```
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script>
function newDiv() {
var div = $('<div id="divNew" style="width: 50px; height: 50px; border: solid 1px; background: Red"></div>');
$('#divParent').append(div);
div.draggable(
{
containment: 'parent'
});
}
</script>
</head>
<body>
<a href="javascript:;" onclick="newDiv()">new div</a>
<div id="divParent" style="width: 500px; height: 500px; border: solid 1px;"></div>
</body>
```
In Safari/Chrome, the divNew can only be moved vertically. jQuery's this feature is currently incompatible? I am using 1.5.2 stable version.It can be found here [jQuery 1.5.2](http://jquery-ui.googlecode.com/files/jquery.ui-1.5.2.zip)
|
the solution i found is to set the element `position: absolute !important`, :))
|
285,517 |
<p>I created a custom login page using Forms Authentication and using a sQL DB to store user data. I am able to create a session variable from the username, but wondering if it is possible to pull a separate field and create a session variable based on that. I would like the session variable to be based off a SalesNumber a 5 digit decimal field. Please give me any comments or suggestions.</p>
<pre><code>cmd = new SqlCommand("Select pwd,SalesNumber from users where uname=@userName", conn);
cmd.Parameters.Add("@userName", System.Data.SqlDbType.VarChar, 25);
cmd.Parameters["@userName"].Value = userName;
Session["userName"] = userName;
</code></pre>
<p>Thanks....</p>
|
[
{
"answer_id": 285588,
"author": "AndreasKnudsen",
"author_id": 36465,
"author_profile": "https://Stackoverflow.com/users/36465",
"pm_score": 2,
"selected": false,
"text": "<p>You could always load it from your code-behind instead of the scriptmanager in \nyour aspx/master. That way the IntelliSense doesn't know it's there. Using ScriptManager.RegisterClientScriptInclude(..).</p>\n"
},
{
"answer_id": 285596,
"author": "z-boss",
"author_id": 28098,
"author_profile": "https://Stackoverflow.com/users/28098",
"pm_score": 1,
"selected": false,
"text": "<p>It could be that third party JavaScript plugin you're using has some errors in it.<br>\nI would check the code in <a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a> and directed this question to the author of the plugin.<br>\nAs for the question itself: I don't think you can exclude it if it's a part of the project, but go over the <a href=\"http://msdn.microsoft.com/en-us/library/hcw1s69b(VS.71).aspx\" rel=\"nofollow noreferrer\">MSDN: Using IntelliSense</a> to prove it.</p>\n"
},
{
"answer_id": 285981,
"author": "Alan Oursland",
"author_id": 37189,
"author_profile": "https://Stackoverflow.com/users/37189",
"pm_score": 4,
"selected": true,
"text": "<p>Service Pack 1 added the following feature:</p>\n\n<p>If you \"anyfile.js\" and \"anyfile-vsdoc.js\" in the same directory, then any references to \"anyfile.js\" will automagically be converted to a reference to \"anyfile-vsdoc.js\" behind the scenes.</p>\n\n<p>Add an empty file next to your plugin with \"-vsdoc\" appended to the filename. That should \"hide\" the plug-in from the external javascript processor.</p>\n"
},
{
"answer_id": 579970,
"author": "kimsk",
"author_id": 58905,
"author_profile": "https://Stackoverflow.com/users/58905",
"pm_score": 1,
"selected": false,
"text": "<p>Since you mentioned jQuery, you could also load the troublesome script during runtime.</p>\n\n<p>$.getScript(\"XXX.js\");</p>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37126/"
] |
I created a custom login page using Forms Authentication and using a sQL DB to store user data. I am able to create a session variable from the username, but wondering if it is possible to pull a separate field and create a session variable based on that. I would like the session variable to be based off a SalesNumber a 5 digit decimal field. Please give me any comments or suggestions.
```
cmd = new SqlCommand("Select pwd,SalesNumber from users where uname=@userName", conn);
cmd.Parameters.Add("@userName", System.Data.SqlDbType.VarChar, 25);
cmd.Parameters["@userName"].Value = userName;
Session["userName"] = userName;
```
Thanks....
|
Service Pack 1 added the following feature:
If you "anyfile.js" and "anyfile-vsdoc.js" in the same directory, then any references to "anyfile.js" will automagically be converted to a reference to "anyfile-vsdoc.js" behind the scenes.
Add an empty file next to your plugin with "-vsdoc" appended to the filename. That should "hide" the plug-in from the external javascript processor.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.