input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Encoding problem using SQLite and WinForms 2.0 C# <p>I am developing a WinForms app using .NET 2.0 and am trying to use SQLite as a DB solution. My main problem is that I have trouble seeing data from the DB in the WinForm when the data is in a non english language (in my case greek).</p>
<p>For db administration purposes I use the <a href="http://sqliteadmin.orbmu2k.de/" rel="nofollow">SQLite administrator</a> which has no trouble at all returning data in greek. But when I load the data in a DataGridView in my form, I get those dreaded "missing character" square symbols. </p>
<p>In order to communicate with the db I use the <a href="http://sqlite.phxsoftware.com/" rel="nofollow">System.Data.SQLite</a> solution.</p>
<p>Is there something I am missing here? I looked for setting the default collation in the database but did not come up with anything, since SQLite does not support collation values like SQL Server (e.g. COLLATE Greek_CI_AS)</p>
<p>Thanks</p>
<p>P.S. I am using SQLite 3 and System.Data.SQLite.dll 1.0.60. The connection string for the test is:
<code>Data Source=test.db;UseUTF8Encoding=True;</code></p>
| <p>Are you retrieving a string, or a byte array from the database? Internally, SQLite uses UTF-8 or UTF-16 strings (depending on which method was used to insert the string into the database) which is what it returns when you get a string value using sqlite3_column_text.</p>
<p>On the other hand, if you ask for a blob, it will just return the underlying bytes, which may not match the character encoding your application is expecting.</p>
<p>I'm not sure how the ADO provider maps on to these underlying operations, but it seems to me that if your text isn't being returned as unicode, or it is but the app is treating it otherwise, that may be where the problem lies.</p>
<p><a href="http://www.sqlite.org/c3ref/column_blob.html" rel="nofollow">http://www.sqlite.org/c3ref/column_blob.html</a></p>
<p><strong>Edit:</strong> While I think of it, try opening your database in <a href="http://sqliteman.com/" rel="nofollow">SQLiteman</a>, to see if there is any difference.</p>
|
Pros and cons of MS Ajax vs. jQuery in an ASP.NET MVC app? <p>Now that RC1 is out I need to decide once and for all whether to use MS Ajax libraries or just jQuery for AJAX requests. The application is a new application. Essentially the way I'll decide is whether or not i get any <strong>significant</strong> benefit from the Microsoft libraries that I wouldn't get from jQuery. I already HAVE jQuery loading and I am concerned about the extra overhead of file size more than anything.</p>
<p>As far as I'm aware -- the only benefit really is that there are helpers like <code>Ajax.BeginForm</code>, but perhaps these will work with jQuery at some point anyway? I was also told today by a government employee friend of mine that MS Ajax library has a LOT of bugs in it - which concerns me.</p>
<p>With Microsoft now having officially <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx">befriended jQuery</a> I wouldn't be too worried about them doing anything in future to leave jQuery in the dust by enhancing their own libraries.</p>
<p>I really don't know a whole lot about exactly what MS Ajax actually does for me. Are there certain pros and cons. Or is it just 90% bloat to support 'update panel' ?</p>
<p>I also find it very interesting that the <a href="http://www.manning.com/palermo/">ASP.NET MVC in Action</a> book just skips over the MS Ajax libraries and jumps straight into jQuery :</p>
<blockquote>
<p>In this chapter the reader will
examine how the ajax technique is
applied to ASP.NET MVC in a more
seamless way than with Web Forms. The
reader will see how to leverage an
increasingly popular, lightweight
javascript library called jQuery.</p>
<p>(from <a href="http://www.manning.com/palermo/palermo_meapch9_sample.pdf">free sample</a> chapter on AJAX)</p>
</blockquote>
<p>Would very much appreciate hearing from anyone about their experiences workin with both, expecially on the following additional questions :</p>
<ul>
<li>is it easy to convert code between the two libraries - assuming relatively simple ajax requirements ? </li>
<li>is debugging notably better or faster in either library</li>
<li>anybody know how ASP.NET 4.0 is progressing and any announced plans for the AJAX library that might be beneficial to MVC?</li>
<li>what in a nutshell could MS AJAX do for an MVC app beyond sending requests and sticking the response in a DIV? </li>
<li>how do i do the equivalent of <code>Ajax.BeginForm(...)</code> and use jQuery ?</li>
<li>what was your deal killer one way or the other?</li>
<li>what are most people out there using?</li>
</ul>
| <p>Personally, I would stick with JQuery. MS AJAX is pretty heavyweight in terms of size and you can do so much with JQuery. As far as whether it is easy to convert code, well it depends on how much of the MS AJAX stuff you are using. I don't think there is really much appreciable difference in debugging from one to the other. You will have a larger community of JQuery users from which to pull resources.</p>
|
What is the PayPal "amount" format in WPS? <p>What is the allowed format for PayPal's Website Payments Standard (WPS) forms in the "amount" field? Must the decimal point be ".", or is it currency-dependant? Must there always be exactly two decimal places, or can there also be three (for currencies that have such small nominations) or none (for currencies that have hyper-inflation)?</p>
<p>I know that this should be a question for PayPal's documentation/forums, but the first has a vast room for improvement (to say the least) and the second is as speedy as a sleeping snail. I have <a href="http://www.paypaldeveloper.com/pdn/board/message?board.id=basicpayments&message.id=33343" rel="nofollow">posted a question</a> there, but I don't expect any replies sooner than about two weeks. Hopefully someone here will have an idea.</p>
| <p>Looks like it's not currency dependent and the API is expecting at most two (2) decimal places with a period separator.</p>
<blockquote>
<p><code>amount</code></p>
<p>[...] Limitations: Value must be a positive number. No currency symbol. Must have two decimal places, decimal separator must be a period (.), and the optional thousands separator must be a comma (,).</p>
</blockquote>
<p><a href="https://cms.paypal.com/us/cgi-bin/?cmd=%5Frender-content&content%5FID=developer/e%5Fhowto%5Fapi%5FButtonMgrAPIIntro">Website Payments Standard Button Manager API Overview</a></p>
|
Trim string in JavaScript? <p>How do I trim a string in JavaScript?</p>
| <p>Since new Browsers (IE9+) have <code>trim()</code> already implemented, you should only implement <code>trim()</code> if it is not already available on the Prototype-Object (overriding it is a huge performance hit). This is generally recommended when extending Native Objects! Note that the added property is enumerable unless you use ES5 <code>Object.defineProperty</code>!</p>
<p>For those browsers who does not support <code>trim()</code>, you can use this polyfill from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim">MDN</a>:</p>
<pre><code>if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
</code></pre>
<hr>
<p>See this:</p>
<pre><code>String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
</code></pre>
|
Java : How to determine the correct charset encoding of a stream <p>With reference to the following thread:
<a href="http://stackoverflow.com/questions/498636/java-app-unable-to-read-iso-8859-1-encoded-file-correctly">http://stackoverflow.com/questions/498636/java-app-unable-to-read-iso-8859-1-encoded-file-correctly</a></p>
<p>What is the best way to programatically determine the correct charset encoding of an inputstream/file ?</p>
<p>I have tried using the following:</p>
<pre><code> File in = new File(args[0]);
InputStreamReader r = new InputStreamReader(new FileInputStream(in));
System.out.println(r.getEncoding());
</code></pre>
<p>But on a file which I know to be encoded with ISO8859_1 the above code yields ASCII, which is not correct, and does not allow me to correctly render the content of the file back to the console.</p>
| <p>You cannot determine the encoding of a arbitrary byte stream. This is the nature of encodings. A encoding means a mapping between a byte value and its representation. So every encoding "could" be the right.</p>
<p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#getEncoding%28%29">getEncoding()</a> method will return the encoding which was set up (read the <a href="http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#getEncoding%28%29">JavaDoc</a>) for the stream. It will not guess the encoding for you.</p>
<p>Some streams tell you which encoding was used to create them: XML, HTML. But not an arbitrary byte stream.</p>
<p>Anyway, you could try to guess an encoding on your own if you have to. Every language has a common frequency for every char. In English the char e appears very often but ê will appear very very seldom. In a ISO-8859-1 stream there are usually no 0x00 chars. But a UTF-16 stream has a lot of them.</p>
<p>Or: you could ask the user. I've already seen applications which present you a snippet of the file in different encodings and ask you to select the "correct" one.</p>
|
Java NIO: Sending large messages quickly leads to truncated packets and data loss <p>I've got this nasty problem where sending multiple, large messages in quick succession from a Java (NIO) server (running Linux) to a client will lead to truncated packets. The messages have to be large and sent very rapidly for the problem to occur. Here's basically what my code is doing (not actual code, but more-or-less what's happening):</p>
<pre><code>//-- setup stuff: --
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
String msg = "A very long message (let's say 20KB)...";
//-- inside loop to handle incoming connections: --
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.socket().setTcpNoDelay(true);
sc.socket().setSendBufferSize(1024*1024);
//-- later, actual sending of messages: --
for (int n=0; n<20; n++){
ByteBuffer bb = encoder.encode(CharBuffer.wrap(msg+'\0'));
sc.write(bb);
bb.rewind();
}
</code></pre>
<p>So, if the packets are long enough and sent as quickly as possible (i.e. in a loop like this with no delay), then on the other end it often comes out something like this:</p>
<pre><code>[COMPLETE PACKET 1]
[COMPLETE PACKET 2]
[COMPLETE PACKET 3]
[START OF PACKET 4][SOME OR ALL OF PACKET 5]
</code></pre>
<p>There is data loss, and the packets start to run together, such that the start of packet 5 (in this example) arrives in the same message as the start of packet 4. It's not just truncating, its running the messages together.</p>
<p>I imagine that this is related to the TCP buffer or "window size", or that the server here is just providing data faster than the OS, or network adapter, or something, can handle it. But how do I check for, and prevent it from happening? If I reduce the length of message per use of sc.write(), but then increase the repetitions, I'll still run into the same problem. It seems to simply be an issue with the amount of data in a short amount of time. I don't see that sc.write() is throwing any exceptions either (I know that in my example above I'm not checking, but have in my tests).</p>
<p>I'd be happy if I could programmatically check if it is not ready for more data yet, and put in a delay, and wait until it is ready. I'm also not sure if "sc.socket().setSendBufferSize(1024*1024);" has any effect, or if I'd need to adjust this on the Linux side of things. Is there a way to really "flush" out a SocketChannel? As a lame workaround, I could try to explicitly force a complete send of anything that is buffered any time I'm trying to send a message of over 10KB, for example (which is not that often in my application). But I don't know of any way to force a send of the buffer (or wait until it has sent). Thanks for any help!</p>
| <p>There are many reasons why sc.write() would not send some or all of the data. You have to check the return value and/or the number of bytes remaining in the buffer.</p>
<pre><code>for (int n=0; n<20; n++){
ByteBuffer bb = encoder.encode(CharBuffer.wrap(msg+'\0'));
if(sc.write(bb) > 0 && bb.remaining() == 0) {
// all data sent
} else {
// could not send all data.
}
bb.rewind();
}
</code></pre>
|
LINQ to SQL - Update to increment a non-primary-key field - thread-safe <p>I have two tables (well, two relevant for this question) :</p>
<p>Bets (holds the bets; Columns : Id, , MessagesPosted, )
Bets_Messages (holds the bets' forum messages; Columns : Id, BetId, )</p>
<p>When I insert a new BetMessage in Bets_Messages I want to update (increment to be precise) the corresponding field in Bets.</p>
<p>In pure T-SQL that would be :</p>
<pre><code>INSERT INTO Bets_Messages (BetId, <bla bla>) VALUES (23, "asfasdfasdf");
UPDATE Bets SET MessagesPosted = MessagesPosted + 1 WHERE Id = 23;
</code></pre>
<p>The above code would work wonderful and it is thread safe; If two threads would make DB calls to it (and for the same Bet ofcourse) the MessagesPosted column would increment nicely since the first UPDATE would put at least a ROWLOCK on it practically serializing the UPDATEs.</p>
<p>However using LINQ to SQL this comes to a more difficult approach: </p>
<pre><code> public void PostMessage(MyProject.Entities.BetMessage betMessageEntity)
{
DatabaseDataContext ctx = GetFreshContext(); // GetFreshContext is a private method that practically initializes a new DataContext
Bets_Message msg = new Bets_Message(betMessageEntity);
ctx.Bets_Messages.InsertOnSubmit(msg);
Bet bet = (from b in ctx.Bets where b.Id == (long)betMessageEntity.BetId select b).Single();
bet.MessagesPosted++;
ctx.SubmitChanges();
}
</code></pre>
<p>Looks nice, huh? Well here's what it will generate : </p>
<pre><code>exec sp_executesql N'INSERT INTO [dbo].[Bets_Messages]([ParentMessageId], [BetsId], [UserId], [Subject], [DisplayXml], [Time], [ReplyDepth], [Text])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)
SELECT CONVERT(BigInt,SCOPE_IDENTITY()) AS [value]',N'@p0 bigint,@p1 bigint,@p2 uniqueidentifier,@p3 nvarchar(6),@p4 nvarchar(114),@p5 datetime2(7),@p6 tinyint,@p7 nvarchar(8)',@p0=NULL,@p1=1,@p2='A0D253AF-6261-49AE-8C11-BA6117EF35C7',@p3=N'aaawww',@p4=N'<m ai="a0d253af-6261-49ae-8c11-ba6117ef35c7" a="AndreiR" s="aaawww" t="2009-01-31T18:04:31.282+02:00">wwwwwaaa</m>',@p5='2009-01-31 18:04:31.2820000',@p6=0,@p7=N'wwwwwaaa'
</code></pre>
<p>(for the BetMessage insert) and for the UPDATE :</p>
<pre><code>exec sp_executesql N'UPDATE [dbo].[Bets]
SET [MessagesPosted] = @p17
WHERE ([Id] = @p0) AND ([UserId] = @p1) AND ([Bets_CategoriesId] = @p2) AND ([Bets_TypesId] = @p3) AND ([TotalSum] = @p4) AND ([TotalBetters] = @p5) AND ([CreateDate] = @p6) AND ([DeadlineDate] = @p7) AND ([ClosedDate] IS NULL) AND ([Bets_StatusesId] = @p8) AND ([LastBetAdded] IS NULL) AND ([Title] = @p9) AND ([ShortDescription] = @p10) AND ([Description] = @p11) AND ([DescriptionPlainText] = @p12) AND ([Version] = @p13) AND ([ReviewedBy] = @p14) AND ([UrlFragment] = @p15) AND ([MessagesPosted] = @p16) AND ([ClosedBy] IS NULL) AND ([OutcomeNumber] IS NULL)',N'@p0 bigint,@p1 uniqueidentifier,@p2 smallint,@p3 tinyint,@p4 money,@p5 int,@p6 datetime2(7),@p7 datetime2(7),@p8 tinyint,@p9 nvarchar(7),@p10 nvarchar(30),@p11 nvarchar(33),@p12 nvarchar(22),@p13 smallint,@p14 uniqueidentifier,@p15 varchar(7),@p16 int,@p17 int',@p0=1,@p1='A0D253AF-6261-49AE-8C11-BA6117EF35C7',@p2=2,@p3=1,@p4=$0.0000,@p5=0,@p6='2008-12-03 00:00:00',@p7='2008-12-31 00:00:00',@p8=2,@p9=N'Pariu 1',@p10=N'Descriere pariu 1 - text chior',@p11=N'Descriere pe larg 1 - html permis',@p12=N'descriere text chior 1',@p13=1,@p14='A0D253AF-6261-49AE-8C11-BA6117EF35C7',@p15='pariu-1',@p16=18,@p17=19
</code></pre>
<p>The problem with the T-SQL generated for the UPDATE is that although seems ok as thread-safety it will probably throw an error in the second thread doing the update on the row instead of waiting for it to finish. Will it?</p>
<p>Here's why I think this.</p>
<p>1st thread does this :</p>
<p>insert the corresponding betMessage,
update the bet row to increment the MessagePosted from 0 to 1</p>
<p>the 2nd thread will do this:</p>
<p>insert it's corresponding betMessage,
update the bet row to increment the MessagePosted from 0 to 1 (it was 0 when it read it). However now it is 1 and the WHERE clause will make it not update since the wHERE clause will evaluate to false. 0 row(s) affected will be sent to the LINQ client and that in turn will throw an exception.</p>
<p>Therefore I will have to write my f*#$ing retry attempt code instead of relying on ROW LOCKs in the SQL Server.</p>
<p>Is there some decent approach that uses LINQ to SQL and <strong>NOT</strong> stored procedures, ad-hoc queries and so on?</p>
<p>Thank you for your patience of reading this long post..</p>
| <p><strong>EDIT</strong>: Actually after rereading your post, I think that the automatic transaction generated by SubmitChanges will already take care of making sure that all of the statements are completed or none are. I was thinking that since you were using the automatically generated id, that you'd do a two-stage update in LINQ, but it seems that SubmitChanges handles it for you.</p>
<p>I'll leave the code below for reference, though I don't think that it's required. The link at the bottom explains about the different ways of accomplishing the transaction.</p>
<p>What you need is a transaction scope to wrap the entire set of inserts/updates in.</p>
<pre><code>using System.Transactions;
public void PostMessage(MyProject.Entities.BetMessage betMessageEntity)
{
using (TransactionScope scope = new TransactionScope()) {
DatabaseDataContext ctx = GetFreshContext();
Bets_Message msg = new Bets_Message(betMessageEntity);
ctx.Bets_Messages.InsertOnSubmit(msg);
ctx.SubmitChanges(); // this is what I thought you did
Bet bet = (from b in ctx.Bets
where b.Id == (long)betMessageEntity.BetId select b)
.Single();
bet.MessagesPosted++;
ctx.SubmitChanges();
scope.Complete();
}
}
</code></pre>
<p>I don't think this will cause automatic promotion to a distributed transaction since all of the commands reuse the same connection in the data context. If it turns out that it does, you can create a transaction on the data context's connection and assign it to the data context's Transaction property. If you do this, though, you'll need to manage and dispose of it yourself.</p>
<p>More info on LINQ2SQL and transactions at <a href="http://msdn.microsoft.com/en-us/library/bb386995.aspx" rel="nofollow">MSDN</a>.</p>
|
Javascript DOM - add form element to newly created appendChild? <p>I have two functions to add and remove table rows that contain a form input element. They both work fine, but I have a problem in that I need to show a Remove button input only on subsequently created table rows. My two function are as as follows:</p>
<pre><code>function addRow(table_id){
var clone;
var rows=document.getElementById(table_id).getElementsByTagName('tr');
var index=rows.length;
var tbo=document.getElementById(table_id).getElementsByTagName('tbody')[0];
clone=rows[index-1].cloneNode(true);
tbo.appendChild(clone);
}
function delRow(table_id,button){
var row = button.parentNode.parentNode;
var tbo = document.getElementById(table_id).getElementsByTagName('tbody')[0];
tbo.removeChild(row);
}
</code></pre>
<p>and the html content is:</p>
<pre><code><form>
<table id="mytab">
<tr>
<td>Upload File <input type="file" name="uploadfile[]" onchange="addRow('mytab')" /> <input name="del_row" type="button" value="Remove Row" onclick="delRow('mytab',this)"/></td>
</tr>
</table>
</form>
</code></pre>
<p>I am by no means a Javascript expert - more of a newbie - so I'm struggling to come up with a solution.</p>
| <p>I'm assuming that you are trying to avoid having the remove button in the first row, but need it there now because you think that to get it in subsequent rows, you need to have it in the row that you are cloning. If, instead, you just insert new HTML for both the upload and delete button inputs in the addRow method you can avoid the clone entirely and it won't matter what your original row contains.</p>
<pre><code>function addRow(table_id){
var table = document.getElementById(table_id);
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
var template = table.rows[0].cells[0].innerHTML;
cell.innerHTML = template + '<input type="button" value="Remove Row"'
+ ' onclick="delRow(\'' + table_id + '\',this);" />'
}
</code></pre>
<p>This still uses the first row as the template, but you can remove the button from it as it is added by appending to the existing text.</p>
|
Using WebClient to get Remote Images Produces Grainy GIFs and Can't Handle PNG+BMP <p>Greetings!</p>
<p>I'm creating a web form prototype (ImageLaoder.aspx) that will return an image so that it may be used like this simple example other Web Forms/web pages:</p>
<pre><code><img src="http://www.mydomain.com/ImageLoader.aspx?i=http://images.mydomain.com/img/a.jpg" />
</code></pre>
<p>So far, it loads JPGs with no problems, however GIFs look "grainy" compared to the orignals and BMPs and PNGs result in the following exception:</p>
<p><strong><em>System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+</em></strong></p>
<p>My code thus far looks like this:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
string l_filePath = Request.QueryString["i"];
System.Drawing.Image l_image = GetImage(l_filePath);
if (l_image != null)
{
System.Drawing.Imaging.ImageFormat l_imageFormat = DetermineImageFormat(l_filePath);
WriteImageAsReponse(l_image, l_imageFormat);
}
}
private System.Drawing.Image GetImage(string filePath)
{
WebClient l_WebClient = new WebClient();
byte[] l_imageBytes = l_WebClient.DownloadData(filePath);
System.Drawing.Image l_image = null;
using (MemoryStream l_MemStream = new MemoryStream(l_imageBytes, 0, l_imageBytes.Length))
{
l_MemStream.Write(l_imageBytes, 0, l_imageBytes.Length);
l_image = System.Drawing.Image.FromStream(l_MemStream, true);
l_MemStream.Close();
}
return l_image;
}
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
if (filePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
return System.Drawing.Imaging.ImageFormat.Jpeg;
else if (filePath.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
return System.Drawing.Imaging.ImageFormat.Gif;
else if (filePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
return System.Drawing.Imaging.ImageFormat.Png;
else
return System.Drawing.Imaging.ImageFormat.Bmp;
}
private void WriteImageAsReponse(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat imageFormat)
{
if (image == null)
return;
System.Drawing.Bitmap l_outputBitMap = new Bitmap(image);
if (imageFormat == System.Drawing.Imaging.ImageFormat.Jpeg)
Response.ContentType = "image/jpg";
else if (imageFormat == System.Drawing.Imaging.ImageFormat.Gif)
Response.ContentType = "image/gif";
else if (imageFormat == System.Drawing.Imaging.ImageFormat.Png)
Response.ContentType = "image/png";
else
Response.ContentType = "image/bmp";
l_outputBitMap.Save(Response.OutputStream, imageFormat);
}
</code></pre>
<p>Any ideas why GIFs are grainy and PNGs and BMPs cause exceptions?</p>
| <p>A few points about your GetImage method:</p>
<ul>
<li>When you use Image.FromStream you shouldn't close (or dispose) the stream</li>
<li>If you're calling Dispose on a stream (with the using statement) you don't need to call Close</li>
<li>You're writing to the stream, but then not "rewinding it" so l_image doesn't actually get any data as far as I can see (unless Image.FromStream resets the position itself). (It could be that the gif/jpg decoders rewind the stream but bmp/png don't, hence the error.)</li>
<li>Why don't you just use the MemoryStream constructor which takes a byte array?</li>
</ul>
<p>In short, I believe your GetImage method can be replaced with:</p>
<pre><code>private Image GetImage(string filePath)
{
WebClient l_WebClient = new WebClient();
byte[] l_imageBytes = l_WebClient.DownloadData(filePath);
MemoryStream l_stream = new MemoryStream(l_imageBytes);
return Image.FromStream(l_stream);
}
</code></pre>
<p>Now, more importantly - why are you loading the image at all? Why don't you just serve the file itself as a response, setting the content type as you're already doing - or possibly just based on the extension? In other words, all of your code would become:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
string filePath = Request.QueryString["i"];
string extension = l_filePath.Substring(l_filePath.LastIndexOf('.') + 1);
Response.ContentType = "image/" + extension;
byte[] data = new WebClient.DownloadData(filePath);
Response.OutputStream.Write(data, 0, data.Length);
Response.End();
}
</code></pre>
<p>A bit more error handling (including "is this a reasonable extension?") would be nice, but other than that I think it's okay. The only benefit of actually loading the image yourself is that you get to validate that it really <em>is</em> an image rather than a virus or something like that.</p>
<p>EDIT: Just out of interest, do you have a good reason why you'd <em>want</em> image requests to go through your server? Why would the web page author write:</p>
<pre><code><img src="http://www.mydomain.com/ImageLoader.aspx?i=http://images.mydomain.com/img/a.jpg" />
</code></pre>
<p>instead of</p>
<pre><code><img src="http://images.mydomain.com/img/a.jpg" />
</code></pre>
<p>There <em>are</em> some reasons why it might be useful, but in many cases it's just a waste.</p>
|
On Linux, is the command-line program mktemp less safe than the C-function mkstemp? <p>Both operations create an empty file and return the filename but mkstemp leaves the file open in exclusive mode and gives you the handle. Is there a safety benefit to the C-function? Does this imply that there is a safety hole in the command-line version?</p>
<p>As an aside, it is interesting that there are several related functions in the C api on Linux and most of them say "Don't use this function" (or similar) in their man page.</p>
| <p>One trick with temporary files in Unix-like operating systems (including Linux and Mac OS) is as soon as you open the file, delete it. You can still access the file, but nobody else can see it or do anything to it, and it will go away as soon as you close the file, even if your program dies a horrible death.</p>
|
How do I specify that a list property's contents are xml serialized, but the property itself should not be respresented in the markup? <p>I've got a class like this:</p>
<pre><code>[XmlRoot("channel")]
public class Channel
{
[XmlElement("title")]
public String Title { get; set; }
[WhatElseGoesHere]
[XmlArrayItem("item")]
public List<Item> Items { get; set; }
}
</code></pre>
<p>My desired output is this:</p>
<pre><code><channel>
<title>The title</title>
<item>{item content}</item>
<item>{item content}</item>
</channel>
</code></pre>
| <p>You could start with xml and work back? Put the desired xml in a file (<code>foo.xml</code>), then:</p>
<pre><code>xsd foo.xml
xsd foo.xsd /classes
notepad foo.cs
</code></pre>
<p>This usually provides <em>an</em> answer - although you can usually do the same thing different ways.</p>
|
Google-Analytics: How do I add an e-mail link as the final step of a goal? <p>I send a confirmation link via e-mail (in multiple places) but it seems Analytics doesn't recognize those clicks (given URL is visited) unless the visit immediate. I am guessing the last part is about session expiration.</p>
<p>How can I define my goal funnel so that confirmation page landings are recognized even after a day or two?</p>
<p>My confirmation URL is in following format:</p>
<pre><code>"http://<domain_name>/confirmation/<10_char_hex_confirmation_code>/"
</code></pre>
| <p>You can't. All the steps of a goal funnel must occur in the same session.</p>
<p>You could always have one goal for signing up (i.e. sending the e-mail), and another goal for the confirmation landing page. Then compare these goal conversions, and you'll get the same story.</p>
|
SQL Server 2005: Nullable Foreign Key Constraint <p>I have a foreign key constraint between tables Sessions and Users. Specifically, Sessions.UID = Users.ID. Sometimes, I want Sessions.UID to be null. Can this be allowed? Any time I try to do this, I get an FK Constraint Violation.</p>
<p>Specifically, I'm inserting a row into Sessions via LINQ. I set the Session.User = null; and I get this error:
<PRE>An attempt was made to remove a relationship between a User and a Session. However, one of the relationship's foreign keys (Session.UID) cannot be set to null.</PRE></p>
<p>However, when I remove the line that nulls the User property, I get this error on my SubmitChanges line:
<PRE>Value cannot be null.
Parameter name: cons</PRE></p>
<p>None of my tables have a field called 'cons', nor is it in my 5,500-line DataContext.designer.cs file, nor is it in the QuickWatch for any of the related objects, so I have no idea what 'cons' is.</p>
<p>In the Database, Session.UID is a nullable int field and User.ID is a non-nullable int. I want to record sessions that may or may not have a UID, and I'd rather do it without disabling constraint on that FK relationship. Is there a way to do this?</p>
| <p>I seemed to remember creating a nullable FK before, so I whipped up a quick test. As you can see below, it is definitely doable (tested on MSSQL 2005).</p>
<p>Script the relevant parts of your tables and constraints and post them so we can troubleshoot further.</p>
<pre><code>CREATE DATABASE [NullableFKTest]
GO
USE [NullableFKTest]
GO
CREATE TABLE OneTable
(
OneId [int] NOT NULL,
CONSTRAINT [PK_OneTable] PRIMARY KEY CLUSTERED
(
[OneId] ASC
)
)
CREATE TABLE ManyTable (ManyId [int] IDENTITY(1,1) NOT NULL, OneId [int] NULL)
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ManyTable_OneTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[ManyTable]') )
ALTER TABLE [dbo].[ManyTable] WITH CHECK ADD CONSTRAINT [FK_ManyTable_OneTable] FOREIGN KEY([OneId])
REFERENCES [dbo].[OneTable] ([OneId])
GO
--let's get a value in here
insert into OneTable(OneId) values(1)
select* from OneTable
--let's try creating a valid relationship to the FK table OneTable
insert into ManyTable(OneId) values (1) --fine
--now, let's try NULL
insert into ManyTable(OneId) values (NULL) --also fine
--how about a non-existent OneTable entry?
insert into ManyTable(OneId) values (5) --BOOM! - FK violation
select* from ManyTable
--1, 1
--2, NULL
--cleanup
ALTER TABLE ManyTable DROP CONSTRAINT FK_ManyTable_OneTable
GO
drop TABLE OneTable
GO
drop TABLE ManyTable
GO
USE [Master]
GO
DROP DATABASE NullableFKTest
</code></pre>
|
What is Important to you in your choice of developer tools? <p>My company sells developer tools. As a developer myself, it is hard not to assume that what is important to me is important to many other developers:</p>
<ol>
<li><p>In our case, the thing we lack the most is time. So, I'm willing to spend money on things like Microsoft Team Foundation Server which integrates well with Visual Studio and handles various aspects of managing a software project in an integrated fashion. And InstallShield Professional, which seems overpriced until I think about how much time it saves me. We arguably spend too much on the latest and greatest computers and monitors. I even built computers for two of us from gaming parts - at one year old they are still faster than a top of the line Dell Precision which we purchased recently (I was too busy to build one at the time).</p></li>
<li><p>I care a lot about performance and efficiency, so I am happy to spend money on tools which help us to build a faster and smaller product.</p></li>
<li><p>I am satisfied with the tools we use with one exception - support. It is amazing to how bad the support can be from some very successful companies.</p></li>
<li><p>I prefer a terse, to the point technical book (K&R C is a great example of what I mean by this) or article to a wordy one.</p></li>
</ol>
<p>So, all of this probably comes across in our product and company:</p>
<ol>
<li><p>We are not embarrassed to charge for our software. We are not the most expensive option, but we are certainly not the least expensive.</p></li>
<li><p>We spend a lot of time on the performance of a feature before we release it. We spent 27 months on V1 of our product - and it did little more than read, write and calculate.</p></li>
<li><p>To make sure that our customers (who are developers) get good support, our developers (including me) take turns providing phone and email support.</p></li>
<li><p>We don't spend time on wordy doc. We have short Welcome / Getting Started / Tutorial sections in our help, but we spend most of our documentation efforts writing terse API reference material and creating samples which address the questions asked most frequently by our customers.</p></li>
</ol>
<p>For each of these subjects, we could arguably do something smarter:</p>
<ol>
<li><p>We could have a less expensive limited version (fewer features and / or less support) or even a free "Express" version with appropriate limitations.</p></li>
<li><p>We could do more features and spend less time honing each of them.</p></li>
<li><p>We could hire a less experienced and less expensive person to do first line support.</p></li>
<li><p>We could spend more time writing wordy documentation or hire a full time documentation person next instead of another developer.</p></li>
</ol>
<h2>What is important to you?</h2>
| <p>If you want to get your software out there you should:</p>
<ul>
<li>Have a fully-featured demo;</li>
<li>Be upfront about pricing. As soon as your website says "Contact us for pricing" I've lost interest;</li>
<li>Be sufficiently cheap that it can be bought without getting approval from the CEO. Look at Jira. Relatively cheap, insanely successful;</li>
<li>Be the best. Eclipse and Netbeans are free and packed with features but when it comes to Java I'll happily pay ~$600 per license for Intellij because it is (imho) way better;</li>
<li>Be justified in cost terms versus the competition. If you're doing a source control tool, how well does it compare to Subversion and relevant plugins (VisualSVN is cheap, TortoiseSVN is free);</li>
<li>Make me more productive and not get in my way (Rational tools get in my way). Another example of this is where software refuses to work because it can't find a license server to talk to. Paranoia about piracy will kill you;</li>
<li>Be designed to help programmers and not designed to be sold to companies (there's a difference).</li>
<li>Be responsive in support and feature requests; and</li>
<li>Have a relatively quick product release cycle. If I'm waiting 2-3 years fo ra major release, sorry I've lost interest and you've lost ground to the competition.</li>
</ul>
|
Is PThread a good choice for multi-platorm C/C++ multi-threading program? <p>Been doing mostly Java and smattering of .NET for last five years and haven't written any significant C or C++ during that time. So have been away from that scene for a while.</p>
<p>If I want to write a C or C++ program today that does some multi-threading and is source code portable across Windows, Mac OS X, and Linux/Unix - is PThread a good choice?</p>
<p>The C or C++ code won't be doing any GUI, so won't need to worry with any of that.</p>
<p>For the Windows platform, I don't want to bring a lot of Unix baggage, though, in terms of unix emulation runtime libraries. Would prefer a PThread API for Windows that is a thin-as-possible wrapper over existing Windows threading APIs.</p>
<p><strong>ADDENDUM EDIT:</strong></p>
<blockquote>
<p>Am leaning toward going with
boost:thread - I also want to be able
to use C++ try/catch exception
handling too. And even though my
program will be rather minimal and not
particularly OOPish, I like to
encapsulate using class and namespace
- as opposed to C disembodied functions.</p>
</blockquote>
| <p>Well, pthreads is the old posix standard for writing threaded programs. Its the lowest level threading routines, so its a good choice for cross-platform threading.</p>
<p>However, there are alternatives:</p>
<ul>
<li><a href="http://www.ddj.com/cpp/184401518">boost::thread</a> - an STL style
threading library </li>
<li>Intel's <a href="http://www.threadingbuildingblocks.org/">Thread
Building Blocks</a> </li>
<li><a href="http://openmp.org/wp/">OpenMP</a> -
both these are a higher-level way of
writing threaded apps without needing
to do any threading calls.</li>
</ul>
<p>As the latter are all fully supported on all platforms, (pthreads requires a bit of compiler settings as its only part of Windows posix subsystem, unless you want to use <a href="http://sourceware.org/pthreads-win32/">Pthreads-w32</a>), then perhaps the latter ones are a better choice. boost::threads are more like a threading library, the other 2 are high-level ways of achieving parallelism without needing to code 'threads', they allow you to write loops that run concurrently automatically (subject to common-sense conditions)</p>
<p>Boost::thread is not a C compatible library though.</p>
<p><strong>edit</strong>: cross-platform abilities of the above:</p>
<blockquote>
<p><a href="http://www.intel.com/cd/software/products/asmo-na/eng/threading/294797.htm#sysreq">Intel TBB is cross-platform</a> (Windows*,
Linux*, and Mac OS* X), supports
32-bit and 64-bit applications and
works with Intel, Microsoft and GNU
compilers.</p>
</blockquote>
<p>OpenMP depends on the compiler you want to use, but GCC and/or Intel <a href="http://openmp.org/wp/openmp-compilers/">compilers have supported</a> OpenMP Windows, Linux and MacOS.</p>
|
Exist any Obj-c library to integration with paypal? <p>I wonder if exist a pre-made objective-c library to work with paypal, including with credit-cards.</p>
<p>My google search not get returns (I look for objective-c paypal)</p>
<p>Also, if exist other librarys for common gateways....</p>
| <p>If you want it to go through your application, however, you could use WebKit to integrate a web view that connects to PayPal. That way, everything can be contained within the application but you would still work with PayPal the way they want you to work with them.</p>
|
What is your personal approach/take on commenting? <h3>Duplicate</h3>
<blockquote>
<p><a href="http://stackoverflow.com/questions/142830/what-are-your-hard-rules-about-commenting-your-code">What are your hard rules about commenting?</a></p>
</blockquote>
<p>A Developer I work with had some things to say about commenting that were interesting to me (see below). What is your personal approach/take on commenting?</p>
<blockquote>
<p>"I don't add comments to code unless
its a simple heading or there's a<br />
platform-bug or a necessary
work-around that isn't obvious. Code
can change and comments may become
misleading. Code should be<br />
self-documenting in its use of
descriptive names and its logical<br />
organization - and its solutions
should be the cleanest/simplest way<br />
to perform a given task. If a
programmer can't tell what a program<br />
does by only reading the code, then
he's not ready to alter it.<br />
Commenting tends to be a crutch for
writing something complex or<br />
non-obvious - my goal is to always
write clean and simple code."</p>
<p>"I think there a few camps when it
comes to commenting, the
enterprisey-type who think they're
writing an API and some grand
code-library that will be used for
generations to come, the
craftsman-like programmer that thinks
code says what it does clearer than a
comment could, and novices that write
verbose/unclear code so as to need to
leave notes to themselves as to why
they did something."</p>
</blockquote>
| <p>There's a tragic flaw with the "self-documenting code" theory. Yes, reading the code will tell you exactly what it <em>is</em> doing. However, the code is incapable of telling you what it's <em>supposed</em> to be doing.</p>
<p>I think it's safe to say that all bugs are caused when code is not doing what it's supposed to be doing :). So if we add some key comments to provide maintainers with enough information to know what a piece of code is supposed to be doing, then we have given them the ability to fix a whole lot of bugs.</p>
<p>That leaves us with the question of how many comments to put in. If you put in too many comments, things become tedious to maintain and the comments will inevitably be out of date with the code. If you put in too few, then they're not particularly useful.</p>
<p>I've found regular comments to be most useful in the following places:</p>
<p>1) A brief description at the top of a .h or .cpp file for a class explaining the purpose of the class. This helps give maintainers a quick overview without having to sift through all of the code.</p>
<p>2) A comment block before the implementation of a non-trivial function explaining the purpose of it and detailing its expected inputs, potential outputs, and any oddities to expect when calling the function. This saves future maintainers from having to decipher entire functions to figure these things out.</p>
<p>Other than that, I tend to comment anything that might appear confusing or odd to someone. For example: "This array is 1 based instead of 0 based because of blah blah".</p>
<p>Well written, well placed comments are invaluable. Bad comments are often worse than no comments. To me, lack of any comments at all indicates laziness and/or arrogance on the part of the author of the code. No matter how obvious it is to you what the code is doing or how fantastic your code is, it's a challenging task to come into a body of code cold and figure out what the heck is going on. Well done comments can make a world of difference getting someone up to speed on existing code.</p>
|
Why would mod_rewrite rewrite twice? <p><a href="http://stackoverflow.com/questions/180007/how-do-configure-optional-or-extraneous-urls">I only recently found out about URL rewriting</a>, so I've still got a lot to learn.</p>
<p>While following the <a href="http://www.easymodrewrite.com/" rel="nofollow">Easy Mod Rewrite</a> tutorial, the results of one of their examples is really confusing me.</p>
<pre><code>RewriteBase /
RewriteRule (.*) index.php?page=$1 [QSA,L]
</code></pre>
<p>Rewrites <strong><code>/home</code></strong> as <strong><code>/index.php?page=index.php&page=home</code></strong>.</p>
<p>I thought the duplicates might have had been caused by something in my host's configs, but a clean install of <a href="http://www.apachefriends.org/en/xampp-windows.html#646" rel="nofollow">XAMPP</a> does the same.</p>
<p>So, does anyone know why this seems to parse twice?</p>
<p>And, to me this seems like, if it's going to do this, it would be an infinite loop -- why does it stop at 2 cycles?</p>
| <p>From Example 1 on <a href="http://web.archive.org/web/20090302114812/http://easymodrewrite.com/notes-last" rel="nofollow">this page</a>, which is part of the tutorial linked in your question:</p>
<blockquote>
<p>Assume you are using a CMS system that rewrites requests for everything to a single index.php script.</p>
<pre><code>RewriteRule ^(.*)$ index.php?PAGE=$1 [L,QSA]
</code></pre>
<p>Yet every time you run that, regardless of which file you request, the PAGE variable always contains "index.php".</p>
<p>Why? You will end up doing two rewrites. Firstly, you request <strong>test.php</strong>. This gets rewritten to <strong>index.php?PAGE=test.php</strong>. A second request is now made for <strong>index.php?PAGE=test.php</strong>. This still matches your rewrite pattern, and in turn gets rewritten to <strong>index.php?PAGE=index.php</strong>.</p>
<p>One solution would be to add a RewriteCond that checks if the file is already "index.php". A better solution that also allows you to keep images and CSS files in the same directory is to use a RewriteCond that checks if the file exists, using -f.</p>
</blockquote>
<hr>
<p><sup>1</sup>the link is to the Internet Archive, since the tutorial website appears to be offline</p>
|
What is the significance of starting constants with 'k'? <p>I'm teaching myself Objective-C and I noticed in a lot of books and examples the use of 'k' and camel-casing in constant definition, e.g. </p>
<pre><code>#define kMyConstant 0
</code></pre>
<p>What is the significance of the 'k'?
Is this unique to Objective-C style, or common to C in general?
Why the deviation from (what I've always thought as a best practice) K_MY_CONSTANT style?</p>
<p>Thanks.</p>
| <p>It was mentioned once before in the SO question, <a href="http://stackoverflow.com/questions/472103/lower-case-k-in-cocoa">Lower case "k" in Cocoa</a>.</p>
<blockquote>
<p>It is a general programming notation
not specific to Objective-C (i.e.
Hungarian Notation) and the "k" stands for "constant".</p>
</blockquote>
<p>If you look at the <a href="http://74.125.95.132/search?q=cache:h1-gASSvV78J:google-styleguide.googlecode.com/svn/trunk/objcguide.xml+constants+with+k+objective-c&hl=en&ct=clnk&cd=6&gl=us&client=firefox-a">Google cache</a> of Google's guidelines for Objective-C you can see that they used to include it in their styleguide:</p>
<blockquote>
<p>Constant names (#defines, enums, const local variables, etc.) should start with a lowercase k and then use mixed case to delimit words, i.e. kInvalidHandle, kWritePerm.</p>
<p>Though a pain to write, they are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names and then trying to explain them through comments. </p>
</blockquote>
<p>But it has since been removed in the <a href="http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml">live version</a> of the document. It should be noted that it goes against the the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html">Official Coding Guidlines for Cocoa</a> from Apple.</p>
|
What's your disaster recovery plan? <p>And what would you recommend for an ASP Net web application, with a not so large SQL server database (around 10Gb)?</p>
<p>I was just wondering, is that a good idea to have an Amazon EC2 instance configured ready to host your app in an emergency?</p>
<p>In this scenario, what would be the best approach to keep the database updated (log shipping? manual backup restore?) and the easiest and fastest way to change the dns settings?</p>
<p>Edit: the acceptable downtime would be something between 4 to 6 hours, thats why i considered using the Amazon ec2 option for its lower cost if compared to renting a secondary server.</p>
| <p><strong>Update</strong> - Just saw your comment. Amazon EC2 with log shipping is definitely the way to go. Don't use mirroring because that normally assumes the other standby database is available. Changing your DNS should not take more than 1/2 hour if you set your TTL to that. That would give you time to integrate any logs that are pending. Might turn on the server once a week or so just to integrate logs that are pending (or less to avoid racking up hourly costs.)</p>
<p><hr /></p>
<p>Your primary hosting location should have redundancy at all levels:</p>
<ul>
<li>Multiple internet connections,</li>
<li>Multiple firewalls set to failover,</li>
<li>Multiple clustered web servers,</li>
<li>Multiple clustered database servers,</li>
<li>If you store files, use a SAN or Amazon S3,</li>
<li>Every server should have some form of RAID depending on the server's purpose,</li>
<li>Every server can have multiple PSUs connected to separate power sources/breakers,</li>
<li>External and internal server monitoring software,</li>
<li>Power generator that automatically turns on when the power goes out, and a backup generator for good measure.</li>
</ul>
<p>That'll keep you running at your primary location in the event of most failure scenarios.</p>
<p>Then have a single server set up at a remote location that is kept updated using log shipping and include it in your deployment script (after your normal production servers are updated...) A colocated server on the other side of the country does nicely for these purposes. To minimize downtime of having to switch to the secondary location keep your TTL on the DNS records as low as you are comfortable.</p>
<p>Of course, so much hardware is going to be steep so you'll need to determine what is worth being down for 1 second, 1 minute, 10 minutes, etc. and adjust accordingly.</p>
|
Two Tables Same Height <p>I want two tables to have the same height. If the left table contain longer text than the right table I want it to be as long as the left table.</p>
<p>This is how it looks now:</p>
<p><img src="http://i.stack.imgur.com/aCoOR.png" alt="enter image description here"></p>
<p>I can't set the height because that would limit how much text you can write...</p>
<p>This is how I want it:</p>
<p><img src="http://i.stack.imgur.com/Ah1iS.png" alt="enter image description here"></p>
<p>Code:</p>
<pre><code><table cellspacing="0" width="30%" align="left" class="rowA">
<tr>
<td>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam, eaque ipsa
quae ab illo inventore veritatis et quasi architecto beatae vitae dicta
sunt explicabo. "Sed ut perspiciatis unde omnis iste natus error sit
voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque
ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae
dicta sunt explicabo.
</td>
</tr>
</table>
<table cellspacing="0" width="70%" align="right" class="rowB">
<tr>
<td>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
</td>
</tr>
</table>
</code></pre>
| <p>Can you use two side-by-side cells instead?</p>
<pre><code><table>
<tr>
<td style="width: 30%">Left Column</td>
<td style="width: 70%">Right Column</td>
</tr>
</table>
</code></pre>
<p><strong>Edit</strong> - Just for completeness... if there is a technical reason someone HAS to use two separate containers such as divs or tables but you need them to be the same height, there is a <a href="http://www.filamentgroup.com/lab/setting_equal_heights_with_jquery/" rel="nofollow">small jQuery script</a> that does just that which degrades nicely. It determines the tallest container then sets the other's min-height attribute to match.</p>
|
How do you encourage end users to fill out trouble tickets? <p>So, I work in a fairly small IT section. We have a trouble ticketing system that about half of our end users use. Some of my coworkers don't really do much to encourage our end users to use the system we have in place. The end result? Constant interruptions because end users will get us by IM or come to our offices directly for trivial things. This can obviously make it difficult to do a good job of writing code.</p>
<p>Now, I suppose I could just say "hey, would you mind filling out a trouble ticket next time?", but then I'd come off as the bad guy because others won't do that. I also don't want end users to feel that I'm unapproachable. I just want them to understand that there's a proper way to ask for help.</p>
<p>So what's the best thing for me to do in a situation like this?</p>
| <p><strong>Make it appealing to do so.</strong> </p>
<p>Mention to the user that issues with trouble tickets are viewed by the entire development team and have been found to get fixed significantly faster. Say that anything without a ticket has the potential to get lost in the shuffle. Provide them outward facing links so they can view the progress and developer/support comments on their ticket. Provide email alerts so they feel like they are part of the process and have instant information about their issue.</p>
<p><strong>Make it as frictionless as possible.</strong></p>
<p>Make the user entry part of the system as easy to use and as intuitive as possible. No one likes filling out tickets and I'm <em>certainly</em> not going to jump through any hoops to do so. No logins, no sign-ins, just type out my issue and contact information and go.</p>
<p><strong>Talk with your team.</strong></p>
<p>Ultimately, no amount of hard work on the above systems is going to matter unless your team and you are on the same page. Call for a team meeting and talk with them about the issue. With your boss present, try and put it in terms he can understand. Mention valuable time lost, issues tracking customer problems which aren't in the system, etc, etc.</p>
|
Why does backtracking make an algorithm non-deterministic? <p>So I've had at least two professors mention that backtracking makes an algorithm non-deterministic without giving too much explanation into why that is. I <em>think</em> I understand how this happens, but I have trouble putting it into words. Could somebody give me a concise explanation of the reason for this?</p>
| <p>It's not so much the case that backtracking makes an algorithm non-deterministic.</p>
<p>Rather, you usually need backtracking to process a non-deterministic algorithm, since (by the definition of non-deterministic) you don't know which path to take at a particular time in your processing, but instead you must try several.</p>
|
Timezone considerations in sql server <p>I'm using an sql server 2005 hosted in the states. Soon we will move the db to Europe.
I'd like to update the dates in the db to take into account the timezone difference.
Is there a good way to do this?
Or is it just a case of looping through the dates and adding the timezone offset?</p>
| <p>Does it really need to change because it was physically moved? If you're supporting global applications I would store all my date/time information in GMT and translate to local on the client side.</p>
|
Dynamic Properties for object instances? <p>After the previous question "What are the important rules in Object Model Design", now I want to ask this: </p>
<p><strong>Is there any way to have dynamic properties for class instances?</strong></p>
<p>Suppose that we have this schematic object model:</p>
<p><img src="http://i.stack.imgur.com/EAwrg.gif" alt="object model"></p>
<p>So, each object could have lots of properties due to the set of implemented Interfaces, and then become relatively heavy object. Creating all the possible -and of course reasonable- object can be a way for solving this problem *(i.e. Pipe_Designed v.s. Pipe_Designed_NeedInspection)*, but I have a large number of interfaces by now, that make it difficult.
I wonder if there is a way to have dynamic properties, something like the following dialog to allow the end user to select available functionalities for his/hers new object.</p>
<p><img src="http://i.stack.imgur.com/9L9nz.gif" alt="dialog"></p>
| <p>What you want is <code>Properties pattern</code>. Check out long and boring but clever article from <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html" rel="nofollow">Steve Yegge on this</a></p>
|
In C++/CLI, what does the hat character ^ do? <p>I was reading Ivor Horton's Beginning Visual C++ 2008 and many of its CLR examples have this definition for main:</p>
<pre><code>int main(array<System::String ^> ^args)
</code></pre>
<p>I went back, page by page, to the beginning of the book to find the first such instance with an explanation what it really means, but couldn't find one.</p>
<p>Obviously it means the same as the standard <code>int main(int argc, char *argv[])</code>, but I'd like to know when and why that <code>^</code> is really used, and why it even exists (does it do something that pointers <code>*</code> and references <code>&</code> cannot represent)?</p>
| <p>It's a managed pointer - while * marks a pointer to an object that is unmanaged, ^ points to a garbage collected object (handled by the framework). Read <a href="http://msdn.microsoft.com/en-us/library/cxx6f46y.aspx">this</a> for more information about the way pointers are handled in .NET.</p>
|
How do Django model fields work? <p>First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) :</p>
<pre><code>
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
# Note use of django.utils.encoding.smart_str() here because
# first_name and last_name will be unicode strings.
return smart_str('%s %s' % (self.first_name, self.last_name))
</code></pre>
<p>By my understanding of python , first_name and last_name are class variables , right ? How is that used in code ( because I guess that setting Person.first_name or Person.last_name will affect all Person instances ) ? Why is it used that way ?</p>
| <p>The essence of your question is "how come these class variables (which I assign Field objects to) suddenly become instance variables (which I assign data to) in Django's ORM"? The answer to that is the magic of Python <a href="http://docs.python.org/reference/datamodel.html">metaclasses</a>.</p>
<p>A metaclass allows you to hook into and modify the process of creating a Python class (not the creation of an instance of that class, the creation of the class itself).</p>
<p>Django's Model object (and thus also your models, which are subclasses) has a <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py">ModelBase metaclass</a>. It looks through all the class attributes of your model, and any that are instances of a Field subclass it moves into a fields list. That list is assigned as an attribute of the <code>_meta</code> object, which is a class attribute of the model. Thus you can always get to the actual Field objects via <code>MyModel._meta.fields</code>, or <code>MyModel._meta.get_field('field_name')</code>.</p>
<p>The <code>Model.__init__</code> method is then able to use the <code>_meta.fields</code> list to determine what instance attributes should be initialized when a model instance is created.</p>
<p>Don't be afraid to dive into the Django source code; it's a great source of education!</p>
|
Mvc Release Candidate "File" ActionResult <p>K... I'm doing something obviously wrong. I have a simple page with a file input control on and a submit button. I'm trying out the new "File" ActionResult that was released with the Mvc RC...</p>
<p>All, I want to happen is when the submit button is clicked the selected file is uploaded to the database. This all works fine...</p>
<p>Then, after the page refreshes I want a image to display the resulting image that was uploaded. The issue, is that the image is not rendering... I get the broken image...</p>
<p>This is the portion that is getting the file and sending it back to the view...</p>
<pre><code> var a = Helper.Service.GetAttachmentById(id, MembershipProvider.SecurityTicket);
if (a == null)
{
return View(new ImagePlaceHolderViewData(new { Id = id }));
}
return View(new ImagePlaceHolderViewData(new { Id = a.Id, Image = a, FileContent = File(a.Data, a.ContentType) }));
</code></pre>
<p>Then in the view I have a image tag like so...</p>
<pre><code><img src="<%=Model.FileContent.FileContents %>" />
</code></pre>
<p>I have also tried...</p>
<pre><code><img src="<%=Model.FileContent%>" />
</code></pre>
<p>Thoughts..??</p>
| <p>FileResult returns the ASCII or binary contents of the file. When you say do the following:</p>
<pre><code><img src="<%=Model.FileContent.FileContents %>" />
</code></pre>
<p>You are attempting to push the binary image data into the <code>src</code> attribute. That will never work, because the <code>src</code> must a URL or a path to an image.</p>
<p>There are several ways of doing what you want, and the most correct solution in this case, would be to create a new controller that returns the binary data like you are attempting, and then you set the <code>src</code> attribute to be the path to correct action on your new controller. E.g:</p>
<pre><code><img src="/image/result/12345" />
</code></pre>
<p>This points to the following (really simple and incomplete) example controller:</p>
<pre><code>public class ImageController : Controller
{
public ActionResult Result(int resultID)
{
// Do stuff here...
return File(..);
}
}
</code></pre>
<p>Note that the name I chose for the action is most likely not any good, but it serves its purpose as an example. Hope this was helpful.</p>
|
MySQL NOT LIKE query not working <p>I have 2 tables:</p>
<ul>
<li>posts</li>
<li>tags</li>
</ul>
<p>Tags table is structured like this:</p>
<ul>
<li>post_id</li>
<li>tag</li>
</ul>
<p>So for every tag that's given for a post, I create a record in the tags table. If a post has 10 tags, there will be 10 records in tags table with that post_id.</p>
<p>I'm now trying to build a search page where users can do a search for posts where tags do not contain the given keywords. This creates a problem though. A query like:</p>
<pre><code>SELECT DISTINCT posts.id, posts.title, posts.content
FROM jobs, tags
WHERE tags.tag NOT LIKE '%$keywords%' AND posts.id=tags.post_id
</code></pre>
<p>doesn't work because if a post has got 6 tags and one of them has got the keyword, it will still be returned because the other 5 records in the tags table don't have that keyword.</p>
<p>What's the best way to solve this? Any way other than creating a new column in the posts table which stores all the comma-separated tags used only for search??</p>
| <p>Make sure you have indexes or this will perform very badly:</p>
<pre><code>SELECT posts.id, posts.title, posts.content
FROM posts
WHERE NOT EXISTS (
SELECT post_id from tags
WHERE tags.tag LIKE '%$keywords%'
AND posts.id=tags.post_id
)
</code></pre>
<p>This gets a list of all posts, excluding those that have a tag matching the tag you specified. (Your orginal query referenced a 'jobs' table. I assumed that was a typo for 'posts'.)</p>
<p><a href="http://www.brainbell.com/tutors/php/php_mysql/Table_aliases_in_SQL_queries.html" rel="nofollow">Table aliases</a> make this a little cleaner:</p>
<pre><code>SELECT p.id, p.title, p.content
FROM posts p
WHERE NOT EXISTS (
SELECT t.post_id from tags t
WHERE t.tag LIKE '%$keywords%'
AND p.id=t.post_id
)
</code></pre>
<p>Then, I'd create these indexes:</p>
<pre><code>Posts: id, tag_id
Tags: post_id, tag
</code></pre>
<p>Then, run your query with '<a href="http://dev.mysql.com/doc/refman/5.1/en/explain.html" rel="nofollow">explain</a>' to see if it's performing well. Update your question with the results and someone will offer further advice. Index tuning is more trial and error than anything else so testing really is necessary.</p>
|
How to efficiently implement an event loop? <p><strong>COM Object</strong> (Server) sends <strong>event notification</strong> successfully to <strong>COM Client</strong></p>
<p><strong>Without:</strong></p>
<ul>
<li>ATL</li>
<li>MFC</li>
</ul>
<p>How to efficiently get the <strong>main thread</strong> to <strong>wait/sleep</strong> (infinitely) until <strong>COM Server</strong> notifies the <strong>COM Client</strong> of a particular <strong>event</strong>?</p>
| <p>With event objects.</p>
<p>The main thread calls CreateEvent() in its initialisation to create an auto-reset event object.</p>
<p>The main thread then enters an event loop in which it calls MsgWaitForMultipleObjects() repeatedly. (<a href="http://sarathc.wordpress.com/2008/09/19/when-and-how-should-we-use-msgwaitformultipleobjects/" rel="nofollow">here</a> is an example of a message loop.)</p>
<p>And you generally <em>do</em> need to check for window messages, even if the main thread has no GUI.</p>
<p>In the client thread (the one that creates the sink object) call SetEvent() within the sink method, after any necessary state update. This will wake up the main thread.</p>
<p>And read <a href="http://msdn.microsoft.com/en-us/library/ms809971.aspx" rel="nofollow">this</a> and <a href="http://blogs.msdn.com/oldnewthing/archive/2005/02/17/375307.aspx" rel="nofollow">this</a>, if you haven't already.</p>
|
How do I convert a decimal to an int in C#? <p>How do I convert a decimal to an int?</p>
| <p>Use <code>Convert.ToInt32</code> from <code>mscorlib</code> as in</p>
<pre><code>decimal value = 3.14m;
int n = Convert.ToInt32(value);
</code></pre>
<p>See <a href="http://msdn.microsoft.com/en-us/library/93kx4xke.aspx">MSDN</a>. You can also use <code>Decimal.ToInt32</code>. Again, see <a href="http://msdn.microsoft.com/en-us/library/system.decimal.toint32.aspx">MSDN</a>. Finally, you can do a direct cast as in</p>
<pre><code>decimal value = 3.14m;
int n = (int) value;
</code></pre>
<p>which uses the explicit cast operator. See <a href="http://msdn.microsoft.com/en-us/library/zf02hx8s.aspx">MSDN</a>.</p>
|
Windows equivalent of the Mac OS X âopenâ command <p>Liu Chang asked a very similar question to this one here, <a href="http://stackoverflow.com/questions/264395/linux-equivalent-of-the-mac-os-x-open-command">http://stackoverflow.com/questions/264395/linux-equivalent-of-the-mac-os-x-open-command</a>.</p>
<p>Is there a windows equivalent for the Mac OS X "open" command. I'm trying to run a profiler that will open it's results, but it's looking for the "open" command. Basically, the command needs to open a file from the command prompt as if it were double-clicked on in explorer.</p>
| <p>The closest thing available is <code>start</code>.</p>
|
format date in c# <p>How can I format a date as <code>dd/mm/yyyy</code> or <code>mm/dd/yy</code> ? </p>
<p>Like in VB <code>format("dd/mm/yy",now)</code></p>
<p>How can I do this in C#?</p>
| <p>It's almost the same, simply use the <code>DateTime.ToString()</code> method, e.g:</p>
<pre><code>DateTime.Now.ToString("dd/MM/yy");
</code></pre>
<p>Or:</p>
<pre><code>DateTime dt = GetDate(); // GetDate() returns some date
dt.ToString("dd/MM/yy");
</code></pre>
<p>In addition, you might want to consider using one of the predefined date/time formats, e.g:</p>
<pre><code>DateTime.Now.ToString("g");
// returns "02/01/2009 9:07 PM" for en-US
// or "01.02.2009 21:07" for de-CH
</code></pre>
<p>These ensure that the format will be correct, independent of the current locale settings. </p>
<p>Check the following MSDN pages for more information</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx">DateTime.ToString() method</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx">Standard Date and Time Format Strings</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx">Custom Date and Time Format Strings</a></li>
</ul>
<hr>
<p>Some additional, related information:</p>
<p>If you want to display a date in a specific locale / culture, then there is an overload of the <code>ToString()</code> method that takes an <code>IFormatProvider</code>:</p>
<pre><code>DateTime dt = GetDate();
dt.ToString("g", new CultureInfo("en-US")); // returns "5/26/2009 10:39 PM"
dt.ToString("g", new CultureInfo("de-CH")); // returns "26.05.2009 22:39"
</code></pre>
<p>Or alternatively, you can set the <code>CultureInfo</code> of the current thread prior to formatting a date:</p>
<pre><code>Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
dt.ToString("g"); // returns "5/26/2009 10:39 PM"
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-CH");
dt.ToString("g"); // returns "26.05.2009 22:39"
</code></pre>
|
How to rename XIB/NIB files in Xcode 3? <p>How do I rename XIB/NIB files in Xcode? There is no "Refactor" option, and right clicking and choosing "Rename" does not work correctly.</p>
| <p>The configuration file <code>Info.plist</code> contains the name of the main XIB file. Changing the relevant property to match the new name should fix your issue.</p>
|
Extending borders <p>I have an image that will be centered (left and right) in the window, there is no left border,but there is a right border. I was wondering if it is possible for the top border to go from the very left of the page (past the image) and stop at the right border and for the bottom border to start at the left end of the image and stretch across all the way to the right of the window. The top and bottom borders are made of two different repeating backgrounds and the left border can be too, if needed.</p>
<p>I've been thinking about this for a while but couldn't come up with any solutions...can someone help me?</p>
| <p>You might want to clarify how flexible you're willing to be. You can approach this multiple ways. Do you want the top and bottom borders to extend to the edge of the viewport (thus needing them to be fluid-width)?</p>
<p>You can handle this using background images with <code>background-position</code> and a sliding door technique, or you can use extraneous markup to create a three-column fluid width layout with your image in the center.</p>
<p>It is up to you but with the three-column technique, you could insert your extra <code>divs</code> (or whatever you would like to use) via JavaScript so you wouldn't have empty containers in your source, and use <code>border-top</code> and <code>border-bottom</code> instead of background images (thus shedding some load-time off of the page).</p>
<p><em>Edit:</em> And to clarify, you want it to look something like this Ascii drawing:</p>
<pre><code>_______________
|img|_____________________
</code></pre>
<p><em>Edit</em>: For the fluid width layout, consult one of many numerous sources on CSS Layouts, here's a good rundown:
<a href="http://www.smashingmagazine.com/2007/01/12/free-css-layouts-and-templates/" rel="nofollow">http://www.smashingmagazine.com/2007/01/12/free-css-layouts-and-templates/</a> </p>
<p>Then on your left and right columns, you would do <code>border-top</code> and <code>border-bottom</code> respectively (or use background-images if you want fancier borders), give your image borders and have the height of your three containers set so the borders line up together. Hope that helps.</p>
|
Post/Redirect/Get: Redirect to specific route <p>I have the following scenario:</p>
<p>I have an edit page, which can be called from different pages. These pages could be the detail view for the current entity, or the list view for the entities (with or without a search in the route).</p>
<p>HOW do I cleanly redirect to the original calling page using the MVC framework? Of course I could simply pass the HttpContext.Request.Url value by holding it in my TempData, but that sort of smells, in my eyes (or, err, nose). It's on a lower level than the rest of the code.</p>
<p>Is there a way to get the routevalues for the previous page in a controller context? If I have that, I could store that temporarily and pass that to the redirect.</p>
| <p><a href="http://blogs.teamb.com/craigstuntz/2009/01/23/37947/" rel="nofollow">Do not use TempData when not redirecting.</a> One AJAX request from your edit page, and the TempData will go away.</p>
<p>Tomas is right that a hidden element or query string parameter is the way to go. But make sure you sanitize the value submitted. You don't want to redirect any old site on the web; you need to ensure that the page to which you redirect is part of your sites.</p>
|
Simple simulations for Physics in Python? <p>I would like to know similar, concrete simulations, as the simulation about watering a field <a href="http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame">here</a>.</p>
<p>What is your favorite library/internet page for such simulations in Python?</p>
<p>I know little Simpy, Numpy and Pygame. I would like to get examples about them.</p>
| <p>If you are looking for some <em>game</em> physics (collisions, deformations, gravity, etc.) which <em>looks</em> real and is reasonably <em>fast</em> consider re-using some <em>physics engine</em> libraries.</p>
<p>As a first reference, you may want to look into <a href="http://www.pymunk.org/" rel="nofollow">pymunk</a>, a Python wrapper of <a href="http://wiki.slembcke.net/main/published/Chipmunk" rel="nofollow">Chipmunk</a> 2D physics library. You can find a list of various Open Source physics engines (2D and 3D) in Wikipedia.</p>
<p>If you are looking for <em>physically correct</em> simulations, no matter what language you want to use, it will be much <em>slower</em> (almost never real-time), and you need to use some <em>numerical analysis</em> software (and probably to write something yourself). Exact answer depends on the problem you want to solve. It is a fairly complicated field (of math).</p>
<p>For example, if you need to do simulations in continuum mechanics or electromagnetism, you probably need Finite Difference, Finite Volume or Finite Element methods. For Python, there are some ready-to-use libraries, for example: <a href="http://www.ctcms.nist.gov/fipy/" rel="nofollow">FiPy</a> (FVM), <a href="http://home.gna.org/getfem/" rel="nofollow">GetFem++</a> (FEM), <a href="http://www.fenics.org/wiki/FEniCS_Project" rel="nofollow">FEniCS/DOLFIN</a> (FEM), and some other.</p>
|
WebForm_PostBackOptions documentation <p>Is there any documentation on the parameters to WebForm_PostBackOptions? I can't find anything by Googling.</p>
| <p>There is no official documentation on this. However if you look at the javascript source code you will see this:</p>
<pre><code>function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit)
</code></pre>
<p>I think the parameter names are quite self-explanatory.</p>
|
Bind to a method in WPF? <p>How do you bind to an objects method in this scenario in WPF?</p>
<pre class="lang-cs prettyprint-override"><code>public class RootObject
{
public string Name { get; }
public ObservableCollection<ChildObject> GetChildren() {...}
}
public class ChildObject
{
public string Name { get; }
}
</code></pre>
<p>XAML:</p>
<pre><code><TreeView ItemsSource="some list of RootObjects">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type data:RootObject}"
ItemsSource="???">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type data:ChildObject}">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</code></pre>
<p>Here I want to bind to the <code>GetChildren</code> method on each <code>RootObject</code> of the tree.</p>
<p><strong>EDIT</strong> Binding to an <code>ObjectDataProvider</code> doesn't seem to work because I'm binding to a list of items, and the <code>ObjectDataProvider</code> needs either a static method, or it creates it's own instance and uses that.</p>
<p>For example, using Matt's answer I get:</p>
<blockquote>
<p>System.Windows.Data Error: 33 : ObjectDataProvider cannot create object; Type='RootObject'; Error='Wrong parameters for constructor.'</p>
<p>System.Windows.Data Error: 34 : ObjectDataProvider: Failure trying to invoke method on type; Method='GetChildren'; Type='RootObject'; Error='The specified member cannot be invoked on target.' TargetException:'System.Reflection.TargetException: Non-static method requires a target.</p>
</blockquote>
| <p>Another approach that might work for you is to create a custom <a href="http://msdn.microsoft.com/en-us/library/ms613620.aspx"><code>IValueConverter</code></a> that takes a method name as a parameter, so that it would be used like this:</p>
<pre><code>ItemsSource="{Binding
Converter={StaticResource MethodToValueConverter},
ConverterParameter='GetChildren'}"
</code></pre>
<p>This converter would find and invoke the method using reflection. This requires the method to not have any arguments.</p>
<p>Here's an example of such a converter's source:</p>
<pre class="lang-c# prettyprint-override"><code>public sealed class MethodToValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var methodName = parameter as string;
if (value==null || methodName==null)
return value;
var methodInfo = value.GetType().GetMethod(methodName, new Type[0]);
if (methodInfo==null)
return value;
return methodInfo.Invoke(value, new object[0]);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("MethodToValueConverter can only be used for one way conversion.");
}
}
</code></pre>
<p>And a corresponding unit test:</p>
<pre class="lang-c# prettyprint-override"><code>[Test]
public void Convert()
{
var converter = new MethodToValueConverter();
Assert.AreEqual("1234", converter.Convert(1234, typeof(string), "ToString", null));
Assert.AreEqual("ABCD", converter.Convert(" ABCD ", typeof(string), "Trim", null));
Assert.IsNull(converter.Convert(null, typeof(string), "ToString", null));
Assert.AreEqual("Pineapple", converter.Convert("Pineapple", typeof(string), "InvalidMethodName", null));
}
</code></pre>
<p>Note that this converter does not enforce the <code>targetType</code> parameter.</p>
|
How do I implement a generic stack in C#? <p>I'm using Visual C# to program an RPN calculator using Stack. Problem is I don't know how to do this. I'm using System.Collections.Generic, but</p>
<pre><code>Stack<double> s = new Stack<double>();
</code></pre>
<p>generates the error:</p>
<blockquote>
<p>Using the generic type 'System.Collections.Generic.Stack' requires '1' type arguments</p>
</blockquote>
<p>I'm pretty clueless here. Thanks for the help.</p>
| <p>Try this</p>
<pre><code>Stack<int> s = new Stack<int>();
</code></pre>
<p>Replace int with whatever type you are storing in the stack. </p>
|
Equivalent code in jQuery when integrating another library <p>I am using <a href="http://en.wikipedia.org/wiki/MooTools" rel="nofollow">MooTools</a> 1.11 and <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow">jQuery</a> 1.2. The Ajax function is not working properly for the following code.</p>
<pre><code>jQuery(document).ready(function($) {
confirm("Hello");
function confirm(message){
$.ajax({
url: 'ajax.php',
....
});
}
});
</code></pre>
<p>What modification should I do to execute the Ajax function correctly?</p>
| <p><a href="http://www.tizag.com/javascriptT/javascriptconfirm.php" rel="nofollow"><code>confirm</code></a> is a built-in function (a reserved name)... try using a different name for it.</p>
|
Passing "const" variable to method in Java <p>Is there an equivalent in Java to the passing on const references in C++?<br>
Isn't leaving out the "constness" misleading in regard to the method signature?</p>
| <p>No, there isn't.</p>
<p>Java "final" is not an exact equivalent of C++ "const". The following (delayed initialization of a final variable) works in Java:</p>
<pre><code>final double x;
int w = 1;
if (w > 2)
{
x = 0.5;
}
else
{
x = - 0.5;
}
</code></pre>
<p>but it doesn't work in C++ with "final" replaced by "const".</p>
<p>Using "final" on a variable in the method declaration can be useful in Java, because allows you to use this variable inside any anonymous class created inside your method.</p>
<p>PS. I was first disappointed by the lack of "const" in Java but later learned to live with "final".</p>
<p>PS2. The Java glossary (<a href="http://mindprod.com/jgloss/immutable.html">http://mindprod.com/jgloss/immutable.html</a>) linked to in this thread has one thing wrong: no, you are not given a 100% guaranntee that the final variable doesn't change its value:</p>
<p>1) it changes from "undefined" to "defined", but the compiler will tell you if you reference it before initialization</p>
<p>2) on Linux, a double has 80-bit precision when stored in a register, but 64-bit when stored in memory. When a final double variable is pushed out of the register, it will be truncated and change its value. As Joel Spolsky says, "abstraction has sprung a leak".</p>
|
sharing asp session over virtual directory <p>In IIS I have asp (classic) site. In that site there is virtual directory. Is there any way to share session between those two web applications?</p>
<p>tnx</p>
| <p>It's possible, but real complicated. Basically, you'll have to make the Session state save in a database rather than in memory. When it's in memory, it'll be scoped to the web application but if you have it in a database, both applications should be able to read it. Here's an article about sharing sessions between asp and asp.net sites. The concept should be the same because they'll be in different web applications:
<a href="http://msdn.microsoft.com/en-us/library/aa479313.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa479313.aspx</a></p>
|
CSS word-wrapping in div <p>I have a div with a width of 250px. When the innertext is wider than that i want it to break down. The div is float: left and now has an overflow. I want the scrollbar to go away by using word-wrapping. How can i achieve this?</p>
<pre><code><div id="Treeview">
<div id="HandboekBox">
<div id="HandboekTitel">
<asp:Label ID="lblManual" runat="server"></asp:Label>
</div>
<div id="HandboekClose">
<asp:ImageButton ID="btnCloseManual" runat="server"
ImageUrl="Graphics/close.png" onclick="btnCloseManual_Click"
BorderWidth="0" ToolTip="Sluit handboek" />
</div>
</div>
<asp:TreeView ID="tvManual" runat="server" RootNodeStyle-CssClass="RootNode">
<Nodes>
</Nodes>
</asp:TreeView>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#Treeview
{
padding-right: 5px;
width: 250px;
height: 100%;
float: left;
border-right: solid 1px black;
overflow-x: scroll;
}
</code></pre>
| <p>As Andrew said, your text should be doing just that.</p>
<p>There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.</p>
<p>See if you don't have the following in your CSS somewhere:</p>
<pre><code>white-space: nowrap
</code></pre>
<p>That will cause text to continue on the same line until interrupted by a line break.</p>
<p>OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).</p>
<p>The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.</p>
|
Regex: How to get all contents inside a tag #[SOME TEXT HERE] <p>I am working on a simple token replacement feature of our product. I have almost resolved all the issue but I missed one thing. A token must support attributes, and an attribute can also be a token. This is part of a bigger project. hope you can help.</p>
<p>The begining tag is <code>"**#[**"</code> and the ending tag is <code>"**]**"</code>. Say, #[FirstName], #[LastName], #[Age, WhenZero="Undisclosed"].</p>
<p>Right now i am using this expression <code>"\#\[[^\]]+\]"</code>. I have this working but it failed on this input:</p>
<pre><code>blah blah text here...
**#[IsFreeShipping, WhenTrue="<img src='/images/fw_freeshipping.gif'/>
<a href='http://www.hellowebsite.net/freeshipping.aspx'>$[FreeShipping]</a>"]**
blah blah text here also...
</code></pre>
<p>It fails becauise it encouter the first ], it stops there. It returns:</p>
<pre><code>*#[IsFreeShipping, WhenTrue="<img src='/images/fw_freeshipping.gif'/>
<a href='http://www.hellowebsite.net/freeshipping.aspx'>$[Product_FreeShipping]*
</code></pre>
<p>My desired result should be</p>
<pre><code>*#[IsFreeShipping, WhenTrue="<img src='/images/fw_freeshipping.gif'/>
<a href='http://www.hellowebsite.net/freeshipping.aspx'>$[FreeShipping]</a>"]*
</code></pre>
| <p>This is a little border-line for a regexp, since it depends on a context, but still...</p>
<pre><code>#\[(\](?=")|[^\]])+\]
</code></pre>
<p>should do it.</p>
<p>The idea is to mention a closing square bracket can be part of the parsed content if followed by a double quotes, as part of the end of an attribute.</p>
<p>If that same square bracket were anywhere within the attribute, that would be a lot harder...</p>
<p><hr /></p>
<p>The advantage with lookahead expression is that you can specify a regexp with a non-fixed match length.<br />
So if the attribute closing square bracket is not followed by a double quote, but rather by another known expression, you just update the lookahead part:</p>
<pre><code>#\[(\](?=</a>")|[^\]])+\]
</code></pre>
<p>will match only the second closing square bracket, since the first is followed by <code></a>"</code>.</p>
<p>Of course, any kind of greedy expression (<code>.*]</code>) would not work, since it would not match the second closing square bracket, but the <em>last</em> one. (Meaning if there are more the one intermediate <code>]</code>, it will be parsed.)</p>
|
Versioning CSS files with a query string like Stackoverflow does? <p>If you look at Stackoverflow.com's source you'll see the reference to their css file is:</p>
<pre><code><link href="/Content/all.min.css?v=2383" rel="stylesheet" type="text/css" />
</code></pre>
<p>How is this done so they can pass a version via query string and have the correct CSS file served up?</p>
| <p><a href="http://particletree.com/notebook/automatically-version-your-css-and-javascript-files/">This (PHP example)</a> article explain you the idea behind it. Basically, you could happend the timestamp of the last time you modified the file. This way everytime you change your CSS, the querystring will change and "forcing" the browser to download the new version. This is valid for both CSS and JS files.</p>
<p>A ASP.NET sample is this:</p>
<pre><code>public static string GetBreaker(string fileName)
{
string cacheBreaker = null;
try
{
if (fileName.StartsWith("~"))
{
fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName.Remove(0));
}
cacheBreaker = File.GetLastWriteTime(fileName).ToFileTime().ToString();
}
catch { }
return string.IsNullOrEmpty(cacheBreaker) ? string.Empty : string.Format("?cachebreaker={0}", cacheBreaker);
}
</code></pre>
<p>And you call this method in your MasterPage in this way:</p>
<pre><code><link href="<%= this.ResolveClientUrl("~/CSS/style.css") %><%=CacheBreaker.GetBreaker("~/CSS/style.css") %>"
rel="stylesheet" type="text/css" />
</code></pre>
|
Running SimpleXMLRPCServer in separate thread and shutting down <p>I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and finally shut down.</p>
<p>This is my ServerThread:</p>
<pre><code>class ServerThread(Thread):
running = True
def run(self):
self.server = #Creates and starts SimpleXMLRPCServer
while (self.running):
self.server.handle_request()
def stop(self):
self.running = False
self.server.server_close()
</code></pre>
<p>The problem is, that calling ServerThread.stop(), followed by Thread.stop() and Thread.join() will not cause the thread to stop properly if it's already waiting for a request in handle_request. And since there doesn't seem to be any interrupt or timeout mechanisms here that I can use, I am at a loss for how I can cleanly shut down the server thread.</p>
| <p>Two suggestions.</p>
<p>Suggestion One is to use a separate process instead of a separate thread.</p>
<ul>
<li><p>Create a stand-alone XMLRPC server program.</p></li>
<li><p>Start it with <code>subprocess.Popen()</code>. </p></li>
<li><p>Kill it when the test is done. In standard OS's (not Windows) the kill works nicely. In Windows, however, there's no trivial kill function, but there are recipes for this.</p></li>
</ul>
<p>The other suggestion is to have a function in your XMLRPC server which causes server self-destruction. You define a function that calls <code>sys.exit()</code> or <code>os.abort()</code> or raises a similar exception that will stop the process.</p>
|
How to do Trim operation to remove space character in a text field in JavaScript? <p>How to do Trim operation to remove space character in a text field in JavaScript?</p>
| <p>A total dupe of this question:</p>
<p><a href="http://stackoverflow.com/questions/196925/what-is-the-best-way-to-trim-in-javascript">http://stackoverflow.com/questions/196925/what-is-the-best-way-to-trim-in-javascript</a></p>
<p>Unless you didn't actually mean trim of course and in fact wanted all the spaces replaced ? In which case you just want:</p>
<pre><code>var myString = "foo bar ddd";
myString = myString.replace(/ /g, "");
</code></pre>
|
Disable/Enable Ribbon Buttons for MFC Feature Pack <p>I am using the MFC Feature Pack and I have some buttons on a ribbon bar, instances of CMFCRibbonButton. The problem is that I would like to enable and disable some of them in certain conditions, but at runtime. How can I do this? because there is no specific method for this...I heard that a solution would be to attach/detach the event handlers at runtime, but I do not know how...</p>
| <p>When you create the <code>CMFCRibbonButton</code> object you have to specify the associated command ID (see the documentation for the <code>CMFCRibbonButton</code> constructor <a href="http://msdn.microsoft.com/en-us/library/bb982247.aspx">here</a>). Enabling and disabling of ribbon buttons is then done using the usual command update mechanism in MFC, using the <a href="http://msdn.microsoft.com/en-us/library/6kc4d8fh.aspx"><code>CCmdUI</code></a> class.</p>
<p>For example, if you have a ribbon button whose command ID is <code>ID_MYCOMMAND</code> and you want to handle this command in your application's view class, you should add these functions to the class:</p>
<pre><code>// MyView.h
class CMyView : public CView {
// ...
private:
afx_msg void OnMyCommand();
afx_msg void OnUpdateMyCommand(CCmdUI* pCmdUI);
DECLARE_MESSAGE_MAP()
};
</code></pre>
<p>and implement them in the .cpp file:</p>
<pre><code>// MyView.cpp
void CMyView::OnMyCommand() {
// add command handler code.
}
void CMyView::OnUpdateMyCommand(CCmdUI* pCmdUI) {
BOOL enable = ...; // set flag to enable or disable the command.
pCmdUI->Enable(enable);
}
</code></pre>
<p>You should also add <code>ON_COMMAND</code> and <code>ON_UPDATE_COMMAND_UI</code> entries to the message map for the <code>CMyView</code> class:</p>
<pre><code>// MyView.cpp
BEGIN_MESSAGE_MAP(CMyView, CView)
ON_COMMAND(ID_MYCOMMAND, &CMyView::OnMyCommand)
ON_UPDATE_COMMAND_UI(ID_MYCOMMAND, &CMyView::OnUpdateMyCommand)
END_MESSAGE_MAP()
</code></pre>
<p>For more information on message maps in MFC, refer to <a href="http://msdn.microsoft.com/en-us/library/0812b0wa.aspx">TN006: Message Maps</a> in MSDN.</p>
<p>I hope this helps!</p>
|
WCF - advantages and disadvantages <p>I would like to find out about BOTH advantages and disadvantages of Windows Communication Foundation from people who have used it or just know it theoretically.</p>
| <p><strong>Primary advantage</strong>: Once you get over the learning curve, WCF makes it relatively easy to expose and consume software components. i.e. Given a component bakes functionality into a WCF Service Contract, a developer can expose that same component in-proc, across processes on a single box, across a Windows intranet, or throughout the internet all by just changing hosts and configuration information. Likewise it's easy for clients of said component to use it in any of those scenarios as well.</p>
<p><strong>Primary disadvantage</strong>: the learning curve. WCF seems very daunting to many developers when they first begin looking into it. I made several false starts trying to get into Juval Lowy's "Programming WCF Services." Though I've found that comprehension came quickly once I began actually creating and consuming components.</p>
<p><em>The key thing to remember</em> is that WCF let's you write some nice functional code and wrap it into a component that you can then relatively easily use just about anywhere with just about any amount of security, reliability and durability. </p>
<p>Compared to what we were forced to use previously, WCF is fantasitc!</p>
|
How can I get an HTML page to read the contents of a text document? <p>How can I get an HTML page (.html) to read the contents of a text document that can be found in the same folder as the .html file? The server is IIS.</p>
<p>Thanks</p>
| <p>Google for <a href="http://www.google.com/search?q=IIS+includes" rel="nofollow">server-side includes</a>.</p>
|
Crystal Reports hanging <p>The company has recently implemented software not written by us. The software uses Crystal Reports and whenever somebody draws a particularly large report and close their browser before the report is finished loading, we cannot draw anymore reports. The only way to fix it is to reset iis which is obviously exceptionally bad practice.</p>
<p>Any ideas on how to overcome this?</p>
<p>Thanks</p>
| <p>So if one person closes their browser prematurely, the app breaks for everyone? Can two people try loading one of these long-running reports at once? Are there multiple templates, and this only breaks one and leaves the others ok?</p>
<p>It sounds a bit like the app's implementation of Crystal is holding an exclusive lock on the original template, and so when the user quits prematurely the app doesn't release the template for other users to use.</p>
|
Eclipse: How to build an executable jar with external jar? <p>I am trying to build an executable jar program which depends on external jar downloaded. In my project, I included them in the build path and can be run and debug within eclipse.</p>
<p>When I tried to export it to a jar, I can run the program but I can't when I try to press a button which includes function calls and classes from the external jar. I have edited the environment variables (Windows XP) CLASSPATH to include paths of all the external jar, but it doesn't work.</p>
<p>A point to note is that I got compile warnings while exporting my executable jar, but it doesn't show up any description about the warnings.</p>
<p>Would someone kindly provide a thorough guide on how to include an external jar program using eclipse?</p>
| <p>Eclipse 3.5 has an option to package required libraries into the runnable jar.
File -> Export...
Choose runnable jar and click next.
The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.</p>
|
How can I drag an eMail from Outlook into an Adobe AIR application <p>This is a quiestion concerning both, Adobe AIR and MS Outlook.</p>
<p>I'd like to drag an eMail from Outlook into an AIR application. I want the following data to be transferred into the AIR application:</p>
<ul>
<li>unique ID of the mail in Outlook to create a link into Outlook</li>
<li>rich text of the mail</li>
<li>some information about the mail like sender, recepient, date etc.</li>
</ul>
<p>Some windows applications do this, like <a href="http://www.mylifeorganized.net/" rel="nofollow">My Life Organized</a> or <a href="http://www.teamscope.com/otherpro/utilities.asp" rel="nofollow">Linker</a>. Is this possible in any way for AIR? I'm pretty sure I need not only the AIR application but also some windows app or Outlook plugin to achieve this. Any ideas?</p>
| <ul>
<li>Basically you listen to <a href="http://livedocs.adobe.com/flex/3/langref/flash/events/NativeDragEvent.html" rel="nofollow">NativeDragEvent</a>.NATIVE_DRAG_ENTER, NATIVE_DRAG_DROP and NATIVE_DRAG_EXIT on the UI element that will receive the drop. </li>
<li>All three of these events are raised with a NativeDragEvent, through which you can access data in various formats via event.clipboard.<a href="http://livedocs.adobe.com/flex/3/langref/flash/desktop/Clipboard.html#getData%28%29" rel="nofollow">getData()</a>, passing in a format specified by <a href="http://livedocs.adobe.com/flex/3/langref/flash/desktop/ClipboardFormats.html" rel="nofollow">ClipboardFormats</a> (eg. ClipboardFormats.FILE_LIST_FORMAT)</li>
<li>In NATIVE_DRAG_ENTER, you can accept/reject the drag operation via the static methods on NativeDragManager</li>
</ul>
<p>The classes you need are all in the <a href="http://livedocs.adobe.com/flex/3/langref/flash/desktop/package-detail.html" rel="nofollow">flash.desktop</a> package. Just experiment with various ClipboardFormats until you see the data you need.</p>
|
What function was used to code these passwords in AFX? <p>I am trying to work out the format of a password file which is used by a LOGIN DLL of which the source cannot be found. The admin tool was written in AFX, so I hope that it perhaps gives a clue as to the algorithm used to encode the passwords.</p>
<p>Using the admin tool, we have two passwords that are encoded. The first is "dinosaur123456789" and the hex of the encryption is here:</p>
<p>The resulting hex values for the dinosaur password are</p>
<p>00h: 4A 6E 3C 34 29 32 2E 59 51 6B 2B 4E 4F 20 47 75 ; Jn<4)2.YQk+NO Gu
10h: 6A 33 09 ; j3.
20h: 64 69 6E 6F 73 61 75 72 31 32 33 34 35 36 37 38 ; dinosaur12345678
30h: 39 30 ; 90</p>
<p>Another password "gertcha" is encoded as
e8h: 4D 35 4C 46 53 5C 7E ; GROUT M5LFS\~</p>
<p>I've tried looking for a common XOR, but failed to find anything. The passwords are of the same length in the password file so I assume that these are a reversible encoding (it was of another age!). I'm wondering if the AFX classes may have had a means that would be used for this sort of thing?</p>
<p>If anyone can work out the encoding, then that would be great!</p>
<p>Thanks, Matthew</p>
<p>[edit:]
Okay, first, I'm moving on and going to leave the past behind in the new solution. It would have been nice to use the old data still. Indeed, if someone wants to solve it as a puzzle, then I would still like to be able to use it.</p>
<p>For those who want to have a go, I got two passwords done.</p>
<p>All 'a' - a password with 19 a's:
47 7D 47 38 58 57 7C 73 59 2D 50 ; G}G8XW|sY-P
79 68 29 3E 44 52 31 6B 09 ; yh)>DR1k.</p>
<p>All 'b' - a password with 16 b's.
48 7D 2C 71 78 67 4B 46 49 48 5F ; H},qxgKFIH_
69 7D 39 79 5E 09 ; i}9y^.</p>
<p>This convinced me that there is no simple solution involved, and that there is some feedback. </p>
| <p>Well, I did a quick cryptanalysis on it, and so far, I can tell you that each password appears to start off with it's ascii value + 26. The next octet seems to be the difference between the first char of the password and the second, added to it's ascii value. The 3d letter, I haven't figured out yet. I think it's safe to say you are dealing with some kind of feedback cipher, which is why XOR turns up nothing. I think each octets value will depend on the previous.</p>
<p>I can go on, but this stuff takes a lot of time. Hopefully this may give you a start, or maybe give you a couple of ideas.</p>
|
StructureMap InstanceScope.Hybrid and IDisposable <p>I'm working on an asp.net-mvc application. The linq data context is being passed into my service objects by structure map. I've got is set to have a scope of hybrid. This all works just fine.</p>
<pre><code>protected override void configure()
{
ForRequestedType<AetherDataContext>()
.TheDefaultIs(() => new AetherDataContext())
.CacheBy(InstanceScope.Hybrid);
}
</code></pre>
<p>The problem is that I keep running our of memory, I'm wondering if the IDisposable interface is ever actually being called.</p>
<p>Anyone got any ideas?</p>
<p>Failing that anyone got any other idea for things that might be causing my memory exceptions?</p>
<p>Update:</p>
<p>So some additional information, I just stuffed a couple of methods into my data context an put brake points in there.</p>
<pre><code>protected override void Dispose(bool disposing)
{
Debug.WriteLine("Disposing: " + DateTime.Now);
base.Dispose(disposing);
}
public new void Dispose()
{
Debug.WriteLine("Disposing: " + DateTime.Now);
base.Dispose();
}
</code></pre>
<p>I'm not quite sure that I'm doing this the correct way, I'm guessing that the new method will be called?</p>
<p>Anyway, neither of the brake points were hit. However the constructor for the same class was called on every request though. Not ideal I'm thinking.</p>
| <p>Ok so the latest version of StructureMap <a href="http://codebetter.com/blogs/jeremy.miller/archive/2009/02/01/structuremap-2-5-3-is-released-and-the-future-of-structuremap.aspx" rel="nofollow">(2.3.5)</a> has a useful little method called </p>
<pre><code>HttpContextBuildPolicy.DisposeAndClearAll();
</code></pre>
<blockquote>
Cleanup convenience methods on HttpContext and ThreadLocal. HttpContextBuildPolicy.DisposeAndClearAll(), ThreadLocalStoragePolicy.DisposeAndClearAll(). Calling either method will eject all cached instances and call IDispose if the object is IDisposable.
</blockquote>
<p>Previously the dispose methods weren't being called called, I added that to Application_EndRequest and they are now. I'm hoping that this will solve some of my memory problems.</p>
<p>We shall see.</p>
|
mysqli binding fields in a prepared statement <p>I have the following code, for which I get the error:</p>
<p><strong>Warning</strong>: mysqli_stmt::bind_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement in file.</p>
<p>If this is only a warning, shouldn't the code still work? I want to do a select * and display all the data except one field, which I want to bind and handle separately. Is there any way around, or a better method? My solution at the moment(untried) is to bind the correct amount of variables to the results with getRecords, and then bind separately as a different name with getHtml.</p>
<p>What are the advanatges of binding, and is it necessary.</p>
<pre><code><?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$id = $_GET["id"];
$con = mysqli_connect("localhost", "user", "password", "db");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$con->set_charset("utf8");
echo "test outside loop";
if($cmd=="GetSaleData") {
echo "test inside loop";
if ($getRecords = $con->prepare("SELECT SELECT Product_NO, Product_NAME, SUBTITLE, CURRENT_BID, START_PRICE, BID_COUNT, QUANT_TOTAL, QUANT_SOLD, ACCESSSTARTS, ACCESSENDS, ACCESSORIGIN_END, USERNAME, BEST_BIDDER_ID, FINISHED, WATCH, BUYITNOW_PRICE, PIC_URL, PRIVATE_AUCTION, AUCTION_TYPE, ACCESSINSERT_DATE, ACCESSUPDATE_DATE, CAT_DESC, CAT_PATH, COUNTRYCODE, LOCATION, CONDITIONS, REVISED, PAYPAL_ACCEPT, PRE_TERMINATED, SHIPPING_TO, FEE_INSERTION, FEE_FINAL, FEE_LISTING, PIC_XXL, PIC_DIASHOW, PIC_COUNT, ITEM_SITE_ID FROM Sales WHERE Product_NO = ?")) FROM SaleS WHERE PRODUCT_NO = ?")) {
$getHtml = $con->prepare("SELECT PRODUCT_DESC FROM SaleS WHERE PRODUCT_NO = ?");
$getHtml->bind_param("i", $id);
$getHtml->execute();
$getHtml->bind_result($PRODUCT_DESC);
$getRecords->bind_param("i", $id);
$getRecords->execute();
$getRecords->bind_result($PRODUCT_NO, $PRODUCT_NAME, $SUBTITLE, $CURRENT_BID, $START_PRICE, $BID_COUNT, $QUANT_TOTAL, $QUANT_SOLD, $ACCESSSTARTS, $ACCESSENDS, $ACCESSORIGIN_END, $USERNAME, $BEST_BIDDER_ID, $FINISHED, $WATCH, $BUYITNOW_PRICE, $PIC_URL, $PRIVATE_Sale, $Sale_TYPE, $ACCESSINSERT_DATE, $ACCESSUPDATE_DATE, $CAT_DESC, $CAT_PATH, $COUNTRYCODE, $LOCATION, $CONDITIONS, $REVISED, $PAYPAL_ACCEPT, $PRE_TERMINATED, $SHIPPING_TO, $FEE_INSERTION,
$FEE_FINAL, $FEE_LISTING, $PIC_XXL, $PIC_DIASHOW, $PIC_COUNT, $ITEM_SITE_ID);
while ($getRecords->fetch()) {
// operations snipped for question
echo "<h1>".$PRODUCT_NAME."</h1>
<div id='leftlayer' class='leftlayer'>
<p><strong>Username: </strong>".$USERNAME."
<p><strong>Shipping to: </strong> ". $country ."
<img src='./images/".$id.".jpg"' width='".$imageSize["width"]."' height='".$imageSize["height"]."'>
</div>
<div id='rightlayer'>
</div>";
//
}
}
}
}
</code></pre>
<p>I would also like to know what is wrong with my img src statement..., I feel I am mising something elementary such as a slash or quote.</p>
<p>edit: The code now displays an error after replace * with column names, however the while loop is never entered, and hence no actions are performed.</p>
| <p>You may need to explicity state the column names in your SELECT rather than use *, <a href="http://www.php.net/manual/en/mysqli-stmt.bind-result.php" rel="nofollow">as per the examples for MySQLi bind_result()</a>.</p>
<p>In relation to the img line, you have an extra " after .jpg</p>
<pre><code><img src='./images/".$id.".jpg"' width=
</code></pre>
<p>should be</p>
<pre><code><img src='./images/".$id.".jpg width=
</code></pre>
<p>Also, you don't actually need to break out of the string and concatenate the variables because using " will cause the string to be parsed for variables anyway.</p>
|
Role security with active directory <p>I have to ensure the security of a asp.net website at work. they ask me to do a role based security with the active directory of my work so i could do a sitemap and give the right acces at the right personne.</p>
<p>wich class of the framework should i use? make generic identity?</p>
| <p>It's already built into AD authentication. If you are authenticating against the AD, either via NTLM logins or an AD connected forms authentication setup then the thread identity will contain the groups the user belongs to, and the role based parts of the sitemap control will work.</p>
<p>Specifically you use the <em>WindowsTokenRoleProvider</em>. This is a one way role manager (you can't add people to groups - you have to use the AD tools for that. The use the sitemap's <a href="http://msdn.microsoft.com/en-us/library/ms178428.aspx" rel="nofollow">built in</a> support for trimming site maps according to role.</p>
|
How do you map an enum as string in fluent nhibernate? <p>Is it possible to map an enum as a string using Fluent Nhibernate?</p>
| <p>Yes, it does that by default if you just do:</p>
<pre><code>Map(x => x.YourProperty);
</code></pre>
<p>Make sure you're using the latest version off the trunk.</p>
<hr>
<p>As <a href="http://stackoverflow.com/users/463181/yavor-shahpasov">Yavor Shahpasov</a> pointed out in the comments, in more recent versions you can accomplish the same with:</p>
<pre><code>Map(x => x.Property).CustomType<GenericEnumMapper<YourPropertyEnumType>>();
</code></pre>
|
How would you build a HttpTraceListener? <p>My application uses the Trace object to log information. The information is captured in a file with the TextWriterTraceListener and it works perfectly. However, I would like to add another TraceListerner which will record the information to a Web Service. In other words, I need an HttpTraceListener. Moreover, I need something <em>intelligent</em>, I wouldnât like to see a HTTP request for every log entry. </p>
<p>How would you build such thing? I know I have to inherit TraceListener (the documentation is somewhat cryptic...) but <strong>does anybody have an idea if a HttpTraceListener already exist</strong>? I don't want to reinvent the wheel...</p>
<p>Thanks!</p>
| <p>Because of your requirements about variable logging, i.e. not issuing a request for every entry, you will most certainly need to create your own listener.</p>
<p>Per MSDN docs on TraceListener (<a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener</a>(VS.80).aspx)</p>
<p>"Inherit from this class to implement a custom listener for the Debug and Trace classes. At a minimum, you must implement the Write and WriteLine methods. Additionally, you can implement the Fail, Close and Flush methods."</p>
<p>I would start with:</p>
<ol>
<li>Inherit from TraceListener.</li>
<li>Implement the Write/WriteLine methods</li>
<li>Add your logic in Write to submit the request to a web service. WriteLine simply appends a line terminator, if you use the base class implementation.</li>
<li>Override Fail/Close/Flush as needed for your application.</li>
</ol>
<p>Those 5 methods will give you all the access you need to implement your listener.</p>
|
How do I return an array from a Visual FoxPro 9 OLEPUBLIC class? <p>As a newbie to FoxPro (but an old-hand at Clipper), I'm a bit at a loss to figure out how to return an array from the following OLEPUBLIC class. <em>edit</em>: I've modified the code belw to take into consideration the remarks made by @Stuart below. </p>
<pre><code>DEFINE CLASS db AS CUSTOM OLEPUBLIC
DIMENSION ada(1) && public scope for later return
FUNCTION opendb( cpName )
SET MULTILOCKS ON
USE (cpName) EXCLUSIVE NOUPDATE
= CURSORSETPROP("Buffering",5)
RETURN ALIAS()
ENDFUNC
&& etc
FUNCTION getrecord( sAlias, nRecno )
SELECT (sAlias)
GOTO (nRecno)
fc = FCOUNT()
DIMENSION this.ada(fc)
FOR i = 1 TO fc
STORE CURVAL(FIELD(i)) to THIS.ada(i)
ENDFOR
RETURN @THIS.ada
ENDFUNC
ENDDEFINE
</code></pre>
<p>Given the following bit of VBScript, I can open the file fine. What I can't seem to do is get back anything more useful than an error message.</p>
<pre><code>set sp = createobject("sloop.db")
al = sp.opendb("p:\testing\sloop\patient.dbf")
wscript.echo sp.getrecord(al,1)
</code></pre>
<p>This is the error message:</p>
<blockquote>
<p>c:\temp\foo.vbs(3, 1) sloop.db sloop.db: .getrecord p:\testing\sloop\sloop.prg Error in line 41 Syntax error. 200</p>
</blockquote>
<p>Line 41, as it turns out, is</p>
<blockquote>
<p>RETURN @THIS.ada</p>
</blockquote>
<p>which is really weird as that's the syntax that Microsoft suggests. Any clues?</p>
| <p>(5 years late, but perhaps still useful to someone out there...)</p>
<p>A better option would be to have your VFP code create a Collection object instead, then parse the array and add all the elements to the collection (using the .Add() method). Then you can pass the collection object back to VB, which is then happy to play with it.</p>
|
Why is the Intellisense for properties and methods of instantiated datacontext not showing? <p>I have a web application project within VS 2008 and I have created a Linq to SQL file onto which I have dragged a table from my data base. The data context is created fine but when I instantiate an object of this type the only item I get showing on the Intellisense for it is the class based on the table I dragged onto the designer and even on this I get no Intellisense if I put a dot after it. Has anyone any idea why I am not seeing all the methods for this datacontext (i.e. SubmitChanges etc).</p>
<pre><code>EmsContentModelDataContext context;
#region Methods
protected void Page_Load(object sender, EventArgs e)
{
context = new EmsContentModelDataContext();
</code></pre>
| <p>OK - it turns out relatively simple. It was just that there were compile errors within that class that was causing the intellisense to break. When I recreated the file from new and cleared the compile errors I got the intellisense back.</p>
|
What's the best way to get a column name in asp.net using ODBC? <p>I have a database that has four columns like this</p>
<p>level_1, level_2, level_3, level_4</p>
<p>There are also id, name, etc., but only these four are the ones that matter to me at the moment.</p>
<p>I need to know which column, by columnname, has the value 'BOSS'.</p>
<p>For example, level_2 may have the value BOSS. I need to know that one of the four columns has the code BOSS and which column, by column name, it is.</p>
<p>The reason is that I have to later update this row but I never know where the value BOSS will be. It could be in level_4, for example.</p>
<p>I know there is a columnname property in DataSet, but I cannot figure out how to use that here. I cannot post my code because there are many iterations of it, none of which work. I am hoping I am overlooking something obvious.</p>
<p>I am using ASP.NET 2.0 and ODBC.</p>
<p>Thank you for any ideas.</p>
<p>just to clarify - I do not need to know how to get the columnname per se. The columnname property works well for that. I do not know which column will have the value BOSS above. Once I can determine that I will get the columnname property value.</p>
<p>The reason I do not know which column will say BOSS is because there are other values that could be in any of the four so the data entry person has to pick an open field and put in the code - it is an old database application I inherited.</p>
<p>update:</p>
<p>Here is what i came up with. I do not like it but here it is. It works but it feels wrong:</p>
<pre><code> String[] myValues = new String[5] {"BOSS", "ANOTHERCODE", "ANOTHERCODE", "ANOTHERCODE", "ANOTHERCODE"};
int x = 0;
foreach (String level in myValues)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
String myColumnValue = ds.Tables[0].Rows[0][x].ToString();
if (myColumnValue == level)
{ return ds.Tables[0].Columns[x].ColumnName; }
x += 1;
}
x = 0;
}
</code></pre>
| <p>Ok, so you have 4 columns that could have the value BOSS. I guess the best way to solve your problem would be to cycle thought these 4 columns until you get the Value BOSS, when you do find it, store the column name on a variable so you can get it back later.</p>
|
How do I get a list of available NamedCache objects from ScaleOut StateServer (SOSS)? <p>I'm using v4.0.</p>
<p><strong>Update:</strong></p>
<p>I've hacked together this so far:</p>
<pre><code>public class AllFilter : IFilter
{
#region IFilter Members
IndexCollection IFilter.GetIndexCollection()
{
return new IndexCollection();
}
MatchOptions IFilter.GetMatchOptions()
{
return MatchOptions.MatchAll;
}
#endregion
}
public class CacheMonitorController : Controller
{
public ActionResult Index()
{
var results =
from result in ApplicationNamespace.GlobalNamespace.Query(new AllFilter()).OfType<StateServerKey>()
group result by result.AppId;
var b = new StringBuilder();
foreach (var result in results)
{
var cache = CacheFactory.GetCache(result.Key);
b.AppendLine(cache.Name);
}
return this.Content(b.ToString(), "text/plain");
}
}
</code></pre>
<p>Unfortunately, the name of the cache always comes up <code>null</code>, even though there is certainly a name when the cache is created. The name certainly needs to be identifiable in the UI, so I need a way to get it.</p>
| <p>Apparently, there is no way to do this in v4.0 - the keys for both the stores themselves, as well as the keys for the values are stored as hashes (in the form of <code>uint</code>s), so unless the NamedCache is retrieved using the actual name, the name cannot be known.</p>
<p>The only alternative would be to track the string values of the keys in another store in the cache.</p>
<p>According to Mark Waterman from ScaleOut software, the ability to retrieve the names will be available in v5.0, which is due to be released spring 2009.</p>
|
How to get the value of a control from the child into the properties of the parent in .NET? <p>I have a form that has a few similar controls and the parent contains the properties, but the child actually has the html controls. How could I setup my getters/setters using the "child" controls in the parent class? (Webforms - fyi)</p>
<p>I found the below via search, and what I'm looking for is the inverse</p>
<p><a href="http://stackoverflow.com/questions/463938/getting-value-of-a-property-in-parent-user-control-from-a-child-user-control">http://stackoverflow.com/questions/463938/getting-value-of-a-property-in-parent-user-control-from-a-child-user-control</a></p>
<p><strong>Edit:</strong></p>
<p>I should have tried this early on, but instead found it "fun" to explain this crazy situation. The below is what worked @ 100%</p>
<pre><code>Get
Return DirectCast(Page.FindControl("lblCASE_NUMBER"), HtmlContainerControl).InnerHtml
End Get
</code></pre>
| <p>If I understood you correctly you have one usercontrol (child) inside another usercontrol(parent) and you need to access the child properties from within the parent.</p>
<p>If this is correct all you need to do is either create properties or methods in the child as you would in any other class. Than just use them from the parent.</p>
|
MS SQL 2005 compare field containing square parenthesis <p>I am using MS SQL Server 2005 (9.0.4035) and trying to find rows that contain the same data in a nvarchar(4000) field. The field contains xml that has both opening and closing square parentheses.<br><br>
Here is sample data:<br>
DataID Data<br>
1 1<br>
2 1<br>
3 2]<br>
4 2]<br>
5 3[<br>
6 3[<br></p>
<p>Using the 'like' operator I expected to get 3 matching pairs, but my problem is that row 5 and 6 do not match each other, I only get back that rows 1 & 2 match, and 3 & 4 match.</p>
<p>I know MS SQL 2005 added regular expression support in queries but I did not expect them to evaluate field data as a regular expression, which I think it is doing. Is there a mode that I need to enable to get the proper results?</p>
<p>Any help appreciated,<br>
Ryan</p>
<p><b>Edit:</b> Added sql statement used:<br></p>
<p>Select t1.DataID, t2.DataID From TestTable t1, TestTable t2<br>
Where t1.DataID <> t2.DataID<br>
and t1.Data like t2.Data</p>
<p><b>Edit:</b> Answer<br>
Using '=' operator works, but escaping the '[' does not.</p>
| <p>Change your query to use = instead of LIKE and you'll get the results that you expect. SQL 2005 T-SQL won't do regex - you'd need to use CLR functions for that - but the LIKE statment does do pattern matching. '[' and ']' are reserved for the pattern matching in a like statment, and you'd have to escape them out if you intended for them to be equality matches. </p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/ms179859.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms179859.aspx</a> for info on the LIKE statement.</p>
<p>Either of the 2 queries below solved the problem in my tests...</p>
<pre><code>--using equals operator...
Select t1.DataID, t2.DataID From TestTable t1, TestTable t2
Where t1.DataID <> t2.DataID
and t1.Data = t2.Data
--using replace to add an escape character.
Select t1.DataID, t2.DataID From TestTable t1, TestTable t2
Where t1.DataID <> t2.DataID
and t1.Data like REPLACE(t2.Data, '[', '\[') escape '\'
</code></pre>
|
How best to update an XML node in MSBuild <p>I have been using the Tigris community tasks to update various AppSettings keys using the XMLUpdate task. </p>
<p>Now, however I want to add a node to the system.net section to set up the proxy. </p>
<p>I declared a property</p>
<pre><code><PropertyGroup>
<proxy>&lt;defaultProxy&gt; &lt;proxy usesystemdefault="False" proxyaddress="http://IPADDRESS:PORT" /&gt; &lt;/defaultProxy&gt;</proxy>
</PropertyGroup>
</code></pre>
<p>and the XMLUpdate Task looks like </p>
<pre><code><XmlUpdate
Prefix="n"
Namespace="http://schemas.microsoft.com/.NetConfiguration/v2.0"
XmlFileName="$(BuildDir)\Builds\_PublishedWebsites\Presentation\Web.config"
XPath="/n:configuration/n:system.net"
Value="$(proxy)" />
</code></pre>
<p>this updates the web config however it updates directly from the property group i.e. doesn't convert the escape characters for the angle brackets. Does anyone have any ideas? </p>
| <p>You could use the XmlMassUpdate instead of XmlUpdate task.</p>
<pre><code><ProjectExtensions>
<defaultProxy>
<proxy usesystemdefault="False" proxyaddress="http://IPADDRESS:PORT"/>
</defaultProxy>
</ProjectExtensions>
<Target Name="SubstituteFromWebConfig">
<XmlMassUpdate
NamespaceDefinitions="msb=http://schemas.microsoft.com/developer/msbuild/2003;n=http://schemas.microsoft.com/.NetConfiguration/v2.0"
ContentFile="$(BuildDir)\Builds\_PublishedWebsites\Presentation\Web.config"
ContentRoot="/n:configuration/n:system.net"
SubstitutionsFile="$(MSBuildProjectFullPath)"
SubstitutionsRoot="/msb:Project/msb:ProjectExtensions/msb:system.web" />
</Target>
</code></pre>
<p>In this example we replace the node pointed by <em>ContentRoot</em> in <em>ContentFile</em> by the one pointed by <em>SubstitutionsRoot</em> in <em>SubstitutionsFile</em> (The current MSBuild file).</p>
<p>This technique takes advantage of the <strong>MSBuild ProjectExtensions element</strong> which allows you to <strong>add XML</strong> to a project file <strong>that will be ignored by the MSBuild engine</strong>.</p>
<p>(Or if you do not want to use XmlMassUpdate, you could use the XmlRead task on a node in ProjectExtensions and a XmlUpdate.)</p>
|
How to force process isolation for an out of process COM server? <p>I'm writing managed code that has to interact with a vendor's COM automation server that runs out of process. I have found that this server becomes unstable if more than one client connects to it. For example, if I have managed code in process A and managed code in process B both connecting to this COM server, a single process will be spun up for the COM server and it's behavior is less than reliable. <strong>I'm hoping there's a way to force a separate process for each client - server connection</strong>. Ideally, I'd like to end up with:</p>
<p>Managed Process A talking to COM Server in process <b>C1</b><br/>
Managed Process B talking to COM Server in process <b>C2</b></p>
<p>One thought that came to mind was that if I ran process A and process B with different security identities, that that might cause the COM infrastructure to create separate server processes. I'd rather not go down that road, however. Managed Process A and Managed Process B are actually Windows Services. And I'm running them with identity Local System (because I need them to be able to interact with the desktop, and you can't check the "Interact with Desktop" box on the services applet for services that don't run as Local System). And the reason I need to interact with desktop is that this COM server occasionally throws up a dialog box on the screen and if the service itself cannot interact with the desktop then the COM server is spawns can't display the dialog (I believe it is displayed on a hidden WinStation).</p>
| <p>Place the component registered at COM+, this put an isolation layer at your.<br>
Use : Control Panel->Administrative Tools<br>
or cmd/execute DCOMCNFG</p>
<p>Component Services->Computers->My Computer->COM+ Application, right click, new application, next, Create an empty application, enter app name âCOM+ your.dllâ, next, select Local Service, next, next, next, finish.</p>
<p>In new item made, expand, at Components, right click, new component, next, select Install new component, select your component.</p>
<p>Click Component properties, tab Identity, select System Account.</p>
<p>For errors in calls see Event after.</p>
|
Generic Database Monitoring Tool <p>It seems like something like this <em>should</em> exist, but I have never heard of it and would find such a utility to be incredibly useful. Many times, I develop applications that have a database backed - SQL Server or Oracle. During development, end users of the app are encouraged to test the site - I can verify this by looking for entries in the database...if there are entries, they have been testing...if not, they haven't.</p>
<p>What I would like is a tool/utility that would do this checking for me. I would specify the Database and connection parameters and the tool would pool the database periodically (based on values that I specify) and alert me if there was any new activity in the database (perhaps it would pop up a notification in the system tray). I could also specify multiple database scenarios to monitor in the tool. If such an app existed, I wouldn't have to manually run queries against databases for new activity. I'm aware of SQL Profiler, but when I reviewed it, it seemed like overkill for what I wanted to do (and it also wouldn't do the Oracle DB monitoring). Also, to use SQL Profiler, you have to be an admin of the database. I would need to monitor databases where I only have a read-only account.</p>
<p>Does someone know if such a tool exists?</p>
| <p>Sounds like something really easy to write yourself. Just query the database schema, then do a select count(*) or select max(lastUpdateTime) query on each table and save the result. If something is different send yourself an email. JDBC in Java gives you access to the schema information in a cross-database manner. Don't know about ADO.</p>
|
ASP.NET 404 (page not found) redirection with original parameters preserved <p>I'm replacing an old web application with a new one, with different structure.</p>
<p>I can not change the virtual directory path for the new app, as I have users which have bookmarked different links to the old app.</p>
<p>Lets say I have a user, who has this bookmark:</p>
<p><a href="http://server/webapp/oldpage.aspx?data=somedata" rel="nofollow">http://server/webapp/oldpage.aspx?data=somedata</a></p>
<p>My new app is going to reside in the same virtual directory, replacing the old one, but it has no longer oldpage.aspx, instead it has different layout, but it still needs the parameter from the old url.</p>
<p>So, I have set to redirect 404 errors to redirectfrombookmark.aspx, where I decide how to process the request.</p>
<p>The problem is, that the only parameter I receive is "aspxerrorpath=/webapp/oldpage.aspx", but not the "data" parameter, and I need it to correctly process the request.</p>
<p>Any idea how I can get the full "original" url in the 404 handler?</p>
<p>EDIT: reading the answers, looks like I did not make the question clear enough:</p>
<ol>
<li>The users have bookmarked many different pages (oldpage1, oldpage2, etc.) and I should handle them equally.</li>
<li>The parameters for each old page are almost the same, and I need a specific ones only.</li>
<li>I want to re-use the "old" virtual directory name for the "new" application.</li>
<li>The search bots, etc., are not a concern, this is internal application with dynamic content, which expires very often.</li>
</ol>
<p>The question is - can I do this w/o creating a bunch of empty pages in my "new" application with the old names, and Request.Redirect in their OnLoad. I.e. can this be done using the 404 mechanism, or some event handling in Global.asax, etc.</p>
| <p>For the purposes of SEO, you should <strong>never</strong> redirect on a 404 error. A 404 should be a dead-end, with some helpful information of how to locate the page you're looking for, such a site map.</p>
<p>You should be using a <strong>301, moved permanently</strong>. This allows the search bots to update their index without losing the page rank assigned to the original page,</p>
<p>See: <a href="http://www.webconfs.com/how-to-redirect-a-webpage.php" rel="nofollow">http://www.webconfs.com/how-to-redirect-a-webpage.php</a> on how to code this type of response.</p>
|
JavaScript Endian Encoding? <p><a href="http://stackoverflow.com/questions/503052/javascript-is-ip-in-one-of-these-subnets/503238#503238">A response on SO</a> got me thinking, does JavaScript guarantee a certain endian encoding across OSs and browsers?</p>
<p>Or put another way are bitwise shifts on integers "safe" in JavaScript?</p>
| <p>Shifting is safe, but your question is flawed because endianness doesn't affect bit-shift operations anyway. Shifting left is the same on big-endian and little-endian systems in all languages. (Shifting right can differ, but only due to interpretation of the sign bit, not the relative positions of any bits.)</p>
<p>Endianness only comes into play when you have the option of interpreting some block of memory as bytes or as larger integer values. In general, Javascript doesn't give you that option since you don't get access to arbitrary blocks of memory, especially not the blocks of memory occupied by variables. <a href="http://www.khronos.org/registry/typedarray/">Typed arrays</a> offer views of data in an endian-sensitive way, but the ordering depends on the host system; it's not necessarily the same for all possible Javascript host environments.</p>
<p>Endianness describes <em>physical</em> storage order, not <em>logical</em> storage order. Logically, the rightmost bit is <em>always</em> the least significant bit. Whether that bit's byte is the one that resides at the lowest memory address is a completely separate issue, and it only matters when your language exposes such a concept as "lowest memory address," which Javascript does not. Typed arrays do, but then only within the context of typed arrays; they still don't offer access to the storage of arbitrary data.</p>
|
Oracle Delete Rows Matching On Multiple Values <p>I want to do something like:</p>
<pre><code>DELETE FROM student WHERE
student.course, student.major IN
(SELECT schedule.course, schedule.major FROM schedule)
</code></pre>
<p>However, it seems that you can only use one column with the IN operator. Is that true? Seems like a query like this should be possible.</p>
| <p>No, you just need parentheses:</p>
<pre><code>DELETE FROM student WHERE
(student.course, student.major) IN
(SELECT schedule.course, schedule.major FROM schedule)
</code></pre>
|
System.Net.Mail.MailMessage questions <p>I am putting some email functionality into one of my asp.net projects:</p>
<p>I need to send an email to a list of subscribers, list varies from a few dozen to a few hundred subscribers - (down the road there could be thousands).</p>
<p>When I have a few dozen emails, I do this:</p>
<pre><code>Mailmsg.Bcc.Add(New System.Net.Mail.MailAddress("asample@gmail.com"))
</code></pre>
<p>for each subscriber, and it works fine. </p>
<p>What would be a practical limit on the number of email addresses you can add this way before you bogged something down? Also, if you add say 300 email address to a 'To' or 'BCC' field, where does the work happen that splits the single email into seperate emails? at your smtp server? </p>
<p>What are the pro's and con's of adding dozens or hundreds of addresses to you emails, versus having your code loop thru and send one at a time. Is one method more likely than another to be flagged as spam?</p>
| <p>The limit is more driven by your connectivity and SMTP server...BUT, you are going about it the wrong way. One sure fire way to be seen as spam is to send an email with a bunch of BCC items. Send one email per recipient with them as the TO address and you will be better off.</p>
|
SQL 2005 Transactional Replication: Behavior during snapshot processing? <p>So, I've got SQL (2005) Transactional Replication generally working well with a single publisher and single (read-only) subscriber. Data changes and updates flow perfectly, with about 5 second latency, which is just fine. </p>
<p>My one nagging problem, that I've spent a couple days trying to solve (and Googling everywhere for answers) is that <em>new</em> sprocs/tables/etc. do not get propagated to the read-only subscriber, even though I've added them as "articles" to the "publication". The publication has "transmit schema changes" set to ON, and stored procedures are set to transfer their definitions. But, for some reason, they don't.</p>
<p>My "snapshot agent" process is set to NOT SCHEDULED. (In other words, it only happens once, when I initiate it manually.) Should I be putting this on a schedule to enable the transfer of new or modified tables and sprocs? </p>
<p>I thought the mere act of adding the object as an article to the publication would do it, but it's still not sending it unless I do a snapshot. The WAN connecting these is totally fast and reliable, so that's not the issue, and table-data-updates transfer relatively fast and flawlessly.</p>
<p>While I could put my snapshot agent on a schedule, does this have any real-time production impacts for users of the main publication database or the read-only copy? (My site currently gets 4+ million unique-users a month, so I'd like to have minimal disruption...) Thanks!</p>
| <p>Transactional replication only distributes (and then subsequently publishes) the DML (Data Manipulation Language) statements from the transaction log of the source (publication) database.</p>
<p>New tables and stored procedures are not replicated to the subscriber. Schema changes in this particular context, although I have to admit it is a little unclear in some of the Books Online documentation, refer to the existing schema, i.e. if you were to a add column to an existing database this change would be propagated to the subscribers.</p>
<p>For clarification here is a Microsoft article that details the schema changes that you can make.</p>
<p>[<a href="http://msdn.microsoft.com/en-us/library/ms151870" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms151870</a>(SQL.90).aspx][1]</p>
<p>I hope this helps. Replication is a big subject area so please let me know if I can be of further assistance.</p>
<p>Oh yes, you are correct, if you add new articles to your publication you will need to create an updated snapshot.</p>
<p>Cheers,</p>
|
How do I submit a form with a link in ASP.Net MVC? <p>I have a HTML form, and I have a Controller Action that accepts the POST request. Everything works with a regular submit button, but I would like to submit the form with a link (<a>-tag) instead, to be able to further control the formatting. Is there any way of doing this nicely built into the ASP.NET MVC Framework, or should I write my own extension method? Is it even possible to do this without javascript (I will use AJAX in the future, but it has to work without).</p>
| <p><a href="http://haacked.com/archive/2009/01/30/delete-link-with-downlevel-support.aspx" rel="nofollow">Here is a complete example.</a> Note that this particular example does something fairly important: it has a fallback for browsers with JavaScript disabled.</p>
|
Intel boot agent problem? <p>keep getting this message over and over adin.. what shoud i do?
Intel(R) Boot Agent FE v4.1.17
Copyright (C) 1997-2004, Intel Corporation</p>
<p>Intel(R) Boot Agent PXE Base Code (PXE-2.1 build 084)
Copyright (C) 1997-2004, Intel Corporation</p>
<p>CLIENT MAC ADDR: 00 16 76 71 64 8B GUID:6377B694 F156 11DA 9A0F 00112FEBB9DF
PXE-E53: NO boot filename received</p>
<p>PXE-M0F: Exiting Intel Boot Agent
No bootable device -- insert boot disk and press any key</p>
| <p>Check if the right hard disk set as boot-device in your BIOS.</p>
<p>If that doesn't work, did you install a new OS? If yes, you might need to boot from a CD and write a new boot record on the hard-disk.</p>
<p>The message means that the Intel Boot Agent couldn't find an Operating System to boot into. Specifically your computer is trying to boot from the network. Check your BIOS settings!</p>
|
LINQ to XML: Collapse mutliple levels to single list <p>I'm currently working on a Silverlight app and need to convert XML data into appropriate objects to data bind to. The basic class definition for this discussion is:</p>
<pre><code>public class TabularEntry
{
public string Tag { get; set; }
public string Description { get; set; }
public string Code { get; set; }
public string UseNote { get; set; }
public List<string> Excludes { get; set; }
public List<string> Includes { get; set; }
public List<string> Synonyms { get; set; }
public string Flags { get; set; }
public List<TabularEntry> SubEntries { get; set; }
}
</code></pre>
<p>An example of the XML that might come in to feed this object follows:</p>
<pre><code><I4 Ref="1">222.2
<DX>Prostate</DX>
<EX>
<I>adenomatous hyperplasia of prostate (600.20-600.21)</I>
<I>prostatic:
<I>adenoma (600.20-600.21)</I>
<I>enlargement (600.00-600.01)</I>
<I>hypertrophy (600.00-600.01)</I>
</I>
</EX>
<FL>M</FL>
</I4>
</code></pre>
<p>So, various nodes map to specific properties. The key ones for this question are the <code><EX></code> and <code><I></code> nodes. The <code><EX></code> nodes will contain a collection of one or more <code><I></code> nodes and in this example matches up to the 'Excludes' property in the above class definition.</p>
<p>Here comes the challenge (for me). I don't have control over the web service that emits this XML, so changing it isn't an option. You'll notice that in this example one <code><I></code> node also contains another collection of one or more <code><I></code> nodes. I'm hoping that I could use a LINQ to XML query that will allow me to consolidate both levels into a single collection and will use a character that will delimit the lower level items, so in this example, when the LINQ query returned a TablularEntry object, it would contain a collection of Exclude items that would appear as follows:</p>
<ul>
<li>adenomatous hyperplasia of prostate
(600.20-600.21)</li>
<li>prostatic:</li>
<li>*adenoma (600.20-600.21)</li>
<li>*enlargement (600.00-600.01)</li>
<li>*hypertrophy (600.00-600.01)</li>
</ul>
<p>So, in the XML the last 3 entries are actually child objects of the second entry, but in the object's Excludes property, they are all part of the same collection, with the former child objects containing an identifier character/string.</p>
<p>I have the beginnings of the LINQ query I'm using below, I can't quite figure out the bit that will consolidate the child objects for me. The code as it exists right now is:</p>
<pre><code>List<TabularEntry> GetTabularEntries(XElement source)
{
List<TabularEntry> result;
result = (from tabularentry in source.Elements()
select new TabularEntry()
{
Tag = tabularentry.Name.ToString(),
Description = tabularentry.Element("DX").ToString(),
Code = tabularentry.FirstNode.ToString(),
UseNote = tabularentry.Element("UN") == null ? null : tabularentry.Element("UN").Value,
Excludes = (from i in tabularentry.Element("EX").Elements("I")
select i.Value).ToList()
}).ToList();
return result;
}
</code></pre>
<p>I'm thinking that I need to nest a FROM statement inside the </p>
<blockquote>
<p>Excludes = (from i...)</p>
</blockquote>
<p>statement to gather up the child nodes, but can't quite work it through. Of course, that may be because I'm off in the weeds a bit on my logic.</p>
<p>If you need more info to answer, feel free to ask.</p>
<p>Thanks in advance,</p>
<p>Steve</p>
| <p>Try this:</p>
<pre><code> List<TabularEntry> GetTabularEntries(XElement source)
{
List<TabularEntry> result;
result = (from tabularentry in source.Elements()
select new TabularEntry()
{
Tag = tabularentry.Name.ToString(),
Description = tabularentry.Element("DX").ToString(),
Code = tabularentry.FirstNode.ToString(),
UseNote = tabularentry.Element("UN") == null ? null : tabularentry.Element("UN").Value,
Excludes = (from i in tabularentry.Element("EX").Descendants("I")
select (i.Parent.Name == "I" ? "*" + i.Value : i.Value)).ToList()
}).ToList();
return result;
}
</code></pre>
<p><strong>(edit)</strong></p>
<p>If you need the current nested level of "I" you could do something like:</p>
<pre><code> List<TabularEntry> GetTabularEntries(XElement source)
{
List<TabularEntry> result;
result = (from tabularentry in source.Elements()
select new TabularEntry()
{
Tag = tabularentry.Name.ToString(),
Description = tabularentry.Element("DX").ToString(),
Code = tabularentry.FirstNode.ToString(),
UseNote = tabularentry.Element("UN") == null ? null : tabularentry.Element("UN").Value,
Excludes = (from i in tabularentry.Element("EX").Descendants("I")
select (ElementWithPrefix(i, '*'))).ToList()
}).ToList();
return result;
}
string ElementWithPrefix(XElement element, char c)
{
string prefix = "";
for (XElement e = element.Parent; e.Name == "I"; e = e.Parent)
{
prefix += c;
}
return prefix + ExtractTextValue(element);
}
string ExtractTextValue(XElement element)
{
if (element.HasElements)
{
return element.Value.Split(new[] { '\n' })[0].Trim();
}
else
return element.Value.Trim();
}
</code></pre>
<p>Input:</p>
<pre><code><EX>
<I>adenomatous hyperplasia of prostate (600.20-600.21)</I>
<I>prostatic:
<I>adenoma (600.20-600.21)</I>
<I>enlargement (600.00-600.01)</I>
<I>hypertrophy (600.00-600.01)
<I>Bla1</I>
<I>Bla2
<I>BlaBla1</I>
</I>
<I>Bla3</I>
</I>
</I>
</EX>
</code></pre>
<p>Result:</p>
<pre><code>* adenomatous hyperplasia of prostate (600.20-600.21)
* prostatic:
* *adenoma (600.20-600.21)
* *enlargement (600.00-600.01)
* *hypertrophy (600.00-600.01)
* **Bla1
* **Bla2
* ***BlaBla1
* **Bla3
</code></pre>
|
Mailchimp API & array <p>I'm having a bear of a time getting the mailchimp api to cough up info. In their example I'm fine (the first is an abridged version of theirs.) How come when the method changes I can't get the array to show the collected information?</p>
<p>Why is this code valid:</p>
<pre><code>$limit = 5;
for($i=0;$i<5;$i++){
$allstats = $acct->campaignEmailStatsAIMAll($campaignId, $i*$limit, $limit);
foreach($allstats as $email=>$stats){
echo "[".$email."]\n";
}
}
</code></pre>
<p>It's taken from here (I just removed some of the iterative data):</p>
<blockquote>
<p><a href="http://www.mailchimp.com/api/rtfm/campaignemailstatsaimall.func.php" rel="nofollow">http://www.mailchimp.com/api/rtfm/campaignemailstatsaimall.func.php</a></p>
</blockquote>
<p>But this code is not:</p>
<pre><code>$limit = 5;
for($i=0;$i<5;$i++){
$allstats = $acct->campaignOpenedAIM($campaignId, $i*$limit, $limit);
foreach ($allstats as $email => $stats) {
echo $stats;
}
}
</code></pre>
<p>This is the function listed here:</p>
<blockquote>
<p><a href="http://www.mailchimp.com/api/rtfm/campaignopenedaim.func.php" rel="nofollow">http://www.mailchimp.com/api/rtfm/campaignopenedaim.func.php</a></p>
</blockquote>
<p>Most importantly, as my attempt has failed, how would you write the second method (<code>campaignOpenAIM</code>) to iterate through the data in the captured array? </p>
<p><strong>UPDATE:</strong> </p>
<p>It would appear that the array is empty. But why is it empty when the parameters haven't changed?</p>
| <p>are you sure that your results ($allstats) is not empty?</p>
|
Create & Copy Access tables to SQL via SSIS? SQL 2008 <p>I am trying come up with a way to pull the tables out of an Access database, automate the creation of those same tables in a SQL 2008 DB, and move the data to the new tables. This process will happen on a regular basis and there may be different tables each time.</p>
<p>I would like to do this totally in SSIS. </p>
<p>C# SQL CLR objects are an option.</p>
<p>The main issue I have been running into is how to get the Access table's schema and then convert that to a SQL script that I can run via SSIS.</p>
<p>Any ideas?</p>
<p>TIA
J</p>
| <p>SSIS cannot adapt to new tables at runtime. (You can change connections, move a source to a table with a different name, but the same schema) So, it's not really easy to do what I think you are saying: Upsize an arbitrary set of tables in an Access DB to SQL (mirroring their structure and data, naming, etc), so that I can then write some straight SQL to transform the data into another SQL database or the same part of the database.</p>
<p>You can access the SSIS object model from C# and build a package (or modify a template package) programmatically and then execute it. This might offer the best bang for your buck, but the SSIS object model is kind of deep. The SSIS Team blog have <a href="http://blogs.msdn.com/mattm/archive/2008/12/30/samples-for-creating-ssis-packages-programmatically.aspx" rel="nofollow">finally started putting up examples</a> (a year after I had to figure a lot of this out for myself)</p>
<p>There is always the upsizing wizard, and I'm sure there are some third party tools.</p>
|
Is it possible to initialize a UINavigationController subclass from a NIB? <p>I have a <code>UITabBarController</code> based application. The tabs will be created from database entries, so I don't know them in advance. I'd like to <strong>programmatically</strong> initialize a <code>UINavigationController</code> subclass (I have a few different kinds) for each tab. </p>
<p>Ideally, I would really like to draw the whole <code>UINavigationController</code> subclass + it's subview using Interface Builder, just like you can do when you add define the view for each tab in IB (that's when you know what the tabs will be in advance). I've tried setting the "Class identity" to my <code>UINavigationController</code> subclass name, then add a <code>UINavigationController</code> inside it, but obviously it didn't inject the instance at the "File's owner" level...</p>
<p>Thanks</p>
| <p>I've ended up not subclassing <code>UINavigationController</code>, it appears it isn't what's recommended. I quickly realized that there wasn't a whole lot of benefit from designing the <code>UINavigationController</code>'s from within IB. Instead, I subclassed <code>UIViewController</code>, wrote the few lines of init for the<code>UINavigationBar</code> (custom buttons, custom middle image) in my <code>viewDidLoad</code>. It's just better to simply wrap the subclass with <code>[[UINavigationController alloc] initWithRootController: subclass];</code> when I programmatically fill my tabs. Subclassing <code>UINavigationController</code>directly prevented me from properly using the <code>navigationItem</code> property of my inject view.</p>
|
logical & physical components <p>For this group assignment we have to produce a design document which includes a decomposition of the system/intermodule dependencies as well as interprocess dependencies. </p>
<p>We are warned to be aware of the differences between logical and physical components. Could someone please explain to me what each is? </p>
<p>Thanks.</p>
| <p>A component is a specialized class that has an external specification in the form of one or more provided and required interfaces, and an internal implementation consisting of one or more classifiers that realize its behaviors. (Thanks to the UML spec for that definition).</p>
<p>A physical component is platform-specific, something like a CORBA or .NET or WSDL component - something that exists in a concrete form in your system. A logical component is platform-independent (or platform-agnostic), a useful design artefact that may or may not be implemented as a physical component.</p>
|
What's the best way to read mixed (i.e. text and binary) data? <p>I need to be able to read a file format that mixes binary and non-binary data. Assuming I know the input is good, what's the best way to do this? As an example, let's take a file that has a double as the first line, a newline (0x0D 0x0A) and then ten bytes of binary data afterward. I could, of course, calculate the position of the newline, then make a BinaryReader and seek to that position, but I keep thinking that there has to be a better way.</p>
| <p>You can use System.IO.BinaryReader. The problem with this though is you <em>must</em> know what type of data you are going to be reading before you call any of the Read methods.</p>
<pre><code>Read(byte[], int, int)
Read(char[], int, int)
Read()
Read7BitEncodedInt()
ReadBoolean()
ReadByte()
ReadBytes(int)
ReadChar()
ReadChars()
ReadDecimal()
ReadDouble()
ReadInt16()
ReadInt32()
ReadInt64()
ReadSByte()
ReadSingle()
ReadString()
ReadUInt16()
ReadUInt32()
ReadUInt64()
</code></pre>
<p>And of course the same methods exist for writing in System.IO.BinaryWriter.</p>
|
Driving NDepend with NUnit <p>Is it possible to use NUnit to run CQL queries using NDepend? It would be nice to be able to just include the NDepend dlls in a UnitTests library and write tests like:</p>
<pre><code>[Test] public void
DomainAssemblyHasNoDatabaseDependencies
...
</code></pre>
<p>or something similar.</p>
<p>This would make it very easy to integrate with Team City, and automatically fail the build if any of the static analysis tests fail.</p>
| <p>This is possible thanks to <a href="http://www.ndepend.com/API/webframe.html" rel="nofollow">NDepend.API</a> released with NDepend v4, and especially thanks to the namespace <a href="http://www.ndepend.com/API/webframe.html?NDepend.API~NDepend.CodeQuery_namespace.html" rel="nofollow">NDepend.CodeQuery</a> that contains what is needed to run programatically CQLinq or CQL code queries and rules presented as a simple string.</p>
<p><a href="http://www.ndepend.com/API/webframe.html?NDepend.API_gettingstarted.html" rel="nofollow">Here is documentation to get started with NDepend.API</a>.</p>
<p>We advise looking at the source code of the PowerTool named <em>Query Code with CQLinq</em> available in <em>$NDependInstallPath$\NDepend.PowerTools.SourceCode\NDepend.PowerTools.sln</em></p>
<p>Notice finally, that thanks to NDepend.API, you can also write directly your code queries/rules or even static analyzer with C# or VB.NET code (hence code that can be embedded in your unit tests).</p>
|
Accessing hardware from within Internet Explorer <p>Is it possible to access hardware devices (web-cams, magnetic card readers, etc.) from within Internet explorer? </p>
<p>If yes, what technologies are used? And are there any .Net examples.</p>
<p>In my case, I need to access a magnetic card reader that would be attached to the client computer. The web-app would need to be able to access the reader and get the card information, which will then be used to access data-tables from a database running on the server.</p>
<p>I have seen web-cams that are integrated into websites, was wondering how that is done? Because if web-cams can be accessed, so should any other device attached to a USB port.</p>
<p>Finally, can SilverLight applications access hardware? Can they print to an attached printer?</p>
| <p>Custom ActiveX control is probably your best bet</p>
|
How do I find the current machine's full hostname in C (hostname and domain information)? <p>In a C project (POSIX), how do I get the fully qualified name for the current system?</p>
<p>For example, I can get just the hostname of my machine by doing
<code>gethostname()</code> from unistd.h. This might give me <code>machine3</code> in return, but I'm actually looking for <code>machine3.somedomain.com</code> for example.</p>
<p>How do I go about getting this information? I do not want to use a call to system() to do this, if possible.</p>
| <p>To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.</p>
<p>The easiest way to do this is by first getting the local hostname using <code>uname()</code> or <code>gethostname()</code> and then performing a lookup with <code>gethostbyname()</code> and looking at the <code>h_name</code> member of the struct it returns. If you are using ANSI c, you <em>must</em> use <code>uname()</code> instead of <code>gethostname()</code>.</p>
<p>Example:</p>
<pre><code>char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);
</code></pre>
<p>Unfortunately, <code>gethostbyname()</code> is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use <code>getaddrinfo()</code>.</p>
<p>Example:</p>
<pre><code>struct addrinfo hints, *info, *p;
int gai_result;
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
exit(1);
}
for(p = info; p != NULL; p = p->ai_next) {
printf("hostname: %s\n", p->ai_canonname);
}
freeaddrinfo(info);
</code></pre>
<p>Of course, this will only work if the machine has a FQDN to give - if not, the result of the <code>getaddrinfo()</code> ends up being the same as the unqualified hostname.</p>
|
scope in PHP classes <p>I am creating a database connection object, and I'm not sure what the best way would be...</p>
<p>If I create a dbConnection class which establishes the connection (using mysql_connect) can I then call mysql_query from anywhere in the main script?</p>
<p>what about from inside OTHER classes? Do i need to pass the object or attribute as parameters?</p>
<p>Basically, I'm looking for the best way (in terms of speed + memory) of connecting to the database ONCE using a simple class...</p>
<p>I've posted my constructor for the Database Connection class:</p>
<pre><code>function __construct($database="") {
if (!empty($database)){ $this->db = $database; }
$this->dblink = mysql_connect($this->host,$this->username,$this->password);
if (!this->dblink) {
//Fatal Error
}
mysql_select_db($this->db, $this->dblink);
</code></pre>
<p>}</p>
| <p>Rather than create your own database abstraction class, I would recommend giving <a href="http://www.woyano.com/jv/ezsql" rel="nofollow">ezSQL</a> a try. The author did an excellent job of making it very easy to use. The data structures returned from the queries done by the class are far more flexible than those returned by mysql_query and it would save you a lot of work.</p>
|
Extract email addresses from a block of text <p>How can I create an array of email addresses contained within a block of text?
I've tried</p>
<p><code>addrs = text.scan(/ .+?@.+? /).map{|e| e[1...-1]}</code></p>
<p>but (not surprisingly) it doesn't work reliably. </p>
| <p>Howabout this for a (slightly) better regular expression</p>
<pre><code>\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
</code></pre>
<p>You can find this here:</p>
<p><a href="http://www.regular-expressions.info/email.html" rel="nofollow">Email Regex</a></p>
<p>Just an FYI, the problem with your email is that you allow only one type of separator before or after an email address. You would match "@" alone, if separated by spaces.</p>
|
SQL tables subquery <p>I have two tables named <code>foo</code> and <code>bar</code>, hypothetically speaking.</p>
<p>foo has columns <code>foo_id</code>, <code>foo_fluff</code>
bar has columns <code>bar_id</code>, <code>foo_id</code>, <code>timestamp</code></p>
<p>I need a query which will retrieve return one row for any foo_id that the table bar contains, with the latest timestamp.</p>
<p>So, if bar has three rows, two of which have a foo_id of 1, and 1 of which has foo_id 2, it'll return 2 rows. For foo_id 1 it'll return the row which has the greater timestamp of the two rows.</p>
| <p>I think this is what you are looking for (unless it must be a subquery and not a join)</p>
<pre><code>select max(bar.timestamp), foo.foo_fluff
from foo
inner join bar
on foo.foo_id = bar.foo_id
group by foo.foo_fluff
</code></pre>
|
Developing a Robocode type game with .Net, for a School Assignment <p>I am currently in my final year at school, studying for a Higher National Diploma in Computer Studies, and basically in this final semester, we need to develop a Software Project, that basically incorporates a <em>whole</em> system.</p>
<p>Now, what I'm thinking of doing is something along the lines of <a href="http://robocode.sourceforge.net/">Robocode</a>, but instead of Java, I will be doing this with the .Net Framework.</p>
<p><hr /></p>
<h2>What is Robocode ?</h2>
<p>For those of you don't know what Robocode is, it's basically a sort of programming game in where people develop their own robots using methods from the class interfaces and downloadable classes that exist, and then they <em>fight</em> each other in an autonomous battle in an arena...like such: </p>
<p><img src="http://articles.techrepublic.com.com/i/tr/cms/contentPics/robocode.gif" alt="alt text" /></p>
<p><hr /></p>
<p>So basically, as I said, I want to recreate this sort of scenario using the .Net Framework..and I am posting this question here on StackOverflow in hope that more experienced developers will be able to guide me in the right direction for this project.</p>
<p>What I have in mind up till now is basically to create:</p>
<ul>
<li>An Offline application that will serve as the battle arena and the user-interface to create new battles with existing robots and such.</li>
<li>An Online interface that players will able to use to register new robots, view past tournament scores etc...</li>
<li>And obviously the Class Interfaces that players will need to use to create their robots.</li>
</ul>
<p><hr /></p>
<h2>Animation and Graphics (for the actual battles)</h2>
<p>Now, of course there will be some sort of animation and movement when the battle occurs, and I haven't decided what yet to use as a medium for this.</p>
<p>The options I currently have in mind are:</p>
<ul>
<li>Developing, as I said in the first above bullet points, an offline application that will serve as a battle grounds, and all animations will be done using mainly C# code</li>
<li>Or develop a Silverlight Application that will handle the animations (thus, changing the scenario from an offline applcation to now an online one</li>
<li>Or, maybe the least feasable of them, create the battle animations using JavaScript, with something like the <a href="http://https%3A//developer.mozilla.org/en/Canvas%5Ftutorial">Canvas</a></li>
</ul>
<p><strong>What do you think could be more suitable for this particular scenario ?</strong></p>
<p><hr /></p>
<h2>Developing Classes and Interfaces</h2>
<p>For the players to develop the robots, I will provide certain Class Interfaces that they will be able to use like in Robocode.</p>
<p>Examples of such events and methods may include:</p>
<pre><code>public void run () {}
public void onScannedRobot(ScannedRobotEvent e) {}
walk(/* ammount in pixels or w/e to walk to */);
turnRight(/* value in degrees for an angular turn */);
//etc...
</code></pre>
<p>Here is a snippet from code in Robocode (Java) :</p>
<pre><code>public class MyFirstRobot extends Robot {
public void run() {
while (true) {
ahead(100);
turnGunRight(360);
back(100);
turnGunRight(360);
}
}
}
</code></pre>
<p>For then to actually make the battles happen, I am thinking of using Reflection to actually read what methods the user is actually making use of and implementing them to run and be invoked at particular moments of the battle and such.</p>
<p><hr /></p>
<p>Now, what I kindly and humbly ask of you experienced developers, is to guide me a bit through this project of mine and advise me on what needs to be done...for starters, <strong><em>is this project feasible at all ?</em></strong> And if it actually is, <strong><em>from where do I need to actually start with my project?</em></strong></p>
<p><hr /></p>
<p>As regards technologies and software I intend to be using are : </p>
<ul>
<li>.NET Framework 3.5, with C# 3.0</li>
<li>LINQ (Language Integrated Query)</li>
<li>SQL Server 2008</li>
<li>Microsoft Visual Studio 2008</li>
<li>jQuery Framework</li>
<li>Possibly Silverlight</li>
</ul>
<p><hr /></p>
<p>I thank you all, even for managing to read up to this point in my question and I will need and appreciate greatly all the help I can get to finish this project.</p>
<p>Thank you for your time and effort.</p>
<p><hr /></p>
<p>Btw, up till now, apart from <a href="http://robocode.sourceforge.net/">Robocode</a>, I have found these games that are similar to what I am trying to create:</p>
<ul>
<li><a href="http://home.gna.org/nrobot/">NRobot</a></li>
<li><a href="http://vrs-net.sourceforge.net/">Virii</a> (thanks <a href="http://stackoverflow.com/questions/505040/developing-a-robocode-type-game-with-net-for-a-school-assignment#505076">Marc</a>)</li>
</ul>
| <blockquote>
<p>is this project feasible at all ?</p>
</blockquote>
<p>It sounds big. I don't know how much time you have. Here's a rule of thumb:</p>
<ul>
<li><p>When the drop-dead due-date happens, if 90% of the system delivering 90% of the functionality is 100% complete, then you might say that the project is at least 90% successful.</p></li>
<li><p>OTOH if 100% of the software delivering 100% of the functionality is only 90% finished (i.e., is not finished) then nothing is finished and the project is a failure.</p></li>
</ul>
<p>A key to success, then, is "incremental development" and "continual delivery". Your project specification says:</p>
<blockquote>
<p>We need to develop a Software Project, that basically incorporates a <em>whole</em> system.</p>
</blockquote>
<p>To do this, I suggest:</p>
<ol>
<li>Create (i.e., design, develop, and test) a <strong>small whole</strong> system</li>
<li>Repeat { backup or version control what you have; add a new, whole little bit to the system, and test it until it's satisfactory } until (you run out of time).</li>
</ol>
|
Refresh A Image Src <p>k... Strager was able to help me a bit. However, it's still not working quite right. Need someone that knows both MVC and jQuery please...</p>
<p>I have a page that has a image that when clicked on will launch a dialog box that gives the ability to upload a file. Once the dialog closes the image is supposed to refresh with what was uploaded/stored in the database...</p>
<p>All works great the first time. However if I try uploading a 2nd image; the 1st image still displays. It also doesn't seem like my controller method is being called the 2nd time... Below is my code...</p>
<p>I've also eliminated that the page is being cached. Again, the controller method is not being called the 2nd time around...</p>
<p><strong>Controller</strong></p>
<pre><code>[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetImage(Guid parentId)
{
var la = Helper.Service.GetAttachmentByEntity(parentId, MembershipProvider.SecurityTicket).ToList();
la.OrderByDescending(x => x.CreatedDate);
return File(la[0].Data, la[0].ContentType);
}
</code></pre>
<p><strong>View</strong></p>
<pre><code><script type="text/javascript">
$(function() {
var iphcObject = $('#<%=imagePlaceHolderControl.ClientID %>');
iphcObject.children().find('#imageUploadDialog').bind('onClose', function() {
iphcObject.children().find('#image').attr('src', '<%=Url.Action("GetImage", "Image", new { parentId = Model.ParentId }) %>');
});
});
</script>
<asp:Panel ID="imagePlaceHolderControl" runat="server">
<div style="border: solid 1px; width: <%=Model.Width%>; height: <%=Model.Height%>; text-align: center; vertical-align: middle;">
<a href="#" onclick="$('#imageUploadDialog').dialog('open');" title="Add a picture...">
<img id="image" src="<%=Url.Content("~/content/images/icon_individual_blank.gif") %>" /></a>
<%Html.RenderDialog("imageUploadDialog", "Upload image...", "ImagePlaceHolder_Upload", "Image", Model, 235, 335); %>
</div>
</asp:Panel>
</code></pre>
| <p>What is #image shouldn't it be find('img')? Or give the IMG an ID of 'image'.</p>
|
How to change the text color on UINavigationBar button items <p>I've got a UINavigationController and i've changed it to white using the Tint property of the navigation bar in Interface Builder. But the text in buttons and the title is still the default color, white, and so gets lost against the white background. Anyone know how to work around this?</p>
| <p>As of iOS 5 this it much easier, using the UIBarButtonItem appearance proxy:</p>
<pre><code> NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor blackColor],
UITextAttributeTextColor,
[UIColor clearColor],
UITextAttributeTextShadowColor, nil];
[[UIBarButtonItem appearance] setTitleTextAttributes: attributes
forState: UIControlStateNormal];
</code></pre>
<p>Set this in application:didFinishLaunchingWithOptions: </p>
|
DeflateStream 4GB Limit in .NET <p>From MSDN: <em><a href="http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx" rel="nofollow">DeflateStream Class</a></em></p>
<p>DeflateStream cannot be used to compress files larger than 4 GB.</p>
<p>Are there any other implementations for .NET without the 4 GB limit?</p>
<p>NOTE: I really need to decompress a file in GZ format with content larger than 4 GB. Can any code do that?</p>
| <p>FYI, we have removed the 4 GB limit from DeflateStream in .NET 4.</p>
|
Recommendation for Sqlite DB manager application? <p>There are quite a few Sqlite GUI applications listed here:</p>
<p><a href="http://www.sqlite.org/cvstrac/wiki?p=ManagementTools">http://www.sqlite.org/cvstrac/wiki?p=ManagementTools</a></p>
<p>some appear to be incomplete, buggy, not maintained, etc. Do you have any recommendations?</p>
| <p>I use the <a href="https://addons.mozilla.org/en-US/firefox/addon/5817">SQLite manager plugin for Firefox</a>.</p>
<p>It seems pretty stable to me.</p>
|
Py2exe for Python 3.0 <p>I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.</p>
<p>Any ideas?</p>
| <h3>Update 2014-05-15</h3>
<p>py2exe for Python 3.x is now released! <a href="https://pypi.python.org/pypi/py2exe">Get it on PyPI</a>.</p>
<h3>Old information</h3>
<p>Have a look at the py2exe SourceForge project SVN repository at:</p>
<p><a href="http://py2exe.svn.sourceforge.net/">http://py2exe.svn.sourceforge.net/</a></p>
<p>The last I looked at it, it said the last update was August 2009. But keep an eye on that to see if there's any Python 3 work in-progress.</p>
<p>I've also submitted two feature requests on the py2exe tracker. So far, no feedback on them:</p>
<ul>
<li><a href="http://sourceforge.net/tracker/?func=detail&aid=3011276&group_id=15583&atid=365583">Support Python 3.x</a></li>
<li><a href="http://sourceforge.net/tracker/?func=detail&aid=3031912&group_id=15583&atid=365583">Project roadmap</a></li>
</ul>
|
How can i know if a given SPWeb is a SearchCenter site programmatically <p>I have a SPWeb object and I want to know whether or not this is a SearchCenter site. How can I know it programmatically. Is there some setting to check or a guid to match etc?</p>
| <p>A SearchCenter is created from a special site template that you can identify from the <a href="http://www.codeplex.com/sharepointinstaller/Thread/View.aspx?ThreadId=34752" rel="nofollow">WebTemplate</a> property on the SPWeb object. It will carry the value 'SRCHCEN'.</p>
|
How do I specify a return url for a link to the login form? <p>Simple enough, it would seem, but it turns out not to be - mainly due to the fact that the View can't possibly know which way through Model and Controller you got there. Regardless, it is a problem that needs a solution:</p>
<p>I have a login link, that takes the user to a form to enter username and password. When the user clicks "submit", I want to redirect to the page he was viewing. The easiest way to do so seems to be specifying the url to the current page as a querystring (<code>...?returnUrl=...</code>) and everything else is already built.</p>
<p>But where do I find this url from my view, when rendering the link? I naturally can't use a RedirectToActionResult as I don't want to actually transfer the user - only render the url in a link. How to?</p>
<p><hr /></p>
<p>EDIT:</p>
<p>I have now started a bounty on this question, and therefore I see fit to clarify my needs as well.</p>
<p>I have a UserControl named Login.ascx in my Shared folder. In it, I render an ActionLink to the login form, and it is included in the footer on my Masterpage. What I want to accomplish is the following:</p>
<p>When the ActionLink is rendered, the querystring <code>returnUrl</code> is appended with <strong>the a route to the view that is currently being rendered</strong>. If this is accomplished, the user will be taken back to the page he/she was viewing after successful login with functionality that is already build into the ASP.NET MVC Framework.</p>
<p>The reason the previous answers have not been sufficient is mainly that they have not provided a way to <strong>build the route url to the current view</strong>. I do know how to append a querystring, but I do not know how to find out what to put in that string.</p>
<p>In order to mark an answer as <em>the</em> answer, I want a method to re-construct the route to the currently shown view, from a usercontrol in the masterpage.</p>
| <p>The solution is to use HttpContext.Current.Request.RawUrl like this:</p>
<pre><code><%= Html.ActionLink("log on", "LogIn", new { controller = "User", returnUrl = HttpContext.Current.Request.RawUrl }) %>
</code></pre>
<p>Or with an extension method from <a href="http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=22359">MVC futures</a> (Microsoft.Web.Mvc.dll):</p>
<pre><code><%= Html.ActionLink<AccountController>(c => c.LogOn("name", "password", false, HttpContext.Current.Request.RawUrl), "login here")%>
</code></pre>
<p>ActionController is the default one in mvc but just add returnUrl to your own. </p>
|
Don't static members make classes kind of (global) objects themselves? <p>Every time I come across an implementation of the singleton pattern or any static classes (i.e. classes with (almost) only static members) I wonder whether this isn't actually a hack and therefore heavy abuse of the principle of classes and instances just to design single objects instead of designing classes and creating a single instance. To me, it looks like static members of classes in general try to add some sort of characteristics to classes which they actually aren't supposed to have and which rather make them object themselves. </p>
<p>But is it really desirable to have single objects implemented like that?
Or do you see things completely differently and don't think that such static classes or singletons have anything in common with actual objects?</p>
| <p>Static members are effectively just namespacing for globals, yes. Nothing wrong with that; namespacing is good, and globals are the cleanest way to accomplish some tasks.</p>
<p>Singletons can be somewhat more interesting (load on demand...) but they're a similar construct (yeah, you could think of a static member as an anonymous singleton managed by the compiler).</p>
<p>Like most things, these tools have their place, and only the ideologues worry about whether or not they "fit" with a particular ideology.</p>
|
How to get the next record in SQL table <p>I have a set of records in my MS SQL table. With Date as the primary key. But the Dates are only for working days and not the continues days. Eg:</p>
<p>1/3/2000 12:00:00 AM 5209.540000000 5384.660000000 5209.540000000 5375.110000000
1/4/2000 12:00:00 AM 5533.980000000 5533.980000000 5376.430000000 5491.010000000
1/5/2000 12:00:00 AM 5265.090000000 5464.350000000 5184.480000000 5357.000000000
1/6/2000 12:00:00 AM 5424.210000000 5489.860000000 5391.330000000 5421.530000000
1/7/2000 12:00:00 AM 5358.280000000 5463.250000000 5330.580000000 5414.480000000
1/10/2000 12:00:00 AM 5617.590000000 5668.280000000 5459.970000000 5518.390000000
1/11/2000 12:00:00 AM 5513.040000000 5537.690000000 5221.280000000 5296.300000000
1/12/2000 12:00:00 AM 5267.850000000 5494.300000000 5267.850000000 5491.200000000</p>
<p>In this i am trying to introduce a new column to the table and the value to it should be the value of the 3rd cloumn minus the value of 3rd column of the previous working day. Please help me in writing such a query. I am finding it difficult as the dates are not present for the week ends.</p>
| <p>There are a few ways of doing this. Here is one.</p>
<pre><code>CREATE TABLE MyTable
(
MyDate datetime NOT NULL PRIMARY KEY,
Col2 decimal(14,4) NOT NULL,
Col3 decimal(14,4) NOT NULL,
Col4 decimal(14,4) NOT NULL,
Col5 decimal(14,4) NOT NULL
)
GO
INSERT INTO MyTable
SELECT '1/3/2000 12:00:00 AM', 5209.540000000, 5384.660000000, 5209.540000000, 5375.110000000
UNION ALL
SELECT '1/4/2000 12:00:00 AM', 5533.980000000, 5533.980000000, 5376.430000000, 5491.010000000
UNION ALL
SELECT '1/5/2000 12:00:00 AM', 5265.090000000, 5464.350000000, 5184.480000000, 5357.000000000
UNION ALL
SELECT '1/6/2000 12:00:00 AM', 5424.210000000, 5489.860000000, 5391.330000000, 5421.530000000
UNION ALL
SELECT '1/7/2000 12:00:00 AM', 5358.280000000, 5463.250000000, 5330.580000000, 5414.480000000
UNION ALL
SELECT '1/10/2000 12:00:00 AM', 5617.590000000, 5668.280000000, 5459.970000000, 5518.390000000
UNION ALL
SELECT '1/11/2000 12:00:00 AM', 5513.040000000, 5537.690000000, 5221.280000000, 5296.300000000
UNION ALL
SELECT '1/12/2000 12:00:00 AM', 5267.850000000, 5494.300000000, 5267.850000000, 5491.200000000
GO
CREATE VIEW MyView
AS
SELECT T1.*,
CalculatedColumn = Col3 -
(SELECT Col3 FROM MyTable Q2
WHERE Q2.MyDate = (SELECT MAX(Q1.MyDate)
FROM MyTable Q1
WHERE Q1.MyDate < T1.MyDate)
)
FROM MyTable T1
GO
SELECT * FROM MyView
GO
</code></pre>
<p><strong>Results</strong></p>
<pre><code>MyDate Col2 Col3 Col4 Col5 CalculatedColumn
----------------------- --------- --------- --------- --------- ----------------
2000-01-03 00:00:00.000 5209.5400 5384.6600 5209.5400 5375.1100 NULL
2000-01-04 00:00:00.000 5533.9800 5533.9800 5376.4300 5491.0100 149.3200
2000-01-05 00:00:00.000 5265.0900 5464.3500 5184.4800 5357.0000 -69.6300
2000-01-06 00:00:00.000 5424.2100 5489.8600 5391.3300 5421.5300 25.5100
2000-01-07 00:00:00.000 5358.2800 5463.2500 5330.5800 5414.4800 -26.6100
2000-01-10 00:00:00.000 5617.5900 5668.2800 5459.9700 5518.3900 205.0300
2000-01-11 00:00:00.000 5513.0400 5537.6900 5221.2800 5296.3000 -130.5900
2000-01-12 00:00:00.000 5267.8500 5494.3000 5267.8500 5491.2000 -43.3900
</code></pre>
|
What are some resources for learning MSIL? <p>Can someone please give me a link to a tutorial or answer how to read msil. </p>
<p>I think once I learn how to read this it could be a very useful tool.</p>
| <p>The instructions are defined in the CLI specification, available at <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">http://www.ecma-international.org/publications/standards/Ecma-335.htm</a>, but this is pretty heavy going.</p>
<p><a href="http://rads.stackoverflow.com/amzn/click/1590596463">Serge Lidin's book</a> is the probably the best resource for learning about IL and ILDASM.</p>
<p>Finally, if you want to just decompile assemblies rather than actually learn your way around IL itself, it is much easier to use <a href="http://www.red-gate.com/products/reflector/">Reflector</a> which will show you the code in C# or Visual Basic format -- much easier to understand!</p>
|
Idiomatic way to set default value in javascript <p>What would be the most idiomatic way to do the following in javascript:</p>
<p>If myParam is not passed into MyFunc by the caller, then I want to set it to a default value. But first I want to try and get it from another object, which may not yet exist: </p>
<pre><code>function MyFunc(myParam) {
if (!myParam) {
if (!myObj) {
myParam = 10;
}
else {
myParam = myObj.myParam;
}
}
alert(myParam);
}
</code></pre>
<p>I started to write:</p>
<pre><code> myParam = myParam || myObj.mParam || 10
</code></pre>
<p>but realized that if myObj does not exist then this would fail. I might guess the following:</p>
<pre><code> myParam = myParam || (myObj && myObj.mParam) || 10
</code></pre>
<p>It might even work. But is it the best way?</p>
<p>How would for example John Resig do it?</p>
| <p>If myObj is a global it needs to reference the window object, otherwise it will throw an error if <code>myObj</code> is undefined.</p>
<pre><code>myParam = myParam || (window.myObj ? window.myObj.mParam : 10);
</code></pre>
<p>or</p>
<pre><code>myParam = myParam || (window.myObj && window.myObj.mParam) || 10;
</code></pre>
<p>This works as well:</p>
<pre><code>myParam = myParam || ((typeof myObj !== "undefined") ? myObj.mParam : 10);
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.