input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
---|---|
SQL Server best way to calculate datediff between current row and next row? <p>I've got the following rough structure:</p>
<pre><code>Object -> Object Revisions -> Data
</code></pre>
<p>The Data can be shared between several Objects.</p>
<p>What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set.</p>
<p>I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc... </p>
<p>Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table? </p>
<p>I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well.</p>
| <p>Here is example SQL. If you have an Identity column, you can use this instead of "ActivityDate".</p>
<pre><code>SELECT DATEDIFF(HOUR, prev.ActivityDate, curr.ActivityDate)
FROM MyTable curr
JOIN MyTable prev
ON prev.ObjectID = curr.ObjectID
WHERE prev.ActivityDate =
(SELECT MAX(maxtbl.ActivityDate)
FROM MyTable maxtbl
WHERE maxtbl.ObjectID = curr.ObjectID
AND maxtbl.ActivityDate < curr.ActivityDate)
</code></pre>
<p>I could remove "prev", but have it there assuming you need IDs from it for deleting.</p>
|
How do I find and decouple entities from a certificate when upgrading MS-SQLServer editions? <p>While in the final throws of upgrading MS-SQL Server 2005 Express Edition to MS-SQL Server 2005 Enterprise Edition, I came across this error:</p>
<blockquote>
<p>The certificate cannot be dropped because one or more entities are either signed or encrypted using it. To continue, correct the problem...</p>
</blockquote>
<p>So, <strong>how do I find and decouple the entities signed/encrypted using this certificate so I can delete the certificate and proceed with the upgrade?</strong></p>
<p>I'm also kind of expecting/assuming that the upgrade setup will provide a new certificate and re-couple those former entities with it or I'll have to forcibly do so after the setup.</p>
| <p>The Microsoft forum has the following code snipit to delete the certificates:</p>
<pre><code>use msdb
BEGIN TRANSACTION
declare @sp sysname
declare @exec_str nvarchar(1024)
declare ms_crs_sps cursor global for select object_name(crypts.major_id) from sys.crypt_properties crypts, sys.certificates certs where crypts.thumbprint = certs.thumbprint and crypts.class = 1 and certs.name = '##MS_AgentSigningCertificate##'
open ms_crs_sps
fetch next from ms_crs_sps into @sp
while @@fetch_status = 0
begin
if exists(select * from sys.objects where name = @sp) begin print 'Dropping signature from: ' + @sp set @exec_str = N'drop signature from ' + quotename(@sp) + N' by certificate [##MS_AgentSigningCertificate##]'
Execute(@exec_str)
if (@@error <> 0)
begin
declare @err_str nvarchar(1024)
set @err_str = 'Cannot drop signature from ' + quotename(@sp) + '. Terminating.'
close ms_crs_sps
deallocate ms_crs_sps
ROLLBACK TRANSACTION
RAISERROR(@err_str, 20, 127) WITH LOG
return
end
end
fetch next from ms_crs_sps into @sp
end
close ms_crs_sps
deallocate ms_crs_sps
COMMIT TRANSACTION
go
</code></pre>
<p><a href="http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3876484&SiteID=17" rel="nofollow">http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3876484&SiteID=17</a></p>
<p>I have not tried the script, so please backup your data and system before attempting and update here with results.</p>
|
Are off-the-cloud desktop applications dead? <p>Although somewhat related to <a href="http://stackoverflow.com/questions/4409/is-the-desktop-app-dead" rel="nofollow">this question</a>, I have what I think is a different take on it.</p>
<p>Is a desktop app that has no connections to the "cloud" dead? I believe that some things are going to continue to be on the machine (operating systems obviously, browsers, some light-weight applications), but more and more things are moving to network-based applications (see Google Docs for office suites, GMail and other web-email clients for email, flickr for photo management, and more).</p>
<p>So other than the lightweight applications, is there anything that, in 5 to 10 years, will continue to be (either out of necessity or just demand) remain on the desktop and off the cloud?</p>
| <p>10 years or more ago this would have been, "Are non-internet applications dead?"</p>
<p>There's things the cloud does better than desktop applications, and in those places I'm sure non-cloud applications will become increasingly rare. But there's plenty of applications where you might not want to use the cloud, the benefits don't outweigh the costs, or the complexity just isn't worth it.</p>
<p>It's a new tool, and it's a better tool than desktop applications for many things. However, you don't throw away a hammer when you buy a screwdriver, you simply reserve it for when a nail needs to be driven.</p>
|
What does the comma operator , do in C? <p>What does the <code>,</code> operator do in C?</p>
| <p>The expression:</p>
<pre><code>(expression1, expression2)
</code></pre>
<p>First expression1 is evaluated, then expression2 is evaluated, and the value of expression2 is returned for the whole expression.</p>
|
What does the PDB get me while debugging and how do I know it's working? <p>I have to use a third-party component without source code. I have the release DLL and release PDB file. Let's call it 'CorporateComponent.dll'. My own code creates objects from this DLL and calls methods on these objects.</p>
<pre><code>CorpObject o = new CorpObject();
Int32 result = o.DoSomethingLousy();
</code></pre>
<p>While debugging, the method 'DoSomethingLousy' throws an exception. What does the PDB file do for me? If it does something nice, how can I be sure I'm making use of it?</p>
| <p>To confirm if you're using the provided PDB, CorporateComponent.pdb, during debugging within the Visual Studio IDE review the output window and locate the line indicating that the CorporateComponent.dll is loaded and followed by the string <code>Symbols loaded</code>.</p>
<p>To illustrate from a project of mine:</p>
<pre><code>The thread 0x6a0 has exited with code 0 (0x0).
The thread 0x1f78 has exited with code 0 (0x0).
'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\Development\Src\trunk\ntity\AvayaConfigurationService\AvayaConfigurationService\bin\Debug \AvayaConfigurationService.exe', Symbols loaded.
'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\Development\Src\trunk\ntity\AvayaConfigurationService\AvayaConfigurationService\bin\Debug\IPOConfigService.dll', No symbols loaded.
</code></pre>
<blockquote>
<p><code>Loaded 'C:\Development\src...\bin\Debug\AvayaConfigurationService.exe', Symbols loaded.</code></p>
</blockquote>
<p>This indicates that the PDB was found and loaded by the IDE debugger.</p>
<p>As indicated by others When examining stack frames within your application you should be able to see the symbols from the CorporateComponent.pdb. If you don't then perhaps the third-party did not include symbol information in the release PDB build.</p>
|
Perform token replacements using VS post-build event command? <p>I would like to "post-process" my app.config file and perform some token replacements after the project builds.</p>
<p>Is there an <em>easy</em> way to do this using a <a href="http://msdn.microsoft.com/en-us/library/42x5kfw4(VS.80).aspx" rel="nofollow">VS post-build event</a> command?</p>
<p><em>(Yeah I know I could probably use NAnt or something, looking for something simple.)</em></p>
| <p>Take a look at <a href="http://xmlpreprocess.sourceforge.net/" rel="nofollow">XmlPreProcess</a>. We use it for producing different config files for our testing and live deployment packages.
We execute it from a nant script as part of a continuous build but, since it's a console app, I see no reason why you coudn't add a call in your project's post-build event instead</p>
|
Inform potential clients about security vulnerabilities? <p>We have a lot of open discussions with potential clients, and they ask frequently about our level of technical expertise, including the scope of work for our current projects. The first thing I do in order to gauge the level of expertise on staff they have now or have previously used is to check for security vulnerabilities like XSS and SQL injection. I have yet to find a potential client who is vulnerable, but I started to wonder, would they actually think this investigation was helpful, or would they think, "um, these guys will trash our site if we don't do business with them." Non-technical folks get scared pretty easily by this stuff, so I'm wondering is this a show of good faith, or a poor business practice?</p>
| <p>I would say that surprising people by suddenly penetration-testing their software may bother people if simply for the fact that they didn't know ahead of time. I would say if you're going to do this (and I believe it's a good thing to do), inform your clients ahead of time that you're going to do this. If they seem a little distraught by this, tell them the benefits of checking for human error from the attacker's point of view in a controlled environment. After all, even the most securely minded make mistakes: the Debian PRNG vulnerability is a good example of this.</p>
|
Google Reader API Unread Count <p>Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password?</p>
| <p>This URL will give you a count of unread posts per feed. You can then iterate over the feeds and sum up the counts.</p>
<p><a href="http://www.google.com/reader/api/0/unread-count?all=true">http://www.google.com/reader/api/0/unread-count?all=true</a></p>
<p>Here is a minimalist example in Python...parsing the xml/json and summing the counts is left as an exercise for the reader:</p>
<pre class="lang-py prettyprint-override"><code>import urllib
import urllib2
username = '[email protected]'
password = '******'
# Authenticate to obtain SID
auth_url = 'https://www.google.com/accounts/ClientLogin'
auth_req_data = urllib.urlencode({'Email': username,
'Passwd': password,
'service': 'reader'})
auth_req = urllib2.Request(auth_url, data=auth_req_data)
auth_resp = urllib2.urlopen(auth_req)
auth_resp_content = auth_resp.read()
auth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\n') if x)
auth_token = auth_resp_dict["Auth"]
# Create a cookie in the header using the SID
header = {}
header['Authorization'] = 'GoogleLogin auth=%s' % auth_token
reader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'
reader_req_data = urllib.urlencode({'all': 'true',
'output': 'xml'})
reader_url = reader_base_url % (reader_req_data)
reader_req = urllib2.Request(reader_url, None, header)
reader_resp = urllib2.urlopen(reader_req)
reader_resp_content = reader_resp.read()
print reader_resp_content
</code></pre>
<p>And some additional links on the topic:</p>
<ul>
<li><a href="http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI">http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI</a></li>
<li><a href="http://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt">How do you access an authenticated Google App Engine service from a (non-web) python client?</a></li>
<li><a href="http://blog.gpowered.net/2007/08/google-reader-api-functions.html">http://blog.gpowered.net/2007/08/google-reader-api-functions.html</a></li>
</ul>
|
How to make git ignore changes in case? <p>I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of it's name. e.g.,:</p>
<p>before: <code>File.h</code></p>
<p>after: <code>file.h</code></p>
<p>I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?</p>
<p><strong>[edit]</strong>
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope.</p>
| <p>Since version 1.5.6 there is an <code>ignorecase</code> option available in the <code>[core]</code> section of <code>.git/config</code></p>
<p>e.g. add <code>ignorecase = true</code></p>
<p>To change it for just one repo, from that folder run:</p>
<pre><code>git config core.ignorecase true
</code></pre>
<p>To change it globally: </p>
<pre><code>git config --global core.ignorecase true
</code></pre>
|
Examples for coding against the PayPal API in .NET 2.0+? <p>Can anyone point me to a good introduction to coding against the paypal API?</p>
| <p>Found this article by Rick Strahl recently <a href="http://www.west-wind.com/presentations/PayPalIntegration/PayPalIntegration.asp">http://www.west-wind.com/presentations/PayPalIntegration/PayPalIntegration.asp</a>. </p>
<p>Have not implemeted anything from it yet, Rick has quite a few articles around the web on ecommerce in aspnet, and he seems to show up everytime I'm searching for it.</p>
|
Is there an ASP.NET pagination control (Not MVC)? <p>I've got a search results page that basically consists of a repeater with content in it. What I need is a way to paginate the results. Getting paginated results isn't the problem, what I'm after is a web control that will display a list of the available paged data, preferably by providing the number of results and a page size</p>
| <p>Repeaters don't do this by default.</p>
<p>However, GridViews do.</p>
<p>Personally, I hate GridViews, so I wrote a Paging/Sorting Repeater control.</p>
<p>Basic Steps:</p>
<ul>
<li>Subclass the Repeater Control</li>
<li>Add a private PagedDataSource to it</li>
<li>Add a public PageSize property</li>
<li>Override Control.DataBind
<ul>
<li>Store the Control.DataSource in the PagedDataSource.</li>
<li>Bind the Control.DataSource to PagedDataSource</li>
</ul></li>
<li>Override Control.Render
<ul>
<li>Call Base.Render()</li>
<li>Render your paging links.</li>
</ul></li>
</ul>
<p>For a walkthrough, you could try this link:</p>
<p><a href="http://aspnet.4guysfromrolla.com/articles/081804-1.aspx" rel="nofollow">http://aspnet.4guysfromrolla.com/articles/081804-1.aspx</a></p>
|
Retaining HTTP POST data when a request is interrupted by a login page <p>Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.</p>
<p>Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.</p>
<p>Can anyone recommend a way to handle this scenario when HTTP POST data is involved?</p>
<p>Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.</p>
<p><hr /></p>
<p><strong>Edit</strong> : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.</p>
| <p>This is one good place where Ajax techniques might be helpful. When the user clicks the submit button, show the login dialog on client side and validate with the server before you actually submit the page.</p>
<p>Another way I can think of is showing or hiding the login controls in a DIV tag dynamically in the main page itself.</p>
|
How could I get my SVN-only host to pull from a git repository? <p>I'd really like to get our host to pull from our Git repository instead of uploading files manually, but it doesn't have Git installed.</p>
<p>So is there a way to trick Subversion (which they do have) into checking out a Git repository?</p>
<p>I think I already know the answer, namely bug my host to add Git and live with it until they do, but I thought I would ask anyway.</p>
| <p>This page should provide a workaround for your problem. </p>
<p><a href="http://code.google.com/p/support/wiki/ImportingFromGit" rel="nofollow">http://code.google.com/p/support/wiki/ImportingFromGit</a></p>
<p>Basically, you create a read-only clone of your Git repository in the SVN repository format, exporting updates as you go. An SVN hook could be written that fires after each update to copy the new files where you need them.</p>
|
Where are people getting that rotaty loading image? <p>I keep running across this loading image</p>
<p><a href="http://georgia.ubuntuforums.com/images/misc/lightbox_progress.gif" rel="nofollow">http://georgia.ubuntuforums.com/images/misc/lightbox_progress.gif</a></p>
<p>which seems to have entered into existence in the last 18 months. All of a sudden it is in every application and is on every web site. Not wanting to be left out is there somewhere I can get this logo, perhaps with a transparent background? Also where did it come from? </p>
| <p>You can get many different AJAX loading animations in any colour you want here: <a href="http://www.ajaxload.info/">ajaxload.info</a></p>
|
When building a Handler, should it be .ashx or .axd? <p>Say I'm building an ASP.Net class that inherits from IHttpHandler, should I wire this up to a URL ending in .ashx, or should I use the .axd extension? </p>
<p>Does it matter as long as there's no naming conflict?</p>
| <p>Ahh.. ScottGu says it doesn't matter, but .ashx is slightly better because there's less chance of a conflict with things like trace.axd and others. That's why the flag went up in my head that .ashx might be better.</p>
<p><a href="http://forums.asp.net/t/964074.aspx" rel="nofollow">http://forums.asp.net/t/964074.aspx</a></p>
|
Fuzzy text (sentences/titles) matching in C# <p>Hey, I'm using <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshteins</a> algorithm to get distance between source and target string.</p>
<p>also I have method which returns value from 0 to 1:</p>
<pre><code>/// <summary>
/// Gets the similarity between two strings.
/// All relation scores are in the [0, 1] range,
/// which means that if the score gets a maximum value (equal to 1)
/// then the two string are absolutely similar
/// </summary>
/// <param name="string1">The string1.</param>
/// <param name="string2">The string2.</param>
/// <returns></returns>
public static float CalculateSimilarity(String s1, String s2)
{
if ((s1 == null) || (s2 == null)) return 0.0f;
float dis = LevenshteinDistance.Compute(s1, s2);
float maxLen = s1.Length;
if (maxLen < s2.Length)
maxLen = s2.Length;
if (maxLen == 0.0F)
return 1.0F;
else return 1.0F - dis / maxLen;
}
</code></pre>
<p>but this for me is not enough. Because I need more complex way to match two sentences.</p>
<p>For example I want automatically tag some music, I have original song names, and i have songs with trash, like <em>super, quality,</em> years like <em>2007, 2008,</em> etc..etc.. also some files have just <a href="http://trash..thash..song_name_mp3.mp3">http://trash..thash..song_name_mp3.mp3</a>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me?</p>
<p>here is my current algo:</p>
<pre><code>/// <summary>
/// if we need to ignore this target.
/// </summary>
/// <param name="targetString">The target string.</param>
/// <returns></returns>
private bool doIgnore(String targetString)
{
if ((targetString != null) && (targetString != String.Empty))
{
for (int i = 0; i < ignoreWordsList.Length; ++i)
{
//* if we found ignore word or target string matching some some special cases like years (Regex).
if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true;
}
}
return false;
}
/// <summary>
/// Removes the duplicates.
/// </summary>
/// <param name="list">The list.</param>
private void removeDuplicates(List<String> list)
{
if ((list != null) && (list.Count > 0))
{
for (int i = 0; i < list.Count - 1; ++i)
{
if (list[i] == list[i + 1])
{
list.RemoveAt(i);
--i;
}
}
}
}
/// <summary>
/// Does the fuzzy match.
/// </summary>
/// <param name="targetTitle">The target title.</param>
/// <returns></returns>
private TitleMatchResult doFuzzyMatch(String targetTitle)
{
TitleMatchResult matchResult = null;
if (targetTitle != null && targetTitle != String.Empty)
{
try
{
//* change target title (string) to lower case.
targetTitle = targetTitle.ToLower();
//* scores, we will select higher score at the end.
Dictionary<Title, float> scores = new Dictionary<Title, float>();
//* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_'
List<String> targetKeywords = new List<string>(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
//* remove all trash from keywords, like super, quality, etc..
targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); });
//* sort keywords.
targetKeywords.Sort();
//* remove some duplicates.
removeDuplicates(targetKeywords);
//* go through all original titles.
foreach (Title sourceTitle in titles)
{
float tempScore = 0f;
//* split orig. title to keywords list.
List<String> sourceKeywords = new List<string>(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
sourceKeywords.Sort();
removeDuplicates(sourceKeywords);
//* go through all source ttl keywords.
foreach (String keyw1 in sourceKeywords)
{
float max = float.MinValue;
foreach (String keyw2 in targetKeywords)
{
float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2);
if (currentScore > max)
{
max = currentScore;
}
}
tempScore += max;
}
//* calculate average score.
float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count));
//* if average score is bigger than minimal score and target title is not in this source title ignore list.
if (averageScore >= minimalScore && !sourceTitle.doIgnore(targetTitle))
{
//* add score.
scores.Add(sourceTitle, averageScore);
}
}
//* choose biggest score.
float maxi = float.MinValue;
foreach (KeyValuePair<Title, float> kvp in scores)
{
if (kvp.Value > maxi)
{
maxi = kvp.Value;
matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic);
}
}
}
catch { }
}
//* return result.
return matchResult;
}
</code></pre>
<p>This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one.. </p>
<p>Ideas? Suggestions? Algos?</p>
<p>by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.):
<a href="http://stackoverflow.com/questions/49263/approximate-string-matching-algorithms">http://stackoverflow.com/questions/49263/approximate-string-matching-algorithms</a></p>
| <p>Kind of old, but It might be useful to future visitors. If you're already using the Levenshtein algorithm and you need to go a little better, I describe some very effective heuristics in this solution:</p>
<p><a href="http://stackoverflow.com/questions/5859561/getting-the-closest-string-match/5859823#5859823">Getting the closest string match</a></p>
<p>The key is that you come up with 3 or 4 (or <a href="http://en.wikipedia.org/wiki/String_metric">more</a>) methods of gauging the similarity between your phrases (Levenshtein distance is just one method) - and then using real examples of strings you want to match as similar, you adjust the weightings and combinations of those heuristics until you get something that maximizes the number of positive matches. Then you use that formula for all future matches and you should see great results.</p>
<p>If a user is involved in the process, it's also best if you provide an interface which allows the user to see additional matches that rank highly in similarity in case they disagree with the first choice.</p>
<p>Here's an excerpt from the linked answer. If you end up wanting to use any of this code as is, I apologize in advance for having to convert VBA into C#.</p>
<hr>
<p>Simple, speedy, and a very useful metric. Using this, I created two separate metrics for evaluating the similarity of two strings. One I call "valuePhrase" and one I call "valueWords". valuePhrase is just the Levenshtein distance between the two phrases, and valueWords splits the string into individual words, based on delimiters such as spaces, dashes, and anything else you'd like, and compares each word to each other word, summing up the shortest Levenshtein distance connecting any two words. Essentially, it measures whether the information in one 'phrase' is really contained in another, just as a word-wise permutation. I spent a few days as a side project coming up with the most efficient way possible of splitting a string based on delimiters.</p>
<p>valueWords, valuePhrase, and Split function:</p>
<pre><code>Public Function valuePhrase#(ByRef S1$, ByRef S2$)
valuePhrase = LevenshteinDistance(S1, S2)
End Function
Public Function valueWords#(ByRef S1$, ByRef S2$)
Dim wordsS1$(), wordsS2$()
wordsS1 = SplitMultiDelims(S1, " _-")
wordsS2 = SplitMultiDelims(S2, " _-")
Dim word1%, word2%, thisD#, wordbest#
Dim wordsTotal#
For word1 = LBound(wordsS1) To UBound(wordsS1)
wordbest = Len(S2)
For word2 = LBound(wordsS2) To UBound(wordsS2)
thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2))
If thisD < wordbest Then wordbest = thisD
If thisD = 0 Then GoTo foundbest
Next word2
foundbest:
wordsTotal = wordsTotal + wordbest
Next word1
valueWords = wordsTotal
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' SplitMultiDelims
' This function splits Text into an array of substrings, each substring
' delimited by any character in DelimChars. Only a single character
' may be a delimiter between two substrings, but DelimChars may
' contain any number of delimiter characters. It returns a single element
' array containing all of text if DelimChars is empty, or a 1 or greater
' element array if the Text is successfully split into substrings.
' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur.
' If Limit greater than 0, the function will only split Text into 'Limit'
' array elements or less. The last element will contain the rest of Text.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _
Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _
Optional ByVal Limit As Long = -1) As String()
Dim ElemStart As Long, N As Long, M As Long, Elements As Long
Dim lDelims As Long, lText As Long
Dim Arr() As String
lText = Len(Text)
lDelims = Len(DelimChars)
If lDelims = 0 Or lText = 0 Or Limit = 1 Then
ReDim Arr(0 To 0)
Arr(0) = Text
SplitMultiDelims = Arr
Exit Function
End If
ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit))
Elements = 0: ElemStart = 1
For N = 1 To lText
If InStr(DelimChars, Mid(Text, N, 1)) Then
Arr(Elements) = Mid(Text, ElemStart, N - ElemStart)
If IgnoreConsecutiveDelimiters Then
If Len(Arr(Elements)) > 0 Then Elements = Elements + 1
Else
Elements = Elements + 1
End If
ElemStart = N + 1
If Elements + 1 = Limit Then Exit For
End If
Next N
'Get the last token terminated by the end of the string into the array
If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart)
'Since the end of string counts as the terminating delimiter, if the last character
'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent
If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1
ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements
SplitMultiDelims = Arr
End Function
</code></pre>
<p><strong>Measures of Similarity</strong></p>
<p>Using these two metrics, and a third which simply computes the distance between two strings, I have a series of variables which I can run an optimization algorithm to achieve the greatest number of matches. Fuzzy string matching is, itself, a fuzzy science, and so by creating linearly independent metrics for measuring string similarity, and having a known set of strings we wish to match to each other, we can find the parameters that, for our specific styles of strings, give the best fuzzy match results.</p>
<p>Initially, the goal of the metric was to have a low search value for for an exact match, and increasing search values for increasingly permuted measures. In an impractical case, this was fairly easy to define using a set of well defined permutations, and engineering the final formula such that they had increasing search values results as desired.</p>
<p><img src="http://i.stack.imgur.com/eGCtC.png" alt="enter image description here"></p>
<p>As you can see, the last two metrics, which are fuzzy string matching metrics, already have a natural tendency to give low scores to strings that are meant to match (down the diagonal). This is very good. </p>
<p><strong>Application</strong>
To allow the optimization of fuzzy matching, I weight each metric. As such, every application of fuzzy string match can weight the parameters differently. The formula that defines the final score is a simply combination of the metrics and their weights:</p>
<pre><code>value = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight +
Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight + lengthWeight*lengthValue
</code></pre>
<p>Using an optimization algorithm (neural network is best here because it is a discrete, multi-dimentional problem), the goal is now to maximize the number of matches. I created a function that detects the number of correct matches of each set to each other, as can be seen in this final screenshot. A column or row gets a point if the lowest score is assigned the the string that was meant to be matched, and partial points are given if there is a tie for the lowest score, and the correct match is among the tied matched strings. I then optimized it. You can see that a green cell is the column that best matches the current row, and a blue square around the cell is the row that best matches the current column. The score in the bottom corner is roughly the number of successful matches and this is what we tell our optimization problem to maximize. </p>
<p><img src="http://i.stack.imgur.com/hsMtp.png" alt="enter image description here"></p>
|
How to properly link your a custom css file in sharepoint <p>I've created a custom list, and made some changes to the way the CQWP renders it on a page by modifying ItemStyle.xsl. However, I'd like to use some custom css classes and therefore I'd like to link to my own custom .css file from the head tag of the pages containing this CQWP.</p>
<p>So my question is, where to do put my .css file and how do I link it properly to a page containing the CQWPs. Please have in mind that I'm making a solution that should be deployed on multi sharepoint installations.</p>
<p>Thanks.</p>
| <p>The microsoft official way is just to copy them into the relevant folders (as seen by downloading their template packs). However, you could also create your own site definition and add the items to the correct libraries and lists in the same way that the master pages are added.</p>
<p>If you are going to deploy CSS and Master Pages through features remember you will have to activate your the publishing infrastructure on the site collection and the publishing feature on the site.</p>
<p>To deploy a master page/page layout as a feature you should follow the steps at the site below, you can use the "fileurl" element to specify your CSS and place it into the correct folder (style library, for example):
<a href="http://www.sharepointnutsandbolts.com/2007/04/deploying-master-pages-and-page-layouts.html" rel="nofollow">http://www.sharepointnutsandbolts.com/2007/04/deploying-master-pages-and-page-layouts.html</a></p>
|
How to efficiently SQL select newest entries from a MySQL database? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/49404/sql-query-to-get-latest-price">SQL Query to get latest price</a> </p>
</blockquote>
<p>I have a database containing stock price history. I want to select most recent prices for every stock that is listed. I know PostreSQL has a <a href="http://stackoverflow.com/questions/25224/joining-latest-of-various-usermetadata-tags-to-user-rows#27159">DISTINCT ON</a> statement that would suit ideally here.</p>
<p>Table columns are <code>name</code>, <code>closingPrice</code> and <code>date</code>; <code>name</code> and <code>date</code> together form a unique index.</p>
<p>The <em>easiest</em> (and very uneffective) way is</p>
<pre><code>SELECT * FROM stockPrices s
WHERE s.date =
(SELECT MAX(date) FROM stockPrices si WHERE si.name = s.name);
</code></pre>
<p>Much better approach I found is</p>
<pre><code>SELECT *
FROM stockPrices s JOIN (
SELECT name, MAX(date) AS date
FROM stockPrices si
GROUP BY name
) lastEntry ON s.name = lastEntry.name AND s.date = lastEntry.date;
</code></pre>
<p>What would be an efficient way to do this? What indexes should I create?</p>
<blockquote>
<p>duplicate of:<br>
<a href="http://stackoverflow.com/questions/49404/sql-query-to-get-latest-price">SQL Query to get latest price</a></p>
</blockquote>
| <p>See <a href="http://stackoverflow.com/questions/49404/sql-query-to-get-latest-price" rel="nofollow">similar post</a></p>
|
Why does windows XP minimize my swing full screen window on my second screen? <p>In the application I'm developping (in Java/swing), I have to show a full screen window on the <em>second</em> screen of the user.
I did this using a code similar to the one you'll find below...
Be, as soon as I click in a window opened by windows explorer, or as soon as I open windows explorer (i'm using windows XP), the full screen window is minimized...</p>
<p>Do you know any way or workaround to fix this problem, or is there something important I did not understand with full screen windows?</p>
<p>Thanks for the help,</p>
<pre><code>import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.Rectangle;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
public class FullScreenTest {
private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="94,35"
private JPanel jContentPane = null;
private JToggleButton jToggleButton = null;
private JPanel jFSPanel = null; // @jve:decl-index=0:visual-constraint="392,37"
private JLabel jLabel = null;
private Window window;
/**
* This method initializes jFrame
*
* @return javax.swing.JFrame
*/
private JFrame getJFrame() {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new Dimension(474, 105));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setContentPane(getJContentPane());
}
return jFrame;
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToggleButton(), null);
}
return jContentPane;
}
/**
* This method initializes jToggleButton
*
* @return javax.swing.JToggleButton
*/
private JToggleButton getJToggleButton() {
if (jToggleButton == null) {
jToggleButton = new JToggleButton();
jToggleButton.setBounds(new Rectangle(50, 23, 360, 28));
jToggleButton.setText("Show Full Screen Window on 2nd screen");
jToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
showFullScreenWindow(jToggleButton.isSelected());
}
});
}
return jToggleButton;
}
protected void showFullScreenWindow(boolean b) {
if(window==null){
window = initFullScreenWindow();
}
window.setVisible(b);
}
private Window initFullScreenWindow() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
GraphicsDevice gd = gds[1];
JWindow window = new JWindow(gd.getDefaultConfiguration());
window.setContentPane(getJFSPanel());
gd.setFullScreenWindow(window);
return window;
}
/**
* This method initializes jFSPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJFSPanel() {
if (jFSPanel == null) {
jLabel = new JLabel();
jLabel.setBounds(new Rectangle(18, 19, 500, 66));
jLabel.setText("Hello ! Now, juste open windows explorer and see what happens...");
jFSPanel = new JPanel();
jFSPanel.setLayout(null);
jFSPanel.setSize(new Dimension(500, 107));
jFSPanel.add(jLabel, null);
}
return jFSPanel;
}
/**
* @param args
*/
public static void main(String[] args) {
FullScreenTest me = new FullScreenTest();
me.getJFrame().setVisible(true);
}
}
</code></pre>
| <p>Usually when an application is in "full screen" mode it will take over the entire desktop. For a user to get to another window they would have to alt-tab to it. At that point windows would minimize the full screen app so that the other application could come to the front. </p>
<p>This sounds like it may be a bug (undocumented feature...) in windows. It should probably not be doing this for a dual screen setup. </p>
<p>One option to fix this is rather than setting it to be "full screen" just make the window the same size as the screen with location (0,0). You can get screen information from the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GraphicsDevice.html#getConfigurations%28%29" rel="nofollow">GraphicsConfigurations on the GraphicsDevice</a>. </p>
|
Returning an element from a List in Scala <p>I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.</p>
<p>Say I have a list of tuples ( <code>List[Tuple2[String, String]]</code>, for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand?</p>
| <pre>
scala> val list = List(("A", "B", 1), ("C", "D", 1), ("E", "F", 1), ("C", "D", 2), ("G", "H", 1))
list: List[(java.lang.String, java.lang.String, Int)] = List((A,B,1), (C,D,1), (E,F,1), (C,D,2), (G,H,1))
scala> list find {e => e._1 == "C" && e._2 == "D"}
res0: Option[(java.lang.String, java.lang.String, Int)] = Some((C,D,1))
</pre>
|
How do you get the logged in Windows domain account from an ASP.NET application? <p>We have an ASP.NET application that manages it's own User, Roles and Permission database and we have recently added a field to the User table to hold the Windows domain account. </p>
<p>I would like to make it so that the user doesn't have to <strong>physically</strong> log in to our application, but rather would be automatically logged in based on the currently logged in Windows domain account DOMAIN\username. We want to authenticate the Windows domain account against our own User table. </p>
<p>This is a piece of cake to do in Windows Forms, is it possible to do this in Web Forms?</p>
<p>I don't want the user to be prompted with a Windows challenge screen, I want our system to handle the log in.</p>
<p><strong>Clarification</strong>: We are using our own custom Principal object.</p>
<p><strong>Clarification</strong>: Not sure if it makes a difference or not, but we are using IIS7.</p>
| <pre><code>using System.Security.Principal;
...
WindowsPrincipal wp = (WindowsPrincipal)HttpContext.Current.User;
</code></pre>
<p>to get the current domain user. Of course you have to make sure that the IIS is set up to handle Windows Authentication.</p>
|
Encrypting appSettings in web.config <p>I am developing a web app which requires a username and password to be stored in the web.Config, it also refers to some URLs which will be requested by the web app itself and never the client.</p>
<p>I know the .Net framework will not allow a web.config file to be served, however I still think its bad practice to leave this sort of information in plain text. </p>
<p>Everything I have read so far requires me to use a command line switch or to store values in the registry of the server. I have access to neither of these as the host is online and I have only FTP and Control Panel (helm) access.</p>
<p>Can anyone recommend any good, free encryption DLL's or methods which I can use? I'd rather not develop my own!</p>
<p>Thanks for the feedback so far guys but I am not able to issue commands and and not able to edit the registry. Its going to have to be an encryption util/helper but just wondering which one!</p>
| <ul>
<li><a href="http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx">Encrypting and Decrypting Configuration Sections</a> (ASP.NET) on MSDN</li>
<li><a href="http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx">Encrypting Web.Config Values in ASP.NET 2.0</a> on ScottGu's <a href="http://weblogs.asp.net/scottgu/default.aspx">blog</a></li>
<li><a href="http://odetocode.com/Blogs/scott/archive/2006/01/08/2707.aspx">Encrypting Custom Configuration Sections</a> on K. Scott Allen's <a href="http://odetocode.com/Blogs/scott/default.aspx">blog</a></li>
</ul>
<p><strong>EDIT:</strong><br />
If you can't use asp utility, you can encrypt config file using <a href="http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.protectsection.aspx">SectionInformation.ProtectSection</a> method.</p>
<p>Sample on codeproject:</p>
<p><a href="https://secure.codeproject.com/KB/aspnet/webconfig.aspx">Encryption of Connection Strings inside the Web.config in ASP.Net 2.0</a> </p>
|
CakePHP ACL Database Setup: ARO / ACO structure? <p>I'm struggling to implement ACL in CakePHP. After reading the documentation in the <a href="http://manual.cakephp.org/view/171/Access-Control-Lists">cake manual</a> as well as several other tutorials, blog posts etc, I found Aran Johnson's excellent tutorial which has helped fill in many of the gaps. His examples seem to conflict with others I've seen though in a few places - specifically in the ARO tree structure he uses.</p>
<p>In his <a href="http://aranworld.com/article/169/acl-and-auth-tutorial-database-setup">examples</a> his user groups are set up as a cascading tree, with the most general user type being at the top of the tree, and its children branching off for each more restricted access type. Elsewhere I've usually seen each user type as a child of the same generic user type. </p>
<p>How do you set up your AROs and ACOs in CakePHP? Any and all tips appreciated!</p>
| <p>CakePHP's built-in ACL system is really powerful, but poorly documented in terms of actual implementation details. A system that we've used with some success in a number of CakePHP-based projects is as follows.</p>
<p>It's a modification of some group-level access systems that have been <a href="http://realm3.com/articles/setting_up_user_groups_with_acl_and_auth_in_cakephp_1.2">documented elsewhere</a>. Our system's aims are to have a simple system where users are authorised on a group-level, but they can have specific additional rights on items that were created by them, or on a per-user basis. We wanted to avoid having to create a specific entry for each user (or, more specifically for each ARO) in the <code>aros_acos</code> table.</p>
<p>We have a Users table, and a Roles table.</p>
<p><strong>Users</strong></p>
<p><code>user_id, user_name, role_id</code></p>
<p><strong>Roles</strong></p>
<p><code>id, role_name</code></p>
<p>Create the ARO tree for each role (we usually have 4 roles - Unauthorised Guest (id 1), Authorised User (id 2), Site Moderator (id 3) and Administrator (id 4)) :</p>
<p><code>cake acl create aro / Role.1</code></p>
<p><code>cake acl create aro 1 Role.2 ... etc ...</code></p>
<p>After this, you have to use SQL or phpMyAdmin or similar to add aliases for all of these, as the cake command line tool doesn't do it. We use 'Role-{id}' and 'User-{id}' for all of ours.</p>
<p>We then create a ROOT ACO - </p>
<p><code>cake acl create aco / 'ROOT'</code></p>
<p>and then create ACOs for all the controllers under this ROOT one:</p>
<p><code>cake acl create aco 'ROOT' 'MyController' ... etc ...</code></p>
<p>So far so normal. We add an additional field in the aros_acos table called <code>_editown</code> which we can use as an additional action in the ACL component's actionMap.</p>
<pre><code>CREATE TABLE IF NOT EXISTS `aros_acos` (
`id` int(11) NOT NULL auto_increment,
`aro_id` int(11) default NULL,
`aco_id` int(11) default NULL,
`_create` int(11) NOT NULL default '0',
`_read` int(11) NOT NULL default '0',
`_update` int(11) NOT NULL default '0',
`_delete` int(11) NOT NULL default '0',
`_editown` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `acl` (`aro_id`,`aco_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code></pre>
<p>We can then setup the Auth component to use the 'crud' method, which validates the requested controller/action against an AclComponent::check(). In the app_controller we have something along the lines of:</p>
<pre><code>private function setupAuth() {
if(isset($this->Auth)) {
....
$this->Auth->authorize = 'crud';
$this->Auth->actionMap = array( 'index' => 'read',
'add' => 'create',
'edit' => 'update'
'editMine' => 'editown',
'view' => 'read'
... etc ...
);
... etc ...
}
}
</code></pre>
<p>Again, this is fairly standard CakePHP stuff. We then have a checkAccess method in the AppController that adds in the group-level stuff to check whether to check a group ARO or a user ARO for access:</p>
<pre><code>private function checkAccess() {
if(!$user = $this->Auth->user()) {
$role_alias = 'Role-1';
$user_alias = null;
} else {
$role_alias = 'Role-' . $user['User']['role_id'];
$user_alias = 'User-' . $user['User']['id'];
}
// do we have an aro for this user?
if($user_alias && ($user_aro = $this->User->Aro->findByAlias($user_alias))) {
$aro_alias = $user_alias;
} else {
$aro_alias = $role_alias;
}
if ('editown' == $this->Auth->actionMap[$this->action]) {
if($this->Acl->check($aro_alias, $this->name, 'editown') and $this->isMine()) {
$this->Auth->allow();
} else {
$this->Auth->authorize = 'controller';
$this->Auth->deny('*');
}
} else {
// check this user-level aro for access
if($this->Acl->check($aro_alias, $this->name, $this->Auth->actionMap[$this->action])) {
$this->Auth->allow();
} else {
$this->Auth->authorize = 'controller';
$this->Auth->deny('*');
}
}
}
</code></pre>
<p>The <code>setupAuth()</code> and <code>checkAccess()</code> methods are called in the <code>AppController</code>'s <code>beforeFilter(</code>) callback. There's an <code>isMine</code> method in the AppControler too (see below) that just checks that the user_id of the requested item is the same as the currently authenticated user. I've left this out for clarity.</p>
<p>That's really all there is to it. You can then allow / deny particular groups access to specific acos - </p>
<p><code>cake acl grant 'Role-2' 'MyController' 'read'</code></p>
<p><code>cake acl grant 'Role-2' 'MyController' 'editown'</code></p>
<p><code>cake acl deny 'Role-2' 'MyController' 'update'</code></p>
<p><code>cake acl deny 'Role-2' 'MyController' 'delete'</code></p>
<p>I'm sure you get the picture.</p>
<p>Anyway, this answer's way longer than I intended it to be, and it probably makes next to no sense, but I hope it's some help to you ...</p>
<p>-- edit --</p>
<p>As requested, here's an edited (purely for clarity - there's a lot of stuff in our boilerplate code that's meaningless here) <code>isMine()</code> method that we have in our AppController. I've removed a lot of error checking stuff too, but this is the essence of it:</p>
<pre><code>function isMine($model=null, $id=null, $usermodel='User', $foreignkey='user_id') {
if(empty($model)) {
// default model is first item in $this->uses array
$model = $this->uses[0];
}
if(empty($id)) {
if(!empty($this->passedArgs['id'])) {
$id = $this->passedArgs['id'];
} elseif(!empty($this->passedArgs[0])) {
$id = $this->passedArgs[0];
}
}
if(is_array($id)) {
foreach($id as $i) {
if(!$this->_isMine($model, $i, $usermodel, $foreignkey)) {
return false;
}
}
return true;
}
return $this->_isMine($model, $id, $usermodel, $foreignkey);
}
function _isMine($model, $id, $usermodel='User', $foreignkey='user_id') {
$user = Configure::read('curr.loggedinuser'); // this is set in the UsersController on successful login
if(isset($this->$model)) {
$model = $this->$model;
} else {
$model = ClassRegistry::init($model);
}
//read model
if(!($record = $model->read(null, $id))) {
return false;
}
//get foreign key
if($usermodel == $model->alias) {
if($record[$model->alias][$model->primaryKey] == $user['User']['id']) {
return true;
}
} elseif($record[$model->alias][$foreignkey] == $user['User']['id']) {
return true;
}
return false;
}
</code></pre>
|
Problem rolling out ADO.Net Data Service application to IIS <p>I am adding a ADO.Net Data Service lookup feature to an existing web page. Everything works great when running from visual studio, but when I roll it out to IIS, I get the following error:</p>
<blockquote>
<p><strong>Request Error</strong><br>The server encountered an error processing the request. See server logs for more details.</p>
</blockquote>
<p>I get this even when trying to display the default page, i.e.:</p>
<blockquote>
<p><a href="http://server/FFLookup.svc">http://server/FFLookup.svc</a></p>
</blockquote>
<p>I have 3.5 SP1 installed on the server.</p>
<p>What am I missing, and which "Server Logs" is it refering to? I can't find any further error messages.</p>
<p>There is nothing in the Event Viewer logs (System or Application), and nothing in the IIS logs other than the GET:</p>
<blockquote>
<p>2008-09-10 15:20:19 10.7.131.71 GET /FFLookup.svc - 8082 - 10.7.131.86 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US)+AppleWebKit/525.13+(KHTML,+like+Gecko)+Chrome/0.2.149.29+Safari/525.13 401 2 2148074254</p>
</blockquote>
<p>There is no stack trace returned. The only response I get is the "Request Error" as noted above.</p>
<p>Thanks</p>
<p>Patrick</p>
| <p>In order to verbosely display the errors resulting from your data service you can place the following tag above your dataservice definition:</p>
<pre><code>[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
</code></pre>
<p>This will then display the error in your browser window as well as a stack trace.</p>
<p>In addition to this dataservices throws all exceptions to the HandleException method so if you implement this method on your dataservice class you can put a break point on it and see the exception:</p>
<pre><code>protected override void HandleException(HandleExceptionArgs e)
{
try
{
e.UseVerboseErrors = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
</code></pre>
|
Adding Items Using DataBinding from TreeView to ListBox WPF <p>I want to add the selected item from the <code>TreeView</code> to the <code>ListBox</code> control using <code>DataBinding</code> (If it can work with <code>DataBinding</code>). </p>
<pre><code><TreeView HorizontalAlignment="Left"
Margin="30,32,0,83"
Name="treeView1"
Width="133" >
</TreeView>
<ListBox VerticalAlignment="Top"
Margin="208,36,93,0"
Name="listBox1"
Height="196" >
</ListBox>
</code></pre>
<p><code>TreeView</code> is populated from the code behind page with some dummy data. </p>
| <p>You can bind to an element using ElementName, so if you wanted to bind the selected tree item to the ItemsSource of a ListBox:</p>
<pre><code>ItemsSource="{Binding SelectedItem, ElementName=treeView1}"
</code></pre>
|
Storing Images in PostgreSQL <p>Alright, so I'm working on an application which will use a Linux back-end running PostgreSQL to serve up images to a Windows box with the front end written in C#.NET, though the front-end should hardly matter. My question is:</p>
<ul>
<li><strong>What is the best way to deal with storing images in Postgres?</strong></li>
</ul>
<p>The images are around 4-6 megapixels each, and we're storing upwards of 3000. It might also be good to note: this is not a web application, there will at most be about two front-ends accessing the database at once.</p>
| <p>Re jcoby's answer:</p>
<p>bytea being a "normal" column also means the value being read completely into memory when you fetch it. Blobs, in contrast, you can stream into stdout. That helps in reducing the server memory footprint. Especially, when you store 4-6 MPix images.</p>
<p>No problem with backing up blobs. pg_dump provides "-b" option to include the large objects into the backup.</p>
<p>So, I prefer using pg_lo_*, you may guess.</p>
<p>Re Kris Erickson's answer:</p>
<p>I'd say the opposite :). When images are not the only data you store, don't store them on the file system unless you absolutely have to. It's such a benefit to be always sure about your data consistency, and to have the data "in one piece" (the DB). BTW, PostgreSQL is great in preserving consistency.</p>
<p>However, true, reality is often too performance-demanding ;-), and it pushes you to serve the binary files from the file system. But even then I tend to use the DB as the "master" storage for binaries, with all the other relations consistently linked, while providing some file system-based caching mechanism for performance optimization. </p>
|
Unfiltering NSPasteboard <p>Is there a way to unfilter an NSPasteboard for what the source application specifically declared it would provide?</p>
<p>I'm attempting to serialize pasteboard data in my application. When another application places an RTF file on a pasteboard and then I ask for the available types, I get eleven different flavors of said RTF, everything from the original RTF to plain strings to dyn.* values. </p>
<p>Saving off all that data into a plist or raw data on disk isn't usually a problem as it's pretty small, but when an image of any considerable size is placed on the pasteboard, the resulting output can be tens of times larger than the source data (with multiple flavors of TIFF and PICT data being made available via filtering).</p>
<p>I'd like to just be able to save off what the original app made available if possible.</p>
<hr>
<p>John, you are far more observant than myself or the gentleman I work with who's been doing Mac programming since dinosaurs roamed the earth. Neither of us ever noticed the text you highlighted... and I've not a clue why. Starting too long at the problem, apparently.</p>
<p>And while I accepted your answer as the correct answer, it doesn't exactly answer my original question. What I was looking for was a way to identify flavors that can become other flavors simply by placing them on the pasteboard <strong>AND</strong> to know which of these types were originally offered by the provider. While walking the types list will get me the preferred order for the application that provided them, it won't tell me which ones I can safely ignore as they'll be recreated when I refill the pasteboard later.</p>
<p>I've come to the conclusion that there isn't a "good" way to do this. <code>[NSPasteboard declaredTypesFromOwner]</code> would be fabulous, but it doesn't exist.</p>
| <p><code>-[NSPasteboard types]</code> will return all the available types for the data on the clipboard, but it should return them <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/instm/NSPasteboard/types" rel="nofollow">"in the order they were declared."</a></p>
<p>The documentation for <code>-[NSPasteboard declareTypes:owner:]</code> says that <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/instm/NSPasteboard/declareTypes:owner:" rel="nofollow">"the types should be ordered according to the preference of the source application."</a></p>
<p>A properly implemented pasteboard owner should, therefore, declare the richest representation of the content (probably the original content) as the first type; so a reasonable single representation should be:</p>
<pre><code>[pb dataForType:[[pb types] objectAtIndex:0]]
</code></pre>
|
ClickOnce Deployment, system update required Microsoft.mshtml <p>We have an application that works with MS Office and uses Microsoft.mshtml.dll. We use ClickOnce to deploy the application. The application deploys without issues on most machines, but sometimes we get errors saying "System Update Required, Microsoft.mshtl.dll should be in the GAC". </p>
<p>We tried installing the PIA for Office without luck. Since Microsoft.mshtml.dll is a system dependent file we cannot include it in the package and re-distribute it. What would be the best way to deploy the application?</p>
| <p>Do you know which version of MS Office you are targeting? These PIAs are very specific to the version of Office. I remember when we were building a smart client application, we used to have Build VM machines, each one targeting a specific version of Outlook.</p>
<p>Another hurdle was not being able to specify these PIAs as pre-requisites or bundle them with the app. These PIAs needs to be installed on the client using Office CD (<a href="http://msdn.microsoft.com/en-us/library/aa159923.aspx" rel="nofollow">at least for 2003 version</a>).</p>
|
Is it possible to build MSBuild files (visual studio sln) from the command line in Mono? <p>Is it possible to build Visual Studio solutions without having to fire up MonoDevelop?</p>
| <p>Current status (Mono 2.10, 2011): xbuild is now able to build all versions of Visual Studio / MSBuild projects, including .sln files. Simply run <code>xbuild</code> just as you would execute <code>msbuild</code> on Microsoft .Net Framework. You don't need Monodevelop installed, xbuild comes with the standard Mono installation.</p>
<p>If your build uses custom tasks, they should still work if they don't depend on Windows executables (such as <code>rmdir</code> or <code>xcopy</code>).</p>
<p>When you are editing project files, use standard Windows path syntax - they will be converted by xbuild, if necessary. One important caveat to this rule is case sensitivity - don't mix different casings of the same file name. If you have a project that does this, you can enable compatibility mode by invoking <code>MONO_IOMAP=case xbuild foo.sln</code> (or try <code>MONO_IOMAP=all</code>). Mono has a page describing more advanced <a href="http://www.mono-project.com/Porting_MSBuild_Projects_To_XBuild">MSBuild project porting</a> techniques.</p>
<p>Mono 2.0 answer (2008): <strike><a href="http://www.mono-project.com/Microsoft.Build">xbuild</a> is not yet complete (it works quite well with VS2005 .csproj files, has problems with VS2008 .csproj and does not handle .sln). Mono 2.1 plans to merge the code base of mdtool (MonoDevelop command line build engine) into it, but currently <a href="http://www.monodevelop.com/MonoDevelop_1.0_Released#Command_line_tools">mdtool</a> is a better choice. <code>mdtool build -f:project.sln</code> or <a href="http://ubuntu.dustinkirkland.com/manpages/intrepid/man1/mdtool.html"><code>man mdtool</code></a> if you have MonoDevelop installed.</strike></p>
|
How do prepared statements work? <p>I'm writing some DB routines and I'm using prepared statements. My environment is PDO with PHP5.</p>
<p>I understand prepared statements primarily provide a performance benefit, as well as some auxiliary bonuses such as not having to manually SQL-escape input data.</p>
<p>My question is about the performance part.</p>
<p>I have two implementations of a getPrice function below that takes a product id and returns its price.</p>
<p>getPrice_A reuses the same PDOStatement object across subsequent calls within the same script execution. Is this necessary or recommended? If so, is there any way to avoid duplicating this extra code across every single get*() in every single model?</p>
<p>getPrice_B creates a new PDOStatement object on every call. Will the DBMS recognize this statement has already been prepared and still be able to skip some work? In other words, does this implementation properly take advantage of the performance benefits of prepared statements?</p>
<p>Having written all this out and read it over, I imagine getPrice_B is fine and getPrice_A is providing a negligible benefit on top of that, which may or may not be worth the extra complication.</p>
<p>I'd still like to hear for sure from someone more knowledgable though.</p>
<p>Assume that <code>$pdo</code> is a valid, connected PDO object in the examples below.</p>
<pre><code><?php
class Product {
static function &getPrice_A($id) {
static $stmt;
if (!$stmt) {
$stmt = $pdo->prepare('SELECT price FROM products WHERE id = ?');
}
$stmt->execute(array($id));
return $stmt->fetchColumn(0);
}
static function &getPrice_B($id) {
$stmt = $pdo->prepare('SELECT price FROM products WHERE id = ?');
$stmt->execute(array($id));
return $stmt->fetchColumn(0);
}
}
// example usage:
$price = Product::getPrice(4982);
echo "Product 4982 costs $price\n";
</code></pre>
| <p>From what I understand, prepared statements will reuse the generated SQL plan if it is the same statement, so the database will see the same prepared statement and not have to do the work to figure out how to query the database. I would say the extra work of saving the prepared statement in <code>Product::getPrice_A</code> is not typically very helpful, more because it can obscure the code rather than an issue of performance. When dealing with performance, I feel it's always best to focus on code clarity and then performance when you have real statistics that indicate a problem.</p>
<p>I would say "yes, the extra work is unnecessary" (regardless of if it really boosts performance). Also, I am not a very big DB expert, but the performance gain of prepared statements is something I heard from others, and it is at the database level, not the code level (so if the code is actually invoking a parameterized statement on the actual DB, then the DB can do these execution plan caching... though depending on the database, you may get the benefit even without the parameterized statement).</p>
<p>Anyways, if you are really worried about (and seeing) database performance issues, you should look into a caching solution... of which I would highly recommend <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>. With such a solution, you can cache your query results and not even hit the database for things you access frequently.</p>
|
What's a clean/simple way to ensure the security of a page? <p>Supposing you have a form that collects and submits sensitive information and you want to ensure it is never accessed via insecure (non-HTTPS) means, how might you best go about enforcing that policy?</p>
| <p>If you're running Apache, you can put a <code>RewriteRule</code> in your <code>.htaccess</code>, like so:</p>
<pre><code>RewriteCond %{HTTPS} "off"
RewriteRule /mypage.html https://example.com/mypage.html
</code></pre>
|
Php function argument error suppression, empty() isset() emulation <p>I'm pretty sure the answer to this question is no, but in case there's some PHP guru</p>
<p>is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of <code>'@'</code></p>
<p>Much like empty and isset do. You can pass in a variable you just made up and it won't error.</p>
<pre><code>ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
</code></pre>
| <p>Summing up, the proper answer is <strong>no, you shouldn't</strong> (see caveat below). </p>
<p>There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.</p>
<p>Summarizing an interesting comment discussion with <a href="http://stackoverflow.com/users/109561/gerry">Gerry</a>: Passing the variable by reference is indeed valid if you <strong>check for the value of the variable inside the function</strong> and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).</p>
|
NullReferenceException on instanciated object? <p>This is a segment of code from an app I've inherited, a user got a Yellow screen of death:</p>
<blockquote>
<p>Object reference not set to an instance of an object</p>
</blockquote>
<p>on the line: </p>
<pre><code>bool l_Success ...
</code></pre>
<p>Now I'm 95% sure the faulty argument is <code>ref l_Monitor</code> which is very weird considering the object is instantiated a few lines before. Anyone have a clue why it would happen? Note that I have seen the same issue pop up in other places in the code.</p>
<pre><code>IDMS.Monitor l_Monitor = new IDMS.Monitor();
l_Monitor.LogFile.Product_ID = "SE_WEB_APP";
if (m_PermType_RadioButtonList.SelectedIndex == -1) {
l_Monitor.LogFile.Log(
Nortel.IS.IDMS.LogFile.MessageTypes.ERROR,
"No permission type selected"
);
return;
}
bool l_Success = SE.UI.Utilities.GetPermissionList(
ref l_Monitor,
ref m_CPermissions_ListBox,
(int)this.ViewState["m_Account_Share_ID"],
(m_PermFolders_DropDownList.Enabled)
? m_PermFolders_DropDownList.SelectedItem.Value
: "-1",
(SE.Types.PermissionType)m_PermType_RadioButtonList.SelectedIndex,
(SE.Types.PermissionResource)m_PermResource_RadioButtonList.SelectedIndex);
</code></pre>
| <p>You sure that one of the properties trying to be accessed on the l_Monitor instance isn't null?</p>
|
Database engines Comparison - Windows Mobile <p>What are the different database options on Windows Mobile available?
I have used CEDB and EDB for linear dataset needs.</p>
<p>I have heard of SQL server 2005 Mobile edition. But what are the advantages over others (if there is any)</p>
| <p>Also take a look at <a href="http://sqlite-wince.sourceforge.net/" rel="nofollow">SQLite for Windows CE</a>. There are also .NET bindings available to use it from the Compact Framework.</p>
|
In Python, how can you easily retrieve sorted items from a dictionary? <p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p>
<p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p>
<p>For example, you had this:</p>
<pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
</code></pre>
<p>I want to print the associated values in the following sequence sorted by key:</p>
<pre><code>this is a
this is b
this is c
</code></pre>
| <p>Do you mean that you need the values sorted by the value of the key?
In that case, this should do it:</p>
<pre><code>for key in sorted(d):
print d[key]
</code></pre>
<p><strong>EDIT:</strong> changed to use sorted(d) instead of sorted(d.keys()), thanks <a href="http://stackoverflow.com/users/1694/eli-courtwright" rel="nofollow">Eli</a>!</p>
|
Algorithm to generate anagrams <p>What would be the best strategy to generate anagrams.</p>
<blockquote>
<pre><code>An anagram is a type of word play, the result of rearranging the letters
of a word or phrase to produce a new word or phrase, using all the original
letters exactly once;
ex.
</code></pre>
<ul>
<li><strong>Eleven plus two</strong> is anagram of <strong><em>Twelve plus one</em></strong> </li>
<li><strong>A decimal point</strong> is anagram of <strong><em>I'm a dot in place</em></strong></li>
<li><strong>Astronomers</strong> is anagram of <strong><em>Moon starers</em></strong></li>
</ul>
</blockquote>
<p>At first it looks straightforwardly simple, just to jumble the letters and generate all possible combinations. But what would be the efficient approach to generate only the words in dictionary.</p>
<p>I came across this page, <a href="http://lojic.com/blog/2007/10/22/solving-anagrams-in-ruby/">Solving anagrams in Ruby</a>. </p>
<p>But what are your ideas?</p>
| <p>Most of these answers are horribly inefficient and/or will only give one-word solutions (no spaces). My solution will handle any number of words and is very efficient.</p>
<p>What you want is a trie data structure. Here's a <strong>complete</strong> Python implementation. You just need a word list saved in a file named <code>words.txt</code> You can try the Scrabble dictionary word list here:</p>
<p><a href="http://www.isc.ro/lists/twl06.zip">http://www.isc.ro/lists/twl06.zip</a></p>
<pre class="lang-py prettyprint-override"><code>MIN_WORD_SIZE = 4 # min size of a word in the output
class Node(object):
def __init__(self, letter='', final=False, depth=0):
self.letter = letter
self.final = final
self.depth = depth
self.children = {}
def add(self, letters):
node = self
for index, letter in enumerate(letters):
if letter not in node.children:
node.children[letter] = Node(letter, index==len(letters)-1, index+1)
node = node.children[letter]
def anagram(self, letters):
tiles = {}
for letter in letters:
tiles[letter] = tiles.get(letter, 0) + 1
min_length = len(letters)
return self._anagram(tiles, [], self, min_length)
def _anagram(self, tiles, path, root, min_length):
if self.final and self.depth >= MIN_WORD_SIZE:
word = ''.join(path)
length = len(word.replace(' ', ''))
if length >= min_length:
yield word
path.append(' ')
for word in root._anagram(tiles, path, root, min_length):
yield word
path.pop()
for letter, node in self.children.iteritems():
count = tiles.get(letter, 0)
if count == 0:
continue
tiles[letter] = count - 1
path.append(letter)
for word in node._anagram(tiles, path, root, min_length):
yield word
path.pop()
tiles[letter] = count
def load_dictionary(path):
result = Node()
for line in open(path, 'r'):
word = line.strip().lower()
result.add(word)
return result
def main():
print 'Loading word list.'
words = load_dictionary('words.txt')
while True:
letters = raw_input('Enter letters: ')
letters = letters.lower()
letters = letters.replace(' ', '')
if not letters:
break
count = 0
for word in words.anagram(letters):
print word
count += 1
print '%d results.' % count
if __name__ == '__main__':
main()
</code></pre>
<p>When you run the program, the words are loaded into a trie in memory. After that, just type in the letters you want to search with and it will print the results. It will only show results that use all of the input letters, nothing shorter.</p>
<p>It filters short words from the output, otherwise the number of results is huge. Feel free to tweak the <code>MIN_WORD_SIZE</code> setting. Keep in mind, just using "astronomers" as input gives 233,549 results if <code>MIN_WORD_SIZE</code> is 1. Perhaps you can find a shorter word list that only contains more common English words.</p>
<p>Also, the contraction "I'm" (from one of your examples) won't show up in the results unless you add "im" to the dictionary and set <code>MIN_WORD_SIZE</code> to 2.</p>
<p>The trick to getting multiple words is to jump back to the root node in the trie whenever you encounter a complete word in the search. Then you keep traversing the trie until all letters have been used.</p>
|
Refresh all update panels on the page? <p>I have some code that modifies a value that several controls in other update panels are bound to. When this event handler fires, I'd like it to force the other update panels to refresh as well, so they can rebind.</p>
<p>Is this possible?</p>
<p>Edit: </p>
<p>To clarify, I have an update panel in one user control, the other update panels are in other user controls, so they can't see each other unless I were to expose some custom properties and use findControl etc etc...</p>
<p>Edit Again:</p>
<p>Here is what I came up with:</p>
<pre><code>public void Update()
{
recursiveUpdate(this);
}
private void recursiveUpdate(Control control)
{
foreach (Control c in control.Controls)
{
if (c is UpdatePanel)
{
((UpdatePanel)c).Update();
}
if (c.HasControls())
{
recursiveUpdate(c);
}
}
}
</code></pre>
<p>I had 3 main user controls that were full of update panels, these controls were visible to the main page, so I added an Update method there that called Update on those three.</p>
<p>In my triggering control, I just cast this.Page into the currentpage and called Update.</p>
<p>Edit:</p>
<p>AARRGGGG!</p>
<p>While the update panels refresh, it does not call Page_Load within the subcontrols in them...What do I do now!</p>
| <p>What about registering a PostBackTrigger (instead of an AsyncPostBackTrigger) that will refresh every panel when a specific event fires. </p>
<p>Or add the trigger that already refreshes some UpdatePanels to the other UpdatePanels as well.</p>
|
How do I maintain position of a DragPanelExtender across postbacks? <p>I already found this article:</p>
<p><a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=181&AspxAutoDetectCookieSupport=1" rel="nofollow">http://www.dotnetcurry.com/ShowArticle.aspx?ID=181&AspxAutoDetectCookieSupport=1</a></p>
<p>But I've got a different situation. I am embedding some hiddenFields inside of the master page and trying to store the position of the dragPanel in those. </p>
<p>I am using javascript to store the position of the dragPanel and then when the user clicks on a link, the new page is loaded, but the dragPanel is reset into the starting position.</p>
<p><strong>Is there any easy way to do this?</strong> </p>
<p>Pseudocode:</p>
<pre><code>**this is in MasterPage.master**
function pageLoad()
{
// call the savePanelPosition when the panel is moved
$find('DragP1').add_move(savePanelPosition);
var elem = $get("<%=HiddenField1.ClientID%>");
if(elem.value != "0")
{
var temp = new Array();
temp = elem.value.split(';');
// set the position of the panel manually with the retrieve value
$find('<%=Panel1_DragPanelExtender.BehaviorID%>').set_location(new
Sys.UI.Point(parseInt(temp[0]),parseInt(temp[1])));
}
}
function savePanelPosition()
{
var elem = $find('DragP1').get_element();
var loc = $common.getLocation(elem);
var elem1 = $get("<%=HiddenField1.ClientID%>");
// store the value in the hidden field
elem1.value = loc.x + ';' + loc.y;
}
<asp:Button ID="Button1" runat="server" Text="Button"/>
<asp:HiddenField ID="HiddenField1" runat="server" Value="0"
</code></pre>
<p>However, <strong>HiddenField</strong> is not visible in the redirected page, foo.aspx</p>
| <p>Rather than storing the position information in a hidden field, store it in a cookie. The information is small, so it will have minimal effect on the page load performance.</p>
|
Bespoke SQL Server 'encoding' sproc - is there a neater way of doing this? <p>I'm just wondering if there's a better way of doing this in SQL Server 2005.</p>
<p>Effectively, I'm taking an originator_id (a number between 0 and 99) and a 'next_element' (it's really just a sequential counter between 1 and 999,999).
We are trying to create a 6-character 'code' from them. </p>
<p>The originator_id is multiplied up by a million, and then the counter added in, giving us a number between 0 and 99,999,999.</p>
<p>Then we convert this into a 'base 32' string - a fake base 32, where we're really just using 0-9 and A-Z but with a few of the more confusing alphanums removed for clarity (I, O, S, Z).</p>
<p>To do this, we just divide the number up by powers of 32, at each stage using the result we get for each power as an index for a character from our array of selected character.</p>
<pre>
Thus, an originator ID of 61 and NextCodeElement of 9 gives a code of '1T5JA9'
(61 * 1,000,000) + 9 = 61,000,009
61,000,009 div (5^32 = 33,554,432) = 1 = '1'
27,445,577 div (4^32 = 1,048,576) = 26 = 'T'
182,601 div (3^32 = 32,768) = 5 = '5'
18,761 div (2^32 = 1,024) = 18 = 'J'
329 div (1^32 = 32) = 10 = 'A'
9 div (0^32 = 1) = 9 = '9'
so my code is 1T5JA9
</pre>
<p>Previously I've had this algorithm working (in Delphi) but now I really need to be able to recreate it in SQL Server 2005. Obviously I don't quite have the same functions to hand that I have in Delphi, but this is my take on the routine. It works, and I can generate codes (or reconstruct codes back into their components) just fine.</p>
<p>But it looks a bit long-winded, and I'm not sure that the trick of selecting the result of a division into an int (ie casting it, really) is necessarily 'right' - is there a better SQLS approach to this kind of thing?</p>
<pre>
CREATE procedure dummy_RP_CREATE_CODE @NextCodeElement int, @OriginatorID int,
@code varchar(6) output
as
begin
declare @raw_num int;
declare @bcelems char(32);
declare @chr int;
select @bcelems='0123456789ABCDEFGHJKLMNPQRTUVWXY';
select @code='';
-- add in the originator_id, scaled into place
select @raw_num = (@OriginatorID * 1000000) + @NextCodeElement;
-- now to convert this to a 6-char code
-- 5^32
select @chr = @raw_num / 33554432;
select @raw_num = @raw_num - (@chr * 33554432);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 4^32
select @chr = @raw_num / 1048576;
select @raw_num = @raw_num - (@chr * 1048576);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 3^32
select @chr = @raw_num / 32768;
select @raw_num = @raw_num - (@chr * 32768);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 2^32
select @chr = @raw_num / 1024;
select @raw_num = @raw_num - (@chr * 1024);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 1^32
select @chr = @raw_num / 32;
select @raw_num = @raw_num - (@chr * 32);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 0^32
select @code = @code + SUBSTRING(@bcelems, 1 + @raw_num, 1);
-- that's it!
end;
</pre>
<p>I'm not desperately concerned about optimisation unless this method is actually an order of magnitude (or so) worse than any alternative. </p>
<p>The code only ever gets executed in small bursts, maybe generating 20 or 30 codes every 10 minutes or so. Because of the large range of numbers I don't want to pre-calculate the codes into a huge table (only small pockets of the overall code range will be used in any given installation).</p>
<p>However, I'm sure there's probably a tidier way of achieving the same result - particularly those divisions and subtractions.</p>
<p>Any constructive criticism, observations or suggestions would be most welcome. </p>
| <p>Seeing as it's SQL Server 2005, any reason not to use a CLR stored procedure? You could use your CLR language of choice then and it'd probably be a relatively direct port of your existing Delphi code.</p>
|
"Background" task in palm OS <p>I'm trying to create a Palm OS app to check a web site every X minutes or hours, and provide a notification when a piece of data is available. I know that this kind of thing can be done on the new Palm's - for example, my Centro can have email or web sites download when the application isn't on top - but I don't know how to do it. Can anyone point me in the right direction?</p>
| <p>This is possible to do but very difficult. There are several steps you'll have to take.</p>
<p>First off, this only works on Palm OS 5 and is sketchy on some of the early Palm OS 5 devices. The latest devices are better but not perfect.</p>
<p>Next, you will need to create an alarm for your application using AlmSetAlarm. This is how you accomplish the "every X minutes or hours" part.</p>
<p>When the alarm fires, your application will get a sysAppLaunchCmdAlarmTriggered launch code, even if it's not already running. If you only want to do something simple and quick, you can do it in response to the launch code and you're done.</p>
<p>After you do your stuff in the alarm launch code, be sure to set up the next alarm so that you continue to be called.</p>
<p>Important notes: You cannot access global variables when responding this launch code! Depending on the setup in your compiler, you probably also won't be able to access certain C++ features, like virtual functions (which internally use global variables). There is a setting you can set in Codewarrior that will help with this, but I'm not too familiar with it. You should architect your code so that it doesn't need globals; for example, you can use FtrSet and FtrGet to store bits of global data that you might need. Finally, you will only be able to access a single 64KB code segment of 68000 machine code. Inter-segment jumps don't work properly without globals set up.</p>
<p>You can get around a lot of these restrictions by moving the majority of your code to a PNOlet, but that's an entirely different and more complicated topic.</p>
<p>If you want to do something more complicated that could take a while (e.g. load a web page or download email), it is strongly recommended not to do it during the alarm launch code. You could do something in the sysAppLaunchCmdDisplayAlarm launch code and display a form to the user allowing them to cancel. But this is bound to get annoying quickly.</p>
<p>Better for the user experience (but much more complicated) is to become a background application. This is a bit of black magic and is not really well supported, but it is possible. There are basically three steps to becoming a background application:</p>
<ol>
<li><p>Protect your application database using DmDatabaseProtect. This will ensure that your application is locked down so it can't be deleted.</p></li>
<li><p>Lock your code segment using MemHandleLock and MemHandleSetOwner (set the owner to 0). This will ensure that your code is loaded into memory and won't be moved.</p></li>
<li><p>Register for some notifications. For example, the sysNotifyIdleTimeEvent is a great notification to use to do some periodic background processing.</p></li>
</ol>
<p>Once you set this up, you can exit from the alarm launch code and then wait for your notifications to fire. You will then do all of your background processing when your notification handlers are called.</p>
<p>Also make sure that if you allocate any system objects (memory, handles, file handles, etc.), you set their owner to 0 (system) if you expect them to persist after you return from your notification handler. Otherwise the system will clean them up. If you do this, be super careful to avoid memory and resource leaks!! They will never get cleaned up when the owner is set to 0!</p>
<p>To leave background mode, simply do the reverse: unregister for notifications, unlock your code segment, and unprotect your application database.</p>
<p>If you do any network operations in the background, be sure that you set the sockets to non-blocking mode and deal correctly with that! Otherwise you will block the foreground application and cause problems.</p>
|
__doPostBack is not working in firefox <p>The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??</p>
<p>It's a simple asp:LinkButton with an OnClick event</p>
<pre><code><asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
</code></pre>
<p>The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.</p>
<p>I enable the control on the page load event.</p>
<p>Any ideas?</p>
<p><hr /></p>
<p>I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"</p>
<p>Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.</p>
<p>Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.</p>
| <p>Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.</p>
<p>From <a href="http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1">http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1</a>:</p>
<blockquote>
<p>To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset</p>
</blockquote>
|
Checking Inheritance with templates in C++ <p>I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.</p>
<pre><code>template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}
</code></pre>
<p>Now, how do I make sure that <code>ImplementationClass</code> can be derived from a set of classes only, similar to java's generics</p>
<pre><code><? extends BaseClass>
</code></pre>
<p>syntax?</p>
| <p>It's verbose, but you can do it like this:</p>
<pre><code>#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
struct base {};
template <typename ImplementationClass, class Enable = void>
class WrapperClass;
template <typename ImplementationClass>
class WrapperClass<ImplementationClass,
typename boost::enable_if<
boost::is_base_of<base,ImplementationClass> >::type>
{};
struct derived : base {};
struct not_derived {};
int main() {
WrapperClass<derived> x;
// Compile error here:
WrapperClass<not_derived> y;
}
</code></pre>
<p>This requires a compiler with good support for the standard (most recent compilers should be fine but old versions of Visual C++ won't be). For more information, see the <a href="http://www.boost.org/doc/libs/1_36_0/libs/utility/enable_if.html" rel="nofollow">Boost.Enable_If documentation</a>.</p>
<p>As Ferruccio said, a simpler but less powerful implementation:</p>
<pre><code>#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>
struct base {};
template <typename ImplementationClass>
class WrapperClass
{
BOOST_STATIC_ASSERT((
boost::is_base_of<base, ImplementationClass>::value));
};
</code></pre>
|
What is the possible mimetype hierachy of an email message? <p>I'm working with a snippet of code that recursively calls itself and tries to pull out a MIME Type part of <code>text/html</code> from an email (if it exists) for further processing.</p>
<p>The "text/html" could exist inside other content such as <code>multipart/alternative</code>, so I'm trying to find out if there is a defined hierarchy for email MIME Types.</p>
<p>Anybody know if there is and what it is? i.e. what types can parent other types?</p>
| <p>Your question assumes that mail clients follow the RFC standards for MIME encoding, which they don't. I'd advise you collect a bunch of mail from sources and try and process it as-it-exists. The problem you are facing is extremely difficult (perhaps impossible) to solve 100%.</p>
|
When do function-level static variables get allocated/initialized? <p>I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.</p>
<pre><code>int globalgarbage;
unsigned int anumber = 42;
</code></pre>
<p>But what about static ones defined within a function?</p>
<pre><code>void doSomething()
{
static bool globalish = true;
// ...
}
</code></pre>
<p>When is the space for <code>globalish</code> allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when <code>doSomething()</code> is first called?</p>
| <p>I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.</p>
<pre><code>include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
};
test t("global variable");
void f()
{
static test t("static variable");
test t2("Local variable");
cout << "Function executed" << endl;
}
int main()
{
test t("local to main");
cout << "Program start" << endl;
f();
cout << "Program end" << endl;
return 0;
}
</code></pre>
<p>The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:</p>
<pre><code>global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed
</code></pre>
|
Service that provides DVD Covers art? <p>Are there any services that allow you to retrieve DVD cover information? I'm working on a small WPF application where this functionality would be handy. If a user inserts a DVD or types a title in, it'll automatically grab the cover art for that DVD.</p>
<p>Thanks.</p>
| <p>Not sure if they have an API, but you should check out <a href="http://albumart.org" rel="nofollow">http://albumart.org</a>. Also check out <a href="http://www.freecovers.net/api" rel="nofollow">http://www.freecovers.net/api</a>, a similar service.</p>
|
Find out where your PHP code is slowing down (Performance Issue) <p>Here's my first question at SO.</p>
<p>I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. </p>
<p>The problem is the applications is <strong>very slow</strong>.</p>
<p>How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code.</p>
<p>I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. </p>
<p>Thoughts?</p>
| <p>I've used <a href="http://www.xdebug.org/docs/profiler">XDebug profiling</a> recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ). </p>
|
Why can't I delete this cookie? <p>Okay, here is the 411 - I have the following event handler in my Global.asax.cs file:</p>
<pre><code>private void Global_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (/* logic that determines that this is an ajax call */)
{
// we want to set a cookie
Response.Cookies.Add(new HttpCookie("MyCookie", "true"));
}
}
</code></pre>
<p>That handler will run during Ajax requests (as a result of the Ajax framework I am using), as well as at other times - the condition of the if statement filters out non-Ajax events, and works just fine (it isn't relevant here, so I didn't include it for brevity's sake).</p>
<p>It suffices us to say that this works just fine - the cookie is set, I am able to read it on the client, and all is well up to that point.</p>
<p>Now for the part that drives me nuts.</p>
<p>Here is the JavaScript function I am using to delete the cookie:</p>
<pre><code>function deleteCookie(name) {
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime() - 1);
document.cookie = (name + "=; expires=" + cookieDate.toGMTString());
}
</code></pre>
<p>So, of course, at some point after the cookie is set, I delete it like so:</p>
<pre><code>deleteCookie("MyCookie");
</code></pre>
<p>Only, that doesn't do the job; the cookie still exists. So, anyone know why?</p>
| <p>you have to delete your cookie at the same path where you created it.
so create your cookie with path=/ and delte it with path=/ as well..</p>
|
DELETE Statement hangs on SQL Server for no apparent reason <p><strong>Edit</strong>: Solved, there was a trigger with a loop on the table (read my own answer further below).</p>
<p><hr /></p>
<p>We have a simple delete statement that looks like this:</p>
<pre><code>DELETE FROM tablename WHERE pk = 12345
</code></pre>
<p>This just hangs, no timeout, no nothing.</p>
<p>We've looked at the execution plan, and it consists of many lookups on related tables to ensure no foreign keys would trip up the delete, but we've verified that none of those other tables have any rows referring to that particular row.</p>
<p>There is no other user connected to the database at this time.</p>
<p>We've run DBCC CHECKDB against it, and it reports 0 errors.</p>
<p>Looking at the results of <em><code>sp_who</code></em> and <em><code>sp_lock</code></em> while the query is hanging, I notice that my spid has plenty of PAG and KEY locks, as well as the occasional TAB lock.</p>
<p>The table has 1.777.621 rows, and yes, pk is the primary key, so it's a single row delete based on index. There is no table scan in the execution plan, though I notice that it contains something that says <em>Table Spool (Eager Spool)</em>, but says Estimated number of rows 1. Can this actually be a table-scan in disguise? It only says it looks at the primary key column.</p>
<p>Tried DBCC DBREINDEX and UPDATE STATISTICS on the table. Both completed within reasonable time.</p>
<p>There is unfortunately a high number of indexes on this particular table. It is the core table in our system, with plenty of columns, and references, both outgoing and incoming. The exact number is 48 indexes + the primary key clustered index.</p>
<p>What else should we look at?</p>
<p>Note also that this table did not have this problem before, this problem occured suddently today. We also have many databases with the same table setup (copies of customer databases), and they behave as expected, it's just this one that is problematic.</p>
| <p>One piece of information missing is the number of indices on the table you are deleting the data from. As SQL Server uses the Primary Key as a pointer in every index, any change to the primary index requires updating every index. Though, unless we are talking a high number, this shouldn't be an issue.</p>
<p>I am guessing, from your description, that this is a primary table in the database, referenced by many other tables in FK relationships. This would account for the large number of locks as it checks the rest of the tables for references. And, if you have cascading deletes turned on, this could lead to a delete in table a requiring checks several tables deep.</p>
|
Subversion merge history visualisation <p>Are there any utilities out there which can draw pictures of the merge history of a subversion repo - we always commit merges with a (fairly) consistent log message, and it would be handy to be able to automatically extract this info into a single picture that shows what branches occurred when, and what the state of merges is.</p>
<p>I'm just interested in an informational tool, not something to help with actually performing merges.</p>
| <p>TortoiseSVN can show <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-revgraph.html" rel="nofollow">revision graph</a> - visual representation of branching \ merging history and more.</p>
|
Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)? <p>I have a class in system-C with some data members as such: </p>
<pre><code>long double x[8];
</code></pre>
<p>I'm initializing it in the construction like this:</p>
<pre><code>for (i = 0; i < 8; ++i) {
x[i] = 0;
}
</code></pre>
<p>But the first time I use it in my code I have garbage there.</p>
<p>Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?</p>
<p>Edit:
@<a href="#56477" rel="nofollow">Prakash</a>:
Actually, this is a typo in the <em>question</em>, but not in my code... Thanks!</p>
| <p>Sure, it will be garbage!</p>
<p>The code should have been as </p>
<pre><code>for (i = 0; i < 8; ++i) {
x[i] = 0;
}
</code></pre>
<p>EDIT: Oops, Sorry for underestimating ;)</p>
|
Foxpro App and removable drives problem <p>I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (<strong>FROM WINDOWS</strong>, not fox):</p>
<p>Windows-No disk
Exception Processing Message c0000012 Parameters .....</p>
<p>Any help please
Nelson Marmol</p>
| <p>Nelson:</p>
<p>"That's how foxpro does it and there is no way around it"?</p>
<p>I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.</p>
<p>You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro?
If you're using VFP 8+, you can use SYS(2450, 1):</p>
<pre><code>Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.
You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.
SYS(2450 [, 0 | 1 ])
Parameters
0
Search along path and default locations before searching in the application. (Default)
1
Search within the application for the specified procedure or UDF before searching the path and default locations.
</code></pre>
<p>One quick workaround could be assign another letter to your USB via the Disk Manager.</p>
|
Can't access variable in C++ DLL from a C app <p>I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put</p>
<pre><code>extern "C" _declspec(dllexport) char* MyNewVariable = 0;
</code></pre>
<p>which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including</p>
<pre><code>_declspec(dllimport) char* MyNewVariable;
</code></pre>
<p>but that just gives me a linker error:</p>
<p>unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA)</p>
<pre><code>extern "C" _declspec(dllimport) char* MyNewVariable;
</code></pre>
<p>as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:</p>
<p>unresolved external symbol __imp__MyNewVariable</p>
<p>How do I write the declaration so that the C++ DLL variable is accessible from the C app?</p>
<p><hr /></p>
<h2>The Answer</h2>
<p>As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.</p>
| <p>you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the <code>.lib</code> file. And yes, you should also declare the variable as:</p>
<pre><code>extern "C" { declspec(dllimport) char MyNewVariable; }
</code></pre>
|
How can I get a fixed-position menu like slashdot's comment filtration menu <p>Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click <a href="http://news.slashdot.org/news/08/09/10/2257242.shtml" rel="nofollow">here</a>.)</p>
<p>My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?</p>
| <p>Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.</p>
<pre><code>var MenuManager = Class.create({
initialize: function initialize(menuElt) {
this.menu = $(menuElt);
this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };
registerEvent(document, 'scroll', this.handleScroll.bind(this));
this.handleScroll();
},
handleScroll: function handleScroll() {
this.scrollOffset = document.viewport.getScrollOffsets().top;
if (this.scrollOffset > this.homePosn.y) {
this.menu.style.position = 'fixed';
this.menu.style.top = 0;
this.menu.style.left = this.homePosn.x;
} else {
this.menu.style.position = 'absolute';
this.menu.style.top = null;
this.menu.style.left = null;
}
}
});
</code></pre>
<p>Just call the constructor with the id of your menu, and the class will take it from there.</p>
|
Is a Flex debugger included in the sdk? <p>I have been writing Flex applications for a few months now and luckily have not needed a full debugger as of yet, so far I have just used a few Alert boxes...</p>
<p>Is there an available debugger that is included in the free Flex SDK? I am not using FlexBuilder (I have been using Emacs and compiling with ant).</p>
<p>If not, how do you debug Flex applications without FlexBuilder? (note: I have no intentions of using flexbuilder)</p>
| <p>A debugger called <code>fdb</code> is included in the Flex SDK. Here's some documentation on how to use it:</p>
<ul>
<li><a href="http://www.adobe.com/devnet/flex/articles/client_debug_08.html" rel="nofollow">Adobe DevCenter: Debugging Client-Side Code in Flex Applications</a></li>
<li><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=debugging_01.html" rel="nofollow">Flex 3 Help: Using the Command-Line Debugger</a></li>
</ul>
|
How do I make dynamic content with dynamic navigation? <p>I'm creating an ASP.NET web site where all pages hang off a database-driven tree-hierarchy. Pages typically present HTML content. But, some will execute programming.</p>
<p>Examples: (1) a "contact us" form or (2) a report generator</p>
<p>How should I represent/reference the programming within the database? Should I have a varchar value of a Web User Control (.ascx) name? Or a Web Form (.aspx) name? Something else? Or should it just be an integer or other such ID in a dictionary within my application?</p>
<p>Can I make an ASP.NET Site Map Provider with this structure?</p>
<p>See more information here: <a href="http://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation" rel="nofollow">Which is the best database schema for my navigation?</a></p>
| <p>You might consider inserting placeholders like <code><my:contact-us-form/></code> in the database on specific pages; that way the database can describe all the static text content instead of completely replacing that database-driven content with an <code>.ascx</code> control.</p>
|
How do I start threads in plain C? <p>I have used fork() in C to start another process. How do I start a new thread?</p>
| <p>Since you mentioned fork() I assume you're on a Unix-like system, in which case <a href="http://en.wikipedia.org/wiki/POSIX_Threads">POSIX threads</a> (usually referred to as pthreads) are what you want to use.</p>
<p>Specifically, pthread_create() is the function you need to create a new thread. Its arguments are:</p>
<pre><code>int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *
(*start_routine)(void *), void * arg);
</code></pre>
<p>The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.</p>
|
round() in Python doesn't seem to be rounding properly <p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p>
<pre><code>n = 5.59
round(n, 1) # 5.6
</code></pre>
<p>But, in actuality, good old floating point weirdness creeps in and you get:</p>
<pre><code>5.5999999999999996
</code></pre>
<p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p>
<p>Short of creating my own round library, is there any way around this?</p>
| <p>Formatting works correctly even without having to round:</p>
<pre><code>"%.1f" % n
</code></pre>
|
What is the Liskov Substitution Principle? <p>I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?</p>
| <p>A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.</p>
<p>In mathematics, a <code>Square</code> is a <code>Rectangle</code>. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made <code>Square</code> derive from <code>Rectangle</code>, then a <code>Square</code> should be usable anywhere you expect a <code>Rectangle</code>. This makes for some strange behavior. </p>
<p>Imagine you had <code>SetWidth</code> and <code>SetHeight</code> methods on your <code>Rectangle</code> base class; this seems perfectly logical. However if your <code>Rectangle</code> reference pointed to a <code>Square</code>, then <code>SetWidth</code> and <code>SetHeight</code> doesn't make sense because setting one would change the other to match it. In this case <code>Square</code> fails the Liskov Substitution Test with <code>Rectangle</code> and the abstraction of having <code>Square</code> inherit from <code>Rectangle</code> is a bad one.</p>
<p><img src="http://lostechies.com/derickbailey/files/2011/03/LiskovSubtitutionPrinciple_52BB5162.jpg" width="640" height="480"></p>
<p>Y'all should check out the other priceless <a href="http://www.lostechies.com/blogs/derickbailey/archive/2009/02/11/solid-development-principles-in-motivational-pictures.aspx">SOLID Principles Motivational Posters</a>.</p>
|
Right Align text in SQL Server <p>We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...</p>
<p>I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:</p>
<pre><code>Value
----------
143.55
3532.13
1.75
</code></pre>
<p>How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".</p>
<p>I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.</p>
<p>Thank you.</p>
| <p>The <a href="http://msdn.microsoft.com/en-us/library/ms189527.aspx">STR function</a> has an optional length argument as well as a number-of-decimals one.</p>
<pre><code>SELECT STR(123.45, 6, 1)
------
123.5
(1 row(s) affected)
</code></pre>
|
Best way to reduce sequences in an array of strings <p>Please, now that I've re-written the question, and before it suffers from further <a href="http://stackoverflow.com/questions/56103/fastest-gun-in-the-west-problem" rel="nofollow">fast-gun answers</a> or premature closure by <a href="http://stackoverflow.com/users/905/keith" rel="nofollow">eager editors</a> let me point out that this is not a duplicate of <a href="http://stackoverflow.com/questions/9673/remove-duplicates-from-array" rel="nofollow">this question</a>. I know how to remove duplicates from an array.</p>
<p>This question is about removing <strong>sequences</strong> from an array, not duplicates in the strict sense.</p>
<p>Consider this sequence of elements in an array;</p>
<pre><code>[0] a
[1] a
[2] b
[3] c
[4] c
[5] a
[6] c
[7] d
[8] c
[9] d
</code></pre>
<p>In this example I want to obtain the following...</p>
<pre><code>[0] a
[1] b
[2] c
[3] a
[4] c
[5] d
</code></pre>
<p>Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.</p>
<p>Further, notice that when two lines repeat they should be reduced to one set (of two lines).</p>
<pre><code>[0] c
[1] d
[2] c
[3] d
</code></pre>
<p>...reduces to...</p>
<pre><code>[0] c
[1] d
</code></pre>
<p>I'm coding in C# but algorithms in any language appreciated.</p>
| <p><strong>EDIT: made some changes and new suggestions</strong></p>
<p>What about a sliding window...</p>
<pre><code>REMOVE LENGTH 2: (no other length has other matches)
//the lower case letters are the matches
ABCBAbabaBBCbcbcbVbvBCbcbcAB
__ABCBABABABBCBCBCBVBVBCBCBCAB
REMOVE LENGTH 1 (duplicate characters):
//* denote that a string was removed to prevent continual contraction
//of the string, unless this is what you want.
ABCBA*BbC*V*BC*AB
_ABCBA*BBC*V*BC*AB
RESULT:
ABCBA*B*C*V*BC*AB == ABCBABCVBCAB
</code></pre>
<p>This is of course starting with length=2, increase it to L/2 and iterate down. </p>
<p>I'm also thinking of two other approaches:</p>
<ol>
<li><strong>digraph</strong> - Set a stateful digraph with the data and iterate over it with the string, if a cycle is found you'll have a duplication. I'm not sure how easy it is check check for these cycles... possibly some dynamic programming, so it could be equivlent to method 2 below. I'm going to have to think about this one as well longer.</li>
<li><strong>distance matrix</strong> - using a levenstein distance matrix you might be able to detect duplication from diagonal movement (off the diagonal) with cost 0. This could indicate duplication of data. I will have to think about this more.</li>
</ol>
|
Which .Net collection for adding multiple objects at once and getting notified? <p>Was considering the <code>System.Collections.ObjectModel ObservableCollection<T></code> class. This one is strange because </p>
<ul>
<li>it has an Add Method which takes <strong>one</strong> item only. No AddRange or equivalent. </li>
<li>the Notification event arguments has a NewItems property, which is a <strong>IList</strong> (of objects.. not T)</li>
</ul>
<p>My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?</p>
<p><em>Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.</em></p>
<p><hr></p>
<p>Related Q:<br>
<a href="http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each</a></p>
| <p>It seems that the <code>INotifyCollectionChanged</code> interface allows for updating when multiple items were added, so I'm not sure why <code>ObservableCollection<T></code> doesn't have an <code>AddRange</code>. You could make an extension method for <code>AddRange</code>, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from <code>ObservableCollection<T></code> as follows:</p>
<pre><code>public class MyObservableCollection<T> : ObservableCollection<T>
{
// matching constructors ...
bool isInAddRange = false;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
// intercept this when it gets called inside the AddRange method.
if (!isInAddRange)
base.OnCollectionChanged(e);
}
public void AddRange(IEnumerable<T> items)
{
isInAddRange = true;
foreach (T item in items)
Add(item);
isInAddRange = false;
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add,
items.ToList());
base.OnCollectionChanged(e);
}
}
</code></pre>
|
Is there any disadvantage to returning this instead of void? <p>Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it).</p>
<p>So suppose you're in a situation where you want to update an object and then return its current value.
instead of saying </p>
<pre><code>myObj.Update();
var val = myObj.GetCurrentValue();
</code></pre>
<p>you will be able to combine the two lines to say</p>
<pre><code>var val = myObj.Update().GetCurrentValue();
</code></pre>
<p><hr /></p>
<p><strong>EDIT:</strong> I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands.</p>
<p>On a related note, what do you guys think of having the language include a new bit of syntactic sugar:</p>
<pre><code>var val = myObj.Update()<.GetCurrentValue();
</code></pre>
<p>This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update.</p>
<p>Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts?</p>
| <p>I think as a general policy, it simply doesn't make sense. Method chaining in this manner works with a properly defined interface but it's only appropriate if it makes semantic sense. </p>
<p>Your example is a prime one where it's not appropriate, because it makes no semantic sense.</p>
<p>Similarly, your syntactic sugar is unnecessary with a properly designed fluent interface.</p>
<p>Fluent interfaces or method chaining <b>can</b> work very well, but need to be designed carefully.</p>
|
What collaboration tools are effective for working with non-technical people? <p>For programmers working in corporate environments and outside of the start up world, there are a wide variety of non-technical people that are important stakeholders in the development process. These include other functions within the company such as marketing, finance and legal, for example, and also include customers and others outside the company.</p>
<p>The point of this question is not âcare and feedingâ of these groups, but simply what tools have been found to work to facilitate collaboration and necessary interaction? Iâm thinking along of the lines of IM versus wikis versus traditional email distribution lists, or the corporate sharepoint portal, but wonder what others have found to work.</p>
| <p><a href="http://www.basecamphq.com/" rel="nofollow">Basecamp</a> is a joy to use, and its primary focus is project management through collaboration.</p>
|
How do I get the current user's Local Settings folder path in C#? <p>I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?</p>
| <p>How about this, for example:</p>
<pre><code>String appData =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
</code></pre>
<p>I don't see an enum for just the Local Settings folder.</p>
<p><a href="http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx">http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx</a> has a list with examples.</p>
|
web page cache setexpires <p>Will the code below work if the clock on the server is ahead of the clock on the client?</p>
<pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
</code></pre>
<p>EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening.</p>
| <p><a href="http://stackoverflow.com/questions/49547/making-sure-a-webpage-is-not-cached-across-all-browsers" rel="nofollow">This question</a> covers making sure a webpage is not cached. It seems you have to set several properties to ensure a web page is not cached across all browsers.</p>
|
Any tool to migrate repo from Vault to Subversion? <p>Are there any <strong>tools</strong> to facilitate a migration from <a href="http://www.sourcegear.com/vault/index.html">Sourcegear's Vault</a> to <a href="http://subversion.tigris.org/">Subversion</a>?</p>
<p>I'd really prefer an existing tool or project (I'll buy!).</p>
<p><strong>Requirements:</strong></p>
<ol>
<li>One-time migration only</li>
<li>Full history with comments</li>
</ol>
<p><strong>Optional:</strong></p>
<ol>
<li>Some support for labels/branches/tags</li>
<li>Relatively speedy. It can take hours but not days.</li>
<li>Cost if available</li>
</ol>
<p>Bonus points if you can share personal experience related to this process.</p>
<p><hr /></p>
<p>One of the reasons I'd like to do this is because we have lots of projects spread between Vault and Subversion (we're finally away from sourcesafe). It'd be helpful in some situations to be able to consolidate a particular customer's repos to SVN.</p>
<p>Additionally, SVN is better supported among third party tools. For example, <a href="http://hudson.dev.java.net/">Hudson</a> and <a href="http://www.redmine.org/">Redmine</a>.</p>
<p>Again, though: we're not abandoning vault altogether.</p>
| <p>We are thinking about migrating from vault to git. I wrote vault2git converter that takes care of history and removes vault bindings from *.sln, *.csproj files.</p>
<p>Once you have git repo, there is git2svn.</p>
<p>I know it sounds like going rounds, but it might be faster than writing vault2svn from scratch.</p>
|
How do I check that a Windows QFE/patch has been installed from c#? <p>What's the best way in c# to determine is a given QFE/patch has been installed?</p>
| <p>Use WMI and inspect the <a href="http://msdn.microsoft.com/en-us/library/aa394391.aspx" rel="nofollow">Win32_QuickFixEngineering</a> enumeration.</p>
<p>From TechNet:</p>
<pre><code>strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuickFixes = objWMIService.ExecQuery _
("Select * from Win32_QuickFixEngineering")
For Each objQuickFix in colQuickFixes
Wscript.Echo "Computer: " & objQuickFix.CSName
Wscript.Echo "Description: " & objQuickFix.Description
Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID
Wscript.Echo "Installation Date: " & objQuickFix.InstallDate
Wscript.Echo "Installed By: " & objQuickFix.InstalledBy
Next
</code></pre>
<p><strong>The HotFixID is what you want to examine.</strong></p>
<p>Here's the output on my system:</p>
<pre>
Hot Fix ID: KB941569
Description: Security Update for Windows XP (KB941569)
Hot Fix ID: KB937143-IE7
Description: Security Update for Windows Internet Explorer 7 (KB937143)
Hot Fix ID: KB938127-IE7
Description: Security Update for Windows Internet Explorer 7 (KB938127)
Hot Fix ID: KB939653-IE7
Description: Security Update for Windows Internet Explorer 7 (KB939653)
Hot Fix ID: KB942615-IE7
Description: Security Update for Windows Internet Explorer 7 (KB942615)
Hot Fix ID: KB944533-IE7
Description: Security Update for Windows Internet Explorer 7 (KB944533)
Hot Fix ID: KB947864-IE7
Description: Hotfix for Windows Internet Explorer 7 (KB947864)
Hot Fix ID: KB950759-IE7
Description: Security Update for Windows Internet Explorer 7 (KB950759)
Hot Fix ID: KB953838-IE7
Description: Security Update for Windows Internet Explorer 7 (KB953838)
Hot Fix ID: MSCompPackV1
Description: Microsoft Compression Client Pack 1.0 for Windows XP
Hot Fix ID: KB873339
Description: Windows XP Hotfix - KB873339
Hot Fix ID: KB885835
Description: Windows XP Hotfix - KB885835
Hot Fix ID: KB885836
Description: Windows XP Hotfix - KB885836
Hot Fix ID: KB886185
Description: Windows XP Hotfix - KB886185
Hot Fix ID: KB887472
Description: Windows XP Hotfix - KB887472
Hot Fix ID: KB888302
Description: Windows XP Hotfix - KB888302
Hot Fix ID: KB890046
Description: Security Update for Windows XP (KB890046)
</pre>
|
Continue Considered Harmful? <p>Should developers avoid using <a href="http://msdn.microsoft.com/en-us/library/923ahwt1.aspx">continue</a> in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about <a href="http://stackoverflow.com/questions/46586/goto-still-considered-harmful">Goto</a>? </p>
| <p>I think there should be more use of continue!</p>
<p>Too often I come across code like:</p>
<pre><code>for (...)
{
if (!cond1)
{
if (!cond2)
{
... highly indented lines ...
}
}
}
</code></pre>
<p>instead of </p>
<pre><code>for (...)
{
if (cond1 || cond2)
{
continue;
}
...
}
</code></pre>
<p>Use it to make the code more readable!</p>
|
Best build process solution to manage build versions <p>I run a rather complex project with several independent applications. These use however a couple of shared components. So I have a source tree looking something like the below.</p>
<ul>
<li>My Project
<ul>
<li>Application A</li>
<li>Shared1</li>
<li>Shared2 </li>
<li>Application B </li>
<li>Application C</li>
</ul></li>
</ul>
<p>All applications have their own MSBuild script that builds the project and all the shared resources it needs. I also run these builds on a CruiseControl controlled continuous integration build server. </p>
<p>When the applications are deployed they are deployed on several servers to distribute load. This means that itâs <em>extremely</em> important to keep track of what build/revision is deployed on each of the different servers (we need to have the current version in the DLL version, for example â1.0.0.68â). </p>
<p>Itâs equally important to be able to recreate a revision/build that been built to be able to roll back if something didnât work out as intended (o yes, that happends ...). Today weâre using SourceSafe for source control but that possible to change if we could present good reasons for that (SS itâs actually working ok for us <em>so</em> far). </p>
<p>Another principle that we try to follow is that itâs only code that been build and tested by the integration server that we deploy further. </p>
<h2>"CrusieControl Build Labels" solution</h2>
<p>We had several ideas on solving the above. The first was to have the continuous integration server build and locally deploy the project and test it (it does that now). As you probably know a successful build in CruiseControl generates a build label and I guess we somehow could use that to set the DLL version of our executables (so build label 35 would create a DLL like â1.0.0.35â )? The idea was also to use this build label to label the <strong>complete</strong> source tree. Then we probably could check out by that label and recreate the build later on. </p>
<p>The reason for labeling the complete tree is to include not only the actual application code (thatâs in one place in the source tree) but also all the shared items (thatâs in different places in the tree). So a successful build of âApplication Aâ would label to whole tree with label âApplicationA35â for example. </p>
<p>There might however be an issue when trying to recreate this build and setting the DLL version before deploying as we then donât have access to the CruiseControl generated build label anymore. If all CrusieControl build labels were unique for all the projects we could use only the number for labeling but thatâs not the case (both application A and B could at the same time be on build 35) so we have to include the application name in the label. Hence SourceSafe label âApplication35â. <strong>How can I then recreate build 34 and set 1.0.0.34 to the DLL version numbers once we built build 35?</strong></p>
<h2>"Revision number" solution</h2>
<p>Someone told me that Subversion for example creates a revision number for the entire source tree on every check in â <strong>is this the case? Has SourceSafe something similar?</strong> If this is correct the idea is then to grab that revision number when getting latest and build on the CruiseControl server. The revision number could then be used to set the DLL version number (to for example â1.0.0.5678â). I guess we could then get this specific revision for the Subversion if needed and that then would include that application and all the shared items to be able to recreate a specific version from the past. <strong>Would that work and could this also be achived using SourceSafe?</strong></p>
<h2>Summarize</h2>
<p>So the two main requirements are:</p>
<ol>
<li>Be able to <strong>track build/revision number of the build and deployed DLL.</strong></li>
<li>Be able to <strong>rebuild a past revision/build, set the old build/revision number on the executables of that build</strong> (to comply with requirement 1).</li>
</ol>
<p><strong>So how would you solve this?</strong> What would be your preferred approach and <strong>how</strong> would you solve it (or do you have a totally different idea?)? **Pleased give detailed answers. **</p>
<p><em>Bonus question</em> What are the difference between a revision number and a build number and when would one really need both?</p>
| <p>Your scheme is sound and achievable in VSS (although I would suggest you consider an alternative, VSS is really an outdated product).</p>
<p>For your "CI" Build - you would do the Versioning take a look at <a href="http://msbuildtasks.tigris.org/" rel="nofollow">MSBuild Community Tasks Project</a> which has a "Version" tasks. Typically you will have a "Version.txt" in your source tree and the MSBuild task will increment the "Release" number while the developers control the Major.Minor.Release.Revision numbers (that's how a client of mine wanted it). You can use revision if you prefer.</p>
<p>You then would have a "FileUpdate" tasks to edit the AssemblyInfo.cs file with that version, and your EXE's and "DLL's" will have the desired version.</p>
<p>Finally the VSSLabel task will label all your files appropriately.</p>
<p>For your "Rebuild" Build - you would modify your "Get" to get files from that Label, obviously not execute the "Version" task (as you are SELECTING a version to build) and then the FileUpdate tasks would use that version number.</p>
<p>Bonus question:</p>
<p>These are all "how you want to use them" - I would use build number for, well the build number, that is what I'd increment. If you are using CI you'll have very many builds - the vast majority with no intention of ever deploying anywhere.</p>
<p>The major and minor are self evident - but revision I've always used for a "Hotfix" indicator. I intend to have a "1.3" release - which would in reality be a product with say 1.3.1234.0 version. While working on 1.4 - I find a bug - and need a hot fix as 1.3.2400.1. Then when 1.4 is ready - it would be say 1.4.3500.0</p>
|
Visual Studio 2008 / Web site problem <p>I am using VS 2008 with SP1 and the IE 8 beta 2. Whenever I start a new Web site or when I double-click an ASPX in the solution explorer, VS insists on attempting to the display the ASPX page in a free-standing IE browser instance. The address is the local file path to the ASPX it's trying to load and an error that says, "The XML page cannot be displayed" is shown. </p>
<p>Otherwise, things work work correctly (I just close the offending browser window. ASP.NET is registered with IIS and I have no other problems. I have tested my same configuration on other PCs and it works fine. Has anyone had this problem? </p>
<p>Thanks</p>
<p>rp</p>
| <p>Right click on the file, select 'Open With' and choose "Web Form Editor" and click "Set as Default".</p>
|
What's the bare minimum permission set for Sql Server 2005 services? <p>Best practices recommend not installing Sql Server to run as SYSTEM. What is the bare minumum you need to give the user account you create for it?</p>
| <p>By default, SQL Server 2005 installation will create a security group called SQLServer2005MSSQLUser$ComputerName$MSSQLSERVER with the correct rights. You just need to create a domain user or local user and make it a member of that group. </p>
<p>More details are available in the SQL Server Books Online: <a href="http://msdn.microsoft.com/en-us/library/ms143504(SQL.90).aspx#Review_NT_rights" rel="nofollow" title="Setting Up Windows Service Accounts">Reviewing Windows NT Rights and Privileges Granted for SQL Server Service Accounts</a></p>
|
How to attach debugger to step into native (C++) code from a managed (C#) wrapper? <p>I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?</p>
<p>This is the wrapper that I have which calls GetData() defined in a C++ file:</p>
<pre><code> [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl,
EntryPoint = "GetData", BestFitMapping = false)]
public static extern String GetData(String url);
</code></pre>
<p>The code is crashing and I want to investigate the root cause.</p>
<p>Thanks,
Nikhil</p>
| <p>Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs.</p>
<p>If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging.</p>
<p>The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.</p>
|
How do I increase the number of default rows per page? <p>Grails scaffolding defaults to 10 rows per page. I would like to increase that number without generating the views and changing the 10 in every file. Where do I change the default?</p>
| <p>You have to install scaffold templates with:</p>
<p>grails install-templates</p>
<p>Now, edit in src/templates/scaffolding Controller.groovy and increase the value params.max as you want</p>
|
What is the overhead cost associated with IoC containers like StructureMap? <p>After attending a recent Alt.NET group on IoC, I got to thinking about the tools available and how they might work. <code>StructureMap</code> in particular uses both attributes and bootstrapper concepts to map requests for <code>IThing</code> to <code>ConcreteThing</code>. Attributes automatically throw up flags for me that either reflection or IL injection is going on. Does anyone know exactly how this works (for <code>StructureMap</code> or other IoC tools) and what the associated overhead might be either at run-time or compile-time?</p>
| <p>I can't say much for other IoC toolkits but I use Spring.Net and have found that there is a one off initial performance penalty at startup. Once the container has been configured the application runs unaffected.</p>
|
Building Flex projects in ant/nant <p>We have a recurring problem at my company with build breaks in our Flex projects. The problem primarily occurs because the build that the developers do on their local machines is fundamentally different from the build that occurs on the build machine. The devs are building the projects using <code>FlexBuilder/eclipse</code> and the build machine is using the command line compilers. Inevitably, the <code>{projectname}-config.xml</code> and/or the batch file that runs the build get out of sync with the project files used by eclipse, so the the build succeeds on the dev's machine, but fails on the build machine.</p>
<p>We started down the path of writing a utility program to convert FlexBuilder's project files into a <code>{projectname}-config.xml</code> file, but it's a) undocumented and b) a horrible hack.</p>
<p>I've looked into the -dump-config switch to get the config files, but this has a couple of problems: 1) The generated config file has absolute paths which doesn't work in our environment (some developers use macs, some windows machines), and 2) only works right when run from the IDE, so can't be build into the build process.</p>
<p>Tomorrow, we are going to discuss a couple of options, neither of which I'm terribly fond of:</p>
<p><strong>a)</strong> Add a post check-in event to Subversion to remove these absolute references, or <br>
<strong>b)</strong> add a pre-build process that removes the absolute reference.</p>
<p>I can't believe that we are the first group of developers to run across this issue, but I can't find any good solutions on Google. How have other groups dealt with this problem?</p>
| <p>I found that one of the undocumented requirements for using ant with Flexbuilder was to have the variable FLEX_HOME set within your ant script. Typically within build.xml have the following:</p>
<pre><code><!â Module properties â>
<property environment=âenvâ/>
<property name=âbuild.dirâ value=âbuildâ/>
<property name=âswf.nameâ value=âMyProjectSwfâ/>
<property name=âroot.mxmlâ value=âMain.mxmlâ/>
<property name=âlocaleâ value=âen_USâ/>
<property name=âFLEX_HOMEâ value=â${env.FLEX_HOME}â/>
</code></pre>
<p>This may seem like a hassle but it is a far more reasonable approach to obtaining consistency across platforms and environments if you are using multiple platforms for your developers.</p>
<p>HTH</p>
|
OOP class design, Is this design inherently 'anti' OOP? <p>I remember back when MS released a forum sample application, the design of the application was like this:</p>
<p>/Classes/User.cs
/Classes/Post.cs
...
/Users.cs
/Posts.cs</p>
<p>So the classes folder had just the class i.e. properties and getters/setters.
The Users.cs, Post.cs, etc. have the actual methods that access the Data Access Layer, so Posts.cs might look like:</p>
<pre><code>public class Posts
{
public static Post GetPostByID(int postID)
{
SqlDataProvider dp = new SqlDataProvider();
return dp.GetPostByID(postID);
}
}
</code></pre>
<p>Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs).</p>
<p>Splitting things into 2 files makes it much more procedural doesn't it?
Isn't this breaking OOP rules since it is taking the behavior out of the class and putting it into another class definition?</p>
| <p>If every method is just a static call straight to the data source, then the "Posts" class is really a Factory. You could certainly put the static methods in "Posts" into the "Post" class (this is how CSLA works), but they are still factory methods.</p>
<p>I would say that a more modern and accurate name for the "Posts" class would be "PostFactory" (assuming that all it has is static methods).</p>
<p>I guess I wouldn't say this is a "procedural" approach necessarily -- it's just a misleading name, you would assume in the modern OO world that a "Posts" object would be stateful and provide methods to manipulate and manage a set of "Post" objects.</p>
|
Are CLR stored procedures preferred over TSQL stored procedures in SQL 2005+? <p>My current view is no, prefer Transact SQL stored procedures because they are a lighter weight and (possibly) higher performing option, while CLR procedures allow developers to get up to all sorts of mischief.</p>
<p>However recently I have needed to debug some very poorly written TSQL stored procs. As usual I found many of the problems due to the original developer developer having no real TSQL experience, they were ASP.NET / C# focused.</p>
<p>So, using CLR procedures would firstly provide a much more familiar toolset to this type of developer, and secondly, the debugging and testing facilities are more powerful (ie Visual Studio instead of SQL Management Studio). </p>
<p>I'd be very interested in hearing your experience as it's seems it is not a simple choice. </p>
| <p>There are places for both well-written, well-thought-out T-SQL and CLR. If some function is not called frequently and if it required extended procedures in SQL Server 2000, CLR may be an option. Also running things like calculation right next to the data may be appealing. But solving bad programmers by throwing in new technology sounds like a bad idea.</p>
|
Rendering Graphics in C# <p>Are there any other way to render graphics in C# beyond GDI+ and XNA? (For the development of a tile map editor)</p>
| <p><a href="http://cs-sdl.sourceforge.net/index.php/Main_Page" rel="nofollow">http://cs-sdl.sourceforge.net/index.php/Main_Page</a> is the solution I've come to love. If you need 3d on top of it, you can use Tao.OpenGL to render inside it. It's fast, industry standard (SDL, that is), and cross-platform.</p>
|
UnhandledException handler in a .Net Windows Service <p>Is it possible to use an UnhandledException Handler in a Windows Service?</p>
<p>Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesnât achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:</p>
<pre>
<code>
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Try
MyServiceComponent.Start()
Catch ex As Exception
'call into our exception handler
MyExceptionHandlingComponent.ManuallyHandleException (ex)
'zero is the default ExitCode for a successfull exit, so if we set it to non-zero
ExitCode = -1
'So, we use Environment.Exit, it seems to be the most appropriate thing to use
'we pass an exit code here as well, just in case.
System.Environment.Exit(-1)
End Try
End Sub
</code>
</pre>
<p>Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?</p>
| <p>Ok, Iâve done a little more research into this now.
When you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to.
These methods are invoked from within the base class so I did a little poking around with reflector.
OnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The vesion on my machine "System.ServiceProcess, Version=2.0.0.0" decompiles like this:</p>
<pre>
<code>
Private Sub ServiceQueuedMainCallback(ByVal state As Object)
Dim args As String() = DirectCast(state, String())
Try
Me.OnStart(args)
Me.WriteEventLogEntry(Res.GetString("StartSuccessful"))
Me.status.checkPoint = 0
Me.status.waitHint = 0
Me.status.currentState = 4
Catch exception As Exception
Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { exception.ToString }), EventLogEntryType.Error)
Me.status.currentState = 1
Catch obj1 As Object
Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { String.Empty }), EventLogEntryType.Error)
Me.status.currentState = 1
End Try
Me.startCompletedSignal.Set
End Sub
</code>
</pre>
<p>So because Me.OnStart(args) is called from within the Try portion of a Try Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try Catch block and therefore any exceptions that occur aren't technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine.
The other 3 entry points (OnStop, OnPause and OnContinue) are all called from the base class in a similar way.</p>
<p>So I âthinkâ that explains why my Exception Handling component canât catch UnhandledException on Start and Stop, but Iâm not sure if it explains why timers that are setup in OnStart canât cause an UnhandledException when they fire. </p>
|
Tools for manipulating PowerPoint files <p>Do you know managed tools for manipulating PowerPoint files?
The tool should be 100% managed code and offer the option to
handle .ppt and .pptx files.</p>
| <p>@<a href="#58318" rel="nofollow">Chris</a>: There won't be a chance that Office 2007 will be available to manipulate the files. So far the only solution which comes close to what I am looking for is <a href="http://www.aspose.com/categories/file-format-components/aspose.slides-for-.net-and-java/default.aspx" rel="nofollow">Aspose.Slides for .NET</a>. The support for .pptx files is "a work in progress" though.</p>
|
How to test a WPF user interface? <p>Using win forms with an <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a>/<a href="http://msdn.microsoft.com/en-us/magazine/cc188690.aspx">MVP</a> architecture, I would normally use a class to wrap a view to test the UI while using mocks for the model and controller/presenter. The wrapper class would make most everything in the UI an observable property for the test runner through properties and events.</p>
<p>Would this be a viable approach to testing a WPF app? Is there a better way? Are there any gotchas to watch out for?</p>
| <p>As for the testing itself, you're probably best off using the <a href="https://msdn.microsoft.com/library/ms747327.aspx">UI Automation</a> framework. Or if you want a more fluent and wpf/winforms/win32/swt-independent way of using the framework, you could download <a href="http://www.codeplex.com/white">White</a> from Codeplex (provided that you're in a position to use open source code in your environment).</p>
<p>For the gotchas; If you're trying to unit test your views, you will probably run in to some threading issues. For instance, if you're running NUnit the default testrunner will run in MTA (Multi-Threaded Appartment), while as WPF needs to run as STA (Single-threaded Appartment). <a href="http://miketwo.blogspot.com/2007/03/unit-testing-wpf-controls-with.html">Mike Two</a> has a real easy getting-started on unit testing WPF, but without considering the threading issue. Josh Smith has some thoughts on the threading issue in <a href="http://joshsmithonwpf.wordpress.com/2007/07/09/using-nunit-with-wpf/">this post</a>, and he also points to <a href="http://www.hedgate.net/articles/2007/01/08/instantiating-a-wpf-control-from-an-nunit-test/">this article</a> by Chris Hedgate. Chris uses a modified version of Peter Provost's <a href="http://www.peterprovost.org/blog/post/NUnit-and-Multithreaded-Tests-CrossThreadTestRunner.aspx">CrossThreadTestRunner</a> to wrap the MTA/STA issues in a bit more friendly way. </p>
|
Avoiding first chance exception messages when the exception is safely handled <p>The following bit of code catches the EOS Exception</p>
<pre><code>using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
</code></pre>
<p>So why do I still receive first-chance exceptions in my console? </p>
<blockquote>
<p>A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll</p>
</blockquote>
<p>Is there a way to hide these first chance exception messages?</p>
| <p>To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages".</p>
<p>However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.</p>
|
Using .NET, how can you find the mime type of a file based on the file signature not the extension <p>I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to <a href="http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java" rel="nofollow">this question</a> only in .Net.</p>
| <p>I did use urlmon.dll in the end. I thought there would be an easier way but this works. I include the code to help anyone else and allow me to find it again if I need it.</p>
<pre><code>using System.Runtime.InteropServices;
</code></pre>
<p>...</p>
<pre><code> [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static System.UInt32 FindMimeFromData(
System.UInt32 pBC,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
System.UInt32 cbSize,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
System.UInt32 dwMimeFlags,
out System.UInt32 ppwzMimeOut,
System.UInt32 dwReserverd
);
public static string getMimeFromFile(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException(filename + " not found");
byte[] buffer = new byte[256];
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
if (fs.Length >= 256)
fs.Read(buffer, 0, 256);
else
fs.Read(buffer, 0, (int)fs.Length);
}
try
{
System.UInt32 mimetype;
FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
System.IntPtr mimeTypePtr = new IntPtr(mimetype);
string mime = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
return mime;
}
catch (Exception e)
{
return "unknown/unknown";
}
}
</code></pre>
|
Version control of deliverables <p>We need to regularly synchronize many dozens of binary files (project executables and DLLs) between many developers at several different locations, so that every developer has an up to date environment to build and test at. Due to nature of the project, updates must be done often and on-demand (overnight updates are not sufficient). This is not pretty, but we are stuck with it for a time.</p>
<p>We settled on using a regular version (source) control system: put everything into it as binary files, get-latest before testing and check-in updated DLL after testing.</p>
<p>It works fine, but a version control client has a lot of features which don't make sense for us and people occasionally get confused.</p>
<p>Are there any tools better suited for the task? Or may be a completely different approach?</p>
<p><strong>Update:</strong> I need to clarify that it's not a tightly integrated project - more like extensible system with a heap of "plugins", including thrid-party ones. We need to make sure those modules-plugins works nicely with recent versions of each other and the core. Centralised build as was suggested was considered initially, but it's not an option.</p>
| <p>I'd probably take a look at rsync.</p>
<p>Just create a .CMD file that contains the call to rsync with all the correct parameters and let people call that. rsync is very smart in deciding what part of files need to be transferred, so it'll be very fast even when large files are involved.</p>
<p>What rsync doesn't do though is conflict resolution (or even detection), but in the scenario you described it's more like reading from a central place which is what rsync is designed to handle.</p>
|
How to resolve SQL query parameters mapping issues while using Oracle OLE DB provider? <p>When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:</p>
<blockquote>
<p>Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable.<br />
ADDITIONAL INFORMATION:<br />
Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle) </p>
</blockquote>
<p>I have tried following the suggestion here but don't quite understand what is required:<a href="http://microsoftdw.blogspot.com/2005/11/parameterized-queries-against-oracle.html">Parameterized queries against Oracle</a></p>
<p>Any ideas?</p>
| <p>To expand on the link given in the question:</p>
<ol>
<li>Create a package variable</li>
<li>Double click on the package variable name. (This allows you to access the properties of the variable)</li>
<li>Set the property 'EvaluateAsExpression' to true</li>
<li>Enter the query in the expression builder.</li>
<li>Set the OLE DB source query to SQL Command from Variable</li>
</ol>
<p>The expression builder can dynamically create expressions using variable to create 'parametised queries'.<br />
So the following 'normal' query:</p>
<pre><code>select * from book where book.BOOK_ID = ?
</code></pre>
<p>Can be written in the expression builder as:</p>
<pre><code>"select * from book where book.BOOK_ID = " + @[User::BookID]
</code></pre>
<p>You can then do null handling and data conversion using the expression builder.</p>
|
Default button size? <p>How do I create a button control (with <code>CreateWindow</code> of a <code>BUTTON</code> window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications?
I should of course take DPI into account and probably other settings.</p>
<blockquote>
<p><strong>Remark:</strong> Using <code>USE_CW_DEFAULT</code> for width and height results in a 0, 0 size button, so that's not a solution.</p>
</blockquote>
| <p>This is what MSDN has to say: <a href="http://msdn.microsoft.com/en-us/library/ms997619.aspx">Design Specifications and Guidelines - Visual Design: Layout</a>.</p>
<p>The default size of a button is 50x14 DLUs, which can be calculated to pixels using the examples shown for <a href="http://msdn.microsoft.com/en-us/library/ms645475(VS.85).aspx">GetDialogBaseUnits</a>.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms645502(VS.85).aspx">MapDialogRect</a> function seems to do the calculation for you.</p>
|
"Quoted-printable line longer than 76 chars" warning when sending HTML E-Mail <p>I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder).</p>
<p>When I test the e-mail, it gets eaten by my spam filter. One of the things that it's scoring badly on is because of the following problem:</p>
<pre>MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars</pre>
<p>I've been through the source of the e-mail, and I've broken each line longer than 76 characters into two lines with a CR+LF in between, but that hasn't fixed the problem.</p>
<p>Can anyone point me in the right direction?</p>
<p>Thanks!</p>
| <p>Quoted printable expands 8 bit characters to "={HEX-Code}", thus making the messages longer. Maybe you are just hitting this limit?</p>
<p>Have you tried to break the message at, say, 70 characters? That should provide space for a couple of characters per line.</p>
<p>Or you just encode the email with Base64 - all mail client can handle that.</p>
<p>Or you just set Content-Transfer-Encoding to 8bit and send the data unencoded. I know of no mail server unable to handle 8bit bytes these days.</p>
|
Windows CDROM Eject <p>Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher?
Open CD tray exists, but I can't seem to make it close especially under W2k. </p>
<p>I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.</p>
| <p>I kind of like to use DeviceIOControl as it gives me the possibility to eject any kind of removable drive (such as USB and flash-disks as well as CD trays). Da codez to properly eject a disk using DeviceIOControl is (just add proper error-handling):</p>
<pre><code>bool ejectDisk(TCHAR driveLetter)
{
TCHAR tmp[10];
_stprintf(tmp, _T("\\\\.\\%c:"), driveLetter);
HANDLE handle = CreateFile(tmp, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
DWORD bytes = 0;
DeviceIoControl(handle, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &bytes, 0);
DeviceIoControl(handle, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, &bytes, 0);
DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, 0, 0, 0, 0, &bytes, 0);
CloseHandle(handle);
return true;
}
</code></pre>
|
Open source PDF library for C/C++ application? <p>I want to be able to generate PDF ouput from my (native) C++ Windows application. Are there any free/open source libraries available to do this?</p>
<p>I looked at the answers to <a href="http://stackoverflow.com/questions/177/how-do-i-programmatically-create-a-pdf-in-my-net-application" rel="nofollow">this question</a>, but they mostly relate to .Net.</p>
| <p><a href="https://github.com/libharu/libharu" rel="nofollow">LibHaru</a></p>
<blockquote>
<p>Haru is a free, cross platform,
open-sourced software library for
generating PDF written in ANSI-C. It
can work as both a static-library (.a,
.lib) and a shared-library (.so,
.dll).</p>
</blockquote>
<p>Didn't try it myself, but maybe it can help you</p>
|
How do I get raw logs from Google Analytics? <p>Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA?</p>
| <p>No you can't get the raw logs, but there's nothing stopping you from getting the exact same data logged to your own web server logs. Have a look at the <a href="https://ssl.google-analytics.com/urchin.js">Urchin code</a> and borrow that, changing the following two lines to point to your web server instead.</p>
<pre><code>var _ugifpath2="http://www.google-analytics.com/__utm.gif";
if (_udl.protocol=="https:") _ugifpath2="https://ssl.google-analytics.com/__utm.gif";
</code></pre>
<p>You'll want to create a <code>__utm.gif</code> file so that they don't show up in the logs as 404s.</p>
<p>Obviously you'll need to parse the variables out of the hits into your web server logs. The log line in Apache looks something like this. You'll have lots of "fun" parsing out all the various stuff you want from that, but everything Google Analytics gets from the basic JavaScript tagging comes in like this.</p>
<pre><code>127.0.0.1 - - [02/Oct/2008:10:17:18 +1000] "GET /__utm.gif?utmwv=1.3&utmn=172543292&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r124&utmdt=My%20Web%20Page&utmhn=www.mydomain.com&utmhid=979599568&utmr=-&utmp=/urlgoeshere/&utmac=UA-1715941-2&utmcc=__utma%3D113887236.511203954.1220404968.1222846275.1222906638.33%3B%2B__utmz%3D113887236.1222393496.27.2.utmccn%3D(organic)%7Cutmcsr%3Dgoogle%7Cutmctr%3Dsapphire%2Btechnologies%2Bsite%253Arumble.net%7Cutmcmd%3Dorganic%3B%2B HTTP/1.0" 200 35 "http://www.mydomain.com/urlgoeshere/" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19"
</code></pre>
|
Converting SVG to PNG using C# <p>I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?</p>
| <p>You can call the command-line version of inkscape to do this:</p>
<p><a href="http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx">http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx</a></p>
<p>Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:</p>
<p><strong>Original Project</strong><br>
<a href="http://www.codeplex.com/svg">http://www.codeplex.com/svg</a></p>
<p><strong>Fork with fixes and more activity:</strong> (added 7/2013)<br>
<a href="https://github.com/vvvv/SVG">https://github.com/vvvv/SVG</a></p>
|
Access to Result sets from within Stored procedures Transact-SQL SQL Server <p>I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?</p>
<pre><code>CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = @orderId
select item, number_of_items, cost from order_line where order_id = @orderId
END
</code></pre>
<p>I need to be able to iterate through both result sets individually.</p>
<p>EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.</p>
<p>The result sets returned by the procedures are not the same data types or number of columns.</p>
| <p>The short answer is: you can't do it.</p>
<p>From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.</p>
<p>To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:</p>
<pre><code>INSERT INTO #Table (...columns...)
EXEC MySproc ...parameters...
</code></pre>
<p>You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.</p>
|
Enforce SSL in code in an ashx handler <p>I have a site, which contains several ashx handlers, on a couple of the handlers I want to reject non-SSL requests. Is there a way that I can do this in code?</p>
| <p>If you must do it programmatically, a way I've done it in the past is to inspect the url and look for "https" in it. Redirect if you don't see that. Request.IsSecureConnection should be the preferred method, however. You may have to add additional logic to handle a loopback address.</p>
|
SqlServer Express slow performance <p>I am stress testing a .NET web application. I did this for 2 reasons: I wanted to see what performance was like under real world conditions and also to make sure we hadn't missed any problems during testing. We had 30 concurrent users in the application using it as they would during the normal course of their jobs. Most users had multiple windows of the application open.</p>
<ul>
<li>10 Users: Not bad</li>
<li>20 Users: Slowing down </li>
<li>30 Users: Very, very slow but no timeouts</li>
</ul>
<p>It was loaded on the production server. It is a virtual server with a 2.66G Hz Xeon processor and 2 GB of RAM. We are using Win2K3 SP2. We have .NET 1.1 and 2.0 loaded and are using SQLExpress SP1.</p>
<p>We rechecked the indexes on all of the tables afterword and they were all as they should be.</p>
<p>How can we improve our application's performance?</p>
| <ol>
<li><p>You may be running into concurrency issues, depending on how your application runs. Try performing your reads with the "nolock" keyword. </p></li>
<li><p>Try adding in table aliases for your columns (and avoid the use of SELECT *), this helps out MSSQL, as it doesn't have to "guess" which table the columns come from. </p></li>
<li><p>If you aren't already, move to SPROCs, this allows MSSQL to index your data better for a given query's normal result set.</p></li>
<li><p>Try following the execution plan of your SPROCS to ensure they are using the indexes you think they are.</p></li>
<li><p>Run a trace against your database to see what the incoming requests look like. You may notice a particular SPROC is being run over and over: generally a good sign to cache the responses on the client if possible. (lookup lists, etc.)</p></li>
</ol>
|
VS 2005 Installer Project Version Number <p>I am getting this error now that I hit version number 1.256.0:
Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####'</p>
<p>The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com:
The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (<a href="http://msdn.microsoft.com/en-us/library/d3ywkte8" rel="nofollow">http://msdn.microsoft.com/en-us/library/d3ywkte8</a>(VS.80).aspx)</p>
<p>Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above.</p>
<p>Does anyone have any ideas on why this would be failing now?</p>
| <p>The link you reference says " This page is specific to Microsoft Visual Studio 2008/.NET Framework 3.5", but you're talking about vs2005.</p>
<p>My guess: a 0-based range of 256 numbers ends at 255, therefore trying to use 256 exceeds that and perhaps they changed it for VS2008</p>
<p>Edit: I looked again and see where that link can be switched to talk about VS2005, and gives the same answer. I'm still sticking to my 0-255 theory though. Wouldn't be the first time this week I came across something incorrect in MSDN docs.</p>
|
What do I need to know to globalize an asp.net application? <p>I'm writing an asp.net application that will need to be localized to several regions other than North America. What do I need to do to prepare for this globalization? What are your top 1 to 2 resources for learning how to write a world ready application.</p>
| <p>A couple of things that I've learned:</p>
<ul>
<li><p>Absolutely and brutally minimize the number of images you have that contain text. Doing so will make your life a billion percent easier since you won't have to get a new set of images for every friggin' language.</p></li>
<li><p>Be very wary of css positioning that relies on things always remaining the same size. If those things contain text, they will <strong>not</strong> remain the same size, and you will then need to go back and fix your designs.</p></li>
<li><p>If you use character types in your sql tables, make sure that any of those that might receive international input are unicode (nchar, nvarchar, ntext). For that matter, I would just standardize on using the unicode versions.</p></li>
<li><p>If you're building SQL queries dynamically, make sure that you include the N prefix before any quoted text if there's any chance that text might be unicode. If you end up putting garbage in a SQL table, check to see if that's there.</p></li>
<li><p>Make sure that all your web pages definitively state that they are in a unicode format. See Joel's article, mentioned above.</p></li>
<li><p>You're going to be using resource files a lot for this project. That's good - ASP.NET 2.0 has great support for such. You'll want to look into the App_LocalResources and App_GlobalResources folder as well as GetLocalResourceObject, GetGlobalResourceObject, and the concept of meta:resourceKey. Chapter 30 of <a href="http://rads.stackoverflow.com/amzn/click/0470041781">Professional ASP.NET 2.0</a> has some great content regarding that. The 3.5 version of the book may well have good content there as well, but I don't own it.</p></li>
<li><p>Think about fonts. Many of the standard fonts you might want to use aren't unicode capable. I've always had luck with Arial Unicode MS, MS Gothic, MS Mincho. I'm not sure about how cross-platform these are, though. Also, note that not all fonts support all of the Unicode character definition. Again, test, test, test.</p></li>
<li><p>Start thinking now about how you're going to get translations into this system. Go talk to whoever is your translation vendor about how they want data passed back and forth for translation. Think about the fact that, through your local resource files, you will likely be repeating some commonly used strings through the system. Do you normalize those into global resource files, or do you have some sort of database layer where only one copy of each text used is generated. In our recent project, we used resource files which were generated from a database table that contained all the translations and the original, english version of the resource files. </p></li>
<li><p>Test. Generally speaking I will test in German, Polish, and an Asian language (Japanese, Chinese, Korean). German and Polish are wordy and nearly guaranteed to stretch text areas, Asian languages use an entirely different set of characters which tests your unicode support.</p></li>
</ul>
|
How do I disable validation in Web Data Administrator? <p>I'm trying to run some queries to get rid of XSS in our database using Web Data Administrator but I keep running into this Potentially Dangerous Request crap.</p>
<p>How do I disable validation of the query in Web Data Administrator?</p>
| <p>Go into the install directory of web data admin, usually:</p>
<p><code>C:\Program Files\Microsoft SQL Server Tools\Microsoft SQL Web Data Administrator</code></p>
<p>Then in the "Web" folder open the file "QueryDatabase.aspx" and edit the following line:</p>
<p><code><%@ Page language="c#" Codebehind="QueryDatabase.aspx.cs" AutoEventWireup="false" Inherits="SqlWebAdmin.query" %></code></p>
<p>Add <code>ValidateRequest="false"</code> to the end of it like so:</p>
<p><code><%@ Page language="c#" Codebehind="QueryDatabase.aspx.cs" AutoEventWireup="false" Inherits="SqlWebAdmin.query" ValidateRequest="false" %></code></p>
<p><strong>NOTE</strong>: THIS IS POTENTIALLY DANGEROUS!! Be Careful!</p>
|
How Do I Load an Assembly and All of its Dependencies at Runtime in C# for Reflection? <p>I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.</p>
<p>What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.</p>
<p>As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.</p>
<p>What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:</p>
<pre><code>String FilePath = Path.GetDirectoryName(FileName);
System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName);
</code></pre>
<p>That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:</p>
<pre><code>AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies();
</code></pre>
<p>That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.</p>
<p>So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.</p>
<p>I know that tools like Reflector do this, I just can't find the syntax for getting at it. </p>
| <p>Couple of options here:</p>
<ol>
<li>Attach to <code>AppDomain.AssemblyResolve</code> and do another <code>LoadFile</code> based on the requested assembly.</li>
<li>Spin up another <code>AppDomain</code> with the directory as its base and load the assemblies in that <code>AppDomain</code>.</li>
</ol>
<p>I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see <code>Assembly.ReflectionOnlyLoad</code>).</p>
|
What is the best way to rollout web applications? <p>I'm trying to create a standard way of rolling out web applications for our company. Currently we do it with zip files, vbscript/javascript, and manual some steps. </p>
<p>For thick client installs we generate MSI installers using Wise/Wix. We don't create installers currently for websites as in general they are just xcopy deploy. However we have some config files that need to be changed, verify that certain handlers are registered in IIS... The list goes on.</p>
<p>Do most people use MSI installers for web applications as well, or some other tool/scripting language?</p>
| <p>I recently spent a few days working on automating deployments at my company. </p>
<p>We use a combination of CruiseControl, NAnt, MSBuild to generate a release version of the app. Then a separate script uses MSDeploy and XCopy to backup the live site and transfer the new files over. </p>
<p>Our solution is briefly described in an answer to this question <a href="http://stackoverflow.com/questions/45783/automate-deployment-for-web-applications" rel="nofollow">http://stackoverflow.com/questions/45783/automate-deployment-for-web-applications</a></p>
|
Programmatically change combobox <p>I need to update a <code>combobox</code> with a new value so it changes the reflected text in it. The cleanest way to do this is after the <code>combobox</code>has been initialised and with a message.</p>
<p>So I am trying to craft a <code>postmessage</code> to the hwnd that contains the <code>combobox</code>.</p>
<p>So if I want to send a message to it, changing the currently selected item to the nth item, what would the <code>postmessage</code> look like?</p>
<p>I am guessing that it would involve <code>ON_CBN_SELCHANGE</code>, but I can't get it to work right.</p>
| <p>You want <a href="http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx" rel="nofollow">ComboBox_SetCurSel</a>:</p>
<pre><code>ComboBox_SetCurSel(hWndCombo, n);
</code></pre>
<p>or if it's an MFC CComboBox control you can probably do:</p>
<pre><code>m_combo.SetCurSel(2);
</code></pre>
<p>I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends <em>back to you</em> when the selection is changed.</p>
<p>Finally, you might want to add the c++ tag to this question.</p>
|
Subsets and Splits