input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Creating XML in C++ Code <p>In my project there are situations where we have to send xml messages (as char *) among modules. They are not really large ones, just 10-15 lines. Right now everybody just creates the string themselves. I dont think this is the right approach. We are already using xerces DOM library. So why not create a Dom tree, serialize it, and then send it.</p>
<p>What do you guys suggest?</p>
| <p>If you are really just creating small XML messages, Xerces is an overkill, IMHO. It is a parser library and you are not parsing anything.</p>
|
Linux cross-compilation for ARM architecture <p>I am interested in cross-compiling a Linux kernel for an ARM target on a x86 host. Are there some good practices you recommend? Which is the best cross-compile suite in your opinion?
Have you settled up a custom cross-compile environment? If yes, what advices do you have? Is it a good idea?</p>
| <p>There are two approaches I've used for ARM/Linux tools. The easiest is to download a pre-built tool chain directly.<br>
<strong>Pro</strong>: It just works and you can get on with the interesting part of your project<br>
<strong>Con</strong>: You are stuck with whichever version of gcc/binutils/libc they picked</p>
<p>If the later matters to you, check out <a href="http://crosstool-ng.org/" rel="nofollow">crosstool-ng</a>. This project is a configuration tool similar to the Linux kernel configuration application. Set which versions of gcc, binutils, libc (GNU or uCLibc), threading, and Linux kernel to build and crosstool-ng does the rest (i.e. downloads the tar balls, configures the tools, and builds them).<br>
<strong>Pro</strong>: You get exactly what you selected during the configuration<br>
<strong>Con</strong>: You get exactly what you selected during the configuration</p>
<p>meaning you take on full responsibility for the choice of compiler/binutil/libc and their associated features/shortcomings/bugs. Also, as mentioned in the comments, there is some "pain" involved in selecting the versions of binutils, C library etc. as not all combinations necessarily work together or even build.</p>
<p>One hybrid approach might be to start with the pre-built tools and replace them later with a custom solution via crosstool-ng if necessary.</p>
<p><strong>Update</strong>: The answer originally used the <a href="http://www.codesourcery.com/gnu_toolchains/arm" rel="nofollow">CodeSourcery tools</a> as an example of a pre-built tool chain. The CodeSourcery tools for ARM were free to <a href="http://www.mentor.com/embedded-software/sourcery-tools/sourcery-codebench/editions/lite-edition/" rel="nofollow">download from Mentor Graphics</a>, but they are now called the Sourcery CodeBench and must be purchased from Mentor Graphics. Other options now include <a href="http://www.linaro.org/downloads/" rel="nofollow">Linaro</a> as well as distribution specific tools from Android, Ubuntu, and others.</p>
|
Does anyone know any gems/plugins/tutorials related to exporting events to iCal, Google Calendar, Outlook from a Rails application? <p>I am trying to figure out if there is already a plug in that does the interaction with iCal, Google APIs that I can use or do I need to just get my hands dirty and write it myself. </p>
<p>If anyone knows of good resources that I can look at that could help me with the implementation, that would be good as well. </p>
<p>I am new to RoR and I have been trying to learn it for a while. I finally decided to just start playing with my own application rather than just following a book. </p>
<p>Any help in this matter would be appreciated. </p>
<p>Thanks!</p>
| <p>Check out the <a href="http://benjamin.francisoud.googlepages.com/googlecalendar">Google Calendar gem</a> for rails. It lets you display a user's Google Calendar in your rails app and they have sample snippets showing how to export events to Google Calendar:</p>
<pre><code>require 'googlecalendar'
g = GData.new
g.login('REPLACE_WITH_YOUR_MAIL@gmail.com', 'REPLACE_WITH_YOUR_PASSWORD')
event = { :title=>'title',
:content=>'content',
:author=>'pub.cog',
:email=>'pub.cog@gmail.com',
:where=>'Toulouse,France',
:startTime=>'2007-06-06T15:00:00.000Z',
:endTime=>'2007-06-06T17:00:00.000Z'}
g.new_event(event)
</code></pre>
<p>For iCal, use the <a href="http://firstruby.wordpress.com/2007/12/10/ical-icalendar-publishing-through-rubyonrails/">iCalendar gem</a> and then you can export events as follows:</p>
<pre><code>require âicalendarâ
class EventController < ApplicationController
def export_events
@event = Event.find(params[:id])
@calendar = Icalendar::Calendar.new
event = Icalendar::Event.new
event.start = @event.dt_time.strftime(â%Y%m%dT%H%M%Sâ)
event.end = @event.dt_time.strftime(â%Y%m%dT%H%M%Sâ)
event.summary = @event.summary
event.description = @event.description
event.location = @event.location
@calendar.add event
@calendar.publish
headers['Content-Type'] = âtext/calendar; charset=UTF-8â³
render_without_layout :text => @calendar.to_ical
end
end
</code></pre>
|
Why no compiler error for main() without a return at the end? <p>I'm working on a C-brain teaser: Write the standard Hello-World program, without semi-colons.</p>
<p>My best answer so far is:</p>
<pre><code>int main(void)
{
if (printf("Hello World!\n"), exit(0), 0)
{
/* do nothing */
}
}
</code></pre>
<p>But I don't understand why I don't get compiler error (Visual Studio):</p>
<pre><code>error C4716: 'main' : must return a value
</code></pre>
<p>I've tried other functions with a return-type declared, but missing a return-statement, and get this compiler error.</p>
<hr>
<p>Note that I've also tried:</p>
<pre><code>int foo(void)
{
if (printf("Hello World!\n"), exit(0), true)
{
/* do nothing */
}
}
int main(void)
{
foo();
}
</code></pre>
<p>And don't get a compiler error on foo. If I remove the "exit(0)", I <em>do</em> get the compiler error. Apparently the compiler has knowledge that "exit" is a special function? This seems very odd to me.</p>
| <p>As Jens pointed out in a comment, the posted code does not exhibit undefined behavior. The original answer here isn't correct and doesn't even really seem to answer the question anyway (on re-reading everything a few years later).</p>
<p>The question can be summed up as, "why doesn't MSVC issue warning C4716 for <code>main()</code> in the same circumstances it would for other functions"?</p>
<p>Note that diagnostic C4716 is a warning, not an error. As far as the C language is concerned (from a standards point of view anyway), there's never a requirement to diagnose a non-error. but that doesn't really explain why there's a difference, it's just a technicality that may mean you can't complain too much...</p>
<p>The real explanation for why MSVC doesn't issue the warning for <code>main()</code> when it does for other functions can really only be answered by someone on the MSVC team. As far as I can tell, the docs do not explain the difference, but maybe I missed something; so all I can do is speculate:</p>
<p>In C++, the <code>main()</code> function is treated specially in that there's an implicit <code>return 0;</code> just before the closing brace. </p>
<p>I suspect that Microsoft's C compiler provides the same treatment when it's compiling in C mode (if you look at the assembly code, the EAX register is cleared even if there's no <code>return 0;</code>), therefore as far as the compiler is concerned there is no reason to issue warning C4716. Note that Microsoft's C mode is C90 compliant, not C99 compliant. In C90 'running off the end' of <code>main()</code> has undefined behavior. However, always returning 0 meets the low requirements of undefined behavior, so there's no problem. </p>
<p>So even if the program in the question <em>did</em> run off the end <code>main()</code> (resulting in undefined behavior) there still wouldn't be a warning.</p>
<hr>
<p>Original, not so good answer:</p>
<p><strike>In ANSI/ISO 90 C, this is undefined behavior, so MS really should produce an error (but they aren't required to by the standard). In C99 the standard permits an implied <code>return</code> at the end of main() - as does C++.</p>
<p>So if this is compiled as C++ or C99, there's no error and it's the same as <code>return 0;</code>. C90 results in undefined behavior (which does not require a diagnostic).</p>
<p>Interestingly (well, maybe not), of the several compilers (VC9, VC6, GCC 3.4.5, Digital Mars, Comeau) I tried this on with my basic, mostly default options set (the environment I pretty much always use for quick-n-dirty testing of code snippets) the only compiler that warns about the missing return statement is VC6 when compiling as a C++ program (VC6 does not complain when compiling for C).</p>
<p>Most of the compilers complain (a warning or error) if the function is not named <code>main</code>. Digital Mars when compiling for C does not and GCC doesn't for C or C++.</strike></p>
|
amending a single file in a past commit in git <p>I want to fix a file in past commit. This might affect all ascending commits.</p>
<p>Is there an easy way to do that? Can you give me a guideline of how to do that?</p>
<p>Many times when I commit twice I find that I've had error in the first commit, and I wish to fix the error without having to 'git reset' my last good commit.</p>
<p>For clarification. I want to change the actual <em>commit</em>, that is, I want the content of the past commit to be changed. IOW I want to <strong>change history!</strong></p>
| <p>If you only want to amend the second to last commit (eg. not long ago, especially not before many branches and merges), then I use this procedure:</p>
<ol>
<li><code>git checkout -b tmp bad-commit</code></li>
<li>fix the files</li>
<li><code>git commit --amend</code></li>
<li><code>git rebase tmp master</code></li>
</ol>
<p>If you have merges in between, you may wanna try <code>rebase -i -p</code>, but the results may vary.</p>
|
How to Convince Programming Team to Let Go of Old Ways? <p>This is more of a business-oriented programming question that I can't seem to figure out how to resolve. I work with a team of programmers who have been working with BASIC for over 20 years. I was brought in to help write the same software in .NET, only with updates and modern practices. The problem is that I can't seem to get any of the other 3 team members(all BASIC programmers, though one does .NET now as well) to understand how to correctly do a relational database. Here's the thing they won't understand:</p>
<p>We basically have a transaction that keeps track of a customer's tag information. We need to be able to track current transactions and past transactions. In the old system, a flat-file database was used that had one table that contained records with the basic current transaction of the customer, and another transaction that contained all the previous transactions of the customer along with important money information. To prevent redundancy, they would overwrite the current transaction with the history transactions-(the history file was updated first, then the current one.) It's totally unneccessary since you only need one transaction table, but my supervisor or any of my other two co-workers can't seem to understand this. How exactly can I convince them to see the light so that we won't have to do ridiculous amounts of work and end up hitting the datatabse too many times? Thanks for the input!</p>
| <p>Firstly I must admit it's not absolutely clear to me from your description what the data structures and logic flows in the existing structures actually are. This does imply to me that perhaps you are not making yourself clear to your co-workers either, so one of your priorities must be to be able explain, either verbally or preferably in writing and diagrams, the current situation and the proposed replacement. Please take this as an observation rather than any criticism of your question.</p>
<p>Secondly I do find it quite remarkable that programmers of 20 years experience do not understand relational databases and transactions. Flat file coding went out of the mainstream a very long time ago - I first handled relational databases in a commercial setting back in 1988 and they were pretty commonplace by the mid-90s. What sector and product type are you working on? It sounds possible to me that you might be dealing with some sort of embedded or otherwise 'unusual' system, in which case you do need to make sure that you don't have some sort of communication issue and you're overlooking a large elephant that hasn't been pointed out to you - you wouldn't be the first 'consultant' brought into a team who has been set up in some manner by not being fed the appropriate information. That said such archaic shops do still exist - one of my current clients systems interfaces to a flat-file based system coded in COBOL, and yes, it is hell to manage ;-)</p>
<p>Finally, if you are completely sure of your ground and you are faced with a team who won't take on board your recommendations - and demonstration code is a good idea if you can spare the time -then you'll probably have to accept the decision gracefully and move one. Myself in this position I would attempt to abstract out the issue - can the database updates be moved into stored procedures for example so the code to update both tables is in the SP and can be modified at a later date to move to your schema without a corresponding application change? Make sure your arguments are well documented and recorded so you can revisit them later should the opportunity arise. </p>
<p>You will not be the first coder who's had to implement a sub-optimal solution because of office politics - use it as a learning experience for your own personal development about handling such situations and commiserate yourself with the thought you'll get paid for the additional work. Often the deciding factor in such arguments is not the logic, but the 'weight of reputation' you yourself bring to the table - it sounds like having been brought in you don't have much of that sort of leverage with your team, so you may have to work on gaining a reputation by exceling at implementing what they do agree to do before you have sufficient reputation in subsequent cases - you need to be modded up first!</p>
|
Converting a string to a class name <p>I have a string variable that represents the name of a custom class. Example: </p>
<pre><code>string s = "Customer";
</code></pre>
<p>I will need to create an arraylist of customers. So, the syntax needed is:</p>
<pre><code>List<Customer> cust = new ..
</code></pre>
<p>How do I convert the string s to be able to create this arraylist on runtime?</p>
| <p>Well, for one thing <code>ArrayList</code> isn't generic... did you mean <code>List<Customer></code>?</p>
<p>You can use <code>Type.GetType(string)</code> to get the <code>Type</code> object associated with a type by its name. If the assembly isn't either mscorlib or the currently executing type, you'll need to include the assembly name. Either way you'll need the namespace too.</p>
<p>Are you sure you really need a generic type? Generics mostly provide <em>compile-time</em> type safety, which clearly you won't have much of if you're finding the type at execution time. You <em>may</em> find it useful though...</p>
<pre><code>Type elementType = Type.GetType("Customer");
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });
object list = Activator.CreateInstance(listType);
</code></pre>
<p>If you need to <em>do</em> anything with that list, you may well need to do more generic reflection though... e.g. to call a generic method.</p>
|
Why does my service reference only generate asynchronous methods? <p>I have a Service Reference (not a web reference) in VS2008 to a web service that I did not write. The reference works, but only asynchronous versions of each method are available for me to use.</p>
<p>In the "Configure Service Reference" dialog, the "Generate asynchronous operations" is checked and grayed out. First of all, I thought checking this box generated async methods in addition to, not instead of, blocking methods. Second, I've never seen it grayed out before.</p>
<p>I have experience writing both sides of both WCF and ASMX-era web services and have never seen this before. What could be causing this?</p>
<p>Thanks.</p>
| <p>I'd be willing to wager ten up-votes that it's because you're doing this in Silverlight. Unfortunately I don't have the tools installed so I can't test this theory, but I do know that service calls from Silverlight can only be asynchronous. Perhaps you are using a Silverlight project template and are creating the service reference there? Visual Studio might be smart enough to know not to generate blocking methods in such a situation.</p>
<p>For reference:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/cc197937(VS.95).aspx">http://msdn.microsoft.com/en-us/library/cc197937(VS.95).aspx</a></p>
|
Browser Detection in HttpModule <p>Is there a way to detect what browser the request is made in the HttpModule?</p>
<p>Thanks.</p>
| <pre><code>public class TestModule : IHttpModule
{
public void Dispose() {
throw new NotImplementedException();
}
public void Init(HttpApplication context) {
context.Request.Browser....;
}
}
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.browser(VS.80).aspx" rel="nofollow">MSDN Reference</a></p>
|
How do you convert a url to a virtual path in asp.net without manual string parsing? <p>I've seen similar questions and answers regarding conversions from virtual to absolute and url, but how can I convert a url to a virtual path without manual string parsing?</p>
<p>Example: </p>
<p>I want "http://myserver/home.aspx" converted to: "~/home.aspx"</p>
<p>I realize the above example would be an easy string parsing routine, but I'm looking for a proper solution that will scale to the changing of the url format.</p>
| <p>You can get most of it from the Uri class:</p>
<pre><code>new Uri("http://myserver.com/home.aspx").AbsolutePath
</code></pre>
<p>Then you just have to prepend the ~</p>
<p>Though, that will might break if you host in a subdirectory - I don't think there's a way to do it specifically in the context of the application you're running.</p>
<p>EDIT: This might do it:</p>
<pre><code>VirtualPathUtility.ToAppRelative(new Uri("http://myserver.com/home.aspx").AbsolutePath);
</code></pre>
|
fread example from C++ Reference <p>I often use the website www.cplusplus.com as a reference when writing C code.</p>
<p>I was reading the example cited on the page for <a href="http://www.cplusplus.com/reference/clibrary/cstdio/fread.html" rel="nofollow">fread</a> and had a question.</p>
<p>As an example they post:</p>
<pre><code>/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer);
return 0;
}
</code></pre>
<p>It seems to me that that if result != lSize, then free(buffer) will never get called. Would this be a memory leak in this example? </p>
<p>I have always thought the examples on their site are of a very high quality. Perhaps I am not understanding correctly?</p>
| <p>Technically, yes it is a memory leak. But any memory allocated by a process is automatically freed when that process terminates, so in this example the calls to free (and fclose) are not really required.</p>
<p>In a more complex program, this would probably be a real problem. The missing free would create a memory leak and the missing fclose would cause a resource leak.</p>
|
Nhibernate: Handling an ITransaction Exception So That New Transactions Can Continue with same ISession <p>I have a list of 10 data objects that I want to insert/update to the database using NHibernate. If one throws an exception (say a primary key violation) I want to still insert/update the other 9. I rolled each object operation into its own atomic transaction, and roll back the transaction if there is an exception. Problem is that if a transaction does cause an exception and is rolled back, on the next transaction Nhibernate complains with the error: null id in Nexus.Data.PortfolioCorporateEntity entry <strong>(don't flush the Session after an exception occurs)</strong></p>
<p>My main program is simple. It creates a session from a sessionfactory, creates the data access layer, does some work on the data objects and then tries to persist those data objects to the database.</p>
<pre><code> sessionsManager = new NHibernateSessionManager();
session = sessionsManager.GetSession();
DALC = new NHibernateDataProvider(session);
â¦
foreach (var pce in pces)
{
try
{
DALC.UpdateOrAddObject<PortfolioCorporateEntity>(pce);
}
catch (Exception ex)
{
Console.WriteLine("Could not add Corporate Entity ID " + pce.CorporateEntity.CorporateEntityID.ToString());
}
}
</code></pre>
<p>This is the updateOrAdd procedure in my Nhibernate Data Access Layer, called 10 times for 10 objects.</p>
<pre><code>public void UpdateOrAddObject<T>(T workObject)
{
using (ITransaction tx = mSession.BeginTransaction) {
try {
mSession.SaveOrUpdate(workObject);
mSession.Flush();
tx.Commit();
}
catch (Exception ex) {
tx.Rollback();
throw;
}
}
}
</code></pre>
<p>Just to make the point clear, the session is instantiated by the calling program and passed to the Data Access Layer object, constructor of which is below.</p>
<pre><code>public NHibernateDataProvider(ISession session)
{
mSession = session;
}
</code></pre>
<p>This works fine except after the exception, it says donât flush the session after exception. Iâm not sure why â transaction was rolled back nicely and the database should be ready to accept another transaction no? What am I doing wrong?</p>
| <p>It's not possible to re-use an NHibernate session after an exception is thrown. <a href="http://nhforge.org/doc/nh/en/index.html#manipulatingdata-exceptions">Quoting the documentation</a>:</p>
<pre><code>If the ISession throws an exception you should immediately rollback the
transaction, call ISession.Close() and discard the ISession instance.
Certain methods of ISession will not leave the session in a consistent state.
</code></pre>
<p>So the answer is that you can't do what you're trying to do. You need to create a new session and re-try the updates there.</p>
|
Persistent connection with client <p>Is there a general way to implement part of an application with JavaScript and supplying a persistent connection to a server? I need the server to be able to push data to the client, regardless of the client being behind a firewall. Thanks in advance</p>
| <p>See <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29" rel="nofollow">Comet</a> - it's like ajax, but it holds a connection open so the server can push information to the client.</p>
<p>Note that compliant browsers will only hold 2 connections (note: <a href="http://stackoverflow.com/questions/5751515/official-references-for-default-values-of-concurrent-http-1-1-connections-per-se">most modern browsers no longer comply</a>) to a particular domain (by default), so you might want to split your domains (e.g. www.yourdomain.com and comet.yourdomain.com) so that you don't drastically slow down the loading of your pages. Or you could just make sure you don't open the comet connection until everything else is loaded. It's just something to be careful of.</p>
|
What open source license for my web application that uses both GPL & LGPL? advice? <p>I've written an application I'd like to release as open source, but i'm not sure what to license it under.</p>
<p>It's all my own code <em>apart from</em> jQuery which is GPL 2.1 and TinyMCE editor which is LGPL 2.1. I'd like to distribute both libraries with my application if possible. Can I release under GPL2.1 ?</p>
<p>All I want to do is license appropriately and pay my open source dues to the clever authors of jQuery and TinyMCE.</p>
<p>Any suggestions? </p>
| <p>jQuery is available under the <a href="http://docs.jquery.com/License" rel="nofollow">MIT or GPL licenses</a>. If you're happy to make the code of your application available under GPL then you're fine. Usually people have issue because they don't want to. And it seems like distributing your application (including jquery) triggers that particular part of GPL but IANAL so don't take that as gospel.</p>
<p>You could also consider the compatibility between the (far less invasive) MIT license and LGPL if you don't want to publish the code to your application.</p>
|
VBA: preceding zeros dropped when copied over <p>I am creating a copy of an Excel file using VBA. In the file, there is a column that includes numbers with preceding zeros. The copy of the file is created, but the data in this column is dropped. I need to keep the values with the preceding zeros. How can I resolve this problem with VBA?</p>
| <p>The best way is to pre-format the column as Text by setting Range.NumberFormat to "@". This way, if a user edits the cell, the cell will stay as text and maintain it's leading zeros. Here is a VBA example:</p>
<p>ActiveSheet.Range("C:C").NumberFormat = "@"</p>
|
How to build ImageButton Control Adapter (or more general, how to build a simple control adapter)? <p>My inspiration for this question was my discovery of the very annoying default style (<code>border-width: 0px;</code>) on the ImageButton web control. The simple solution is to override it by adding your own style to the control e.g. <code>Style="border-width: 2px;"</code>.</p>
<p>How every, it would have been nice to just make a simple control adapter that would just step in at the right place and just tell the control not to render the default styling.</p>
<p>After looking a bit at the code from the CSSFriendly ControlAdapter project, it seems like they are recreating much of the rendering, which is overkill for what I want to do -- i.e. just change the default styling that is rendered out.</p>
<p>So the question, how to just modify the rendering of the default styles through control adapters, and leave the rest as is?</p>
<p>Is it even possible?</p>
<p>Thanks, Egil.</p>
| <p>There are two ways to do this. Both will require writing up a custom Control Adapter. Either you can set the actual value in code, or you can just not include the value at all and then use CSS to set your value. Here's the code you'll need to do this.</p>
<pre><code>namespace TestApp
{
using System.IO;
using System.Web.UI;
using System.Web.UI.Adapters;
public class ImageAdapter : ControlAdapter
{
protected override void Render(HtmlTextWriter writer)
{
base.Render(new RewriteImageHtmlTextWriter(writer));
}
public class RewriteImageHtmlTextWriter : HtmlTextWriter
{
public RewriteImageHtmlTextWriter(TextWriter writer)
: base(writer)
{
InnerWriter = writer;
}
public RewriteImageHtmlTextWriter(HtmlTextWriter writer)
: base(writer)
{
InnerWriter = writer.InnerWriter;
}
public override void AddAttribute(HtmlTextWriterAttribute key, string value, bool fEncode)
{
if (key == HtmlTextWriterAttribute.Border)
{
// change the value
//value = "2";
// -or-
// don't include the value
//return;
}
base.AddAttribute(key, value, fEncode);
}
public override void AddStyleAttribute(HtmlTextWriterStyle key, string value)
{
if (key == HtmlTextWriterStyle.BorderWidth)
{
// change the value
//value = "2px";
// -or-
// don't include the value
//return;
}
base.AddStyleAttribute(key, value);
}
}
}
}
</code></pre>
<p>Then you'll need to add an entry into one of your browser files like this</p>
<pre><code><browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Image" adapterType="TestApp.ImageAdapter, TestApp" />
</controlAdapters>
</browser>
</browsers>
</code></pre>
|
How do I copy my entire working copy between hard drives? <p>Whenever I try to copy an entire working copy using simple drag and drop between two computers (e.g. from an old computer to a new one, or from one VM to another) in order to avoid having to redownload the entire several GB set of code from our online repository I get an error as soon as I reach any of the hidden SVN-BASE files.</p>
<p>Is there a way to copy an entire working copy with these intact?</p>
<p>I'm using Vista x64.</p>
| <p>I can't answer for Vista, but on XP you just copy the directory.</p>
<p>I guess that Vista has decided that the files are hidden and so do not need to be copied, or they're locked and not available for copying. In the former, make them un-hidden (with the global file options in explorer's Organise menu, under folder & Search options, view tab), in the latter, try stopping TortoiseSVN's cache which might be holding on to them.</p>
<p>or try Xcopy from a command prompt.</p>
|
protect_from_forgery vs. Firefox <p>I've recently switched from storing session data in a cookie to storing it in the database.</p>
<p>Now every POST request causes an <b>ActionController::InvalidAuthenticityToken</b> error. It only happens in Firefox, and only on my home machine (I tried it out at work today in the same version of FF and everything was fine). This leads me to believe that it's something do do with the cookie I deleted yesterday...</p>
<p>Here's the relevant part of environment.rb:</p>
<pre><code># Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_basillslam_session',
:secret => '373ee5b69a4a31d3318485fs368c41fac6b797a1f5c35693b49bd34e8a96291b92dd577bd49de7aeea56c9ffa1af2d8386bafe857220cafacfa0028f01be357d78'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with 'rake db:sessions:create')
config.action_controller.session_store = :active_record_store
</code></pre>
<p>In application.rb:</p>
<pre><code>protect_from_forgery :secret => 'f1d54db45b47ec94a6a54b1e744fafa6'
</code></pre>
<p>Here's the part of the full trace where the error is thrown:</p>
<pre><code>C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/request_forgery_protection.rb:79:in `verify_authenticity_token'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:469:in `send!'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:469:in `call'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:441:in `run'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:716:in `run_before_filters'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:695:in `call_filters'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:689:in `perform_action_without_benchmark'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
C:/INSTAN~1/ruby/lib/ruby/1.8/benchmark.rb:293:in `measure'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/rescue.rb:199:in `perform_action_without_caching'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/caching.rb:678:in `perform_action'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:33:in `cache'
C:/INSTAN~1/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/query_cache.rb:8:in `cache'
[etc. ... ]
</code></pre>
<p>Has anybody experienced this before? Or does anybody know why this might be happening?</p>
| <p>The exact same thing happened to me when I switched one of my sites. Delete the Rails session cookie for that site in your home Firefox Browser.</p>
<p>It only happens if you had a pre-existing session that used the cookie store. So, hopefully, only you and your browser will ever see the issue. After you've deleted the cookie, you'll never see the error again.</p>
<p>With the session in the database and only a random key to map to that session in the browsers cookies, the session protection magic is no longer necessary.</p>
|
How different is CakePHP from Ruby on Rails? <p>I almost never hear the word CakePHP without hearing the word Rails shortly afterwards. Are these two frameworks mainly similar based on how they adhere to the MVC model or do they have other significant similarities/differences? </p>
<p>One of the main attractions of Rails for me is how easy it is to do Ajax. Would that also be true of CakePHP?</p>
| <p>CakePHP is like a cheap, bastardized ripoff of Rails. It tries to be like Rails without doing any of the stuff that makes Rails great. It kinda feels similar, I guess.</p>
<p>CakePHP has an Ajax helper that does something similar to the Ajax-related helper methods in Rails, so yes, in some way, it's also true.</p>
<p>But CakePHP is really an exercise in futility: its authors wrote it so they wouldn't have to learn Ruby, even though learning Ruby and Rails together is probably easier than figuring out the monstrous mess that is CakePHP.</p>
<p>(This, coming from somebody who does CakePHP at his day job.)</p>
<p><hr /></p>
<p>Since y'all asked, my biggest complaint about CakePHP is how it manages to totally butcher the conveniences of object-oriented programming: sure, it implements the Active Record pattern just as much as Rails does, but it makes you pass around data structures.</p>
<p>I feel like any logical person would implement an ORM using faulting and dynamic loading of properties in to objects, which is exactly what ActiveRecord (the Rails library) does. The whole idea of setting a member variable called <code>$recursive</code> to determine which relationships to load is just plain flawed.</p>
<p>Being based on PHP is pretty fatal, too; you can't do anything with global state, you have to depend on <code>mod_rewrite</code>, you pay the startup penalty on every request. Sure, there's optimizations for any environment you're using, but still. People say Ruby is slow, but my own Rails apps run faster than their CakePHP equivalents, last I checked. I admit to being without data on this.</p>
<p>Worst of all, the bugs in CakePHP just about kill it for me. I could tell any number of stories about</p>
<ul>
<li>the time we spent two days figuring out why CakePHP refused to connect to the right database host</li>
<li>the time half of our pages went blank because of the memory ceiling from using too many components</li>
<li>the amount of code that lives in our AppController because every component load costs several <strong>megabytes</strong> of memory</li>
<li>the black art of massaging data structures to make XML output work correctly</li>
<li>how we traced down the blank <code><javascript></code> tag that shows up at the end of every page</li>
</ul>
|
How can I upload a document to SharePoint with Perl? <p>I have a Perl app that runs some perforce operations, in the end I would like it to upload the results to SharePoint website. </p>
<ul>
<li>What is the simplest Perl script that can accomplish a task of adding a document to SharePoint? </li>
</ul>
<p>The script would need to run on Solaris and use as few as possible external libraries as possible (definitely pure classic Perl) getting anything additional installed on these unix boxes is a pain and would have to be done by remote team.</p>
<p>If this can uploading document can easily be done with wget, that would be of interest too. Anyways, I am looking for 1 or a couple liner that's easy to understand.</p>
<p>UPDATES based on comments:</p>
<ul>
<li>Perl Mechanize sounded like a good idea, but for some reason I am not able to authenticate, Error GETing <code>http://sharepoint Unauthorized ....</code> </li>
</ul>
<p>I had this:</p>
<pre><code>my $m = WWW::Mechanize->new();
$m->credentials($user => $pass);
$m->get($url);
</code></pre>
<p>But mechanize won't authenticate against sharepoint for some reason.</p>
<ul>
<li>Does anybody have a link or a sample on how to use sharepoint webdav from unix via perl? </li>
</ul>
<p>I installed and tried to open <a href="http://www.webdav.org/perldav" rel="nofollow">my typical sharepoint site</a> via "dave" webdav browser, but I get <code>** Unauthorized. **</code> error. </p>
<ul>
<li>How to solve it with the webdav approach with perl on unix? </li>
</ul>
| <p>This sounds like a job for <a href="http://search.cpan.org/perldoc?WWW::Mechanize" rel="nofollow">WWW::Mechanize</a>. It has excellent support for dealing with forms.</p>
|
Check all radio controls with a specific substring on an ASP.NET form <p>I'm working on a .NET-powered questionnaire which contains several repeater controls, each row of which contains three radiobuttons. I'm trying to write a simple Javascript function to check all the controls on the page which contain the word "chkGreen" in the control name/id.</p>
<p>The page looks something like this:</p>
<pre><code>Repeater 1
Description 1 ( ) Green ( ) Yellow ( ) Red
Description 2 ( ) Green ( ) Yellow ( ) Red
Description 3 ( ) Green ( ) Yellow ( ) Red
Repeater 2
Description 1 ( ) Green ( ) Yellow ( ) Red
Description 2 ( ) Green ( ) Yellow ( ) Red
Description 3 ( ) Green ( ) Yellow ( ) Red
</code></pre>
<p>Here's the function so far:</p>
<pre><code> for (i = 0; i < document.Form1.elements.length; i++) {
var _control = document.Form1.elements[i].id
if (_control.indexOf("chkGreen") > 0) {
eval(_control.checked = true);
}
}
</code></pre>
<p>This function does not work. When I add a document.write or alert() to the statement, it properly fires, so the logic is apparently working, it's just the actual radiobutton check code is not working.</p>
<p>Any thoughts?</p>
| <p>You don't need to eval the _control.checked line.</p>
<pre><code>for (i = 0; i < document.Form1.elements.length; i++) {
var _control = document.Form1.elements[i]; // EDIT: you want the element, not the id of the element
if (_control.indexOf("chkGreen") > 0) {
_control.checked = true;
}
}
</code></pre>
|
Java: how do I check if a Date is within a certain range? <p>I have a series of ranges with start dates and end dates. I want to check to see if a date is within that range.</p>
<p>Date.before() and Date.after() seem to be a little awkward to use. What I really need is something like this pseudocode:</p>
<pre><code>boolean isWithinRange(Date testDate) {
return testDate >= startDate && testDate <= endDate;
}
</code></pre>
<p>Not sure if it's relevant, but the dates I'm pulling from the database have timestamps. </p>
| <pre><code>boolean isWithinRange(Date testDate) {
return !(testDate.before(startDate) || testDate.after(endDate));
}
</code></pre>
<p>Doesn't seem that awkward to me. Note that I wrote it that way instead of </p>
<pre><code>return testDate.after(startDate) && testDate.before(endDate);
</code></pre>
<p>so it would work even if testDate was exactly equal to one of the end cases.</p>
|
Director 11 and Flash with AS 2 communication <p>I have a Director project with 3 scripts (2 behaviors and 1 movie script). I have the following code in my movie script:</p>
<pre><code>on startRecording ()
--do stuff
_movie.script["script2"].passGrade(75, 3, 4)
end
</code></pre>
<p>and in one of my behavior scripts, I have the following:</p>
<pre><code>on passGrade (acc, dur, tim)
member("Assessment", "Assessment").displayGrade(acc, dur, tim)
end passGrade
</code></pre>
<p>where the name of the second behavior script is <code>script2</code>and there is a Flash object on the stage called <code>Assessment</code> which has an ActionScript method called <code>displayGrade</code> which takes 3 numbers as input.</p>
<p>I have 2 questions. First, the call <code>-movie.script["script2"].passGrade(75, 3, 4)</code> does not work, and I can't figure out why. Am I not allowed to call from a movie script to a behavior? Or am I not doing this correctly? The second question is how do I call the ActionScript method? The script is defined as a behavior for the Flash object, which is called <code>Assessment</code>, but Director doesn't seem to be able to locate the method.</p>
<p>I am using Director 11 with HotFix 3, and the Flash object was compiled for ActionScript 2.</p>
| <p>The syntax for calling the behavior script should rather be:</p>
<p>script("script2").passGrade(75, 3, 4)</p>
<p>Alternatively you could attach your behavior to the flash sprite (the instance of your flash on the stage), and send the call to the sprite:</p>
<p>sendSprite (flashSpriteNumOrNameOrRef, #passGrade, 75, 3, 4)</p>
<p>About calling a function inside the flash sprite, you do more or less the same, but you send the call to the flash sprite, not the member:</p>
<p>sprite(flashSpriteNumOrNameOrRef).displayGrade(acc, dur, tim)</p>
<p>if the behavior is attached to the sprite:
sprite(me.spriteNum).displayGrade(acc, dur, tim)</p>
|
Creating an AJAX Script Control <p>Call me a 'n00b', but I am new to creating Script Controls. I want to create a simple control with 3 text boxes. I have a .cs file that looks like this:</p>
<pre><code> public class SmokingCalc : ScriptControl
{
public SmokingCalc()
{
Render(htmlWriter);
}
protected override void Render(HtmlTextWriter writer)
{
costTextbox.RenderControl(writer);
base.Render(writer);
}
protected override IEnumerable<ScriptDescriptor>
GetScriptDescriptors()
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("SmokingCalc.SmokingCalc", this.ClientID);
yield return descriptor;
}
// Generate the script reference
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
yield return new ScriptReference("SmokingCalc.SmokingCalc.js", this.GetType().Assembly.FullName);
}
protected HtmlTextWriter htmlWriter;
protected TextBox costTextbox;
protected TextBox amountTextbox;
protected TextBox yearsTextbox;
protected Button submitButton;
}
}
</code></pre>
<p>and I have absolutely no idea why the textbox wont render? I think I am missing something...</p>
<p>[EDIT] The error I'm getting is the "Object reference is not set to an instance to an object".</p>
<p>[ANSWERED] I changed the file as follows, and it works, so far at least.</p>
<pre><code> public class SmokingCalc : ScriptControl
{
public SmokingCalc()
{
}
protected override void CreateChildControls()
{
base.CreateChildControls();
costTextbox.ID = "costTextbox";
amountTextbox.ID = "amountTextbox";
yearsTextbox.ID = "yearsTextbox";
submitButton.ID = "submitButton";
submitButton.Text = "Submit";
Controls.Add(costTextbox);
Controls.Add(amountTextbox);
Controls.Add(yearsTextbox);
Controls.Add(submitButton);
}
protected override IEnumerable<ScriptDescriptor>
GetScriptDescriptors()
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("SmokingCalc.SmokingCalc", this.ClientID);
descriptor.AddProperty("costTextboxID", costTextbox.ClientID);
descriptor.AddProperty("amountTextboxID", amountTextbox.ClientID);
descriptor.AddProperty("yearsTextboxID", amountTextbox.ClientID);
descriptor.AddProperty("submitButtonID", submitButton.ClientID);
yield return descriptor;
}
// Generate the script reference
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
yield return new ScriptReference("SmokingCalc.SmokingCalc.js", this.GetType().Assembly.FullName);
}
protected TextBox costTextbox = new TextBox();
protected TextBox amountTextbox = new TextBox();
protected TextBox yearsTextbox = new TextBox();
protected Button submitButton = new Button();
}
</code></pre>
| <p>Did you try <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.createchildcontrols.aspx" rel="nofollow"><code>CreateChildControls</code></a>?:</p>
<pre><code>public class SmokingCalc : ScriptControl
{
protected override void CreateChildControls()
{
this.Controls.Add(costTextbox);
}
protected override IEnumerable<ScriptDescriptor>
GetScriptDescriptors()
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("SmokingCalc.SmokingCalc", this.ClientID);
yield return descriptor;
}
// Generate the script reference
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
yield return new ScriptReference("SmokingCalc.SmokingCalc.js", this.GetType().Assembly.FullName);
}
protected HtmlTextWriter htmlWriter;
protected TextBox costTextbox = new TextBox();
protected TextBox amountTextbox = new TextBox();
protected TextBox yearsTextbox = new TextBox();
protected Button submitButton = new Button();
}
</code></pre>
|
Two encodings used in RTF string won't display correct in RichTextBox? <p>I am trying to parse some RTF, that i get back from the server. For most text i get back this works fine (and using a RichTextBox control will do the job), however some of the RTF seems to contain an additional "encoding" and some of the characters get corrupted.</p>
<p>The original string is as follows (and contains some of the characters used in Polish):</p>
<pre><code>Ä
ÄÄÅÅóÅźż
</code></pre>
<p>The RTF string with hex encoded characters that is send back looks like this</p>
<pre><code>{\lang1045\langfe1045\f16383 {\'b9\'e6\'ea\'b3{\f7 \'a8\'bd\'a8\'ae}\'9c\'9f\'bf}}
</code></pre>
<p>I am having problems decoding the <strong>Åó</strong> characters in the returned string, they seem to be represented by two hex values each, whereas the rest of the string is represented (as expected) by single hex values.</p>
<p>Using a RichTextBox control to "parse" the RTF results in corrupter text (the two characters in question are displayed as four different unwanted characters).</p>
<p>If i would encode the plain string myself to hex using the expected codepage (1250, Latin 2, the ANSI codepage for lcid 1045) i would get the following:</p>
<pre><code>\'B9\'E6\'EA\'B3\'F1\'F3\'9C\'9F\'BF
</code></pre>
<p>I am lost as to how i can correctly decode the <strong>{\f7 \'a8\'bd\'a8\'ae}</strong> part of the returned string that should correspond to <strong>Åó</strong>.</p>
<p>Note that there is no font definition for <strong>\f7</strong> in the RTF header and the string looks fine when viewed directly on the server meaning that the characters (if they are corrupted) are corrupted somewhere in the conversion before sending.</p>
<p>I am not sure if the problem is on the server side (as i have no control over that), but since the server is used for a lot of translation work i assume that the returned string is ok.</p>
<p>I have been going through the RTF specs but can not find any hint regarding this type of combination of encodings.</p>
| <p>I don't know why it's happening, but the encoding appears to be <a href="http://en.wikipedia.org/wiki/GBK" rel="nofollow">GBK</a> (or something sufficiently similar).</p>
<p>Perhaps the server tries to do some "clever" matching to find the characters, or the server's default character encoding is GBK or so, and those characters (and only those) also occur in GBK so it prefers that.</p>
<p>I found out by adding the offending hex codes (<code>A8 BD A8 AE</code>) as bytes into a simple HTML file, so I could go through my browser's encodings and see if anything matched:</p>
<pre><code><html><body>¨½¨®</body></html>
</code></pre>
<p>To my surprise, my browser came up with "Åó" straight away.</p>
|
How do you display custom UIViews in InterfaceBuilder? <p>I seem to enjoy designing new <code>UIViews</code> and <code>UIControls</code> that implement their own <code>-drawRect:</code> method. This work well for me, especially when composed using <code>UIViews</code> in <em>Interface Builder</em>.</p>
<p>But composing them in Interface Builder is annoying because they just show up as boring plain rectangles.</p>
<p>It would be great if the views would actually render themselves as the built-in controls do.</p>
<p>Is there any way I can structure my project so that Interface Builder will render my custom views?</p>
| <p>In order to do this, you actually have to create a plug-in for Interface Builder that uses your custom class. Once you create and install your plug-in, you will be able to drag and drop instances of your class (your view) onto another window/view/whatever just like any other control. To get started with creating IB Plug-Ins, please see the <a href="https://developer.apple.com/legacy/library/documentation/DeveloperTools/Conceptual/IBPlugInGuide/IBPlugInGuide.pdf" rel="nofollow">Interface Builder Plug-In Programming Guide</a>. Also, I recommend taking a look at Aaron Hillegass's book, <em><a href="http://rads.stackoverflow.com/amzn/click/0321503619" rel="nofollow">Cocoa Programming for Mac OS X</a></em>. As well as being very well written and easy to understand, it has a chapter on creating your own IB Palette controls.</p>
|
Why does MIcroQuill Smartheap throw "mem_bad_pointer" errors after I embed perl? <p>I am embedding perl in a C++ application that uses <a href="http://www.microquill.com/smartheap/index.html" rel="nofollow">Smartheap</a>. Regardless of whether I compile the perl to use its own malloc or the system's I get a bunch of error mem___bad_pointer dialogs. It seems to work fine when I just click "ok" and ignore the errors, but obviously I need to actually solve the problem.</p>
<p>Do I maybe need to compile SmartHeap into my perl build? Is that even feasible?</p>
<p>Below is <a href="http://www.microquill.com/kb/docs/APPENDXB.html" rel="nofollow">the only documentation</a> page about mem__bad_pointer's I could find, but I am no closer to solving the problem. I do not understand how or where perl and Smartheap are conflicting with each other. Any pointers appreciated.</p>
<ul>
<li>The pointer was allocated by a memory manager other than SmartHeap, such as from another DLL or EXE, or from the compiler runtime library. Examine your map file to see that the SmartHeap version of malloc, _fmalloc/farmalloc, or operator new is being linked in.</li>
<li>The pointer is âwildâ (uninitialized), is allocated on the stack (local variable), or is otherwise invalid.</li>
<li>The pointer was previously freed. If SmartHeap has freed the page from which the pointer was originally allocated, SmartHeap wonât be able to detect that itâs a double free. However, SmartHeap will report the invalid pointer. Use dbgMemDeferFreeing to catch this type of bug.</li>
<li>The pointer was incremented or decremented since the time of allocation.</li>
<li>For 16-bit x86, the pointer was cast to a near pointer after allocation, in which case the segment portion of the pointer has been lost.</li>
<li>The memory pool from which the pointer was allocated has been freed, or SmartHeap has been unregistered from the task.</li>
<li>The task from which the pointer was allocated has terminated (see section B.4).</li>
</ul>
| <p>Without seeing the code it is hard to debug the problem.
Perhaps you are allocating memory using both smartheap and the regular memory manager. this can be caused when you allocat memory in a dll build without smart heap.</p>
<p>Depending on your code, the allocation could be fine and you may be writing outside the allcoated memory area.</p>
|
How does TransactionScope roll back transactions? <p>I'm writing an integration test where I will be inserting a number of objects into a database and then checking to make sure whether my method retrieves those objects.</p>
<p>My connection to the database is through NHibernate...and my usual method of creating such a test would be to do the following:</p>
<pre><code>NHibernateSession.BeginTransaction();
//use nhibernate to insert objects into database
//retrieve objects via my method
//verify actual objects returned are the same as those inserted
NHibernateSession.RollbackTransaction();
</code></pre>
<p>However, I've recently found out about <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx">TransactionScope</a> which apparently can be used for this very purpose...</p>
<p>Some <a href="http://dotnetslackers.com/articles/ado_net/Managing_Transactions_using_TransactionScope.aspx">example code I've found</a> is as follows:</p>
<pre><code>public static int AddDepartmentWithEmployees(Department dept)
{
int res = 0;
DepartmentAdapter deptAdapter = new DepartmentAdapter();
EmployeeAdapter empAdapter = new EmployeeAdapter();
using (TransactionScope txScope = new TransactionScope())
{
res += deptAdapter.Insert(dept.DepartmentName);
//Custom method made to return Department ID
//after inserting the department "Identity Column"
dept.DepartmentID = deptAdapter.GetInsertReturnValue();
foreach(Employee emp in dept.Employees)
{
emp.EmployeeDeptID = dept.DepartmentID;
res += empAdapter.Insert(emp.EmployeeName, emp.EmployeeDeptID);
}
txScope.Complete();
}
return res;
}
</code></pre>
<p>I believe that if I don't include the line <code>txScope.Complete()</code> that the data inserted will be rolled back. But unfortunately I don't understand how that is possible... how does the <code>txScope</code> object keep a track of the <code>deptAdapter</code> and <code>empAdapter</code> objects and their transactions on the database.</p>
<p>I feel like I'm missing a bit of information here...am I really able to replace my <code>BeginTransaction()</code> and <code>RollbackTransaction(</code>) calls by surrounding my code using <code>TransactionScope</code>?</p>
<p>If not, how then does <code>TransactionScope</code> work to roll back transactions?</p>
| <p>Essentially TransactionScope doesn't track your Adapter's, what it does is it tracks database connections. When you open a DB connection the connections will looks if there is an ambient transaction (Transaction Scope) and if so enlist with it. Caution if there are more the one connection to the same SQL server this will escalate to a Distribtued Transaction. </p>
<p>What happens since you're using a using block you are ensuring dispose will be called even if an exception occurs. So if dispose is called before txScope.Complete() the TransactionScope will tell the connections to rollback their transactions (or the DTC). </p>
|
Should I be testing a methods implementation using mocks <p>I'm having a bit of trouble doing some unit-testing using moq.</p>
<p>If I have a function like this:</p>
<pre><code>public string GetName(IMapinfoWrapper wrapper)
{
return wrapper.Evaluate("My com command");
///"My comm command" is the same all the time.
}
</code></pre>
<p>Then I have a test that checks the return value of the GetName function:</p>
<pre><code>[Test]
public void Test()
{
Mock<IMapinfoWrapper> mock = new Mock<IMapinfoWrapper>();
mock.Expect(mapinfo => mapinfo.Evaluate(It.IsAny<String>()))
.Returns("TableName");
Assert.AreEqual("TableName", GetName(mock.object));
}
</code></pre>
<p>So my question is should the mock be define like this:</p>
<pre><code>mock.Expect(mapinfo => mapinfo.Evaluate(It.IsAny<String>()))
.Returns("TableName");
</code></pre>
<p>or like this:</p>
<pre><code>mock.Expect(mapinfo => mapinfo.Evaluate("My com command")
.Returns("TableName");
</code></pre>
<p>My only problem with using the second way is that I feel like I'm tying the implementation of the method GetName to always use the "My com command" string internally. </p>
<p>Is this what I should be doing or am I doing this all wrong.? <br>I have only started doing unit-testing and mocking so I'm still not sure how everything should go together.</p>
| <p>It depends on what you are actually testing.</p>
<p>If the expectation is that any string passed to Evaluate will return "TableName", then use the call to IsAny.</p>
<p>Otherwise, if you are expecting specific output given specific input, like the case of passing "My com command", then pass the second.</p>
<p>It seems like you aren't looking for specific input, but rather (in this case) doing basic sanity checking, so I would say the former is the right move (again in this case, but you should have more specific cases if you have the use cases for it).</p>
|
How do I control the format in which MS-SQL Server returns datetime values? <p>Specifically, I wish to get the date format in a pure (ISO) format:</p>
<p>YYYY-MM-DD HH:mm:ss</p>
<p>I'm looking for a SET command or something that I can use.</p>
<p>I do not wish to rely on the culture setting of the server.</p>
<p>Note: I'm interested in the string format in which dates are returned, not entered.</p>
| <p>To change the default format you need to add a new language (sp_addlanguage), set it's date format, then set the default language to it. More details can be found on this old <a href="http://support.microsoft.com/kb/173907" rel="nofollow">technet article</a>.</p>
<p>If you don't want to do that, then you can change it "per connection" using <a href="http://technet.microsoft.com/en-us/library/ms189491.aspx" rel="nofollow">SET DATEFORMAT</a>.</p>
<p>And if you don't want to do that, then you can use <a href="http://www.sql-server-helper.com/tips/date-formats.aspx" rel="nofollow">CONVERT</a> to convert it to the relevent format string in each query.</p>
|
WS Addressing and Multiple "ReplyTo" <p>Please any one clarify me WS Addressing in WCF does support the multiple ReplyTo or not?.</p>
| <p>This would answer your question in depth <a href="http://msdn.microsoft.com/en-us/magazine/cc163412.aspx" rel="nofollow">@ Microsoft</a></p>
<p>...</p>
<p><strong>Multiple Endpoints and Unique Addresses</strong></p>
<p>There are a few reasons why you might wish to expose multiple endpoints on a particular service. One reason is to expose the same contract using a few different bindings. For example, you may have some consumers that can only deal with WS-I Basic Profile 1.1-compliant services (one binding) and others that can handle the full suite of standards (another binding). Or you may have some internal enterprise consumers that demand binary TCP transmissions for performance reasons (yet another binding). The ability to expose the same contract using different bindings allows you to accommodate all of these consumers at the same time.
When exposing multiple endpoints with different bindings, each endpoint address must be unique. This is because each endpoint requires a different transport listener and channel stack. Consider the service configuration in Figure 4. In this example, all of the endpoints expose the same contract (ISimpleMath) but each one uses a different binding, so each address must be unique. If you modify an endpoint to use the same address as one of the other endpoints, Windows Communication Foundation will throw an exception while opening the ServiceHost.</p>
<p>...</p>
|
Top 1 on Left Join SubQuery <p>I am trying to take a person and display their current insurance along with their former insurance. I guess one could say that I'm trying to flaten my view of customers or people. I'm running into an issue where I'm getting multiple records back due to multiple records existing within my left join subqueries. I had hoped I could solve this by adding "TOP 1" to the subquery, but that actually returns nothing...</p>
<p>Any ideas?</p>
<pre><code> SELECT
p.person_id AS 'MIRID'
, p.firstname AS 'FIRST'
, p.lastname AS 'LAST'
, pg.name AS 'GROUP'
, e.name AS 'AOR'
, p.leaddate AS 'CONTACT DATE'
, [dbo].[GetPICampaignDisp](p.person_id, '2009') AS 'PI - 2009'
, [dbo].[GetPICampaignDisp](p.person_id, '2008') AS 'PI - 2008'
, [dbo].[GetPICampaignDisp](p.person_id, '2007') AS 'PI - 2007'
, a_disp.name AS 'CURR DISP'
, a_ins.name AS 'CURR INS'
, a_prodtype.name AS 'CURR INS TYPE'
, a_t.date AS 'CURR INS APP DATE'
, a_t.effdate AS 'CURR INS EFF DATE'
, b_disp.name AS 'PREV DISP'
, b_ins.name AS 'PREV INS'
, b_prodtype.name AS 'PREV INS TYPE'
, b_t.date AS 'PREV INS APP DATE'
, b_t.effdate AS 'PREV INS EFF DATE'
, b_t.termdate AS 'PREV INS TERM DATE'
FROM
[person] p
LEFT OUTER JOIN
[employee] e
ON
e.employee_id = p.agentofrecord_id
INNER JOIN
[dbo].[person_physician] pp
ON
p.person_id = pp.person_id
INNER JOIN
[dbo].[physician] ph
ON
ph.physician_id = pp.physician_id
INNER JOIN
[dbo].[clinic] c
ON
c.clinic_id = ph.clinic_id
INNER JOIN
[dbo].[d_Physgroup] pg
ON
pg.d_physgroup_id = c.physgroup_id
LEFT OUTER JOIN
(
SELECT
tr1.*
FROM
[transaction] tr1
LEFT OUTER JOIN
[d_vendor] ins1
ON
ins1.d_vendor_id = tr1.d_vendor_id
LEFT OUTER JOIN
[d_product_type] prodtype1
ON
prodtype1.d_product_type_id = tr1.d_product_type_id
LEFT OUTER JOIN
[d_commission_type] ctype1
ON
ctype1.d_commission_type_id = tr1.d_commission_type_id
WHERE
prodtype1.name <> 'Medicare Part D'
AND tr1.termdate IS NULL
) AS a_t
ON
a_t.person_id = p.person_id
LEFT OUTER JOIN
[d_vendor] a_ins
ON
a_ins.d_vendor_id = a_t.d_vendor_id
LEFT OUTER JOIN
[d_product_type] a_prodtype
ON
a_prodtype.d_product_type_id = a_t.d_product_type_id
LEFT OUTER JOIN
[d_commission_type] a_ctype
ON
a_ctype.d_commission_type_id = a_t.d_commission_type_id
LEFT OUTER JOIN
[d_disposition] a_disp
ON
a_disp.d_disposition_id = a_t.d_disposition_id
LEFT OUTER JOIN
(
SELECT
tr2.*
FROM
[transaction] tr2
LEFT OUTER JOIN
[d_vendor] ins2
ON
ins2.d_vendor_id = tr2.d_vendor_id
LEFT OUTER JOIN
[d_product_type] prodtype2
ON
prodtype2.d_product_type_id = tr2.d_product_type_id
LEFT OUTER JOIN
[d_commission_type] ctype2
ON
ctype2.d_commission_type_id = tr2.d_commission_type_id
WHERE
prodtype2.name <> 'Medicare Part D'
AND tr2.termdate IS NOT NULL
) AS b_t
ON
b_t.person_id = p.person_id
LEFT OUTER JOIN
[d_vendor] b_ins
ON
b_ins.d_vendor_id = b_t.d_vendor_id
LEFT OUTER JOIN
[d_product_type] b_prodtype
ON
b_prodtype.d_product_type_id = b_t.d_product_type_id
LEFT OUTER JOIN
[d_commission_type] b_ctype
ON
b_ctype.d_commission_type_id = b_t.d_commission_type_id
LEFT OUTER JOIN
[d_disposition] b_disp
ON
b_disp.d_disposition_id = b_t.d_disposition_id
WHERE
pg.d_physgroup_id = @PhysGroupID
</code></pre>
| <p>In Sql server 2005 you can use OUTER APPLY</p>
<pre><code>SELECT p.person_id, s.e.employee_id
FROM person p
OUTER APPLY (SELECT TOP 1 *
FROM Employee
WHERE /*JOINCONDITION*/
ORDER BY /*Something*/ DESC) s
</code></pre>
<p><a href="http://technet.microsoft.com/en-us/library/ms175156.aspx">http://technet.microsoft.com/en-us/library/ms175156.aspx</a></p>
|
How many sub-directories should be put into a directory <p>At SO there has been much discussion about how many files in a directory are appropriate: on older filesystems stay below a fey thousand on newer stay below a few hundred thousand.
Generally the suggestion is to create sub-directories for every few thousand files.</p>
<p>So the next question is: what is the maximum number of sub directories I should put into a directory? Nesting them too deep kills dir tree traversal performance. IS there a nesting them to shallow?</p>
| <p>From a practicality standpoint applications might not handle well large directory entries.
For example Windows Explorer gets bogged down with with several thousand directory entries (I've had Vista crash, but XP seems to handle it better).</p>
<p>Since you mention nesting directories also keep in mind that there are limits to the length of fully qualified (with drive designator and path) filenames <a href="http://en.wikipedia.org/wiki/Filename" rel="nofollow">(See wikipedia 'filename' entry)</a>. This will vary with the operating system file system <a href="http://en.wikipedia.org/wiki/Comparison_of_file_systems" rel="nofollow">(See Wikipedia 'comparison on file systems' entry)</a>. </p>
<p>For Windows NTFS it is supposed to be 255, however, I have encountered problems with commands and API functions with fully qualified filenames at about 120 characters. I have also had problems with long path names on mapped networked drives (at least with Vista and I.E. Explorer 7). </p>
<p>Also there are limitations on the nesting level of subdirectories. For example CD-ROM (ISO 9660) is limited to 8 directory levels (something to keep in mind if you would want to copy your directory structure to a CD-ROM, or another filesystem).</p>
<p>So there is a lot of inconsistency when you push the file system to extremes
(while the file system may be able to handle it theoretically, apps and libraries may not).</p>
|
GLSL versions change log? <p>Is there someplace I can read about the changes and additions made in GLSL from version 1.1 to 1.2 and from 1.2 to 1.3?<br />
Google seem to be at a loss for this and I really don't want to start reading the complete specification.</p>
| <p><a href="http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.30.08.withchanges.pdf">Version 1.3</a> of the spec has differences from 1.2 marked, it also lists changes from 1.2. <a href="http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf">Version 1.2</a> has a list of changes from 1.1.</p>
|
How bad is this pattern? <p>I've been using this pattern when I need to control how long various async operations take. I don't mean specifically for WebRequest (I know you can set the timeout property), I just used this as an example for the pattern.</p>
<pre><code> var request = WebRequest.Create(someUri);
WebResponse response = null;
request.BeginGetResponse(result =>
{
var asyncRequest = (WebRequest)result.AsyncState;
response = asyncRequest.EndGetResponse(result);
}, request);
DateTime timeout = DateTime.Now.AddSeconds(10);
while (response == null && DateTime.Now <= timeout)
{
Thread.Sleep(0);
}
if (response == null) throw new Exception("Timeout!");
</code></pre>
<p>Anywhere I read about Thread.Sleep(), I heard it's a baaaad thing to do, but I don't really think this use case abuses it.</p>
<p>I know it is possible that it could be a little bit more than exactly 10 seconds, but that isn't important to me.</p>
<p>So, is this <em>truly</em> a bad way to accomplish what I'm accomplishing, and if so, what is a better way to do it?</p>
<p>EDIT: Perhaps I should clarify what I"m trying to accomplish.</p>
<p>The purpose is to control the maximum amount of time spent waiting on a call. I'm aware that this defeats the purpose of an async call, but the intention was never to be asynchronous, I'm just using it as a means to control when I exit a call.</p>
| <p>The WaitHandles wait methods supports time out, use that. Something like:</p>
<pre><code> var asyncResult = request.BeginGetResponse(...
asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10))
</code></pre>
|
How to determine if a linked list has a cycle using only two memory locations <p>Does anyone know of an algorithm to find if a linked list loops on itself using only two variables to traverse the list. Say you have a linked list of objects, it doesn't matter what type of object. I have a pointer to the head of the linked list in one variable and I am only given one other variable to traverse the list with. </p>
<p>So my plan is to compare pointer values to see if any pointers are the same. The list is of finite size but may be huge. I can set both variable to the head and then traverse the list with the other variable, always checking if it is equal to the other variable, but, if I do hit a loop I will never get out of it. I'm thinking it has to do with different rates of traversing the list and comparing pointer values. Any thoughts?</p>
| <p>I would suggest using <code>Floyd's Cycle-Finding Algorithm</code> <em>aka</em> The <code>Tortoise and the Hare Algorithm</code>. It has O(n) complexity and I think it fits your requirements.</p>
<p>Example code:</p>
<pre><code>function boolean hasLoop(Node startNode){
Node slowNode = Node fastNode1 = Node fastNode2 = startNode;
while (slowNode && fastNode1 = fastNode2.next() && fastNode2 = fastNode1.next()){
if (slowNode == fastNode1 || slowNode == fastNode2) return true;
slowNode = slowNode.next();
}
return false;
}
</code></pre>
<p>More info on Wikipedia: <a href="http://en.wikipedia.org/wiki/Floyd%27s_cycle-finding_algorithm#Tortoise_and_hare">Floyd's cycle-finding algorithm</a>.</p>
|
Java security in non-web app <p>Does anyone know of a good, open source security framework for java?</p>
<p>I've played with jSecurity a bit, and it seems really cool, but the documentation is so sparce I can't seem to make any progress. </p>
<p>Spring security seems web-app oriented -- but I may be wrong. </p>
<p>I am not opposed to writing this myself, but it seems like this should have been done before, why reinvent the wheel?</p>
<p>All this needs to do is be able to provide fine grained security permissions on each level of the app(s).</p>
<p>Example:
App1 has actions 1, 2, 3 (like 'canOpenRemoteFiles', or 'canReprocessTransactions')
App2 has actions 4, 5, 6, 7</p>
<p>I will ultimately need to do something like: </p>
<pre><code>// -- the call may not be this declarative
boolean foo = user.getApp1().canReprocessTransactions();
// do something with foo...
// -- or something like this
boolean bar = user.getApp2().canDoAction1();
// do something with bar...
// -- or...
ArrayList < String > dirsCanAccess = user.getApp1().getAccessableDirs();
</code></pre>
<p>Thanks in advance. </p>
| <p>The last time I looked at Spring-Security it seemed very much web based.</p>
<p>But... the Spring guys are pretty good and I suspect that they have lot of building blocks you could use from the core Spring-Security library. </p>
|
Unix Shell scripting for copying files and creating directory <p>I have a source directory eg <strong>/my/source/directory/</strong> and a destination directory eg <strong>/my/dest/directory/</strong>, which I want to mirror with some constraints.</p>
<ul>
<li>I want to copy files which meet certain criteria of the <strong>find</strong> command, eg <strong>-ctime -2</strong> (less than 2 days old) to the dest directory to mirror it</li>
<li>I want to include some of the prefix so I know where it came from, eg /source/directory </li>
<li>I'd like to do all this with absolute paths so it doesn't depend which directory I run from</li>
<li>I'd guess not having <strong>cd</strong> commands is good practice too.</li>
<li>I want the subdirectories created if they don't exist</li>
</ul>
<p>So </p>
<pre><code>/my/source/directory/1/foo.txt -> /my/dest/directory/source/directory/1/foo.txt
/my/source/directory/2/3/bar.txt -> /my/dest/directory/source/directory/2/3/bar.txt
</code></pre>
<p>I've hacked together the following command line but it seems a bit ugly, can anyone do better?</p>
<pre><code>find /my/source/directory -ctime -2 -type f -printf "%P\n" | xargs -IFILE rsync -avR /my/./source/directory/FILE /my/dest/directory/
</code></pre>
<p>Please comment if you think I should add this command line as an answer myself, I didn't want to be greedy for reputation.</p>
| <p>This is remarkably similar to a (closed) question: <a href="http://stackoverflow.com/questions/363209/bash-scripting-copying-files-without-overwriting/363305#363305">Bash scripting copying files without overwriting</a>. The answer I gave cites the '<code>find | cpio</code>' solution mentioned in other answers (minus the time criteria, but that's the difference between 'similar' and 'same'), and also outlines a solution using GNU 'tar'.</p>
<h3>ctime</h3>
<p>When I tested on Solaris, neither GNU tar nor (Solaris) cpio was able to preserve the ctime setting; indeed, I'm not sure that there is any way to do that. For example, the <code>touch</code> command can set the atime or the mtime or both - but not the ctime. The <code>utime()</code> system call also only takes the mtime or atime values; it does not handle ctime. So, I believe that if you find a solution that preserves ctime, that solution is likely to be platform-specific. (Weird example: hack the disk device and edit the data in the inode - not portable, requires elevated privileges.) Rereading the question, though, I see that 'preserving ctime' is not part of the requirements (phew); it is simply the criterion for whether the file is copied or not.</p>
<h3>chdir</h3>
<p>I think that the '<code>cd</code>' operations are necessary - but they can be wholly localized to the script or command line, though, as illustrated in the question cited and the command lines below, the second of which assumes GNU tar.</p>
<pre><code>(cd /my; find source/directory -ctime -2 | cpio -pvdm /my/dest/directory)
(cd /my; find source/directory -ctime -2 | tar -cf - -F - ) |
(cd /my/dest/directory; tar -xf -)
</code></pre>
<p>Without using <code>chdir()</code> (aka <code>cd</code>), you need specialized tools or options to handle the manipulation of the pathnames on the fly.</p>
<h3>Names with blanks, newlines, etc</h3>
<p>The GNU-specific '<code>find -print0</code>' and '<code>xargs -0</code>' are very powerful and effective, as noted by Adam Hawes. Funnily enough, GNU <code>cpio</code> has an option to handle the output from '<code>find -print0</code>', and that is '<code>--null</code>' or its short form '<code>-0</code>'. So, using GNU <code>find</code> and GNU <code>cpio</code>, the safe command is:</p>
<pre><code>(cd /my; find source/directory -ctime -2 -print0 |
cpio -pvdm0 /my/dest/directory)
</code></pre>
<p><em>Note</em>:This does not overwrite pre-existing files under the backup directory. Add <code>-u</code> to the <code>cpio</code> command for that.</p>
<p>Similarly, GNU <code>tar</code> supports <code>--null</code> (apparently with no <code>-0</code> short-form), and could also be used:</p>
<pre><code>(cd /my; find source/directory -ctime -2 -print0 | tar -cf - -F - --null ) |
(cd /my/dest/directory; tar -xf -)
</code></pre>
<p>The GNU handling of file names with the null terminator is extremely clever and a valuable innovation (though I only became aware of it fairly recently, courtesy of SO; it has been in GNU tar for at least a decade).</p>
|
List of CSS features not supported by IE6 <p>I just finished slicing and coding a very nice table-less css template for my website, all the time I was testing with IE7 and Chrome.</p>
<p>Then I just had the brilliant idea of testing this template with IE6, I installed Windows XP on a Virtual PC and then I opened my website on IE6.</p>
<p><strong>It looks extremely bad!</strong></p>
<p>The format of my page looked like garbage, nothing displaying correctly like in IE7 and Chrome. I knew that some things were not supported by IE6, but I didn't think that my page would render like it did.</p>
<p>So I would like to know if there is a place where I can see what is not supported by IE6 so I can fix my CSS or even create a new one only for IE6.</p>
<p>Any info will be very helpful!</p>
<p>Thanks!</p>
| <p>IE6 has LOTS of CSS bugs so that will be contributing to your page rendering. <a href="http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx">The official list of what is and isn't supported is here</a>.</p>
<p>What might also help you is <a href="http://positioniseverything.net/">positioniseverything.net</a>, they have a comprehensive list of IE bugs and their fixes.</p>
<p>If you're still struggling to get it right post a link to your page.</p>
|
Moodle / Joomla / JFusion - best development platform for e-learning, communication and information portal? <p>I've been asked to develop an information and e-learning website with an emphasis on community aspects that will also encompass a lot of other areas. There is a tight budget to this project, so I'm looking to use off the shelf products where possible - but I need to make sure I pick the best possible platform to begin with. </p>
<p>I am a php developer with extensive database knowledge, so I'm envisioning a degree of active development.</p>
<p>The main requirements are:</p>
<ul>
<li>User Contribution / Community Building</li>
<li>General Content</li>
<li>E-learning </li>
<li>Forums</li>
<li>Blogs</li>
<li>Articles</li>
<li>eCommerce</li>
<li>Listings Directory</li>
<li>Wikis</li>
</ul>
<p>Future areas that have been discussed by the organisation include social networking, so there is a definite emphasis on the community and user contributory aspects.</p>
<p>I know that Moodle is regarded as a leader when it comes to developing e-learning solutions, but I'm fearful it will fall short in the many other areas that the site requires (I'm aware there are plugins / modules available for Moodle, but I'm not sure if generally there is enough development in these areas).</p>
<p>A solution which looks promising to me is <a href="http://www.jfusion.org" rel="nofollow">JFusion</a>, which is an open-source bridge to combine several different systems (in terms of structure and user authentication) - this is built around Joomla, but supports Moodle and several forum software products, along with Magento eCommerce. This would also open up the massive world of Joomla extensions, which I think would cover all the requirements above.</p>
<p>So, to summarise, <strong>my question is - should I try to stick within the confines of Moodle, or should I look to other solutions to cover all angles?</strong> </p>
<p>I'd be very interested to hear from developers who've used both platforms - or perhaps know of more suitable platforms on which to base things.</p>
| <p>Is your primary task to provide a featured LMS, custom social-type extension around an LMS, or merely content?</p>
<p>Moodle is an excellent product, and I think it's likely that you can do what you need around that, but the JFusion solution you're outlining sounds promising to me on the face of it. At that point I'd go with whichever suits your teams technical skills and comfort better.</p>
|
C# data structure for multiple unit conversions <p>I have a C# app and I need to convert between 3 different units (say for example: litres, gallons, and pints). </p>
<p>The app needs to know about certain volumes of liquid, say: 1 pint, 10 pints, 20 pints and 100 pints. I intend to do the calculations and hard code the values (not ideal but necessary), </p>
<p>I'm looking for a data structure that will allow me to easily convert from one unit to another.</p>
<p>Any suggestions?</p>
<p>Please note: I'm not <em>actually</em> using volumes of liquid, its just an example!</p>
| <p>You can store a matrix of conversion factors where</p>
<ul>
<li>a: Is litres</li>
<li>b: Is pints</li>
<li>c: Are gallons</li>
</ul>
<p>You'd have (not accurate, but assuming there are two pints to a litre and 4 litres to a gallon)</p>
<pre><code> a b c
a 1 2 0.25
b 0.5 1 0.125
c 4 8 1
</code></pre>
<p>Alternatively, you can decide that everything is converted to a base value (litres) before being converted to another type, then you just need the first line.</p>
<p>Wrap this in a method that takes a number of units and "from" type and "two" type for the conversion.</p>
<p>Hope this helps</p>
<p><strong>EDIT:</strong> some code, as requested</p>
<pre><code> public enum VolumeType
{
Litre = 0,
Pint = 1,
Gallon = 2
}
public static double ConvertUnits(int units, VolumeType from, VolumeType to)
{
double[][] factor =
{
new double[] {1, 2, 0.25},
new double[] {0.5, 1, 0.125},
new double[] {4, 8, 1}
};
return units * factor[(int)from][(int)to];
}
public static void ShowConversion(int oldUnits, VolumeType from, VolumeType to)
{
double newUnits = ConvertUnits(oldUnits, from, to);
Console.WriteLine("{0} {1} = {2} {3}", oldUnits, from.ToString(), newUnits, to.ToString());
}
static void Main(string[] args)
{
ShowConversion(1, VolumeType.Litre, VolumeType.Litre); // = 1
ShowConversion(1, VolumeType.Litre, VolumeType.Pint); // = 2
ShowConversion(1, VolumeType.Litre, VolumeType.Gallon); // = 4
ShowConversion(1, VolumeType.Pint, VolumeType.Pint); // = 1
ShowConversion(1, VolumeType.Pint, VolumeType.Litre); // = 0.5
ShowConversion(1, VolumeType.Pint, VolumeType.Gallon); // = 0.125
ShowConversion(1, VolumeType.Gallon, VolumeType.Gallon);// = 1
ShowConversion(1, VolumeType.Gallon, VolumeType.Pint); // = 8
ShowConversion(1, VolumeType.Gallon, VolumeType.Litre); // = 4
ShowConversion(10, VolumeType.Litre, VolumeType.Pint); // = 20
ShowConversion(20, VolumeType.Gallon, VolumeType.Pint); // = 160
}
</code></pre>
|
Wrapping the Credential Manager API in .NETCF <p>think I successfully made a managed wrapperclass to the Credential API functions mentioned <a href="http://msdn.microsoft.com/en-us/library/aa922921.aspx" rel="nofollow">here</a> with a little help from <a href="http://blogs.msdn.com/peerchan/pages/487834.aspx" rel="nofollow">there</a> At least the Win32-Errorcodes returned from that functions are Zero or other but expected (i.e. <a href="http://help.netop.com/support/errorcodes/win32_error_codes.htm" rel="nofollow">1168</a> from CredDelete if calling it twice) and the appropriate values are stored at the correct place in the registry (HKLM/Comm/Security/Credman/1..).</p>
<p>Now I am using the Webbrowser-Control embedded in a WindowsForm on a PPC to authenticate to a Website which uses NTLM-Authentication. I dont want to let a popupdialog appear in which the user has to enter his credentials. Instead I am giving the user the possibilities to store his credentials on the device which he has inputted in an Optiondialog-Form in the first place (intern calling CredWrite/CredUpdate).</p>
<p>But the PIE is given a damn about it what I do with the API, neither CredWrite, -Update or -Delete is actually working. So what am I missing here?</p>
<p>Sample code for CredWrite:</p>
<pre><code>[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int CredWrite([In]IntPtr pCred, [In]CREDWRITE_FLAGS dwflags);
public enum CREDWRITE_FLAGS : int
{
CRED_FLAG_FAIL_IF_EXISTING = 0x00000400
}
public struct CRED
{
public int dwVersion;
public CRED_TYPE dwType;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszUser;
public int dwUserLen;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszTarget;
public int dwTargetLen;
public IntPtr pBlob;
public int dwBlobSize;
public CRED_FLAGS dwFlags;
}
public enum CRED_TYPE
{
CRED_TYPE_NTLM = 0x00010002,
CRED_TYPE_KERBEROS = 0x00010004,
CRED_TYPE_PLAINTEXT_PASSWORD = 0x00010006,
CRED_TYPE_CERTIFICATE = 0x00010008,
CRED_TYPE_GENERIC = 0x0001000a,
CRED_TYPE_DOMAIN_PASSWORD = 0x00010001,
}
public enum CRED_FLAGS : int
{
CRED_FLAG_PERSIST = 0x00000001,
CRED_FLAG_DEFAULT = 0x00000002,
CRED_FLAG_SENSITIVE = 0x00000008,
CRED_FLAG_TRUSTED = 0x00000010
}
public static void WriteCredentials(string target, string userName, string password)
{
CRED cred = new CRED();
cred.dwVersion = 1;
cred.dwType = CRED_TYPE.CRED_TYPE_NTLM;
cred.wszTarget = target;
cred.dwTargetLen = target.Length + 1;
cred.wszUser = userName;
cred.dwUserLen = userName.Length + 1;
cred.dwBlobSize = (Encoding.Unicode.GetBytes(password).Length + 1) * 2;
//cred.pBlob = Marshal.StringToCoTaskMemUni(password); //<--not in CF
//cred.pBlob = Marshal2.StringToHGlobalUni(password); //<--from OpenNETCF, the same?
cred.pBlob = Marshal.StringToBSTR(password); //<--not sure of that, but tried the other one also
cred.dwFlags = CRED_FLAGS.CRED_FLAG_PERSIST | CRED_FLAGS.CRED_FLAG_SENSITIVE | CRED_FLAGS.CRED_FLAG_TRUSTED; //<-- results in 25 which is also used in creds read which are stored by the IE-UI-CredMan-dialog
IntPtr credPtr = Marshal.AllocHGlobal(Marshal.SizeOf(cred));
Marshal.StructureToPtr(cred, credPtr, true);
int ret = -1;
ret = CredWrite(credPtr, CREDWRITE_FLAGS.CRED_FLAG_FAIL_IF_EXISTING); //returns zero, unless called twice with the same target/username-tuple.
Marshal.FreeHGlobal(credPtr);
}
</code></pre>
<p>BTW the so called "MS-Experts" are mentioning that PIE has its own cahing mechanism for creds, and thats why PIE is ignoring the changes on CredUpdate. But I doubt that this is 100% correct, cause when I call CredWrite on a device with no credentials at all, that PIE ignores them too (popups cred-inputdialog).</p>
<p>Can someone assist me in that?</p>
| <p>The things I'd check are</p>
<ol>
<li>If you manually log in using the dialog, does it store anything at the expected credential registry key(HKLM/Comm/Security/Credman/1..)? If not, then I'd say it's pretty strong evidence that it isn't using the Cred Manager.</li>
<li>If you do manual NTLM authentication (with Explorer for example), does the browser pop up the credential dialog?</li>
</ol>
<p>I have done NTLM authentication with a device before, just not with the browser control and I used the <a href="http://msdn.microsoft.com/en-us/library/aa924676.aspx" rel="nofollow">Authentication Services APIs</a>. <a href="http://blog.opennetcf.com/ctacke/2005/02/08/NTLMDomainAuthenticationInCE.aspx" rel="nofollow">Here's an example in native</a>. I've been meaning to port it to managed, just haven't found the time.</p>
<p><strong>Edit 1</strong>: In further looking at your code, I don't like the blob. What makes you think it should go in as a BSTR? That's a COM type, and I highly doubt it's what you want. I'd be inclined to just send in a byte array with the password. I'd try Unicode first, since CE is heavily biased toward Unicode, then ASCII if that fails.</p>
<p>I also think your marshaling of the CRED structure is suspect, but that's simply because I've been using the CF since pre-1.0 days and I've learned to "trust but verify" everything the marshaler does. I'd at least look at the CRED instance in a memory view and make sure that those string are indeed just 4-byte pointers and that the addresses that they point to actually contain your string data (nothing more and null terminated).</p>
|
Any way to make Intellisense work, when opening a cs file that's not part of the project? <p>What we ideally need is, to know how Microsoft handles XAML generated code (Those *.g.cs files). If you goto a XAML code behind, intellisense will work even if the *.g.cs file is not part of the project!! </p>
<p><hr /></p>
<p><strong>Context:</strong></p>
<p>In a custom VS package, we need to have some logic to open a CS file (with out making it a part of the project) in the VS IDE, to allow the user to edit it.</p>
<p>We are hooking up the document to the Running document table and receiving the events like Saving, Close and all, using IVSRunningDocumentTable. Works good.</p>
<p>Now the problem is, when the document is opened, Intellisense can't work, for the simple reason that the opened document is not part of the project (sadly, we can't do that, we can't make it code behind).</p>
| <p>Intellisense is driven by a memory cache of identifiers and types. These types are cached based on the project you are in and the references that project has. If the code file you are editing is not part of a project, Visual Studio would have to load every possible assembly and create intellisense data for each type in the entire .NET framework because it would have no way of knowing whether or not your code file required it.</p>
<p>I guess Visual Studio <em>could</em> load intellisense based on the content of the file but that is not the way it currently works.</p>
|
C# ASMX webservice semi -permanant storage requirement <p>I'm writing a mock of a third-party web service to allow us to develop and test our application. </p>
<p>I have a requirement to emulate functionality that allows the user to submit data, and then at some point in the future retrieve the results of processing on the service. What I need to do is persist the submitted data somewhere, and retrieve it later (not in the same session). What I'd like to do is persist the data to a database (simplest solution), but the environment that will host the mock service doesn't allow for that. </p>
<p>I tried using IsolatedStorage (application-scoped), but this doesn't seem to work in my instance. (I'm using the following to get the store...</p>
<pre><code>IsolatedStorageFile.GetStore(IsolatedStorageScope.Application |
IsolatedStorageScope.Assembly, null, null);
</code></pre>
<p>I guess my question is (bearing in mind the fact that I understand the limitations of IsolatedStorage) how would I go about getting this to work? If there is no consistent way to do it, I guess I'll have to fall back to persisting to a specific file location on the filesystem, and all the pain of permission setting that entails in our environment.</p>
| <p>Self-answer.</p>
<p>For the pruposes of dev and test, I realised it would be easiest to limit the lifetime of the persisted objects, and use </p>
<pre><code>HttpRuntime.Cache
</code></pre>
<p>to store the objects. This has just enough flexibility to cope with my situation.</p>
|
"cloud architecture" concepts in a system architecture diagrams <p>If you design a distributed application for easy scale-out, or you just want to make use of any of the new âcloud computingâ offerings by Amazon, Google or Microsoft, there are some typical concepts or components you usually end up using:</p>
<ul>
<li>distributed blob storage (aka S3)</li>
<li>asynchronous, durable message queues (aka SQS) </li>
<li>non-Relational-/non-transactional databases (like SimpleDB, Google BigTable, Azure SQL Services)</li>
<li>distributed background worker pool</li>
<li>load-balanced, edge-service processes handling user requests (often virtualized)</li>
<li>distributed caches (like memcached)</li>
<li>CDN (content delivery network like Akamai)</li>
</ul>
<p>Now when it comes to design and sketch an architecture that makes use of such patterns, are there any commonly used symbols I could use? Or even a download with some cool Visio stencils? :)</p>
<p>It doesnât have to be a formal system like UML but I think it would be great if there were symbols that everyone knows and understands, like we have commonly used shapes for databases or a documents, for example. I think it would be important to not mix it up with traditional concepts like a normal file system (local or network server/SAN), or a relational database. </p>
<p>Simply speaking, I want to be able to draw some conclusions about an applicationâs scalability or data consistency issues by just looking at the system architecture overview diagram.</p>
<p><strong>Update:</strong> Thank you very much for your answers. I like the idea of putting a small "cloud symbol" on the traditional symbols. However I leave this thread open just in case someone will find specific symbols (maybe in a book or so) - or uploaded some pimped up Visio stencils ;)</p>
| <p>Here are two sets of symbols that map nicely to concepts in cloud platforms.</p>
<p>For Windows Azure:
<a href="http://davidpallmann.blogspot.com/2011/07/windows-azure-design-patterns-part-1.html" rel="nofollow">http://davidpallmann.blogspot.com/2011/07/windows-azure-design-patterns-part-1.html</a> (download <a href="http://neudesic.blob.core.windows.net/webpatterns/AzureDesignPatternIcons.zip" rel="nofollow">here</a>)</p>
<p><strong>EDIT Feb 2014</strong> ==> Here's a more complete set released recently by Microsoft: <a href="http://www.microsoft.com/en-us/download/details.aspx?id=41937" rel="nofollow">http://www.microsoft.com/en-us/download/details.aspx?id=41937</a> <strong>This is now the best option to use for Windows Azure.</strong></p>
<p>Amazon Web Services:
<a href="http://aws.typepad.com/aws/2011/12/introducing-aws-simple-icons-for-your-architecture-diagrams.html" rel="nofollow">http://aws.typepad.com/aws/2011/12/introducing-aws-simple-icons-for-your-architecture-diagrams.html</a> </p>
<p>And @markus was obviously well ahead of the curve since he posted this question well before these became available.</p>
|
C#: How to make a form remember its Bounds and WindowState (Taking dual monitor setups into account) <p>I have made a class which a form can inherit from and it handles form Location, Size and State. And it works nicely. Except for one thing: </p>
<p>When you maximize the application on a different screen than your main one, the location and size (before you maximized) gets stored correctly, but when it is maximized (according to its previous state) it is maximized on my main monitor. When I then restore it to normal state, it goes to the other screen where it was before. When I then maximize it again, it of course maximized on the correct screen.</p>
<p>So my question is... how can I make a form, when it is maximized, remember what screen it was maximized on? And how do I restore that when the form opens again?</p>
<p><hr /></p>
<h2>Kind of complete solution to problem</h2>
<p>I accepted the answer which had a very good tip about how to if on screen. But that was just part of my problem, so here is my solution:</p>
<p><strong>On load</strong></p>
<ol>
<li>First get stored <code>Bounds</code> and <code>WindowState</code> from whatever storage.</li>
<li>Then set the <code>Bounds</code>.</li>
<li>Make sure <code>Bounds</code> are visible either by <code>Screen.AllScreens.Any(ø => ø.Bounds.IntersectsWith(Bounds))</code> or <code>MdiParent.Controls.OfType<MdiClient>().First().ClientRectangle.IntersectsWith(Bounds)</code>.
<ul>
<li>If it doesn't, just do <code>Location = new Point();</code>.</li>
</ul></li>
<li>Then set window state.</li>
</ol>
<p><strong>On closing</strong></p>
<ol>
<li>Store <code>WindowState</code>.</li>
<li>If <code>WindowState</code> is <code>FormWindowState.Normal</code>, then store <code>Bounds</code>, otherwise store <code>RestoreBounds</code>.</li>
</ol>
<p>And thats it! =)</p>
<h2>Some example code</h2>
<p>So, as suggested by <a href="http://stackoverflow.com/users/57488/oliver">Oliver</a>, here is some code. It needs to be fleshed out sort of, but this can be used as a start for whoever wants to:</p>
<h3>PersistentFormHandler</h3>
<p>Takes care of storing and fetching the data somewhere.</p>
<pre><code>public sealed class PersistentFormHandler
{
/// <summary>The form identifier in storage.</summary>
public string Name { get; private set; }
/// <summary>Gets and sets the window state. (int instead of enum so that it can be in a BI layer, and not require a reference to WinForms)</summary>
public int WindowState { get; set; }
/// <summary>Gets and sets the window bounds. (X, Y, Width and Height)</summary>
public Rectangle WindowBounds { get; set; }
/// <summary>Dictionary for other values.</summary>
private readonly Dictionary<string, Binary> otherValues;
/// <summary>
/// Instantiates new persistent form handler.
/// </summary>
/// <param name="windowType">The <see cref="Type.FullName"/> will be used as <see cref="Name"/>.</param>
/// <param name="defaultWindowState">Default state of the window.</param>
/// <param name="defaultWindowBounds">Default bounds of the window.</param>
public PersistentFormHandler(Type windowType, int defaultWindowState, Rectangle defaultWindowBounds)
: this(windowType, null, defaultWindowState, defaultWindowBounds) { }
/// <summary>
/// Instantiates new persistent form handler.
/// </summary>
/// <param name="windowType">The <see cref="Type.FullName"/> will be used as base <see cref="Name"/>.</param>
/// <param name="id">Use this if you need to separate windows of same type. Will be appended to <see cref="Name"/>.</param>
/// <param name="defaultWindowState">Default state of the window.</param>
/// <param name="defaultWindowBounds">Default bounds of the window.</param>
public PersistentFormHandler(Type windowType, string id, int defaultWindowState, Rectangle defaultWindowBounds)
{
Name = string.IsNullOrEmpty(id)
? windowType.FullName
: windowType.FullName + ":" + id;
WindowState = defaultWindowState;
WindowBounds = defaultWindowBounds;
otherValues = new Dictionary<string, Binary>();
}
/// <summary>
/// Looks for previously stored values in database.
/// </summary>
/// <returns>False if no previously stored values were found.</returns>
public bool Load()
{
// See Note 1
}
/// <summary>
/// Stores all values in database
/// </summary>
public void Save()
{
// See Note 2
}
/// <summary>
/// Adds the given <paramref key="value"/> to the collection of values that will be
/// stored in database on <see cref="Save"/>.
/// </summary>
/// <typeparam key="T">Type of object.</typeparam>
/// <param name="key">The key you want to use for this value.</param>
/// <param name="value">The value to store.</param>
public void Set<T>(string key, T value)
{
// Create memory stream
using (var s = new MemoryStream())
{
// Serialize value into binary form
var b = new BinaryFormatter();
b.Serialize(s, value);
// Store in dictionary
otherValues[key] = new Binary(s.ToArray());
}
}
/// <summary>
/// Same as <see cref="Get{T}(string,T)"/>, but uses default(<typeparamref name="T"/>) as fallback value.
/// </summary>
/// <typeparam name="T">Type of object</typeparam>
/// <param name="key">The key used on <see cref="Set{T}"/>.</param>
/// <returns>The stored object, or the default(<typeparamref name="T"/>) object if something went wrong.</returns>
public T Get<T>(string key)
{
return Get(key, default(T));
}
/// <summary>
/// Gets the value identified by the given <paramref name="key"/>.
/// </summary>
/// <typeparam name="T">Type of object</typeparam>
/// <param name="key">The key used on <see cref="Set{T}"/>.</param>
/// <param name="fallback">Value to return if the given <paramref name="key"/> could not be found.
/// In other words, if you haven't used <see cref="Set{T}"/> yet.</param>
/// <returns>The stored object, or the <paramref name="fallback"/> object if something went wrong.</returns>
public T Get<T>(string key, T fallback)
{
// If we have a value with this key
if (otherValues.ContainsKey(key))
{
// Create memory stream and fill with binary version of value
using (var s = new MemoryStream(otherValues[key].ToArray()))
{
try
{
// Deserialize, cast and return.
var b = new BinaryFormatter();
return (T)b.Deserialize(s);
}
catch (InvalidCastException)
{
// T is not what it should have been
// (Code changed perhaps?)
}
catch (SerializationException)
{
// Something went wrong during Deserialization
}
}
}
// Else return fallback
return fallback;
}
}
</code></pre>
<p><strong>Note 1:</strong> In the load method you have to look for previously stored <code>WindowState</code>, <code>WindowBounds</code> and other values. We use SQL Server, and have a <code>Window</code> table with columns for <code>Id</code>, <code>Name</code>, <code>MachineName</code> (for <code>Environment.MachineName</code>), <code>UserId</code>, <code>WindowState</code>, <code>X</code>, <code>Y</code>, <code>Height</code>, <code>Width</code>. So for every window, you would have one row with <code>WindowState</code>, <code>X</code>, <code>Y</code>, <code>Height</code> and <code>Width</code> for each user and machine. In addition we have a <code>WindowValues</code> table which just has a foreign key to <code>WindowId</code>, a <code>Key</code> column of type <code>String</code> and a <code>Value</code> column of type <code>Binary</code>. If there is stuff that is not found, I just leave things default and return false.</p>
<p><strong>Note 2:</strong> In the save method you then, of course do the reverse from what you do in the Load method. Creating rows for <code>Window</code> and <code>WindowValues</code> if they don't exist already for the current user and machine.</p>
<h3>PersistentFormBase</h3>
<p>This class uses the previous class and forms a handy base class for other forms.</p>
<pre><code>// Should have been abstract, but that makes the the designer crash at the moment...
public class PersistentFormBase : Form
{
private PersistentFormHandler PersistenceHandler { get; set; }
private bool handlerReady;
protected PersistentFormBase()
{
// Prevents designer from crashing
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
Load += persistentFormLoad;
FormClosing += persistentFormFormClosing;
}
}
protected event EventHandler<EventArgs> ValuesLoaded;
protected event EventHandler<EventArgs> StoringValues;
protected void StoreValue<T>(string key, T value)
{
if (!handlerReady)
throw new InvalidOperationException();
PersistenceHandler.Set(key, value);
}
protected T GetValue<T>(string key)
{
if (!handlerReady)
throw new InvalidOperationException();
return PersistenceHandler.Get<T>(key);
}
protected T GetValue<T>(string key, T fallback)
{
if (!handlerReady)
throw new InvalidOperationException();
return PersistenceHandler.Get(key, fallback);
}
private void persistentFormLoad(object sender, EventArgs e)
{
// Create PersistenceHandler and load values from it
PersistenceHandler = new PersistentFormHandler(GetType(), (int) FormWindowState.Normal, Bounds);
PersistenceHandler.Load();
handlerReady = true;
// Set size and location
Bounds = PersistenceHandler.WindowBounds;
// Check if we have an MdiParent
if(MdiParent == null)
{
// If we don't, make sure we are on screen
if (!Screen.AllScreens.Any(ø => ø.Bounds.IntersectsWith(Bounds)))
Location = new Point();
}
else
{
// If we do, make sure we are visible within the MdiClient area
var c = MdiParent.Controls.OfType<MdiClient>().FirstOrDefault();
if(c != null && !c.ClientRectangle.IntersectsWith(Bounds))
Location = new Point();
}
// Set state
WindowState = Enum.IsDefined(typeof (FormWindowState), PersistenceHandler.WindowState) ? (FormWindowState) PersistenceHandler.WindowState : FormWindowState.Normal;
// Notify that values are loaded and ready for getting.
var handler = ValuesLoaded;
if (handler != null)
handler(this, EventArgs.Empty);
}
private void persistentFormFormClosing(object sender, FormClosingEventArgs e)
{
// Set common things
PersistenceHandler.WindowState = (int) WindowState;
PersistenceHandler.WindowBounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
// Notify that values will be stored now, so time to store values.
var handler = StoringValues;
if (handler != null)
handler(this, EventArgs.Empty);
// Save values
PersistenceHandler.Save();
}
}
</code></pre>
<p>And thats pretty much it. To use it, a form would just inherit from the PersistentFormBase. That would automatically take care of bounds and state. If anything else should be stored, like a splitter distance, you would listen for the <code>ValuesLoaded</code> and <code>StoringValues</code> events and in those use the <code>GetValue</code> and <code>StoreValue</code> methods.</p>
<p>Hope this can help someone! Please let me know if it does. And also, please provide some feedback if there is anything you think could be done better or something. I would like to learn =)</p>
| <p>There's no built in way to do this - you'll have to write the logic yourself. One reason for this is that you have to decide how to handle the case where the monitor that the window was last shown on is no longer available. This can be quite common with laptops and projectors, for example. The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen(VS.80).aspx" rel="nofollow">Screen</a> class has some useful functionality to help with this, although it can be difficult to uniquely and consistently identify a display.</p>
|
ORM or something to handle SQL tables with an order column efficiently <p>I got an Java application using SQL tables that contains an ordered list of entities, ordered by
an order column. I would like to add/remove things in/from the middle
of the list. Now, I'm wondering if some persistence framework / orm / you-name-it
could provide this kind of functionality with batch update of order
column. </p>
<p>At the basic case Hibernate (and probably others also) provide this
functionality.
The problem is that the objects are handled one at time, which becomes
problem when the list is large enough. Alternate solution would be to
do the thing with a batch SQL update, like the following for example:</p>
<pre><code>UPDATE table SET order_col = order_col + 1 WHERE order_col > 47
INSERT TO table VALUES ('new_id', 'new_description, ..., 47)
</code></pre>
<p>which is done quite fast by the database engine but isn't supported. </p>
<p>Now, I understand that this
kind of batch updates don't fit so well when thinking the objects and their
versioning, dirty checking etc.
I'd still ask if somebody has some nice ideas or if some persistence
framework / ORM / you-name-it would provide some help.
Of course I can do the thing with custom SQL/HQL/... but was wondering
if there would be some solution already (I'd think somebody else could
have done something like this before and even put it under open source). Also other good ideas related to the problem are welcome =)</p>
| <p>My advice is to do two things:</p>
<ol>
<li>Choose very large increments between your items, say one million. This way you can move an item at 8,000,000 to before 7,000,000 by changing just it to 6,500,000; and</li>
<li>Every now and again reorder the items as a batch job.</li>
</ol>
<p>The large increments don't eliminate the problem of doing a large reorder but the need to do a big reorder highly unlikely and the batch job is there to reorder them say once every day/week/month as required.</p>
<p>Changing a whole bunch of items at once is just messy and asking for trouble.</p>
|
How can I keep variables from being re-initialized every time I call a C++ function? <p>How do I get past this variable initialization problem? If I only could figure out how to only initialize them only once...</p>
<pre><code>* Main.cpp : main project file.
/************************** Begin Header **************************/
#include "stdafx.h" //Required by Visual C ++
#include <string> //Required to use strings
#include <iostream> //Required for a bunch of important things
#include <iomanip> //Required for manipulation of text and numbers
using namespace System; // Automatically uses System namespace
using namespace std; // Automatically uses std namespace
#pragma hdrstop // Stops header here
/*************************** End Header ***************************/
//* Begin Function Headers *//
void inputData(); // This will be used to organize class member calls when setting and getting new data.
int getData(); // Will get user data, input in character string, convert to an integer and then perform data validation.
void createReport(int place, int number, string type); // Will organize commands to create the report and display it on the screen.
//* End Function Headers *//
class JarsSold // Begin Class -- JarsSold
{
/* Begin Initialization & Creation of important resources */
private:
static const int MaxArray = 5; // Value for the size of array JARS_SOLD
int JARS_SOLD[MaxArray]; // Creation of array with size of MaxArray
/* End Initialization & Creation of important resources */
public: // Makes underlining elements Public instead of the default Private
JarsSold() // Begin Constructor
{ // Put something in num array
JARS_SOLD[0] = 0; // [1]
JARS_SOLD[1] = 0; // [2]
JARS_SOLD[2] = 0; // [3]
JARS_SOLD[3] = 0; // [4]
JARS_SOLD[4] = 0; // [5]
} // End Constructor
~JarsSold(){}; // Destructor
/* Put all members for JarsSold class below here */
void setNumber(int num, int value) // Set the number of jars sold with number placement in array and value to replace it with
{
JARS_SOLD[num] = value; // Stores value into JARS_SOLD at whatever num is at the time
}; // End setNumber class member
int getNumber(int num) // Get the current number held for jars sold with number placement in array
{
return JARS_SOLD[num]; // Returns whatever is in JARS_SOLD depending on what num is at the time
} // End getNumber class member
/* Put all members for JarsSold class above here */
}; // End Class -- JarsSold
class SalsaTypes // Begin Class -- SalsaTypes
{
/* Begin Initialization & Creation of important resources */
private:
static const int MaxArray = 5; // Value for the size of array JARS_SOLD
string SALSA_TYPES[MaxArray]; // Creation of array with size of MaxArray
/* End Initialization & Creation of important resources */
public: // Makes underlining elements public instead of the default Private
SalsaTypes() // Begin Constructor
{ // Add default strings to str array
SALSA_TYPES[0] = "Mild"; // [1] Stores Mild into SALSA_TYPES at 0 spot
SALSA_TYPES[1] = "Medium"; // [2] Stores Medium into SALSA_TYPES at 1 spot
SALSA_TYPES[2] = "Sweet"; // [3] Stores Sweet into SALSA_TYPES at 2 spot
SALSA_TYPES[3] = "Hot"; // [4] Stores Hot into SALSA_TYPES at 3 spot
SALSA_TYPES[4] = "Zesty"; // [5] Stores Zesty into SALSA_TYPES at 4 spot
} // End Constructor
~SalsaTypes(){}; // Destructor
/* Put all members for SalsaTypes class below here */
void setType(int num, string type) // Set salsa type with number placement in array and string value to replace with
{
SALSA_TYPES[num] = type; // Stores the string type into SALSA_TYPES at whatever num is at the time
}; // End setType class member
string getType(int num) // Get the Salsa Type with number placement in array
{
return SALSA_TYPES[num]; // Returns SALSA_TYPES depending on what is in num at the time
}; // End getType class member
/* Put all members for SalsaTypes class above here */
};// End Class -- SalsaTypes
void main( void ) // Begin Main Program
{
cout << fixed << setprecision(1) << setw(2); // Do a little customization with IoManip, might as well, we just might need it
// Main Program Contents Begin Here //
// Opening Credits for Program
cout << "Welcome to the /Professional Edition\\ of the Chip and Salsa Sale Tool EXPRESS." << endl;
cout << "This handy-dandy tool will make a chip and salsa manufacturer's job much easier!" << endl;
cout << endl << endl << endl;
cout << "Press any key to begin inputing the number of jars sold for these salsa flavors: " << endl << endl;
cout << "-Mild" << endl << "-Medium" << endl<< "-Sweet" << endl << "-Hot" << endl << "-Zesty" << endl << endl << endl;
system("pause"); // Pause here. After this begin data input
cout << endl << endl << endl;
inputData(); // Will deal with data input, validation, and reports
// Main Program Contents End Here //
} //End Main Program
// All Content for Functions Begin Here //
void inputData() // Begin inputData Function
{
// Begin Create Class Obects //
SalsaTypes salsa;
JarsSold jars;
// End Create Class Objects //
// Variable Creation Begin //
// Variable Creation End //
// All Content for Functions Begin Here //
for (int i = 0 ; i < 5 ; i++) // Start For Loop
{
cout << "Input how many Jars were sold for \"" << salsa.getType(i) << "\"" << ": "; // Displays which Salsa we are reffering to
jars.setNumber(i,getData()); // Will use getData() to determine what value to send to the JarsSold class.
createReport(i,jars.getNumber(i),salsa.getType(i)); // Send these numbers to another function so it can make a report later
cout << endl << endl; // Using this as a spacer
}
// All Content for Functions End Here //
}; // End inputData Function
int getData() // Begin getData Function
{
// Variable Creation Begin //
char charData[40]; // Will be used to store user data entry
int numTest; // Will be used for Data Validation methods
// Variable Creation End //
// Main Contents of Function Begin Here //
retry: // Locator for goto command
cin >> charData; // Ask user for input. Will store in character string then convert to an integer for data validation using 'Atoi'
numTest = atoi ( charData ); // Convert charData to integer and store in numTest
if (numTest < 0) { numTest = 0; cout << endl << endl << "You can't enter negative numbers! Try Again." << endl << endl << "Re-enter number: "; goto retry;} // Filter out negative numbers
// Main Contents of Function End Here //
return numTest; // If it makes it this far, it passed all the tests. Send this value back.
}; // End getData Function
void createReport(int place, int number, string type) // Begin createReport Function
{
// Variable Creation Begin //
int const MAX = 5; // Creat array size variable
int lowest; // The integer it will use to store the place of the lowest jar sales in the array
int highest; // The integer it will use to store the place of the highest jar sales in the array
int total; // The integer it will use to store total sales
int numArray[MAX]; // Create array to store jar sales (integers)
string typeArray[MAX]; // Create array to store types of salsa (strings)
// Variable Creation End //
// Main Contents of Function Begin Here //
numArray[place] = number; // Store number into new array
typeArray[place] = type; // Store type into new array
if (place = 4) // If the array is full it means we are done getting data and it is time to make the report.
{ // Begin making report, If statement start
for ( int i = 0 ; i < 5 ; i++ ) // Using a for-loop to find the highest and lowest value in the array
{ // For Loop to find high and low values BEGIN
if ( lowest < numArray[i]) // Keep setting lowest to the lowest value until it finds the lowest one
{ // Start If
lowest = numArray[i]; // Lowest equals whatever is in numArray at i spot
} // End If
if ( highest > numArray[i]) // Keep setting highest to the highest value until it finds the highest one
{ // Start If
highest = numArray[i]; // Highest equals whatever is in numArray at i spot
} // End If
total += numArray[i]; // Will continually add numArray at i spot until it has the total sales
} // For Loop to find high and low values END
// Main Contents of Function End Here //
} // END creatReport Function
// All Content for Functions Ends Here //
</code></pre>
<p>Well my problem is...I need to get my data across from one function to another. I thought I could figure out how to create Global Class Objects but I couldn't. So I thought I could get around just passing the arguments to another function and then restoring them in its own arrays and then keep doing that until i've completely copied all number arrays and string arrays. Well...yeah that does work EXCEPT this part in createReport():</p>
<pre><code>// Variable Creation Begin //
int const MAX = 5; // Create array size variable
int lowest; // The integer it will use to store the place of the lowest jar sales in the array
int highest; // The integer it will use to store the place of the highest jar sales in the array
int total; // The integer it will use to store total sales
int numArray[MAX]; // Create array to store jar sales (integers)
string typeArray[MAX]; // Create array to store types of salsa (strings)
// Variable Creation End //
</code></pre>
<p>What happens is, I guess I am so tired that I missed it, every time I call that function it re-initializes those same variables again. I will put variables into another variable and then it will get re-initialized to default values.</p>
<p>I tried using a counter variable that counted to one after it initialized and then after it was 1 it wouldnt initialize again. No that didn't work because the variables werent initialized outside the scope of the if statement. I then tried a GOTO statement that would skip the initialization after it happened once. Nope something went wrong with the first initialization phase and no compilation.</p>
<p>I need to figure out how I can either </p>
<ol>
<li>keep those variables from getting re-assigned or initialized so they can maintain their values. Or </li>
<li>figure out how to create global class objects (and yes I've tried the extern classes with multiple source files. No luck just lots of errors)</li>
</ol>
<p>I'm not very good at programming yet. But I assure you I've been working on this piece for hours and hours and hours and I stayed up all night just constantly trial and error. I really proud of myself because this code is pretty advanced for me. I've looked at every tutorial on Google and I'm fresh out of luck -- you guys are my last hope!! Sorry again guys. I know this is a dumb question...</p>
<p>One last quick question. How do you create Global Class Objects? For example</p>
<pre><code>MyClass
{
MyClass(){};
~MyClass(){};
}
MyClass MyClassObject;
</code></pre>
<p>How do I use MyClassObject throughout my entire program?</p>
<p>The only way I can use it is if I create a new object every time with every function I use. And that means I lose all data stored inside my class?</p>
<p>I've read that having global object isn't a good idea though. I would love to not have to use them but I have no clue on any alternatives that I can actually understand.</p>
<p>Any other critiques or tips is GREATLY appreciated. I love this stuff I just don't have many people to ask questions to.</p>
| <p>You're doing really well! The simple answer is to write static in front of your variables:</p>
<pre><code>static int const MAX = 5; // Creat array size variable
static int lowest; // The integer it will use to store the place of the lowest jar sales in the array
static int highest; // The integer it will use to store the place of the highest jar sales in the array
static int total; // The integer it will use to store total sales
static int numArray[MAX]; // Create array to store jar sales (integers)
static string typeArray[MAX]; // Create array to store types of salsa (strings
</code></pre>
<p>I think I can give you better advice though, I'll look at your code for a bit longer. As for global variables, what you wrote there with MyClassObject would work fine. You'd use it like this:</p>
<pre><code>MyClass {
public:
MyClass(){};
~MyClass(){};
int variable;
};
MyClass MyClassObject;
// in a method you'd do this
void whateverMethod() {
MyClassObject.variable = 5;
std::cout << MyClassObject.variable << std::endl;
}
</code></pre>
<p>That kind of thing. There are some style issues that could be fixed but to be honest I say just get it working first and then we can talk about those.</p>
|
Should failing tests make the continuous build fail? <p>If one has a project that has tests that are executed as part of the build procedure on a build machine, if a set tests fail, should the entire build fail?<br />
What are the things one should consider when answering that question? Does it matter which tests are failing?</p>
<p><hr /></p>
<p>Background information that prompted this question:</p>
<p>Currently I am working on a project that has <a href="http://www.nunit.org/">NUnit</a> tests that are done as part of the build procedure and are executed on our <a href="http://ccnet.thoughtworks.com/">cruise control .net</a> build machine.</p>
<p>The project used to be setup so that if any tests fail, the build fails. The reasoning being if the tests fail, that means the product is not working/not complete/it is a failure of a project, and hence the build should fail.</p>
<p>We have added some tests that although they fail, they are not crucial to the project (see below for more details). So if those tests fail, the project is not a complete failure, and we would still want it to build.</p>
<p>One of the tests that passes verifies that incorrect arguments result in an exception, but the test does not pass is the one that checks that all the allowed arguments do <em>not</em> result in an exception. So the class rejects all invalid cases, but also some valid ones. This is not a problem for the project, since the rejected valid arguments are fringe cases, on which the application will not rely.</p>
| <p>If it's in any way doable, then do it. It greatly reduces the <a href="http://www.pragprog.com/the-pragmatic-programmer/extracts/software-entropy">broken-window-problem</a>:</p>
<p>In a system with no (visible) flaws, introducing a small flaw is usually seen as a very bad idea. So if you've got a project with a green status (no unit test fails) and you introduce the first failing test, then you (and/or your peers) will be motivated to fix the problem.</p>
<p>If, on the other side, there are known-failing tests, then adding just another broken test is seen as keeping the status-quo.</p>
<p>Therefore you should always strive to keep <em>all</em> tests running (and not just "most of them"). And treating every single failing test as reason for failing the build goes a long way towards that goal.</p>
|
TFS build agent, same port as team server? <p>My team foundation is setup to use port 8080, when I am creating a new build agent it defaults to port 9191.</p>
<p>Which one should I use?</p>
<p>I am getting an error when I try and run my build, it says the build agent was unreachable.</p>
<p>I created a share on my drive c:\tfsbuilds, and I added the TFSService account and gave it full rights.</p>
<p>I am using the \computername\tfsbuilds as my path to the builds folder.</p>
<p>What else could be wrong?</p>
<p><b>Error message</b></p>
<p>Team Foundation Build on computer TFSBUILDS.MyServer1.local (port 9191) is not responding. (Detail Message: Unable to connect to the remote server)</p>
| <p>Has the Build service been started? This is probably the most common issue as the service will need to be started first. And yes, 9191 is the default port for the build agents. Can you also check your firewall?</p>
|
SQL Server - Transactional Replication (partial data only) <p>I have 6 months of data, how do I replicate only the most current 3 months of data to the subscribers?</p>
| <p>You can use filtered replication. When you read examples about filtered replication, you'll probably see it referring to a branch office scenario where a single central office stores data for several branch offices, and each branch only wants to replicate their own data. It involves creating filters on a key, and in your case, you'll want to use your date range as the key.</p>
<p>Here's an <a href="http://sqlserverpedia.com/wiki/Creating_Transactional_Replication_Publications" rel="nofollow">article on filtered replication with transactional replication</a>, and another on <a href="http://sqlserverpedia.com/wiki/Creating_Merge_Replication_Publications" rel="nofollow">filtering with merge replication</a>.</p>
|
Can we write a sub function or procedure inside another stored procedure - SQL Server <p>I want to check if SQL Server(2000/05/08) has the ability to write a nested stored procedure, what I meant is - WRITING a Sub Function/procedure inside another stored procedure. NOT calling another SP. </p>
<p>Why I was thinking about it is- One of my SP is having a repeated lines of code and that is specific to only this SP.So if we have this nested SP feature then I can declare another sub/local procedure inside my main SP and put all the repeating lines in that. and I can call that local sp in my main SP. I remember such feature is available in Oracle SPs.</p>
<p>If SQL server is also having this feature, can someone please explain some more details about it or provide a link where I can find documentation.</p>
<p>Thanks in advance
Sai</p>
| <p>It does not have that feature. It is hard to see what real benefit such a feature would provide, apart from stopping the code in the nested SPROC from being called from elsewhere.</p>
|
How to use a ThrottlingFilter for Jetty in Restlet <p>I would like to configure a webservice so that once the accept queue is full the service returns 503. Currently, these requests seem to just time out. </p>
<p>I did set paramters like <strong>maxThreads</strong> and <strong>acceptQueuesize</strong> (as described here: <a href="http://www.restlet.org/documentation/1.1/ext/com/noelios/restlet/ext/jetty/JettyServerHelper" rel="nofollow">http://www.restlet.org/documentation/1.1/ext/com/noelios/restlet/ext/jetty/JettyServerHelper</a>).</p>
<p>But the service does not respond with 503 once the acceptQueue is full.</p>
<p>It seems jetty's ThrottlingFilter (<a href="http://www.mortbay.org/jetty/jetty-6/apidocs/index.html?index-all.html" rel="nofollow">http://www.mortbay.org/jetty/jetty-6/apidocs/index.html?index-all.html</a>) is what I'm looking for, but I don't know how to apply within my restlet service.</p>
| <p>You won't be able to take advantage of ThrottlingFilter unless you deploy your application as a WAR file into Jetty. JettyServerHelper bootstraps Restlet as a standalone server using Jetty to accept HTTP connections and hence cannot utilize a Servlet Filter. I'm not sure if there is anyway to utilize similar processing logic from the ThrottlingFilter in Jetty outside of the Servlet world or not.</p>
|
SMTP server that saves all mail to a folder? <p>Are there any free SMTP servers that just accept the mail sent through them, and save it to your hard disk, without sending it to the recipient. I would like to use this for testing my applications. Instead of just waiting around for the mail to go through, it would be nice if all emails could just be dropped in a folder, so that I can look at them. I could put some hooks into my program to just save instead of sending the message, but I don't think it's a full test, if the code follows a different path. Are there any existing applications like this? </p>
<p>I figure this would be really helpful, because you could test the mail abilities without needing to wait for the mail server to deliver it, and so that you can code while you're offline, and don't have access to an actual mail server.</p>
<p>[EDIT]</p>
<p>I'm specifically using .Net, but I'm not using the default SMTP mail handling classes in .Net, because of how limited they were in .Net 1.1. We are using a third party library (chilkat). I know that things have changed since then, but the code is stable and works, so no point in rewriting against the .Net API now. </p>
<p>I would like something that works as an SMTP server specifically because I could use it in the future for whatever projects I worked on, no matter the language.</p>
| <p>You can use the standard smtp settings in your app or web.config and just specify what folder you want the emails to go.</p>
<pre><code><smtp
deliveryMethod="specifiedPickupDirectory"
from="from address">
<specifiedPickupDirectory>Your folder here</specifiedPickupDirectory>
</smtp>
</code></pre>
<p>This allows you to simply store the emails without an smtp server</p>
|
How do I write a value to the registry on a Windows Mobile 5 device? <p>I have a string value that I want to write to the registry as a Dword to read via another program. How can i create a new key/string using c# .net?</p>
| <p>You need to use Microsoft.Win32.Registry to add to the mobile device registry. All of the methods have mobile support: <a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.registry_members.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.win32.registry_members.aspx</a></p>
|
Best way to Implement a MySQL Hash Table? <p><strong>Background</strong></p>
<p>I'm currently developing an online community and I want to store some temporary information in a hash table. Currently this information is being stored in memcached, however, should the memcached service need to be restarted or failed, I would like to resort back to the on disk hash/cache.</p>
<p><strong>The Question</strong></p>
<p>What is the most effective method of implementing an on disk Hash or Cache table in MySql? Are there any techniques that I can use to get out of a simple table which will have the following fields:</p>
<ul>
<li>Hash Value</li>
<li>Stored Value</li>
<li>Expiry Date</li>
</ul>
<p>Any help or insight would be much appreciated.</p>
<p><strong>Clarity</strong></p>
<ul>
<li>I won't be storing any complex data objects, just simple text strings.</li>
<li>My current plan is to implement an InnoDB table.</li>
<li>Any links to articles on a similar topic would be a bonus.</li>
</ul>
| <p>You already laid out most of the solution for now: one table, three columns (probably a fourth that's a meaningless integer ID for a primary key), and an index on the hash value column. Ask again later when you have a testable / fixable problem to overcome.</p>
<p>"...premature optimization is the root of all evil" -<a href="http://en.wikipedia.org/wiki/Optimization_(computer_science)#cite_note-0">Knuth</a></p>
|
Remove server.policy from sun application server <p>I encounter <code>java.lang.StackOverflowError</code> error after deployment of the java web application (<code>.war</code>). If I remove the <code>server.policy</code> file. I will not encounter this error however it means that there will be no security. I realize that the error will occur if I include the following in <code>server.policy</code> which by default is included permission <code>java.lang.RuntimePermission</code> - <code>modifyThreadGroup</code>;</p>
<p>If inside the <code>server.policy</code> file I just remove this permission <code>java.lang.RuntimePermission</code> - <code>modifyThreadGroup</code>;</p>
<p>I will get access denied as by default the security manager will check for this permission.</p>
<p>Anyone have any idea what is wrong and how do I resolve this?</p>
<p><code>java.lang.StackOverflowError</code></p>
| <p>The obvious way to get a <code>StackOverflowError</code> due to having security enabled is by not giving code that is involved in security checks privileges. So I guess it's something to do with your configuration, perhaps where a codeBase has changed or exactly the same code appears in the search order before the code given privileges.</p>
|
Should I use Top(1) in a SubQuery <p>Example Query:</p>
<pre><code>select *
from A join B on A.ID = B.SOMEVALUE
where A.VALUE="something" and
B.ID =
(select ID from B where SOMEVALUE = A.ID and
THISDATE = (select max(SOMEDATE) from B where ...))
</code></pre>
<p>so, if you can read SQL you should see that I am doing a couple correlated subqueries to narrow down the results of the join . (and yes, this is horribly over-simplified).</p>
<p>In certain cases the subquery:</p>
<pre><code>select ID from B where SOMEVALUE = A.ID and
THISDATE = (select max(SOMEDATE) from B where ...)
</code></pre>
<p>can return more than 1 value, which causes an error </p>
<blockquote>
<p>"Subquery returned more than 1 value.
This is not permitted when the
subquery follows =, !=, <, <= , >, >=
or when the subquery is used as an
expression."</p>
</blockquote>
<p>which I fully expect. This is obviously not a good thing and I have code in place to (hopefully) prevent these duplicates from getting into the database in the first place (ie table B <em>should</em> only have 1 row that matches the </p>
<pre><code>SOMEVALUE = A.ID and max(SOMEDATE)
</code></pre>
<p>criteria), however end-users are nothing if not creative in finding ways I can't think of to break software.</p>
<p>So now to my question:</p>
<p>Would it be better to change the first subquery to </p>
<pre><code>select top 1 * from B ...
</code></pre>
<p>to prevent the user from seeing an error when/if (hopefully never) this situation arises or let the error come through. I'm leaning to not adding the top statement and letting the error come through rather then let the user see potentially incorrect data. I'm wondering if anyone has any thoughts on Best Practices in a situation like this...</p>
| <p>Normally TOP 1 is a good idea.</p>
<p>Consider a large table with millions of rows with no index on the column you are matching, however you are only looking for a single row.</p>
<p>SELECT TOP 1 will mean the table scan stops as soon as the one item is found.</p>
<p>Without the TOP 1, the table scan will continue right through to the end.</p>
<p>As with anything that involves scanning (or brute force) to do the search. Using TOP 1, it should on average be 50% quicker than not using TOP 1.</p>
<p>However, Depending on what you need to return back, A real performance gain can normally be made by using EXISTS.</p>
<p>Instead of writing</p>
<pre><code>SELECT * FROM table t
WHERE t.id = (SELECT TOP 1 foreignid from table2)
</code></pre>
<p>You can use</p>
<pre><code>SELECT * FROM table t
WHERE EXISTS (SELECT 1 from table2 WHERE foreignid = t.id)
</code></pre>
|
AOP for third-party classes <p>I have used AOP within spring with no real problems, mainly for transaction management, for which it works a charm. </p>
<p>My question is this... the only examples I've seen for AOP so far is to pointcut a class that you have created yourself. Is it possible to pointcut a class within a third party library, for example a database connection class. The context is that I wish to create some logs and gather information when an oracle data source executes a call to the database, which is unfortunately contained within a stack of oracle class files. How would you pointcut this class/method when the SQL is executed?</p>
| <p>I think this will work:</p>
<ol>
<li>Let Spring be responsible for initializing your DataSource</li>
<li>Apply an aspect against the getConnection() method on your DataSource</li>
<li>In your advice, wrap the returned Connection in a new class ("LoggingConnection") which implements Connection and delegates all methods to the "real" wrapped Connection (I believe this is the Decorator pattern)</li>
<li>Add whatever logging code you need to the "LoggingConnection" class</li>
</ol>
<p>Bear in mind that this approach creates a proxy of the original DataSource and delegates to it for each method call. In the context of a database operation this shouldn't create a lot of additional overhead. You will want to be extremely careful what your code is doing, lest it throw exceptions and prevent Connections from behaving appropriately. Perhaps use try/catch/finally and put the call that delegates to the "real" Connection in your finally block.</p>
<p>Another totally different approach would be to use AspectJ and do load-time weaving. That way you can decorate the class with new functionality as soon as the ClassLoader loads it.</p>
|
MSDN C# ProcessController Sample <p>I've found this MSDN article that explains how to monitor processes and services with C#:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa645519(VS.71).aspx" rel="nofollow">ProcessController Sample: Demonstrates Processes and Services Monitoring</a></p>
<p>However, I can't download or find this sample anywhere! And it would be really helpful.</p>
<p>Can somebody help me?</p>
| <p>The information you are looking for is here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/z9hsy596(VS.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/z9hsy596(VS.80).aspx</a></p>
<p>You need to install the Microsoft .NET Framework SDK v2.0 which comes with the QuickStart samples.</p>
<p>In response to your comment:</p>
<p>I downloaded from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=FE6F2099-B7B4-4F47-A244-C96D69C35DEC&displaylang=en" rel="nofollow">this page</a>. I then ran <code>setup.exe</code> and on the page titled <strong>Installation Options</strong> I checked the <strong>QuickStart Samples</strong> box and completed the installation. I then followed the instructions <a href="http://msdn.microsoft.com/en-us/library/z9hsy596(VS.80).aspx" rel="nofollow">here</a> to access the QuickStarts on my system.</p>
|
Help with custom getline() function <p>Can anyone explain to me why this isn't working?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
char *getline(int lim)
{
char c;
int i;
char *line;
line = malloc(sizeof(char) * lim);
i = 0;
while((c = getchar()) != '\n' && c != EOF && i < lim-1)
{
*line = c;
line++;
i++;
}
*line = '\0';
printf("%s", line);
return line;
}
</code></pre>
<p>I'm not worried about the return value right now - just the reason as to why <code>printf("%s", line)</code> isn't working.</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong> fixed to <code>line = malloc(sizeof(char) * lim);</code> but it is still not working.</p>
<p><strong>Solution:</strong> the address of <code>*line</code> was being incremented throughout the function. When it was passed to <code>printf()</code>, <code>*line</code> pointed to '\0' because that's where its adress was incremented to. Using a temprorary pointer that stored the original address allocated by <code>malloc()</code> to <code>*line</code> and then passing that pointer into <code>printf()</code>, allowed for the function to walk up the pointer.</p>
| <p>Because you are only allocating enough space for a single character in this line:</p>
<pre><code>line = malloc(sizeof(char));
</code></pre>
<p>And that is getting filled with the <code>\0</code> before your <code>printf</code> statement.</p>
<p>I'm guessing you want to change this line to:</p>
<pre><code>/* Allocate enough room for 'lim' - 1 characters and a trailing \0 */
line = malloc(sizeof(char) * lim);
</code></pre>
<p>Or even better:</p>
<pre><code>char *line, *tmp;
tmp = line = malloc(sizeof(char) * lim);
</code></pre>
<p>And then use <code>tmp</code> in all of your pointer math, this way <code>line</code> will still point to the start of your string.</p>
<p>And I know it's early in your development, but you'll want to make sure you <code>free()</code> the memory that you <code>malloc()</code>.</p>
<p><hr /></p>
<p>Here is a working version of your function including my suggested changes:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
char *getline(int lim)
{
char c;
int i;
char *line, *tmp;
tmp = line = malloc(sizeof(char) * lim);
i = 0;
/* NOTE: 'i' is completely redundant as you can use 'tmp',
* 'line,' and 'lim' to determine if you are going to
* overflow your buffer */
while((c = getchar()) != '\n' && c != EOF && i < lim-1)
{
*tmp = c;
tmp++;
i++;
}
*tmp = '\0';
printf("%s", line);
return line;
}
</code></pre>
|
Minimal hosted bug tracking <p>We are a small businesses with limited time to do this ourselves.<br>
Can anyone recommend a good (cheap, preferably) hosted solution for simple bug tracking?<br>
Right now we have three products that needs bugtracking.</p>
<p>All we need is</p>
<ul>
<li>Allow customers to submit bugs</li>
<li>Assign bug</li>
<li>Show status of bug</li>
<li>Automatic send email to customer when bug status is changed/resolved/closed (if requested)</li>
</ul>
<p>Besides that a small wiki/project would be nice.</p>
| <p>Hosted FogBugz will do all of that. It's free for one or two developers, $25/developer/month for more than that.</p>
|
C# - Get Field Types <p>In a C# 2.0 I have a list of fields and a list of values (stored as strings), a table name, and an ODBC Connection. </p>
<p>I need to get the data types of the fields that are on that table, so I know how to generate my sql.</p>
<p>What's the best way to get that information from what I've got?</p>
<p>My only idea is to do a <code>SELECT TOP 0 * FROM @TableName</code> in a data adapter, get back a dataset, and iterate through the list of field names against the datacolumn's in the datatable.</p>
<p>Is there any better way to go about this?</p>
| <p>Try this</p>
<pre><code>select * from sys.columns where object_id = object_id('MyTable')
</code></pre>
<p>Hope this helps.</p>
|
C++ virtual function from constructor <p><strong>Why the following example prints "0" and what must change for it to print "1" as I expected ?</strong></p>
<pre><code>#include <iostream>
struct base {
virtual const int value() const {
return 0;
}
base() {
std::cout << value() << std::endl;
}
virtual ~base() {}
};
struct derived : public base {
virtual const int value() const {
return 1;
}
};
int main(void) {
derived example;
}
</code></pre>
| <p>Because <code>base</code> is constructed first and hasn't "matured" into a <code>derived</code> yet. It can't call methods on an object when it can't guarantee that the object is already properly initialized.</p>
|
Paging & Sorting grids with ASP.Net MVC <p>I'm new to MVC, and am not following how you'd do paging and sorting on a grid. I'm used to using the asp.Net GridView control with an ObjectDataSource pointed at objects in our business layer - and in that case the ODS handles all of the paging & sorting using the methods that our ORM generates on the objects.</p>
<p>I've looked at using the same ORM with MVC - and things work out fine there - i just loop thru the collections to build the table on the page - but without the ODS to handle the paging & sorting, i'm confused as to how I'd handle that. Would I have a separate controller for the paging and sorting? </p>
<p>I understand that I need to roll my own - but where do I start? I've created a CustomerController, and a view that displays a table of customers that looks like below - and I want to sort on FirstName or LastName columns. My Model has a Sort() method on it that'll take a string sort expression in the format that would be used by a GridView/ODS pair. Would I create a new Action on my CustomerController called Sort, and put an ActionLink in my header?</p>
<pre><code> <table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
<td>
<%= Html.Encode(item.LastName) %>
</td>
</tr>
<% } %>
</table>
</code></pre>
| <p>nowadays MVC 3 now has a webGrid out of the box. I know this question is from a while ago, but I ended up on it when looking for something about webGrid. So I thought it should have an answer mentioning the new webGrid.</p>
<p>Here are a few good posts on how to use it:</p>
<p><a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=615" rel="nofollow">http://www.dotnetcurry.com/ShowArticle.aspx?ID=615</a></p>
<p><a href="http://cnug.co.in/blogs/shijuv/archive/2010/10/08/using-the-webgrid-helper-in-asp-net-mvc-3-beta.aspx" rel="nofollow">http://cnug.co.in/blogs/shijuv/archive/2010/10/08/using-the-webgrid-helper-in-asp-net-mvc-3-beta.aspx</a></p>
<p><a href="http://www.nickharris.net/tag/webgrid/" rel="nofollow">http://www.nickharris.net/tag/webgrid/</a></p>
<p>It supports sorting, paging and also some Ajax stuff. It can do lot for you already, but you can also specify every separate column separately. </p>
<p><strong>Update:</strong><br>
There are also many JavaScript libraries available that can do the table for you. I personally like to use <a href="http://www.datatables.net/" rel="nofollow">DataTables</a>. You can feed it an existing html table generated on the server or give it an endpoint where it can retrieve the data (all or just one page).</p>
<p>There are plenty more, just Google around.</p>
|
Where to put using statements in a C# .cs file <p><strong>DUPE: <a href="http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace">http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace</a></strong></p>
<p>If I add a new class using Visual Studio to the project, It adds all the using statements before namespace but for the same project, FxCop says that put the name spaces inside namespace. Which is a better style of coding?</p>
| <p>See <a href="http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace">http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace</a></p>
|
is there an alternative to the Internet Developer Toolbar for IE7? <p>Does anyone know of an alternative to the <strong><a href="http://www.microsoft.com/downloads/details.aspx?familyid=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en" rel="nofollow">Internet Developer Toolbar</a></strong> for IE7 that I can use for dom browsing and css debugging? I've used Firebug in the past and the IDT seemed anemic in comparison. It also seemed to crash my browser a lot. </p>
<p>OR: Has the IDT for IE7 improved to the point that it's almost as good as Firebug? </p>
<p>Update: shortly after writing this I started using the Developer Toolbar. Well, that's a strong term. I <em>tried</em> to use it. It's not working at all. Specifically I needed Select Element By Click and it won't do a damn thing. All the menu options are grayed out even after restarting IE7. Good thing I asked this question, looks like the IDT is just as buggy as I remember. </p>
| <p><a href="http://www.debugbar.com/" rel="nofollow">Debug Bar</a> is pretty nice, and is free for personal use. You have to pay for it if using commercially though.</p>
<p><strong>Update:</strong> I should add that it did crash once or twice when there was some fairly advanced javascript. Didn't kill the entire browser but the toolbar was rendered useless until I restarted IE.</p>
|
Refresh NSTableView After Click - Not Refreshing <p>I have an app with a UITableView, using both icons and disclosure buttons. I want to update the icon on a row with a "selected" icon, and update the previously-selected row with an "unselected" icon. I have the code in place, but when I click on the rows, it sets both rows to the "selected" state, even though via debugging I can see that my state variable is being set to the correct row. If I keep clicking rows I can sometimes get the "unselected" state to show. I suspect it's a refresh issue, but I've tried the setNeedsDisplay method on the cells and the tableView itself, but with no luck. Anyone run into this before? BTW, this is in the simulator (2.2.1) - haven't tried it on the device.</p>
<p>Here's the code:</p>
<pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int newRow = [indexPath row];
int oldRow = [lastIndexPath row];
if (newRow != oldRow)
{
[[tableView cellForRowAtIndexPath:indexPath] setImage: [UIImage imageNamed:@"IsSelected.png"]];
c_oListPtr.c_sCurItem = [[tableView cellForRowAtIndexPath:indexPath] text];
[[tableView cellForRowAtIndexPath:lastIndexPath] setImage: [UIImage imageNamed:@"NotSelected.png"]];
[lastIndexPath release];
lastIndexPath = indexPath;
[[tableView cellForRowAtIndexPath:lastIndexPath] setNeedsDisplay];
[[tableView cellForRowAtIndexPath:indexPath] setNeedsDisplay];
[tableView setNeedsDisplay];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
</code></pre>
<p>Thanks
-Mike</p>
| <p>Have you tried <code>[tableView reloadData]</code>?</p>
|
Where to find novice SAP BAPI coding guides? <p>I've been working with applications interfacing with SAP via a web service for a little while now and I want to get into programming the BAPI's behind the web services as well. My company has been using a SAP consultant for the BAPI programming and I'd like to move into filling that role also.</p>
<p>I have a decent amount of experience with the core functionalities of SAP as an end user, so I'm not completely new there. But I've never done any BAPI programming before and I've had a hard time finding good beginner guides. I'd like to find something for experienced programmers that takes you from the SAP equivalent of "hello world" to writing business critical BAPIs.</p>
<p>I've heard that BAPI coding is similar to coding in SQL, is that true?</p>
<p>Also, I'd like to find a free online guide, but I realize that might be wishful thinking so any comprehensive books would also be helpful.</p>
| <p>I'm not sure about online resources, but there are a couple of quite good books to learn ABAP programming, you'd be looking for ABAP basics and/or ABAP objects (the latter one sounds better and more "advanced" but is typically just a more modern version of the language). One suggestion I've used in the past that is going quite a long way is <a href="http://rads.stackoverflow.com/amzn/click/0201750805" rel="nofollow" title="Horst Keller Book">this book</a>. As these are "Enterprise books", be prepared to spend a bit more money than for a paperback book.</p>
<p>Topics that should be covered:</p>
<ul>
<li>Data dictionary (SAPs term for definining tables, structures etc.)</li>
<li>Report programming</li>
<li>GUI programming (not really required)</li>
<li>functions (not sure about the English translation for "Funktionsbaustein", it is a function with parameters etc,. but defined in the data dictionary)</li>
<li>transactions</li>
</ul>
<p>This would be some basics you should know before advancing to understanding BAPIs .. </p>
<p>BAPIs are just SAP provided functions (coded in ABAP and extensible) that are more "stable" between releases (i.e. they do not change all that much) and that can be called from within a SAP system or from "the outside" (either another SAP system or a non-SAP program).</p>
<p>SAP provides a lot of BAPIs (you can add your own if you want) that allow programs to do a lot / more of the stuff that users can do through the SAPGUI. Even though SAP's preferences are changing "daily", it is the preferred way of programming the SAP system on a higher level than just ABAP, comparable to plain Java vs. programming with an elaborate class library.</p>
<p>A lot of ABAP programming is like working in a 4GL (that's why it used to be called ABAP/4), lots of handling data you are reading/writing to a database, but also outputting that data to a user and handling user input. I'd describe it as a weird mixture between COBOL and VB ,,, and certainly a good skill to have.</p>
|
ActionScript 2, list of nested movieclips <p>has anyone ever tried to get the list of all the movieclips (even the nested ones) that are on Stage at a specified stopped (and current) frame in Flash 8, AS 2?</p>
<p>I did the following:</p>
<pre><code>for(i in _root){
if(typeof(_root[i])=="movieclip"){
trace(_root[i]);}
}
</code></pre>
<p>But this is good for a first level search: that is, if inside the movieclips you have other movieclips, you can't reach them. Furthermore, inside a movieclip there can be more then one movieclip.</p>
<p>Has anyone ever tried to do what I'm trying to do?</p>
<p>Bye!</p>
| <p>exactly as suggested by inkedmn</p>
<p>printStuff first checks to see if the value it finds is a mc then if it is, traces and then checks inside it for more mcs.</p>
<pre><code>printStuff = function(object){
for(var x in object){
if(typeof(object[x])=="movieclip"){
trace(object[x]);
printStuff(object[x]);
}
}
}
printStuff(_root);
</code></pre>
<p>oh....and sorry for being a year and some change late...</p>
|
Should you request timeouts on locks in .NET? <p>In <a href="http://www.pragprog.com/titles/mnee">Release It!</a>, Michael Nygard reasons that many catastrophic system failures are often caused by a chain of things going wrong. For example, two threads deadlock. There's now two less threads in the thread pool, so load increases on the other threads increasing <em>their</em> likelihood of deadlocks. Suddenly, the server does not respond at all, because the thread pool is exhausted, which causes the load balancer to divert traffic to the other servers (who are all running the same code), which increases <em>their</em> likelihood of deadlocks. Suddenly the whole farm is offline. </p>
<p>Most RDBMS servers detect deadlocks and decide a "loser" (one transaction is aborted, the other can continue). By contrast, in C#, the <strong>lock</strong> statement will wait indefinitely for a lock to be acquired. </p>
<p>You can however call <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.tryenter.aspx">Monitor.TryEnter(lockObject, TimeSpan)</a> to request a lock or timeout. It returns false if the timeout expires and the lock could not be acquired. Some have <a href="http://www.interact-sw.co.uk/iangblog/2004/03/23/locking">wrapped this in using statements</a> to keep a nice syntax. </p>
<p>So my question is, do you always acquire locks using timeouts, or not? And what issues do timeouts create versus a deadlock scenario? </p>
| <p>I normally do use timeouts. The biggest issue here is that if the timeout is reached, the requesting operation is going to be aborted. This is obviously preferrable to deadlocking. There's a bigger problem there though: if the operation is critical and you start aborting because something else is deadlocked, if your design is not sound, you could end up causing the farm-going-down issue you described via this method (though softer: your app will no longer work, but you haven't lost control).</p>
<p>The main difference is that you actually have control here, whereas if threads start deadlocking, there's nothing you can do within your code to fix the problem once the failure has started.</p>
|
Inserting Dates into HTML Table Cells <p>I am wanting to have a series of dates (mainly Month, Day, Year) displayed within a vertical arrangement of table cells on a web page. The first date needs to be the current date minus one day, with the next date in the sequence be the current date, The remaining dates need to incrementally be one day in future out to 16 days. </p>
<p>Can someone provide help me figure out how to do this? I have looked at and understand a Javascript to manipulate and display a single date (add or subtract) but am unable to get that date in a cell as well as figure out how to display the other multiple dates mentioned above in a HTML table. </p>
| <p>Try this:</p>
<p>HTML</p>
<pre><code><table id="myTable"></table>
</code></pre>
<p>JavaScript</p>
<pre><code>var table = document.getElementById('myTable')
var myDate = new Date();
myDate.setDate(myDate.getDate() - 1)
for(var i = 0; i < 16; i++)
{
var row = document.createElement('TR');
var cell = document.createElement('TD');
cell.innerText = myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getYear();
myDate.setDate(myDate.getDate() + 1)
row.appendChild(cell);
table.tBodies[0].appendChild(row);
}
</code></pre>
|
How can I test if IIRF works? <p><a href="http://www.codeplex.com/IIRF/Thread/List.aspx" rel="nofollow">http://www.codeplex.com/IIRF/Thread/List.aspx</a></p>
<p>My webhost installed IIRF for me and I am convinced that they did not do it correctly. I've tried numerous examples including one that I know works with apache's mod_rewrite but I can't get anything to work with IIRF. Is there rule or configuration option that you guys have that you know of that will show whether or not the thing is working correctly?</p>
<p>Even something like rewrite all urls to anothersite.com will will help me right now. I hope you guys realize the reason I came for your help. I can figure out how to do the rewrite rules on my own but I don't know if the errors are because of me or the webhost. I have limited options as well since I am on a shared webhost.</p>
| <p>The new version of <a href="http://iirf.codeplex.com">IIRF</a>, v1.2.16 R3, includes a StatusUrl directive that will give you a status page if you do an HTTP GET on it. It looks like this:
<img src="http://i38.tinypic.com/23kaz3d.png" alt="IIRF Status page" /></p>
<p>If you get that page, then IIRF is running.</p>
|
Advice needed on REST URL to be given to 3rd parties to access my site <p><strong>Important: This question isn't actually really an ASP.NET question.</strong> Anyone who knows anything about URLS can answer it. I just happen to be using ASP.NET routing so included that detail.</p>
<p>In a nutshell my question is : </p>
<p>"What URL format should I design that i can give to external parties to get to a specific place on my site that will be future proof. [I'm new to creating these 'REST' URLs]."
<hr></p>
<p>I need an ASP.NET routing URL that will be given to a third party for tracking marketing campaigns. It is essentially a 'gateway' URL that redirects the user to a specific page on our site which may be the homepage, a special contest or a particular product.</p>
<p>In addition to <a href="http://stackoverflow.com/questions/257609/which-browsers-plugins-block-httpreferer-from-being-sent">trying to capture</a> the <a href="http://mail-archives.apache.org/mod_mbox/roller-dev/200511.mbox/<4377751C.8040507@busybuddha.org" rel="nofollow">referrer</a> I will need to receive a partnerId, a campaign number and possibly other parameters. I want to provide a route to do this BUT I want to get it right first time because obviously I cant easily change it once its being used externally.</p>
<p>How does something like this look?</p>
<pre><code>routes.MapRoute(
"3rd-party-campaign-route",
"campaign/{destination}/{partnerid}/{campaignid}/{custom}",
new
{
controller = "Campaign",
action = "Redirect",
custom = (string)null // optional so we need to set it null
}
);
</code></pre>
<p><strong>campaign</strong> : possibly don't want the word 'campaign' in the actual link -- since users will see it in the URL bar. i might change this to just something cryptic like 'c'.</p>
<p><strong>destination</strong> : dictates which page on our site the link will take the user to. For instance PR to direct the user to products page. </p>
<p><strong>partnerid</strong> : the ID for the company that we've assigned - such as SO for Stack overflow.</p>
<p><strong>campaignid</strong> : campaign id such as 123 - unique to each partner. I have realized that I think I'd prefer for the 3rd party company to be able to manage the campaign ids themselves rather than us providing a website to 'create a campaign'. I'm not
completely sure about this yet though. </p>
<p><strong>custom</strong> : custom data (optional). i can add further custom data parameters without breaking existing URLS</p>
<p>Note: the reason i have 'destination' is because the campaign ID is decided upon by the client so they need to also tell us where the destination of that campaign is. Alternatively they could 'register' a campaign with us. This may be a better solution to avoid people putting in random campaign IDs but I'm not overly concerned about that and i think this system gives more flexibility.</p>
<p>In addition we want to know perhaps which image they used to link to us (so we can track which banner works the best). I THINK this is a candiate for a new campaignid as opposed to a custom data field but i'm not sure.</p>
<p>Currently I am using a very primitive URL such as <a href="http://example.com?cid=123" rel="nofollow">http://example.com?cid=123</a>. In this case the campaign ID needs to be issued to the third party and it just isn't a very flexible system. I want to move immediately to a new system for new clients.</p>
<p>Any thoughts on future proofing this system? What may I have missed? I know i can always add new formats but I want to use this format as much as possible if that is a good idea.</p>
| <p>This URL:</p>
<pre><code>"campaign/{destination}/{partnerid}/{campaignid}/{custom}",
</code></pre>
<p>...doesn't look like a resource to me, it looks like a remote method call. There is a lot of business logic here which is likely to change in the future. Also, it's complicated. My gut instinct when designing URLs is that simpler is generally better. This goes double when you are handing the URL to an external partner.</p>
<p>Uniform <strong>Resource</strong> Locators are supposed to specify, well, resources. The destination is certainly a resource (but more on this in a moment), and I think you could consider the campaign a resource. The partner is not a resource you serve. Custom is certainly not a resource, as it's entirely undefined. </p>
<p>I hear what you're saying about not wanting to have to tell the partners to "create a campaign," but consider that you're likely to eventually have to go down this road anyway. As soon as the campaign has any properties other than the partner identifier, you pretty much have to do this.</p>
<p>So my first to conclusions are that you should probably get rid of the partner ID, and derive it from the campaign. Get rid of custom, too, and use query string parameters instead, should it be necessary. It is appropriate to use query string parameters to specify how to return a resource (as opposed to the identity of the resource).</p>
<p>Removing those yields:</p>
<pre><code>"campaign/{destination}/{campaignid}",
</code></pre>
<p>OK, that's simpler, but it still doesn't look right. What's destination doing in between campaign and campaign ID? One approach would be to rearrange things:</p>
<pre><code>"campaign/{campaignid}/{destination}",
</code></pre>
<p>Another would be to use Astoria-style indexing:</p>
<pre><code>"campaign({campaignid})/{destination}",
</code></pre>
<p>For some reason, this looks odd to a lot of people, but it's entirely legal. Feel free to use other legal characters to separate campaign from the ID; the point here is that a / is not the only choice, and may not be the appropriate choice.</p>
<p><strong>However...</strong></p>
<p>One question we haven't covered yet is what should happen if/when the user submits a valid destination, but an invalid campaign or partner ID. If the correct response is that the user should see an error, then all of the above is still valid. If, on the other hand, the correct response is that the user should be silently taken to the destination page anyway, then the campaign ID is really a query string parameter, not a part of the resource. Perhaps some partners wouldn't like being given a URL with a question mark in it, but from a purely REST point of view, I think that's the right approach, if the campaign ID's validity does not determine where the user ends up. In this case, the URL would be:</p>
<pre><code>"campaign/{destination}",
</code></pre>
<p>...and you would add a query string parameter with the campaign ID.</p>
<p>I realize that I haven't given you a definite answer to your question. The trouble is that most of this rests on business considerations which you are probably aware of, but I'm certainly not. So I'm more trying to cover the philosophy of a REST-ful URL, rather than attempting to explain your business to you. :)</p>
|
Gridlines in excel through interop <p>Any idea where the setting is hiding for turning gridlines off while using excel 2003 from interop? </p>
| <p>DisplayGridlines is a method on an Excel Window object.
For example:</p>
<pre><code>ActiveWindow.DisplayGridlines = true
</code></pre>
|
What is the most effective way to present and communicate a performance improvement (e.g. percentages, raw data, graphics)? <p>Is it better to describe improvements using percentages or just the differences in the numbers? For example if you improved the performance of a critical ETL SQL Query from 4000 msecs to 312 msecs how would you present it as an 'Accomplishment' on a performance review? </p>
| <p>In currency. Money is the most effective medium for communicating value, which is what you're trying to use the performance review to demonstrate.</p>
<p>Person hours saved, (very roughly) estimated value of $NEW_THING_THE_COMPANY_CAN_DO_AS_RESULT, future hardware upgrades averted, etc.</p>
<p>You get the nice bonus that you show that you're sensitive to the company's financial position; a geek who can align himself with what the company is really about.</p>
|
Data mapper pattern and automated updates of other objects <p>I'm building a PHP application using the data mapper pattern to separate my DB from the domain objects. I have a mapper class that returns Site objects based on data from the DB and accepts existing Site objects to be saved back to the DB.</p>
<p>My problem is that in the system one (and only one) of all the sites has to be marked as the "primary" site, which means that if I set one as the primary, I'd like to be able to automatically unset the current primary.</p>
<p>So, something like:</p>
<pre><code>$mapper = new Site_Mapper();
$site = $mapper->fetch(2);
$site->isPrimary = true;
$mapper->save($site);
</code></pre>
<p>Would somehow in the background automatically do this:</p>
<pre><code>$mapper = new Site_Mapper();
$site = $mapper->fetch(1);
$site->isPrimary = false;
$mapper->save($site);
</code></pre>
<p>Question is, where should the logic for automatically updating the existing primary site go? It has to happen after the object is saved back to the DB, not before, in case the DB query fails and you're left with no site as the primary.</p>
<p>Cheers,
Jack</p>
| <p>Sounds like a job for a database trigger.</p>
<pre><code>DELIMITER $$
CREATE TRIGGER test_trigger AFTER INSERT ON table
FOR EACH ROW BEGIN
IF NEW.isPrimary = 1 THEN
UPDATE table
SET isPrimary = 0
WHERE id <> NEW.id;
END IF;
END$$
DELIMITER ;
</code></pre>
|
Mathematical formula for calculating call duration <p>I was working for a telecom company some years ago and I had to generate a formula which calculates duration of a call according to the following algorithm:</p>
<ul>
<li>t1 is the first period </li>
<li>t2 is the recurring period</li>
<li>RCT is the actual call time (in seconds)</li>
<li>CD is the effective call duration (for billing purposes)</li>
</ul>
<p>if RCT is less than t1, then the CD equals t1<br />
if RCT is greater than t1, then CD = t1 + x*t2, where x will "round" RCT to the next highest multiple of t2.</p>
<p>This algorithm translates to: "Charge for the first t1 seconds, then charge every t2 seconds after that".</p>
<p>Example:</p>
<pre><code>t1 t2 RCT CD
60 10 48 60
60 10 65 70
60 10 121 130
30 20 25 30
30 20 35 50
30 20 65 70
</code></pre>
<p>Can you create a function / SQL that will return the "call duration" CD?</p>
<p>Without using if then else ...?</p>
| <p>Assuming int columns:</p>
<pre><code>SELECT t1
,t2
,RCT
CASE
WHEN RCT < t1
THEN t1
ELSE
t1 + t2 * ((RCT - t1) / t2 + SIGN((RCT - t1) % t2))
END AS CD
</code></pre>
<p>But I guess there is still one CASE, let me see if I can get rid of it.</p>
<p>With only integer arithmetic (still not ANSI):</p>
<pre><code>SELECT t1
,t2
,RCT
,CD
,t1 + SIGN(RCT / t1) * t2 * ((RCT - t1) / t2 + SIGN((RCT - t1) % t2)) AS CalcCD
FROM Calls
</code></pre>
|
Logging causing XML Parsing to break? <p>I'm seeing something very very strange happening in a Flex app I'm maintaining.</p>
<p>I've been going through it removing all calls to trace() and replacing it with calls into the logging framework (using the built in mx.logging stuff). After doing so some XML parsing code suddenly broke, and I can't for the life of me figure out why.</p>
<p>here's the code:</p>
<pre><code>private var loader:URLLoader; // created elsewhere
private function handleComplete(event:Event):void {
default xml namespace = com;
xml = XML(loader.data);
var response:XML = new XML(xml..raniResponse);
//now handles a null response object
if(xml && response.children().length() > 0) {
LOG.debug("Got response.");
var cityXML:XML = new XML(xml..city);
var stateXML:XML = new XML(xml..stateProv);
/* Some extra processing is done here */
}
}
</code></pre>
<p>With the code like this, with that LOG.debug() call in place, I get the following error on the line cityXML is defined:</p>
<pre><code>TypeError: Error #1088: The markup in the document following the root element must be well-formed.
</code></pre>
<p>If I comment out the LOG.debug() call it works fine.</p>
<p>I thought there might be some weirdness with the custom log target I created, so I removed that. Currently the only target being used is the built-in trace target.</p>
<p>Does anyone know what's going on? Why would a logging call break the XML parsing? I can't think of anything it could be doing that would break it.</p>
<p>EDIT:</p>
<p>I did some more tests, and it's just getting weirder.</p>
<p>I changed the code based on David's comment to use xml..city[0] instead of new XML(xml..city) for both assignments. This caused the exception to happen a bit later (in some code not shown above where it's referencing cityXML). So I tried stepping through in the debugger and noticed something odd.</p>
<p>cityXML was being set to null, while stateXML was getting the proper value. Looking at the xml object in the debugger showed all the correct data, so it should have been fine. As a random test I rearranged the code so that stateXML was being loaded first. After doing that, stateXML is null, while cityXML is correct.</p>
<p>So, whichever assignment happens immediately after the log is failing, but whatever happens after that worked fine.</p>
<p>Here's the (somewhat sanitized) XML that's being parsed:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<com:MyCompanyRANIv.01 xmlns:com="com:myc:rani:1:0:message" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<com:raniResponse>
<com:telephonyInfo>
<com:countryCode>1</com:countryCode>
<com:telephoneNumber>14121234567</com:telephoneNumber>
</com:telephonyInfo>
<com:geoInfo>
<com:coordinates>
<com:latLon>
<com:lat>40.49</com:lat>
<com:lon>-79.92</com:lon>
</com:latLon>
</com:coordinates>
<com:countryInfo>
<com:country>
<com:featureName>United States</com:featureName>
<com:featureTypeDescription>United States of America</com:featureTypeDescription>
<com:featureCode value="US" system="ISO 3166" family="Country Code" systemVer="1-alpha-2" />
</com:country>
</com:countryInfo>
<com:stateProvInfo>
<com:stateProv>
<com:featureName>PENNSYLVANIA</com:featureName>
<com:featureTypeDescription xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<com:featureCode family="US State Code" system="FIPS State Alpha Code" systemVer="" value="PA" />
</com:stateProv>
</com:stateProvInfo>
<com:regionInfo>
<com:region>
<com:featureName xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<com:featureTypeDescription xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<com:featureCode family="" system="" systemVer="" value="" />
</com:region>
</com:regionInfo>
<com:countyParishInfo>
<com:countyParish>
<com:featureName>ALLEGHENY</com:featureName>
<com:featureTypeDescription xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<com:featureCode family="" system="" systemVer="" value="" />
</com:countyParish>
</com:countyParishInfo>
<com:cityInfo>
<com:city>
<com:featureName>PITTSBURGH</com:featureName>
<com:featureTypeDescription xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<com:featureCode family="" system="" systemVer="" value="" />
</com:city>
</com:cityInfo>
<com:buildingInfo>
<com:building>
<com:featureName xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<com:featureTypeDescription xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
</com:building>
</com:buildingInfo>
<com:streetAddress address="" />
</com:geoInfo>
<com:services host="false" wireless="false" other="false" />
</com:raniResponse>
<com:raniRequest>
<com:fullyQualifiedTelephoneNumber>14121234567</com:fullyQualifiedTelephoneNumber>
</com:raniRequest>
</com:MyCompanyRANIv.01>
</soapenv:Body>
</soapenv:Envelope>
</code></pre>
| <p>That's a tough one. I never used the logging classes, so I'm unsure of that part of the question, but converting an XMLList to XML like you do:</p>
<pre><code>var cityXML:XML = new XML(xml..city);
</code></pre>
<p>works only if the XMLList contains a single item, otherwise you get the warning you quoted. Try the following form instead:</p>
<pre><code>var cityXML:XML = xml..city[0];
</code></pre>
<p>This works for empty lists as well as for lists with many items. You could also check the number of children with <code>xml..city.length()</code> and log a warning message if it is not 1. Perhaps this will help to figure out the exact problem.</p>
<p>How this is effected by adding or removing logging calls, though, beats me.</p>
<p>(On a somewhat related note, I noticed that declaring <em>and</em> assigning value to an XML variable within a <code>case</code> block of a switch statement does not work as expected, i.e. the assignment is simply ignored, and the variable will not be assigned a value. Breaking the line in two helps. This also seemed like a bug to me, so perhaps not everything is right with the compilation of XML-related code in AS3.)</p>
|
What's wrong with my javascript? Fading images <p>I'm trying to make Javascript change the style of certain DIV IDs by changing their background every few seconds. Basically, a fading header...here's my code, and it just doesn't change the background, at all.</p>
<p>How do you call a function?</p>
<p><a href="http://pixolia.net/sandbox/morph/index.php" rel="nofollow">http://pixolia.net/sandbox/morph/index.php</a></p>
| <p>Your javascript is in functions and isn't being called from anywhere. Try calling one of the functions from window.onload, or $(document).ready(function(){ }); if you're using jQuery</p>
|
Safely override C++ virtual functions <p>I have a base class with a virtual function and I want to override that function in a derived class. Is there some way to make the compiler check if the function I declared in the derived class actually overrides a function in the base class? I would like to add some macro or something that ensures that I didn't accidentally declare a new function, instead of overriding the old one.</p>
<p>Take this example:</p>
<pre><code>class parent {
public:
virtual void handle_event(int something) const {
// boring default code
}
};
class child : public parent {
public:
virtual void handle_event(int something) {
// new exciting code
}
};
int main() {
parent *p = new child();
p->handle_event(1);
}
</code></pre>
<p>Here <code>parent::handle_event()</code> is called instead of <code>child::handle_event()</code>, because the child's method misses the <code>const</code> declaration and therefore declares a new method. This could also be a typo in the function name or some minor difference in the parameters types. It can also easily happen if the interface of the base class changes and somewhere some derived class wasn't updated to reflect the change.</p>
<p>Is there some way to avoid this problem, can I somehow tell the compiler or some other tool to check this for me? Any helpful compiler flags (preferably for g++)? How do you avoid these problems?</p>
| <p>Since g++ 4.7 it does understand the new C++11 <code>override</code> keyword:</p>
<pre><code>class child : public parent {
public:
// force handle_event to override a existing function in parent
// error out if the function with the correct signature does not exist
virtual void handle_event(int something) override;
};
</code></pre>
|
What's a simple way to undelete a file in subversion? <p>These instructions are a little intimidating and confusing: <a href="http://svnbook.red-bean.com/en/1.0/ch04s04.html#svn-ch-4-sect-4.3">http://svnbook.red-bean.com/en/1.0/ch04s04.html#svn-ch-4-sect-4.3</a> .
And also they don't seem to mention that it's much simpler if you haven't yet checked in after doing the "<code>svn rm</code>" [1]. </p>
<p>So I thought this would be a good place to record a simpler answer for those googling for this.</p>
<p>[1] To an svn newbie, it might appear that "<code>svn rm</code>" immediately destroys the file. I recall doing <code>svn rm</code> thinking that would just remove it from source control and freaking out when the file itself actually disappeared. So a sub-question is, what's the right way to remove a file from version control without actually removing your local copy?</p>
| <p>If you just did</p>
<pre><code>svn rm foo.txt
</code></pre>
<p>then you can undo that with simply</p>
<pre><code>svn revert foo.txt
</code></pre>
<p>If you already checked in after doing the "<code>svn rm</code>" then you can look at the log (<code>svn log</code>), find the last revision where the file existed, and grab it from that version.</p>
<p>One way to do that is to merge in the old revision that has the file. Assuming the current revision is 123 and the last version with that file is 120, then do this:</p>
<pre><code>svn merge -r123:120
</code></pre>
<p>Maybe first do a dry run to make sure it won't do anything you don't want:</p>
<pre><code>svn --dry-run merge -r123:120
</code></pre>
<hr>
<p>For the sub-question, how to remove a file from svn without removing the local copy:</p>
<pre><code>svn rm foo.txt --keep-local
</code></pre>
<p>Or, of course, you could just copy to a temp file before svn rm'ing and then copy back:</p>
<pre><code>cp foo.txt foo.txt-tmp
svn rm foo.txt
(svn ci -m "just removed foo.txt from the repository")
cp foo.txt-tmp foo.txt
</code></pre>
|
How can I simulate key presses to any currently focused window? <p>I am trying to change the keys my keyboard sends to applications. I've already created a global hook and can prevent the keys I want, but I want to now send a new key in place. Here's my hook proc:</p>
<pre><code>LRESULT __declspec (dllexport) HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
int ret;
if(nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
kbStruct = (KBDLLHOOKSTRUCT*)lParam;
printf("\nCaught [%x]", kbStruct->vkCode);
if(kbStruct->vkCode == VK_OEM_MINUS)
{
printf(" - oem minus!");
keybd_event(VK_DOWN, 72, KEYEVENTF_KEYUP, NULL);
return -1;
}
else if(kbStruct->vkCode == VK_OEM_PLUS)
{
printf(" - oem plus!");
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
return -1;
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
</code></pre>
<p>I've tried using SendMessage and PostMessage with GetFocus() and GetForegroudWindow(), but can't figure out how to create the LPARAM for WM_KEYUP or WM_KEYDOWN. I also tried keybd_event(), which does simulate the keys (I know because this hook proc catches the simulated key presses), including 5 or 6 different scan codes, but nothing affects my foreground window.</p>
<p>I am basically trying to turn the zoom bar on my ms3200 into a scroll control, so I may even be sending the wrong keys (UP and DOWN). </p>
| <p>Calling keybd_event is correct. If all you're doing is a key up, maybe the window processes the key down message instead. You really need to send a key down followed by a key up:</p>
<pre><code>keybd_event(VK_UP, 75, 0, NULL);
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
</code></pre>
<p>Or, better yet, send the key down when the OEM key goes down and a key up when the OEM key goes up. You can tell the down/up state by kbStruct->flags & LLKHF_UP.</p>
|
Are you using Virtual Machine as your primary development enviroment? <p>Recently I have purchased a notebook that cames with Windows Home Basic (that don't have with ASP.Net/IIS. I thought in upgrade the Windows version to one with ASP.Net/IIS, but I thought in another possibility:</p>
<p>I have an Hard Disk Case with a 360Gb HD. I thought in create a virtual machine with Windows Ultimate (installing too ASP.Net, IIS and Visual Studio 2008) in this HD Case, then I can access my "development enviroment" in any computer that I will work on (my desktop machine and my notebook).</p>
<p>But I was worried about the performance. I don't have experience working in Virtual Machines (I use it just to quick compatibility tests)...</p>
<p>Are you using Virtual Machine as your primary development enviroment? What your finds?</p>
<p>====================<br>
<em>Thanks for your answers! It really did help me! I would like to know too about portability ie.: the virtual machine that I created in my laptop will work in the desktop? I will need re-activate Windows?</em></p>
| <p>I use VMWare and Microsoft VPC-based VMs quite a lot, hosted in a Quad 6600-based XP Pro box.</p>
<p>My use of VMs was initially to test in different environments, and for debugging I've had to install SQL Server and VS2008 in one or two of them.</p>
<p>For those purposes, VMs are very convenient.</p>
<p>But based on that experience, I wouldn't make a VM my primary dev environment, simply for performance reasons. VM performance is surprisingly good, but the difference (for pretty much everything), although not huge, is enough to notice.</p>
<p>When I'm compiling dozens of times a day, running big queries, etc, etc, I don't want my dev machine to be any slower than it absolutely has to be.</p>
|
What's the use of yield break? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/231893/what-does-yield-break-do-in-c">What does âyield break;â do in C#?</a> </p>
</blockquote>
<p>Can anyone see a use for the "yield break" statement that could not have been otherwise achieved by using "break" or "return".</p>
<p>This statement seems to be utterly useless. What's more, without this statement, the "yield return X" statement could have been simplified to "yield X", which much more readable.</p>
<p>What am I missing?</p>
| <p>To give a code example, say you want to write an iterator that returns nothing if the source is null or empty.</p>
<pre><code>public IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
{
if (source == null)
yield break;
foreach (T item in source)
yield return item;
}
</code></pre>
<p>Without the yield break it becomes impossible to return an empty set inside an iterator.</p>
|
How can I make Tomcat pre-compile JSPs on startup? <p>We're using both Apache Tomcat 6.0 and Jetty 6 where I work. We mostly use Jetty for testing (it's great for running embedded in JUnit tests) and Tomcat for production.</p>
<p>By default, Tomcat compiles JSPs on-the-fly as users request them. But this results in degraded performance for the first hit. It also highlights <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=43878">bizarre bugs</a> in Tomcat's JSP compiler.</p>
<p>The <a href="http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html">Tomcat documentation</a> gives recommendations for pre-compiling JSPs at build time using Ant (and a Maven plugin is also available)... but the resulting WAR contains Tomcat-specific stuff e.g. PageContextImpl.proprietaryEvaluate, so we can't use it in Jetty.</p>
<p>Is there some flag or setting we can use somewhere to force Tomcat to precompile all JSPs as soon as the WAR is initialized? We're prepared to wait a little longer on startup for this.</p>
<p>In advance: I know there's a way to pre-compile exactly <em>one</em> JSP by explicitly identifying a /servlet/load-on-startup tag in web.xml for one JSP. But for dozens or even hundreds of JSPs that becomes unmanageable.</p>
| <p><a href="http://www.devshed.com/c/a/BrainDump/Tomcat-Capacity-Planning/" rel="nofollow">http://www.devshed.com/c/a/BrainDump/Tomcat-Capacity-Planning/</a></p>
<p><hr /></p>
<pre><code> project name="pre-compile-jsps" default="compile-jsp-servlets">
<!-- Private properties. -- >
<property name="webapp.dir" value="${basedir}/webapp-dir"/>
<property name="tomcat.home" value="/opt/tomcat"/>
<property name="jspc.pkg.prefix" value="com.mycompany"/>
<property name="jspc.dir.prefix" value="com/mycompany"/>
<!-- Compilation properties. -->
<property name="debug" value="on"/>
<property name="debuglevel" value="lines,vars,source"/>
<property name="deprecation" value="on"/>
<property name="encoding" value="ISO-8859-1"/>
<property name="optimize" value="off"/>
<property name="build.compiler" value="modern"/>
<property name="source.version" value="1.5"/>
<!-- Initialize Paths. -->
<path id="jspc.classpath">
<fileset dir="${tomcat.home}/bin">
<include name="*.jar"/>
</fileset>
<fileset dir="${tomcat.home}/server/lib">
<include name="*.jar"/>
</fileset>
<fileset dir="${tomcat.home}/common/i18n">
<include name="*.jar"/>
</fileset>
<fileset dir="${tomcat.home}/common/lib">
<include name="*.jar"/>
</fileset>
<fileset dir="${webapp.dir}/WEB-INF">
<include name="lib/*.jar"/>
</fileset>
<pathelement location="${webapp.dir}/WEB-INF/classes"/>
<pathelement location="${ant.home}/lib/ant.jar"/>
<pathelement location="${java.home}/../lib/tools.jar"/>
</path>
<property name="jspc.classpath" refid="jspc.classpath"/>
<!--========================================================== -->
<!-- Generates Java source and a web.xml file from JSP files. -->
<!-- ==========================================================
-->
<target name="generate-jsp-java-src">
<mkdir dir="${webapp.dir}/WEB-INF/jspc-src/${jspc.dir.prefix}"/>
<taskdef classname="org.apache.jasper.JspC" name="jasper2">
<classpath>
<path refid="jspc.classpath"/>
</classpath>
</taskdef>
<touch file="${webapp.dir}/WEB-INF/jspc-web.xml"/>
<jasper2 uriroot="${webapp.dir}"
package="${jspc.pkg.prefix}"
webXmlFragment="${webapp.dir}/WEB-INF/jspc-web.xml"
outputDir="${webapp.dir}/WEB-INF/jspc-src/${jspc.dir.prefix}"
verbose="1"/>
</target>
<!-- ========================================================== -->
<!-- Compiles (generates Java class files from) the JSP servlet -->
<!-- source code that was generated by the JspC task. -->
<!-- ========================================================== -->
<target name="compile-jsp-servlets" depends="generate-jsp-java-src">
<mkdir dir="${webapp.dir}/WEB-INF/classes"/>
<javac srcdir="${webapp.dir}/WEB-INF/jspc-src"
destdir="${webapp.dir}/WEB-INF/classes"
includes="**/*.java"
debug="${debug}"
debuglevel="${debuglevel}"
deprecation="${deprecation}"
encoding="${encoding}"
optimize="${optimize}"
source="${source.version}">
<classpath>
<path refid="jspc.classpath"/>
</classpath>
</javac>
</target>
<!-- ========================================================= -->
<!-- Cleans any pre-compiled JSP source, classes, jspc-web.xml -->
<!-- ========================================================= -->
<target name="clean">
<delete dir="${webapp.dir}/WEB-INF/jspc-src"/>
<delete dir="${webapp.dir}/WEB-INF/classes/${jspc.dir.prefix}"/>
<delete file="${webapp.dir}/WEB-INF/jspc-web.xml"/>
</target>
</project
</code></pre>
<p>This build file will find all of your webappâs JSP files, compile them into servlet classes, and generate servlet mappings for those JSP servlet classes. The servlet map pings it generates must go into your webappâs WEB-INF/web.xml file, but it would be difficult to write an Ant build file that knows how to insert the servlet mappings into your web.xml file in a repeatable way every time the build file runs. Instead, we used an XML entity include so that the generated servlet mappings go into a new file every time the build file runs and that servlet mappings file can be inserted into your web.xml file via the XML entity include mechanism. To use it, your webappâs WEB- INF/web.xml must have a special entity declaration at the top of the file, plus a reference to the entity in the content of the web.xml file where you want the servlet mappings file to be included. Here is how an empty servlet 2.5 webappâs web.xml file looks with these modifications:</p>
<pre><code><!DOCTYPE jspc-webxml [
<!ENTITY jspc-webxml SYSTEM "jspc-web.xml">
]>
<web-app xmlns=http://java.sun.com/xml/ns/javaee
xmlns:xsi=http://www.w3.org/2001/ XMLSchema-instance
xsi:schemaLocation="http:// java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/
javaee/web-app_2_5.xsd"
version="2.5">
<!-- We include the JspC-generated mappings here. -->
&jspc-webxml;
<!-- Non-generated web.xml content goes here. -->
</web-app>
</code></pre>
<p>Make sure your webappâs web.xml file has the inline DTD (the DOCTYPE tag) all the way at the top of the file and the servlet 2.5 web-app schema declaration below that. Then, wherever you want to insert the generated servlet mappings in your web.xml file, put the entity reference &jspc-webxml; . Remember, the entity reference begins with an ampersand ( & ), then has the name of the entity, and ends with a semicolon ( ; ). </p>
<p>To use the build file, just edit it and set all of the properties at the top to values that match your setup, and then run it like this: </p>
<p>$ ant -f pre-compile-jsps.xml </p>
|
How to execute ANT tasks on only files that have been modified <p>I have a build script that does a number of things (minimize javascript, upload to amazon s3 etc). The minimize ANT task only operates on the javascript that I have modified and ignores the rest (I didn't write this script). I would like to do something similar for the amazon s3 task where only the updated content is upload in the task. Any leads on how to do this would be greatly appreciated. </p>
| <p>You can select a fileset with a modified date tag. The modified tag is insanely powerful, so check it out: <a href="http://ant.apache.org/manual/Types/selectors.html#modified">Ant Selectors - Modified</a>.</p>
<p>In order for it to tell what has changed, it can keep a cache in a property file, which updates after each successful build, unless you use the delayupdate attribute - so perhaps to test it, you can have:</p>
<pre><code><param name="commitUpdate" value="false" />
[...]
<ftp ...>
<fileset dir="src">
<modified delayupdate="${commitUpdate}" />
</fileset>
</ftp>
</code></pre>
<p>And of course you could set that commitUpdate via a command-line param or something.</p>
|
Learning Clojure without Java Knowledge <p>Ok, so I'm psyched about another list. I got myself a copy of the beta Clojure programming book...</p>
<p>And the one thing I'm noticing most is that it's assumed I know... like all the major java classes.</p>
<p>Except, generally, I don't really care about Java. I just want enough knowledge of it for Clojure to be an option for me.</p>
<p>Any suggestion as to how to learn just what I need of it all?</p>
| <p>Umm, actually, though Clojure was developed with Java developers considered, it was not written <em>for</em> Java programmers. </p>
<blockquote>
<p>Clojure is designed to interoperate well in the Java environment.</p>
</blockquote>
<p>Although it does, this is not <em>what</em> it was designed for (at least not in language part of the "Java environment"). And "Java environment" implies that the language and JVM are interconnected in some way that makes them one. They are not. Conjure is a native JVM language (unlike Jython or JRuby), and it uses a very well-built virtual machine to live within.</p>
<blockquote>
<p>Like Greg said though, Clojure is built to be with Java, and unless you want to really get into Clojure's software transactional memory system, I'd say to check out a different Lisp.</p>
</blockquote>
<p>Nope, sorry. Clojure was not "build to be with Java". It was built for the JVM. You can use Java libraries if you like, but it isn't required (though it is useful). And as far as the advice to use a different Lisp if you don't want to learn Java. That's ridiculous. Clojure isn't meant to be Java; it is meant to be a 1st-class Lisp. And one, by the way, that means to enhance Lisp in certain ways, to make it more modern and functional. It's ability to work well with Java should be considered a bonus, not a liability. </p>
<blockquote>
<p>As Greg above points out, languages like Clojure and Groovy target the JVM for one main reason, so that Java developers can have the best of both worlds.</p>
</blockquote>
<p>Also wrong. For reasons stated above. They were not written for Java developers. Sorry to be so blunt here, but I haven't seen one educated post on Clojure in these replies,and I just learned about Clojure today! It is just frustrating to see this kind of harmful advice so easily given. </p>
<p>I will just end with a quote by Rick Hickey (the guy who wrote Clojure):</p>
<p>"You can hate Java and like the JVM."</p>
<p>He goes on to say that that is where he stands.</p>
|
Fact check: how vulnerable are .NET apps to decompilation? <p>I came across <a href="http://msmobiles.com/news.php/7973.html" rel="nofollow">this post</a> on the MSMobiles.com blog that says the following, among other things:</p>
<blockquote>
<p>.Net is great in so many ways but for
commercial apps? No way! Anybody can
just look at your source code. A high
end obfuscator will help a lot but any
determined hacker will fix your code
in less than a day. I know this from
sad experience despite spending $1000s
on anti-piracy and obfuscation tools.</p>
</blockquote>
<p>It then says the following about developing commercial Windows Mobile apps in .NET:</p>
<blockquote>
<p>be prepared for 1-day delay after
which your competitors will copy your
functionality and place their own apps
with the same functionality in the
Skymarket</p>
</blockquote>
<p>For those familiar with .NET: is this truth or nonsense? Is this issue somehow specific to Windows Mobile, or does it apply to .NET on Windows as well? This just seemed surprising to me because I know that Microsoft writes a good amount of its own client-side software in .NET (and that many vendors write expensive apps in Java, which apparently has the same problems), and it seems strange that their IP could be stolen so easily.</p>
| <p>I would argue it is largely non-sense for the simple reason that if your competitive advantage and business success is dependent on some algorithm in your code then you are screwed already. Successful apps are about so much more than just the code, it is one of many pieces.</p>
<p>If this is something you really fear then I would invest in obfuscation and pre-pay for some legal counsel (pretty cheap believe it or not) who will send cease and desist letters on your behalf to a competitor who you believe stole your code. While this is going almost nowhere legally - the threat of action is just about your most effective tool.</p>
|
Converting a repository from git to subversion <p>Reasons for doing this aside, is there a reasonable way to <strong>convert an entire git repository to subversion</strong>?</p>
<p>I can find only tons on information on migrating <em>from</em> subversion <em>to</em> git, and exchanging changesets between the two, but not for doing a simple conversion of the entire git repository to svn. </p>
| <p>The general problem with doing conversions this direction is that Git repositories can contain more than just a linear history of revisions, as Subversion would expect. Multiple ancestries with divergent histories and frequent merge commits are all possible, which can't be easily represented in a Subversion repository.</p>
<p>For simple cases where you do have a linear history in your Git repository, you can use <code>git-svn dcommit</code> to push the lot up to an otherwise empty Subversion repository.</p>
|
How to best clean up resources for .NET application? <p>What are the best way or method of best practise to ensure that a Winforms .NET application releases all the resources it consumed in the lifecycle of its execution?</p>
<p>In particular, the release of file handles and images.</p>
<p>Thanks.</p>
| <p>If your implementation is whiteboxed then calling Close on file stream should close it's memory stream.</p>
<p>If class implements IDisposable just use the using block if in C# so the resource will be disposed:</p>
<pre><code>using (var foo = new Foo())
{
// Do some stuff to foo
}
</code></pre>
<p>If you are writing a wrapper that will consume memory intensively then I recommend implementing <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow">IDisposable</a>.</p>
|
Programmatically create shortcut keys combo for desktop "shortcut" <p>Is there a way through code, or through the creation of a setup project (via VS), to create a desktop shortcut <strong>with a keyboard shortcut pre-defined</strong>?</p>
<p><img src="http://img89.imageshack.us/img89/8066/shortcutce8.jpg" alt="alt text" /></p>
| <p>You can use the <a href="http://msdn.microsoft.com/en-us/library/bb774950(VS.85).aspx" rel="nofollow">IShellLink interface</a>, HotKey method to define a hotkey.</p>
|
Pass arguments into C program from command line <p>So I'm in Linux and I want to have a program accept arguments when you execute it from the command line.</p>
<p>For example, </p>
<p><code>./myprogram 42 -b -s</code></p>
<p>So then the program would store that number 42 as an int and execute certain parts of code depending on what arguments it gets like -b or -s.</p>
| <p>You could use <a href="http://www.gnu.org/software/libtool/manual/libc/Getopt.html">getopt</a>.</p>
<pre><code> #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int bflag = 0;
int sflag = 0;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "bs")) != -1)
switch (c)
{
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("bflag = %d, sflag = %d\n", bflag, sflag);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
</code></pre>
|
Need help in login validation using javascript <p>Please could somebody point me out what is the error here? Using javascript i am validating the user input. When i click the login button without checking the javascript function, it goes to the welcome page. Here is my code:</p>
<pre><code><script type="text/javascript">
function validLogin()
{
if(document.getElementById("txtUserName").value == "")
{
alert("Please enter your UserName");
return false;
}
if(document.getElementById("txtPassword").value == "")
{
alert("Please enter your Password");
return false;
}
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
BtnLogin.Attributes.Add("onClick","return ValidLogin();");
}
</code></pre>
| <p>I see that you're using ASP .NET (the Page_Load event on your posted code).</p>
<p>I think that will be easier to handle validation through <a href="http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp" rel="nofollow">ASP .NET Validation Controls</a>, i.e. <a href="http://www.w3schools.com/ASPNET/control_reqfieldvalidator.asp" rel="nofollow">RequiredFieldValidator</a>.</p>
|
An object reference is required for the nonstatic field, method, or property on a Windows form <pre><code>namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//int[] val ={ 0, 0 };
int val;
if (textBox1.Text == "")
{ MessageBox.Show("Input any no"); }
else
{
val = Convert.ToInt32(textBox1.Text);
Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
ot1.Start(val);
}
}
private static void ReadData(object state)
{
System.Windows.Forms.Application.Run();
}
void setTextboxText(int result)
{
if (this.InvokeRequired)
{ this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result }); }
else
{
SetTextboxTextSafe(result);
}
}
void SetTextboxTextSafe(int result)
{
label1.Text = result.ToString();
}
private static void SumData(object state)
{
int result;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
delegate void IntDelegate(int result);
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
</code></pre>
<p>Could anyone gave me the answer why this error is occuring
An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)</p>
| <p>It looks like you are calling a non static property from a static method. You will need to either make the property static, or create an instance of Form1.</p>
<pre><code>static void SetTextboxTextSafe(int result)
{
label1.Text = result.ToString();
}
</code></pre>
<p>OR</p>
<pre><code>private static void SumData(object state)
{
int result;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
</code></pre>
|
create service on windows <p>I am having trouble starting my service on my pc. My code is based on this article <a href="http://www.gamedev.net/reference/articles/article1899.asp" rel="nofollow">http://www.gamedev.net/reference/articles/article1899.asp</a></p>
<p>When i call installService from my int main(int argc, char *argv[]), it is registered successfully (i can see it in msconfig and services.msc). However it has not started. I manually start the service via services.msv and i get the error "Error 2: system cannot find the file specified". Why is this? i registered the services no more then a min ago, my external HD is still on (where this is currently stored. i'll move a nondev version to c:/ when its ready) What am i doing wrong and is there another tutorial i can look at (i only found the one linked via google)</p>
<pre><code>#define srvName "MyTestService_01312009"
void installService(char*path)
{
SC_HANDLE handle = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
SC_HANDLE service = ::CreateService(
handle,
srvName,
"MyTestService_01312009b",
GENERIC_READ | GENERIC_EXECUTE,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
path,
NULL,
NULL,
NULL,
NULL,
NULL
);
}
void uninstallService()
{
SC_HANDLE handle = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );//?
SC_HANDLE service = ::OpenService( handle, srvName, DELETE );
if( service != NULL )
{
// remove the service!
::DeleteService( service );
}
}
SERVICE_STATUS_HANDLE hStatus;
SERVICE_STATUS status;
/*
if( ::StartServiceCtrlDispatcher( dispatchTable ) == 0 )
{
// if this fails, it's probably because someone started us from
// the command line. Print a message telling them the "usage"
}
*/
void WINAPI ServiceCtrlHandler( DWORD control )
{
switch( control )
{
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
// do shutdown stuff here
status.dwCurrentState = SERVICE_STOPPED;
status.dwWin32ExitCode = 0;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
break;
case SERVICE_CONTROL_INTERROGATE:
// just set the current state to whatever it is...
break;
}
::SetServiceStatus( hStatus, &status );
}
void WINAPI ServiceDispatch( DWORD numArgs, char **args )
{
// we have to initialize the service-specific stuff
memset( &status, 0, sizeof(SERVICE_STATUS) );
status.dwServiceType = SERVICE_WIN32;
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
hStatus = ::RegisterServiceCtrlHandler( srvName, &ServiceCtrlHandler );
// more initialization stuff here
FILE *f = fopen("c:/testSrv.bin", "wb");
::SetServiceStatus( hStatus, &status );
}
SERVICE_TABLE_ENTRY dispatchTable[] =
{
{ srvName, &ServiceDispatch },
{ NULL, NULL }
};
</code></pre>
| <p>Maybe you can use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow">Process Monitor</a> to find out what's wrong. </p>
<p>Start it, and look for <code>NAME NOT FOUND</code> results that occur in connection with the service start.</p>
|
Web services and interface compatibility <p>Adding a service reference to a web service (this is all WCF) in Visual Studio produces some generated code including a client-side restatement of the interface being exposed.</p>
<p>I understand why this interface is generated: you might be consuming a 3rd party service and not have access to the actual interface.</p>
<p>But I do, and the two are <em>not</em> assignment compatible even though the transparent proxy does indeed exactly implement the interface to which I want to cast.</p>
<p>I can use reflection, but that's ugly. Is there some way to defeat this faux type safety and inject metadata to so I can use an interface with a class?</p>
<p><hr /></p>
<p>My specific problem departs from the norm in complicated ways that have to do with a single client that uses some derivatives of a base class directly and uses others remotely via service references. The base class for each server needs to keep references to subscribing clients in a collection for enumeration to notify events, and the problem was type varied due to the use of proxies. </p>
<p>None of these answers solves my specific problem, yet every single answer was instructive and helpful. I found my own solution (use a dual binding) but I would never have figured it out if you hadn't radically improved my understanding of the whole business.</p>
<p>Three excellent answers. How to choose just one? I choose the first, because it directly solves the problem I first <em>thought</em> I had.</p>
| <p>If you already have the contract dll at the client, you don't even need a service reference (unless you are using it to write the setup code for you) - you can simply subclass ClientBase and expose the Channel, and use that directly - something like (no IDE handy...):</p>
<pre><code>public class WcfClient<T> : ClientBase<T> where T : class
{
public new T Channel {get {return base.Channel;}}
}
</code></pre>
<p>Then you can just do things like:</p>
<pre><code>using(var client = new WcfClient<IFoo>())
{
client.Channel.Bar(); // defined by IFoo
}
</code></pre>
<p>You still need the configuration settings in the config to determine the address, binding, etc - but less messy than proxy generation. Also, you might choose to re-implement <code>IDipsoable</code> to deal with the fact that WCF proxies can throw in <code>Dispose()</code> (which is bad):</p>
<pre><code>public class WcfClient<T> : ClientBase<T>, IDisposable where T : class
{
public new T Channel {get {return base.Channel;}}
void IDisposable.Dispose() {
try {
switch(State) {
case CommunicationState.Open: Close(); break;
// etc
}
} catch {} // swallow it down (perhaps log it first)
}
}
</code></pre>
|
Open a new tab in firefox and keep ff in the background <p>Is the a way to programmatically open a URL in a new tab in firefox without firefox gaining focus?<br><br>
What I found out so far:<br></p>
<ul><li><code>firefox -new-window <URL></code> lets ff stay in the background, but opens a new window instead of a tab.
<li><code>firefox -new-tab <URL></code> opens <URL> in a new tab but gives focus to ff.
</ul>
<p>EDIT: What I'm trying to accomplish is making the feed reader plugin in claws mail open stuff in firefox in the background, so that I can go through my feeds and open everything that interests me and actually read all the stuff after that.
Oh and I should probably mention that a linux/gnome-only solution would be fine, too.</p>
| <p>If you set browser.tabs.loadDivertedInBackground to true in about:config then -new-tab will open tabs in the background and not focus the window. This does more than you (or I) want but perhaps it is a suitable work-around for you?</p>
|
iPhone Development - Keyboard does not automatically adjust when taking input using TextField placed in a TableView <p>I just downloaded 2.2.1 and i've seen that my input view does not adjust itself when an input field (NSTextField) is selected. Earlier the view was adjusting itself w.r.t keyboard.</p>
<p>I was using 2.1. How can i achieve the same effect?</p>
| <p>This was a bug, which has been fixed by Apple.</p>
|
Is Django a good choice for a security critical application? <p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| <p>Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.</p>
<p>Django, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used. </p>
<p>Django has a Profile model where you can keep additional authentication factors.</p>
<p>Django offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking.</p>
<p>Security is a number of first-class features in Django.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.