input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
java ee | ejb3 | runtime dispatch <p>I would like to call an ejb3 at runtime. The name of the ejb and the method name will only be available at runtime, so I cannot include any remote interfaces at compile time.</p>
<pre><code>String bean = 'some/Bean';
String meth = 'doStuff';
//lookup the bean
Object remoteInterface = (Object) new InitialContext().lookup(bean);
//search the method ..
// foreach (methods)
// if method == meth, method.invoke(bean);
</code></pre>
<p>the beans should be distributed accross multiple application servers, and all beans are to be called remotely.</p>
<p>Any hints? specifically i do <strong>not</strong> want:</p>
<ol>
<li>dependency injection</li>
<li>inclusion of appliation specific ejb interfaces in the dispatcher (above)</li>
<li>webservices, thats like throwing out processing power for nothing, all the xml crap</li>
</ol>
<p>Is it possible to load an ejb3 remote interface over the network (if yes, how?), so I could cache the interface in some hashmap or something.</p>
<p>I have a solution with a remote dispatcher bean, which I can include in the above main dispatcher, which does essentially the same, but just relays the call to a local ejb (which I can lookup how? naming lookup fails). Given the remote dispatcher bean, I can use dependency injection.</p>
<p>thanks for any help</p>
<p>(netbeans and glassfish btw)</p>
|
<p>ejb3 calls use RMI. RMI supports remote class loading, so i'd suggest looking into that.</p>
<p>also, JMX mbeans support fully untyped, remote invocations. so, if you could use mbeans instead of session beans, that could work. (JBoss, for instance, supports ejb3-like mbeans with some custom annotations).</p>
<p>lastly, many app servers support CORBA invocations, and CORBA supports untyped method invocations.</p>
|
Is there a guide to path referencing in PHP? <p>I know how to include files that are in folders further down the heirachy but I have trouble finding my way back up.
I decided to go with the set_include_path to default all further includes relative to a path 2 levels up but don't have the slightest clue how to write it out.</p>
<p>Is there a guide somewhere that details path referencing for PHP?</p>
|
<p>I tend to use <strong><a href="http://uk3.php.net/dirname" rel="nofollow">dirname</a></strong> to get the current path and then use this as a base to calculate all future path names.</p>
<p>For example,</p>
<pre><code>$base = dirname( __FILE__ ); # Path to directory containing this file
include( "{$base}/includes/Common.php" ); # Kick off some magic
</code></pre>
|
With wicket where does hibernate.cfg.xml file go? <p>I'm new to Wicket and Hibernate and can't get past the "org.hibernate.HibernateException: /hibernate.cfg.xml not found" error. I've put that file in every location imagineable but I'm still stuck. Where exactly does that file go and/or am I missing a wicket file config setting somewhere?</p>
|
<p>Ensure hibernate.cfg.xml file placed in classpath.</p>
|
Excel: 'Unable to set the Calculation property of the Application class' <p>I'm trying to automate some stuff in MS Excel. When I try to set the Calculation property I get the following error message: 'Unable to set the Calculation property of the Application class'</p>
<p>I believe this property should be settable.</p>
<p>Any advice appreciated!</p>
|
<p>Googling produces this suggestion:</p>
<p>You need to have a open workbook, ie</p>
<pre><code>xl.Workbooks.Add
xl.Calculation = xlCalculationManual
</code></pre>
|
Without creating a list, how can I query the integers between two values in Prolog? <p>For example, if I make a query like 'between(1,4,X)?' I would expect something like X=2,X=3. Is this possible?</p>
|
<pre><code> between(A,B,X):-X is A+1,X<B.
between(A,B,X):-A2 is A+1,A2<B-1,between(A2,B,X).
</code></pre>
|
ASP.NET v1.1 Could not load type TBRWEB.frmLogin <p>I have a web app that I wanted copy to a new project.</p>
<p>I created the new app with VS2003 and copied across the web forms, config, global asa, etc. and made sure IIS says it is a web app.</p>
<p>However, I still get this error when I run the app using IE from VS IDE:</p>
<pre><code>ASP.NET v1.1 Could not load type TBRWEB.frmLogin
</code></pre>
<p>I also made sure the assembly name and root namespace are the same as original.</p>
<p>Any ideas?</p>
|
<p>These error normally occurs if the .aspx page or the Global.asax page contains a reference to a code-behind module and if the application has not been built.</p>
<p>Look in your project settings and check the value of the <strong>default namespace</strong> (in the application section).</p>
<p>Then check the <strong>"inherits" attribute in the control header</strong> of your ascx control (and yll other aspx/ascx files). I suspect that these two names are not the same. Creating a new project maybe you choose a different name which became the default namespace. </p>
<p>The simplest solution would be to change the namespace of your project to TBRWEB, if that is an option.</p>
<p>if it is not that easy, then my follow-up questions are:</p>
<ul>
<li>Did you successfully build (compile) the application? </li>
<li>If it's a ASP.NET web site (not web project), did you forget to copy the .cs/.vb files in the App_Code folder?</li>
</ul>
|
How can I get Html.CheckBox() as boolean during POST in custom IModelBinder? <p>I am using <code>Html.CheckBox()</code>. The resulting HTML is:</p>
<pre><code><input id="IsMultiGraph" name="IsMultiGraph" value="true" type="checkbox">
<input name="IsMultiGraph" value="false" type="hidden">
</code></pre>
<p>On the server I have an Action which is accepting the form post information and using a custom IModelBinder to bind the form results to one of my models. Here is a snippet of the code I am running in the IModelBinder:</p>
<pre><code>bool isMultiGraph;
if (!bool.TryParse(bindingContext.HttpContext.Request["IsMultiGraph"], out isMultiGraph))
bindingContext.ModelState.AddModelError("IsMultiGraph", "Invalid boolean for \"IsMultiGraph\""); //this should not ever happen unless someone is programatically posting
result.IsMultiGraph = isMultiGraph;
</code></pre>
<p>The problem is that since <code>Html.CheckBox()</code> is rendering a checkbox as well as a hidden input field if I change the state of the textbox the postback value is doubled (ie. "true,false").</p>
<p>I understand why this is done and I'm looking for the best way to parse the current value of the CheckBox during a postback (checked = true, unchecked = false). Is there another helper method in MVC for this or should I just write my own?</p>
|
<p>One way is to use the <code>GetValues</code> method of the <code>NameValueCollection</code> class in order to get the first value of the array property like this:</p>
<pre><code>bindingContext.HttpContext.Request.Form.GetValues("IsMultiGraph")[0]
</code></pre>
|
Castle MonoRail & ELMAH <p>Is anyone using Castle MonoRail and ELMAH with success?</p>
<p>We are using a number of Resuces to present users with friendly error messages, but if we do this the exceptions never get as far as ELMAH as the MonoRail rescue intercepts them.</p>
<p>Ideally we want the user to see the rescue, but for the exception to be logged in ELMAH.</p>
<p>Any ideas/pointers?</p>
<p>Cheers,</p>
<p>Jay.</p>
|
<p>After looking at the links Macka posted, I wrote this simple monorail exception handler:</p>
<pre><code>public class ElmahExceptionHandler : AbstractExceptionHandler {
public override void Process(IRailsEngineContext context) {
ErrorSignal.FromCurrentContext().Raise(context.LastException);
}
}
</code></pre>
<p>Then I registered it in web.config, monorail section:</p>
<pre><code><monorail>
<extensions>
<extension type="Castle.MonoRail.Framework.Extensions.ExceptionChaining.ExceptionChainingExtension, Castle.MonoRail.Framework"/>
</extensions>
<exception>
<exceptionHandler type="MyNamespace.ElmahExceptionHandler, MyAssembly"/>
</exception>
...
</monorail>
</code></pre>
<p>And that's it.</p>
|
How do I get rid of TagExtraInfo JSTL warning in Eclipse? <p>I'm working with JSTL in Eclipse, using the WTP. I have jstl and standard.jar in my WEB-INF/lib directory, and everything works. Eclipse is giving me this warning in my JSP:</p>
<p>The TagExtraInfo class for c:forEach (org.apache.taglibs.standard.tei.ForEachTEI) was not found on the build path.</p>
<p>I have JSTL included:</p>
<pre><code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
</code></pre>
<p>The warning is on a line that uses a c:forEach. How can I get rid of it?
My project is targeting Tomcat v6.</p>
|
<p>Add the standard.jar from the web-inf directory to your build path jars.</p>
|
ASP.NET MVC on IIS 6 - wildcard mapping - the incoming request does not match any route <p>I have been trying to set up my Beta 1 MVC app on IIS 6 and cannot get it to run correctly. I have added a Wildcard mapping to the .net isapi DLL as suggested in other blog posts but get the following error when I access the root of the website:</p>
<pre><code>The incoming request does not match any route.
..
[HttpException (0x80004005): The incoming request does not match any route.]
System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +147
System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +36
System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +4
HCD.Intranet.Web.Default.Page_Load(Object sender, EventArgs e) +81
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
</code></pre>
<p>I am using the Default.aspx page supplied in the MVC template application that rewrites access to the root of the website properly.</p>
<pre><code>public partial class Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
HttpContext.Current.RewritePath(Request.ApplicationPath);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
}
</code></pre>
<p>If I try and access a route within the application, such as /Project, I get the standard IIS 404 error page, not the .net error page.</p>
<p>I tried adding the following line to my Web.config httpHandlers section:</p>
<pre><code><add verb="*" path="*" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</code></pre>
<p>This gave me a different error - the .net 404 error page.</p>
<p>I added the following to my Global.asax, which did nothing:</p>
<pre><code>protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Context.Request.FilePath.Equals("/"))
Context.RewritePath("Default.aspx");
}
</code></pre>
<p>I am using the following route configuration (uses the restful routing supplied by the MvcContrib project):</p>
<pre><code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
SimplyRestfulRouteHandler.BuildRoutes(routes);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
</code></pre>
<p>Any suggestions would be grealy received as I've exhausted all options for the time I have right now.</p>
<p>Many thanks.</p>
|
<p>Here's what I did to get extensionless URLs working with IIS 6 and ASP.NET MVC Beta 1.</p>
<ul>
<li>Create a default ASP.NET MVC Beta
project and compile it.</li>
<li>Create a new IIS website pointing to
the application directory.</li>
<li>In the IIS properties for the
website, click the HomeDirectory
tab.</li>
<li>Click the "Configuration..." button.
In the "Mappings" tab, click
"Insert..."</li>
<li>Next to the "Wildcard application
maps" label In the textbox, type in
"c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll"</li>
<li>Uncheck the box labelled "Verify
that file exists" Click OK</li>
<li>Navigate to /home It worked!</li>
</ul>
<p>You shouldn't need to change web.config at all. You just need to map all requests to IIS to the ASP.NET Isapi dll otherwise ASP.NET will never get those requests.</p>
|
import mechanize module to python script <p>I tried to import mechanize module to my python script like this,</p>
<p>from mechanize import Browser</p>
<p>But, Google appengine throws HTTP 500 when accessing my script.</p>
<p>To make things more clear, Let me give you the snapshot of my package structure,</p>
<pre><code>root
....mechanize(where all the mechanize related files there)
....main.py
....app.yaml
....image
....script
</code></pre>
<p>Can anyone help me out to resolve this issue?</p>
<p>Thanks,
Ponmalar</p>
|
<p>The mechanize main page says:</p>
<blockquote>
<p>mechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in turn, a subclass of urllib2.OpenerDirector</p>
</blockquote>
<p>My understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible.</p>
|
mvc framework for winforms .net <p>Please suggest a good MVC framework for Winforms.</p>
|
<p><a href="http://www.codeplex.com/CompositeWPF" rel="nofollow">http://www.codeplex.com/CompositeWPF</a> (MVC application block for WPF/Silverlight)</p>
<p><a href="http://blogs.msdn.com/priozersk/archive/2008/11/04/mobile-mvc-framework-part-4-passing-data-between-controllers.aspx" rel="nofollow">http://blogs.msdn.com/priozersk/archive/2008/11/04/mobile-mvc-framework-part-4-passing-data-between-controllers.aspx</a> (MVC framework for .NET Compact Framework)</p>
<p>Regards,
tamberg</p>
|
std::wcout to console window in XCode <p>In an XCode project, if I use <code>std::cout</code> to write to the console the output is fine.</p>
<p>However, if I use <code>std::wcout</code> I get no output.</p>
<p>I know that this is a thorny issue in C++, and I've been googling around to try and find a specific solution in the XCode case. A couple of things I found that it was suggested should work were:</p>
<pre><code>
std::cout.imbue( std::locale("") );
</code></pre>
<p>and</p>
<pre><code>
std::setlocale(LC_ALL, "");
</code></pre>
<p>Neither of these have made any difference. Before I resign myself to spending the next couple of weeks studying the facets API just to be able to write to the console I thought I'd check with the esteemed audidence here.</p>
<p>[Update]</p>
<p>I think the reason for the problem I've been having is actually to do with the specific encoding of some of the strings I'm trying to print.</p>
<p>If I send just a string literal, using the <code>L"my string" syntax</code> it works! It appears this is using UTF32 - little endian encoding.</p>
<p>However, I've been mixing this with strings I've been passed from Objective C++ code using NSUTF32BigEndianStringEncoding encoding. It's this mix of encodings that's causing the problems.</p>
<p>I think we can consider this matter closed. Thanks for reading.</p>
|
<p>std::wcout should work just like std::cout.</p>
<p>The following works fine on my MAC:</p>
<pre><code>#include <iostream>
int main()
{
std::cout << "HI" << std::endl;
std::wcout << L"PLOP" << std::endl;
}
</code></pre>
<p>Maybe (though some code would have been nice) its because you are not flushing the buffer. Remember that std::cout and std::wcout are buffered. This means the output will not be pushed to the console until the buffer is filled or you explicitly flush the buffer.</p>
<p>You can flush the buffer with:</p>
<pre><code>std::wcout << flush();
// or
std::wcout << endl; // Those also puts a '\n' on the stream.
</code></pre>
|
_configthreadlocale and localeconv <p>As we all know, global data, like the locale settings affecting the numeric decimal point printf() and strtod() are using, is evil. Fortunately, MSVC++ 9 allows to use per-thread locales by a <code>_configthreadlocale(_ENABLE_PER_THREAD_LOCALE)</code> call. Unfortunately, it seems that the localeconv() function does not notice this and still returns the global locale settings, e.g. localeconv()->decimal_point seems to always return the global locale setting before the _configthreadlocale() call. Is this a bug in the MSVC library or is this expected?</p>
<p>TIA
Paavo</p>
|
<p>Despite the suggestion that this is expected behaviour from rubenvb, this is actually a bug that I ran into a while ago. I suspect rubenvb misread this part of the question:</p>
<blockquote>
<p>Unfortunately, it seems that the localeconv() function does not notice this and still returns the global locale settings, e.g. localeconv()->decimal_point seems to always return the global locale setting before the _configthreadlocale() call.</p>
</blockquote>
<p>The question wasn't intending on having localeconv() return on a per-thread basis before calling _configthreadlocale() as that would break the time continuum. The question was suggesting that the results of calling localeconv() after calling _configthreadlocale() are the same as calling it beforehand, which is unexpected. This essentially means Microsofts implementation of the C++ STL streams are fundamentally broken when using _configthreadlocale().</p>
|
How do you connect/retrieve data from a MYSQL database using objects in PHP? <p>Generally I connect and retrieve data using the standard way (error checking removed for simplicity):</p>
<pre><code>$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");
while($item = mysql_fetch_array($items)) {
my_function($item[rowname]);
}
</code></pre>
<p>Where my_function does some useful things witht that particular row.</p>
<p>What is the equivalent code using objects?</p>
|
<p>Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.</p>
<pre><code>$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
//each :keyword represents a parameter or value to be bound later
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');
# Variables are set here.
$query->bindParam(':id', $id); // this is a pass by reference
$query->bindValue(':pass', $pass); // this is a pass by value
$query->execute(); // query is run
// to get all the data at once
$res = $query->fetchall();
print_r($res);
</code></pre>
<p>see <a href="http://ca3.php.net/manual/en/book.pdo.php" rel="nofollow">PDO driver at php.net</a></p>
<p>Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.</p>
<p>There is also the <a href="http://ca3.php.net/manual/en/book.mysqli.php" rel="nofollow">mysqli</a> extension to do a similar task, but I personally find PDO to be cleaner.</p>
<p>What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.</p>
<p>You can then use <a href="http://ca3.php.net/manual/en/pdostatement.fetchobject.php" rel="nofollow">$query->fetchobject</a> to retrieve your data as an object.</p>
|
Server monitoring and alerting software? <p>What software does everyone use to monitor hardware? I know about nagios and cacti, but does anyone use any other software?</p>
|
<p><a href="http://www.solarwinds.com/products/ipmonitor/" rel="nofollow">SolarWinds IPMonitor</a> is pretty useful. A bit like cacti or nagios, but more pleasing to the eye. Windows only, and not free (not even as in "free beer"), though. ;-)</p>
|
Is there an OpenID 2.0 plugin for Symfony? <p>I am using sfOpenID plugin for Symfony, which doesn't support OpenID 2.0. That means, for example, that people using Yahoo! OpenID can't login to my site.</p>
<p>There is an OpenID 2.0 plugin that works with sfGuard, but I am not using nor planning to use sfGuard. Plus, it requires to install Zend framework, too, which is an overkill in my scenario.</p>
<p>So I've got two questions, really:</p>
<ul>
<li>is there another OpenID plugin for Symfony supporting OpenID 2.0?</li>
<li>what would be the hack required to make sfOpenID support OpenID 2.0?</li>
</ul>
<p>I suppose I could study OpenID specs and hack it myself, but then, I am a lazy programmer :)</p>
|
<p>I think you've covered all your options with sfOpenID and taOpenIDsfGuardPlugin for Symfony's plugins.</p>
<p>Without studying OpenID's specs in detail though, you could try one of those PHP libraries (<a href="http://wiki.openid.net/Libraries">http://wiki.openid.net/Libraries</a>) by dropping it in your lib and connecting to a <code>sfUser</code>, or whatever you're using for authentication. There is also the OpenID Enabled library (<a href="http://openidenabled.com/php-openid/">http://openidenabled.com/php-openid/</a>) which still uses PHP4 although compatible with PHP5 if you <a href="http://www.php.net/manual/en/errorfunc.configuration.php">tweak the error reporting level</a> to exclude some warnings.</p>
<p>There are a few tutorials out there that explains how to enable OpenID on your site with PHP: <a href="http://www.saeven.net/openid.htm">http://www.saeven.net/openid.htm</a> or <a href="http://www.plaxo.com/api/openid_recipe">http://www.plaxo.com/api/openid_recipe</a>. </p>
<p>And better yet, use this knowledge to <a href="http://www.symfony-project.org/book/1_1/17-Extending-Symfony#How%20to%20Write%20a%20Plug-In">make a sfPlugin out of it</a> afterwards.</p>
|
Is there a way to measure parse time in PHP? <p>Optimization of PHP code via runtime benchmarking is straight forward. Keep track of $start and $end times via microtime() around a code block - I am not looking for an answer that involves microtime() usage.</p>
<p>What I would like to do is measure the time it takes PHP to get prepared to run it's code - code-parse/op-code-tree-building time. My reasoning is that while it's easy to just include() every class that you <strong>might</strong> need for every page that you have on a site, the CPU overhead can't be "free". I'd like to know how "expensive" parse time really is.</p>
<p>I am assuming that an opcode cache such as APC is <strong>not</strong> part of the scenario.</p>
<p>Would I be correct that measurement of parse time in PHP is something that would have to take place in mod_php?</p>
<p><strong>EDIT</strong>: If possible, taking into account <code>$_SERVER['DOCUMENT_ROOT']</code> usage in code would be helpful. Command solutions might take a bit of tinkering to do this (but still be valuable answers).</p>
|
<p>Yes. There is.</p>
<pre><code><?php return; rest of the code ?>
</code></pre>
<p>or</p>
<pre><code><?php whole code; $%^parse erorr!@! ?>
</code></pre>
<p>and then compare time of running empty script</p>
<pre><code>time php empty.php
</code></pre>
<p>with time it takes to run (or fail) regular script with the additions I've mentioned above:</p>
<pre><code>time php test.php
</code></pre>
<p>I've used this method on large files and PHP5.3 on Core2Duo 2.4Ghz can parse between 1.5 and 4.5MB of PHP code per second (it depends very much on complexity of the code of course).</p>
|
Multi file upload with PHP/Javascript and no flash <p>I'm trying to make a webpage that allows the uploading of multiple files at the same times. I will limit the file extensions to the most common images like JPG, JPEG, PNG and GIF.</p>
<p>I've done some research on this and everywhere I look it's flash this and flash that.</p>
<p>I don't want to use flash really. Especially with Flash 10, which disables the most common used method to enable multifile upload.</p>
<p>What I'm looking for is a way to keep creating more and more input fields, each with a browse button and then with one final upload button at the bottom of the form. Creating the new input fields with a Javascript is nog big deal really.</p>
<p>So I'm wondering how this works. Do I need to give all file-input fields the same name atribute so I can use 1 piece of PHP code to solve this? Or Is there some way for PHP to detect howmany files have been sumbitted and simply put the code for parsing a file inside a for-loop?</p>
|
<p>You can keep adding 'file' inputs but use a name of something like 'upload[]'</p>
<pre><code><input type="file" name="upload[]">
</code></pre>
<p>Then in $_FILES['upload'] you will have an array of files you can loop over like </p>
<pre><code>foreach ($_FILES['upload'] as $file) {
echo $file['size'];
}
</code></pre>
|
How can I place a MFC CFormView inside a CDockablePane? <p>How can I place a MFC CFormView inside a CDockablePane which was introduced in the VS 2008 MFC Feature Pack?</p>
|
<p>Check the <a href="http://www.bcgsoft.com/samples/docview.htm" rel="nofollow">BCGSoft</a> Samples for doing this with a cview. The class names are a little different but its more or less the same stuff since they provided CDockablePane to Microsoft.</p>
|
iPhone UIwebview with embedded quicktime video? <p>When I load a HTML page with a .MOV embedded video on my App using a UIWebview it appears a broken icon, any idea? The same HTML page on Iphone Safari works fine and the media player is started without problem...</p>
|
<p>Where is the webpage? Is it embedded in your app? If you not giving the UIWebView a URL to load it from the server where it is make sure you set the baseURL properly so that the webview knows how to handle handle relative URLs.</p>
|
Preventing Duplicate Inserts Into SQL With PHP <p>I'm going to running thousands of queries into SQL and I need to prevent the duplication of field 'domain'. Never had to do this before and any help would be appreciated.</p>
|
<p>You probably want to create a "UNIQUE" constraint on the field "Domain" - this constraint will raise an error if you create two rows that have the same domain in the database. For an explanation, see <a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow">this tutorial in W3C school</a> -</p>
<p><a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow">http://www.w3schools.com/sql/sql_unique.asp</a></p>
<p>If this doesn't solve your problem, please clarify the database you have chosen to use (MySql?).</p>
<p>NOTE: This constraint is completely separate from your choice of PHP as a programming language, it is a SQL database definition thing. A huge advantage of expressing this constraint in SQL is that you can trust the database to preserve the constraint even when people import / export data from the database, your application is buggy or another application shares the database.</p>
|
Level of database rebuilding in a daily build routine <p>I am in the process of designing a daily build routine for my project. We are using Flex 3 and SQL Server 2005. I am unsure to what degree I should be rebuilding the database on a daily build. Should I be dropping all tables and stored procedures and adding them back in? Then I would have to have a script that put all the default data back into the tables.</p>
<p>Or should I have the DBA write Alter scripts that only run when changes are made and concentrate on building the code on a daily basis?</p>
|
<p>This really depends on your current stage of project development. </p>
<p>While in active development without any production deployments the simple thing to do is just drop and re-create your database every time. This way your code and database should be in sync, especially if you are doing unit testing. This is basically doing a trunk build i.e. latest and greatest. It is much simpler to maintain. Scripting your default data is easy and a great way to have a clean setup when you need one. Check out the <a href="http://vyaskn.tripod.com/code.htm" rel="nofollow"><code>sp_ generate_inserts</code></a> stored procedure for a nice utility to script the data from an existing database.</p>
<p>Once you have production databases and will be altering you database with code releases, it's important to test change scripts also. Change scripts tend to be a bit tougher to write due to dependencies and data manipulation considerations.</p>
|
How to develop *real life* oop skills? <p>I've been studying OOP for quite a while now and I have a good grasp of the theory. I read the <a href="http://rads.stackoverflow.com/amzn/click/0596008678">Head First</a> book on OOP and, while it reinforced a lot of the theory, I found the case studies to be somewhat trivial.</p>
<p>I find that I'm applying OOP principles to my code each day, but I'm not sure if I'm applying them correctly. I need to get to the point where I am able to look at my code and know whether I'm using inheritance appropriately, whether my object is cohesive enough, etc.</p>
<p>Does anyone have any good recommendations (books, online guides, blogs, walk-throughs, etc.) for taking the next step in developing solid OOP skills?</p>
<p>I am working primarily in .NET (visual basic), but I welcome suggestions that incorporate various platforms.</p>
|
<p>Read <a href="http://rads.stackoverflow.com/amzn/click/0201485672">Refactoring</a> by Martin Fowler, and apply it to your own work.</p>
<p>It will take you through a litany of malodorous characteristics of software code that describe how to detect improperly constructed classes, and even more importantly, how to fix them.</p>
|
How can I override the OnBeforeUnload dialog and replace it with my own? <p>I need to warn users about unsaved changes before they leave a page (a pretty common problem). </p>
<pre><code>window.onbeforeunload=handler
</code></pre>
<p>This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.</p>
<p>So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?</p>
<p>Javascript in my page:</p>
<pre><code><script type="text/javascript">
window.onbeforeunload=closeIt;
</script>
</code></pre>
<p>The closeIt() function:</p>
<pre><code>function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
</code></pre>
<p>Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):</p>
<pre><code>$(window).beforeunload(function() {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
</code></pre>
<p>which also doesn't work - I cannot seem to bind to the beforeunload event. </p>
|
<p>You can't modify the default dialogue for <code>onbeforeunload</code>, so your best bet may be to work with it.</p>
<pre><code>window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx">Here's a reference</a> to this from Microsoft:</p>
<blockquote>
<p>When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.</p>
</blockquote>
<p>The problem seems to be:</p>
<ol>
<li>When <code>onbeforeunload</code> is called, it will take the return value of the handler as <code>window.event.returnValue</code>.</li>
<li>It will then parse the return value as a string (unless it is null).</li>
<li>Since <code>false</code> is parsed as a string, the dialogue box will fire, which will then pass an appropriate <code>true</code>/<code>false</code>.</li>
</ol>
<p>The result is, there doesn't seem to be a way of assigning <code>false</code> to <code>onbeforeunload</code> to prevent it from the default dialogue.</p>
<p>Additional notes on jQuery:</p>
<ul>
<li>Setting the event in jQuery <strong>may</strong> be problematic, as that allows other <code>onbeforeunload</code> events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.</li>
<li><p>jQuery doesn't have a shortcut for <code>onbeforeunload</code> so you'd have to use the generic <code>bind</code> syntax.</p>
<pre><code>$(window).bind('beforeunload', function() {} );
</code></pre></li>
</ul>
|
Is it possible to get a list of added or deleted files from Subversion? <p>I want to retrieve a list of the files that has been added or deleted from our Subversion repository over, for example, the last month.</p>
<p>I'd prefer to have the file names, and not just a count.</p>
<p>Is this possible from the Subversion command line, or would I need to use a script to trawl the log?</p>
|
<p>I don't think you can do it with just the command-line tools, but outputting it with an XML format and doing some grepping or filtering would probably give you what you want.</p>
<p>Try this for a start:</p>
<pre><code>svn log -v --xml | grep 'action="[A|D]"'
</code></pre>
|
Making an Image Greyscale with GD Library <p>My mission is to create a little app where you can upload a picture, and the app will turn it into ASCII art. I'm sure these exist already but I want to prove that I can do it myself.</p>
<p>This would involve taking an image, making it greyscale and then matching each pixel with a character depending on how dark the picture is and how full the character is.</p>
<p>So my question is, Using the GD Library (or i guess some other means if necessary) how do I make an image black and white?</p>
|
<p>As pointed out by <a href="http://stackoverflow.com/users/9021/nickf">nickf</a> in his <a href="http://stackoverflow.com/questions/276780/making-an-image-greyscale-with-gd-library#276811">comment</a>, the simple formula <code>(pixel.r + pixel.g + pixel.b) / 3</code> is not correct. Use the GD-included function <code>imagefilter()</code> (no need to iterate over all pixels in an image using PHP loops) instead:</p>
<pre><code>$im = imagecreatefrompng('dave.png');
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagepng($im, 'dave.png');
</code></pre>
|
How would I express this Scheme function more clearly? <pre><code>(define (repeated f n)
if (= n 0)
f
((compose repeated f) (lambda (x) (- n 1))))
</code></pre>
<p>I wrote this function, but how would I express this more clearly, using simple recursion with repeated?</p>
<p>I'm sorry, I forgot to define my compose function.</p>
<pre><code>(define (compose f g) (lambda (x) (f (g x))))
</code></pre>
<p>And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.</p>
|
<p>I'm assuming that (repeated f 3) should return a function g(x)=f(f(f(x))). If that's not what you want, please clarify. Anyways, that definition of repeated can be written as follows:</p>
<pre><code>(define (repeated f n)
(lambda (x)
(if (= n 0)
x
((repeated f (- n 1)) (f x)))))
(define (square x)
(* x x))
(define y (repeated square 3))
(y 2) ; returns 256, which is (square (square (square 2)))
</code></pre>
|
ASP.NET MVC and Ajax <p>From what I've read about ASP.NET MVC, it appears it requires posting to work, is there any working example (With source available) of a ASP.NET MVC website that has no postbacks with the help of Ajax?</p>
<p>(I checked the related questions earlier but couldn't find what I was looking for)</p>
<p>Thanks in advance.</p>
<p>edit: I need jQuery solutions not Atlas Toolkit stuff!</p>
|
<p>This is from Preview 4...</p>
<p><a href="http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx" rel="nofollow">http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx</a></p>
<p>With jquery</p>
<p><a href="http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx" rel="nofollow">http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx</a></p>
|
Detect another host with the same MAC address <p>How can I detect if another host is using the same MAC address as the current host, e.g. because the other host is spoofing?</p>
<p>I'm working in an embedded environment, so looking for answers on a protocol level, rather than âuse such and such a toolâ.</p>
<p><strong>Edit</strong>: RARP does <em>not</em> solve this problem. For RARP to get any reply at all, there has to be at least one host on the segment which supports RARP. Since RARP is obsolete, modern operating systems don't support it. Furthermore, all RARP can do is tell you your own IP address - the response won't be any different if thereâs another host on the segment with the same MAC, unless that host has itself used a different IP address.</p>
|
<p>This question is too interesting to put down! After several false starts I started thinking about the essential components of the problem and scoured the RFCs for advice. <strong>I haven't found a definitive answer,</strong> but here's my thought process, in the hope that it helps:</p>
<ul>
<li><p>The original question asks how to detect another device with your MAC address. Assuming you're on an IP network, what's required to accomplish this?</p></li>
<li><p>The <em>passive</em> method would be simply to <em>listen</em> to traffic and look for any packets that you didn't transmit but have your MAC address. This may or may not occur, so although it <em>can</em> tell you definitively if a duplicate exists, it <em>cannot</em> tell you definitively that it doesn't.</p></li>
<li><p>Any <em>active</em> method requires you to transmit a packet that <em>forces</em> an impostor to respond. This immediately eliminates any methods that depend on <em>optional</em> protocols.</p></li>
<li><p>If another device is spoofing you, it <em>must</em> (by definition) respond to packets with <em>your</em> MAC address as the destination. Otherwise it's <em>snooping</em> but not <em>spoofing</em>.</p></li>
<li><p>The solution should be independent of IP address and involve only the MAC address. </p></li>
<li><p>So the answer, it seems, would be to transmit either a broadcast (ethernet) packet or a packet with your MAC address as its destination, that requires a response. The monkeywrench is that an IP address is usually involved, and you don't know it.</p></li>
</ul>
<p><em>What sort of protocol fits this description?</em></p>
<p><strong>Easy Answer:</strong></p>
<ul>
<li>If your network supports BOOTP or DHCP, you're done, because this authoritatively binds a MAC address to an IP address. Send a BOOTP request, get an IP address, and try to talk to it. You may need to be creative to force the packet onto the wire and prevent yourself from responding (I'm thinking judicious use of iptables and NAT).</li>
</ul>
<p><strong>Not-so-easy Answers:</strong></p>
<ul>
<li><p>A protocol that's independent of IP: either one that doesn't use the IP layer, or one that allows broadcasts. None comes to mind.</p></li>
<li><p>Send <em>any</em> packet that would normally generate a response from you, prevent yourself from responding, and look for a response from another device. It would seem sensible to use your IP address as the destination, but I'm not convinced of that. Unfortunately, the details (and, therefore the answer) are left as an exercise for the OP ... but I hope the discussion was helpful.</p></li>
</ul>
<p>I suspect the final solution will involve a combination of techniques, as no single approach seems to guarantee a dependable determination.</p>
<p>Some information is available at <a href="http://en.wikipedia.org/wiki/ARP_spoofing#Defenses">http://en.wikipedia.org/wiki/ARP_spoofing#Defenses</a></p>
<p>If all else fails, you may enjoy this: <a href="http://www.rfc-editor.org/rfc/rfc2321.txt">http://www.rfc-editor.org/rfc/rfc2321.txt</a></p>
<p><em>Please</em> post a follow-up with your solution, as I'm sure it will be helpful to others. Good luck!</p>
|
What are the benefits to marking a field as `readonly` in C#? <p>What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing during the lifecycle of the class or are there any compiler speed improvements due to this keyword</p>
|
<p>I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value. </p>
<p>However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. The readonly keyword compiles down to .initonly which is verifiable by the CLR. </p>
<p>The real advantage of this keyword is to generate immutable data structures. Immutable data structures by definition cannot be changed once constructed. This makes it very easy to reason about the behavior of a structure at runtime. For instance, there is no danger of passing an immutable structure to another random portion of code. They can't changed it ever so you can program reliably against that structure.</p>
<p>Here is a good entry about one of the benefits of immutability: <a href="http://strangelights.com/blog/archive/2008/05/18/1617.aspx">Threading</a></p>
|
AccessControlException when attempting to delete a file <p>We have a java web service application that uses log4j to do logging. An exception gets thrown when log4j tries to delete its rolling log files</p>
<pre><code>Exception:java.security.AccessControlException: access denied
(java.io.FilePermission /var/opt/SUNWappserver/domains/domain1/
applications/j2ee-modules/ourwebservice/WEB-INF/logs/IMWrapper.log.10 delete)
</code></pre>
<p>When we do an <code>ls</code> in the directory the service account does have access to read and write to the files and the directory.</p>
<p>From some initial Googling it seems we may have to change the <code>security.policy</code> file to allow the service to delete files. Any suggestions?</p>
|
<p>As a quickfix you can start the application using a policy file with the following content:</p>
<pre><code>grant {
permission java.security.AllPermission;
};
</code></pre>
<p>using the command line option:</p>
<p>-Djava.security.policy=file:<your_policy_file></p>
<p>See <a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/PolicyFiles.html" rel="nofollow">this link</a> for more info how to configure your policy file to get the required access rights.</p>
<p>EDIT: I'm sorry, but I don't know how to configure your web application how to use that policy file, but at least the link should hint you towards getting the required rights...</p>
|
Define an Extension Method for IEnumerable<T> which returns IEnumerable<T>? <p>How do I define an Extension Method for <code>IEnumerable<T></code> which returns <code>IEnumerable<T></code>?
The goal is to make the Extension Method available for all <code>IEnumerable</code> and <code>IEnumerable<T></code> where <code>T</code> can be an anonymous type.</p>
|
<p>The easiest way to write any iterator is with an iterator block, for example:</p>
<pre><code>static IEnumerable<T> Where<T>(this IEnumerable<T> data, Func<T, bool> predicate)
{
foreach(T value in data)
{
if(predicate(value)) yield return value;
}
}
</code></pre>
<p>The key here is the "<code>yield return</code>", which turns the method into an iterator block, with the compiler generating an enumerator (<code>IEnumerator<T></code>) that does the same. When called, generic type inference handles the <code>T</code> automatically, so you just need:</p>
<pre><code>int[] data = {1,2,3,4,5};
var odd = data.Where(i=>i%2 != 0);
</code></pre>
<p>The above can be used with anonymous types just fine.</p>
<p>You can, of coure, specify the <code>T</code> if you want (as long as it isn't anonymous):</p>
<pre><code>var odd = data.Where<int>(i=>i%2 != 0);
</code></pre>
<p>Re <code>IEnumerable</code> (non-generic), well, the simplest approach is for the caller to use <code>.Cast<T>(...)</code> or <code>.OfType<T>(...)</code> to get an <code>IEnumerable<T></code> first. You can pass in <code>this IEnumerable</code> in the above, but the caller will have to specify <code>T</code> themselves, rather than having the compiler infer it. You can't use this with <code>T</code> being an anonymous type, so the moral here is: don't use the non-generic form of <code>IEnumerable</code> with anonymous types.</p>
<p>There are some slightly more complex scenarios where the method signature is such that the compiler can't identify the <code>T</code> (and of course you can't specify it for anonymous types). In those cases, it is usually possible to re-factor into a different signature that the compiler <em>can</em> use with inference (perhaps via a pass-thru method), but you'd need to post actual code to provide an answer here.</p>
<p><hr /></p>
<p>(updated)</p>
<p>Following discussion, here's a way to leverage <code>Cast<T></code> with anonymous types. The key is to provide an argument that can be used for the type inference (even if the argument is never used). For example:</p>
<pre><code>static void Main()
{
IEnumerable data = new[] { new { Foo = "abc" }, new { Foo = "def" }, new { Foo = "ghi" } };
var typed = data.Cast(() => new { Foo = "never used" });
foreach (var item in typed)
{
Console.WriteLine(item.Foo);
}
}
// note that the template is not used, and we never need to pass one in...
public static IEnumerable<T> Cast<T>(this IEnumerable source, Func<T> template)
{
return Enumerable.Cast<T>(source);
}
</code></pre>
|
Is there a good Python GUI shell? <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
|
<p>One project I'm aware of that provides similar features (inline plotting, customisable rendering) is <a href="http://fishsoup.net/software/reinteract/">Reinteract</a>. Another (though possibly a bit heavyweight for general usage) is <a href="http://www.sagemath.org/">SAGE</a> which provides functionality for web-based <a href="http://www.sagenb.org">notebooks</a>.</p>
<p>These aren't quite shells - they're designed more as a mathematical notebook (so for instance, you can modify an earlier result and have the change propogate to later calculations), but they're close to what you're looking for, and could probably be modified to be used as such.</p>
|
I need to get the password which is Hashed in ASP.net <p>I am storing all my passwords in the form hashed. I need to retrieve these passwords
Eg</p>
<p>My password is "123456" I save this as hashed "3453474852dfdsfdsfdf" value.</p>
<p>I need to retrieve the original password from the hashed value. (Get Password).</p>
<p>How can I do that?. I am doing SHA1 hashing algorithm.</p>
|
<p>This is not possible. SHA1 is, very carefully and deliberately, a <a href="https://secure.wikimedia.org/wikipedia/en/wiki/One-way_function" rel="nofollow">one-way function</a>.</p>
<p>Why are you trying to recover the original password? It is not needed for authentication, because you simply hash the input password and compare the hash values.</p>
<p>If it is because the user forgot their password, then standard practice appears to be generating a randomized reset link and emailing it to the user.</p>
|
What is the best way to transfer a file using Java? <p>I am writing code for uploading a file from a client to my server and the performance isn't as fast as I think it should be.</p>
<p><strong>I have the current code snippet that is doing the file transfer and I was wondering how I could speed up the transfer.</strong></p>
<p>Sorry about all of the code:</p>
<pre><code>InputStream fileItemInputStream ;
OutputStream saveFileStream;
int[] buffer;
while (fileItemInputStream.available() > 0) {
buffer = Util.getBytesFromStream(fileItemInputStream);
Util.writeIntArrToStream(saveFileStream, buffer);
}
saveFileStream.close();
fileItemInputStream.close();
</code></pre>
<p>The Util methods are as follows:</p>
<pre><code>public static int[] getBytesFromStream(InputStream in, int size) throws IOException {
int[] b = new int[size];
int count = 0;
while (count < size) {
b[count++] = in.read();
}
return b;
}
</code></pre>
<p>and:</p>
<pre><code>public static void writeIntArrToStream(OutputStream out, int[] arrToWrite) throws IOException {
for (int i = 0; i < arrToWrite.length; i++) {
out.write(arrToWrite[i]);
}
}
</code></pre>
|
<p>Reading a single byte at a time will be horribly inefficient. You're also relying on <code>available</code>, which is rarely a good idea. (It will return 0 if there are no bytes <em>currently</em> available, but there may be more to come.)</p>
<p>This is the right sort of code to copy a stream:</p>
<pre><code>public void copyStream(InputStream input, OutputStream output) throws IOException
{
byte[] buffer = new byte[32*1024];
int bytesRead;
while ((bytesRead = input.read(buffer, 0, buffer.length)) > 0)
{
output.write(buffer, 0, bytesRead);
}
}
</code></pre>
<p>(The caller should close both streams.)</p>
|
is it worth keeping the OS look and feel? <p>Is it worth to try to keep your GUI within the system looks ?</p>
<p>Every major program have their own anyways...
(visual studio, iexplorer, firefox, symantec utilities, adobe ...)</p>
<p>Or just the frame and dialogs should be left in the system look 'n feel range ?</p>
<p><strong>update:</strong></p>
<p>One easy exemple, if you want to add a close button to your tab, usually you make it against your current desktop theme. But if the user has a different theme, your close button is out of place, it doesn't fit the system look anymore.</p>
<p>I played with the uxtheme api, but there is nothing much you can do, and some themes i've seen are incomplete sets.</p>
<p>So to address this issue, the best way i see, is to do like visual studio/firefox/chrome roolup your own tab control with your theme...</p>
|
<p>I think, that unless your program becomes a very major part of the users life, you should strive to minimize "surprises" and maximimze recognizability (is that even a word?).</p>
<p>So, if you are making something that is used by 1.000 people for 10 minutes a day, go with system looks, and mechanisms.</p>
<p>If, on the other hand, you are making something that 100 people are using for 6 hours a day, I would start exploring what UI improvements and shortcuts I could cram in to make those 6 hours easier to deal with. </p>
<p>Notice however, that UI fixes must not come at the expense of performance. This is almost always the case in the beginning when someone thinks that simply overriding the OnPaint event in .Net will be sufficient.</p>
<p>Before you know it you are once again intercepting NC_PAINT and NC_BACKGROUNDERASE and all those little tricks to make it go as fast as the built-in controls.</p>
|
MS Access: How to bypass/suppress an error? <p>I'm executing a query like this</p>
<pre><code>select field from table;
</code></pre>
<p>In that query, there is a loop running on many tables. So, if the field is not present in a table I get a </p>
<blockquote>
<p>Runtime Error 3061</p>
</blockquote>
<p>How can I by pass this error such as that on this error flow should go to another point?</p>
<p>This is the code I have recently after going through this forum.</p>
<pre><code>Option Explicit
Private Sub UpdateNulls()
Dim rs2 As DAO.Recordset
Dim tdf As DAO.TableDef
Dim db As Database
Dim varii As Variant, strField As String
Dim strsql As String, strsql2 As String, strsql3 As String
Dim astrFields As Variant
Dim intIx As Integer
Dim field As Variant
Dim astrvalidcodes As Variant
Dim found As Boolean
Dim v As Variant
Open "C:\Documents and Settings\Desktop\testfile.txt" For Input As #1
varii = ""
Do While Not EOF(1)
Line Input #1, strField
varii = varii & "," & strField
Loop
Close #1
astrFields = Split(varii, ",") 'Element 0 empty
For intIx = 1 To UBound(astrFields)
'Function ListFieldDescriptions()
Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection
Dim rs As ADODB.Recordset, rs3 As ADODB.Recordset
Dim connString As String
Dim SelectFieldName
Set cn = CurrentProject.Connection
SelectFieldName = astrFields(intIx)
Set rs = cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, Empty, SelectFieldName))
'Show the tables that have been selected '
While Not rs.EOF
'Exclude MS system tables '
If Left(rs!Table_Name, 4) <> "MSys" Then
strsql = "Select t.* From [" & rs!Table_Name & "] t Inner Join 01UMWELT On t.fall = [01UMWELT].fall Where [01UMWELT].Status = 4"
End If
Set rs3 = CurrentDb.OpenRecordset(strsql)
'End Function
strsql2 = "SELECT label.validcode FROM variablen s INNER JOIN label ON s.id=label.variablenid WHERE varname='" & astrFields(intIx) & "'"
Set db = OpenDatabase("C:\Documents and Settings\Desktop\Codebook.mdb")
Set rs2 = db.OpenRecordset(strsql2)
With rs2
.MoveLast
.MoveFirst
astrvalidcodes = rs2.GetRows(.RecordCount)
.Close '
End With
With rs3
.MoveFirst
While Not rs3.EOF
found = False
For Each v In astrvalidcodes
If v = .Fields(0) Then
found = True
Debug.Print .Fields(0)
Debug.Print .Fields(1)
Exit For
End If
Next
If Not found Then
msgbox "xxxxxxxxxxxxxxxx"
End If
End If
.MoveNext
Wend
End With
On Error GoTo 0 'End of special handling
Wend
Next intIx
End Sub
</code></pre>
<p>I'm getting a</p>
<blockquote>
<p>Type Mismatch Runtime Error </p>
</blockquote>
<p>in <code>Set rs3 = CurrentDb.OpenRecordset(strsql)</code></p>
<p>I guess I'm mixing up <code>ado</code> and <code>dao</code> but I'm not certainly sure where it is.</p>
|
<p>Use the <code>On Error</code> statement that VBA supplies:</p>
<pre><code>Sub TableTest
On Error Goto TableTest_Error
' ...code that can fail... '
Exit Sub
:TableTest_Error
If Err.Number = 3061 Then
Err.Clear()
DoSomething()
Else
MsgBox Err.Description ' or whatever you find appropriate '
End If
End Sub
</code></pre>
<p>Alternatively, you can switch off automatic error handling (e.g. breaking execution and displaying an error message) on a line-by-line basis:</p>
<pre><code>Sub TableTest
' ... fail-safe code ... '
On Error Resume Next
' ...code that can fail... '
If Err.Number = 3061 Then
Err.Clear()
DoSomething()
Else
MsgBox Err.Description
End If
On Error Goto 0
' ...mode fail-safe code... '
End Sub
</code></pre>
<p>There are these statements available:</p>
<ul>
<li><code>On Error Resume Next</code> switches off VBA-integrated error handling (message box etc.) completely, execution simply resumes on the next line. Be sure to check for an error very early after you've used that, as a dangling error can disrupt the normal execution flow. Clear the error as soon as you caught it to prevent that. </li>
<li><code>On Error Goto <Jump Label></code> resumes execution at a given label, primarily used for per-function error handlers that catch all sorts of errors.</li>
<li><code>On Error Goto <Line Number></code> resumes at a given line number. Stay away from that, it's not useful, even dangerous.</li>
<li><code>On Error Goto 0</code> it's close cousin. Reinstates the VBA integrated error management (message box etc.)</li>
</ul>
<p><hr /></p>
<p><strong>EDIT</strong></p>
<p>From the edited qestion, this is my proposal to solve your problem.</p>
<pre><code>For Each FieldName In FieldNames ' assuming you have some looping construct here '
strsql3 = "SELECT " & FieldName & " FROM table"
On Error Resume Next
Set rs3 = CurrentDb.OpenRecordset(strsql3)
If Err.Number = 3061 Then
' Do nothing. We dont care about this error '
Err.Clear
Else
MsgBox "Uncaught error number " & Err.Number & " (" & Err.Description & ")"
Err.Clear
End If
On Error GoTo 0
Next FieldName
</code></pre>
<p>Be sure to clear the error <em>in any case</em> before you go on with a loop in the same Sub or Function. As I said, a dangling error causes code flow to become unexpected!</p>
|
MySql: MyISAM vs. Inno DB! <p>What are the differences between MyISAM and Inno DB types in MySql?</p>
|
<p>The main difference is that InnoDB supports transactions while MyISAM does not.</p>
<p>There are numerous other differences, however the common one's i am aware of are:</p>
<ul>
<li>MyISAM has typically been considered faster at searching, but recent InnoDB improvements are removing this difference and improving high concurrency workload performance</li>
<li>InnoDB support transactions whilst MyISAM does not</li>
<li>InnoDB handles indexes a bit differently, storing the primary key as part of every index (making indexes take up more room on the disk, but also making a covering index more likely)</li>
<li>MyISAM does table level locking while InnoDB can do row level locking</li>
<li>Different memory/buffer/index settings are used in the MySQL configuration files</li>
<li>InnoDB is typically said to have better crash recovery</li>
<li>As mentioned in another answer, the data is store on disk differently. I believe InnoDB is configurable in this area and can have one file per table etc. if required</li>
</ul>
<p>I'm sure a google search or the MySQL site will bring up numerous other differences in more detail.</p>
|
How do I get Ltk to display what the user is writing and what the functions print? <p>The kind of functions are of the sort of:</p>
<pre><code>(defun display-all ()
"Display all items in the database."
(dolist (item *database*)
(format t "~{~a:~10t~a~%~}~%" item)))
(defun prompt-read (prompt)
(format *query-io* "~a: " prompt)
(force-output *query-io*)
(read-line *query-io*))
(defun prompt-for-item ()
(make-database
(prompt-read "Name")
(prompt-read "Price")))
</code></pre>
<p>I've read the Ltk documentation, but there doesn't seem to be any examples of text widget usage.</p>
|
<p>You create the text widget like every other widget. The Lisp-side object has <code>text</code> accessor function with writer method which sets the text on Tk side. Minimal example:</p>
<pre><code>(with-ltk ()
(let* ((text-widget (make-instance 'text :width 15 :height 2))
(b1 (make-instance 'button
:text "Print"
:command #'(lambda () (princ (text text-widget)))))
(b2 (make-instance 'button :text "Reset"
:command #'(lambda () (setf (text text-widget) "reset")))))
(pack text-widget)
(pack b1)
(pack b2)))
</code></pre>
|
What are the best PDC 2008 videos that I need to look at? <p>Considering the full list of PDC videos published <a href="http://channel9.msdn.com/posts/pdc2008/RSS/Default.aspx" rel="nofollow">here</a> what are, in your opinion, the best session to download and see, considering their relevance to your work, technology and so on? Pleas, one session per answer (exception only for the sessions split in two parts) and please vote it so to move the best ones to the top.</p>
|
<p>I would have to say that my favorite session was the "future of C#" video, very nice to be able to see what is coming in the future for C# and the .NET framework.</p>
|
What is the equivalent of the .NET Framework 2.0 SDK for the .NET Framework 3.5? <p>On our build server, we've installed the .NET Framework 2.0 SDK in order to kick off MSBuild and run our builds. Now we are upgrading to the .NET Framework 3.5. We do not want to install the complete Visual Studio, but we cannot find a .NET Framework 3.5 SDK on the internet either?</p>
<p>The question: What do we need ot download and install to get the equivalent of a .NET Framework 3.5 SDK installation?</p>
|
<p>.net 3.5 comes with compiler and msbuild bundled with it. just download the normal .net 3.5 framework (not the client profile) and you'll be fine.</p>
|
Hibernate JPA Sequence (non-Id) <p>Is it possible to use a DB sequence for some column that <strong>is not the identifier/is not part of a composite identifier</strong>? </p>
<p>I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier.</p>
<p>What I want is to use a sequence to create a new value for an entity, where the column for the sequence is <strong>NOT</strong> (part of) the primary key:</p>
<pre><code>@Entity
@Table(name = "MyTable")
public class MyEntity {
//...
@Id //... etc
public Long getId() {
return id;
}
//note NO @Id here! but this doesn't work...
@GeneratedValue(strategy = GenerationType.AUTO, generator = "myGen")
@SequenceGenerator(name = "myGen", sequenceName = "MY_SEQUENCE")
@Column(name = "SEQ_VAL", unique = false, nullable = false, insertable = true, updatable = true)
public Long getMySequencedValue(){
return myVal;
}
}
</code></pre>
<p>Then when I do this:</p>
<pre><code>em.persist(new MyEntity());
</code></pre>
<p>the id will be generated, but the <code>mySequenceVal</code> property will be also generated by my JPA provider.</p>
<p>Just to make things clear: I want <strong>Hibernate</strong> to generate the value for the <code>mySequencedValue</code> property. I know Hibernate can handle database-generated values, but I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property. If Hibernate can generate values for primary keys, why can't it generate for a simple property?</p>
|
<p>Looking for answers to this problem, I stumbled upon <a href="http://forum.hibernate.org/viewtopic.php?p=2405140">this link</a></p>
<p>It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The <code>@GeneratedValue</code> annotation is only used in conjunction with <code>@Id</code> to create auto-numbers.</p>
<p>The <code>@GeneratedValue</code> annotation just tells Hibernate that the database is generating this value itself.</p>
<p>The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:</p>
<pre>
@Entity
public class GeneralSequenceNumber {
@Id
@GeneratedValue(...)
private Long number;
}
@Entity
public class MyEntity {
@Id ..
private Long id;
@OneToOne(...)
private GeneralSequnceNumber myVal;
}
</pre>
|
MOSS 2007: SPListItem.GetFormattedValue for DateTime fields has a bug? <p>SPListItem.GetFormattedValue seems to have a strange behavior for DateTime fields.
It retrieves the DateTime value through SPListItem's indexer which according to this <a href="http://msdn.microsoft.com/en-us/library/ms197282.aspx">MSDN article</a> returns <em>local</em> time.
Here's a snippet from Reflector</p>
<pre><code>public string GetFormattedValue(string fieldName)
{
SPField field = this.Fields.GetField(fieldName);
if (field != null)
{
return field.GetFieldValueAsHtml(this[fieldName]);
}
return null;
}
</code></pre>
<p>So it uses SPListItem's indexer to retrieve the value and than SPFields.GetFieldValueAsHtml to format the value. GetFieldValueAsHtml seems to assume the date is in UTC and convert it to local time no matter what kind it is. (Reflector shows that it uses GetFieldValueAsText which uses value.ToString() but for some reason it assumes the time to be UTC.)</p>
<p>The end result is that the string representation on a time field obtained trough listItem.GetFormattedValue() (at least in my case) is incorrect, being local time + (local time - UTC).</p>
<p>Have anybody encountered the same issue with SPListItem.GetFormattedValue() and what was your workaround?</p>
|
<p>Converting the date back to universal time before calling GetFieldValueAsHtml works just fine.</p>
<pre><code>DateTime localTime = (DateTime)item["DueDate"];
// this is local time but if you do localDateTime.Kind it returns Unspecified
// treats the date as universal time..
// let's give it the universal time :)
DateTime universalTime = SPContext.Current.Web
.RegionalSettings.TimeZone.LocalTimeToUTC(localTime);
string correctFormattedValue =
item.Fields["DueDate"].GetFieldValueAsHtml(universalTime);
</code></pre>
|
Seen this binary date format? <p>3/10/2008 = 1822556159</p>
<p>2/10/2008 = 1822523391</p>
<p>1/10/2008 = 1822490623</p>
<p>30/09/2008 = 1822392319</p>
<p>29/09/2008 = 1822359551</p>
<p>This is all the information that I know at the current time. </p>
<p>Dates increment by 32768 except when changing month when the increment is 32768 x 2 (65536).</p>
<p>Has anyone seen this binary date format and how can I extract the correct date?</p>
<p><hr /></p>
<p>It is possible that the remaining portion of the date is for time (hours, minutes, seconds)</p>
|
<p>September 30th 2008</p>
<pre><code>1822392319 = 0x6c9f7fff
0x6c = 108 = 2008 (based on 1900 start date)
0x9 = 9 = September
0xf7fff - take top 5 bits = 0x1e = 30
</code></pre>
<p>October 1st 2008</p>
<pre><code>1822490623 = 0x6ca0ffff
0x6c = 108 = 2008
0xa = 10 = October
0x0ffff - take top 5 bits = 0x01 = 1
</code></pre>
<p>It's anyone's guess what the remaining 15 one-bits are for, if anything.</p>
<p>EDIT: by take top 5 bits I mean:</p>
<pre><code>day_of_month = (value >> 15) & 0x1f
</code></pre>
<p>Similarly:</p>
<pre><code>year = (value >> 24) & 0xff + 1900
month = (value >> 20) & 0x0f
</code></pre>
|
XPath vs DeSerialization: which one is better in performance for read operations <p>I'm passing small (2-10 KB)XML documents as input to a WCF service. now I've two option to read data values from incoming XML</p>
<ol>
<li>Deserialize to a strongly typed object and use object properties to access values</li>
<li>use XPath to access values</li>
</ol>
<p>which approach is faster? some statistics to support your answer would be great.</p>
|
<p>I would deserialize it.</p>
<p>If you use xpath, you will deserialize (or "load") it to XmlDocument or something anyway. So both solutions use time deserializing. After this is done, xpath will be slower because of the time spent parsing that string, resolving names, executing functions and so on. Also, if you go with xpath, you get no type safety. Your compiler can't check the xpath syntax for you.</p>
<p>If you use XmlSerializer and classes, you get static typing. Really fast access to you data, and if you want to query them with xpath, there are still ways to do that.</p>
<p>Also, I would like to say that your code would probably be easier to understand with classes.</p>
<p>The only drawback is that the xml has to conform to the same schema all the time, but that might not be a real problem in your case.</p>
<p>I hope that you forgive the absence of statistics, I think the arguments are strong enough without examples. If you want an ultimate answer, try both and keep a stopwatch ready.</p>
|
Recurring Payments in PayPal <p>I am trying to use the Recurring payment API offered by PayPal.
I have a scenario which I am not able to address directly. It goes like this.</p>
<p>We have a website where we sell some services. Now the services are charged per user license. A user can buy/cancel user license in between. We want to offer the customer a recurring billing option. We have to notice here that the amount may vary each billing cycle based on the number of user licenses the customer uses during that cycle.</p>
<p>Is there any way I can achieve this using PayPal recurring Payment API's.</p>
|
<p>I realize this is a very old post, but it still shows up for Google searches, so I thought I'd add:</p>
<p>Paypal does allow you to do this now, using their new <a href="https://www.x.com/community/ppx/adaptive_payments">adaptive payments api</a>.</p>
<p>Authorize.net also has a service that might work called <a href="http://developer.authorize.net/api/cim/">Customer Information Manager</a>.</p>
|
Input Audio as a Stream in CF 3.5 <p>I googled around and coulnd't really find an answer.</p>
<p><strong>How do I open an audio input device</strong> (namely a microphone) <strong>as a stream</strong> (preferably) <strong>on a CE/WinMobile device using Compact Framework?</strong></p>
<p>I looked at WindowsMobile.DirectX, at various classes that contained Audio in their name and nothing seemed to do the trick.</p>
<p>What I want to do is basically to stream the audio input over the network to the server.</p>
|
<p>The usual answer for "trying to do something with the CF and can't" is OpenNetCF.</p>
<p>Here's the <a href="http://www.opennetcf.com/library/sdf/html/f3fc3169-4143-54bc-1594-186da1fb01c2.htm" rel="nofollow">page for WaveAudio</a> which includes a Recorder class with a RecordFor method that records to a stream for a given number of seconds. It's not quite ideal for your purposes, but really close. The OpenNetCF folk tend to be pretty responsive to requests.</p>
|
How can I run sql server stored procedures in parallel? <p>I want to do something like:</p>
<pre><code>exec sproc1 and sproc2 at the same time
when they are both finished exec sproc3
</code></pre>
<p>I can do this in dts.
Is there a way to do it in transact sql?
Or is there a way to do it with a batch script (eg vbs or powershell)?</p>
|
<p>You could create a CLR Stored Procedure that (using C#) would call the first two on their own threads, and then block until both are complete... then run the third one.</p>
<p>Are you able to use CLR sprocs in your situation? If so, I'll edit this answer to have more detail.</p>
|
How do I add custom column to existing WSS list template <p>I need to use feature stapler to add some text columns to Posts list inside OOTB blog site definition. I plan not to use site columns, but only to add those columns to list (I don't use site columns because I have multiple site collections and there will be only one Posts list per site collection, so site columns are not very reusable in this case). My question is: How do I achieve this? </p>
|
<p>Perhaps you can create a feature that uses the object model from the feature receiver to add (and remove as appropriate) the columns to just the specific list when the feature is activated.</p>
<p>I would use the XML Schema approach for creating the columns in order to ensure the same GUID for each column. <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection.addfieldasxml.aspx" rel="nofollow">See</a></p>
|
Unable to turn on SecureSocketLayer with DirectoryServices.Protocols.LdapConnection <p>I am trying to fix a bug with SSL in a product and noticed that although the code sets SSL to be true, in the next line in the code SSL is still at false. I wrote a unit test for this and the unit test confirms my suspicions. </p>
<pre><code> [TestMethod]
public void SecureSocketLayerSetToTrue( )
{
var ldapConnection = new LdapConnection(
new LdapDirectoryIdentifier( "ldap.test.com", 636 ));
ldapConnection.SessionOptions.SecureSocketLayer = true;
Assert.IsTrue( ldapConnection.SessionOptions.SecureSocketLayer );
}
</code></pre>
<p>The test fails. Is there something here that I am missing?</p>
|
<p>It turns out that the way that the DirectoryServices.Protocols implements it's LDAP calls is by passing them through to a low-level LDAP API. This LDAP API is what is queried when a get is done on the property.</p>
<p>The low-level API is only updated when the methods are executed. You can think about this like it is building command-line arguments for an executable that hasn't been launched yet.</p>
<p>When a call like Bind() is made, then the executable is launched and the properties will report the correct value.</p>
<p>So, just because the property was saying that the value was false, it was using the true when necessary.</p>
|
How can I create or read OpenOffice spreadsheets from Perl? <p>What is a good way to create and read an OpenOffice spreadsheet in Perl?</p>
|
<p>I think that the open office native document format is based around the OpenDocument specifications, and is bascially a zip compressed XML format. This being true you could probably manipulate it using your perl XML manipulation tools of choice. </p>
<p>Alternatively, there's the <a href="http://search.cpan.org/perldoc?OpenOffice::OODoc::Intro">Open Office OpenDocument Connector suite of modules on the CPAN</a> which offers a high level API to the OpenDocument spec. </p>
<p>To my knowledge, the table methods in these modules should allow for both reading and writing data in OO Calc documents.</p>
|
ASP.Net Client Events on DropDownList? <p>Is there a client event that I can use for when a DropDownList's data has been loaded/bound onto the control? I need to trigger event on their side when this happens.</p>
<hr>
<p>Basically, I am trying to lock out the controls while the data is being loaded as if there is a slowdown (not uncommon) a user can start inputting data and then lose focus as they are typing. </p>
<p>I tried doing this in the tags but the methods located there seem to stop working after the first postback! (Any help there would be greatly appreciated). As a workaround I tried attaching the events to the elements themselves and while this works for locking, using the onchange event, I am unable to unlock it upon the data successfully loading!</p>
<p>Any ideas? Thanks for the answers so far :) </p>
|
<p>Since data will be bound on the server side, you don't have a client-side event for that specific event, however, one the page has rendered, the data will be there, so you may want to run your client script in the document.load event, or using something like jQuery's document.ready event. That will trigger your script to run once the page (including your bound drop down) is finished loading.</p>
|
Simulating connection problems for .NET HttpWebRequest <p>Are there ways to programmatically simulate connection problems (slow connection, response does not complete, connection gets dropped, etc.) when using the HttpWebRequest class?</p>
<p>Thanks</p>
<p>EDIT: To elaborate more, I need this for debugging but would want to turn it into a test eventually. I'm using the async methods BeginGetRequestStream, EndGetRequestStream, BeginGetResponse and EndGetResponse. I have wrapped them all in proper (I hope) Try Catch blocks which log the exceptions that happen.</p>
<p>I know this works for some cases (e.g. when I pull out the network cable). But on some rare occasions (i.e. only when the website I'm requesting is slow) then my system crashes and I get this in the Event Log</p>
<pre><code>Exception: System.Net.WebException
Message: The request was aborted: The connection was closed unexpectedly.
StackTrace: at System.Net.ConnectStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at System.IO.Compression.DeflateStream.ReadCallback(IAsyncResult baseStreamResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.ContextAwareResult.CompleteCallback(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</code></pre>
<p>I am making an assumption it's from HttpWebRequest but then again all my code is wrapped in Try Catch blocks.</p>
<p>Would mocks help in such a case?</p>
|
<p>@Chris
Unfortunately, Microsoft neglected to <a href="http://bartling.blogspot.com/2009/01/net-base-class-library-types-not.html" rel="nofollow">make many of the BCL objects easily mockable</a>, as they tend to use abstract classes, and .NET classes are closed by design (in other words, for a method to be overridden by a subclass, it needs to be explicitly marked as virtual), whereas Java is open by design (that is, a subclass can override any method, unless they are marked as final). Using interfaces or marking the methods as virtual would have saved a lot of headaches in the testing space. Microsoft may have the testability religion now (e.g. ASP.NET MVC), but it's a bit late for the BCL.</p>
<p>Typemock Isolator <a href="http://blog.typemock.com/2008/07/is-visibility-of-tested-methods.html" rel="nofollow">may be able to help</a>, but I don't believe Moq can, in this case.</p>
|
How to implement CEditListCtrl <p>How to implement CEditListCtrl?. List control with edit capabality (Report/Grid view).
I have a list view in Report View. It has some values. I need to extend this to edit the values present in the list view.
I declared a class which inherits from CListCtrl. And I have handled the two Window messages to start and end the edit. Upon getting the messages I am displaying a Text box. But I am not getting the control inside these message handlers. Is there a way to know the reason?</p>
<p>Or Is there a other way to implement this.</p>
|
<p>There are some neat grid controls on Code Project which might help:</p>
<p><a href="http://www.codeproject.com/KB/miscctrl/gridctrl.aspx" rel="nofollow">http://www.codeproject.com/KB/miscctrl/gridctrl.aspx</a></p>
<p><a href="http://www.codeproject.com/KB/library/gridprojects.aspx" rel="nofollow">http://www.codeproject.com/KB/library/gridprojects.aspx</a></p>
<p><a href="http://www.codeproject.com/KB/MFC/UltimateGrid.aspx" rel="nofollow">http://www.codeproject.com/KB/MFC/UltimateGrid.aspx</a></p>
|
Partial sharing of git repositories <p>I am new to git. I am wondering whether the following scenario is supported, and if so how (i.e. git commands for setup and update).</p>
<p>A repository is available from three different places: 'local', 'mirror' and 'github'. 'mirror' mirrors 'local' completely and 'github' mirrors 'local' except for a 'copyrighted' directory.</p>
<p>Thanks.</p>
|
<p>You could use the <a href="http://git-scm.com/docs/git-submodule" rel="nofollow">git submodule</a> support to hold the "copyrighted" directory in a separate Git repository. Keep this separate repository somewhere accessible to people who should be able to see it, and don't push it to github. For people accessing the public repository, they would see a reference to a "copyrighted" repository but would be unable to populate it.</p>
|
DropDownList with LinqDataSource and an empty option <p>Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?</p>
|
<p>Here's how to add a value at the top of the list. It can be an empty string, or some text.</p>
<pre><code><asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
</code></pre>
<p>Be sure to set the DropDownList's AppendDataBoundItems=True. </p>
|
Sql Server CE 3.5 Merge Replication Synchronise is Hanging <p>I am using SQL Server 2005 CE framework 3.5 and attempting to use merge replication between my hand held and my SQL Server. When I run the code to synchronise it just seems to sit forever, and when I put a breakpoint in my code it never gets past the call to Synchronize().</p>
<p>If I look at the replication monitor in sql server, it gets to the point where it says the subscription is no longer synchronising and doesn't show any errors. Therefore I am assuming this to mean the synchronisation is complete.</p>
<p><a href="http://server/virtualdirectory/sqlcesa35.dll?diag" rel="nofollow">http://server/virtualdirectory/sqlcesa35.dll?diag</a> does not report any issues.</p>
<p>This is my first attempt at any handheld development, so I may have done something daft. However, SQL Server seems to be reporting a successful synchronisation.</p>
<p>Any help would be greatly appreciated as I have spent ages on this ! </p>
<p>Here is my code.</p>
<pre><code>const string DatabasePath = @"SD Card\mydb.sdf";
var repl = new SqlCeReplication
{
ConnectionManager = true,
InternetUrl = @"http://server/virtualdirectory/sqlcesa35.dll",
Publisher = @"servername",
PublisherDatabase = @"databasename",
PublisherSecurityMode = SecurityType.DBAuthentication,
PublisherLogin = @"username",
PublisherPassword = @"password",
Publication = @"publicationname",
Subscriber = @"PPC",
SubscriberConnectionString = "Data Source=" + DatabasePath
};
try
{
Cursor.Current = Cursors.WaitCursor;
if (!File.Exists(DatabasePath))
{
repl.AddSubscription(AddOption.CreateDatabase);
}
repl.Synchronize();
MessageBox.Show("Successfully synchronised");
}
catch (SqlCeException e)
{
DisplaySqlCeErrors(e.Errors, e);
}
finally
{
repl.Dispose();
Cursor.Current = Cursors.Default;
}
</code></pre>
|
<p>Another thing you can do to speed up the Synchronize operation is to specify a db file path that is in your PDA's main program memory (instead of on the SD Card as in your example). You should see a speed improvement of up to 4X (meaning the Sync may take only 25% as long as it's taking now).</p>
<p>If you're running out of main program memory on your PDA, you can use System.IO.File.Move() to move the file to the SD Card after the Synchronize call. This seems a bit strange, I know, but it's much faster to sync to program memory and copy to the SD card then it is to sync directly to the SD card.</p>
|
How do you override ToString in a static class? <p>I have a public static class in which I would like to have a ToString() method. </p>
<p>I have defined it as public static string ToString(), but get the following warning: </p>
<blockquote>
<p>'Class.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.</p>
</blockquote>
<p>If I add the override keyword I get this error instead: </p>
<blockquote>
<p>A static member 'Class.ToString()' cannot be marked as override, virtual, or abstract</p>
</blockquote>
<p>How do I get rid of that warning and let my static class have the ToString() method.</p>
<p>Thank you,<br />
Keith</p>
|
<p>Yes, using the "new" modifier will effectively silence the compiler warning but you are <strong>explicitly hiding</strong> an instance method with a static method. (This is different than overriding the method.) Typically you don't want to hide an instance method except with very good reasons and you really shouldn't hide it with a static method as that really changes the behavior semantics of the call. Every object in .NET has an instance method named ToString() that has specific behavior that developers expect; by hiding that behavior with a new static method you are changing that expectation which can lead to a lot of confusion.</p>
<p>What are you "to stringing"? Static classes typically don't hold internal state so there really shouldn't be any internal data to provide as the logical output of a ToString() call. You may want to rethink your class design or provide a different method name that more clearly indicates the purpose of the method without hiding the instance ToString().</p>
|
Perform a modulus in a huge number? <p>I need to do a modulus operation on very large integers. The biggest integer supported by my platform (edit: .NET 2.0) is a 64 bit integer, which aren't big enough for the numbers I'm working with.</p>
<p>How can I do a modulus on really big integers, like 12654875632126424875387321657498462167853687516876876?</p>
<p>I have a solution that treats the number as a string and works it in pieces one by one, but I wanted to know if there's a better way.</p>
<p>Here's my function treating the number as a string. It basically does long division the way you'd do it by hand.</p>
<pre><code> Public Function MyMod(ByVal numberString As String, ByVal modby As Integer) As Integer
Dim position As Integer = -1
Dim curSubtraction As Integer = 0
While position < numberString.Length - 1
position += 1
curSubtraction = curSubtraction * 10 + CInt(numberString.Substring(position, 1))
If (curSubtraction / modby) < 1 And position = numberString.Length - 1 Then
Return curSubtraction
ElseIf (curSubtraction / modby) < 1 Then
Continue While
Else
curSubtraction = curSubtraction Mod modby
End If
End While
Return curSubtraction
End Function
</code></pre>
<p>Is there a cleaner, more efficient way?</p>
<p>EDIT: To clarify, the integers are coming from IBAN bank account numbers. According to the specification, you have to convert the IBAN account number (containing letters) into one integer. Then, you do a modulus on the integer. So, I guess you could say that the real source of the integer to perform the modulus on is a string of digits.</p>
|
<p>You haven't specified where the numbers are coming from, but you might be able to make some simplifications. If the numbers are originally smaller, then consider things like:</p>
<pre><code>(a + b) MOD n = ((a MOD n) + (b MOD n)) MOD n
</code></pre>
<p>or</p>
<pre><code>ab MOD n = (a MOD n)(b MOD n) MOD n
</code></pre>
|
Best process for auto-zipping of multiple MP3s <p>I've got a project which requires a fairly complicated process and I want to make sure I know the best way to do this. I'm using ASP.net C# with Adobe Flex 3. The app server is Mosso (cloud server) and the file storage server is Amazon S3. The existing site can be viewed at <a href="https://www.noisetrade.com" rel="nofollow">NoiseTrade.com</a></p>
<p>I need to do this:</p>
<ul>
<li>Allow users to upload MP3 files to
an album "widget" </li>
<li>After the user has uploaded their
album/widget, I need to
automatically zip the mp3 (for other
users to download) and upload the
zip along with the mp3 tracks to
Amazon S3</li>
</ul>
<p>I actually have this working already (using client side processing in Flex) but this no longer works because of Adobe's flash 10 "security" update. So now I need to implement this server-side.</p>
<p>The way I am thinking of doing this is:</p>
<ul>
<li>Store the mp3 in a temporary folder
on the app server</li>
<li>When the artist "publishes" create a
zip of the files in that folder
using a c# library</li>
<li>Start the amazon S3 upload process (zip and mp3s)
and email the user when it is
finished (as well as deleting the
temporary folder)</li>
</ul>
<p>The major problem I see with this approach is that if a user deletes or adds a track later on I'll have to update the zip file but the temporary files will not longer exist.</p>
<p>I'm at a loss at the best way to do this and would appreciate any advice you might have.</p>
<p>Thanks!</p>
|
<p>The bit about updating the zip but not having the temporary files if the user adds or removes a track leads me to suspect that you want to build zips containing multiple tracks, possibly complete albums. If this is incorrect and you're just putting a single mp3 into each zip, then StingyJack is right and you'll probably end up making the file (slightly) <em>larger</em> rather than smaller by zipping it.</p>
<p>If my interpretation is correct, then you're in luck. Command-line zip tools frequently have flags which can be used to add files to or delete files from an existing zip archive. You have not stated which library or other method you're using to do the zipping, but I expect that it probably has this capability as well.</p>
|
Does VS2008 have somewhat C++0x support? <p>Does VS2008 have somewhat C++0x standard support?</p>
<p>DUPLICATE <a href="http://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards">http://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards</a></p>
|
<p>No afaik. I believe VS2010 will have more support:</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&displaylang=en" rel="nofollow">http://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&displaylang=en</a></p>
<p><a href="http://blogs.msdn.com/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx" rel="nofollow">http://blogs.msdn.com/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx</a></p>
|
Script Minification and Continuous Integration with MSBuild <p>On a recent project I have been working on in C#/ASP.NET I have some fairly complicated JavaScript files and some nifty Style Sheets. As these script resources grow in size it <a href="http://developer.yahoo.com/yui/compressor/">is advisable to minify the resources</a> and keep your web pages as light as possible, of course. I know many developers who hand-feed their JavaScript resources into compressors after debugging and then deploy their applications.</p>
<p>When it comes to source control and automated builds in the satisfying world of continuous integration (thank you <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome%2Bto%2BCruiseControl.NET">CruiseControl.NET</a>); hand compression will simply not do. The only way to maintain source control and offer compressed resources is to keep JS/CSS source & their minified brethren in a separate directory structure. Then register only one set of resources or the other in code-behind. However, if a developer makes a change to JS/CSS source and then fails to re-compact it and check in both versions, then youâre code-line is now out of sync. Not to mention inelegant.</p>
<p>I am thinking that it would be nice to write a custom executable (if one does not exist yet) for the CC.NET task block which would find and compress all JavaScript and CSS resources in the target directory after the build action but before the asp.net publish to target. This way, developers would only work on JS and CSS source and users would only get the minified resources.</p>
<p><strong>Is there an application that already performs this task and if not, what kind of resource(s) should I look to install on the build server to have CC.NET execute?</strong></p>
<p>(The <a href="http://stackoverflow.com/questions/258781/best-packing-strategy-for-js-during-continuous-integration">closest question</a> I could find here to this one required NAnt, which is not an option in my case.)</p>
<p><strong>EDIT:</strong>
Dave Ward now has a great article on <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/">how to automatically minify in Visual Studio</a> at his site.</p>
|
<p>The <a href="https://github.com/loresoft/msbuildtasks/" rel="nofollow">MSBuildCommunityTasks Project</a> has a few MSBuild tasks that may do what you are looking for including Merge and JSCompress. </p>
<p>You could add these into your MSBuild project in the AfterBuild target to allow the project to perform this action every time the project is built and nothing would ever be out of sync. Your web application could then reference the compacted version for run but the developers would edit the full versions.</p>
<p>Nothing else would be needed on the server except the MSBuild community tasks assembly. You can put this assembly in your own source tree and reference from there and your CI build should get that assembly and everything it needs when it builds.</p>
|
Membership.GetUser() & MARS <p>I'm using asp.net membership, and need to make a call to Membership.GetUser() while I have another open SQL connection, but my code dies at that call. I have MultipleActiveResultSets=True in the connection string that is used by both my code and the Membership provider. It appears that the Membership class is ignoring the MARS part of the connect string.</p>
<p>Any suggestions as to how I can get MARS to work with the Membership class so I can solve this problem?</p>
<p>Thanks,</p>
<p>Scott</p>
|
<p>Did you try to use separate connection string (one for data one for Membership provider) without option âMultipleActiveResultSets=Trueâ ? </p>
<p>Does it work then ? If it works you can use <em>SqlConnectionStringBuilder</em> to create new connection string (from the original) without MARS option.</p>
|
How do I collapse elements in a Report Table? <p>I have an SSRS report where I need to collapse data into a summary column like so:<br>
+Program<br>
-Program2<br>
Program2DataElement1 | Program2DataElement2 | etc.</p>
<p>How does one doe this? I see it in other reports, but can't for the life of me find the area to set it up. When I put in a group, I get something like this on all records: <br>
Program<br>
ProgramDataElement | ProgramDataElement | ...</p>
<p>What am I mising? Thanks in advance!</p>
|
<p>I believe these are the steps:</p>
<ol>
<li>Edit group</li>
<li>Click on Visibility Tab</li>
<li>For Initial Visibility, select the "hidden" radio button.</li>
</ol>
|
Vertical Text with jQuery <p>I'm looking to vertically align text by adding <code><br /></code> tags between characters with jQuery.</p>
<pre><code><div id="foo"><label>Vertical Text</label></div>
</code></pre>
<p>would look like this:</p>
<p>V<br />
e<br />
r<br />
t<br />
i<br />
c<br />
a<br />
l<br />
<br />
T<br />
e<br />
x<br />
t<br /></p>
|
<p>Let's go golfing!</p>
<pre><code>$('#foo label').html($('#foo label').text().replace(/(.)/g,"$1<br />"));
</code></pre>
<p>Completely untested, but the pattern in the regex looks like a boob.</p>
|
question on how to use sql server integrated service <p>I have a table called book with, the attrbutes are booked_id, yearmon, and day_01....day_31. Now i need to unpivot the table and transform day_01...day_31 into rows, I have successed in doing that, but the problem is that my yearmon is a format of 200805 and i need to append a day to it based on day_01 or day_02 etc, so that i can create a new column with date information for example, if it is day_01, it looks like 20080501. Instead of writing huge query, does anyone how to use ssis to tranform it</p>
|
<p>You should be able to use the Unpivot component and the Derived Column component to do what you need. Look into those and post back if they don't seem to do what you need.</p>
|
What's the best way to implement friendly URL in ASP.net? <p>What's the best way to implement friendly URL in ASP.net?</p>
|
<p>The <a href="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx" rel="nofollow">ASP.NET Routing Framework</a> provided in .NET 3.5 SP1 is a good one.</p>
<p>Although it is very new, it can handles many URL-related tasks and most frequently used URL-friendly schemes very well.</p>
<p>It can be used outside of MVC, too.</p>
|
External Tool Development for SQL Server Management Studio 2005 <p>Does anyone have any experience of developing external tools for SSMS 2005. </p>
<p>Ideally I would like to be able to interact with the query windows directly, for example, taking the query text from the window to perform some processing on it.</p>
<p>Any pointers in the right direction would be great.</p>
<p>Thanks in advance</p>
|
<p>Have you looked at Sql Server Management Objects (SMO)?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms162557.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms162557.aspx</a></p>
|
UTF-8 all the way through <p>
I'm setting up a new server, and want to support UTF-8 fully in my web application. I have tried in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.</p>
<p>Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL and PHP to do this - is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?</p>
<p>This is for a new Linux server, running MySQL 5, PHP 5 and Apache 2.</p>
|
<p><strong>Data Storage</strong>:</p>
<ul>
<li><p>Specify the <code>utf8mb4</code> character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use <code>utf8mb4</code> encoding if a <code>utf8mb4_*</code> collation is specified (without any explicit character set).</p></li>
<li><p>In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply <code>utf8</code>, which only supports a subset of Unicode characters. I wish I were kidding.</p></li>
</ul>
<p><strong>Data Access</strong>:</p>
<ul>
<li><p>In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to <code>utf8mb4</code>. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.</p></li>
<li><p>Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:</p>
<ul>
<li><p>If you're using the <a href="http://www.php.net/manual/en/book.pdo.php">PDO</a> abstraction layer with PHP ≥ 5.3.6, you can specify <code>charset</code> in the <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php">DSN</a>:</p>
<pre><code>$dbh = new PDO('mysql:charset=utf8mb4');
</code></pre></li>
<li><p>If you're using <a href="http://www.php.net/manual/en/book.mysqli.php">mysqli</a>, you can call <a href="http://php.net/manual/en/mysqli.set-charset.php"><code>set_charset()</code></a>:</p>
<pre><code>$mysqli->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($link, 'utf8mb4'); // procedural style
</code></pre></li>
<li><p>If you're stuck with plain <a href="http://php.net/manual/en/book.mysql.php">mysql</a> but happen to be running PHP ≥ 5.2.3, you can call <a href="http://php.net/manual/en/function.mysql-set-charset.php"><code>mysql_set_charset</code></a>.</p></li>
</ul></li>
<li><p>If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: <a href="http://dev.mysql.com/doc/en/charset-connection.html"><code>SET NAMES 'utf8mb4'</code></a>.</p></li>
<li><p>The same consideration regarding <code>utf8mb4</code>/<code>utf8</code> applies as above.</p></li>
</ul>
<p><strong>Output</strong>:</p>
<ul>
<li><p>If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or <a href="http://stackoverflow.com/q/4696499">HTML metadata</a>).</p></li>
<li><p>In PHP, you can use the <a href="http://www.php.net/manual/en/ini.core.php#ini.default-charset"><code>default_charset</code></a> php.ini option, or manually issue the <code>Content-Type</code> MIME header yourself, which is just more work but has the same effect.</p></li>
</ul>
<p><strong>Input</strong>:</p>
<ul>
<li><p>Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's <a href="http://php.net/manual/en/function.mb-check-encoding.php"><code>mb_check_encoding()</code></a> does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.</p></li>
<li><p>From my reading of the current <a href="http://whatwg.org/html">HTML spec</a>, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:</p>
<ul>
<li><em>For HTML before HTML5 only</em>: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the the only way to reliably do this is add the <code>accept-charset</code> attribute to all your <code><form></code> tags: <code><form ... accept-charset="UTF-8"></code>.</li>
<li><em>For HTML before HTML5 only</em>: note that the W3C HTML spec says that clients "should" default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <code><form></code> tag.</li>
</ul></li>
</ul>
<p><strong>Other Code Considerations</strong>:</p>
<ul>
<li><p>Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.</p></li>
<li><p>You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's <a href="http://www.php.net/manual/en/book.mbstring.php"><code>mbstring</code></a> extension.</p></li>
<li><p><strong>PHP's built-in string operations are <em>not</em> by default UTF-8 safe.</strong> There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent <code>mbstring</code> function.</p></li>
<li><p>To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from <a href="http://www.utf8.com/">utf8.com</a> for some good resources to learn everything you need to know.</p></li>
</ul>
|
How can I get a collection of all the colors in System.Drawing.Color? <p>How can I extract the list of colors in the System.Drawing.Color struct into a collection or array?</p>
<p>Is there a more efficient way of getting a collection of colors than using this struct as a base?</p>
|
<p>So you'd do:</p>
<pre><code>string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));
</code></pre>
<p>... to get an array of all the collors.</p>
<p>Or... You could use reflection to just get the colors. KnownColors includes items like "Menu", the color of the system menus, etc. this might not be what you desired. So, to get just the names of the colors in System.Drawing.Color, you could use reflection:</p>
<pre><code>Type colorType = typeof(System.Drawing.Color);
PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (System.Reflection.PropertyInfo c in propInfoList) {
Console.WriteLine(c.Name);
}
</code></pre>
<p>This writes out all the colors, but you could easily tailor it to add the color names to a list. </p>
<p>Check out this Code Project project on <a href="http://www.codeproject.com/KB/cs/reflectioncolorchart.aspx" rel="nofollow">building a color chart</a>.</p>
|
How to invoke a C# web service through PHP? <p>I've written a web service using ASP.NET (in C#) and I'm attempting to write an example PHP client using NuSOAP. Where I'm tripped up on are examples of how to do this; some show <code>soapval</code> being used (and I don't quite understand the parameters - for example passing <code>false</code> as <code>string</code> types, etc.), while others are just using straight <code>array</code>s. Let's say the WSDL for my web service as reported by <code>http://localhost:3333/Service.asmx?wsdl</code> looks something like:</p>
<pre><code>POST /Service.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/webservices/DoSomething"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<DoSomething xmlns="http://tempuri.org/webservices">
<anId>int</anId>
<action>string</action>
<parameters>
<Param>
<Value>string</Value>
<Name>string</Name>
</Param>
<Param>
<Value>string</Value>
<Name>string</Name>
</Param>
</parameters>
</DoSomething>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>My first PHP attempt looks like:</p>
<pre><code><?php
require_once('lib/nusoap.php');
$client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl');
$params = array(
'anId' => 3, //new soapval('anId', 'int', 3),
'action' => 'OMNOMNOMNOM',
'parameters' => array(
'firstName' => 'Scott',
'lastName' => 'Smith'
)
);
$result = $client->call('DoSomething', $params, 'http://tempuri.org/webservices/DoSomething', 'http://tempuri.org/webservices/DoSomething');
print_r($result);
?>
</code></pre>
<p>Now aside from the Param type being a complex type which I'm pretty sure my simple <code>$array</code> attempt will not automagically work with, I'm breakpointing in my web service and seeing the method I've marked as <code>WebMethod</code> (without renaming it, its literally <code>DoSomething</code>) and seeing the arguments are all default values (the <code>int</code> is <code>0</code>, the <code>string</code> is <code>null</code>, etc.).</p>
<p>What should my PHP syntax look like, and what do I have to do to pass the <code>Param</code> type correctly?</p>
|
<p>You have to wrap things in tons of nested arrays.</p>
<pre><code><?php
require_once('lib/nusoap.php');
$client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl');
$params = array(
'anId' => 3,
'action' => 'OMNOMNOMNOM',
'parameters' => array(
'Param' => array(
array('Name' => 'firstName', 'Value' => 'Scott'),
array('Name' => 'lastName', 'Value' => 'Smith')
)
)
);
$result = $client->call('DoSomething', array($params),
'http://tempuri.org/webservices/DoSomething',
'http://tempuri.org/webservices/DoSomething');
print_r($result);
?>
</code></pre>
|
How can I style XML with CSS for viewing in a browser without first transforming to (X)HTML? <p>I know that CSS can be used to control the presentation of (X)HTML in modern browsers. I was under the impression that this was possible for arbitrary XML as well. (Am I mistaken?)</p>
<p><strong>A concrete example</strong>: given the following XML</p>
<pre><code><log>
<entry revision="1">
<author>J Random Hacker</author>
<message>Some pithy explanation</message>
</entry>
</log>
</code></pre>
<p>I'd like to associate a CSS with this XML such that when viewed in a modern (WebKit, FireFox) browser, I see something like:</p>
<pre><code>+----------------------------------+
| revision | 1 |
+----------------------------------+
| author | J Random Hacker |
+----------------------------------+
| message | Some pithy explanation|
+----------------------------------+
</code></pre>
<p>Where my oh-so-beautiful ascii-art is meant to indicate some table-like layout.</p>
<p>That is: XML+CSS --> "pixels for user" instead of XML+XSLT --> XHTML+CSS --> "pixels for user".</p>
<p>My hope is that this approach could be simpler way (for me) to present XML documents that are already document-like in their structure. I'm also just plain curious.</p>
|
<p>It is indeed possible to use CSS to format an XML document.</p>
<p><a href="http://www.w3schools.com/Xml/xml_display.asp" rel="nofollow">W3 schools example</a></p>
<p>(The W3C do recommend using xslt to do this sort of thing instead CSS though)</p>
|
Which style of Ruby string quoting do you favour? <p>Which style of Ruby string quoting do you favour? Up until now I've always used <code>'single quotes'</code> unless the string contains certain escape sequences or interpolation, in which case I obviously have to use <code>"double quotes"</code>.</p>
<p>However, is there really any reason not to just use double quoted strings everywhere?</p>
|
<p>Don't use double quotes if you have to escape them. And don't fall in "single vs double quotes" trap. Ruby has excellent support for arbitrary delimiters for string literals:</p>
<p><a href="http://rors.org/2008/10/26/dont-escape-in-strings">http://rors.org/2008/10/26/dont-escape-in-strings</a></p>
|
Can CCK take care of my fields for a programatically defined node type in drupal? <p>Does the CCK api allow me to create a node type, from a custom module, with a bunch of fields that use CCK to store their state? If so can these fields be locked so that users may not alter them, but still allow the user to add more fields to the node type?</p>
<p>Thanks</p>
|
<p>I <em>think</em> the answer to your first question is "yes" (for Drupal 6, at least, which has elements of the CCK integrated into Drupal Core). I believe the <a href="http://drupal.org/project/amazon" rel="nofollow" title="Amazon module">Amazon module</a> does this sort of thing, albeit it with just one field. </p>
<p>I don't think the idea in your second request is achievable, though. This would seem to require field-level permissions' control whilst Drupal only supports module-level permissions' control. </p>
|
Why does Log4Net run so slow in my Windows Service? <p>I have a windows service that uses log4net. We noticed that the service in question was running painfully slow so we attached a debugger to it and stepped through. It appears that each time it tries to write an entry to the log via log4net that it takes anywhere from 10 to 30 seconds before the next line of code can execute. Obviously this adds up...</p>
<p>The service is 2.0 .net
We're using log4Net 1.2.0.30714.
We've tested this on a machine running vista and a machine running win sever 2003 and have seen the same or similar results.</p>
|
<p>Jeff mentioned a performance problem with Log4Net in <a href="http://blog.stackoverflow.com/2008/09/podcast-20/" rel="nofollow">Podcast 20</a>. It's possible that you are seeing a similar issue.</p>
|
OpenCV Object Detection - Center Point <p>Given an object on a plain white background, does anybody know if OpenCV provides functionality to easily detect an object from a captured frame? </p>
<p>I'm trying to locate the corner/center points of an object (rectangle). The way I'm currently doing it, is by brute force (scanning the image for the object) and not accurate. I'm wondering if there is functionality under the hood that i'm not aware of.</p>
<p><strong>Edit Details</strong>:
The size about the same as a small soda can. The camera is positioned above the object, to give it a 2D/Rectangle feel. The orientation/angle from from the camera is random, which is calculated from the corner points.</p>
<p>It's just a white background, with the object on it (black). The quality of the shot is about what you'd expect to see from a Logitech webcam.</p>
<p>Once I get the corner points, I calculate the center. The center point is then converted to centimeters.</p>
<p>It's refining just 'how' I get those 4 corners is what I'm trying to focus on. You can see my brute force method with this image: <a href="http://i228.photobucket.com/albums/ee295/AOC_Ethanael/can.png">Image</a></p>
|
<p>There's already an example of how to do rectangle detection in OpenCV (look in samples/squares.c), and it's quite simple, actually.</p>
<p>Here's the rough algorithm they use:</p>
<pre><code>0. rectangles <- {}
1. image <- load image
2. for every channel:
2.1 image_canny <- apply canny edge detector to this channel
2.2 for threshold in bunch_of_increasing_thresholds:
2.2.1 image_thresholds[threshold] <- apply threshold to this channel
2.3 for each contour found in {image_canny} U image_thresholds:
2.3.1 Approximate contour with polygons
2.3.2 if the approximation has four corners and the angles are close to 90 degrees.
2.3.2.1 rectangles <- rectangles U {contour}
</code></pre>
<p>Not an exact transliteration of what they are doing, but it should help you.</p>
|
How do you check for ajax updates using a WebBrowser control in .net 2.0? <p>I have a web page that is being displaying in a winform app using the WebBrowser Control. I need to perform an event when the HTML in the web page changes; however, I cannot find an event that is triggered for situations when the pages is updated through Ajax. The DocumentComplete, FileDownloaded, and ProgressChanged events are not always triggered by Ajax requests. The only other way I can think to solve the issue is to poll the document object and look for changes; however, I don't think that is a very good solution. </p>
<p>Is there another event I am missing that will be triggered on an ajax update or some other way to solve the problem? </p>
<p>I am using C# and .net 2.0</p>
|
<p>I have been using a a timer, and just watching for a change in a specific elements content.</p>
<pre><code>Private AJAXTimer As New Timer
Private Sub WaitHandler1(ByVal sender As Object, ByVal e As System.EventArgs)
'Confirm that your AJAX operation has completed.
Dim ProgressBar = Browser1.Document.All("progressBar")
If ProgressBar Is Nothing Then Exit Sub
If ProgressBar.Style.ToLower.Contains("display: none") Then
'Stop listening for ticks
AJAXTimer.Stop()
'Clear the handler for the tick event so you can reuse the timer.
RemoveHandler AJAXTimer.Tick, AddressOf CoveragesWait
'Do what you need to do to the page here...
'If you will wait for another AJAX event, then set a
'new handler for your Timer. If you are navigating the
'page, add a handler to WebBrowser.DocumentComplete
End If
Exit Sub
Private Function InvokeMember(ByVal FieldName As String, ByVal methodName As String) As Boolean
Dim Field = Browser1.Document.GetElementById(FieldName)
If Field Is Nothing Then Return False
Field.InvokeMember(methodName)
Return True
End Function
</code></pre>
<p>I have 2 objects that get event handlers, the WebBrowser and the Timer.
I rely mostly on the DocumentComplete event on the WebBrowser and the Tick event on the Timer.</p>
<p>I write DocumentComplete or Tick handlers per action required, and each handler will usually RemoveHandler itself, so a successful event will only be handled once. I also have a procedure called RemoveHandlers that will remove all handlers from the browser and timer.</p>
<p>My AJAX commands usually look like:</p>
<pre><code>AddHandler AJAXTimer.Tick, AddressOf WaitHandler1
InvokeMember("ContinueButton", "click")
AJAXTimer.Start
</code></pre>
<p>My Navigate commands like:</p>
<pre><code>AddHandler Browser1.DocumentComplete, AddressOf AddSocialDocComp
Browser1.Navigate(NextURL) 'or InvokeMember("ControlName", "click") if working on a form.
</code></pre>
|
file path portability <p>I have a program that I need to run under *nix and windows. because the program takes file paths from files the issue is what to do about the <code>\</code> vs <code>/</code> issue. </p>
<p>My current thought is to put in a regex that converts the wrong one to the right one depending on what system I'm on. This will have the effect of letting either type work on either system. Aside from the fact that <a href="http://fishbowl.pastiche.org/2003/08/18/beware_regular_expressions/" rel="nofollow">now I have two problems</a>, does anyone see any other problems?</p>
<p>(Other better solutions are more than welcome)</p>
<p>Edit: the primary issue is getting windows paths to work on unix rather than the other way around.</p>
|
<p>The / is fully supported in win32 too.</p>
<p>Also see this <a href="http://stackoverflow.com/questions/122455/handling-file-paths-cross-platform">related question</a></p>
|
Email Notification Service <p>What are some ideas (using .NET and SQL 2005) for implementing a service that sends emails? The emails are to be data-driven. The date and time an email is to be sent is a field in a table.</p>
|
<p>I have built several high volume email notification services used to send data driven emails in the past. A few recommendations:</p>
<ul>
<li>Look into using a high quality email service provider that specializes in managing bounces, unsubscribes, isp and black list management, etc. If sending email is critical to your business, but not your main business it will be worth it. Most will have an api for sending templated messages, click tracking, open rates and will have provide triggers etc. </li>
<li>Look into the SQL Server Service Broker to queue the actual messages, otherwise you can consider Microsoft Message Queuing Services. There is no need to build your own queuing service. We spent too much time dealing with queing infrastructure code when this was already solved.</li>
<li>Develop a flexible set of events on your business tier to allow for the triggering of such messages and put them in your queue asynchronously, this will save you alot of grief in the long run as opposed to polling on the DB or hacking it in with Database triggers.</li>
</ul>
|
Create DB2 History Table Trigger <p>I want to create a history table to track field changes across a number of tables in DB2. </p>
<p>I know history is usually done with copying an entire table's structure and giving it a suffixed name (e.g. user --> user_history). Then you can use a pretty simple trigger to copy the old record into the history table on an UPDATE.</p>
<p>However, for my application this would use too much space. It doesn't seem like a good idea (to me at least) to copy an entire record to another table every time a field changes. So I thought I could have a generic 'history' table which would track individual field changes:</p>
<pre><code>CREATE TABLE history
(
history_id LONG GENERATED ALWAYS AS IDENTITY,
record_id INTEGER NOT NULL,
table_name VARCHAR(32) NOT NULL,
field_name VARCHAR(64) NOT NULL,
field_value VARCHAR(1024),
change_time TIMESTAMP,
PRIMARY KEY (history_id)
);
</code></pre>
<p>OK, so every table that I want to track has a single, auto-generated id field as the primary key, which would be put into the 'record_id' field. And the maximum VARCHAR size in the tables is 1024. Obviously if a non-VARCHAR field changes, it would have to be converted into a VARCHAR before inserting the record into the history table.</p>
<p>Now, this could be a completely retarded way to do things (hey, let me know why if it is), but I think it it's a good way of tracking changes that need to be pulled up rarely and need to be stored for a significant amount of time. </p>
<p>Anyway, I need help with writing the trigger to add records to the history table on an update. Let's for example take a hypothetical user table:</p>
<pre><code>CREATE TABLE user
(
user_id INTEGER GENERATED ALWAYS AS IDENTITY,
username VARCHAR(32) NOT NULL,
first_name VARCHAR(64) NOT NULL,
last_name VARCHAR(64) NOT NULL,
email_address VARCHAR(256) NOT NULL
PRIMARY KEY(user_id)
);
</code></pre>
<p>So, can anyone help me with a trigger on an update of the user table to insert the changes into the history table? My guess is that some procedural SQL will need to be used to loop through the fields in the old record, compare them with the fields in the new record and if they don't match, then add a new entry into the history table. </p>
<p>It'd be preferable to use the same trigger action SQL for every table, regardless of its fields, if it's possible.</p>
<p>Thanks!</p>
|
<p>I don't think this is a good idea, as you generate even more overhead per value with a big table where more than one value changes. But that depends on your application.</p>
<p>Furthermore you should consider the practical value of such a history table. You have to get a lot of rows together to even get a glimpse of context to the value changed and it requeries you to code another application that does just this complex history logic for an enduser. And for an DB-admin it would be cumbersome to restore values out of the history.</p>
<p>it may sound a bit harsh, but that is not the intend. An experienced programmer in our shop had a simmilar idea through table journaling. He got it up and running, but it ate diskspace like there's no tomorrow. </p>
<p>Just think about what your history table should really accomplish.</p>
|
How do I get projects to place their build output into the same directory with Scons? <h2>Background</h2>
<p>I'm trying out Scons by setting up a basic C++ sample project that has two sub-projects: </p>
<ul>
<li>Prj1 is an EXE that depends on Prj2</li>
<li>Prj2 is a DLL that exports some functions</li>
</ul>
<p>The problem I'm running into is that the library builds its .obj, .pdb, .lib, .dll, etc. files in the same directory as it's SConscript file while the EXE builds its files in the same directory as its SConscript. The application successfully builds both the Prj2 dependency and itself. However, you cannot run the resulting EXE because it can't find the library it needs because it is in the other directory.</p>
<h2>Question</h2>
<p>How can I get multiple projects that have dependences to output their binaries and debug information into a common directory so that they can be executed and debugged?</p>
<h2>Potential Solutions</h2>
<p>This is what I have thought of so far:</p>
<ul>
<li>I tried using VariantDir (previously called BuildDir) however this doesn't seem to work. Perhaps I'm messing something up here.</li>
<li>I could potentially tell the compiler and the linker explicitly (via Fo/Fd for example) where to drop their files (is this the best or only solution???)</li>
<li>Execute a copy command on the resulting binaries (this seems like a hack and quite a pain to manage/maintain)</li>
</ul>
<h2>Update</h2>
<p>I updated the File Structure and file contents below to reflect the working solution in it's entirety. Thanks to grieve for his insight.</p>
<h2>Command</h2>
<p>With this configuration, you must unfortunately execute the build by cd'ing to the build directory and then running the command below. I need to get a properly working alias setup to get around this.</p>
<pre><code>
build> scons ../bin/project1.exe
</code></pre>
<h2>File Structure</h2>
<pre><code> /scons-sample
/bin
/release
/debug
/build
SConstruct
scons_helper.py
/prj1
SConscript
/include
/src
main.cpp
/prj2
SConscript
/include
functions.h
/src
functions.cpp
</code></pre>
<h2>SConstruct</h2>
<pre><code>
import os.path
BIN_DIR = '../bin'
OBJ_DIR = './obj'
#--------------------------------------
# CxxTest Options
#--------------------------------------
CXXTEST_DIR = '../extern/CxxTest/CxxTest-latest'
PERL = 'perl -w'
TESTS = '*.h'
TESTGEN = PERL + CXXTEST_DIR + '/cxxtestgen.pl'
CXXTESTGEN_FLAGS = '--runner=ParenPrinter \
--abort-on-fail \
--have-eh'
#--------------------------------------
# Options
#--------------------------------------
SetOption( 'implicit_cache', 1 )
# command line options
opts = Options()
opts.AddOptions(
EnumOption(
'debug',
'Debug version (useful for developers only)',
'no',
allowed_values = ('yes', 'no'),
map = { },
ignorecase = 1
)
)
#--------------------------------------
# Environment
#--------------------------------------
env = Environment(
options = opts,
#--------------------------------------
# Linker Options
#--------------------------------------
LIBPATH = [
'../extern/wxWidgets/wxWidgets-latest/lib/vc_dll'
],
LIBS = [
# 'wxmsw28d_core.lib',
# 'wxbase28d.lib',
# 'wxbase28d_odbc.lib',
# 'wxbase28d_net.lib',
'kernel32.lib',
'user32.lib',
'gdi32.lib',
'winspool.lib',
'comdlg32.lib',
'advapi32.lib',
'shell32.lib',
'ole32.lib',
'oleaut32.lib',
'uuid.lib',
'odbc32.lib',
'odbccp32.lib'
],
LINKFLAGS = '/nologo /subsystem:console /incremental:yes /debug /machine:I386',
#--------------------------------------
# Compiler Options
#--------------------------------------
CPPPATH = [
'./include/',
'../extern/wxWidgets/wxWidgets-latest/include',
'../extern/wxWidgets/wxWidgets-latest/vc_dll/mswd'
],
CPPDEFINES = [
'WIN32',
'_DEBUG',
'_CONSOLE',
'_MBCS',
'WXUSINGDLL',
'__WXDEBUG__'
],
CCFLAGS = '/W4 /EHsc /RTC1 /MDd /nologo /Zi /TP /errorReport:prompt'
)
env.Decider( 'MD5-timestamp' ) # For speed, use timestamps for change, followed by MD5
Export( 'env', 'BIN_DIR' ) # Export this environment for use by the SConscript files
#--------------------------------------
# Builders
#--------------------------------------
SConscript( '../prj1/SConscript' )
SConscript( '../prj2/SConscript' )
Default( 'prj1' )
</code></pre>
<h2>scons_helper.py</h2>
<pre><code>
import os.path
#--------------------------------------
# Functions
#--------------------------------------
# Prepends the full path information to the output directory so that the build
# files are dropped into the directory specified by trgt rather than in the
# same directory as the SConscript file.
#
# Parameters:
# env - The environment to assign the Program value for
# outdir - The relative path to the location you want the Program binary to be placed
# trgt - The target application name (without extension)
# srcs - The list of source files
# Ref:
# Credit grieve and his local SCons guru for this:
# http://stackoverflow.com/questions/279860/how-do-i-get-projects-to-place-their-build-output-into-the-same-directory-with
def PrefixProgram(env, outdir, trgt, srcs):
env.Program(target = os.path.join(outdir, trgt), source = srcs)
# Similar to PrefixProgram above, except for SharedLibrary
def PrefixSharedLibrary(env, outdir, trgt, srcs):
env.SharedLibrary(target = os.path.join(outdir, trgt), source = srcs)
def PrefixFilename(filename, extensions):
return [(filename + ext) for ext in extensions]
# Prefix the source files names with the source directory
def PrefixSources(srcdir, srcs):
return [os.path.join(srcdir, x) for x in srcs]
</code></pre>
<h2>SConscript for Prj1</h2>
<pre><code>
import os.path
import sys
sys.path.append( '../build' )
from scons_helper import *
Import( 'env', 'BIN_DIR' ) # Import the common environment
prj1_env = env.Clone() # Clone it so we don't make changes to the global one
#--------------------------------------
# Project Options
#--------------------------------------
PROG = 'project1'
#--------------------------------------
# Header Files
#--------------------------------------
INC_DIR = [
'../prj2/include'
]
HEADERS = [
''
]
#--------------------------------------
# Source Files
#--------------------------------------
SRC_DIR = './src'
SOURCES = [
'main.cpp'
]
# Prefix the source files names with the source directory
SOURCES = PrefixSources( SRC_DIR, SOURCES )
#--------------------------------------
# Compiler and Linker Overrides
#--------------------------------------
prj1_env.Append(
CPPPATH = INC_DIR,
LIBS = 'project2',
LIBPATH = BIN_DIR,
# Microsoft Visual Studio Specific
PDB = os.path.join( BIN_DIR, PROG + '.pdb' )
)
#--------------------------------------
# Builders
#--------------------------------------
PrefixProgram( prj1_env, BIN_DIR, PROG, SOURCES )
</code></pre>
<h2>SConscript for Prj2</h2>
<pre><code>
import os.path
import sys
sys.path.append( '../build' )
from scons_helper import *
Import( 'env', 'BIN_DIR' ) # Import the common environment
prj2_env = env.Clone() # Clone it so we don't make changes to the global one
#--------------------------------------
# Project Options
#--------------------------------------
PROG = 'project2'
#--------------------------------------
# Header Files
#--------------------------------------
INC_DIR = [
''
]
HEADERS = [
'functions.h'
]
#--------------------------------------
# Source Files
#--------------------------------------
SRC_DIR = './src/'
SOURCES = [
'functions.cpp'
]
# Prefix the source files names with the source directory
SOURCES = PrefixSources( SRC_DIR, SOURCES )
#--------------------------------------
# Compiler and Linker Overrides
#--------------------------------------
# Update the environment with the project specific information
prj2_env.Append(
CPPPATH = INC_DIR,
# Microsoft Visual Studio Specific
PDB = os.path.join( BIN_DIR, PROG + '.pdb' )
)
#--------------------------------------
# Builders
#--------------------------------------
PrefixSharedLibrary( prj2_env, BIN_DIR, PROG, SOURCES )
</code></pre>
|
<p>Ok Third try is a charm. I am just placing this in a new answer to keep it cleaner. I talked with my local scons guru, and he stated that the install method should work, but there is a much easier way.</p>
<p>Simply define the full path where you want the executable (or dll) to go. So:</p>
<pre><code>prj2_env.Program(target = os.path.join(BIN_DIR,PROG), source = SOURCES )
</code></pre>
<p>If you don't want to have to do this in all places you can make a global function:</p>
<pre><code>def PrefixProgram(env, trgt, srcs):
env.Program(target = os.path.join(env.["MY_OUTPUT_DIR"], trgt), source = srcs)
</code></pre>
<p>Then in your SConscript, something like:</p>
<pre><code>import ('PrefixProgram')
# stuff ...
PrefixProgram(prj2_env, PROG, SOURCES)
</code></pre>
<p>Note that you can add your own attribute to the environment, which is where the</p>
<pre><code>env["MY_OUTPUT_DIR"]
</code></pre>
<p>comes from. I wrote this off the cuff, so expect some minor syntax errors and what not. Obviously you can apply the same trick for shared and static libraries.</p>
<p>In the interest of full disclosure I offered my local scons guru the chance to answer this himself, but he was scared he would become addicted to the site and declined. :)</p>
|
Where can I find sample code on mouse movements and polygon spins in OpenGL? <p>Where can I find sample code on mouse movements and polygon spins in OpenGL?
I am using Java, so sample code in Java is preferred.</p>
|
<p>You'd probably find this useful:</p>
<p><a href="http://pepijn.fab4.be/software/nehe-java-ports/" rel="nofollow">http://pepijn.fab4.be/software/nehe-java-ports/</a></p>
|
Corner radius in Adobe Air application <p>How can we make rounded corners on the vbox control in the Air
application?</p>
<p>I am hiding the header and setting transparent to true, but then it does not show
me rounded corners on the VBox in the application. I am showing this VBox
to the user.</p>
<p>Thanks in advance.</p>
|
<p>You can do this by implementing a custom Border:</p>
<pre><code>package your.package
{
import flash.display.*;
import flash.geom.*;
import flash.utils.*;
import mx.skins.halo.HaloBorder;
import mx.utils.GraphicsUtil;
public class RoundedBorder extends HaloBorder
{
private var topCornerRadius:Number;
private var bottomCornerRadius:Number;
private var setup:Boolean;
/**
* Get the CSS style attributes from the element to which to apply this
* gradient.
*/
private function readElementCssStyles():void
{
topCornerRadius = getStyle("cornerRadius") as Number;
if (!topCornerRadius)
{
topCornerRadius = 0;
}
bottomCornerRadius = getStyle("bottomCornerRadius") as Number;
if (!bottomCornerRadius)
{
bottomCornerRadius = topCornerRadius;
}
}
/**
* Paint the gradient background.
*
* @param unscaledWidth
* @param unscaledHeight
*
*/
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var rectWidth:Number
= unscaledWidth - this.borderMetrics.left - this.borderMetrics.right;
var rectHeight:Number
= unscaledHeight - this.borderMetrics.top - this.borderMetrics.bottom;
readElementCssStyles();
var topRadius:Number = Math.max(topCornerRadius-2, 0);
var bottomRadius:Number = Math.max(bottomCornerRadius-2, 0);
GraphicsUtil.drawRoundRectComplex(this.graphics,
this.borderMetrics.left,
this.borderMetrics.top,
rectWidth,
rectHeight,
topRadius,
topRadius,
bottomRadius,
bottomRadius);
}
}
}
</code></pre>
<p>Then in your MXML application you have to define a CSS class for your VBox like this:</p>
<pre><code> <mx:Style>
.roundedBorder
{
border-style:solid;
border-thickness: 1;
border-skin: ClassReference("your.package.RoundedBorder");
corner-radius: 5;
}
</mx:Style>
</code></pre>
<p>I have ripped this code out of a more complex class. Hope I did not forgot anything and that it will work as posted.</p>
|
3D laser scanner capturing normals? <p>The Lab university I work at is in the process of purchasing a laser scanner for scanning 3D objects. All along from the start we've been trying to find a scanner that is able to capture real RAW normals from the actual scanned surface. It seems that most scanners only capture points and then the software interpolates to find the normal of the approximate surface.</p>
<p>Does anybody know if there is actually such a thing as capturing raw normals? Is there a scanner that can do this and not interpolate the normals from the point data?</p>
|
<p>Highly unlikely. Laser scanning is done using ranges. What you want would be combining two entirely different techniques. Normals could be evaluated with higher precision using well controlled lighting etc, but requiring a very different kind of setup. Also consider the sampling problem: What good is a normal with higher resolution than your position data?</p>
|
i18n - best practices for internationalization - XLIFF, gettext, INI, ...? <p>EDIT: <strong>I would really like to see some general discussion about the formats, their pros and cons!</strong></p>
<p>EDIT2: The 'bounty didn't really help to create the needed discussion, there are a few interesting answers but the comprehensive coverage of the topic is still missing. Six persons marked the question as favourites, which shows me that there is an interest in this discussion.</p>
<p>When deciding about <strong>internationalization</strong> the toughest part IMO is the choice of storage format.</p>
<p>For example the Zend PHP Framework offers the following adapters which cover pretty much all my options:</p>
<ul>
<li>Array : no, hard to maintain</li>
<li><strong>CSV : don't know, possible problems with encoding</strong></li>
<li><strong>Gettext : frequently used, poEdit for all platforms available BUT complicated</strong></li>
<li><strong>INI : don't know, possible problems with encoding</strong></li>
<li>TBX : no clue</li>
<li>TMX : too much of a big thing? no editors freely available.</li>
<li>QT : not very widespread, no free tools</li>
<li><strong>XLIFF : the comming standard? BUT no free tools available.</strong></li>
<li>XMLTM : no, not what I need</li>
</ul>
<p>basically I'm stuck with the 4 'bold' choices. I would like to use INI files but I'm reading about the encoding problems... is it really a problem, if I use strict UTF-8 (files, connections, db, etc.)?</p>
<p>I'm on Windows and I tried to figure out how poEdit functions but just didn't manage. No tutorials on the web either, is <strong>gettext</strong> still a choice or an endangered species anyways?</p>
<p>What about <strong>XLIFF</strong>, has anybody worked with it? Any tips on what tools to use?</p>
<p>Any ideas for <strong>Eclipse</strong> integration of any of these technologies?</p>
|
<p>POEdit isn't really hard to get a hang of. Just create a new .po file, then tell it to import strings from source files. The program scans your PHP files for any function calls matching <code>_("Text"), gettext("Text")</code>, etc. You can even specify your own functions to look for.</p>
<p>You then enter a translation in the appropriate box. When you save your .po file, a .mo file is automatically generated. That's just a binary version of the translations that gettext can easily parse. </p>
<p>In your PHP script make a call to <code>bindtextdomain()</code> telling it where your .mo file is located. Now any strings passed to <code>gettext</code> (or the underscore function) will be translated.</p>
<p>It makes it really easy to keep your translation files up to date. POEdit also has some neat features like allowing comments, showing changed and dropped strings and allowing fuzzy matches, which means you don't have to re-translate strings that have been slightly modified.</p>
|
Does LINQ to Entities reuse instances of objects? <p>Using LINQ to Entities sounds like a great way to query against a database and get actual CLR objects that I can modify, data bind against and so forth. But if I perform the same query a second time do I get back references to the same CLR objects or an entirely new set? </p>
<p>I do not want multiple queries to generate an ever growing number of copies of the same actual data. The problem here is that I could alter the contents of one entity and save it back to the database but another instance of the entity is still in existence elsewhere and holding the old data.</p>
|
<p>Within the same DataContext, my understanding is that you'll always get the same objects - for queries which return full objects instead of projections.</p>
<p>Different DataContexts will fetch different objects, however - so there's a risk of seeing stale data there, yes.</p>
|
Enabling/Disabling Aero from a Windows Service <p>I have some code to enable/disable the Windows Aero service in Vista, and I would like to run it in a Windows Service. The code works in a standalone application, but when I run it from a Service, nothing happens. No errors or exceptions are thrown.</p>
<p>I realise that running code in a service is a different scope than running code in an application, but in this case, how would I enable/disable Aero from the service? Is this even possible? </p>
<p>Here is the code I am working with:</p>
<pre><code>public static readonly uint DWM_EC_DISABLECOMPOSITION = 0;
public static readonly uint DWM_EC_ENABLECOMPOSITION = 1;
[DllImport("dwmapi.dll", EntryPoint="DwmEnableComposition")]
protected static extern uint Win32DwmEnableComposition(uint uCompositionAction);
public static bool EnableAero()
{
Win32DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
}
</code></pre>
<p>Edit: </p>
<p>It turns out that the DwmEnableComposition call is returning HRESULT 0x80070018, or ERROR_BAD_LENGTH. Seems like a strange error, since the code works when not running as a service.</p>
<p>I also tried changing the entire thing to the following code, but got the same result. It sets the window station and desktop, and it seems to be correct, but the call to DwmEnableComposition results in the same error. I've not included the PInvoke declarations for brevity.</p>
<pre><code> protected override void OnStop()
{
IntPtr winStation = OpenWindowStation("winsta0", true, 0x10000000 /* GENERIC_ALL */);
if (winStation == null || winStation.ToInt32() == 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
if (!SetProcessWindowStation(winStation))
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
uint thread = GetCurrentThreadId();
IntPtr hdesk = OpenInputDesktop(0, false, 0x10000000 /* GENERIC_ALL */);
if (hdesk == null || hdesk.ToInt32() == 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
if (!SetThreadDesktop(hdesk))
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
uint result = Win32DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
if (result != 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
}
</code></pre>
|
<p>I had the same error code, when creating WPF FlowDocuments through a service running under 64-bit Vista. After digging around I can accross <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361469" rel="nofollow">this post on Microsoft Connect</a>, which points out that </p>
<blockquote>
<p>"... The problem is caused by an interop problem with the DWM ..."</p>
</blockquote>
<p>and</p>
<blockquote>
<p>"... it will fix the WPF crash in all
services including IIS7 ..."</p>
</blockquote>
<p>Here is the direct link to the hot-fix downloads; <a href="http://support.microsoft.com/kb/959209" rel="nofollow">KB 959209</a> </p>
<p>This fixed our problems with running unit tests through CruiseControl.Net (CCNet) running 64-bit Vista. The tests where fine when not running through a service.</p>
|
Java File.canWrite() on Vista and super hidden files <p>I have some code that effectively does this :</p>
<pre><code>File file = new File("C:\\Program Files (x86)\\Something\\fred.txt");
System.out.println("file.canWrite() = " + file.canWrite());
</code></pre>
<p>It prints true.
Now the odd thing is, I can create the file without any exceptions. Furthermore, another program can read the file I've created. The thing is, in Windows Explorer, the file doesn't show up at all!</p>
<p>Show hidden files you may be thinking, but no, I've got that option turned on.</p>
<p>I've also found out about 'super hidden files' in Vista, so I've turned that option on and I still can't see the file! Maybe I haven't edited my registry correctly - I can only assume the file is super hidden - where else could it be?</p>
<p>Now the problem is that I'm creating an html file and the when I fire up a browser, it can't see the html file because it's super hidden.</p>
<p>How can I prevent Java creating a super hidden file? This is running under JRE 6 update 6.</p>
|
<p>You are most likely a "victim" of folder redirection. When UAC is enabled, any writes to Program Files is redirected to somewhere else when you're not running the program as an administrator.</p>
<p>You should find your file in C:\Users\<username>\AppData\Local\VirtualStore\<insert>\<expected>\<path>\<here>.</p>
<p>The proper fix, of course, is to not write to Program Files in the first place. Instead, use somewhere in the user's home directory (the exact location you should write to depends on the purpose of the app).</p>
|
Random image picker PHP <pre><code>$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";
$i = 0;
*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";
$boxes = array();
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
//echo $rand;
$slice = array_splice($images, $rand);
$boxes[$i] = $slice;
$i++;
}*
</code></pre>
<p>I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated</p>
<p>UPDATE</p>
<p>I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?</p>
<pre><code>$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
$i++;
}
</code></pre>
|
<p>This might be a nicer way of doing it:</p>
<pre><code>foreach (array_rand($images, 5) as $key) {
$boxes[] = $images[$key];
}
</code></pre>
|
Alternative to HttpListener? <p>I'm developing an application that is so far using HttpListener to provide a small standalone http server. However, I've recently discovered that HttpListener needs to be run as Administrator, which is not always going to be possible.</p>
<p>What would the best alternative be? I need http GET and POST, both of which are not simply reading/writing files on the filesystem, they need to run custom .Net code.</p>
<p>My research so far has brought up Cassini, but as far as I can tell, I would have to write a custom version. Is there anything else? In partiular something with the same interface as HttpListener, but that does not require Administrator privileges would be amazing!</p>
|
<p>One alternative that I've found is <a href="http://www.codeplex.com/webserver">C# Webserver</a> on CodePlex.</p>
<p><i>"... a flexible http server which can be embedded in any .Net application. It has a modular design where features are added using modules. The server also supports REST and all http verbs ..."</i></p>
<p>It has an HttpListener class which I imagine is similar to System.Net.HttpListener, but I haven't used either one of them yet so I can't be certain.</p>
|
How do I automatically fail a nant build if NDepend query raises a warning <p>OK first some background. I am busy automating our build process. We run a mixture of Vs 2005 and VS 2008 both targeting platform 2.0. We use Nant to do our builds using the MSBUILD task to do the compile and Cruise Control .net to do our CI. Currently we treat all warnings as errors, fail the build if any FxCop rules fail (except a small subset that we disabled), fail the build if Simian detects any code duplication of more than 5 lines across all projects.</p>
<p>I have written NDepend CQL query to enforce a few rules that are hard to implement in FxCop. I want to fail the build if the number of lines in a method/class breach a certain limit. I also want to fail if the cyclomatic complexity of a method is too high.</p>
<p>I can easily run NDepend as part of my build. But I can't get the build to fail if my CQL queries return results > 0</p>
<p>So this is the question:</p>
<ol>
<li>Has anybody tried something
similar? </li>
<li>Is there a Nant task
that supports this? </li>
<li>If there is
a Nant task that calls NDepend, but
doesn't fail the build is the source
available so I can add this feature?</li>
</ol>
<p>Thanks,
Stephen</p>
|
<p>What we do is actually have a powershell script run right after that parses through the output file, and throws a series of errors with an appropriate message depending on which condition it found. As soon as powershell throws an error the build fails.</p>
|
Calling a C function with a varargs argument dynamically <p>I am programming in C against a third party library (in HP/Mercury Loadrunner) that allows a varargs-style variable size argument list for one of it's functions. I want to call this function but I do not know up front how many arguments I will have. </p>
<p>There is a function made by one of my predecessors that serves somewhat but the problem here is that this function assumes the worst case scenario (over 3000 arguments) and hand-codes for that.</p>
<p>To illuminate, here's the (beginning of) the code. The function we call is <code>web_submit_data()</code>. It will HTTP post a set of form data. This implementation came about when dealing with dynamically generated forms with an arbitrary number of fields.
(Cleaned up a fair bit from the original, which hand coded indexes by hand as well..)</p>
<p><hr /></p>
<pre><code>web_submit_data_buffer_gazillion_items( const char *bufferName, const char *bufferValue)
{
const int size = 129;
int i = 0;
int j = 11;
web_submit_data(&bufferName[i++ * size], //"some form"
&bufferName[i++ * size], //"Action=https://blah.blah/form");
&bufferName[i++ * size], //"Method=POST");
&bufferName[i++ * size], //"TargetFrame=");
&bufferName[i++ * size], //"RecContentType=text/html");
&bufferName[i++ * size], //"Referer=https://blah.blah/index.html");
&bufferName[i++ * size], //"Snapshot=t1.inf");
&bufferName[i++ * size], //"Mode=HTML");
ITEMDATA, // missing in action: indexes 8 through 10
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
..
(repeat the last 3 lines ad nauseum)
..
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size]);
}
</code></pre>
<p>Now I have found an external library that might work (<a href="http://www.dyncall.org">http://www.dyncall.org</a>) but I would much rather not a) be completely processor dependant and b) attempt to teach Loadrunner about linking in external sources..</p>
<p>Edit:
The original function used hardcoded indexes instead of using a variable. Can still revert to that if it turns out to be too unpredictable. However, as I am unlikely to run this with a different compiler or hardware / OS I doubt that really is worth it.</p>
<p>Also: I don't have control over the implementation of web_submit_data(). So just pushing the problem down one level isn't going to cut it..</p>
<p>Another thing to note: The spec for <code>web_submit_data()</code> uses a constant called LAST to mark the end of the argument list. The original implementation doesn't use it. Presumably the callsite does ..</p>
|
<p>Variable length arguments are basically just a pointer to a bunch of packed data that is passed to the required function. It is the responsibility of the called function to interpret this packed data.</p>
<p>The architecture safe way to do this is to use the va_list macros (that n-alexander mentioned), otherwise you may run into issues with how various data types are padded in memory.</p>
<p>The proper way to design varargs functions is to actually have two versions, one that accepts the '...', which in turn extracts the va_list and passes it to a function that takes a va_list. This way you can dynamically construct the arguments if you need to and can instead call the va_list version of the function.</p>
<p>Most standard IO functions have varargs versions: vprintf for printf, vsprintf for sprintf... you get the idea. See if your library implements a function named "vweb_submit_data" or something to that effect. If they don't, email them and tell them to fix their library.</p>
<p>3000 lines of the same thing (even if it is preprocessor induced) makes me cringe</p>
|
Protecting Javascript Code in a FF extension <p>I am looking to protect the code of my Firefox extension because it has server calls in it that no would be a security risk if someone could make them outside of the extension. Any suggestions on how to encrypt it?</p>
|
<p>This is basically impossible. You want to give executable code to an untrusted client that has "secret" calls in it, yet not let the client know the secrets? How, then, is it going to execute the code?</p>
<p>At some point, it must be decrypted. Which means the client has everything it needs to perform the decryption, which means a user can do it, and build a malicious version of your extension.</p>
<p>The only choice you have is to redesign such that vulnerable services are not publically exposed.</p>
|
RegEx to replace value including new lines <p>I have a snippet looking something like the below.</p>
<pre><code>string bodyTypeAssemblyQualifiedName = "XXX.XX.XI.CustomerPayment.Schemas.r1.CustomerPayments_v01, XXX.XX.XI.CustomerPaym" +
"ent.Schemas.r1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ac564f277cd4488" +
"e";
</code></pre>
<p>I'd like use regular expression in C# to get it to: </p>
<pre><code>string bodyTypeAssemblyQualifiedName = null;
</code></pre>
<p>I've tried using a RegEx like the below but it doesn't match the newlines ...</p>
<pre><code>bodyTypeAssemblyQualifiedName\s=\s(?<location>.*?);
</code></pre>
|
<p>This works:</p>
<blockquote>
<p>(?<=string\sbodyTypeAssemblyQualifiedName\s=\s)(?s:[^;]*)(?=;)</p>
</blockquote>
<p>Which is the equivalent of:</p>
<ol>
<li>After the string "string
bodyTypeAssemblyQualifiedName = "</li>
<li>Turn on single line (treat \r\n as
any other character) ( this is what
(?s: ) does)</li>
<li>match every character that is not a semicolon</li>
<li>until a single semicolon is reached</li>
</ol>
|
Is there a good HttpClient library for J2ME/MIDP? <p>I want to call some RESTful web services from a J2ME client running on a MIDP enabled mobile device. I read the MIDP api for HTTPConnections and thought this is just crying out for a simple wrapper to hide all those unpleasant byte arrays and such like. Before I write my own I wondered whether there was a good open source library already available.</p>
<p>-FE- </p>
|
<p>You might want to check out this little gem, Mobile Ajax for Java ME:</p>
<p><a href="https://meapplicationdevelopers.java.net/mobileajax.html" rel="nofollow">https://meapplicationdevelopers.java.net/mobileajax.html</a></p>
<p>One part is (from the site):</p>
<blockquote>
<p>Asynchronous I/O for Java ME</p>
<p>This library provides the equivalent
of XmlHttpRequest for Java ME with
some additional functionality useful
for invoking RESTful web services.</p>
<p>It is layered on top of the
com.sun.me.web.path library. Features
include -</p>
<pre><code>* Asynchronous versions of HTTP Get and Post
* HTTP Basic Authentication
* Multipart MIME (sender only)
* Progress listeners
</code></pre>
</blockquote>
|
Win32 WriteProcessMemory() magical offset value <p>I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "magic" value that I got lucky with and picked at random during a moment of frustration, the call works on my system, but fails on other ones. (see the code below)</p>
<p>Can anybody suggest what this magical offset is doing for me? By trial and error, I can find values that work on specific systems, but I can't find a general solution to this problem.</p>
<p>Thanks,
PaulH</p>
<pre><code>#define MAGIC_OFFSET (DWORD)0x01020000
LVHITTESTINFO hti = { 0 };
hti.pt = clientPoint;
LPVOID lpBuffer = ::VirtualAlloc( NULL, 1, MEM_RESERVE, PAGE_READWRITE );
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
lpBuffer = ::VirtualAlloc( (LPVOID)((DWORD)lpBuffer + MAGIC_OFFSET), sizeof( hti ), MEM_RESERVER, PAGE_READWRITE );
DWORD dwBuffer = (DWORD)lpBuffer + MAGIC_OFFSET - sizeof( hti );
if( !::WriteProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
if( ListView_HitTest( hWndListView, (LPVOID)dwBuffer ) < 0 )
return 0;
if( !::ReadProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
</code></pre>
<p>Clarification (added by Cd-MaN): this is on a Windows Mobile platform, probably non-x86 architecture. So the situation may be different (are there separate address spaces in ARM processors?).</p>
|
<p>Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of <a href="http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx" rel="nofollow">shared memory</a>, and I did a quick check to make sure these functions are supported by <a href="http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx" rel="nofollow">Windows Mobile 5</a>.</p>
|
Unpacking MSI in .Net <p>I have an installer that deploys web services to IIS. After this has finshed a custom action fires that updates the database with the scripts required by the webservices. The scripts are currently deploying to IIS aswell because they are part of the .net project. How can I configure the installation process so the scripts arn't part of the project and get un-packed from the MSI so my custom action can access them?</p>
|
<p>If you are using the standard Visual Studio setup projects do this:</p>
<ol>
<li>Add your scripts as files to your setup project</li>
<li>Right-click on the files</li>
<li>Select "Properties"</li>
<li>Change the "PackageAs" property to "vsdpaLoose"</li>
</ol>
<p>Your files will now be output alongside your MSI so will be available at any time.</p>
|
Is it possible to use/access scalar functions with LINQ to SQL? <p>We have scalar functions in our database for returning things like "number of tasks for a customer" or "total invoice amount for a customer". </p>
<p>We are experimenting and looking to try to do this w/o stored procedures ... normally we would just call this function in our stored procedure and return it as a single value. </p>
<p>Is there a way to use or access scalar functions with LINQ to SQL? If so, I would be interested in see an example of how to ... if not, how would it be best to handle this type of situation ... if it is even doable.</p>
|
<p>LINQ-to-SQL supports use with UDFs, if that is what you mean. Just drag the UDF onto the designer surface and you're done. This creates a matching method on the data-context, marked <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.functionattribute.aspx"><code>[Function(..., IsComposable=true)]</code></a> or similar, telling LINQ-to-SQL that it can use this in queries (note that EF doesn't support this usage).</p>
<p>You would then use it in your query like:</p>
<pre><code>var qry = from cust in ctx.Custs
select new {Id = cust.Id, Value = ctx.GetTotalValue(cust.Id)};
</code></pre>
<p>which will become TSQL something like:</p>
<pre><code>SELECT t1.Id, dbo.MyUdf(t1.Id)
FROM CUSTOMER t1
</code></pre>
<p>(or there-abouts).</p>
<p>The fact that it is composable means that you can use the value in queries - for example in a <code>Where()</code>/<code>WHERE</code> - and so reduce the data brought back from the server (although obviously the UDF will still need to be executed in some way).</p>
<p><a href="http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/608b6b08532ed7eb/4cf42640934bf45e#bfc790be1a24e37a">Here's a similar example</a>, showing a pseudo-UDF at use on a data-context, illustrating that the C# version of the method is not used.</p>
<p>Actually, I'm currently looking at such UDFs to provide "out of model" data in a composable way - i.e. a particular part of the system needs access to some data (that happens to be in the same database) that isn't really part of the same model, but which I want to <code>JOIN</code> in interesting ways. I also have existing SPs for this purpose... so I'm looking at porting those SPs to tabular UDFs, which provides a level of contract/abstraction surrounding the out-of-model data. So because it isn't part of my model, I can only get it via the UDF - yet I retain the ability to compose this with my regular model.</p>
|
RGB back buffer in Win32 <p>I have an array of RGB values, whose size I can guarantee to match the client area of a window on screen.</p>
<p>Using the Win32 API, what are the easiest and fastest ways to get the contents of my array on the screen in response to a WM_PAINT message?</p>
<p>If it makes it simpler/faster, we can assume it's a 32-bit display and each element of the array is 32 bits.</p>
|
<p>If you have complete control over your backing format, use a DIB format and a dummy BITMAPINFO structure. Then use <a href="http://msdn.microsoft.com/en-us/library/ms532346(VS.85).aspx" rel="nofollow">SetDIBitsToDevice</a> to copy to the DC.</p>
<p>Be aware of the peculiarities of the DIB format - every line has to be extended to a multiple of 4 bytes, the first line of the buffer is the bottom line of the image, and the byte order is Blue,Green,Red.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.