input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
---|---|
Running JIRA on a VM <p>Anyone have any success or failure running Jira on a VM?</p>
<p>I am setting up a new source control and defect tracking server. My server room is near full and my services group suggested a VM. I saw that a bunch of people are running SVN on VM (including NCSA). The VM would also free me from hardware problems and give me high availability. Finally, it frees me from some red tape and it can be implemented faster.</p>
<p>So, does anyone know of any reason why I shouldn't put Jira on a VM?</p>
<p>Thanks</p>
|
<p>We just did the research for this, this is what we found:</p>
<ul>
<li>If you are planning to have a small number of projects (10-20) with 1,000 to 5,000 issues in total and about 100-200 users, a recent server (2.8+GHz CPU) with 256-512MB of available RAM should cater for your needs.</li>
<li>If you are planning for a greater number of issues and users, adding more memory will help. We have reports that allocating 1GB of RAM to JIRA is sufficient for 100,000 issues.</li>
<li>For reference, Atlassian's JIRA site (http://jira.atlassian.com/) has over 33,000 issues and over 30,000 user accounts. The system runs on a 64bit Quad processor. The server has 4 GB of memory with 1 GB dedicated to JIRA.</li>
</ul>
<p>For our installation (<10000 issues, <20 concurrent sessions at a time) we use very little server resources (<1GB Ram, running on a quad-core processor we typically use <5% with <30% peak), and VM didn't impact performance in any measurable ammount.</p>
|
Save and Restore Form Position and Size <p>In a WinForms 2.0 C# application, what is the typical method used for saving and restoring form position and size in an application?</p>
<p>Related, is it possible to add new User scoped application settings AT RUNTIME? I totally see how to add settings at design time, that's not a problem. But what if I want to create one at runtime?</p>
<p>More details:</p>
<p>My application is a conversion of an existing Visual FoxPro application. I've been trying to read as much as I can about application settings, user settings, etc. and get myself clear on the .Net way of doing things, but there are still several things I am confused on.</p>
<p>In the Fox app, saved settings are stored in the registry. My forms are subclassed, and I have base class code that automatically saves the form position and size in the registry keyed on the form name. Whenever I create a new form, I don't have to do anything special to get this behavior; it's built in to the base class. My .Net forms are also subclassed, that part is working well.</p>
<p>In .Net, I get the impression I'm supposed to use User scoped settings for things like user preferences. Size and location of a form definitely seem like a user preference. But, I can't see any way to automatically add these settings to the project. In other words, every time I add a new form to my project (and their are 100's of forms), I have to remember to ADD a User scoped application setting and be sure to give it the same name as the form, i.e., "FormMySpecialSizePosition" to hold the size and position. I'd rather not have to remember to do that. Is this just tough luck? Or am I totally barking up the wrong tree by trying to use User scoped settings? Do I need to create my own XML file to hold settings, so that I can do whatever I want (i.e, add a new setting at runtime)? Or something else?</p>
<p>Surely this is a very common and somebody can tell the "right" way to do it. Thanks in advance!</p>
|
<pre><code>private void Form1_Load( object sender, EventArgs e )
{
// restore location and size of the form on the desktop
this.DesktopBounds =
new Rectangle(Properties.Settings.Default.Location,
Properties.Settings.Default.Size);
// restore form's window state
this.WindowState = ( FormWindowState )Enum.Parse(
typeof(FormWindowState),
Properties.Settings.Default.WindowState);
}
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
System.Drawing.Rectangle bounds = this.WindowState != FormWindowState.Normal ? this.RestoreBounds : this.DesktopBounds;
Properties.Settings.Default.Location = bounds.Location;
Properties.Settings.Default.Size = bounds.Size;
Properties.Settings.Default.WindowState =
Enum.GetName(typeof(FormWindowState), this.WindowState);
// persist location ,size and window state of the form on the desktop
Properties.Settings.Default.Save();
}
</code></pre>
|
Python sockets suddenly timing out? <p>I came back today to an old script I had for logging into Gmail via SSL. The script worked fine last time I ran it (several months ago) but now it dies immediately with:</p>
<pre><code><urlopen error The read operation timed out>
</code></pre>
<p>If I set the timeout (no matter how long), it dies even more immediately with:</p>
<pre><code><urlopen error The connect operation timed out>
</code></pre>
<p>The latter is reproducible with:</p>
<pre><code>import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
</code></pre>
<p>returning:</p>
<pre><code>socket.sslerror: The connect operation timed out
</code></pre>
<p>but I can't seem to reproduce the former and, after much stepping thru the code, I have no clue what's causing any of this.</p>
|
<pre><code>import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
ssl.server()
--> '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com'
</code></pre>
<p>It works just fine. I can't reproduce your error.</p>
|
jQuery/JavaScript to replace broken images <p>I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.</p>
<p>How do I use jQuery to get the set of images, filter it to broken images then replace the src?</p>
<hr/>
<p>--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.</p>
|
<p>Handle the <code>onError</code> event for the image to reassign its source using JavaScript:</p>
<pre><code>function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
</code></pre>
<pre><code><img src="image.png" onerror="imgError(this);"/>
</code></pre>
<p>Or without a JavaScript function:</p>
<pre><code><img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
</code></pre>
<p>The following compatibility table lists the browsers that support the error facility:</p>
<p><a href="http://www.quirksmode.org/dom/events/error.html">http://www.quirksmode.org/dom/events/error.html</a></p>
|
Casting array of objects (which implement interface IFoo) to IFoo[] in C# <pre><code>class A : IFoo
{
}
...
A[] arrayOfA = new A[10];
if(arrayOfA is IFoo[])
{
// this is not called
}
</code></pre>
<p>Q1: Why is <code>arrayOfA</code> not an array of <code>IFoos</code>?</p>
<p>Q2: Why can't I cast <code>arrayOfA</code> to <code>IFoo[]</code>?</p>
|
<p><code>arrayOfA</code> <strong>is</strong> <code>IFoo[]</code>. </p>
<p>There must be something else wrong with your program.</p>
<p>You seem to have mocked up some code to show the problem, but in fact your code (see below) works as you expect. Try updating this question with the real code - or as close to real as you can - and we can take another look.</p>
<pre><code>using System;
public class oink {
public static void Main() {
A[] aOa = new A[10];
if (aOa is IFoo[]) { Console.WriteLine("aOa is IFoo[]"); }
}
public interface IFoo {}
public class A : IFoo {}
}
PS D:\> csc test.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.
PS D:\> D:\test.exe
aOa is IFoo[]
PS D:\>
</code></pre>
|
Eventhandling in ascx usercontrols <p>What is best practises for communicating events from a usercontrol to parent control/page i want to do something similar to this:</p>
<pre><code>MyPage.aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceholder" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnSomeEvent="MyUserControl_OnSomeEvent" />
MyUserControl.ascx.cs:
public partial class MyUserControl: UserControl
{
public event EventHandler SomeEvent;
....
private void OnSomething()
{
if (SomeEvent!= null)
SomeEvent(this, EventArgs.Empty);
}
</code></pre>
<p>Question is what is best practise?</p>
|
<p>You would want to create an event on the control that is subscribed to in the parent. See <a href="http://www.odetocode.com/code/94.aspx">OdeToCode</a> for an example.</p>
<p>Here is the article for longevity sake:</p>
<p>Some user controls are entirely self contained, for example, a user control displaying current stock quotes does not need to interact with any other content on the page. Other user controls will contain buttons to post back. Although it is possible to subscribe to the button click event from the containing page, doing so would break some of the object oriented rules of encapsulation. A better idea is to publish an event in the user control to allow any interested parties to handle the event.</p>
<p>This technique is commonly referred to as âevent bubblingâ since the event can continue to pass through layers, starting at the bottom (the user control) and perhaps reaching the top level (the page) like a bubble moving up a champagne glass.</p>
<p>For starters, letâs create a user control with a button attached.</p>
<pre><code><%@ Control Language="c#" AutoEventWireup="false"
Codebehind="WebUserControl1.ascx.cs"
Inherits="aspnet.eventbubble.WebUserControl1"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5"
%>
<asp:Panel id="Panel1" runat="server" Width="128px" Height="96px">
WebUserControl1
<asp:Button id="Button1" Text="Button" runat="server"/>
</asp:Panel>
</code></pre>
<p>The code behind for the user control looks like the following.</p>
<pre><code>public class WebUserControl1 : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Panel Panel1;
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("WebUserControl1 :: Page_Load <BR>");
}
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("WebUserControl1 :: Begin Button1_Click <BR>");
OnBubbleClick(e);
Response.Write("WebUserControl1 :: End Button1_Click <BR>");
}
public event EventHandler BubbleClick;
protected void OnBubbleClick(EventArgs e)
{
if(BubbleClick != null)
{
BubbleClick(this, e);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
</code></pre>
<p>The user control specifies a public event (BubbleClick) which declares a delegate. Anyone interested in the BubbleClick event can add an EventHandler method to execute when the event fires â just like the user control adds an EventHandler for when the Button fires the Click event.</p>
<p>In the OnBubbleClick event, we first check to see if anyone has attached to the event (BubbleClick != null), we can then invoke all the event handling methods by calling BubbleClick, passing through the EventArgs parameter and setting the user control (this) as the event sender. Notice we are also using Response.Write to follow the flow of execution.</p>
<p>An ASPX page can now put the user control to work.</p>
<pre><code><%@ Register TagPrefix="ksa"
TagName="BubbleControl"
Src="WebUserControl1.ascx"
%>
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="aspnet.eventbubble.WebForm1"
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<ksa:BubbleControl id="BubbleControl" runat="server" />
</form>
</body>
</HTML>
</code></pre>
<p>In the code behind for the page.</p>
<pre><code>public class WebForm1 : System.Web.UI.Page
{
protected WebUserControl1 BubbleControl;
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("WebForm1 :: Page_Load <BR>");
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
BubbleControl.BubbleClick += new EventHandler(WebForm1_BubbleClick);
}
#endregion
private void WebForm1_BubbleClick(object sender, EventArgs e)
{
Response.Write("WebForm1 :: WebForm1_BubbleClick from " +
sender.GetType().ToString() + "<BR>");
}
}
</code></pre>
<p>Notice the parent page simply needs to add an event handler during InitializeComponent method. When we receive the event we will again use Reponse.Write to follow the flow of execution.</p>
<p>One word of warning: if at anytime events mysteriously stop work, check the InitializeComponent method to make sure the designer has not removed any of the code adding event handlers.</p>
|
Built in unit-testing in VS <p>I'm looking for advice on the built-in unit testing feature provided in VS08. Can any body please tell me if they know of any reasons NOT to use this feature over any of the other packages available (I'm vaguely familiar with NUnit)?</p>
<p>I'm planning on applying unit testing to an older project just to learn the ropes of unit testing and some of the newer features in the .NET 3.5 framework. I like the look of the built in feature as from the quick demo I ran it seemed incredibly easy to use and I generally find Microsoft documentation very helpful.</p>
<p>I'd be very grateful if anyone who is familiar with this feature could alert me to any issues I should be aware of or any reasons to avoid this in favour of another package.</p>
<p>Note: I've tried raking through this (excellent) site for details specific to VS's built in unit testing feature. It has been <a href="http://stackoverflow.com/questions/709/net-testing-framework-advice">mentioned</a> a few times but I couldn't an exact match but please accept my apologies if this has been answered elsewhere.</p>
<p>Thank you, Eric</p>
|
<p>It looks like the discussion <a href="http://stackoverflow.com/questions/92869/nunit-vs-visual-studio-2008s-test-projects-for-unit-testing">here</a> can answer your question.</p>
|
Handling the data in an IN clause, with SQL parameters? <p>We all know that prepared statements are one of the best way of fending of SQL injection attacks. What is the best way of creating a prepared statement with an "IN" clause. Is there an easy way to do this with an unspecified number of values? Take the following query for example.</p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (1,2,3)
</code></pre>
<p>Currently I'm using a loop over my possible values to build up a string such as. </p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDVAL_1,@IDVAL_2,@IDVAL_3)
</code></pre>
<p>Is it possible to use just pass an array as the value of the query paramter and use a query as follows?</p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDArray)
</code></pre>
<p>In case it's important I'm working with SQL Server 2000, in VB.Net</p>
|
<p>Here you go - first create the following function...</p>
<pre><code>Create Function [dbo].[SeparateValues]
(
@data VARCHAR(MAX),
@delimiter VARCHAR(10)
)
RETURNS @tbldata TABLE(col VARCHAR(10))
As
Begin
DECLARE @pos INT
DECLARE @prevpos INT
SET @pos = 1
SET @prevpos = 0
WHILE @pos > 0
BEGIN
SET @pos = CHARINDEX(@delimiter, @data, @prevpos+1)
if @pos > 0
INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, @pos-@prevpos-1))))
else
INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, len(@data)-@prevpos))))
SET @prevpos = @pos
End
RETURN
END
</code></pre>
<p>then use the following...</p>
<pre><code>Declare @CommaSeparated varchar(50)
Set @CommaSeparated = '112,112,122'
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (select col FROM [SeparateValues](@CommaSeparated, ','))
</code></pre>
<p>I think sql server 2008 will allow table functions.</p>
<p><strong>UPDATE</strong></p>
<p>You'll squeeze some extra performance using the following syntax...</p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable
Cross Apply [SeparateValues](@CommaSeparated, ',') s
Where MyTable.id = s.col
</code></pre>
<p>Because the previous syntax causes SQL Server to run an extra "Sort" command using the "IN" clause. Plus - in my opinion it looks nicer :D!</p>
|
SQL Server post-join rowcount underestimate <p>The Query Optimizer is estimating that the results of a join will have only one row, when the actual number of rows is 2000. This is causing later joins on the dataset to have an estimated result of one row, when some of them go as high as 30,000.</p>
<p>With a count of 1, the QO is choosing a loop join/index seek strategy for many of the joins which is much too slow. I worked around the issue by constraining the possible join strategies with a <code>WITH OPTION (HASH JOIN, MERGE JOIN)</code>, which improved overall execution time from 60+ minutes to 12 seconds. However, I think the QO is still generating a less than optimal plan because of the bad rowcounts. I don't want to specify the join order and details manually-- there are too many queries affected by this for it to be worthwhile.</p>
<p>This is in Microsoft SQL Server 2000, a medium query with several table selects joined to the main select.</p>
<p>I think the QO may be overestimating the cardinality of the many side on the join, expecting the joining columns between the tables to have less rows in common.</p>
<p>The estimated row counts from scanning the indexes before the join are accurate, it's only the estimated row count after certain joins that's much too low.</p>
<p>The statistics for all the tables in the DB are up to date and refreshed automatically.</p>
<p>One of the early bad joins is between a generic 'Person' table for information common to all people and a specialized person table that about 5% of all those people belong to. The clustered PK in both tables (and the join column) is an INT. The database is highly normalized.</p>
<p>I believe that the root problem is the bad row count estimate after certain joins, so my main questions are:</p>
<ul>
<li>How can I fix the QO's post join rowcount estimate?</li>
<li>Is there a way that I can hint that a join will have a lot of rows without specifying the entire join order manually?</li>
</ul>
|
<p>Although the statistics were up to date, the scan percentage wasn't high enough to provide accurate information. I ran this on each of the base tables that was having a problem to update all the statistics on a table by scanning all the rows, not just a default percentage.</p>
<pre><code>UPDATE STATISTICS <table> WITH FULLSCAN, ALL
</code></pre>
<p>The query still has a lot of loop joins, but the join order is different and it runs in 2-3 seconds.</p>
|
A free tool to check C/C++ source code against a set of coding standards? <p>It looks quite easy to find such a tool for Java (<a href="http://checkstyle.sourceforge.net/">Checkstyle</a>, <a href="http://jcsc.sourceforge.net/">JCSC</a>), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalization, spacing, identation, bracket placement, and so on.</p>
|
<p>The only tool I know is <a href="http://bitbucket.org/verateam/vera">Vera</a>. Haven't used it, though, so can't comment how viable it is. <a href="http://www.inspirel.com/vera/ce/demo.html">Demo</a> looks promising.</p>
|
Best Java Obfuscation Application For Size Reduction <p>An important part of mobile development, especially when you are talking about mobile games, is dealing with the application size restrictions. Some devices enforce their own size limits, while all the carriers have their own size requirements for applications to be released in their deck space.</p>
<p>My question is, is there a java obfuscation application that gets better size reduction results than the other java obfuscation apps that are out there? </p>
<p>I use Proguard because it is the default Netbeans obfuscator and you can get fairly good size reduction results out of it (by the way, the version of Proguard that comes with Netbeans 6.1 is 3.7. There are newer versions that get even better results, I recommend getting the latest). But, I'm interested in what else is out there and whether they do a better job than Proguard.</p>
<p><strong>My Conclusion:</strong></p>
<p>I appreciate the responses. Carlos, your response was enough to convince me that Proguard is the current way to go. I could still be convinced otherwise, but don't feel bad with my current setup.</p>
<p>I have also had some issues with proguard obfuscating and running on some phones, but not too many. I was always able to fix the problem by not using the Proguard argument "-overloadaggressively". Just something to keep in mind if you are experiencing odd behavior related to obfuscating.</p>
<p>Thanks again.</p>
|
<p>I also prefer ProGuard for both it's size reduction and breadth of obfuscation - see <a href="http://proguard.sourceforge.net/" rel="nofollow">http://proguard.sourceforge.net/</a>. I don't necessarily have size constraints other than download speeds, but haven't found anything that shrinks further.</p>
|
Practical Alternative for Windows Scheduled Tasks (small shop) <p>Greetings,</p>
<p>I work in a very small shop (2 people), and since I started a few months back we have been relying on Windows Scheduled tasks. Finally, I've decided I've had enough grief with some of its inabilities such as</p>
<ol>
<li>No logs that I can find except on a domain level (inaccessible to machine admins who aren't domain admins)</li>
<li>No alerting mechanism (e-mail, for one) when the job fails.</li>
</ol>
<p>Once again, we are a small shop. I'm looking to do the analogous scheduling system upgrade than I'm doing with source control (VSS --> Subversion). I'm looking for suggestions of systems that </p>
<ol>
<li>Are able to do the two things outlined above</li>
<li>Have been community-tested. I'd love to be a guinae pig for exciting software, but job scheduling is not my day job.</li>
<li>Ability to remotely manage jobs a plus</li>
<li>Free a plus. Cheap is okay, but I have very little interest in going through a full blown sales pitch with 7 power point presentations.</li>
<li>Built-in ability to run common tasks besides .EXE's a (minor) plus (run an assembly by name, run an Excel macro by name a plus, run a database stored procedure, etc.). </li>
</ol>
<p>Thanks in advance,
Alan.</p>
|
<p>I think you can look at :</p>
<p><a href="http://www.visualcron.com/">http://www.visualcron.com/</a></p>
|
symbian application as background process <p>is it possible to create java application that will
work as background process on symbian smartphones?</p>
|
<p>You can approximate it but J2ME (the version of java on mobile phones) may not be the right technology to do this.</p>
<ul>
<li><p>starting a MIDlet (a Java application for mobile phones) when the phone is switched on is tricky at best without coding a small Symbian OS C++ module that will start it for you. If you want to try anyway, look at the PushRegistry class in the MIDP specs
(http://java.sun.com/javame/reference/apis/jsr118/). The Content Handling API might provide some way to do it too (http://java.sun.com/javame/reference/apis/jsr211). When you are ready to give up, do it in C++.</p></li>
<li><p>Backgrounding a MIDlet isn't hard. The phone's "menu" key will do it for you. Programatically, Canvas.setCurrent(null) has a good chance of working. Trying to trick the phone by providing a fully transparent GUI and not handling any keypad activity will absolutely not work. Creating and starting a separate Thread in the MIDlet should allow you to keep something running even after your overload of MIDlet.pauseApp() has been called by the application management system.</p></li>
<li><p>The real issue is that the MIDlet will not have any Inter Process Communication system unless you make one. The usual way of doing that is a loopback socket connection over which you transfer data. Not a nice or efficient way of simulating IPC. Sharing a RMS record can only be done from within the same MIDlet suite (you can package several MIDlets into the same .jar file), I think. The code to create a provider/consumer data flow over a file connection is even uglier and will raise security issues.</p></li>
</ul>
<p>Without any more information about what you want to use it for, my answer is : maybe but you should probably not try.</p>
|
Is FileStream lazy-loaded in .NET? <p>I have a question about using streams in .NET to load files from disk. I am trying to pinpoint a performance problem and want to be sure it's where I think it is.</p>
<pre><code>Dim provider1 As New MD5CryptoServiceProvider
Dim stream1 As FileStream
stream1 = New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
provider1.ComputeHash(stream1)
</code></pre>
<p>Q: Are the bytes read from disk when I create the FileStream object, or when the object consuming the stream, in this case an MD5 Hash algorithm, actually reads it?</p>
<p>I see significant performance problems on my web host when using the <code>ComputeHash</code> method, compared to my local test environment. I'm just trying to make sure that the performance problem is in the hashing and not in the disk access.</p>
|
<p>FileStream simply exposes an IO.Stream around a file object, and uses buffers. It doesn't read the entire file in the constructor (the file could be larger than RAM). </p>
<p>The performance issue is most likely in the hashing, and you can perform some simple benchmarks to prove whether it's because of file IO or the algorithm itself.</p>
<p>But one of the first things you might try is:</p>
<pre><code>provider1.ComputeHash(stream1.ToArray());
</code></pre>
<p>This should make the FileStream read the entire file and return an array of bytes. .ToArray() may invoke a faster method than the .Read() method that ComputeHash will call.</p>
|
Apply stroke to a textblock in WPF <p>How do you apply stroke (outline around text) to a textblock in xaml in WPF?</p>
|
<p>Below is my more idiomatically WPF, full-featured take on this. It supports pretty much everything you'd expect, including:</p>
<ul>
<li>all font related properties including stretch and style</li>
<li>text alignment (left, right, center, justify)</li>
<li>text wrapping</li>
<li>text trimming</li>
<li>text decorations (underline, strike through etcetera)</li>
</ul>
<p>Here's a simple example of what can be achieved with it:</p>
<pre><code><local:OutlinedTextBlock FontFamily="Verdana" FontSize="20pt" FontWeight="ExtraBold" TextWrapping="Wrap" StrokeThickness="1" Stroke="{StaticResource TextStroke}" Fill="{StaticResource TextFill}">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit
</local:OutlinedTextBlock>
</code></pre>
<p>Which results in:</p>
<p><img src="http://i.stack.imgur.com/gyDYX.png" alt="enter image description here"></p>
<p>Here's the code for the control:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
[ContentProperty("Text")]
public class OutlinedTextBlock : FrameworkElement
{
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
"StrokeThickness",
typeof(double),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextInvalidated));
public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(
"TextAlignment",
typeof(TextAlignment),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(
"TextDecorations",
typeof(TextDecorationCollection),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(
"TextTrimming",
typeof(TextTrimming),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(
"TextWrapping",
typeof(TextWrapping),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));
private FormattedText formattedText;
private Geometry textGeometry;
public OutlinedTextBlock()
{
this.TextDecorations = new TextDecorationCollection();
}
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
[TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public FontStretch FontStretch
{
get { return (FontStretch)GetValue(FontStretchProperty); }
set { SetValue(FontStretchProperty, value); }
}
public FontStyle FontStyle
{
get { return (FontStyle)GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
public FontWeight FontWeight
{
get { return (FontWeight)GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
public Brush Stroke
{
get { return (Brush)GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
public double StrokeThickness
{
get { return (double)GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection)this.GetValue(TextDecorationsProperty); }
set { this.SetValue(TextDecorationsProperty, value); }
}
public TextTrimming TextTrimming
{
get { return (TextTrimming)GetValue(TextTrimmingProperty); }
set { SetValue(TextTrimmingProperty, value); }
}
public TextWrapping TextWrapping
{
get { return (TextWrapping)GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
protected override void OnRender(DrawingContext drawingContext)
{
this.EnsureGeometry();
drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry);
}
protected override Size MeasureOverride(Size availableSize)
{
this.EnsureFormattedText();
// constrain the formatted text according to the available size
// the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions
// the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw
this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width);
this.formattedText.MaxTextHeight = Math.Max(0.0001d, availableSize.Height);
// return the desired size
return new Size(this.formattedText.Width, this.formattedText.Height);
}
protected override Size ArrangeOverride(Size finalSize)
{
this.EnsureFormattedText();
// update the formatted text with the final size
this.formattedText.MaxTextWidth = finalSize.Width;
this.formattedText.MaxTextHeight = finalSize.Height;
// need to re-generate the geometry now that the dimensions have changed
this.textGeometry = null;
return finalSize;
}
private static void OnFormattedTextInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.formattedText = null;
outlinedTextBlock.textGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.UpdateFormattedText();
outlinedTextBlock.textGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private void EnsureFormattedText()
{
if (this.formattedText != null || this.Text == null)
{
return;
}
this.formattedText = new FormattedText(
this.Text,
CultureInfo.CurrentUICulture,
this.FlowDirection,
new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),
this.FontSize,
Brushes.Black);
this.UpdateFormattedText();
}
private void UpdateFormattedText()
{
if (this.formattedText == null)
{
return;
}
this.formattedText.MaxLineCount = this.TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;
this.formattedText.TextAlignment = this.TextAlignment;
this.formattedText.Trimming = this.TextTrimming;
this.formattedText.SetFontSize(this.FontSize);
this.formattedText.SetFontStyle(this.FontStyle);
this.formattedText.SetFontWeight(this.FontWeight);
this.formattedText.SetFontFamily(this.FontFamily);
this.formattedText.SetFontStretch(this.FontStretch);
this.formattedText.SetTextDecorations(this.TextDecorations);
}
private void EnsureGeometry()
{
if (this.textGeometry != null)
{
return;
}
this.EnsureFormattedText();
this.textGeometry = this.formattedText.BuildGeometry(new Point(0, 0));
}
}
</code></pre>
|
What's the easiest non-memory intensive way to output XML from Python? <p>Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer that doesn't incur much of a memory overhead. So that rules out xml.dom and xml.dom.minidom. Suggestions?</p>
|
<p>I think you'll find XMLGenerator from xml.sax.saxutils is the closest thing to what you want.</p>
<pre>
import time
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesNSImpl
LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR']
class xml_logger:
def __init__(self, output, encoding):
"""
Set up a logger object, which takes SAX events and outputs
an XML log file
"""
logger = XMLGenerator(output, encoding)
logger.startDocument()
attrs = AttributesNSImpl({}, {})
logger.startElementNS((None, u'log'), u'log', attrs)
self._logger = logger
self._output = output
self._encoding = encoding
return
def write_entry(self, level, msg):
"""
Write a log entry to the logger
level - the level of the entry
msg - the text of the entry. Must be a Unicode object
"""
#Note: in a real application, I would use ISO 8601 for the date
#asctime used here for simplicity
now = time.asctime(time.localtime())
attr_vals = {
(None, u'date'): now,
(None, u'level'): LOG_LEVELS[level],
}
attr_qnames = {
(None, u'date'): u'date',
(None, u'level'): u'level',
}
attrs = AttributesNSImpl(attr_vals, attr_qnames)
self._logger.startElementNS((None, u'entry'), u'entry', attrs)
self._logger.characters(msg)
self._logger.endElementNS((None, u'entry'), u'entry')
return
def close(self):
"""
Clean up the logger object
"""
self._logger.endElementNS((None, u'log'), u'log')
self._logger.endDocument()
return
if __name__ == "__main__":
#Test it out
import sys
xl = xml_logger(sys.stdout, 'utf-8')
xl.write_entry(2, u"Vanilla log entry")
xl.close()
</pre>
<p>You'll probably want to look at the rest of the article I got that from at <a href="http://www.xml.com/pub/a/2003/03/12/py-xml.html">http://www.xml.com/pub/a/2003/03/12/py-xml.html</a>.</p>
|
UML aggregation when interfaces are used <p><strong>How do I represent an aggregation relation between two classes in UML, such that each class has a link to the other class's interface, not the implementing class?</strong></p>
<p>E.g. I have a class Foo that implements iFoo, and Bar that implements iBar. Foo should have a member variable of type iBar, and Bar should have a member variable of type iFoo.</p>
<p>If I create an aggregation between the two implementing classes, then the member will be of the type of the implementing class, not the superclass. And aggregations between interfaces are invalid in UML (and don't make much sense).</p>
|
<p>Can you not have Foo (implementation) aggregate iBar (interface)? That seems to me the proper way to describe this relationship.</p>
<p>So something like this:</p>
<pre><code>----------------- -----------------
| <<interface>> | | <<interface>> |
| iFoo |<> <>| iBar |
----------------- \/ -----------------
^ /\ ^
| / \ |
-----------------/ \-----------------
| Foo | | Bar |
----------------- -----------------
</code></pre>
|
EEFileLoadException when using C# classes in C++(win32 app) <p>For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper. </p>
<p>I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated!</p>
<p>Managed C++ wrapper code (this is in a DLL):</p>
<pre><code>extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
//this class references c# in the constructor
return new CMyWrapper( );
}
extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile)
{
delete pConfigFile;
}
extern "C" __declspec(dllexport) void TestFunction(void)
{
::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);
}
</code></pre>
<p>Test Code (this is an EXE):</p>
<pre><code>typedef void* (*CreateObjectPtr)();
typedef void (*TestFunctionPtr)();
int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[])
{
HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));
_ASSERT(hModule != NULL);
PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");
_ASSERT(pFunc1 != NULL);
TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;
PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");
_ASSERT(pFunc2 != NULL);
CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;
(*pTest)(); //this successfully pops up a message box
(*pCreateObjectFunc)(); //this tosses an EEFileLoadException
return 0;
}
</code></pre>
<p>For what it's worth, the Event Log reports the following:
.NET Runtime version 2.0.50727.143 -
Fatal Execution Engine Error (79F97075) (80131506)</p>
<p>Unfortunately, Microsoft has no information on that error.</p>
|
<p>The problem was where the DLLs were located.</p>
<ul>
<li>c:\dlls\managed.dll</li>
<li>c:\dlls\wrapper.dll</li>
<li>c:\exe\my.exe</li>
</ul>
<p>I confirmed this by copying managed.dll into c:\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. (or in the GAC).</p>
<p>For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below:</p>
<p>AssemblyResolver.h:</p>
<pre><code>/// <summary>
/// Summary for AssemblyResolver
/// </summary>
public ref class AssemblyResolver
{
public:
static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
Console::WriteLine( "Resolving..." );
Assembly^ thisAssembly = Assembly::GetExecutingAssembly();
String^ thisPath = thisAssembly->Location;
String^ directory = Path::GetDirectoryName(thisPath);
String^ pathToManagedAssembly = Path::Combine(directory, "managed.dll");
Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);
return newAssembly;
}
};
</code></pre>
<p>Wrapper.cpp:</p>
<pre><code>#include "AssemblyResolver.h"
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
try
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler );
return new CMyWrapper( );
}
catch(System::Exception^ e)
{
System::Console::WriteLine(e->Message);
return NULL;
}
}
</code></pre>
|
MySQL Trigger & Stored Procedure Replication <p>Ok,I'm running a setup with a single master and a number of slaves. All writes go through the master and are replicated down to the slaves which are used strictly for reads. </p>
<p>Now I have a stored procedure (not function) which is called by a trigger on an insert. According to the MySQL docs, for replication triggers log the call to the trigger while stored procedures actually log the result of the stored procedure. </p>
<p>So my question is, when my trigger gets fired, will it replicate both the trigger and the results of the procedure that the trigger calls (resulting in the procedure effectively being run twice)? Or will it simply replicate the trigger have the slaves re-run the stored procedure on their own?</p>
<p>Thanks</p>
|
<p>In MySQL 5.0 (and MySQL 5.1 with statement based binary logging), only the calling query is logged, so in your case, the INSERT would be logged. </p>
<p>On the slave, the INSERT will be executed and then the trigger will be re-run on the slave. So the trigger needs to exist on the slave, and assuming it does, then it will be executed in exactly the same way as the master.</p>
<p>In MySQL 5.1, there is row-based binary logging, which will log only the rows being changed, so the trigger would not be re-fired on the slave, but all rows that changed would still be propagated.</p>
|
Can't add server to a moved workspace <p>I have this workspace downloaded off the web and I try running it on a tomcat server from a fresh installation of Eclipse Ganymede. This particular project came with its own workspace. </p>
<p>When I select Tomcat v6.0 I get a message </p>
<blockquote>
<p>Cannot create a server using the selected type</p>
</blockquote>
<p>Older tomcat versions are available, though. </p>
<p>I guess I have to recreate some configuration setting. The question is which one? This seems to be some odd error as creating a new dynamic web project lets me configure tomcat for both of them</p>
|
<p>I had a similar problem, but my solution is a little simpler. The problem was causesd by renaming the original folder that was referenced by the server definition.</p>
<p>Go to Window/Preferences/Server/Runtime Environments, remove the broken reference. Then, click 'Add' to create a new reference, select the appropriate tomcat version, click next and you'll see the incorrect path reference. Fix it. Move on.</p>
|
What Python GUI APIs Are Out There? <p>Simple question:</p>
<ul>
<li>What Python GUI API's are out there and what are the advantages of any given API?</li>
</ul>
<p>I'm not looking for a religious war here, I'm just wanting to get a good handle on all that is out there in terms of Python GUI APIs.</p>
|
<p><a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow">Here's a good list.</a></p>
|
Volume (Balance) Control for XP/Vista <p>Is there a method for controlling the Balance of the Wave output that will work on both XP and Vista?</p>
|
<p>Vista has a new api for everything related to mixers and audio, per process legacy api's should still work, but to change global volume, you would have to look at the new COM interfaces added to Vista</p>
<p><a href="http://www.codeproject.com/KB/vista/CoreAudio.aspx" rel="nofollow">This</a> should get you started</p>
|
Windsor Interceptors AOP & Caching <p>I'm considering using Castle Windsor's Interceptors to cache data for helping scale an asp.net site.</p>
<p>Does anyone have any thoughts/experience with doing this?</p>
<p>Minor clarification:
My intention was to use Windsor to intercept 'expensive' calls and delegate to MemCacheD or Velocity (or another distributed cache) for the caching itself.</p>
|
<p>Hey there, We've used Castle Windsor Interceptors, based on this article: <a href="http://www.davidhayden.com/blog/dave/archive/2007/03/14/CastleWindsorAOPPolicyInjectionApplicationBlock.aspx" rel="nofollow">http://www.davidhayden.com/blog/dave/archive/2007/03/14/CastleWindsorAOPPolicyInjectionApplicationBlock.aspx</a> as well as the one mentioned above.</p>
<p>I found the whole thing pretty easy and it's a very elegant way to do AOP. However....</p>
<p>Careful with the performance though. Using interception creates a dynamic proxy that will definitely slow things down. Based on our benchmarks using a 500 Node computing farm we saw a performance decrease of about 30% by using interception in Windsor, this was outside what we were doing inside the interception as well (essentially logging method calls and params passed in to our methdods). and simply removing the interception sped the whole app up quite a bit. </p>
<p>Careful you don't make your expensive calls <em>really</em> expensive. :) If I were you I would look to cache at a different level, probably by implementing an IRepository type pattern and then backing that with various caching strategies where appropriate. </p>
<p>Good luck, </p>
<p>--<br>
Matt. </p>
|
Infopath 2007 - Emailed forms not rendering correctly <p>So I have a form that uses infopath services via sharepoint, and after multiple attempts at attempting to fix a rendering problem (tables appear WAY too wide to be readable), I think I have found the problem : date controls.</p>
<p>It seems date controls within Infopath 2007 screw with rendering somehow. To test, I made 2 variations of a VERY simple form - one with a date control, one with a text control - and placed them inside a table.</p>
<p>When emailed, the one with the date control rendered incorrectly.</p>
<p>My question is - has anyone experienced this before? If you have time, test it out. I think it is a bug or something, but not exactly sure.</p>
<p>I am using Infopath 2007, Sharepoint 2007, and Outlook 2007.</p>
<p><hr /></p>
<h2><strong>Updated Sept 19, 2008</strong></h2>
<p>Yes, web form capability is checked.
Web compatible date controls? I think so - everything looks perfect in the browser... only the email messes up.
and yes you are correct. My mistake this is Sharepoint 2007. I fixed it above.</p>
<p>If anyone has the time, try it out - it's very frustrating to have to use text boxes for dates. Especially with the 'talent' we have here. lol</p>
|
<p>Do you have web form compatability checked in all the necessary places? Are you using the web compatible date controls? Are you sure you are using SharePoint 2003, I thought Form Services was a 2007 update.</p>
|
How do I read selected files from a remote Zip archive over HTTP using Python? <p>I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory).</p>
<p>I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.</p>
|
<p>Here's how I did it (grabbing all files ending in ".ranks"):</p>
<pre><code>import urllib2, cStringIO, zipfile
try:
remotezip = urllib2.urlopen(url)
zipinmemory = cStringIO.StringIO(remotezip.read())
zip = zipfile.ZipFile(zipinmemory)
for fn in zip.namelist():
if fn.endswith(".ranks"):
ranks_data = zip.read(fn)
for line in ranks_data.split("\n"):
# do something with each line
except urllib2.HTTPError:
# handle exception
</code></pre>
|
Best way to catch a WCF exception in Silverlight? <p>I have a Silverlight 2 application that is consuming a WCF service. As such, it uses asynchronous callbacks for all the calls to the methods of the service. If the service is not running, or it crashes, or the network goes down, etc before or during one of these calls, an exception is generated as you would expect. The problem is, I don't know how to catch this exception.</p>
<ul>
<li><p>Because it is an asynchronous call, I can't wrap my begin call with a try/catch block and have it pick up an exception that happens after the program has moved on from that point.</p></li>
<li><p>Because the service proxy is automatically generated, I can't put a try/catch block on each and every generated function that calls EndInvoke (where the exception actually shows up). These generated functions are also surrounded by External Code in the call stack, so there's nowhere else in the stack to put a try/catch either.</p></li>
<li><p>I can't put the try/catch in my callback functions, because the exception occurs before they would get called.</p></li>
<li><p>There is an Application_UnhandledException function in my App.xaml.cs, which captures all unhandled exceptions. I could use this, but it seems like a messy way to do it. I'd rather reserve this function for the truly unexpected errors (aka bugs) and not end up with code in this function for every circumstance I'd like to deal with in a specific way.</p></li>
</ul>
<p>Am I missing an obvious solution? Or am I stuck using Application_UnhandledException?</p>
<p>[Edit]<br />
As mentioned below, the Error property is exactly what I was looking for. What is throwing me for a loop is that the fact that the exception is thrown and appears to be uncaught, yet execution is able to continue. It triggers the Application_UnhandledException event and causes VS2008 to break execution, but continuing in the debugger allows execution to continue. It's not really a problem, it just seems odd.</p>
|
<p>I check the Error property of the event args in the service method completed event handler. I haven't had issues with the event handler not being called. In the case where the server goes down, the call takes a few seconds then comes back with a ProtocolException in the Error property.</p>
<p>Assuming you have tried this and your callback really never gets called, you might look into customizing the generated proxy class. See <a href="http://blogs.msdn.com/pedram/archive/2007/08/10/customising-wcf-proxy-generation-in-visual-studio-2008.aspx">this article</a>.</p>
|
Stateful Web Services <p>I'm building a java/spring application, and i may need to incorporate a stateful web service call.
Any opinions if i should totally run away from a stateful services call, or it can be done and is enterprise ready?</p>
|
<p>Statefulness runs counter to the basic architecture of HTTP (ask Roy Fielding), and reduces scalability.</p>
|
DNS- Route DNS for subfolder to different server? <p>LEt's say I want to have a subfolder called- <a href="http://www.foo.com/news/" rel="nofollow">http://www.foo.com/news/</a> but I actually want that news folder on a different server. I realize it can be done easily with subdomains, but I was really hoping for the subfolder thing.</p>
<p>Is it possible? How?</p>
|
<p>The <strong>only</strong> real way to it is with a reverse proxy ( <em>Or a webserver acting as a reverse proxy</em> ) between you and the outside world that knows what IP address each folder is in. </p>
<p>Its not possible to just make something, for example have google.com appear at <a href="http://foobar.com/google/">http://foobar.com/google/</a> because the browser won't route to the IP address ( lack of information ). </p>
<p>You can <em>fake</em> that effect with a fullpage IFrame or Other frameset system, but that's rather dodgy.</p>
<p>If you are using apache, you can set this up with mod_proxy. More details can be found here: </p>
<ul>
<li><a href="http://httpd.apache.org/docs/1.3/mod/mod_proxy.html">Mod_Proxy(1.3) Manual</a></li>
<li><a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html">Mod_Proxy(2.0) Manual</a></li>
<li><a href="http://www.apachetutor.org/admin/reverseproxies">Apache Tutor.org guide</a></li>
</ul>
|
Using JQuery with ASP.NET MVC Framework <p>I have searched the forum, and google for this topic. Most of the articles are talking about using JSON to call the controller/action on the server and do ajax effect on the result.</p>
<p>I am trying to use some very basic JQuery features, like the JQuery UI/Tabs, and JQuery UI/Block for a dialog window. I cannot get these simple samples to work in my MVC project. Any ideas how I should modify these samples? I only need these basic feature now and I can go from here.</p>
<p>Thanks!</p>
|
<p>Actually I just got it working. The problem is that I need to modify the path to an absolute path to the view page because the relative path doesn't work with the MVC routes {controller}/{action}/{id}.</p>
<p>Thanks!</p>
|
Fetch one row per account id from list <p>I have a table with game scores, allowing multiple rows per account id: <code>scores (id, score, accountid)</code>. I want a list of the top 10 scorer ids and their scores.</p>
<p>Can you provide an sql statement to select the top 10 scores, but only one score per account id? </p>
<p>Thanks!</p>
|
<pre><code>select username, max(score) from usertable group by username order by max(score) desc limit 10;
</code></pre>
|
Where is the best place to store user related data in asp.net? <p>When a customer logs in to my site, I need to know their account id and their menu id. This lets me know what data they can see on a page and what menu they get. I don't want to have to read this data over and over. Should I store this in a session variable or customize the membership user and membership provider to contain this information?</p>
|
<p>As already suggested, the profile system is super easy.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx</a></p>
|
Can this macro be converted to a function? <p>While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure:</p>
<pre><code>#define STRUCTSIZE(s) (sizeof(s) / sizeof(*s))
</code></pre>
<p>Very useful as it is but can it be converted into an inline function or template?</p>
<p>OK, ARRAYSIZE would be a better name but this is legacy code (no idea where it came from, it's at least 15 years old) so I pasted it 'as is'.</p>
|
<p>As been stated, the code actually work out the number of elements in an array, not struct. I would just write out the sizeof() division explicitly when I want it. If I were to make it a function, I would want to make it clear in its definition that it's expecting an array.</p>
<pre><code>template<typename T,int SIZE>
inline size_t array_size(const T (&array)[SIZE])
{
return SIZE;
}
</code></pre>
<p>The above is similar to <a href="http://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#95664">xtofl's</a>, except it guards against passing a pointer to it (that says point to a dynamically allocated array) and getting the wrong answer by mistake.</p>
<p><strong>EDIT</strong>: Simplified as per <a href="http://stackoverflow.com/users/1674/johnmcg">JohnMcG</a>.
<strong>EDIT</strong>: inline.</p>
<p>Unfortunately, the above does not provide a compile time answer (even if the compiler does inline & optimize it to be a constant under the hood), so cannot be used as a compile time constant expression. i.e. It cannot be used as size to declare a static array. Under C++0x, this problem go away if one replaces the keyword <em>inline</em> by <em>constexpr</em> (constexpr is inline implicitly).</p>
<pre><code>constexpr size_t array_size(const T (&array)[SIZE])
</code></pre>
<p><a href="http://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#97523">jwfearn's</a> solution work for compile time, but involve having a typedef which effectively "saved" the array size in the declaration of a new name. The array size is then worked out by initialising a constant via that new name. In such case, one may as well simply save the array size into a constant from the start.</p>
<p><a href="http://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#98059">Martin York's</a> posted solution also work under compile time, but involve using the non-standard <em>typeof()</em> operator. The work around to that is either wait for C++0x and use <em>decltype</em> (by which time one wouldn't actually need it for this problem as we'll have <em>constexpr</em>). Another alternative is to use Boost.Typeof, in which case we'll end up with</p>
<pre><code>#include <boost/typeof/typeof.hpp>
template<typename T>
struct ArraySize
{
private: static T x;
public: enum { size = sizeof(T)/sizeof(*x)};
};
template<typename T>
struct ArraySize<T*> {};
</code></pre>
<p>and is used by writing</p>
<pre><code>ArraySize<BOOST_TYPEOF(foo)>::size
</code></pre>
<p>where <em>foo</em> is the name of an array.</p>
|
How to detect whether Vista UAC is enabled? <p>I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?</p>
|
<p>This registry key should tell you:</p>
<pre><code>HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
</code></pre>
<p>Value <code>EnableLUA (DWORD)</code></p>
<p><code>1</code> enabled / <code>0</code> or missing disabled</p>
<p>But that assumes you have the rights to read it. </p>
<p>Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see <a href="http://blogs.msdn.com/cjacks/archive/2006/10/09/How-to-Determine-if-a-User-is-a-Member-of-the-Administrators-Group-with-UAC-Enabled-on-Windows-Vista.aspx" rel="nofollow">here</a>). Not foolproof, but it may work.</p>
<p>The issue here is more of a "why do you need to know" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem. </p>
|
JQuery error option in $.ajax utility <p>The documentation indicates that the error: option function will make available: XHR instance, a status message string (in this case always error) and an optional exception object returned from the XHR instance (Book: JQuery in Action)</p>
<p>Using the following (in the $.ajax call) I was able to determine I had a "parsererror" and a "timeout" (since I added the timeout: option) error</p>
<pre><code>error: function(request, error){}
</code></pre>
<p>What are other things you evaluate in the error option? do you include the optional exception object?</p>
<p><strong>EDIT:</strong> one of the answers indicates all the return errors...learning more about what is of value (for debugging) in the XHR instance and exception object would be helpful</p>
<p>This is a complete $.ajax call:</p>
<pre><code>$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
dataType: "text",
data: {
'_service' : 'myService',
'_program' : 'myProgram',
'start' : start,
'end' : end
},
beforeSend: function() {
$("#loading").removeClass("hide");
},
timeout: 5000,
error: function(request,error) {
$("#loading").addClass("hide");
if (error == "timeout") {
$("#error").append("The request timed out, please resubmit");
}
else {
$("#error").append("ERROR: " + error);
}
},
success: function(request) {
$("#loading").addClass("hide");
var t = eval( "(" + request + ")" ) ;
} // End success
}); // End ajax method
</code></pre>
<p>Thanks for the input</p>
|
<p>I find the request more useful than the error.</p>
<pre><code>error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}</code></pre>
<p><strong>xhr</strong> is XmlHttpRequest.<br/>
<strong>readyState</strong> values are 1:loading, 2:loaded, 3:interactive, <em>4:complete</em>.<br/>
<strong>status</strong> is the HTTP status number, i.e. 404: not found, 500: server error, <em>200: ok</em>.<br/>
<strong>responseText</strong> is the response from the server - this could be text or JSON from the web service, or HTML from the web server.</p>
|
VB.Net (or C#) 2008 Multi Threaded Import <p>I am looking to build a multi-threaded text import facility (generally CSV into SQL Server 2005) and would like to do this in VB.NET but I am not against C#. I have VS 2008 trial and just dont know where to begin. Can anyone point me in the direction of where I can look at and play with the source of a <em>VERY</em> simple multi-threaded application for VS 2008?</p>
<p>Thanks!</p>
|
<p>This is a great article:</p>
<p><a href="http://www.devx.com/DevX/10MinuteSolution/20365" rel="nofollow">http://www.devx.com/DevX/10MinuteSolution/20365</a></p>
<p>In particular:</p>
<pre><code>Dim t As Thread
t = New Thread(AddressOf Me.BackgroundProcess)
t.Start()
Private Sub BackgroundProcess()
Dim i As Integer = 1
Do While True
ListBox1.Items.Add("Iterations: " + i)
i += 1
Thread.CurrentThread.Sleep(2000)
Loop
End Sub
</code></pre>
|
How can I generate a list of function dependencies in MATLAB? <p>In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this?</p>
<p>Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here. </p>
|
<p>For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions:</p>
<ol>
<li>mlint</li>
<li>dependency report and </li>
<li>coverage report</li>
</ol>
<p>Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies. To use profile, you could do </p>
<pre><code>>> profile on % turn profiling on
>> foo; % entry point to your matlab function or script
>> profile off % turn profiling off
>> profview % view the report
</code></pre>
<p>If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a):</p>
<ol>
<li>depfun</li>
<li>depdir</li>
</ol>
<p>For example, </p>
<pre><code>>> deps = depfun('foo');
</code></pre>
<p>gives a structure, deps, that contains all the dependencies of foo.m.</p>
<p>From answers <a href="http://stackoverflow.com/a/29049918/4612">2</a>, and <a href="http://stackoverflow.com/a/34621308/4612">3</a>, newer versions of MATLAB (post 2015a) use <code>matlab.codetools.requiredFilesAndProducts</code> instead.</p>
<p>See answers </p>
<p>EDIT:</p>
<p>Caveats thanks to @Mike Katz comments</p>
<blockquote>
<ul>
<li><p>Remember that the Profiler will only
show you files that were actually used
in those runs, so if you don't go
through every branch, you may have
additional dependencies. The
dependency report is a good tool, but
only resolves static dependencies on
the path and just for the files in a
single directory. </p></li>
<li><p>Depfun is more reliable but gives you
every possible thing it can think of,
and still misses LOAD's and EVAL's.</p></li>
</ul>
</blockquote>
|
How do I add FTP support to Eclipse? <p>I'm using Eclipse PHP Development Tools. What would be the easiest way to access a file or maybe create a remote project trough FTP and maybe SSH and SFTP?.</p>
|
<p>Eclipse natively supports FTP and SSH. Aptana is not necessary.</p>
<p>Native FTP and SSH support in Eclipse is in the "Remote System Explorer End-User Runtime" Plugin.</p>
<p>Install it through Eclipse itself. These instructions may vary slightly with your version of Eclipse:</p>
<ol>
<li>Go to 'Help' -> 'Install New Software' (in older Eclipses, this is called something a bit different)</li>
<li>In the 'Work with:' drop-down, select your version's plugin release site. Example: for Kepler, this is <br/> <em>Kepler - <a href="http://download.eclipse.org/releases/kepler">http://download.eclipse.org/releases/kepler</a></em> </li>
<li>In the filter field, type 'remote'.</li>
<li>Check the box next to 'Remote System Explorer End-User Runtime'</li>
<li>Click 'Next', and accept the terms. It should now download and install.</li>
<li>After install, Eclipse may want to restart.</li>
</ol>
<p>Using it, in Eclipse:</p>
<ol>
<li>Window -> Open Perspective -> (perhaps select 'Other') -> Remote System Explorer</li>
<li>File -> New -> Other -> Remote System Explorer (folder) -> Connection (or type Connection into the filter field)</li>
<li>Choose FTP from the 'Select Remote System Type' panel.</li>
<li>Fill in your FTP host info in the next panel (username and password come later).</li>
<li>In the Remote Systems panel, right-click the hostname and click 'connect'.</li>
<li>Enter username + password and you're good!</li>
<li>Well, not exactly 'good'. The RSE system is fairly unusual, but you're connected.</li>
<li>And you're one smart cookie! You'll figure out the rest.</li>
</ol>
<p><strong>Edit:</strong> To change the default port, follow the instructions on this page: <a href="http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/">http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/</a></p>
|
In Perl, how do I create a hash whose keys come from a given array? <p>Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say <pre>if($hash{X}) { ... }</pre></p>
<p>Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.</p>
|
<pre><code>%hash = map { $_ => 1 } @array;
</code></pre>
<p>It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.</p>
<p>What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.</p>
|
How to find Commit Charge programmatically? <p>I'm looking for the total <a href="http://en.wikipedia.org/wiki/Commit_charge" rel="nofollow">commit charge</a>.</p>
|
<pre><code> public static long GetCommitCharge()
{
var p = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes");
return p.RawValue;
}
</code></pre>
|
What is a variable's linkage and storage specifier? <p>When someone talks about a variables storage class specifier, what are they talking about?<br />
They also often talk about variable linkage in the same context, what is that?</p>
|
<p>The storage class specifier controls the <em>storage</em> and the <em>linkage</em> of your variables. These are two concepts that are different.
C specifies the following specifiers for variables: auto, extern, register, static.</p>
<p><strong>Storage</strong><br />
The storage duration determines how long your variable will live in ram.<br />
There are three types of storage duration: static, automatic and dynamic.</p>
<p><em>static</em><br />
If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables.</p>
<p><em>automatic</em><br />
If the variable is declared in a function, but <strong>without</strong> the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function. Once you return, the variable no longer exist. Automatic storage is typically done on the stack. It is a very fast operation to create these variables (simply increment the stack pointer by the size).</p>
<p><em>dynamic</em><br />
If you use malloc (or new in C++) you are using dynamic storage. This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically.</p>
<p><strong>Linkage</strong><br />
Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage.</p>
<p><em>no linkage</em><br />
This variable is only visible where it was declared. Typically applies to variables declared in a function.</p>
<p><em>internal linkage</em><br />
This variable will be visible to all the functions within the file (called a <a href="http://stackoverflow.com/questions/28160/multiple-classes-in-a-header-file-vs-a-single-header-file-per-class">translation unit</a>), but other files will not know it exists.</p>
<p><em>external linkage</em><br />
The variable will be visible to other translation units. These are often thought of as "global variables".</p>
<p>Here is a table describing the storage and linkage characteristics based on the specifiers</p>
<pre>
Storage Class Function File
Specifier Scope Scope
-----------------------------------------------------
none automatic static
no linkage external linkage
extern static static
external linkage external linkage
static static static
no linkage internal linkage
auto automatic invalid
no linkage
register automatic invalid
no linkage
</pre>
|
Find a private field with Reflection? <p>Given this class</p>
<pre><code>class Foo
{
// Want to find _bar with reflection
[SomeAttribute]
private string _bar;
public string BigBar
{
get { return this._bar; }
}
}
</code></pre>
<p>I want to find the private item _bar that I will mark with a attribute. Is that possible? </p>
<p>I have done this with properties where I have looked for an attribute, but never a private member field.</p>
<p>What are the binding flags that I need to set to get the private fields?</p>
|
<p>Use <code>BindingFlags.NonPublic</code> and <code>BindingFlags.Instance</code> flags</p>
<pre><code>FieldInfo[] fields = myType.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);
</code></pre>
|
Python reading Oracle path <p>On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit.</p>
<p>I was getting errors about loading the OCI dll, so I installed the 32 bit client into <code>C:\oracle32</code>.</p>
<p>If I add this to the <code>PATH</code> environment variable, it works great. But I also want to run the Pylons app as a service (<a href="http://wiki.pylonshq.com/display/pylonscookbook/How+to+run+Pylons+as+a+Windows+service" rel="nofollow">using this recipe</a>) and don't want to put this 32-bit library on the path for all other applications. </p>
<p>I tried using <code>sys.path.append("C:\\oracle32\\bin")</code> but that doesn't seem to work.</p>
|
<p>sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH.</p>
<p>I'm not sure that this will work, but you can try:</p>
<pre><code>import os
os.environ['PATH'] += os.pathsep + "C:\\oracle32\\bin"
</code></pre>
|
Flex best practices? <p>I have the feeling that is easy to find samples, tutorials and simple examples on Flex.<br>
It seems harder to find tips and good practices based on real-life projects.<br>
Any tips on how to :</p>
<ul>
<li>How to write maintainable actionscript code</li>
<li>How to ensure a clean separation of concern. Has anybody used an MVC framework such as cairngorm, puremvc or easymvc on a real Flex project ?</li>
<li>How to fetch data from a server with blazeds/amfphp ?</li>
<li>How to reduce latency for the end-user ?</li>
<li>...</li>
</ul>
|
<p>I work often with Flex in my job, and I will be happy to help.. but your questions deserve an article for each one :) I'll try some short answer.</p>
<p>Maintenable code: I think that the same rules of any other OO languages apply. Some flex-specific rules I'm use to follow: use strong typed variables, always consider dispatching events as the way for your UI components talk each other (a little more initial work, very flexible and decoupled later).</p>
<p>Frameworks: looked at it, read the documentation.. very nice, but I still feel that their complications are not balanced by the benefits they provide. Anyway I'd like to change my mind on this point..</p>
<p>Talking with server: Right now I'm using BlazeDS, it works very well.. there are many tutorials on the subject out there, if you find any trouble setting up it I would be happy to help.</p>
<p>Latency: Do you mean in client/server comunications? If so, you should explore the various type of channels BlazeDS implements.. pull-only, two-way http polling, near real-time on http (comet).. if you need more, LiveCycle Data Services ES, the commrcial implementation from which BlazeDS is born, among other things offer another protocol called RTMP, it isn't http-tunnelled so there can be problem with firewalls and proxies, but it offers better performance (there is a free closed-source version of LCDS). I use the standard http channels in intranet environments, and found no real performance problems even with large datasets.</p>
<p>Well.. quite a lot of stuff, can't be more specific now on each of this points, ask you if need :)</p>
|
OLEDBConnection.Open() generates 'Unspecified error' <p>I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server <strong>only</strong>. The application works fine on two other servers (development and testing servers).</p>
<p>The following code generates an 'Unspecified Error' in the Exception.Message.</p>
<p><strong>Quote:</strong></p>
<pre><code> System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
try
{
x.Open();
}
catch (Exception exp)
{
string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message;
Utilities.SendErrorEmail(errorEmailBody);
}
</code></pre>
<p><strong>:End Quote</strong></p>
<p>The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control.</p>
<p>I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.</p>
|
<p>While the permissions issue may be more common you can also encounter this error from Windows file system/Access Jet DB Engine connection limits, 64/255 I think. If you bust the 255 Access read/write concurrent connections or the 64(?) connection limit per process you can get this exact same error. At least I've come across that in an application where connections were being continually created and never properly closed. A simple <code>Conn.close();</code> dropped in and life was good. I imagine Excel could have similar issues. </p>
|
Web Dev - Where to store state of a shopping-cart-like object? <p>You're building a web application. You need to store the state for a <em>shopping cart like</em> object during a user's session.</p>
<p>Some notes:</p>
<ul>
<li>This is not exactly a shopping cart, but more like an itinerary that the user is building... but we'll use the word cart for now b/c ppl relate to it.</li>
<li>You do not care about "abandoned" carts</li>
<li>Once a cart is completed we will persist it to some server-side data store for later retrieval.</li>
</ul>
<p><strong>Where</strong> do you store that stateful object? And <strong>how</strong>?</p>
<ul>
<li>server (session, db, etc?)</li>
<li>client (cookie key-vals, cookie JSON object, hidden form-field, etc?)</li>
<li>other...</li>
</ul>
<p><strong>Update</strong>: It was suggested that I list the platform we're targeting - tho I'm not sure its totally necessary... but lets say the front-end is built w/ASP.NET MVC.</p>
|
<p>It's been my experience with the Commerce Starter Kit and MVC Storefront (and other sites I've built) that no matter what you think now, information about user interactions with your "products" is paramount to the business guys. There's so many metrics to capture - it's nuts.</p>
<p>I'll save you all the stuff I've been through - what's by far been the most successful for me is just creating an Order object with "NotCheckedOut" status and then adding items to it and the user adds items. This lets users have more than one cart and allows you to mine the tar out of the Orders table. It also is quite easy to transact the order - just change the status.</p>
<p>Persisting "as they go" also allows the user to come back and finish the cart off if they can't, for some reason. Forgiveness is massive with eCommerce. </p>
<p>Cookies suck, session sucks, Profile is attached to the notion of a user and it hits the DB so you might as well use the DB.</p>
<p>You might <em>think</em> you don't want to do this - but you need to <em>trust</em> me and know that you WILL indeed need to feed the stats wonks some data later. I promise you.</p>
|
Can I create a Visual Studio macro to launch a specific project in the debugger? <p>My project has both client and server components in the same solution file. I usually have the debugger set to start them together when debugging, but it's often the case where I start the server up outside of the debugger so I can start and stop the client as needed when working on client-side only stuff. (this is much faster). </p>
<p>I'm trying to save myself the hassle of poking around in Solution Explorer to start individual projects and would rather just stick a button on the toolbar that calls a macro that starts the debugger for individual projects (while leaving "F5" type debugging alone to start up both processess). </p>
<p>I tried recording, but that didn't really result in anything useful. </p>
<p>So far all I've managed to do is to locate the project item in the solution explorer: </p>
<pre><code> Dim projItem As UIHierarchyItem
projItem = DTE.ToolWindows.SolutionExplorer.GetItem("SolutionName\ProjectFolder\ProjectName").Select(vsUISelectionType.vsUISelectionTypeSelect)
</code></pre>
<p>(This is based loosely on how the macro recorder tried to do it. I'm not sure if navigating the UI object model is the correct approach, or if I should be looking at going through the Solution/Project object model instead). </p>
|
<p>Ok. This appears to work from most UI (all?) contexts provided the solution is loaded: </p>
<pre><code> Sub DebugTheServer()
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()
DTE.ActiveWindow.Object.GetItem("Solution\ServerFolder\ServerProject").Select(vsUISelectionType.vsUISelectionTypeSelect)
DTE.Windows.Item(Constants.vsWindowKindOutput).Activate()
DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance")
End Sub
</code></pre>
|
Best Approach For Configuring Multiple .Net Applications <p>We have a suite of interlinked .Net 3.5 applications. Some are web sites, some are web services, and some are windows applications. Each app currently has its own configuration file (app.config or web.config), and currently there are some duplicate keys across the config files (which at the moment are kept in sync manually) as multiple apps require the same config value. Also, this suite of applications is deployed across various envrionemnts (dev, test, live etc)</p>
<p>What is the best approach to managing the configuration of these multiple apps from a single configuration source, so configuration values can be shared between multiple apps if required? We would also like to have separate configs for each environment (so when deploying you don't have to manually change certain config values that are environment specific such as conenction strings), but at the same time don't want to maintain multiple large config files (one for each environment) as keeping this in sync when adding new config keys will prove troublesome.</p>
<p>Thanks in advance</p>
<p>Robin</p>
|
<p>Visual Studio has a relatively obscure feature that lets you add existing items as links, which should accomplish what you're looking for. Check out <a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/04/15/how-to-share-configuration-files-between-projects.aspx" rel="nofollow">Derik Whittaker's post</a> on this topic for more detail.</p>
<p>Visual Studio really should make this option more visible. Nobody really thinks to click on that little arrow next to the "Add" button.</p>
|
Writing post data from one java servlet to another <p>I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST.
(Non essential xml generating code replaced with "Hello there")</p>
<pre><code> StringBuilder sb= new StringBuilder();
sb.append("Hello there");
URL url = new URL("theservlet's URL");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "" + sb.length());
OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
</code></pre>
<p>This is causing a server error, and the second servlet is never invoked.</p>
|
<p>This kind of thing is much easier using a library like <a href="http://hc.apache.org/httpclient-3.x/">HttpClient</a>. There's even a <a href="http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup">post XML code example</a>:</p>
<pre><code>PostMethod post = new PostMethod(url);
RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
</code></pre>
|
SQL server 2000 Like Statement Usage <p>I have a SQL statement that looks like:</p>
<pre><code>SELECT [Phone]
FROM [Table]
WHERE
(
[Phone] LIKE '[A-Z][a-z]'
OR [Phone] = 'N/A'
OR [Phone] LIKE '[0]'
)
</code></pre>
<p>The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used <code>like</code> statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned. </p>
<p>Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine. </p>
<p>What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.</p>
|
<p>Check <a href="http://technet.microsoft.com/en-us/library/aa933232%28v=sql.80%29.aspx" rel="nofollow">here</a>.</p>
<p>[] matches a range of characters.</p>
<p>I think you want something like this:</p>
<pre><code>SELECT [Phone]
FROM [Table]
WHERE
(
[Phone] LIKE '%[A-Z]%'
OR [Phone] LIKE '%[a-z]%'
OR [Phone] = 'N/A'
OR [Phone] LIKE '0'
)
</code></pre>
|
How to read the value of a text input in a Flash SWF from a Flex App? <p>I have a Flex application, which loads a SWF from CS3. The loaded SWF contains a text input called "myText". I can see this in the SWFLoader.content with no problems, but I don't know what type I should be treating it as in my Flex App. I thought the flex docs covered this but I can only find how to interact with another Flex SWF.</p>
<p>The Flex debugger tells me it is of type fl.controls.TextInput, which makes sense. But FlexBuilder doesn't seem to know this class. While Flash and Flex both use AS3, Flex has a whole new library of GUI classes. I thought it also had all the Flash classes, but I can't get it to know of ANY fl.*** packages.</p>
|
<p>The <code>fl.*</code> hierarchy of classes is Flash CS3-only. It's the Flash Components 3 library (I believe it's called, I might be wrong). However, you don't need the class to work with the object. As long as you can get a reference to it in your code, which you seem to have, you can assign the reference to an untyped variable and work with it anyway:</p>
<pre><code>var textInput : * = getTheTextInput(); // insert your own method here
textInput.text = "Lorem ipsum dolor sit amet";
textInput.setSelection(4, 15);
</code></pre>
<p>There is no need to know the type of an object in order to interact with it. Of course you lose type checking at compile time, but that's really not much of an issue, you just have to be extra careful.</p>
<p>If you really, really want to reference the object as its real type, the class in question is located in </p>
<pre><code>Adobe Flash CS3/Configuration/Component Source/ActionScript 3.0/User Interface/fl/controls/TextInput.as
</code></pre>
<p>...if you have Flash CS3 installed, because it only ships with that application.</p>
|
What's the most current, good practice, and easiest way to use sessions in PHP? <p>Sessions in PHP seemed to have changed since the last time I used them, so I'm looking for a simple way of using sessions but at the same time for it to be relatively secure and a good common practice.</p>
|
<p>Session management changed some time back (I think it was around 4.4). The old mechanism still works, but is deprecated. It's rather confusing, so I recommend staying clear of it. Today, you use sessions by accessing the global variable $_SESSION (It's an array). You <em>can</em> put object instances in there, but you need to load the class definitions for those objects before starting the session on the next page. Using <a href="http://docs.php.net/manual/en/language.oop5.autoload.php" rel="nofollow">autoload</a> can help you out here.</p>
<p>You must <a href="http://docs.php.net/manual/en/function.session-start.php" rel="nofollow">start a session</a> before you can use $_SESSION. Since starting the session sends headers, you can't have any output before. This can be solved in one of two ways:
Either you always begin the session at the start of your script. Or you <a href="http://docs.php.net/manual/en/book.outcontrol.php" rel="nofollow">buffer all output</a>, and send it out at the end of the script.</p>
<blockquote>
<p>One good idea is to regenerate the session on each request. this makes hijack much less likely.</p>
</blockquote>
<p>That's (slightly) bad advice, since it can make the site inaccessible. You should <a href="http://docs.php.net/manual/en/function.session-regenerate-id.php" rel="nofollow">regenerate the session-id</a> whenever a users privileges changes though. In general that means, whenever they log in. This is to prevent session-fixation (A form of session-hijacking). See <a href="http://www.sitepoint.com/forums/showthread.php?t=571084" rel="nofollow">this recent thread @ Sitepoint</a> for more on the subject.</p>
<p>Using cookiebased sessions <em>only</em> is OK, but if you regenerate session id's on login, it doesn't add any additional security, and it lowers accessibility a bit.</p>
|
Is there anything wrong with returning default constructed values? <p>Suppose I have the following code:</p>
<pre><code>class some_class{};
some_class some_function()
{
return some_class();
}
</code></pre>
<p>This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?</p>
|
<p>No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.</p>
|
Tools To Help You Plan Projects / Features <p>What tools do you use to plan a project or a large feature set? I currently use a mix of Word for writing specs and Photoshop for mockups, but is there something more suited for developers?</p>
|
<p>I would set up a Wiki. Its what I use for planning, since its visible to everyone on the team, and editable by everyone on the team. <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a> is the Wiki that I use. <a href="http://moinmoin.wikiwikiweb.de/" rel="nofollow">MoinMoin</a> is another Wiki that I have used.</p>
|
How do I remove the .NET Compact Framework from my Windows Mobile 5 device? <p>I'm trying to get a number of third party applications to work on my Windows Mobile 5 smartphone.</p>
<p>I've installed the latest version (3.5) of the Microsoft.NET Compact Framework, but whenever I run the apps I get an error message which states: "This application [Application Name] requires a newer version of the Microsoft .NET Compact Framework than the version installed on this device."</p>
<p>Given I've supposedly successfully installed the latest version, this doesn't make sense, leading me to believe I need to remove the .NET Compact Framework and start again. (I've tried reinstalling it, but as far as I can tell there's no automated way of removing it on the device, or from my PC.)</p>
<p>Does anyone have any suggestions as to what I need to do? Thanks!</p>
|
<p>It's probably better to <em>not</em> uninstall, and if it's on the device in ROM you can't uninstall it anyway.</p>
<p>There are a couple options available to you.</p>
<ol>
<li>The different CF versions coexist fine, so you can install the older version and leave 3.5 on it.</li>
<li>The CF can be set for compatibility mode. That means you can tell just a single app compiled against an old version use the 3.5 runtimes in compatibility mode or you can set that device-wide so <em>all</em> older CF apps will run agains the 3.5 EE in compatibility mode.</li>
</ol>
<p>For online resources discussing configuration files and compatibility mode, see these links:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb629366.aspx" rel="nofollow">MSDN Article on Configuration File Settings</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/d5cd9b2c.aspx" rel="nofollow">MSDN Article on Configuring Runtime Versions</a></li>
<li><a href="http://blogs.msdn.com/davidklinems/archive/2005/04/19/409541.aspx" rel="nofollow">David Kline's blog on Compatibility Mode</a></li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=C8174C14-A27D-4148-BF01-86C2E0953EAB&displaylang=en" rel="nofollow">The CF 3.5 Power Toys</a> (includes an app for setting configurations)</li>
</ul>
<p>Note: I forgot to mention in the original response that using option #2 (running against CF 3.5) will very likely improve the performance of the app as well, since it will be running with the newest CLR.</p>
|
Why is Visual Studio constantly crashing? <p>Visual Studio randomly crashes when adding/removing references and projects.
Any thoughts why? Will installing Sp1 help?</p>
<p>EDIT: I do not work with any addons except SourceSafe. I do most of my development in connected mode.<br></p>
<p>Developing using:<br>
Visual Studio 2008 <br>
WinXp Terminal Service -> Win2k3 Sp2 (64bit)<br>
VSS 8.0, 32bit<br></p>
|
<p>Try deleting your .user and .suo files - these are the user options files that VS creates. You get a .user file for each project and a .suo file for your solution. When they get corrupted, odd things happen. Deleting them will make you lose little things like which project is selected as the startup project when you start debugging, but it usually clears up odd behavior like this.</p>
<p>You may also want to clear out any temporary file locations, like the Temporary ASP.NET Files folders (if you're working in ASP.NET) just in case something odd is being cached somewhere.</p>
|
Real-world problems with naive shuffling <p>I'm writing a number of articles meant to teach beginning programming concepts through the use of poker-related topics. Currently, I'm working on the subject of shuffling.</p>
<p>As <a href="http://www.codinghorror.com/blog/archives/001015.html" rel="nofollow" title="The Danger of Naivete">Jeff Atwood points out on CodingHorror.com</a>, one simple shuffling method (iterating through an array and swapping each card with a random card elsewhere in the array) creates an uneven distribution of permutations. In an actual application, I would just use the <a href="http://en.wikipedia.org/wiki/Knuth_shuffle" rel="nofollow" title="Knuth Fisher-Yates shuffle">Knuth Fisher-Yates shuffle</a> for more uniform randomness. But, I don't want to bog down an explanation of programming concepts with the much less coder-friendly algorithm.</p>
<p>This leads to the question: Just how much of an advantage would a black-hat have if they knew you were using a naive shuffle of a 52-card deck? It seems like it would be infinitesimally small.</p>
|
<p>The knuth shuffle is an insignificant change compared to the naive shuffle: Just swap with any card in the remaining (unshuffled) section of the deck instead of anywhere in the entire deck. If you think of it as repeatedly choosing the next card in order from the remaining unchosen cards, it's pretty intuitive, too.</p>
<p>Personally, I think teaching students a poor algorithm when the proper one is no more complicated (and easier to visualise!) is a bad approach.</p>
|
std::map insert or std::map find? <p>Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?</p>
|
<p>The answer is you do neither. Instead you want to do something suggested by Item 24 of <a href="http://rads.stackoverflow.com/amzn/click/0201749629">Effective STL</a> by <a href="http://www.aristeia.com/">Scott Meyers</a>:</p>
<pre><code>typedef map<int, int> MapType; // Your map type may vary, just change the typedef
MapType mymap;
// Add elements to map here
int k = 4; // assume we're searching for keys equal to 4
int v = 0; // assume we want the value 0 associated with the key of 4
MapType::iterator lb = mymap.lower_bound(k);
if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first)))
{
// key already exists
// update lb->second if you care to
}
else
{
// the key does not exist in the map
// add it to the map
mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert,
// so it can avoid another lookup
}
</code></pre>
|
Any HTTP proxies with explicit, configurable support for request/response buffering and delayed connections? <p>When dealing with mobile clients it is very common to have multisecond delays during the transmission of HTTP requests. If you are serving pages or services out of a prefork Apache the child processes will be tied up for seconds serving a single mobile client, even if your app server logic is done in 5ms. I am looking for a HTTP server, balancer or proxy server that supports the following:</p>
<ol>
<li><p>A request arrives to the proxy. The proxy starts buffering in RAM or in disk the request, including headers and POST/PUT bodies. The proxy DOES NOT open a connection to the backend server. This is probably the most important part.</p></li>
<li><p>The proxy server stops buffering the request when:</p>
<ul>
<li>A size limit has been reached (say, 4KB), or</li>
<li>The request has been received completely, headers and body</li>
</ul></li>
<li><p>Only now, with (part of) the request in memory, a connection is opened to the backend and the request is relayed.</p></li>
<li><p>The backend sends back the response. Again the proxy server starts buffering it immediately (up to a more generous size, say 64KB.) </p></li>
<li><p>Since the proxy has a big enough buffer the backend response is stored completely in the proxy server in a matter of miliseconds, and the backend process/thread is free to process more requests. The backend connection is immediately closed.</p></li>
<li><p>The proxy sends back the response to the mobile client, as fast or as slow as it is capable of, without having a connection to the backend tying up resources.</p></li>
</ol>
<p>I am fairly sure you can do 4-6 with Squid, and nginx appears to support 1-3 (and looks like fairly unique in this respect). My question is: is there any proxy server that empathizes these buffering and not-opening-connections-until-ready capabilities? Maybe there is just a bit of Apache config-fu that makes this buffering behaviour trivial? Any of them that it is not a dinosaur like Squid and that supports a lean single-process, asynchronous, event-based execution model?</p>
<p>(Siderant: I would be using nginx but it doesn't support chunked POST bodies, making it useless for serving stuff to mobile clients. Yes cheap 50$ handsets love chunked POSTs... sigh)</p>
|
<p>What about using both nginx and Squid (client â Squid â nginx â backend)? When <em>returning</em> data from a backend, Squid does convert it from C-T-E: chunked to a regular stream with Content-Length set, so maybe it can normalize POST also.</p>
|
How do I capture an asterisk on the form's KeyUp event? OR, How do I get a KeyChar on the KeyUp event? <p>I'm trying to hijack an asterisk with the form's KeyUp event. I can get the SHIFT key and the D8 key on the KeyUp event, but I can't get the * out of it. I can find it easily in the KeyPress event (e.KeyChar = "*"c), but company standards say that we have to use the KeyUp event for all such occasions. Thanks!</p>
|
<p>Cache the charcode on KeyPress and then respond to KeyUp. There are other key combinations that will generate the asterisk, especially if you're facing international users who may have different keyboard layouts, so you can't rely on the KeyUp to give you the information you need.</p>
|
Run macro automatically OnSave in Word <p>I have a macro which refreshes all fields in a document (the equivalent of doing an <kbd>F9</kbd> on the fields). I'd like to fire this macro automatically when the user saves the document.</p>
<p>Under options I can select "update fields when document is printed", but that's not what I want. In the VBA editor I only seem to find events for the <code>Document_Open()</code> event, not the <code>Document_Save()</code> event.</p>
<p>Is it possible to get the macro to fire when the user saves the document?</p>
<p>Please note:</p>
<ol>
<li>This is Word 97. I know it is
possible in later versions of Word</li>
<li>I don't want to replace the standard
Save button on the toolbar with a
button to run my custom macro.
Replacing the button on the toolbar
applies to all documents and I only
want it to affect this one document.</li>
</ol>
<p>To understand why I need this, the document contains a "SaveDate" field and I'd like this field to update on the screen when the user clicks Save. So if you can suggest another way to achieve this, then that would be just as good.</p>
|
<p>As far as I can remember of Word 97, you're fresh out of luck. The only document events in '97 were Open and Close. </p>
<p>I don't have Word 97 available, but in Word 2000+ you can set a field that reads a document property. You could check that out. In Word 2003 it's under <strong>Insert > Field...</strong> and the one you're looking for is called <strong>SaveDate</strong>.</p>
<p>Edit: D'Uh. You already knew this. Misunderstood your issue. Apologies.</p>
|
How to get the ROWID from a Progress database <p>I have a Progress database that I'm performing an ETL from. One of the tables that I'm reading from does not have a unique key on it, so I need to access the ROWID to be able to uniquely identify the row. What is the syntax for accessing the ROWID in Progress?</p>
<p>I understand there are problems with using ROWID for row identification, but it's all I have right now.</p>
|
<p>A quick caveat for my answer - it's nearly 10 years since I worked with <a href="http://www.progress.com/">Progress</a> so my knowledge is probably more than a little out of date.</p>
<p>Checking the <a href="http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf">Progress Language Reference</a> [PDF] seems to show the two functions I remember are still there: <code>ROWID</code> and <code>RECID</code>. The <code>ROWID</code> function is newer and is preferred.</p>
<p>In Progress 4GL you'd use it something like this:</p>
<pre><code>FIND customer WHERE cust-num = 123.
crowid = ROWID(customer).
</code></pre>
<p>or:</p>
<pre><code>FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK.
</code></pre>
<p>Checking the <a href="http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf">Progress SQL Reference</a> [PDF] shows <code>ROWID</code> is also available in SQL as a Progress extension. You'd use it like so:</p>
<pre><code>SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123
</code></pre>
<p><strong>Edit:</strong> Edited following Stefan's feedback.</p>
|
NHibernate, auditing and computed column values <p>How is possible to set some special column values when update/insert entities via NHibernate without extending domain classes with special properties?</p>
<p>E.g. every table contains audit columns like CreatedBy, CreatedDate, UpdatedBy, UpdatedDate. But I dont want to add these poperties to the domain classes. I want to keep domain modedl Percistence Ignorance factor as high as possible.</p>
|
<p>You might want to try looking into NHibernate's IUserType.</p>
<p>At the bottom of the following page is an example where ayende removes some encryption logic out of the entity and allows NHibernate to just take care of it.</p>
<p><a href="http://ayende.com/Blog/archive/2008/07/31/Entities-dependencies-best-practices.aspx" rel="nofollow">http://ayende.com/Blog/archive/2008/07/31/Entities-dependencies-best-practices.aspx</a></p>
|
What's the best tool to track a process's memory usage over a long period of time in Windows? <p>What is the best available tool to monitor the memory usage of my C#/.Net windows service over a long period of time. As far as I know, tools like perfmon can monitor the memory usage over a short period of time, but not graphically over a long period of time. I need trend data over days, not seconds.</p>
<p>To be clear, I want to monitor the memory usage at a fine level of detail over a long time, and have the graph show both the whole time frame and the level of detail. I need a small sampling interval, and a large graph.</p>
|
<p>Perfmon in my opinion is one of the best tools to do this but make sure you properly configure the sampling interval according to the time you wish to monitor.</p>
<p>For example if you want to monitor a process:</p>
<ul>
<li>for 1 hour : I would use 1 second intervals (this will generate 60*60 samples)</li>
<li>for 1 day : I would use 30 second intervals (this will generate 2*60*24 samples)</li>
<li>for 1 week : I would use 1 minute intervals (this will generate 60*24*7 samples)</li>
</ul>
<p>With these sampling intervals Perfmon should have no problem generating a nice graphical output of your counters.</p>
|
force Maven2 to copy dependencies into target/lib <p>How do I get my project's runtime dependencies copied into the <code>target/lib</code> folder? </p>
<p>As it is right now, after <code>mvn clean install</code> the <code>target</code> folder contains only my project's jar, but none of the runtime dependencies.</p>
|
<p>This works for me:</p>
<pre class="lang-xml prettyprint-override"><code><project>
...
<profiles>
<profile>
<id>qa</id>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
</code></pre>
|
How can I fix this delphi 7 compile error - "Duplicate resource(s)" <p>I'm trying to compile a Delphi 7 project that I've inherited, and I'm getting this error:</p>
<blockquote>
<p>[Error] WARNING. Duplicate resource(s):<br>
[Error] Type 2 (BITMAP), ID EDIT:<br>
[Error] File C:[path shortened]\common\CRGrid.res resource kept; file c:\common\raptree.RES resource discarded.</p>
</blockquote>
<p>It says warning, but it's actually an error - compilation does not complete.</p>
<p>It looks like two components - CRGrid and RapTree - are colliding somehow. Does anyone have any ideas on how to fix this?</p>
<p>Other than removing one of components from the project, of course.</p>
|
<p>Try firing up your resource editor (I'm pretty sure Delphi comes with one) and open the files. Check what bitmap resources are in the two, see which can be the duplicate.</p>
<p>If you need to keep both resources, you need to renumber one of them.</p>
|
WAS hosting vs. Windows Service hosting <p>I'm working on a project using Windows 2008, .NET 3.5 and WCF for some internal services and the question of how to host the services has arisen.</p>
<p>Since we're using Windows 2008 I was thinking it'd be good to take advantage of Windows Process Activation Service (WAS) although the feeling on the project seems to be that using Windows Services would be better.</p>
<p>So what's the low down on using WAS to host WCF services in comparison to a Windows Service? Are there any real advantages to using Windows Services or is WAS the way to go?</p>
|
<p>Recently I had to answer very similar question and these are the reasons why I decided to use IIS 7.0 and WAS instead of Windows Service infrastructure.</p>
<ol>
<li>IIS 7.0 is much more robust host and it comes with numerous features that make debugging easy. Failed requests tracing, worker process recycling, process orphaning to name a few.</li>
<li>IIS 7.0 gives you more option to specify what should happen with the worker process in certain circumstances. </li>
<li>If you host your service under IIS it doesn't have a worker process assigned to it until the very first request. This is something that was a desired behaviour from my perspective but it might be different in your case. Windows Service gives you the ability to start your service in a more deterministic way.</li>
<li>From my experience WAS itself doesn't provide increased reliability. It's biggest advantage is that it exposes the richness of IIS to applications that use protocols different than HTTP. By different I mean: TCP, named pipes and MSMQ.</li>
<li>The only disadvantage of using WAS that I'm aware of is that the address your service is exposed at needs to be compliant with some sort of pattern. How it looks like in case of MSMQ is described <a href="http://blogs.msdn.com/tomholl/archive/2008/07/12/msmq-wcf-and-iis-getting-them-to-play-nice-part-1.aspx">here</a></li>
</ol>
|
How to send mail from ASP.NET with IIS6 SMTP in a dedicated server? <p>I'm trying to configure a dedicated server that runs ASP.NET to send mail through the local IIS SMTP server but mail is getting stuck in the Queue folder and doesn't get delivered.</p>
<p>I'm using this code in an .aspx page to test:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" %>
<% new System.Net.Mail.SmtpClient("localhost").Send("[email protected]",
"[email protected]", "testing...", "Hello, world.com"); %>
</code></pre>
<p>Then, I added the following to the Web.config file:</p>
<pre><code><system.net>
<mailSettings>
<smtp>
<network host="localhost"/>
</smtp>
</mailSettings>
</system.net>
</code></pre>
<p>In the IIS Manager I've changed the following in the properties of the "Default SMTP Virtual Server".</p>
<pre><code>General: [X] Enable Logging
Access / Authentication: [X] Windows Integrated Authentication
Access / Relay Restrictions: (o) Only the list below, Granted 127.0.0.1
Delivery / Advanced: Fully qualified domain name = thedomain.com
</code></pre>
<p>Finally, I run the SMTPDiag.exe tool like this:</p>
<pre><code>C:\>smtpdiag.exe [email protected] [email protected]
Searching for Exchange external DNS settings.
Computer name is THEDOMAIN.
Failed to connect to the domain controller. Error: 8007054b
Checking SOA for gmail.com.
Checking external DNS servers.
Checking internal DNS servers.
SOA serial number match: Passed.
Checking local domain records.
Checking MX records using TCP: thedomain.com.
Checking MX records using UDP: thedomain.com.
Both TCP and UDP queries succeeded. Local DNS test passed.
Checking remote domain records.
Checking MX records using TCP: gmail.com.
Checking MX records using UDP: gmail.com.
Both TCP and UDP queries succeeded. Remote DNS test passed.
Checking MX servers listed for [email protected].
Connecting to gmail-smtp-in.l.google.com [209.85.199.27] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to gmail-smtp-in.l.google.com.
Connecting to gmail-smtp-in.l.google.com [209.85.199.114] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to gmail-smtp-in.l.google.com.
Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.27] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to alt2.gmail-smtp-in.l.google.com.
Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.114] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to alt2.gmail-smtp-in.l.google.com.
Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.27] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to alt1.gmail-smtp-in.l.google.com.
Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.27] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to alt2.gmail-smtp-in.l.google.com.
Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.114] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to alt2.gmail-smtp-in.l.google.com.
Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.114] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to alt1.gmail-smtp-in.l.google.com.
Connecting to gsmtp183.google.com [64.233.183.27] on port 25.
Connecting to the server failed. Error: 10060
Failed to submit mail to gsmtp183.google.com.
Connecting to gsmtp147.google.com [209.85.147.27] on port 25.
Connecting to the server failed. Error: 10051
Failed to submit mail to gsmtp147.google.com.
</code></pre>
<p>I'm using ASP.NET 2.0, Windows 2003 Server and the IIS that comes with it.</p>
<p>Can you tell me what else to change to fix the problem?</p>
<p>Thanks</p>
<hr>
<p>@mattlant</p>
<p>This is a dedicated server that's why I'm installing the SMTP manually.</p>
<blockquote>
<p>EDIT: I use exchange so its a little
different, but its called a smart host
in exchange, but in plain SMTP service
config i think its called something
else. Cant remember exactly the
setting name.</p>
</blockquote>
<p>Thank you for pointing me at the Smart host field. Mail is getting delivered now.</p>
<p>In the Default SMTP Virtual Server properties, the Delivery tab, click Advanced and fill the "Smart host" field with the address that your provider gives you. In my case (GoDaddy) it was k2smtpout.secureserver.net.</p>
<p>More info here: <a href="http://help.godaddy.com/article/1283" rel="nofollow">http://help.godaddy.com/article/1283</a></p>
|
<p>I find the best thing usually depending on how much email there is, is to just forward the mail through your ISP's SMTP server. Less headaches. Looks like that's where you are having issues, from your SMTP to external servers, not asp.net to your SMTP.</p>
<p>Just have your SMTP server set to send it to your ISP, or you can configure asp.net to send to it.</p>
<p>EDIT: I use exchange so it's a little different, but it's called a smart host in exchange, but in plain SMTP service config I think it's called something else. </p>
<p>I can't remember exactly the setting name.</p>
|
Version control on a 2GB USB drive <p>For my school work, I do a lot of switching computers (from labs to my laptop to the library). I'd kind of like to put this code under some kind of version control. Of course the problem is that I can't always install additional software on the computers I use. Is there any kind of version control system that I can keep on a thumb drive? I have a 2GB drive to put this on, but I can get a bigger one if necessary.</p>
<p>The projects I'm doing aren't especially big FYI.</p>
<p><strong>EDIT:</strong> This needs to work under windows.</p>
<p><strong>EDIT II:</strong> Bazaar ended up being what I chose. It's even better if you go with TortoiseBzr.</p>
|
<p>I do this with Git. Simply, create a Git repository of your directory:</p>
<pre><code>git-init
git add .
git commit -m "Done"
</code></pre>
<p>Insert the stick, cd to directory on it (I have a big ext2 file I mount with -o loop), and do:</p>
<pre><code>git-clone --bare /path/to/my/dir
</code></pre>
<p>Then, I take the stick to other computer (home, etc.). I can work directly on stick, or clone once again. Go to some dir on the hard disk and:</p>
<pre><code>git-clone /path/to/stick/repos
</code></pre>
<p>When I'm done with changes, I do 'git push' back to stick, and when I'm back at work, I 'git push' once again to move the changes from stick to work computer. Once you set this up, you can use 'git pull' to fetch the changes only (you don't need to clone anymore, just the first time) and 'git push' to push the changes the other way.</p>
<p>The beauty of this is that you can see all the changes with 'git log' and even keep some unrelated work in sync when it changes at both places in the meantime.</p>
<p>If you don't like the command line, you can use graphical tools like gitk and git-gui.</p>
|
Asterisk AGI framework for IVR; Adhearsion alternative? <p>I am trying to get started writing scalable, telecom-grade applications with Asterisk and Ruby. I had originally intended to use the Adhearsion framework for this, but it does not have the required maturity and its documentation is severely lacking. AsteriskRuby seems to be a good alternative, as it's well documented and appears to be written by Vonage.</p>
<p>Does anyone have experience deploying AGI-based IVR applications? What framework, if any, did you use? I'd even consider a non-Ruby one if it's justified. Thanks!</p>
|
<p>SipX is really the wrong answer. I've written some extremely complicated VoiceXML on SipX 3.10.2 and it's been all for naught since SipX 4 is dropping SipXVXML for an interface that requires IVRs to be compiled JARs. Top that off with Nortel filing bankruptcy, extremely poor documentation on the open-source version, poor compliance with VXML 2.0 (as of 3.10.2) and SIP standards (as of 3.10.2, does not trunk well with ITSPs). I will applaud it for a bangup job doing what it was designed to do, be a PBX. But as an IVR, if I had it to do all over again, I'd do something different. I don't know what for sure, but something different. I'm toying with Trixbox CE now and working on tying it into JVoiceXML or VoiceGlue.</p>
<p>Also, don't read that SipX wiki crap. It compares SipX 3.10 to AsteriskNOW 1 to Trixbox 1. Come on. It's like comparing Mac OS X to Win95! A more realistic comparison would be SipX 4 (due out 1Q 2009) to Asterisk 1.6 and Trixbox 2.6, which would show that they accomplish near identical results except in the arena of scalibility and high-availability; SipX wins at that. But, for maturity and stability, I'd advocate Asterisk.</p>
<p>Also, my real world performance results with SipXVXML:<br />
Dell PowerEdge R200, Xeon Dual Core 3.2GHz, handles 17 calls before jitters.<br />
HP DL380 G4, Dual Xeon HT 3.2 GHz, handles 30 calles before long pauses.</p>
<p>I'll post my findings when I finish evaluating VoiceGlue and JVoiceXML but I think I'm going to end up writing a custom PHP called from AGI since all the tools are native to Asterisk.</p>
|
How do I parse a PHP serialized datastructure in Java? <p>I have a system that combines the best and worst of Java and PHP. I am trying to migrate a component that was once written in PHP into a Java One.</p>
<p>Does anyone have some tips for how I can parse a PHP serialized datastructure in Java? By serialized I mean output from php's serialize function.</p>
|
<p>PHP serializes to a simple text-based format. <a href="http://hurring.com/scott/code/java/serialize/v0.1/PHPSerialize.java" rel="nofollow">PHPSerialize</a> looks like a parser written in Java. You can also port the <a href="http://pypi.python.org/pypi/phpserialize/1.1" rel="nofollow">Python implementation</a> to Java -- I doubt it's very complex.</p>
|
What is your favorite hot-key in Eclipse? <p>I've been using Visual Studio with Re-Sharper for the past few years and have recently taken a gig at a Java shop where we use Eclipse. Googling for Eclipse hotkeys has returned a bunch of 'Top 10 Hot-Key' posts, but that's about it. </p>
<p>What are your favorite hotkeys? And which are essential? </p>
|
<p>These are the ones I file under "muscle memory."</p>
<h2>Editing</h2>
<ul>
<li><kbd>Ctrl+Shift+O</kbd> - organise imports (removes unused imports, adds missing imports, sorts imports)</li>
<li><kbd>Ctrl+Shift+I</kbd> - unindent selection</li>
<li><kbd>Ctrl+/</kbd> - comment/uncomment selected lines</li>
<li><kbd>Alt+Shift+R</kbd> - rename selection</li>
</ul>
<h2>Navigation</h2>
<ul>
<li><kbd>Ctrl+Shift+T</kbd> - find as you type for Java classes in your projects</li>
<li><kbd>Ctrl+Shift+R</kbd> - find as you type for all resources in your projects</li>
<li><kbd>Alt+Left</kbd> - step backwards through editing history</li>
<li><kbd>Alt+Right</kbd> - step forwards through editing history</li>
</ul>
<h2>Execution</h2>
<ul>
<li><kbd>Ctrl+F11</kbd> - run again</li>
<li><kbd>F11</kbd> - run again in debug mode</li>
</ul>
|
Focus-follows-mouse (plus auto-raise) on Mac OS X <p>(I don't want to hear about how crazy I am to want that! :)</p>
<p>Focus-follows-mouse is also known as point-to-focus, pointer focus, and (in some implementations) sloppy focus. [Add other terms that will make this more searchable!] X-mouse</p>
|
<p><a href="http://steve-yegge.blogspot.com/2008/04/settling-osx-focus-follows-mouse-debate.html">Steve Yegge</a> wrote an essay about this a while back, where he tried and failed to write a suitable extension. I've since tried to find focus-follows-mouse applications for OS X and failed also.</p>
|
Does having many unused beans in a Spring Bean Context waste significant resources? <p>My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.</p>
<p>My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.</p>
<p>Any ideas?</p>
|
<p>Taken from the <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lazy-init">Spring Reference Manual</a>:</p>
<blockquote>
<p>The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).</p>
<p>However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.</p>
<p>When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example: </p>
</blockquote>
<pre><code><bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
</code></pre>
<p>But, unless your beans are using up resources like file locks or database connections, I wouldn't worry too much about simple memory overhead if it is easier for you to have this one configuration for multiple (but different) profiles.</p>
|
What are the common undefined/unspecified behavior for C that you run into? <p>An example of unspecified behavior in the C language is the order of evaluation of arguments to a function. It might be left to right or right to left, you just don't know. This would affect how foo(c++, c) or foo(++c, c) gets evaluated.</p>
<p>What other unspecified behavior is there that can surprise the unaware programmer?</p>
|
<p>A language lawyer question. Hmkay.</p>
<p>My personal top3: </p>
<ol>
<li>violating the strict aliasing rule</li>
<li>violating the strict aliasing rule</li>
<li><p>violating the strict aliasing rule</p>
<p>:-)</p></li>
</ol>
<p><strong>Edit</strong> Here is a little example that does it wrong twice:</p>
<p>(assume 32 bit ints and little endian)</p>
<pre><code>float funky_float_abs (float a)
{
unsigned int temp = *(unsigned int *)&a;
temp &= 0x7fffffff;
return *(float *)&temp;
}
</code></pre>
<p>That code tries to get the absolute value of a float by bit-twiddling with the sign bit directly in the representation of a float.</p>
<p>However, the result of creating a pointer to an object by casting from one type to another is not valid C. The compiler may assume that pointers to different types don't point to the same chunk of memory. This is true for all kind of pointers except void* and char* (sign-ness does not matter). </p>
<p>In the case above I do that twice. Once to get an int-alias for the float a, and once to convert the value back to float. </p>
<p>There are three valid ways to do the same.</p>
<p>Use a char or void pointer during the cast. These always alias to anything, so they are safe.</p>
<pre><code>float funky_float_abs (float a)
{
float temp_float = a;
// valid, because it's a char pointer. These are special.
unsigned char * temp = (unsigned char *)&temp_float;
temp[3] &= 0x7f;
return temp_float;
}
</code></pre>
<p>Use memcopy. Memcpy takes void pointers, so it will force aliasing as well. </p>
<pre><code>float funky_float_abs (float a)
{
int i;
float result;
memcpy (&i, &a, sizeof (int));
i &= 0x7fffffff;
memcpy (&result, &i, sizeof (int));
return result;
}
</code></pre>
<p>The third valid way: use unions. This is explicitly <strong>not undefined since C99:</strong></p>
<pre><code>float funky_float_abs (float a)
{
union
{
unsigned int i;
float f;
} cast_helper;
cast_helper.f = a;
cast_helper.i &= 0x7fffffff;
return cast_helper.f;
}
</code></pre>
|
How do I examine the configuration of a remote git repository? <p>I've got a git-svn clone of an svn repo, and I want to encourage my colleagues to look at git as an option. The problem is that cloning the repo out of svn takes 3 days, but cloning from my git instance takes 10 minutes.</p>
<p>I've got a script that will allow people to clone my git repo and re-point it at the original SVN, but it requires knowing how I set some of my config values. I'd prefer the script be able to pull those values over the wire.</p>
|
<p>I'd say the better way to do this would be, instead of requiring that your coworkers do a git clone, just give them a a tarball of your existing git-svn checkout. This way, you don't have to repoint or query anything, as it's already done.</p>
|
How can I get Eclipse to show .* files? <p>By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences.</p>
|
<p>In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters</p>
<p><img src="http://i.stack.imgur.com/NWo2x.jpg" alt="filters menu"></p>
<p>From there, uncheck .* resources.</p>
<p>So <code>Package Explorer -> View Menu -> Filters -> uncheck .* resources</code>.</p>
<p>With Eclipse Kepler and OS X this is a bit different:</p>
<pre><code>Package Explorer -> Customize View -> Filters -> uncheck .* resources
</code></pre>
|
What is the strict aliasing rule? <p>When asking about <a href="http://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into">common undefined behavior in C</a>, souls more enlightened than I referred to the strict aliasing rule.<br />
What are they talking about?</p>
|
<p>A typical situation you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to <code>uint32_t</code>s or <code>uint16_t</code>s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.</p>
<p>So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:</p>
<pre><code>struct Msg
{
unsigned int a;
unsigned int b;
};
void SendWord(uint32_t*);
int main()
{
// Get a 32-bit buffer from the system
uint32_t* buff = malloc(sizeof(Msg));
// Alias that buffer through message
Msg* msg = (Msg*)(buff);
// Send a bunch of messages
for (int i =0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendWord(buff[0] );
SendWord(buff[1] );
}
}
</code></pre>
<p>The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases another of an <a href="http://en.cppreference.com/w/c/language/type">incompatible type</a> is undefined behavior. Unfortunately, you can still code this way, maybe* get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code. </p>
<p>*(gcc appears pretty inconsistent in its ability to give aliasing warnings, giving us a friendly warning <a href="http://ideone.com/f53sg">here</a> but not <a href="http://ideone.com/VCKeX">here</a>)</p>
<p>To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of <code>buff</code> every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load <code>buff[0]</code> and <code>buff[1</code>] once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of <code>buff</code> could change at anytime from anywhere by anybody. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.</p>
<p>Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.</p>
<pre><code> void SendMessage(uint32_t* buff, size_t size32)
{
for (int i = 0; i < size32; ++i)
{
SendWord(buff[i]);
}
}
</code></pre>
<p>And rewrote our earlier loop to take advantage of this convenient function</p>
<pre><code> for (int i =0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendMessage(buff, 2);
}
</code></pre>
<p>The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If <code>SendMessage</code> is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.</p>
<p><strong>So how do I get around this?</strong></p>
<ul>
<li>Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.</li>
</ul>
<pre>
union {
Msg msg;
unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
};
</pre>
<ul>
<li><p>You can disable strict aliasing in your compiler (<a href="http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825">f[no-]strict-aliasing</a> in gcc)) </p></li>
<li><p>You can use <code>char*</code> for aliasing instead of your system's word. The rules allow an exception for <code>char*</code> (including <code>signed char</code> and <code>unsigned char</code>). It's always assumed that <code>char*</code> aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.</p></li>
</ul>
<p><strong>Beginner beware</strong></p>
<p>This is only one potential minefield when overlaying two types onto each other. You should also learn about <a href="http://en.wikipedia.org/wiki/Endianness">endianness</a>, <a href="http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/aligned.html">word alignment</a>, and how to deal with alignment issues through <a href="http://grok2.tripod.com/structure_packing.html">packing structs</a> correctly.</p>
|
How to Naturally/Numerically Sort a DataView? <p>I am wondering how to naturally sort a DataView... I really need help on this. I found articles out there that can do lists with IComparable, but I need to sort the numbers in my dataview.</p>
<p>They are currently alpha sorted because they are numbers with 'commas' in them. Please help me out.</p>
<p>I would like to find something instead of spending the time to create it my self.</p>
<p>P.S. expression and sortdirection work, but they of course Alpha sort. Please help.</p>
|
<p>I often like to add a "SortOrder" column to results that I want to sort in a way other than is provided by the data. I usually use an integer and just add it when I am getting the data.</p>
<p>I don't show this column and only use it for the purposes of establishing the order.</p>
<p>I'm not sure if this is what you are looking for, but it is quick and easy and gives you a great deal of control.</p>
|
Modularity of Classes <p>Are there any tips or tricks to make my classes and application designs more modular?</p>
|
<p>I would say that the most important thing is <strong>orthogonality.</strong> What is it? Basically you shouldn't need to modify underlying "engine" if there is a cosmetic change in GUI. A bugfix strictly in the "engine" shouldn't need any changes in some other part of program.</p>
<p><strong>It is not easy</strong> to have a modular program. Think for some time about Windows and Linux, when in the first case everything depends on everything (and MS works really hard to change that, with first effects in Vista), and Linux, when you can switch between desktop environments, cron implementations, web server implementations, package managers...</p>
<p>Make your code <strong>shy.</strong> The Law of Demeter - don't ask for an object, and then ask this object for something else. Ask directly for this "something else". But you probably want to research this topic more.</p>
|
Managing the patch level of multiple windows systems <p>In an environment with multiple windows servers what is the best way to ensure patch compliance accross all systems? </p>
<p>Is there a simple tool (some sort of client/server app?) that allows reports to be generated showing the status of all the systems so any that aren't automatically patching themselves can be fixed without having to manually check each systemevery time an audit is needed?</p>
|
<p><a href="http://technet.microsoft.com/en-us/wsus/default.aspx" rel="nofollow">WSUS</a> is good for Windows, it's for large distributed enterprises.</p>
|
How do I have a socket accept connections only from the localhost (in Java)? <p>I have a java app (not running in any application container) which listens on a ServerSocket for connections. I would like it to only accept connections which come from localhost. Currently, after a connection is accepted, it checks the peer IP and rejects it if it is not the loopback address, but I know that peer IP addresses can be spoofed. So, if possible, I'd prefer to bind to a socket that only listens on the loopback interface; is this possible?</p>
<p>I've tried a few different things (such as specifying "127.0.0.1" as the local address when calling bind()) with no luck. Thanks in advance.</p>
<hr>
<p>Thank you all for your help. I'm embarrassed to admit that this was all my mistake. Our application listens on two different ports, and I was binding one to the loopback interface but testing against the other. When I actually try to telnet to the correct port, everything works fine (i.e., binding to "127.0.0.1" does exactly what it's supposed to).</p>
<p>As for spoofing the loopback address, you guys are right. I shouldn't have made it sound like the primary concern. Really, the desired behavior is to only take local connections, and binding to only the local interface is a more direct way of achieving that than accepting all connections and then closing non-local ones.</p>
|
<p>Peer IP addresses cannot be spoofed in this manner, have you nothing to fear from using the technique of inspecting the peer and deciding to drop the connection during establishment.</p>
<p>However: binding to 127.0.0.1 should work, and cause the operating system to tell the connecting host that there is nothing listening if they connect on one of the systems other ip addresses. Can you amend this question with a compilable example? Perhaps you've made a simple error.</p>
|
Passing PHP associative arrays to and from XML <p>Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:</p>
<pre><code>$items = array("1", "2",
array(
"item3.1" => "3.1",
"item3.2" => "3.2"
"isawesome" => true
)
);
</code></pre>
<p>How would I turn it into something similar to the following XML in as few lines as possible, then back again?</p>
<pre><code><items>
<item>1</item>
<item>2</item>
<item>
<item3_1>3.1</item3_1>
<item3_2>3.2</item3_2>
<isawesome>true</isawesome>
</item>
</items>
</code></pre>
<p>I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's <a href="http://php.net/manual/en/book.xmlreader.php">XMLReader</a> and <a href="http://php.net/manual/en/book.xmlwriter.php">XMLWriter</a>, but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:</p>
<pre><code>$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);
</code></pre>
<p>Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?</p>
<p>I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it.</p>
|
<p><a href="http://php.net/simplexml" rel="nofollow">SimpleXML</a> works great for your use.</p>
|
Does writing and speaking on software make you a better programmer? <p>Do you think that writing about software (i.e. having a blog) and speaking on software (and concepts) make you a better programmer?</p>
|
<p>Statistically speaking yes. You only retain about 20% of what you read and hear, but 80% of what you teach.</p>
<p>By writing about something or teaching about it, you force yourself to understand the concepts on a much deeper level.</p>
<p><strong>UPDATE:</strong></p>
<p>I wanted to update this with some links to more concrete data to support the statistics that I have been taught numerous times about learning retention rates. However, it would appear there is some <a href="http://www.willatworklearning.com/2006/05/people_remember.html">controversy surrounding these numbers</a>, even though the <a href="http://www.ntl.org/">NTL Institute for Applied Behavioral Science</a> maintains that research was done to back them up.</p>
|
Does several levels of base classes slow down a class/struct in c++? <p>Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ...</p>
<p>Does multiple inheritance slow down a class?</p>
|
<p>Non-virtual function-calls have absolutely no performance hit at run-time, in accordance with the c++ mantra that you shouldn't pay for what you don't use.
In a virtual function call, you generally pay for an extra pointer lookup, no matter how many levels of inheritance, or number of base classes you have.
Of course this is all implementation defined.</p>
<p>Edit: As noted elsewhere, in some multiple inheritance scenarios, an adjustment to the 'this' pointer is required before making the call. Raymond Chen describes <a href="http://blogs.msdn.com/oldnewthing/archive/2004/02/06/68695.aspx">how this works</a> for COM objects. Basically, calling a virtual function on an object that inherits from multiple bases can require an extra subtraction and a jmp instruction on top of the extra pointer lookup required for a virtual call.</p>
|
Is it possible to get Code Coverage Analysis on an Interop Assembly? <p>I've asked this question over on the MSDN forums also and haven't found a resolution:</p>
<p><a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3686852&SiteID=1" rel="nofollow">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3686852&SiteID=1</a></p>
<p>The basic problem here as I see it is that an interop assembly doesn't actually contain any IL that can be instrumented (except for maybe a few delegates). So, although I can put together a test project that exercises the interop layer, I can't get a sense for <em>how many</em> of those methods and properties I'm actually calling.</p>
<p>Plan B is to go and write a code generator that creates a library of RCWWs (Runtime Callable Wrapper Wrappers), and instrument that for the purposes of code coverage.</p>
<p>Edit: @<a href="#148618" rel="nofollow">Franci Penov</a>,</p>
<p>Yes that's exactly what I want to do. The COM components delivered to us constitute a library of some dozen DLLs containing approx. 3000 types. We consume that library in our application and are charged with testing that Interop layer, since the group delivering the libraries to us does minimal testing. Code coverage would allow us to ensure that all interfaces and coclasses are exercised. That's all I'm attempting to do. We have separate test projects that exercise our own managed code.</p>
<p>Yes, ideally the COM server team should be testing and analyzing their own code, but we don't live in an ideal world and I have to deliver a quality product based on their work. If can produce a test report indicating that I've tested 80% of their code interfaces and 50% of those don't work as advertised, I can get fixes done where fixes need to be done, and not workaround problems.</p>
<p>The mock layer you mentioned would be useful, but wouldn't ultimately be achieving the goal of testing the Interop layer itself, and I certainly would not want to be maintaining it by hand -- we are at the mercy of the COM guys in terms of changes to the interfaces.</p>
<p>Like I mentioned above -- the next step is to generate wrappers for the wrappers and instrument those for testing purposes.</p>
|
<p>To answer your question - it's not possible to instrument interop assemblies for code coverage. They contain only metadata, and no executable code as you mention yourself.</p>
<p>Besides, I don't see much point in trying to code coverage the interop assembly. You should be measuring the code coverage of code you write.</p>
<p>From the MDN forums thread you mention, it seems to me you actually want to measure how your code uses the COM component. Unless your code's goal is to enumerate and explicitly call all methods and properties of the COM object, you don't need to measure code coverage. You need unit/scenario testing to ensure that your code is calling the right methods/properties at the right time.</p>
<p>Imho, the right way to do this would be to write a mock layer for the COM object and test that you are calling all the methods/properties as expected.</p>
|
When is it appropriate to use Time#utc in Rails 2.1? <p>I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?</p>
<p>When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?</p>
|
<p>If you've set:</p>
<pre><code>config.time_zone = 'UTC'
</code></pre>
<p>In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.</p>
<p>Then if you set Time.zone (in a before_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.</p>
<p>Just be careful with Time.now.</p>
<p>Also see:</p>
<p><a href="http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/" rel="nofollow">http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/</a></p>
<p><a href="http://errtheblog.com/posts/49-a-zoned-defense" rel="nofollow">http://errtheblog.com/posts/49-a-zoned-defense</a> - you can use the JS here to detect zones</p>
<p>Hope that helps.</p>
|
How can I create a Netflix-style iframe overlay without a huge javascript library? <p>I'm trying to use a link to open an overlay instead of in a separate popup window. This overlay should consist of a semi-transparent div layer that blocks the whole screen from being clicked on. I also aim to disable scrolling at this point. Not matter where you are on the main page, when the link is clicked, the overlay should be in the center of the screen's X and Y origins. Inside of this overlay div, should be an iframe configured such that 3 sizes of content can be loaded. </p>
|
<p><a href="http://mjijackson.com/shadowbox/" rel="nofollow">Shadowbox</a> is a nice script for inline "popups". It can work with any of the usual JS libraries if you use any (jQuery, Prototype, etc) or on its own, has a pretty comprehensive skinning system so you can adapt the looks without having to go into the source code itself.<br />
It is also the only such script (there are dozens) I've tried that would work reliably across all usual browsers. </p>
<p>It won't disable scrolling for you (you can still see the normal page background scroll by through the dark overlay), but the "popup" will in any case stay fixed on the screen.</p>
|
Is it safe to add delegates to events with keyword new? <p>One thing I am concerned with is that I discovered two ways of registering delegates to events.</p>
<ol>
<li>OnStuff += this.Handle; </li>
<li>OnStuff += new StuffEventHandler(this.Handle);</li>
</ol>
<p>The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do "OnStuff -= new StuffEventHandler(this.Handle);"? It feels like I am not removing anything at all, since I'm throwing in another StuffEventHandler reference. Does the event compare the delegate by reference? I am concerned I could start a nasty memory pool here. Get me? I don't have the reference to the "new StuffEventHandler" I previously registered.</p>
<p>What is the downside of doing #1?</p>
<p>What is benefit of doing #2? </p>
|
<p>Number one is just shorthand that will generate the same MSIL as the 2nd one, at compile type it'll look at this.Handle and infer the delegate to instantiate. But you should never unsubscribe by using new.</p>
<p>So there is no difference between the 2, just some syntactic sugar to make our code cleaner.</p>
|
Eclipse text comparison order <p>I'm using Eclipse 3.4 (on Mac) and I've got an annoyance with the text comparison having the files I'm comparing in a specific order which is not what I want.</p>
<p>When I compare two files it always seems to put the first file (alphabetically) on the left, and the latter one on the right, but I want to be able to change this on a comparison by comparison basis.<br />
IE comparing 'file-a' and 'file-b' will always have 'file-a' on the left, but that isn't always what I want. I seem to recall in earlier versions of Eclipse that changing the file that was right-clicked when choosing Compare With -> Each Other changed the order, but that isn't working for me in 3.4.</p>
<p>An example of why I care:<br />
I've just performed a subversion merge and had a conflict, so I now have the following files:<br />
<em>file<br />
file.merge-left<br />
file.merge-right<br />
file.working</em> </p>
<p>I've made changes to <em>file</em> and now want to compare <em>file</em> to <em>file.merge-right</em> and <em>file.working</em> to <em>file.merge-left</em> and split the editors so I can have the working/left changes sitting above the file/right changes, and then just page through the compare editors and make sure the differences between this file and the file that the merge comes from have been preserved, but <em>file</em> is on the left while <em>file.working</em> is on the right, and hence the differences need to be compared diagonally rather than just comparing top and bottom.</p>
|
<p>Yes, that's actually very annoying. We use an external tool called Beyond Compare (we have a corporate licence) which can swap the two sides easily.</p>
<p>What you should probably do is raise an enhancement request on the relevant Eclipse team with Bugzilla. If there's enough demand, it'll either make it into the next release or someone will write a new (or modify the existing) plug-in to allow swaps.</p>
|
Generating a unique machine id <p>I need to write a function that generates an id that is unique for a given machine running a Windows OS.</p>
<p>Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use?
Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric.</p>
<p>However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen.</p>
<p>For reference, these are the metrics I'm currently using:</p>
<pre><code>Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeed
Win32_BIOS:Manufacturer
Win32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,Version
Win32_DiskDrive:Model, Manufacturer, Signature, TotalHeads
Win32_BaseBoard:Model, Manufacturer, Name, SerialNumber
Win32_VideoController:DriverVersion, Name
</code></pre>
|
<p>I had the same problem and after a little research I decided the best would be to read <code>MachineGuid</code> in registry key <code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography</code>, as @Agnus suggested. It is generated during OS installation and won't change unless you make another fresh OS install. Depending on the OS version it may contain the network adapter MAC address embedded (plus some other numbers, including random), or a pseudorandom number, the later for newer OS versions (after XP SP2, I believe, but not sure). If it's a pseudorandom theoretically it can be forged - if two machines have the same initial state, including real time clock. In practice, this will be rare, but be aware if you expect it to be a base for security that can be attacked by hardcore hackers.</p>
<p>Of course a registry entry can also be easily changed by anyone to forge a machine GUID, but what I found is that this would disrupt normal operation of so many components of Windows that in most cases no regular user would do it (again, watch out for hardcore hackers).</p>
|
What tools do you use to implement SOA/Messaging? <p><a href="http://www.nservicebus.com/" rel="nofollow">NServiceBus</a> and <a href="http://code.google.com/p/masstransit/" rel="nofollow">MassTransit</a> are two tools that can be used to implement messaging with MSMQ and other message queues.</p>
<p>I find that once you start using messaging to have applications talk to each other, you don't really want to go back to the old RPC style.</p>
<p>My question is, what other tools are out there? What tools do you use?</p>
|
<p><a href="http://activemq.apache.org/" rel="nofollow">Apache ActiveMQ</a> is probably the most popular and powerful open source message broker out there with the most active open source community behind it as well as <a href="http://open.iona.com/products/enterprise-activemq/" rel="nofollow">commercial support, training and tooling if you need it</a>.</p>
<p>One of the more interesting aspects of ActiveMQ is its wide support for <a href="http://activemq.apache.org/cross-language-clients.html" rel="nofollow">a large number of different language bindings and transport protocols</a></p>
|
Why can't I delete a file in %ProgramFiles% from a Unit Test via Resharper's Test Runner Unit Test? <p>I am trying to write a test which, in it's fixtures Setup, it backs up a file and deletes the original, runs the test without the original present, then in the teardown, restores the original from the backup. The file is located in my %ProgramFiles% folder. I get an UnauthorizedAccessException on the fileInfo.Delete() statement. I have no problem deleting this file from another test project on the same machine that is not running from the Resharper Test Runner.</p>
<p>I can't move the file to somewhere else - it's ssapi.dll, an installed dll for Visual SourceSafe. (Yes, I'm doing something invasive in a Unit Test.)</p>
<p>It's the same user (me) for both ways -- I checked it via Task Manager. My user account is a member of the local Administrators group. What other factors are there which determine my "Authorization" to do something with a file?</p>
<p>RESOLVED: Though it doesn't answer my original question (which I'd still like to know the answer to), I have found a workaround for my testing purposes, using the System.Security.Permissions framewok, doing a Demand for FileIOPermissionAccess.Read in the app (non-test) code which requires the file (for an Interop call), and a Deny for the same in the test of that code which requires a scenario that that file is not there. This should work for now (and I love having learned a bit about the System.Security.Permissions namespace)!</p>
|
<p>Not really a solution, but I'd consider fixing this problem from a different angle.</p>
<p>You could perhaps consider changing the directory to %AppData% (you might need to make this change for you main application also).</p>
<p>It might solve your problem and also will see you well when you move to Vista, since UAC could stop you (or the application user) from using the %ProgramFiles% directory.</p>
|
Is there a way to check if there are symbolic links pointing to a directory? <p>I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.</p>
<p>What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple. </p>
<p>Is there a way to check if there are any symlinks pointing to a particular folder?</p>
|
<p>I'd use the find command.</p>
<pre><code>find . -lname /particular/folder
</code></pre>
<p>That will recursively search the current directory for symlinks to <code>/particular/folder</code>. Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called "folder":</p>
<pre><code>find . -lname '*folder'
</code></pre>
<p>From there you would need to weed out any false positives.</p>
|
What is the standard way to add N seconds to datetime.time in Python? <p>Given a <code>datetime.time</code> value in Python, is there a standard way to add an integer number of seconds to it, so that <code>11:34:59</code> + 3 = <code>11:35:02</code>, for example?</p>
<p>These obvious ideas don't work:</p>
<pre><code>>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
</code></pre>
<p>In the end I have written functions like this:</p>
<pre><code>def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
</code></pre>
<p>I can't help thinking that I'm missing an easier way to do this though.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/656297/python-time-timedelta-equivalent">python time + timedelta equivalent</a></li>
</ul>
|
<p>You can use full <code>datetime</code> variables with <code>timedelta</code>, and by providing a dummy date then using <code>time</code> to just get the time value.</p>
<p>For example:</p>
<pre><code>import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print a.time()
print b.time()
</code></pre>
<p>results in the two values, three seconds apart:</p>
<pre><code>11:34:59
11:35:02
</code></pre>
<p>You could also opt for the more readable</p>
<pre><code>b = a + datetime.timedelta(seconds=3)
</code></pre>
<p>if you're so inclined.</p>
<hr>
<p>If you're after a function that can do this, you can look into using <code>addSecs</code> below:</p>
<pre><code>import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print a
print b
</code></pre>
<p>This outputs:</p>
<pre><code> 09:11:55.775695
09:16:55
</code></pre>
|
Connecting to IMDB <p>Has any one done this before? It would seem to me that there should be a webservice but i can't find one. I am writing an application for personal use that would just show basic info from IMDB.</p>
|
<p>The libraries for <a href="http://www.imdb.com/" rel="nofollow">IMDB</a> seem quite unreliable at present and highly inefficient. I really wish <a href="http://www.imdb.com/" rel="nofollow">IMDB</a> would just create a webservice.</p>
<p>After a bit of searching I found a reasonable alternative to <a href="http://www.imdb.com/" rel="nofollow">IMDB</a>. It provides all the basic information such as overview, year, ratings, posters, trailers etc.:</p>
<p><a href="http://api.themoviedb.org/" rel="nofollow">The Movie Database (TMDb)</a>.</p>
<p>It provides a webservice with wrappers for several languages (<a href="http://api.themoviedb.org/2.1/wrappers" rel="nofollow">http://api.themoviedb.org/2.1/wrappers</a>) and seems reliable so far. The search results have been, for myself, more accurate as well.</p>
|
Mashups and SharePoint <p>Can somebody in SO please provide me with a list of resources about Enterprise Mashups and technologies related to SharePoint platform?</p>
<p><strong>Update</strong> (as per suggestion of @Spoon16 in the comments):-
The mashup application may typically retrieve a list of contacts from a SharePoint site and display the address of a selected contact person on a map (again maybe Google maps).</p>
|
<p>There are a number of different ways to pull external information into SharePoint.</p>
<p>For mashing up SharePoint data in external applications:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms479390.aspx" rel="nofollow">Web Services</a>; great web services coverage for the underlying API will allow you to build external mashups (like the one you mention in your question comment). Specifically take a look at the <a href="http://msdn.microsoft.com/en-us/library/ms479390.aspx" rel="nofollow">Lists Service</a>.</li>
</ul>
<p>For mashing up external data sources inside of SharePoint:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms563661.aspx" rel="nofollow">Business Data Catalog</a>; when you have the enterprise version of Microsoft Office SharePoint Portal server you can use the Business Data Catalog to interact with a very wide variety of external datasources in a read/write fashion. Works with relational databases and web services.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms570748.aspx" rel="nofollow">Enterprise Search</a>; the indexing capabilities provided by SharePoint's Enterprise search technology are extensive</li>
<li><a href="http://office.microsoft.com/en-us/sharepointserver/HA101079761033.aspx" rel="nofollow">RSS Web Part</a>; allows you to consume and apply XSLT transform to any RSS feed and output the result on any SharePoint page</li>
<li><a href="http://office.microsoft.com/en-us/sharepointtechnology/HA011609261033.aspx" rel="nofollow">Page Viewer Web Part</a>; allows an iframe to be embedded on any page, provides an easy mechanism of integrating external applications into the SharePoint environment</li>
</ul>
<p>SharePoint has an <a href="http://msdn.microsoft.com/en-us/sharepoint/default.aspx" rel="nofollow">extensive development framework</a> that enables you to leverage the full capabilities of the .NET framework to make your wildest mashup dreams come true. You can use even add additional services to SharePoint that expose the underlying data in custom ways (not covered by the Out of the Box web services) if you like.</p>
|
Hidden Features of Visual Studio (2005-2010)? <p>Visual Studio is such a massively big product that even after years of working with it I sometimes stumble upon a new/better way to do things or things I didn't even know were possible.</p>
<p>For instance-</p>
<ul>
<li><p><kbd>Crtl</kbd> + <kbd>R</kbd>, <kbd>Ctrl</kbd> + <kbd>W</kbd> to show white spaces. Essential for editing Python build scripts.</p></li>
<li><p>Under <code>"HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor"</code>
Create a String called <a href="http://stackoverflow.com/questions/84209/vertical-line-after-a-certain-amount-characters-in-visual-studio">Guides</a> with the value "RGB(255,0,0), 80" to have a red line at column 80 in the text editor.</p></li>
</ul>
<p>What other hidden features have you stumbled upon?</p>
|
<p>Make a selection with ALT pressed - selects a square of text instead of whole lines.</p>
|
SSO in webpages <p>I would like to know what's the best technique to do single sign-on in web sites. It means that if you enter in more than one website, you will be authenticated in a "transparent" way. I'm using php + curl to set the cookies for the different sites, but i really would like to know if does exist a standard way to do it.</p>
|
<p>For a standard secure way you need :</p>
<ul>
<li>an authentication server</li>
<li>an authentication filter on each site that need SSO</li>
</ul>
<p>The mechanism is a little bit complex, it involves http redirects and secure authentication tickets. You will find detailled explanation on the <a href="http://www.ja-sig.org/products/cas/">CAS website</a> (a popular java SSO server).<br>
I recommend to read this page "<a href="http://www.ja-sig.org/wiki/display/CASC/CAS+Java+Client+Gateway+Example">CAS Java Client Gateway Example</a>", especially the sequence diagram at the bottom of the page.</p>
|
How to pause / resume any external process under Windows? <p>I am looking for different ways to pause and resume programmatically a particular process via its process ID under Windows XP.</p>
<p><a href="http://www.codeproject.com/KB/threads/pausep.aspx" rel="nofollow">Process suspend/resume tool</a> does it with <code>SuspendThread</code> / <code>ResumeThread</code> but warns about multi-threaded programs and deadlock problems.</p>
<p><a href="http://technet.microsoft.com/en-us/sysinternals/bb897540.aspx" rel="nofollow">PsSuspend</a> looks okay, but I wonder if it does anything special about deadlocks or uses another method?</p>
<p>Prefered languages : C++ / Python</p>
|
<p>If you "debug the debugger" (for instance, using <code>logger.exe</code> to trace all API calls made by <code>windbg.exe</code>), it appears that the debugger uses <code>SuspendThread()</code>/<code>ResumeThread()</code> to suspend all of the threads in the process being debugged. </p>
<p>PsSuspend may use a different way of suspending processes (I'm not sure), but it is still possible to hang other processes: if the process you're suspending is holding a shared synchronization object that is needed by another process, you may block that other process from making any progress. If both programs are well-written, they should recover when you resume the one that you suspended, but not all programs are well-written. And if this causes your program that is doing the suspending to hang, then you have a deadlock.</p>
|
How do you bind in xaml to a dynamic xpath? <p>I have a list box that displays items based on an XPath query.</p>
<p>This XPath query changes depending on the user's selection elsewhere in the GUI.
The XPath always refers to the same document.</p>
<p>At the moment, I use some C# code behind to change the binding of the control to a new XPath expression.</p>
<p>I'd like instead to bind in XAML to an XPath, then change the value of that XPath as required.</p>
<p>How would i do that?</p>
|
<p>I think that you're trying to over complicate the problem. But have you thought about allocating the XPath to a dynamic resource:</p>
<pre><code><.... ={Binding XPath={DynamicResource:res resource-name}} ... />
</code></pre>
<p>The best place to read about all-binding is Beatriz's blog: <a href="http://www.beacosta.com/blog/" rel="nofollow">http://www.beacosta.com/blog/</a> </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.