text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How should you go about learning ASP.NET after life as a ColdFusion developer? As someone who has spent around 10 years programming web applications with Adobe's ColdFusion, I have decided to add ASP.NET as a string to my bow.
For someone who has spent so long with CF and the underlying Java, ASP.NET seems a little alien to me. How should I go about getting up to speed with ASP.NET so that I can be truly dangerous with it? Do I need to know C# at any great amount of detail?
I want to be in a position where I can build basic web apps fairly quickly so I can learn more doing the tricky stuff.
A: I'm only maybe six months down the same path, but here are some thoughts from my experience so far:
The C# language shouldn't give you much problem if you have very much experience with Java at all (or even CFScript). As a reference, though, when I was starting, I found csharp-station a good primer for language basics. It won't help you much as far as the ASP.NET side goes; but it is good for syntax. More you'll be familiarizing yourself with the .NET libraries. The IDE actually can be an enormous help here.
Here are the three biggest differences I found making the transition:
*
*ASP.NET Server Controls - In ColdFusion, you really have pretty
direct control over the HTML; you
work very closely with the page.
This isn't so much the case in
ASP.NET. The server controls are
meant to relieve you of a lot of the
tedium, but at a cost of maybe some
direct control. As a CF programmer,
I'm very particular about what gets
actually output to the browser; and
at first ASP.NET frustrated me
because it spits out a lot of extra
code. Still, the controls are
really powerful, and it pays to
familiarize yourself with them.
Form and validation controls,
especially, save you from a lot of
the tedium in CF of handling post
back and validation. W3Schools
actually has a decent list of web
server controls.
*The page model - ColdFusion is pretty agnostic in terms of page
flow. ASP.NET is very much geared
towards using post backs, and is
very event driven. If you're not
using a framework with CF (e.g.
Model Glue), this may be foreign to
you. .NET takes care of handling a
lot of the post back behavior for
you. Also, not to say that
ColdFusion can't be object and
function driven by good use of
CFC's, but ASP.NET really tries to
push you down the OO path compared
to CF in my experience.
*Database access - Using ASP.NET really made me appreciate how
powerful cfquery really is. The
csharp-station site also has a good
tutorial on working with the native
.NET db tools. I haven't worked on
enough projects yet to start looking
around for DB access extensions; I'm
pretty sure Jeff recommended
something that they used for
building this site, so you might
check that out. Otherwise, I really
suggest you familiarize yourself
with the DataSet object. It's
somewhat similar to a query object
in CF, and lets you run query of
queries, etc... Looping over
queries in CF is very common, but it
doesn't happen nearly as much in
ASP.NET because of data binding.
A: Microsoft has a video called ASP.NET for ColdFusion developers you may be interested in.
Edit, here's another
A: ADO.NET is a core concept, and I would really recommend taking a course in it. Having a qualified instructor explain exactly what the differences are between a DataSet, DataReader (and so forth -- there are a lot of different data access object types) is invaluable. Not to mention you'll better understand the appropriate time and place to use each; and you can ask questions and get immediate answers in a classroom setting.
I took an ADO.NET class (one night a week, about 8 weeks) at my local university for around $400. Even if my company hadn't paid for it, I would have been happy to, and I can highly recommend anyone trying to learn .NET do the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I "Add Existing Item" an entire directory structure in Visual Studio? I have a free standing set of files not affiliated with any C# project at all that reside in a complicated nested directory structure.
I want to add them in that format to a different directory in an ASP.NET web application I am working on; while retaining the same structure. So, I copied the folder into the target location of my project and I tried to “add existing item” only to lose the previous folder hierarchy.
Usually I have re-created the directories by hand, copied across on a one-to-one basis, and then added existing items. There are simply too many directories/items in this case.
So how do you add existing directories and files in Visual Studio 2008?
A: In Solution Explorer:
*
*Click Show All Files (second icon from the left at the top of Solution Explorer).
*Locate the folder you want to add.
*Right-click and select "Include in Project"
I use this to install add-ons like HTML editors and third-party file browsers.
A: Drag the files / folders from Windows Explorer into the Solution Explorer. It will add them all. Note this doesn't work if Visual Studio is in Administrator Mode, because Windows Explorer is a User Mode process.
A: You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."
A: Enable "Show All Files" for the specific project (you might need to hit "Refresh" to see them)**.
The folders/files that are not part of your project appear slightly "lighter" in the project tree.
Right click the folders/files you want to add and click "Include In Project". It will recursively add folders/files to the project.
** These buttons are located on the mini Solution Explorer toolbar.
** Make sure you are NOT in debug mode.
A: This is what I do:
*
*Right click on solution -> Add -> Existing Website...
*Choose the folder where your website is. Just the root folder of the site.
Then everything will be added on your solution from folders to files, and files inside those folders.
A: At last, Visual Studio 2017 allows the user to import an entire directory with a single click. Visual Studio 2017 has a new functionality "Open Folder" that allows opening the entire folder, even without the need to save it as solution. The source code can be imported using the following methods.
*
*Menu File → Open → *Folder (Ctrl + Shift + O)
*devenv.exe <source folder>
It even supports building and debugging CMake projects.
Bring your C++ codebase to Visual Studio with “Open Folder”
A: There is now an open-source extension in the Marketplace that seems to do what the OP was asking for:
Folder To Solution Folder
If it doesn't do exactly what you want, the code is available, so you can modify it to suit your scenario.
HTH
A: I just want to point out that two of the solutions offered previously,
*
*Drag and drop from Windows Explorer
*Show All Files and then include in project.
do not do what the question asked for:
Include in project while preserving the directory structure.
At least not in my case (C++/CLI project Visual Studio 2013 on Windows 7).
In Visual Studio, once you are back in the normal view (not Show All Files), the files you added are all listed at the top level of the project.
Yes, on disk they still reside where they were, but in Solution Explorer they are loose.
I did not find a way around it except recreating the directory structure in Solution Explorer and then doing Add Existing Items at the right location.
A: A neat trick I discovered is that if you go to "Add existing...", you can drag the folder from the open dialog to your solution.
I have my Visual Studio to open in Admin Mode automatically, so this was a good workaround for me as I didn't want to have to undo that just to get this to work.
A: I didn't immediately understand this based upon these descriptions but here is what I finally stumbled on:
*
*Turn on "Show All Files" - there is an icon on the Solution Explorer toolbar
*Using Windows Explorer (not solution explorer), move your files into the directory structure where you want them to reside
*Click "Refresh" also on the Solution Explorer toolbar
*The files that you've moved should be visible "ghosted" in the Solution Explorer tree structure where you've placed them
*Right click on your ghosted files or folders and click "Include in Project". All the contents of a folder will be included
A: Below is the icon for the 'Show All Files', just for easy reference.
A:
Click above in the red circle. Your folder will appear in Solution Explorer.
Right click on your folder -> Include in project.
A: You can change your project XML to add existing subfolders and structures automatically into your project like "node_modules" from NPM:
This is for older MSBuild / Visual Studio versions
<ItemGroup>
<Item Include="$([System.IO.Directory]::GetFiles("$(MSBuildProjectDirectory)\node_modules","*",SearchOption.AllDirectories))"></Item>
</ItemGroup>
For the current MSBuild / Visual Studio versions:
Just put it in the nodes of the xml:
<Project>
</Project>
In this case just change $(MSBuildProjectDirectory)\node_modules to your folder name.
A: What worked for me was to drag the folder into Visual Studio, then right click the folder and select "Open Folder in File Explorer". Then select all and drag them into the folder in Visual Studio.
A: In Windows 7 you could do the following:
Right click on your project and select "Add->Existing Item". In the dialog which appears, browse to the root of the directory you want to add. In the upper right corner you have a search box. Type *.cs or *.cpp, whatever the type of files you want to add. After the search finishes, select all files, click Add and wait for a while...
A: The cleanest way that I've found to do this is to create a new Class Library project in the target folder, and redirect all of its build output elsewhere. It still leaves a .csproj file sitting in that folder, but it does let you see it in Visual Studio and pick which files to include in your project.
A: It has been a while since this was originally posted, but here is an alternative answer.
If you only care to be able to look at the physical files from inside visual studio and do not necessarily require to see them in the solution explorer default view, then click on the switch view button and choose the folder view and any physical directory/directories that are under your solution root folder will appear here even if they do not appear in the solution explorer default view.
If however, you want to add a folder tree that isn't too large as a virtual solution directory/directories to match your existing tree structure, do that and and then "add the existing" physical files to the virtual directory/directories. If the physical directory exists in your solution directory it will not copy the files - it will link directly to the physical files but they will appear as part of the solution virtual directories.
A: It's annoying that Visual Studio doesn't support this natively, but CMake could generate the Visual Studio project as a work around.
Other than that, just use Qt Creator. It can then export a Visual Studio project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "788"
} |
Q: Visual Studio 2008 / Web site problem 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.
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?
Thanks
rp
A: Right click on the file, select 'Open With' and choose "Web Form Editor" and click "Set as Default".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I override onbeforeunload for a particular element? I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.
Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.
The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?
A: Let me guess: the help "icon" is actually a link with a javascript: url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.
<!-- clicking this link will do nothing. No onbeforeunload handler triggered.
Nothing.
And you could put something in before the return false bit...
...and the onunload handler would still not get called... -->
<a href="http://www.google.com/" onclick="return false;">blah1</a>
<!-- this should also do nothing, but IE will trigger the onbeforeunload
handler -->
<a href="javascript:void(0)">blah2</a>
A: EDIT: My "workaround" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.
OK so while I was writing the question, I came up with a workaround which will work for now.
I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.
Probably not a flawless workaround but it will work for now.
A: on the internet you will find many people suggesting you use something like
window.onbeforeunload = null
but this does not work for me in IE6. reading up in the MSDN docs for the event object i found a reference to the event.cancelBubble property, which i thought was the solution. but thanks to Orso who pointed out that setting "event.cancelBubble=true" is useless, the way to get rid of the confirm prompt is to exclude the return statement altogether, i chose to use a boolean variable as a flag to decide whether to return something or not. in the example below i add the javascript code programattically in the code behind:
Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", @" <script> window.onbeforeunload = confirmExit; function confirmExit() { if(postback == false) return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons.""; } </script>");
then the help button contains the following aspx markup:
OnClientClick="postback=true;return true;
this sets the 'postback' variable to true, which gets picked up in the confirmExit() function, having the effect of cancelling the event.
hope you find this useful. it is tested and works in IE6 and FF 1.5.0.2.
A: I have a method that is a bit clunky but it will work in most instances.
Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.
<html>
<head>
<script language="Javascript" type="text/javascript">
window.onbeforeunload = exitCheck;
window.onunload = onCloseDoSomething;
function onCloseDoSomething()
{
alert("This is executed at unload");
}
function exitCheck(evt)
{
return "Any string here."}
</script>
</head>
<frameset rows="100%">
<FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx">
</frameset>
<body>
</body>
</html>
Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.
If the outer frame is refreshed or actually closed the events will fire.
Like i said, not full-proof but will get round the firing of the event on every click or postback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What's the bare minimum permission set for Sql Server 2005 services? 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?
A: 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.
More details are available in the SQL Server Books Online: Reviewing Windows NT Rights and Privileges Granted for SQL Server Service Accounts
A: Typically I create a Domain User with only the specific rights on the network which I will require the server to have (i.e. to write to the network backup drive), I then add the account to local power users or local administrators depending on what needs to be done on the machine, however this isn't required. I've installed SQL a number of times using a standard user as a Service Account but you need to ensure that the user has access to write to the resources as listed at https://web.archive.org/web/20081223155956/http://support.microsoft.com/kb/283811 . Its probably not as defined an answer as you wanted but I'm only a developer (not a professional DBA / System Engineer).
Mauro
PS dont downmark me for saying "only a developer" :P
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to convert decimal to hexadecimal in JavaScript How do you convert decimal values to their hexadecimal equivalent in JavaScript?
A: If you want to convert a number to a hexadecimal representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:
function toHexString(n) {
if(n < 0) {
n = 0xFFFFFFFF + n + 1;
}
return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}
A: AFAIK comment 57807 is wrong and should be something like:
var hex = Number(d).toString(16);
instead of
var hex = parseInt(d, 16);
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
A: function toHex(d) {
return ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}
A: And if the number is negative?
Here is my version.
function hexdec (hex_string) {
hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);
hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);
return parseInt(hex_string, 10);
}
A: As the accepted answer states, the easiest way to convert from decimal to hexadecimal is var hex = dec.toString(16). However, you may prefer to add a string conversion, as it ensures that string representations like "12".toString(16) work correctly.
// Avoids a hard-to-track-down bug by returning `c` instead of `12`
(+"12").toString(16);
To reverse the process you may also use the solution below, as it is even shorter.
var dec = +("0x" + hex);
It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec.
A: For completeness, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift >>> operator. For instance:
> (-1).toString(16)
"-1"
> ((-2)>>>0).toString(16)
"fffffffe"
There is however one limitation: JavaScript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's complement.
A: I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).
Simple .toString(16) didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note that symbols defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):
var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
var result = '';
while (symbols--) {
result = hex[num & 0xF] + result;
num >>= 4;
}
return result;
}
It performs faster than .toString(16) on 1-2 byte numbers and slower on larger numbers (when symbols >= 6), but still should outperform methods that encode negative values properly.
A: Converting hex color numbers to hex color strings:
A simple solution with toString and ES6 padStart for converting hex color numbers to hex color strings.
const string = `#${color.toString(16).padStart(6, '0')}`;
For example:
0x000000 will become #000000
0xFFFFFF will become #FFFFFF
Check this example in a fiddle here
A: With padding:
function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
A: Convert a number to a hexadecimal string with:
hexString = yourNumber.toString(16);
And reverse the process with:
yourNumber = parseInt(hexString, 16);
A: How to convert decimal to hexadecimal in JavaScript
I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.
function DecToHex(decimal) { // Data (decimal)
length = -1; // Base string length
string = ''; // Source 'string'
characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array
do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift
string += characters[decimal & 0xF]; // Mask byte, get that character
++length; // Increment to length of string
} while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0
decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'
do
decimal += string[length];
while (length--); // Flip string forwards, with the prefixed '0x'
return (decimal); // return (hexadecimal);
}
/* Original: */
D = 3678; // Data (decimal)
C = 0xF; // Check
A = D; // Accumulate
B = -1; // Base string length
S = ''; // Source 'string'
H = '0x'; // Destination 'string'
do {
++B;
A& = C;
switch(A) {
case 0xA: A='A'
break;
case 0xB: A='B'
break;
case 0xC: A='C'
break;
case 0xD: A='D'
break;
case 0xE: A='E'
break;
case 0xF: A='F'
break;
A = (A);
}
S += A;
D >>>= 0x04;
A = D;
} while(D)
do
H += S[B];
while (B--)
S = B = A = C = D; // Zero out variables
alert(H); // H: holds hexadecimal equivalent
A: You can do something like this in ECMAScript 6:
const toHex = num => (num).toString(16).toUpperCase();
A: If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code
const hugeNumber = "9007199254740991873839" // Make sure its in String
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);
console.log(hexOfHugeNumber)
A: The accepted answer did not take into account single digit returned hexadecimal codes. This is easily adjusted by:
function numHex(s)
{
var a = s.toString(16);
if ((a.length % 2) > 0) {
a = "0" + a;
}
return a;
}
and
function strHex(s)
{
var a = "";
for (var i=0; i<s.length; i++) {
a = a + numHex(s.charCodeAt(i));
}
return a;
}
I believe the above answers have been posted numerous times by others in one form or another. I wrap these in a toHex() function like so:
function toHex(s)
{
var re = new RegExp(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/);
if (re.test(s)) {
return '#' + strHex( s.toString());
}
else {
return 'A' + strHex(s);
}
}
Note that the numeric regular expression came from 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency.
Update: After testing this thing several times I found an error (double quotes in the RegExp), so I fixed that. HOWEVER! After quite a bit of testing and having read the post by almaz - I realized I could not get negative numbers to work.
Further - I did some reading up on this and since all JavaScript numbers are stored as 64 bit words no matter what - I tried modifying the numHex code to get the 64 bit word. But it turns out you can not do that. If you put "3.14159265" AS A NUMBER into a variable - all you will be able to get is the "3", because the fractional portion is only accessible by multiplying the number by ten(IE:10.0) repeatedly. Or to put that another way - the hexadecimal value of 0xF causes the floating point value to be translated into an integer before it is ANDed which removes everything behind the period. Rather than taking the value as a whole (i.e.: 3.14159265) and ANDing the floating point value against the 0xF value.
So the best thing to do, in this case, is to convert the 3.14159265 into a string and then just convert the string. Because of the above, it also makes it easy to convert negative numbers because the minus sign just becomes 0x26 on the front of the value.
So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. This means to everyone that on the server side you will need to unhex the incoming string and then to determine the incoming information is numeric. You can do that easily by just adding a "#" to the front of numbers and "A" to the front of a character string coming back. See the toHex() function.
Have fun!
After another year and a lot of thinking, I decided that the "toHex" function (and I also have a "fromHex" function) really needed to be revamped. The whole question was "How can I do this more efficiently?" I decided that a to/from hexadecimal function should not care if something is a fractional part but at the same time it should ensure that fractional parts are included in the string.
So then the question became, "How do you know you are working with a hexadecimal string?". The answer is simple. Use the standard pre-string information that is already recognized around the world.
In other words - use "0x". So now my toHex function looks to see if that is already there and if it is - it just returns the string that was sent to it. Otherwise, it converts the string, number, whatever. Here is the revised toHex function:
/////////////////////////////////////////////////////////////////////////////
// toHex(). Convert an ASCII string to hexadecimal.
/////////////////////////////////////////////////////////////////////////////
toHex(s)
{
if (s.substr(0,2).toLowerCase() == "0x") {
return s;
}
var l = "0123456789ABCDEF";
var o = "";
if (typeof s != "string") {
s = s.toString();
}
for (var i=0; i<s.length; i++) {
var c = s.charCodeAt(i);
o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);
}
return "0x" + o;
}
This is a very fast function that takes into account single digits, floating point numbers, and even checks to see if the person is sending a hex value over to be hexed again. It only uses four function calls and only two of those are in the loop. To un-hex the values you use:
/////////////////////////////////////////////////////////////////////////////
// fromHex(). Convert a hex string to ASCII text.
/////////////////////////////////////////////////////////////////////////////
fromHex(s)
{
var start = 0;
var o = "";
if (s.substr(0,2).toLowerCase() == "0x") {
start = 2;
}
if (typeof s != "string") {
s = s.toString();
}
for (var i=start; i<s.length; i+=2) {
var c = s.substr(i, 2);
o = o + String.fromCharCode(parseInt(c, 16));
}
return o;
}
Like the toHex() function, the fromHex() function first looks for the "0x" and then it translates the incoming information into a string if it isn't already a string. I don't know how it wouldn't be a string - but just in case - I check. The function then goes through, grabbing two characters and translating those in to ASCII characters. If you want it to translate Unicode, you will need to change the loop to going by four(4) characters at a time. But then you also need to ensure that the string is NOT divisible by four. If it is - then it is a standard hexadecimal string. (Remember the string has "0x" on the front of it.)
A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.
<?php
echo <<<EOD
<html>
<head><title>Test</title>
<script>
var a = -3.14159265;
alert( "A = " + a );
var b = a.toString();
alert( "B = " + b );
</script>
</head>
<body>
</body>
</html>
EOD;
?>
Because of how JavaScript works in respect to the toString() function, all of those problems can be eliminated which before were causing problems. Now all strings and numbers can be converted easily. Further, such things as objects will cause an error to be generated by JavaScript itself. I believe this is about as good as it gets. The only improvement left is for W3C to just include a toHex() and fromHex() function in JavaScript.
A: Without the loop:
function decimalToHex(d) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}
// Or "#000000".substr(0, 7 - hex.length) + hex;
// Or whatever
// *Thanks to MSDN
Also isn't it better not to use loop tests that have to be evaluated?
For example, instead of:
for (var i = 0; i < hex.length; i++){}
have
for (var i = 0, var j = hex.length; i < j; i++){}
A: Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the # elsewhere for HTML/CSS):
function rgb2hex(r,g,b) {
if (g !== undefined)
return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
else
return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}
A: To sum it all up;
function toHex(i, pad) {
if (typeof(pad) === 'undefined' || pad === null) {
pad = 2;
}
var strToParse = i.toString(16);
while (strToParse.length < pad) {
strToParse = "0" + strToParse;
}
var finalVal = parseInt(strToParse, 16);
if ( finalVal < 0 ) {
finalVal = 0xFFFFFFFF + finalVal + 1;
}
return finalVal;
}
However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.
A: I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:
((0xFF + number +1) & 0x0FF).toString(16);
You can use this instruction to any number bytes, only you add FF in respective places. For example, to two bytes:
((0xFFFF + number +1) & 0x0FFFF).toString(16);
If you want cast an array integer to string hexadecimal:
s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}
A: In case you're looking to convert to a 'full' JavaScript or CSS representation, you can use something like:
numToHex = function(num) {
var r=((0xff0000&num)>>16).toString(16),
g=((0x00ff00&num)>>8).toString(16),
b=(0x0000ff&num).toString(16);
if (r.length==1) { r = '0'+r; }
if (g.length==1) { g = '0'+g; }
if (b.length==1) { b = '0'+b; }
return '0x'+r+g+b; // ('#' instead of'0x' for CSS)
};
var dec = 5974678;
console.log( numToHex(dec) ); // 0x5b2a96
A: This is based on Prestaul and Tod's solutions. However, this is a generalisation that accounts for varying size of a variable (e.g. Parsing signed value from a microcontroller serial log).
function decimalToPaddedHexString(number, bitsize)
{
let byteCount = Math.ceil(bitsize/8);
let maxBinValue = Math.pow(2, bitsize)-1;
/* In node.js this function fails for bitsize above 32bits */
if (bitsize > 32)
throw "number above maximum value";
/* Conversion to unsigned form based on */
if (number < 0)
number = maxBinValue + number + 1;
return "0x"+(number >>> 0).toString(16).toUpperCase().padStart(byteCount*2, '0');
}
Test script:
for (let n = 0 ; n < 64 ; n++ ) {
let s=decimalToPaddedHexString(-1, n);
console.log(`decimalToPaddedHexString(-1,${(n+"").padStart(2)}) = ${s.padStart(10)} = ${("0b"+parseInt(s).toString(2)).padStart(34)}`);
}
Test results:
decimalToPaddedHexString(-1, 0) = 0x0 = 0b0
decimalToPaddedHexString(-1, 1) = 0x01 = 0b1
decimalToPaddedHexString(-1, 2) = 0x03 = 0b11
decimalToPaddedHexString(-1, 3) = 0x07 = 0b111
decimalToPaddedHexString(-1, 4) = 0x0F = 0b1111
decimalToPaddedHexString(-1, 5) = 0x1F = 0b11111
decimalToPaddedHexString(-1, 6) = 0x3F = 0b111111
decimalToPaddedHexString(-1, 7) = 0x7F = 0b1111111
decimalToPaddedHexString(-1, 8) = 0xFF = 0b11111111
decimalToPaddedHexString(-1, 9) = 0x01FF = 0b111111111
decimalToPaddedHexString(-1,10) = 0x03FF = 0b1111111111
decimalToPaddedHexString(-1,11) = 0x07FF = 0b11111111111
decimalToPaddedHexString(-1,12) = 0x0FFF = 0b111111111111
decimalToPaddedHexString(-1,13) = 0x1FFF = 0b1111111111111
decimalToPaddedHexString(-1,14) = 0x3FFF = 0b11111111111111
decimalToPaddedHexString(-1,15) = 0x7FFF = 0b111111111111111
decimalToPaddedHexString(-1,16) = 0xFFFF = 0b1111111111111111
decimalToPaddedHexString(-1,17) = 0x01FFFF = 0b11111111111111111
decimalToPaddedHexString(-1,18) = 0x03FFFF = 0b111111111111111111
decimalToPaddedHexString(-1,19) = 0x07FFFF = 0b1111111111111111111
decimalToPaddedHexString(-1,20) = 0x0FFFFF = 0b11111111111111111111
decimalToPaddedHexString(-1,21) = 0x1FFFFF = 0b111111111111111111111
decimalToPaddedHexString(-1,22) = 0x3FFFFF = 0b1111111111111111111111
decimalToPaddedHexString(-1,23) = 0x7FFFFF = 0b11111111111111111111111
decimalToPaddedHexString(-1,24) = 0xFFFFFF = 0b111111111111111111111111
decimalToPaddedHexString(-1,25) = 0x01FFFFFF = 0b1111111111111111111111111
decimalToPaddedHexString(-1,26) = 0x03FFFFFF = 0b11111111111111111111111111
decimalToPaddedHexString(-1,27) = 0x07FFFFFF = 0b111111111111111111111111111
decimalToPaddedHexString(-1,28) = 0x0FFFFFFF = 0b1111111111111111111111111111
decimalToPaddedHexString(-1,29) = 0x1FFFFFFF = 0b11111111111111111111111111111
decimalToPaddedHexString(-1,30) = 0x3FFFFFFF = 0b111111111111111111111111111111
decimalToPaddedHexString(-1,31) = 0x7FFFFFFF = 0b1111111111111111111111111111111
decimalToPaddedHexString(-1,32) = 0xFFFFFFFF = 0b11111111111111111111111111111111
Thrown: 'number above maximum value'
Note: Not too sure why it fails above 32 bitsize
A: *
*rgb(255, 255, 255) // returns FFFFFF
*rgb(255, 255, 300) // returns FFFFFF
*rgb(0,0,0) // returns 000000
*rgb(148, 0, 211) // returns 9400D3
function rgb(...values){
return values.reduce((acc, cur) => {
let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
return acc + (val.length === 1 ? '0'+val : val);
}, '').toUpperCase();
}
A: If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.
function decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16).toUpperCase();
}
console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));
A: Constrained/padded to a set number of characters:
function decimalToHex(decimal, chars) {
return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}
A: For anyone interested, here's a JSFiddle comparing most of the answers given to this question.
And here's the method I ended up going with:
function decToHex(dec) {
return (dec + Math.pow(16, 6)).toString(16).substr(-6)
}
Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a color data type, you might instead prefer to extract the RGB values from the decimal and use rgb().
For example (JSFiddle):
let c = 4210330 // your color in decimal format
let rgb = [(c & 0xff0000) >> 16, (c & 0x00ff00) >> 8, (c & 0x0000ff)]
// Vanilla JS:
document.getElementById('some-element').style.color = 'rgb(' + rgb + ')'
// jQuery:
$('#some-element').css('color', 'rgb(' + rgb + ')')
This sets #some-element's CSS color property to rgb(64, 62, 154).
A: var number = 3200;
var hexString = number.toString(16);
The 16 is the radix and there are 16 values in a hexadecimal number :-)
A: The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
A: function dec2hex(i)
{
var result = "0000";
if (i >= 0 && i <= 15) { result = "000" + i.toString(16); }
else if (i >= 16 && i <= 255) { result = "00" + i.toString(16); }
else if (i >= 256 && i <= 4095) { result = "0" + i.toString(16); }
else if (i >= 4096 && i <= 65535) { result = i.toString(16); }
return result
}
A: Arbitrary precision
This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm
*
*split number to sign (s), integer part (i) and fractional part (f) e.g for -123.75 we have s=true, i=123, f=75
*integer part to hex:
*
*if i='0' stop
*get modulo: m=i%16 (in arbitrary precision)
*convert m to hex digit and put to result string
*for next step calc integer part i=i/16 (in arbitrary precision)
*fractional part
*
*count fractional digits n
*multiply k=f*16 (in arbitrary precision)
*split k to right part with n digits and put them to f, and left part with rest of digits and put them to d
*convert d to hex and add to result.
*finish when number of result fractional digits is enough
// @param decStr - string with non-negative integer
// @param divisor - positive integer
function dec2HexArbitrary(decStr, fracDigits=0) {
// Helper: divide arbitrary precision number by js number
// @param decStr - string with non-negative integer
// @param divisor - positive integer
function arbDivision(decStr, divisor)
{
// algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/
let ans='';
let idx = 0;
let temp = +decStr[idx];
while (temp < divisor) temp = temp * 10 + +decStr[++idx];
while (decStr.length > idx) {
ans += (temp / divisor)|0 ;
temp = (temp % divisor) * 10 + +decStr[++idx];
}
if (ans.length == 0) return "0";
return ans;
}
// Helper: calc module of arbitrary precision number
// @param decStr - string with non-negative integer
// @param mod - positive integer
function arbMod(decStr, mod) {
// algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/
let res = 0;
for (let i = 0; i < decStr.length; i++)
res = (res * 10 + +decStr[i]) % mod;
return res;
}
// Helper: multiply arbitrary precision integer by js number
// @param decStr - string with non-negative integer
// @param mult - positive integer
function arbMultiply(decStr, mult) {
let r='';
let m=0;
for (let i = decStr.length-1; i >=0 ; i--) {
let n = m+mult*(+decStr[i]);
r= (i ? n%10 : n) + r
m= n/10|0;
}
return r;
}
// dec2hex algorithm starts here
let h= '0123456789abcdef'; // hex 'alphabet'
let m= decStr.match(/-?(.*?)\.(.*)?/) || decStr.match(/-?(.*)/); // separate sign,integer,ractional
let i= m[1].replace(/^0+/,'').replace(/^$/,'0'); // integer part (without sign and leading zeros)
let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0'); // fractional part (without last zeros)
let s= decStr[0]=='-'; // sign
let r=''; // result
if(i=='0') r='0';
while(i!='0') { // integer part
r=h[arbMod(i,16)]+r;
i=arbDivision(i,16);
}
if(fracDigits) r+=".";
let n = f.length;
for(let j=0; j<fracDigits; j++) { // frac part
let k= arbMultiply(f,16);
f = k.slice(-n);
let d= k.slice(0,k.length-n);
r+= d.length ? h[+d] : '0';
}
return (s?'-':'')+r;
}
// -----------
// TESTS
// -----------
let tests = [
["0",2],
["000",2],
["123",0],
["-123",0],
["00.000",2],
["255.75",5],
["-255.75",5],
["127.999",32],
];
console.log('Input Standard Abitrary');
tests.forEach(t=> {
let nonArb = (+t[0]).toString(16).padEnd(17,' ');
let arb = dec2HexArbitrary(t[0],t[1]);
console.log(t[0].padEnd(10,' '), nonArb, arb);
});
// Long Example (40 digits after dot)
let example = "123456789012345678901234567890.09876543210987654321"
console.log(`\nLong Example:`);
console.log('dec:',example);
console.log('hex: ',dec2HexArbitrary(example,40));
A: The problem basically how many padding zeros to expect.
If you expect string 01 and 11 from Number 1 and 17. it's better to use Buffer as a bridge, with which number is turn into bytes, and then the hex is just an output format of it. And the bytes organization is well controlled by Buffer functions, like writeUInt32BE, writeInt16LE, etc.
import { Buffer } from 'buffer';
function toHex(n) { // 4byte
const buff = Buffer.alloc(4);
buff.writeInt32BE(n);
return buff.toString('hex');
}
> toHex(1)
'00000001'
> toHex(17)
'00000011'
> toHex(-1)
'ffffffff'
> toHex(-1212)
'fffffb44'
> toHex(1212)
'000004bc'
A: Here's my solution:
hex = function(number) {
return '0x' + Math.abs(number).toString(16);
}
The question says: "How to convert decimal to hexadecimal in JavaScript". While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish hexadecimal codes from programmatic identifiers and other numbers (1234 could be hexadecimal, decimal, or even octal).
Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.
The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.
The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1862"
} |
Q: NHibernate.MappingException: No persister for: XYZ Now, before you say it: I did Google and my hbm.xml file is an Embedded Resource.
Here is the code I am calling:
ISession session = GetCurrentSession();
var returnObject = session.Get<T>(Id);
Here is my mapping file for the class:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true">
<id name="ID" column="ID" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="NumberOfBuckets" column="NumberOfBuckets" />
<property name="SearchCriteriaOne" column="SearchCriteriaOne" />
<bag name="_Businesses" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Business, HQData"/>
</bag>
<bag name="_Buckets" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Bucket, HQData"/>
</bag>
</class>
</hibernate-mapping>
Has anyone run to this issue before?
Here is the full error message:
MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
Update, here's what the solution for my scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
A: Something obvious, yet quite useful for someone new to NHibernate.
All XML Mapping files should be treated as Embedded Resources rather than the default Content. This option is set by editing the Build Action attribute in the file's properties.
XML files are then embedded into the assembly, and parsed at project startup during NHibernate's configuration phase.
A: My issue was that I forgot to put the .hbm in the name of the mapping xml. Also make sure you make it an embedded resource!
A: I got this off of here:
In my case the mapping class was not public. In other words, instead of:
public class UserMap : ClassMap<user> // note the public!
I just had:
class UserMap : ClassMap<user>
A: I had similar problem, and I solved it as folows:
I working on MS SQL 2008, but in the NH configuration I had bad dialect:
NHibernate.Dialect.MsSql2005Dialect
if I correct it to:
NHibernate.Dialect.MsSql2008Dialect
then everything's working fine without a exception "No persister for: ..."
David.
A: Spending about 4 hours on googling and stackoverflowing, trying all of stuff around there, i've found my error:
My mapping file was called .nbm.xml instead of .hbm.xml. That was insane.
A: I had the same problem because I was adding the wrong assembly in Configuration.AddAssembly() method.
A: I was also adding the wrong assembly during initialization. The class I'm persisting is in assembly #1, and my .hbm.xml file is embedded in assembly #2. I changed cfg.AddAssembly(... to add assembly #2 (instead of assembly #1) and everything worked. Thanks!
A: To add to Amol's answer, don't make the mistake of specifying the Interface class type. Make sure you specify the implementation class. (Ie. don't use IDomainObjectType). Not that I made this mistake... :)
A: Should it be name="Id"? Typos are a likely cause.
Next would be to try it out with a non-generic test to make sure you're passing in the proper type parameter.
Can you post the entire error message?
A: This error occurs because of invalid mapping configuration. You should check where you set .Mappings for your session factory. Basically search for ".Mappings(" in your project and make sure you specified correct entity class in below line.
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())
A: Sounds like you forgot to add a mapping assembly to the session factory configuration..
If you're using app.config...
.
.
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Project.DomainModel"/> <!-- Here -->
</session-factory>
.
.
A: If running tests on the repository from a seperate assembly, then make sure your Hibernate.cfg.xml is set to output always in the bin directory of said assembly. This wasn't happening for us and we got the above error in certain circumstances.
Disclaimer: This might be a slightly esoteric bit of advice, given that it's a direct result of how we structure our repository integration test assemblies (i.e. we have a symbolic link from each test assembly to a single Hibernate.xfg.xml)
A: Don't forget to specify mapping information in .config file
e.g.
where MyApp.Data is assembly that contains your mappings
A: Had a similar problem when find an object by id...
All i did was to use the fully qualified name in the class name. That is
Before it was :
find("Class",id)
Object so it became like this :
find("assemblyName.Class",id)
A: Make sure you have called the CreateCriteria(typeof(DomainObjectType)) method on Session for the domain object which you intent to fetch from DB.
A: I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.
My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.
OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
OBJEKTE res = await _objRepo.UpdateAsync(t);
If inparam would go straight to UpdateAsync() it cannot find a matching persistor.
It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:
t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}
inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}
The fun thing though is that the source of inparam is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.
A: I my case I fetched an entity without await:
var company = _unitOfWork.Session.GetAsync<Company>(id);
and then I tried to delete it:
await _unitOfWork.Session.DeleteAsync(company);
I could not decipher the error message that I'm deleting a Task<Company> instead of Company:
MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]
A: You would think that after 14 years, all possible answers to this question have been written down. It seems like that is not the case.
In the application I'm currently working on, there are several ISessionFactory instances, each one for a different database.
If you're taking the wrong one to create your ISession, of course it will have no idea of the class you're trying to persist, which was the error in my case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "136"
} |
Q: Remove all classes that begin with a certain string I have a div with id="a" that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:
$("#a").removeClass("bg*");
A: Using 2nd signature of $.fn.removeClass :
// Considering:
var $el = $('<div class=" foo-1 a b foo-2 c foo"/>');
function makeRemoveClassHandler(regex) {
return function (index, classes) {
return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
}
}
$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class="a b c foo"></div>]
A: With jQuery, the actual DOM element is at index zero, this should work
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
A: For modern browsers:
let element = $('#a')[0];
let cls = 'bg';
element.classList.remove.apply(element.classList, Array.from(element.classList).filter(v=>v.startsWith(cls)));
A: I've written a simple jQuery plugin - alterClass, that does wildcard class removal.
Will optionally add classes too.
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
A: An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:
function removeclasses(controlIndex,classPrefix){
var classes = $("#"+controlIndex).attr("class").split(" ");
$.each(classes,function(index) {
if(classes[index].indexOf(classPrefix)==0) {
$("#"+controlIndex).removeClass(classes[index]);
}
});
}
Now this function can be called from anywhere, onclick of button or from code:
removeclasses("a","bg");
A: http://www.mail-archive.com/[email protected]/msg03998.html says:
...and .removeClass() would remove all classes...
It works for me ;)
cheers
A: I was looking for solution for exactly the same problem. To remove all classes starting with prefix "fontid_" After reading this article I wrote a small plugin which I'm using now.
(function ($) {
$.fn.removePrefixedClasses = function (prefix) {
var classNames = $(this).attr('class').split(' '),
className,
newClassNames = [],
i;
//loop class names
for(i = 0; i < classNames.length; i++) {
className = classNames[i];
// if prefix not found at the beggining of class name
if(className.indexOf(prefix) !== 0) {
newClassNames.push(className);
continue;
}
}
// write new list excluding filtered classNames
$(this).attr('class', newClassNames.join(' '));
};
}(fQuery));
Usage:
$('#elementId').removePrefixedClasses('prefix-of-classes_');
A: In one line ...
Removes all classes that match a regular expression someRegExp
$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});
A: You don't need any jQuery specific code to handle this. Just use a RegExp to replace them:
$("#a").className = $("#a").className.replace(/\bbg.*?\b/g, '');
You can modify this to support any prefix but the faster method is above as the RegExp will be compiled only once:
function removeClassByPrefix(el, prefix) {
var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
el.className = el.className.replace(regx, '');
return el;
}
A: A regex splitting on word boundary \b isn't the best solution for this:
var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ").trim();
or as a jQuery mixin:
$.fn.removeClassPrefix = function(prefix) {
this.each(function(i, el) {
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = $.trim(classes.join(" "));
});
return this;
};
2018 ES6 Update:
const prefix = "prefix";
const classes = el.className.split(" ").filter(c => !c.startsWith(prefix));
el.className = classes.join(" ").trim();
A: I know it's an old question, but I found out new solution and want to know if it has disadvantages?
$('#a')[0].className = $('#a')[0].className
.replace(/(^|\s)bg.*?(\s|$)/g, ' ')
.replace(/\s\s+/g, ' ')
.replace(/(^\s|\s$)/g, '');
A: Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use
document.getElementById("a").className
instead of
$("#a").className
A: I also use hyphen'-' and digits for class name. So my version include '\d-'
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.\d-*?\b/g, '');
A: (function($)
{
return this.each(function()
{
var classes = $(this).attr('class');
if(!classes || !regex) return false;
var classArray = [];
classes = classes.split(' ');
for(var i=0, len=classes.length; i<len; i++) if(!classes[i].match(regex)) classArray.push(classes[i]);
$(this).attr('class', classArray.join(' '));
});
})(jQuery);
A: The top answer converted to jQuery for those wanting a jQuery only solution:
const prefix = 'prefix'
const classes = el.attr('class').split(' ').filter(c => !c.startsWith(prefix))
el.attr('class', classes.join(' ').trim())
A: $("#element").removeAttr("class").addClass("yourClass");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "114"
} |
Q: Crash Instantiating System.Xml.Serialization.XmlSerializer in C# We're seeing a crash when instantiating an instance of the System.Xml.Serialization.XmlSerializer class in a C# library. The crash occurs in the constructor, when it tries to add a duplicate key to a dictionary. I've included a stack trace below.
This crash is only occurring on one machine, and repairing our installation of .NET 3.5 didn't help. Has anyone else seen any similar issues?
System.ArgumentException was unhandled
Message="Item has already been added. Key in dictionary: 'mainbuild' Key being added: 'mainbuild'"
Source="mscorlib"
StackTrace:
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at System.Collections.Hashtable.Add(Object key, Object value)
at System.Collections.Specialized.StringDictionary.Add(String key, String value)
at System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
at System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
at Microsoft.CSharp.CSharpCodeGenerator.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs)
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)
at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)
at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at OurTools.Tools.Common.XML.DataAccess`1.DeserializeFromXml(String strFilePath) in c:\AutomatedBuild\projects\1.0\OurTools.Tools.Common\OurTools.Tools.Common\XML\DataAcess.cs:line 100
at OurTools.Tools.Common.ProjectFileManager.GetProjectInfoModel() in c:\AutomatedBuild\projects\1.0\OurTools.Tools.Common\OurTools.Tools.Common\ProjectFileManager.cs:line 252
at OurTools.Tools.Common.ProjectFileManager.GetAvailableCultures() in c:\AutomatedBuild\projects\1.0\OurTools.Tools.Common\OurTools.Tools.Common\ProjectFileManager.cs:line 299
at OurAppLib.GeneratorOptions.DefaultCultures() in c:\AutomatedBuild\projects\1.0\OurApp\OurAppLib\GeneratorOptions.cs:line 192
at OurAppLib.GeneratorOptions.ReadCulturesFromArgs(List`1 arglist, String& errormsg) in c:\AutomatedBuild\projects\1.0\OurApp\OurAppLib\GeneratorOptions.cs:line 358
at OurAppLib.GeneratorOptions.ReadFromArgs(String[] args, String& errormsg) in c:\AutomatedBuild\projects\1.0\OurApp\OurAppLib\GeneratorOptions.cs:line 261
at OurApp.Program.Main(String[] args) in c:\AutomatedBuild\projects\1.0\OurApp\OurApp\Program.cs:line 76`print("code sample");`
A: Found this link, which explains the issue:
http://social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/4476f044-bab9-492d-bb94-4e0960bd2d26
A quick summary: When serializing, the object makes a dictionary out of all environment variables, but appears to run a ToLower() on all entries. So, if you have two environment variables that are the same except for casing, you'll get a crash.
This is only going to be a problem when running from inside a system like cygwin which enforces case sensitivity for variables. In our case, we're using make.
There are a couple solutions, but they all revolve around making sure that your environment doesn't have any duplicated variables when your c# app runs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to attach debugger to step into native (C++) code from a managed (C#) wrapper? 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?
This is the wrapper that I have which calls GetData() defined in a C++ file:
[DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl,
EntryPoint = "GetData", BestFitMapping = false)]
public static extern String GetData(String url);
The code is crashing and I want to investigate the root cause.
Thanks,
Nikhil
A: in addition to Lou's advise for starting the debugger, you can select which debug engines are used when attaching to an existing process by clicking on 'Select...' in the 'attach to process' dialog and choosing both 'managed code' and 'native code'.
Debugging in this way is called mixed mode debugging. See this blog post for some tips.
I believe this isn't supported for 64 bit processes ... though would love to be wrong on that point.
A: 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.
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.
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.
A: To anyone using WinDbg:
1>Setup symbols
Look at these commands. (Help: in console .hh < command> )
.sympath
.sympath+
.symfix
2>Set up source path
.srcpath
3>Load SOS extention to debug managed / mixed mode programs.
(Make sure you have extention path setup correctly)
Add Microsoft.NET\Framework\v2.0.50727 for x86 using-
.extpath
Set a breakpoint for the clr to load.
sxe ld:mscorwks
(F5 / g)
(Wait for ModLoad BP on mscorwks.dll)
Make sure you dont have a duplicate sos extention already loaded. See:
.chain
Now we're ready to load the sos extention. :)
.loadby sos mscorwks
4> Reload all the symbols..
.reload
Now you're all set :)
(YMMV)
A: Mixed debugging is not supported in 64bit mode (as of Visual Studio 2008).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: BackgroundWorker thread in ASP.NET Is it possible to use BackGroundWorker thread in ASP.NET 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time?
Scenario
*
*The browser requests a page, say SendEmails.aspx
*SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails.
*The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent.
*Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete.
My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.
A: You shouldn't do any threading from ASP.NET pages. Any thread that is long running is in danger of being killed when the worker process recycles. You can't predict when this will happen. Any long-running processes need to be handled by a windows service. You can kick off these processes by dropping a message in MSMQ, for example.
A: ThreadPool.QueueUserWorkItem(delegateThatSendsEmails)
or on System.Net.Mail.SmtpServer use the SendAsync method.
You want to put the email sending code on another thread, because then it will return the the user immediately, and will just process, no matter how long it takes.
A: It is possible. Once you start a new thread asynchronously from page, page request will proceed and send the page back to the user. The async thread will continue to run on the server but will no longer have access to the session.
If you have to show task progress, consider some Ajax techniques.
A: What you need to use for this scenario is Asynchronous Pages, a feature that was added in ASP.NET 2.0
Asynchronous pages offer a neat
solution to the problems caused by
I/O-bound requests. Page processing
begins on a thread-pool thread, but
that thread is returned to the thread
pool once an asynchronous I/O
operation begins in response to a
signal from ASP.NET. When the
operation completes, ASP.NET grabs
another thread from the thread pool
and finishes processing the request.
Scalability increases because
thread-pool threads are used more
efficiently. Threads that would
otherwise be stuck waiting for I/O to
complete can now be used to service
other requests. The direct
beneficiaries are requests that don't
perform lengthy I/O operations and can
therefore get in and out of the
pipeline quickly. Long waits to get
into the pipeline have a
disproportionately negative impact on
the performance of such requests.
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
A: If you want using multitheading in your ASP page, you might using simple threading model like this:
{
System.Threading.Thread _thread = new Thread(new ThreadStart(Activity_DoWork));
_thred.Start();
}
Activity_DoWork()
{
/*Do some things...
}
This method is correct working with ASP pages. The ASP page with BackgroundWorker will not start while BackgroundWorker will finish.
A: 5 years later, but problems the same… If you want to perform fire-and-forget operations from your application and forget about all difficulties related to background job processing in ASP.NET applications, you can use http://hangfire.io.
*
*It does not loose your jobs on recycling process, because it uses persistent storage to keep information about background jobs.
*It automatically retries your background jobs that were aborted or failed due to transient exception (SMTP Server connectivity errors).
*It allows you to easily debug background jobs through the integrated web interface.
*It is very easy to install/configure/use HangFire.
There is also tutorial Sending Mail in Background with ASP.NET MVC for using HangFire with Postal.
A: If you don't want to use the AJAX libraries, or the e-mail processing is REALLY long and would timeout a standard AJAX request, you can use an AsynchronousPostBack method that was the "old hack" in the .net 1.1 days.
Essentially what you do is have your submit button begin the e-mail processing in an asynchronous state, while the user is taken to an intermediate page. The benefit to this is that you can have your intermediate page refresh as much as needed, without worrying about hitting the standard timeouts.
When your background process is complete, it will put a little "done" flag in the database/application variable/whatever. When your intermediate page does a refresh of itself, it detects this flag and automatically redirects the user to the "done" page.
Again, AJAX makes all of this moot, but if for some reason you have a very intensive or timely process that has to be done over the web, this solution will work for you. I found a nice tutorial on it here and there are plenty more out there.
I had to use a process like this when we were working on a "web check-in" type application that was interfacing with a third party application and their import API was hideously slow.
EDIT: GAH! Curse you Guzlar and your god-like typing abilities 8^D.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: .NET ListView row padding There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around?
A: A workaround is to use an ImageList that is as tall as you want the items to be. Just fill a blank image with the background color. You can even make the image 1 wide so as to not take much space horizontally.
A: I know this post is fairly old, however, if you never found the best option, I've got a blog post that may help, it involves utilizing LVM_SETICONSPACING.
According to my blog,
Initially, you'll need to add:
using System.Runtime.InteropServices;
Next, you'll need to import the DLL, so that you can utilize SendMessage, to modify the ListView parameters.
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
Once that is complete, create the following two functions:
public int MakeLong(short lowPart, short highPart)
{
return (int)(((ushort)lowPart) | (uint)(highPart << 16));
}
public void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding)
{
const int LVM_FIRST = 0x1000;
const int LVM_SETICONSPACING = LVM_FIRST + 53;
SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding));
}
Then to use the function, just pass in your ListView, and set the values. In the example, 64 pixels is the image width, and 32 pixels is my horizontal spacing/padding, 100 pixels is the image height, and 16 pixels is my vertical spacing/padding, and both parameters require a minimum of 4 pixels.
ListViewItem_SetSpacing(this.listView1, 64 + 32, 100 + 16);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I close a browser window without receiving the "Do you want to close this window" prompt? How can I close a browser window without receiving the Do you want to close this window prompt?
The prompt occurs when I use the window.close(); function.
A: window.open('', '_self', ''); window.close();
This works for me.
A: For security reasons, a window can only be closed in JavaScript if it was opened by JavaScript. In order to close the window, you must open a new window with _self as the target, which will overwrite your current window, and then close that one (which you can do since it was opened via JavaScript).
window.open('', '_self', '');
window.close();
A:
window.open('', '_self', '').close();
Sorry a bit late here, but i found the solution, at least for my case. Tested on Safari 11.0.3 and Google Chrome 64.0.3282.167
A: Scripts are not allowed to close a window that a user opened. This is considered a security risk. Though it isn't in any standard, all browser vendors follow this (Mozilla docs). If this happens in some browsers, it's a security bug that (ideally) gets patched very quickly.
None of the hacks in the answers on this question work any longer, and if someone would come up with another dirty hack, eventually it will stop working as well.
I suggest you don't waste energy fighting this and embrace the method that the browser so helpfully gives you — ask the user before you seemingly crash their page.
A: From here:
<a href="javascript:window.opener='x';window.close();">Close</a>
You need to set window.opener to something, otherwise it complains.
A: Because of the security enhancements in IE, you can't close a window unless it is opened by a script. So the way around this will be to let the browser think that this page is opened using a script, and then to close the window. Below is the implementation.
Try this, it works like a charm!
javascript close current window without prompt IE
<script type="text/javascript">
function closeWP() {
var Browser = navigator.appName;
var indexB = Browser.indexOf('Explorer');
if (indexB > 0) {
var indexV = navigator.userAgent.indexOf('MSIE') + 5;
var Version = navigator.userAgent.substring(indexV, indexV + 1);
if (Version >= 7) {
window.open('', '_self', '');
window.close();
}
else if (Version == 6) {
window.opener = null;
window.close();
}
else {
window.opener = '';
window.close();
}
}
else {
window.close();
}
}
</script>
javascript close current window without prompt IE
A: My friend... there is a way but "hack" does not begin to describe it. You have to basically exploit a bug in IE 6 & 7.
Works every time!
Instead of calling window.close(), redirect to another page.
Opening Page:
alert("No whammies!");
window.open("closer.htm", '_self');
Redirect to another page. This fools IE into letting you close the browser on this page.
Closing Page:
<script type="text/javascript">
window.close();
</script>
Awesome huh?!
A: Here is Javascript function which I use to close browser without Prompt or Warning, it can also be called from Flash.
It should be in html file.
function closeWindows() {
var browserName = navigator.appName;
var browserVer = parseInt(navigator.appVersion);
//alert(browserName + " : "+browserVer);
//document.getElementById("flashContent").innerHTML = "<br> <font face='Arial' color='blue' size='2'><b> You have been logged out of the Game. Please Close Your Browser Window.</b></font>";
if(browserName == "Microsoft Internet Explorer"){
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
if (ie7)
{
//This method is required to close a window without any prompt for IE7 & greater versions.
window.open('','_parent','');
window.close();
}
else
{
//This method is required to close a window without any prompt for IE6
this.focus();
self.opener = this;
self.close();
}
}else{
//For NON-IE Browsers except Firefox which doesnt support Auto Close
try{
this.focus();
self.opener = this;
self.close();
}
catch(e){
}
try{
window.open('','_self','');
window.close();
}
catch(e){
}
}
}
A: window.opener=window;
window.close();
A: Create a JavaScript function
<script type="text/javascript">
function closeme() {
window.open('', '_self', '');
window.close();
}
</script>
Now write this code and call the above JavaScript function
<a href="Help.aspx" target="_blank" onclick="closeme();">Help</a>
Or simply:
<a href="" onclick="closeme();">close</a>
A: This will work :
<script type="text/javascript">
function closeWindowNoPrompt()
{
window.open('', '_parent', '');
window.close();
}
</script>
A: This works in Chrome 26, Internet Explorer 9 and Safari 5.1.7 (without the use of a helper page, ala Nick's answer):
<script type="text/javascript">
window.open('javascript:window.open("", "_self", "");window.close();', '_self');
</script>
The nested window.open is to make IE not display the Do you want to close this window prompt.
Unfortunately it is impossible to get Firefox to close the window.
A: In the body tag:
<body onload="window.open('', '_self', '');">
To close the window:
<a href="javascript:window.close();">
Tested on Safari 4.0.5, FF for Mac 3.6, IE 8.0, and FF for Windows 3.5
A: In my situation the following code was embedded into a php file.
var PreventExitPop = true;
function ExitPop() {
if (PreventExitPop != false) {
return "Hold your horses! \n\nTake the time to reserve your place.Registrations might become paid or closed completely to newcomers!"
}
}
window.onbeforeunload = ExitPop;
So I opened the console and write the following
PreventExitPop = false
This solved the problem.
So, find out the JavaScript code and find the variable(s) and assign them to an appropriate "value" which in my case was "false"
A: The browser is complaining because you're using JavaScript to close a window that wasn't opened with JavaScript, i.e. window.open('foo.html');.
A: Place the following code in the ASPX.
<script language=javascript>
function CloseWindow()
{
window.open('', '_self', '');
window.close();
}
</script>
Place the following code in the code behind button click event.
string myclosescript = "<script language='javascript' type='text/javascript'>CloseWindow();</script>";
Page.ClientScript.RegisterStartupScript(GetType(), "myclosescript", myclosescript);
If you dont have any processing before close then you can directly put the following code in the ASPX itself in the button click tag.
OnClientClick="CloseWindow();"
Hope this helps.
A: I am going to post this because this is what I am currently using for my site and it works in both Google Chrome and IE 10 without receiving any popup messages:
<html>
<head>
</head>
<body onload="window.close();">
</body>
</html>
I have a function on my site that I want to run to save an on/off variable to session without directly going to a new page so I just open a tiny popup webpage. That webpage then closes itself immediately with the onload="window.close();" function.
A: The best solution I have found is:
this.focus();
self.opener=this;
self.close();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "93"
} |
Q: Registry key that contains the folder for the local user's Programs folder on Vista I'm troubleshooting a problem with creating Vista shortcuts.
I want to make sure that our Installer is reading the Programs folder from the right registry key.
It's reading it from:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs
And it's showing this directory for Programs:
C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
From what I've read, this seems correct, but I wanted to double check.
A: Don't use the registry to read this. Use SHGetFolderPath with CSIDL_PROGRAMS.
For a reason why, see Raymond Chen's comments on the "Shell Folders" key:
http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx
A: use windows installer properties. will probably be easier.
http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx#system_folder_properties
A: You should probably use API for this, such as SHGetFolderPath
A: Sounds correct to me.
A: Example of the SHGetFolderPath in VB
http://support.microsoft.com/kb/252652
A: Helpful code snippet:
public class Utilities
{
public enum FolderPaths
{
CSIDL_DESKTOP = 0x0000, // <desktop>
CSIDL_INTERNET = 0x0001, // Internet Explorer (icon on desktop)
CSIDL_PROGRAMS = 0x0002, // Start Menu\Programs
CSIDL_CONTROLS = 0x0003, // My Computer\Control Panel
CSIDL_PRINTERS = 0x0004, // My Computer\Printers
CSIDL_PERSONAL = 0x0005, // My Documents
CSIDL_FAVORITES = 0x0006, // <user name>\Favorites
CSIDL_STARTUP = 0x0007, // Start Menu\Programs\Startup
CSIDL_RECENT = 0x0008, // <user name>\Recent
CSIDL_SENDTO = 0x0009, // <user name>\SendTo
CSIDL_BITBUCKET = 0x000a, // <desktop>\Recycle Bin
CSIDL_STARTMENU = 0x000b, // <user name>\Start Menu
CSIDL_MYDOCUMENTS = CSIDL_PERSONAL, // Personal was just a silly name for My Documents
CSIDL_MYMUSIC = 0x000d, // "My Music" folder
CSIDL_MYVIDEO = 0x000e, // "My Videos" folder
CSIDL_DESKTOPDIRECTORY = 0x0010, // <user name>\Desktop
CSIDL_DRIVES = 0x0011, // My Computer
CSIDL_NETWORK = 0x0012, // Network Neighborhood (My Network Places)
CSIDL_NETHOOD = 0x0013, // <user name>\nethood
CSIDL_FONTS = 0x0014, // windows\fonts
CSIDL_TEMPLATES = 0x0015,
CSIDL_COMMON_STARTMENU = 0x0016, // All Users\Start Menu
CSIDL_COMMON_PROGRAMS = 0X0017, // All Users\Start Menu\Programs
CSIDL_COMMON_STARTUP = 0x0018, // All Users\Startup
CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019, // All Users\Desktop
CSIDL_APPDATA = 0x001a, // <user name>\Application Data
CSIDL_PRINTHOOD = 0x001b, // <user name>\PrintHood
CSIDL_LOCAL_APPDATA = 0x001c // <user name>\Local Settings\Applicaiton Data (non roaming)
}
[DllImport("shfolder.dll", CharSet = CharSet.Unicode)]
public static extern int SHGetFolderPath(IntPtr owner, int folder, IntPtr token, int flags, StringBuilder path);
}
void MyFunction()
{
StringBuilder path = new StringBuilder(260);
String folderPath = "";
if (0 == Utilities.SHGetFolderPath(IntPtr.Zero, (int) Utilities.FolderPaths.CSIDL_MYVIDEO, IntPtr.Zero, 0, path))
{
folderPath = path.ToString();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a standard ReSharper code style definition that matches all the StyleCop requirements? The ReSharper reformat code feature is very handy and flexible, particularly with the new code layout templating flexibility JetBrains have added in version 3.0.
Is there a standard set of code style settings for ReSharper which match the rules enforced by Microsoft StyleCop, so that StyleCop compliance can be as easy as running the ReSharper "reformat code" feature?
A: I am looking for the same things.
Here is a Custom Type member layout:
<?xml version="1.0" encoding="utf-8"?>
<Patterns xmlns="urn:shemas-jetbrains-com:member-reordering-patterns">
<!--Do not reorder COM interfaces and structs marked by
StructLayout attribute-->
<Pattern>
<Match>
<Or Weight="100">
<And>
<Kind Is="interface"/>
<HasAttribute CLRName="System.Runtime.InteropServices.InterfaceTypeAttribute"/>
</And>
<HasAttribute CLRName="System.Runtime.InteropServices.StructLayoutAttribute"/>
</Or>
</Match>
</Pattern>
<!--Special formatting of NUnit test fixture-->
<Pattern RemoveAllRegions="true">
<Match>
<And Weight="100">
<Kind Is="class"/>
<HasAttribute CLRName="NUnit.Framework.TestFixtureAttribute"
Inherit="true"/>
</And>
</Match>
<!--Setup/Teardow-->
<Entry>
<Match>
<And>
<Kind Is="method"/>
<Or>
<HasAttribute CLRName="NUnit.Framework.SetUpAttribute"
Inherit="true"/>
<HasAttribute CLRName="NUnit.Framework.TearDownAttribute"
Inherit="true"/>
<HasAttribute CLRName="NUnit.Framework.FixtureSetUpAttribute"
Inherit="true"/>
<HasAttribute CLRName="NUnit.Framework.FixtureTearDownAttribute"
Inherit="true"/>
</Or>
</And>
</Match>
<Group Region="Setup/Teardown"/>
</Entry>
<!--All other members-->
<Entry/>
<!--Test methods-->
<Entry>
<Match>
<And Weight="100">
<Kind Is="method"/>
<HasAttribute CLRName="NUnit.Framework.TestAttribute"
Inherit="false"/>
</And>
</Match>
<Sort>
<Name/>
</Sort>
</Entry>
</Pattern>
<!--Default pattern-->
<Pattern>
<!--public delegate-->
<Entry>
<Match>
<And Weight="100">
<Access Is="public"/>
<Kind Is="delegate"/>
</And>
</Match>
<Sort>
<Name/>
</Sort>
<Group Region="Delegates"/>
</Entry>
<!--public enum-->
<Entry>
<Match>
<And Weight="100">
<Access Is="public"/>
<Kind Is="enum"/>
</And>
</Match>
<Sort>
<Name/>
</Sort>
<Group>
<Name Region="${Name} enum"/>
</Group>
</Entry>
<!--fields and constants-->
<Entry>
<Match>
<Or>
<Kind Is="constant"/>
<Kind Is="field"/>
</Or>
</Match>
<Sort>
<Kind Order="constant field"/>
<Readonly/>
<Static/>
<Name/>
</Sort>
<Group Region="Fields"/>
</Entry>
<!-- Events-->
<Entry>
<Match>
<Kind Is="event"/>
</Match>
<Sort>
<Name/>
</Sort>
<Group Region="Events"/>
</Entry>
<!--Constructors. Place static one first-->
<Entry>
<Match>
<Kind Is="constructor"/>
</Match>
<Sort>
<Static/>
</Sort>
<Group Region="Constructors"/>
</Entry>
<!--properties, indexers-->
<Entry>
<Match>
<Or>
<Kind Is="property"/>
<Kind Is="indexer"/>
</Or>
</Match>
<Sort>
<Name/>
</Sort>
<Group Region="Properties"/>
</Entry>
<!--interface implementations-->
<Entry>
<Match>
<And Weight="100">
<Kind Is="member"/>
<ImplementsInterface/>
</And>
</Match>
<Sort>
<ImplementsInterface Immediate="true"/>
<Kind Order="property"/>
<Name/>
</Sort>
<Group>
<ImplementsInterface Immediate="true"
Region="${ImplementsInterface} Members"/>
</Group>
</Entry>
<!-- public Methods -->
<Entry>
<Match>
<And>
<Kind Is="method"/>
<Access Is="public"/>
</And>
</Match>
<Sort>
<Static/>
<Name/>
</Sort>
<Group>
</Group>
</Entry>
<!-- internal Methods -->
<Entry>
<Match>
<And>
<Kind Is="method"/>
<Access Is="internal"/>
</And>
</Match>
<Sort>
<Static/>
<Name/>
</Sort>
<Group>
</Group>
</Entry>
<!--protected internal Methods -->
<Entry>
<Match>
<And>
<Kind Is="method"/>
<Access Is="protected-internal"/>
</And>
</Match>
<Sort>
<Static/>
<Name/>
</Sort>
<Group>
</Group>
</Entry>
<!-- protected Methods -->
<Entry>
<Match>
<And>
<Kind Is="method"/>
<Access Is="protected"/>
</And>
</Match>
<Sort>
<Static/>
<Name/>
</Sort>
<Group>
</Group>
</Entry>
<!-- private Methods -->
<Entry>
<Match>
<And>
<Kind Is="method"/>
<Access Is="private"/>
</And>
</Match>
<Sort>
<Static/>
<Name/>
</Sort>
<Group>
</Group>
</Entry>
<!--all other members-->
<Entry/>
<!--nested types-->
<Entry>
<Match>
<Kind Is="type"/>
</Match>
<Sort>
<Name/>
</Sort>
<Group>
<Name Region="Nested type: ${Name}"/>
</Group>
</Entry>
</Pattern>
</Patterns>
<!--
I. Overall
I.1 Each pattern can have <Match>....</Match> element. For the given type
declaration, the pattern with the match, evaluated to 'true' with the
largest weight, will be used
I.2 Each pattern consists of the sequence of <Entry>...</Entry> elements.
Type member declarations are distributed between entries
I.3 If pattern has RemoveAllRegions="true" attribute, then all regions
will be cleared prior to reordering. Otherwise, only auto-generated
regions will be cleared
I.4 The contents of each entry is sorted by given keys (First key is
primary, next key is secondary, etc). Then the declarations are
grouped and en-regioned by given property
II. Available match operands
Each operand may have Weight="..." attribute. This weight will be added
to the match weight if the operand is evaluated to 'true'.The default
weight is 1
II.1 Boolean functions:
II.1.1 <And>....</And>
II.1.2 <Or>....</Or>
II.1.3 <Not>....</Not>
II.2 Operands
II.2.1 <Kind Is="..."/>. Kinds are: class, struct, interface, enum,
delegate, type, constructor, destructor, property, indexer, method,
operator, field, constant, event, member
II.2.2 <Name Is="..." [IgnoreCase="true/false"] />. The 'Is' attribute
contains regular expression
II.2.3 <HasAttribute CLRName="..." [Inherit="true/false"] />. The 'CLRName'
attribute contains regular expression
II.2.4 <Access Is="..."/>. The 'Is' values are: public, protected, internal,
protected internal, private
II.2.5 <Static/>
II.2.6 <Abstract/>
II.2.7 <Virtual/>
II.2.8 <Override/>
II.2.9 <Sealed/>
II.2.10 <Readonly/>
II.2.11 <ImplementsInterface CLRName="..."/>. The 'CLRName' attribute
contains regular expression
II.2.12 <HandlesEvent />
-->
based on this one, that did not do the trick for me but who deserves the credit: http://www.clydesdalesoftware.net/blogs/jluif/CommentView,guid,1875594b-0d23-401f-8e22-f1cbf87beefe.aspx
This is a header snippet that complies to stylecop:
// <copyright file="$FileName$" company="$Company$">
// Copyright (c) 2008 All Right Reserved
// </copyright>
// <author>$author$</author>
// <email>$email$</email>
// <date>$date$</date>
// <summary>$summary$</summary>
Still not quite there but it is a start.
Since this answer the Custom type member layout has been put in the StyleCop for resharper plugin. See here
A: Try the ReSharper StyleCop plugin at: http://www.codeplex.com/StyleCopForReSharper
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Is there a Windows Registry "dictionary" that explains the whole (or most of) the Windows Registry? I'd like to be able to see what registry keys are used for. A book on the registry would be fine as well. Info on Windows Vista changes would be great!
A: The wikipedia article is actually rather nice. Not a full account of everything, but not too shabby either.
http://en.wikipedia.org/wiki/Windows_Registry
A: Oh, how I wish there was a single site where the registry was collectively documented by all who write values there! Keep in mind, any app can create its own set of registry keys and values, so it's not just MS who would be necessary to such an effort. Though they would be a key player!
In the meantime, there are two MS sites I use as startng points when I need to know what a particular key/value pair do:
Windows 2003 registry reference:
http://technet.microsoft.com/en-us/library/cc778196.aspx
Windows 2000 Registry reference:
http://technet.microsoft.com/en-us/library/cc974061.aspx
Keep in mind that since Windows is an evolving thing, even information about older versions can be very helpful. Also note that W2003 bears a lot of resemblance to XP. Sadly, I have not found a link to the Vista/Windows 2008 registries similar to the above.
When you need to know what's up with a specific key, and it's not found in one of the above links, try a search of that key's full path at http://support.microsoft.com
A: Always look up APIs in the Windows SDK first instead of registry entries first . For example, if you store the path to the user's my document folder (yes it is in registery), your code may break when the user's registery roams to another machine where the user's profile is stored in a different location.
Suggested reading:
The long and sad story of the Shell Folders key
A: I have used this help file in the past. Very good resource
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: SQL/Oracle: when indexes on multiple columns can be used If I create an index on columns (A, B, C), in that order, my understanding is that the database will be able to use it even if I search only on (A), or (A and B), or (A and B and C), but not if I search only on (B), or (C), or (B and C). Is this correct?
A: That is not correct. Always best to come up with a test case that represents your data and see for yourself. If you want to really understand the Oracle SQL Optimizer google Jonathan Lewis, read his books, read his blog, check out his website, the guy is amazing, and he always generates test cases.
create table mytab nologging as (
select mod(rownum, 3) x, rownum y, mod(rownum, 3) z from all_objects, (select 'x' from user_tables where rownum < 4)
);
create index i on mytab (x, y, z);
exec dbms_stats.gather_table_stats(ownname=>'DBADMIN',tabname=>'MYTAB', cascade=>true);
set autot trace exp
select * from mytab where y=5000;
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=10)
1 0 INDEX (SKIP SCAN) OF 'I' (INDEX) (Cost=1 Card=1 Bytes=10)
A: Up to version Oracle 8 an index will never be used unless the first column is included in the SQL.
In Oracle 9i the Skip Scan Index Access feature was introduced, which lets the Oracle CBO attempt to use indexes even when the prefix column is not available.
Good overview of how skip scan works here: http://www.quest-pipelines.com/newsletter-v5/1004_C.htm
A: There are actually three index-based access methods that Oracle can use when a predicate is placed on a non-leading column of an index.
i) Index skip-scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#PFGRF10105
ii) Fast full index scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i52044
iii) Index full scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i82107
I've most often seen the fast full index scan "in the wild", but all are possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: What is your experience with Sun CoolThreads technology? My project has some money to spend before the end of the fiscal year and we are considering replacing a Sun-Fire-V490 server we've had for a few years. One option we are looking at is the CoolThreads technology. All I know is the Sun marketing, which may not be 100% unbiased. Has anyone actually played with one of these?
I suspect it will be no value to us, since we don't use threads or virtual machines much and we can't spend a lot of time retrofitting code. We do spawn a ton of processes, but I doubt CoolThreads will be of help there.
(And yes, the money would be better spent on bonuses or something, but that's not going to happen.)
A: IIRC The coolthreads technology is referring to the fact that rather than just ramping up the clock speed ever higher to improve performance they are now looking at multiple core processors with hyperthreading effectively giving you loads of processors on one chip. Overall the processing capacity available is higher but without the additional electrical power and aircon requirements you would expect (hence cool). Its usefulness definitely depends on what you are planning to run on it. If you are running Apache with the multiple threads core it will love it as it can run the individual response threads on the individual cpu cores. If you are simply running single thread processes you will get some performance increases over a single cpu box but not as great (any old fashioned non mod_perl/mod_python CGID processes would still be sharing the the cpu a bit). If your application consists of one single threaded process running maxed out on the box you will get very little improvement on a single core cpu running at the same speed.
Peter
Edit:
Oh and for a benchmark. We compared a T2000 in our server farm to our current V240s (May have been V480's I don't recall) The T2000 took the load of 12-13 of the Older boxes in a live test without any OS tweeking for performance. As I said Apache loves it :-)
A: Disclosure: I work for Sun (but as an engineer in client software).
You don't necesarily need multithreaded code to make use of these machines. Having multiple processes will make use of multiple hardware threads on multiple cores.
The old T1 processors (T1000 and T2000 boxes) did have only a single FPU, and weren't really suitable for tasks with much more than about 1% floating point. The newer T2 and T2+ processors have an FPU per core. That's probably still not great for massive floating point crunching, but is much more respectable.
(Note: Hyper-Threading Technology is a trademark of Intel. Sun uses the term Chip MultiThreading (CMT).)
A: We used Sun Fire T2000s for my last system. The boxes themselves were far exceeded our capacity requirements in terms of processing power. For us the decision was based on the lower power consumption and space requirement. We successfully ran WebSphere 6, Oracle 10g and SunONE Directory server on the same box.
A: My info may be a bit out of date (last used these servers 2 years ago) but as I recall one big gotcha was that all the cores on a single CPU all shared the same FPU unit, so if your code did a lot of floating point (we were doing GIS) the FPU was a massive bottleneck and you didn't get much benefit from the large number of threads.
A: For any process with high parallelism these machines (eg, the t1000/t2000) are great for their cost. I've been running oracle on them for about 18 months now and it works great.
If you task is a single threaded/single process, then you'd be better off with a high speed dual/quad core intel machine.
If your application has lots of threads/lots of processes then these machines will likely be great for it.
Best of all, Sun will send you one for 60 days to evaluate, that is what we did before committing to it, ended up getting 2 t2000's and have recently purchased another 4 t1000's.
A: It hit me last night that our core processes aren't multi-threaded, but the machine in question does have a bunch of system processes that are. In particular, it acts as an NFS server. It sounds like running hundreds of processes will benefit from all those cores, as well.
I'll see if we can get a demo unit to test on first.
A: Sun has been selling the Niagra machines to be all things to all comers. They do have their place: web services being the best deployment. We have run Oracle on some T2000s and it worked well for highly parallelized operations. But the machines fall flat on single-treaded operations, the performance of which is rather bad. If you have floating point work to do, look elsewhere. Even the newer chips with A FPU per core is inadequate. Also, these machines cannot take a enterprise-class pounding for long and we've had reliability problems. Multi-core techology is more hype than substance. Sandia National Lab's research on it and found that four to eight cores is about the top-end of usefulnes and that a 16 core chip has the same throughput as a dual core chip. So a 16 core chip is a waste of a lot of money. Also, as the number of cores increase, the clock speed muust decrease, because of the thermal wall. Most manufacturers will probably settle on quad-core chips until memory technology improves (you can't keep 16 cores fed with memory and most of the cores are stalled). Finally, given the chaos at Sun, you'd do better to look elsewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: When creating a new GUI, is WPF the preferred choice over Windows Forms? Most restrictions and tricks with windows forms are common to most programmers. But since .NET 3.0 there is also WPF available, the Windows Presentation Foundation. It is said that you can make "sexy applications" more easy with it and with .NET 3.5 SP1 it got a good speed boost on execution.
But on the other side a lot of things are working different with WPF. I will not say it is more difficult but you have to learn "everything" from scratch.
My question: Is it worth to spend this extra time when you have to create a new GUI and there is no time pressure for the project?
A: Consider WPF if interface design is important to you, because WPF can deliver better UI experience. But Windows Forms has on its side the years of evolution, so it's proven to work and you can find many versed programmers for that platform.
Also portability may be an issue, WPF only works with Windows XP SP2 and up.
Also, WPF has a steep learning curve, meaning it's not easy to deliver a quality product without having specific WPF experience.
A: I'm seven months into using WPF on what has now become a core system for my customer, and I'd like to share some more thoughts with you about the experience of learning and using WPF as a line of business presentation platform.
In general, the comments I made above still hold... The design time support for WPF isn't here yet. If you're in a big rush to get a rich-client application out of the door, go with Windows Forms. Period. Microsoft aren't in any hurry to discontinue the GDI / Windows Forms platform, so you can count on good support for a fair time into the future.
WPF is not easy to master, but that shouldn't be where you leave your descision about whether or not to invest your time and energy into learning WPF. Despite its present lack of maturity, WPF is built around some useful, modern concepts.
In WPF, for example, your investment in well-written business objects with sound validating logic is a solid investment. Unlike Windows Forms, WPF's data binding is briming with features that allow interface controls to react to invalid user input without writing GUI code to detect those errors. This is valuable.
The styling and templating capabilities in WPF have proven to be valuable too. Despite the common misconception that the only use for styling and templating is to create on-screen eye-candy, the truth is that these features significantly simplify the coding of a user interface which gives rich feedback - like buttons that disable/enable themselves base on the state of the underlying business logic layer, or tooltips which intelligently find their text based on the state of the object under the cursor, etc.
These all add up to incredibly valuable features for "nothing fancy" business applications, simply because they make it easy to keep the interface congruent with the underlying data.
In a nutshell:
*
*In Windows Forms you design your user
interface, then write code to drive
that user interface, which generally
also includes code to drive your
data objects.
*In WPF you invest in the business layer that drives your data objects, then design an interface that listens to your data objects.
It's a seemingly subtle difference, but it makes a huge difference in your ability to re-use code... which begs the question: "Is the Windows Forms vs WPF question actually an investment decision?"
(This seems to have become my favourite thread.)
A: Well, one answer is "when you have to support 1.1 or 2.0", since WPF is part of .NET 3.0. There are known OS limitations for WPF, and there is an obvious skills issue: if you have a team of developers that know winforms, then it may be easier to turn out robust code with winforms. However, if you are writing a lot of UI code it is probably worth beginning to pick up WPF at some point.
WPF also shares a lot in common with Silverlight, so it has transferable benefits.
A: WPF comes with many advantages such as superb data binding features,
separation of concerns, separation of design and logic etc...
As a developer I enjoy the ability to define my UI using XAML as opposed to
being tied to the Windows Forms designer and I feel good knowing I can count
on another designer to make my app look good.
Personally I don't care older versions of Windows are not supported,
but one of the big problems with WPF is that is is not (currently/ever) supported
by Mono (http://www.mono-project.com) so WPF apps will not run on Mac OS or Linux.
(Altough Silverlight applications will).
If you have the time and resources to invest in learning WPF, do it!
Even if you're going to be writing Silverlight applications to support multiple OS's.
If you need desktop applications to run on multiple OS's stick with SWF.
A: Are there any compelling reasons to use WPF
Absolutely! WPF is absolutely incredible! It will be a major benefit for practically any project because it has so many features and abilities that Windows Forms lacks.
For business applications the biggest wins will be:
*
*The fantastic data binding and templating make the biggest difference. Once a decent data model is in place, it only takes a few clicks to create a data template and use Expression Blend to configure exactly how your object will look using drag-and-drop. And binding to things like color or shape is trivial.
*Screen layout is incredibly flexible. Not only can everything in WPF smoothly adjust to container size and shape changes, but items can trivially be enlarged and rotated, and even extend outside their containing frame.
*Ordinary objects can be presented any way you like, can easily have different presentations in different screens, can share presentation, and can adapt their presentation to changes in data values.
*If you need to print, rendering to the printer is trivial. Properly configured, WPF makes Crystal Reports or SQL Server Reporting Services (SSRS) look like a child's toy.
*Your user interface will look and feel much more dynamic, including nice features such as buttons that animate when you pass the mouse over them.
For utilities and games, other advantages come to the forefront:
*
*You can easily add shapes, lines, and arbitrary drawings to your application without using an external editor. Every component of these can be data-bound and animated, or controlled by code. In Windows Forms you ususally just have to import a bitmap and use it as-is unless you want to go to a lot of work.,
*Animations are cool! Users will be really impressed, as long as you don't overdo it. They can also help people see what is going on and reduce the need for hilighting. For example, when dragging an object you can animate the target to show what will happen if you drop it.
*Colors, gradient fills, brushes, fancy fonts, rotation of any objects, tile brushes, etc. Anything you want graphically is yours for the asking.
*Incredibly customizable. I needed to draw railroad tracks for one application, so I could drop a train on them. A couple of hours later I had railroad tracks I could draw anywhere on the screen using Bézier curves, and they would join and switch automatically.
The bottom line is that any significant-size GUI you could build in Windows Forms can be built in WPF in a third of the effort (or less) and look way, way better.
Does WPF require more resources (RAM in particular)
You do pay a price compared to Windows Forms, but it is a small one.
*
*RAM can go up or down depending on your implementation. WPF stores its data more efficiently so individual objects are smaller, but there tend to be more objects in WPF than in Windows Forms so this balances out, and either one can come out ahead.
*CPU will go up compared to Windows Forms. In my experience, the actual update of WPF objects onscreen takes about twice as much CPU as normal Windows Forms rendering. If your application spends most of its time updating the screen, WPF may not be for you. But in that case you're probably not using Windows Forms either: Most serious games are written directly to DirectX.
*Disk usage will be slightly less for WPF because it takes so much less code than Windows Forms. The data will be the same size, of course.
One more note about CPU use: Animations and transforms (motion, translation, etc.) is actually more efficient on WPF than in Windows Forms because of its retained mode storage. It is the initial getting of the objects up there that is slower.
Maintenance overhead
WPF is a huge win over Windows Forms when it comes to maintenance. Since everything is done in 1/5 as much code as before, there is 1/5 as much to maintain. Plus all the boilerplate stuff is gone so you can focus on the code that actually does the work.
Benefits of XAML
XAML is the core of WPF. Although WPF can be used without XAML, XAML makes it incredibly easy to use. XAML has HTML's ability to easily specify a user interface, but its built-in tags are much more powerful, and you can easily define your own. (In fact, it is normal to do so).
Some specific advantages of XAML:
*
*Your entire UI is defined in a text file that is easy to read and manipulate, both for users and tools
*MarkupExtensions allow Bindings to be specified in a clear and simple way
*Type converters allow properties with complex types to be easily specified. For example, you can say Brush="Green" or you can specify a radial gradient brush with three stops.
*You can create your own elements
*You can easily leverage WPF's powerful "attached properties"
Other insights
I dreamed of something like WPF for many years. Many people have implemented portions of this functionality, but to get it all in one place and at such a price ($0) is amazing.
WPF is a huge paradigm shift from Windows Forms and will take some getting used to, but the time spend learning it will pay itself back many-fold.
WPF still has a few warts even five years later, but its power will totally blow you away once you experience it. If someone tries to drag you back to Windows Forms, you'll only go kicking and screaming.
Tips:
- Do get a copy of Expression Blend for development
- Do edit XAML by hand occasionally
- Don't give up when it seems strange at first
A: WPF enables you to do some amazing things, and I LOVE it... but I always feel obligated to qualify my recommendations, whenever developers ask me whether I think they should be moving to the new technology.
Are your developers willing (preferrably, EAGER) to spend the time it takes to learn to use WPF effectively? I never would have thought to say this about MFC, or Windows Forms, or even unmanaged DirectX, but you probably do NOT want a team trying to "pick up" WPF over the course of a normal dev. cycle for a shipping product!
Do at least one or two of your developers have some design sensibilities, and do individuals with final design authority have a decent understanding of development issues, so you can leverage WPF capabilities to create something which is actually BETTER, instead of just more "colorful", featuring gratuitous animation?
Does some percentage of your target customer base run on integrated graphics chip sets that might not support the features you were planning -- or are they still running Windows 2000, which would eliminate them as customers altogether? Some people would also ask whether your customers actually CARE about enhanced visuals but, having lived through internal company "Our business customers don't care about colors and pictures" debates in the early '90s, I know that well-designed solutions from your competitors will MAKE them care, and the real question is whether the conditions are right, to enable you to offer something that will make them care NOW.
Does the project involve grounds-up development, at least for the presentation layer, to avoid the additional complexity of trying to hook into incompatible legacy scaffolding (Interop with Win Forms is NOT seamless)?
Can your manager accept (or be distracted from noticing) a significant DROP in developer productivity for four to six months?
This last issue is due to what I like to think of as the "FizzBin" nature of WPF, with ten different ways to implement any task, and no apparent reason to prefer one approach to another, and little guidance available to help you make a choice. Not only will the shortcomings of whatever choice you make become clear only much later in the project, but you are virtually guaranteed to have every developer on your project adopting a different approach, resulting in a major maintenance headache. Most frustrating of all are the inconsistencies that constantly trip you up, as you try to learn the framework.
You can find more in-depth WPF-related information in an entry on my blog:
http://missedmemo.com/blog/2008/09/13/WPFTheFizzBinAPI.aspx
A: There are many differences. We loved WPF for:
*
*The declarative style of programming.
*Animations and state transitions
*Expression Blend is a great tool
*Good style support.
However, we stuck with Windows Forms because:
*
*The extra time it takes for a
developer to learn WPF when they
already know Windows Forms.
*WPF will not run on Windows 2000 or
lower.
A: WPF requires either Windows Vista or Windows XP SP2, which is not an onerous requirement, but it is a relevant one. If you want to run on Windows 2000 (which some people still do), then WPF won't work for you.
WPF is also a newer technology and not as proven as Windows Forms so you might choose Windows Forms as a less risky option, particularly for larger applications.
That being said, yes WPF is the future. Visual Studio 2010 is being rewritten in WPF, which will probably be the largest WPF application to date and it will also be a real test for the technology.
Obviously, legacy Windows Forms applications would be another situation where it is the correct choice.
A: The biggest consideration when deciding which one to use is to consider what .NET Framework your target audience have installed. I find that more people have the lower .NET Framework versions that only support Windows Forms, but that's just my personal experience.
A: As others have said, there are advantages and disadvantages either way you go here. The advantages of WPF, as others have said, include:
*
*The ability to make very rich UIs relatively easily.
*Easier animation and special effects
*Inherent scalability (use the Windows Vista magnifier tool on a WPF application, and on a Windows Forms application: Note that in the WPF application, all the vector art scales beautifully)
*(OPINION ALERT) I feel it's "easier" to do document-oriented systems in WPF
However, there are drawbacks to WPF, where Windows Forms comes out on top:
*
*WPF's in-box control suite is far more limited than that of Windows Forms.
*There's greater support in the third-party control space for Windows Forms. (That's changing, of course, but think about it: Windows Forms has been around since 2001; WPF just a few years. By advantage of time, Windows Forms has greater support in the community.)
*Most developers already know Windows Forms; WPF provides a new learning curve
Finally, bear in mind that you can create great, attractive and engaging UIs in either tool, if you do the work (or use the right third-party tools). At the end of the day, neither is necessarily better in all circumstances. Use what feels right for the project.
A: The advantages of WPF is that it is much easier to create nice looking GUI's with custom controls and animations. WPF also helps further serparate the presentation and logic layers. If you have designers, it allows you to farm of 95% of this work to non-coders and allows the coders to work on logic. The disadvantages are the software costs for Expressions Blend, and the lack of any of the Visual Studio code profiling tools working well as they tend to get caught up in the frameworks calls in trying to render XAML. I am sure there are others but these were the only two we really saw.
The main consideration is if you wish to require your customers to have to install .NET 3.0 or even better .NET 3.5 SP1. You will get some niegative feedback
A: WPF makes it much easier to hand off the forms design work to an actual designer, not a developer in designer's clothing. If that's something you'd like to do, WPF is your answer. If the classic Windows styled buttons are fine, then Windows Forms is probably the way to go.
(Multiple answers make the claim that you should use WPF if interface design is "important to you" but that's pretty vague. Interface design is always "important".)
A: If you have an MSDN license, check out Expression tools. It's designed explicitly for WPF, exports directly to Visual Studio and it may help ease your transition.
A: If you only care about supporting Windows and don't mind the time it takes to learn it, go with WPF. It's fast, flexible, easy to reskin, and has great tools to work with it.
A: As a side bonus, Silverlight is based on WPF and starting with either lets you gain the know how for working with the other. If things continue to go web based, having prior knowledge (and a library of existing code) to transfer easily to the browser (or Windows Live Mesh) might help give your software an extra lease of life.
A: If you decide to go with WPF, considering pros and cons already explained in the above answers, I highly recommend going through this dnrTV episode with Billy Hollis
A: In DotNetRocks episode 315, Brian Noyes discusses this extensively.
A: For the last 3 1/2 years I've been doing Windows Forms development (at two companies). Both applications were used extensively and ended up having GDI problems. Large Windows Forms applications will eventually run out of GDI resources - causing the end user to have to reboot.
A: There is a known issue with text rendering in WPF. Many users report that the heavy use of anti-aliasing and pixel-blending used causes blurry text. This is a big deal breaker in some circumstances and, as far as I know, has been acknowledged by Microsoft at some level.
A: The programming model for WPF is more open and flexible than Windows Forms is, but like ASP.NET MVC, it requires a little more discipline in terms of correctly implementing Model-View-ViewModel patterns.
My first LOB application with WPF ended up as an utter failuire, because it was a resource hog which brought my end-user's very-low-end laptops grinding to a halt... and this was ultimately because I just lept in with WPF + LINQ to SQL and expected a good result... and this is where WPF diverges so strongly from Windows Forms... In Windows Forms, you can get away with that sort of thing. WPF is much heavier on resources than Windows Forms, and if you don't architect your application to be lean, you end up with a 800-pound gorilla.
Don't shy away from WPF... explore it. But be aware that the acceptable sins of Windows Forms coding won't produce good results in WPF. They're fundamentally different engines, which lend themselves to fundamentally different coding patterns.
Last Word: If you do go ahead with WPF, get well acquianted with data virtualization for use with lists and grids. What is a simple data-bound ListItem or GridCell ends up being a hefty logical + visual object-graph in WPF, and if you don't learn how to virtualize, you application won't perform well on large data sets.
A: Scott is complaining about Expression Blend and how it doesn't make sense to him as a developer. My first reaction to Expression Blend was like that. However, now I see it as an invaluable tool, but it really depends on what type of developer you are.
I am user interface developer that has had to perform the Integrator role, and I eventually found Expression Blend invaluable to create styles, and control templates in a WYSIWYG manner. I almost always have Expression Blend and Visual Studio up an running on the same project at the same time.
I also think that playing around in Expression Blend and taking a look at the XAML that gets spit out is an excellent way to learn the WPF API ... much like using the designer in Windows Forms and checking the C# code it spits out is helpful in learning how to use whatever you are designing there.
Expression Blend is helpful. Just give it a try, especially if you are working on the visuals for the application.
A: A quote from an earlier post from Mark:
*
*In Windows Forms you design your user interface, then write code to drive that user interface, which generally also includes code to drive your data objects.
*In WPF you invest in the business layer that drives your data objects, then design an interface that listens to your data objects.
I would argue that this is more of a design choice, rather than whether or not you are using Windows Forms or WPF. However, I can appreciate that certain technologies might be better suited for a particular approach.
A: There is a very steep learning curve to WPF, and I recommend you get the obvious books first (Adam Nathan,
Sells/Griffiths, and
Chris Anderson) and
blogs (Josh Smith, etc.). Just be prepared for it, and make sure your project allows you the time to learn WPF.
In addition to learning the technology, spend some time learning the patterns used to construct WPF applications. Model View ViewModel (MVVM) seems to be the one that has gained a great deal of acceptance.
Personally, I think WPF is worth it but be forewarned. Also note that you effectively restrict your users to Windows XP SP2+ and Windows Vista. We've made that decision, but you may have some different requirements.
A: Both of technologies have their pros and cons. In a large application with a "classic" UI I'd use Windows Forms. In an application which require a rich user interface (skinning, animations, changing user interface) I'd choose WPF. Please check the article WPF vs. Windows Forms comparing WPF and Windows Forms.
A: Aside from the flexibility in UI design, there are some technical advantages to WPF:
1.) WPF doesn't rely on GDI objects. Well, I think it uses 2 GDI objects for the instance of the window itself, but that's practically nothing. I've been involved to a certain extent in a very large internal Windows Forms application. The people in our office sometimes run 3 or 4 instances of it simultaneously. The problem is that they frequently run into the 10,000 GDI object limit inherent to Windows 2000, XP and Vista. When that happens the entire OS becomes unresponsive and you'll start to see visual artifacts. The only way to clear it up is to close applications down.
2.) WPF utilizes the GPU. The ability for WPF to off-load some of the UI processing to the GPU is brilliant. I only expect this aspect of it to get better with time. As a former OpenGL programming hobbyist I can appreciate the power that comes from the GPU. I mean, my $100 video card has 112 cores running at 1.5 GHz each (and that's not top of the line by any means). That kind of parallel processing power can put any quad-core CPU to shame.
However, WPF is still pretty new. It won't run on Windows 2000. And in fact, a WPF application can be slow to start up after a fresh reboot. I talk about all of this on my blog:
http://blog.bucketsoft.com/2009/05/wpf-is-like-fat-super-hero.html
A: After three months of trying to hammer out a line-of-business (LOB) application on WPF, I reached a point of considering turning back to Windows Forms for my project, and in researching other people's opinions, came across this thread...
Yes, WPF is a brilliant technology and it has benefits that span far beyond mere eye-candy... the templating and binding capabilities are great examples. The whole object model offers more flexibility and broader possibilities. That doesn't, however, make it the defacto platform for future LOB applications.
The "problems" which WPF solves in terms of separating GUI from business logic aren't problems which can't be readily solved in Windows Forms by simply starting with the right architecture and mind-set. Even the object-path binding capabilities of WPF can be reproduced in Windows Forms with some very simple helper classes. The data template capabilities of WPF are very nice, but again they're nothing that you can't simulate in Windows Forms on those rare occasions when you absolutely don't know exactly what objects you're going to represent on any given part of the screen.
Where Windows Forms races ahead is in terms of maturity. You can't swing a dead cat on Google without hitting some blog where someone has solved a Windows Forms problem for you. WPF, on the other hand, has comparatively less learning resources available, fewer custom controls available, and hasn't had as many of its teething problems solved.
At the peak of making a WPF vs Windows Forms decision has got to be the maturity of the development environment. Windows Forms editors are slick, responsive and intuitive. Feedback about errors gets to you instantly, the solutions are usually obvious, and the compile->debug->edit cycle in Windows Forms is very quick.
WPF applications, on the other hand, have comparatively pathetic design time support, with the design view all-too ready to chicken out at the first encounter of an error, often requiring a project build after the fix before the designer is willing to kick in again. Drag'n'drop of components from the toolbox might as well not be supported, given the vast range of circumstances under which it either doesn't work at all, or yields completely unintuitive results. Despite the promise of the WpfToolkit, there still isn't a usable DataGrid for WPF that yields any kind of resonable performance or design time friendliness.
Debugging WPF applications is a bit like the old ASP.NET debugging paradigm... hit F5 -> wait -> launch -> error -> stop -> fix -> hit F5 -> wait -> launch -> error -> groan -> stop -> fix -> hit F5.... All XAML which your program is running is locked, and tracking down XAML specific problems is often tedious.
The bottom line, simply put, is that the development tools for Windows Forms are going to have you banging out front-ends in a fraction of the time of a WPF application... especially if you're creating master-detail grids or spreadsheet like interfaces, which most LOB have. With Windows Forms, you start with 90% of the work already done for you.
I'm a huge fan of the WPF architecture. I just wish the design-time tool-set didn't feel like a pre-alpha debug-build.
Edit: This answer was posted about .NET 3.5 + Visual Studio 2008, but .NET 4.0 with Visual Studio 2010 ships with a WPF data grid. While many improvements have been made to the new WPF development experience, my answer here remains unchanged, and I'd like to add the following suggestion:
If you're in a rush to do RAD development, go with Windows Forms. If you're looking to produce a well architected, maintainable, scalable, resource firendly, multi-user Line-Of-Business application, consider ASP.NET MVC + HTML 5 + jQuery... My projects with these technologies have resulted in better outcomes, sooner, for my customers. MVC offers all of the same templating that WPF does, and jQuery enables animations and complex interactions. More importantly, an ASP.NET MVC + jQuery solution doesn't require your end users to have modern desktops with decent graphics hardware.
A: I think it is worth learning WPF. Once you are up to speed, design work on your forms is much easier IMHO. I wouldn't worry as much about the 'sexy' stuff. Most of this is just a fad. You can make 'normal' Winforms-style applications very quickly and easy in WPF.
The whole concept lends itself to easier design IMO.
A: I don't agree with some of the answers here. WPF is really well suited for line of business (LOB) applications. (The frog design LOB client is the best example). And besides all the possibilities to have your UI be eye candy (which is not necessary in business applications), WPF offers a lot more for you.
The data binding and templating features are just superior to Windows Forms. It also offers a far better way for separating code and presentation.
We've successfully used WPF for 2 LOB applications in teams with no more than 2-3 developers.
The biggest problem you will face is probably the steep learning curve of WPF (compared to Windows Forms) which will decrease development speed with developers not used to WPF.
A: We are currently rewriting our application in WPF from Windows Forms. Yes, there is a steep learning curve and you have to "re-learn" some things, but it is so worth it. And combined with WCF, we are finding we are writing less code, faster, and more robust than ever before.
Stick with it for a while, read Adam Nathan's book, and check out the ever growing library of third-party controls like those from Telerik and ComponentOne. One negative, in my view, is that the design tool, Expression Blend, is very awkward to use. The latest version is still in beta, but it just doesn't feel right to those of us who have used Visual Studio for years. Yes, it's mainly for designers, but some things you just can't do in Visual Studio.
A: WPF's support for declarative UI through XAML, rich controls templating and styling and tools like Expression Blend, makes it a lot better for designers to work with developers on the same project. Plus, it gives the developers the flexibility of attached dependency properties and the extremely powerful databinding. In addition Silverlight supports a subset of XAML and the same control classes as WPF, so your application can be ported as RIA with minimal efforts.
I would choose WPF over Windows Forms any day. Even if the target machines only have .NET 2.0, if the user can install additional programs, the new .NET Framework Client profile makes it quite easy to deploy WPF applications.
The only reason I might decide to stick with Windows Forms is if the product will be deployed on machines that are locked down and have only .NET 2.0 or .NET 1.1.
A: Only if you don't have WPF expertise and you don't want to invest in it :)
A: For conversion projects (from Visual Basic 6.0), it's hard to get a team to switch to WPF. Besides the learning curve, people are already used to the old interface. Windows Forms, although being phased out, will be around for a long time still.
A: I'd use Winforms for quick proof of concept stuff, because, while it's terrible for real applications, it is very good for "Visual Basic 6.0" - style rapid prototyping.
So, here an example:
If I need to trace through multiple steps of a process (like downloading something, calculating / converting, creating intelligent ouput) and making everything reproducible, I usually make a quick Form, with a ListBox and a few buttons, done.
Since I'm a REAL developer, the logic will already be in classes other than the view anyway, so this is a fine place to start.
A: Using WPF provides you with the means to customize your application to a great extent. You can code very quickly, that is, create a customize control like a textbox within seconds and customize various attributes like content style, etc., and the best part is the UI beauty, that is, animations, triggers, etc., graphics. But it requires good hardware specifications and some special features available only in Windows Vista and Windows 7.
Windows Forms does not have these rich features which really count, otherwise we can create any type of application using it which we can in WPF.
Windows Forms and WPF are a different species all together, it all depends on the project requirements, that is, what the client or user wants.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: How do I increase the number of default rows per page? 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?
A: You have to install scaffold templates with:
grails install-templates
Now, edit in src/templates/scaffolding Controller.groovy and increase the value params.max as you want
A: I found this but can't get it to work. You're supposed to be able (according to this) to scaffold and then override the actions you want (say list) in your controller, but like I said, it doesn't work for me...
class PersonController {
def scaffold = true
def list = {
if(!params.max) params.max = 20
[ personList: Person.list( params ) ]
}
}
A: Ok, if you use dynamic scaffolding a workaround for this bug, is edit directly in your GRAILS_HOME/src/grails/templates/scaffolding
A: Add to the uri:
?max=<num_rows_desired>
For instance:
http://projecthost:8080/Library/Books/list?max=20
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Update schema and rows in one transaction, SQL Server 2005 I'm currently updating a legacy system which allows users to dictate part of the schema of one of its tables. Users can create and remove columns from the table through this interface. This legacy system is using ADO 2.8, and is using SQL Server 2005 as its database (you don't even WANT to know what database it was using before the attempt to modernize this beast began... but I digress. =) )
In this same editing process, users can define (and change) a list of valid values that can be stored in these user created fields (if the user wants to limit what can be in the field).
When the user changes the list of valid entries for a field, if they remove one of the valid values, they are allowed to choose a new "valid value" to map any rows that have this (now invalid) value in it, so that they now have a valid value again.
In looking through the old code, I noticed that it is extremely vulnerable to putting the system into an invalid state, because the changes mentioned above are not done within a transaction (so if someone else came along halfway through the process mentioned above and made their own changes... well, you can imagine the problems that might cause).
The problem is, I've been trying to get them to update under a single transaction, but whenever the code gets to the part where it changes the schema of that table, all of the other changes (updating values in rows, be it in the table where the schema changed or not... they can be completely unrelated tables even) made up to that point in the transaction appear to be silently dropped. I receive no error message indicating that they were dropped, and when I commit the transaction at the end no error is raised... but when I go to look in the tables that were supposed to be updated in the transaction, only the new columns are there. None of the non-schema changes made are saved.
Looking on the net for answers has, thus far, proved to be a waste of a couple hours... so I turn here for help. Has anyone ever tried to perform a transaction through ADO that both updates the schema of a table and updates rows in tables (be it that same table, or others)? Is it not allowed? Is there any documentation out there that could be helpful in this situation?
EDIT:
Okay, I did a trace, and these commands were sent to the database (explanations in parenthesis)
(I don't know what's happening here, looks like it's creating a temporary stored procedure...?)
declare @p1
int set @p1=180150003 declare @p3 int
set @p3=2 declare @p4 int set @p4=4
declare @p5 int set @p5=-1
(Retreiving the table that holds definition information for the user-generated fields)
exec sp_cursoropen @p1 output,N'SELECT * FROM CustomFieldDefs ORDER BY Sequence',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5
go
(I think my code was iterating through the list of them here, grabbing the current information)
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,1025,1,1
go
exec sp_cursorfetch 180150003,1028,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
(This appears to be where I'm entering the modified data for the definitions, I go through each and update any changes that occurred in the definitions for the custom fields themselves)
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=1,@Description='asdf',@Format='U|',@IsLookUp=1,@Length=50,@Properties='U|',@Required=1,@Title='__asdf',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=2,@Description='give',@Format='Y',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_give',@Type='B',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=3,@Description='up',@Format='###-##-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_up',@Type='N',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=4,@Description='Testy',@Format='',@IsLookUp=0,@Length=50,@Properties='',@Required=0,@Title='_Testy',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=5,@Description='you',@Format='U|',@IsLookUp=0,@Length=250,@Properties='U|',@Required=0,@Title='_you',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=6,@Description='never',@Format='mm/dd/yyyy',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_never',@Type='D',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=7,@Description='gonna',@Format='###-###-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_gonna',@Type='C',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
(This is where my code removes the deleted through the interface before this saving began]... it is also the ONLY thing as far as I can tell that actually happens during this transaction)
ALTER TABLE CustomizableTable DROP COLUMN _weveknown;
(Now if any of the definitions were altered in such a way that the user-created column's properties need to be changed or indexes on the columns need to be added/removed, it is done here, along with giving a default value to any rows that didn't have a value yet for the given column... note that, as far as I can tell, NONE of this actually happens when the stored procedure finishes.)
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '__asdf'
go
ALTER TABLE CustomizableTable ALTER COLUMN __asdf VarChar(50) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable (
__asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF);
go
select * from IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON
CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF);
go
UPDATE CustomizableTable SET [__asdf] = '' WHERE [__asdf] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_give'
go
ALTER TABLE CustomizableTable ALTER COLUMN _give Bit NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__give') DROP INDEX idx__give ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_give] = 0 WHERE [_give] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_up'
go
ALTER TABLE CustomizableTable ALTER COLUMN _up Int NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__up') DROP INDEX idx__up ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_up] = 0 WHERE [_up] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_Testy'
go
ALTER TABLE CustomizableTable ADD _Testy VarChar(50) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__Testy') DROP INDEX idx__Testy ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_Testy] = '' WHERE [_Testy] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_you'
go
ALTER TABLE CustomizableTable ALTER COLUMN _you VarChar(250) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__you') DROP INDEX idx__you ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_you] = '' WHERE [_you] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_never'
go
ALTER TABLE CustomizableTable ALTER COLUMN _never DateTime NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__never') DROP INDEX idx__never ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_never] = '1/1/1900' WHERE [_never] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_gonna'
go
ALTER TABLE CustomizableTable ALTER COLUMN _gonna Money NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__gonna') DROP INDEX idx__gonna ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_gonna] = 0 WHERE [_gonna] IS NULL
go
(Closing the Transaction...?)
exec sp_cursorclose 180150003
go
After all that ado above, only the deletion of the column occurs. Everything before and after it in the transaction appears to be ignored, and there were no messages in the SQL Trace to indicate that something went wrong during the transaction.
A: The code is using a server-side cursor, that's what those calls are for. The first set of calls is preparing/opening the cursor. Then fetching rows from the cursor. Finally closing the cursor. Those sprocs are analogous to the OPEN CURSOR, FETCH NEXT, CLOSE CURSOR T-SQL statements.
I'd have to take a closer look (which I will), but my guess is there is something going on with the server-side cursor, the encapsulating transaction, and the DDL.
Some more questions:
*
*Are you meaning to use server-side cursors in this case?
*Are the ADO Commands all using the same active connection?
Update:
I'm not exactly sure what's going on.
It looks like you're using server-side cursors so you can use Recordset.Update() to push changes back to the server, in addition to executing generated SQL statements to alter schema and update data in the dynamic table(s). Using the same connection, inside an explicit transaction.
I'm not sure what effect the cursor operations will have on the rest of the transaction, or vice-versa, and to be honest I'm surprised this isn't working.
I don't know how large of a change it would be, but I would recommend moving away from the server-side cursors and building the UPDATE statements for your table updates.
Sorry I couldn't be of more help.
BTW- I found the following information on the sp_cursor calls:
http://jtds.sourceforge.net/apiCursors.html
A: The behavior you describe is allowed. How is the code making the schema changes? Building SQL on the fly and executing through an ADO Command? Or using ADOX?
If you have access to the database server, try running a SQL Profiler trace while testing the scenario you outlined. See if the trace logs any errors/rollbacks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are some good examples of a WS-Eventing client in Java? There are a few web service frameworks available for Java: Axis2, CXF, JBossWS, and Metro. Does anyone have some good examples of a WS-Eventing client with these frameworks?
A: Check out Apache Savan. It's was a publisher/subscriber implementation for Axis2 that supported WS-Eventing (see sample.eventing.Client for an example client) but was retired in 2014.
JBossWS has some information about setting up a service here, but I didn't see any example for a client. Regarding CXF is includes support for eventing although it uses native types, nothing from JAX-WS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When should you use full-text indexing? We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner:
SELECT *
FROM customer
WHERE fname LIKE '%someName%'
Does full-text indexing help in the scenario? We're using SQL Server 2005.
A: According to my test scenario:
*
*SQL Server 2008
*10.000.000 rows each with a string like "wordA wordB
wordC..." (varies between 1 and 30 words)
*selecting count(*) with CONTAINS(column, "wordB")
*result size several hundred thousands
*catalog size approx 1.8GB
Full-text index was in range of 2s whereas like '% wordB %' was in range of 1-2 minutes.
But this counts only if you don't use any additional selection criteria! E.g. if I used some "like 'prefix%'" on a primary key column additionally, the performance was worse since the operation of going into the full-text index costs more than doing a string search in some fields (as long those are not too much).
So I would recommend full-text index only in cases where you have to do a "free string search" or use some of the special features of it...
A: It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use the full-text functions. (e.g. MATCH/AGAINST in mySQL or FREETEXT/CONTAINS in MS SQL)
Here is two good articles on when, why, and how to use full-text indexing in SQL Server:
*
*How To Use SQL Server Full-Text Searching
*Solving Complex SQL Problems with Full-Text Indexing
A: To answer the question specifically for MSSQL, full-text indexing will NOT help in your scenario.
In order to improve that query you could do one of the following:
*
*Configure a full-text catalog on the column and use the CONTAINS() function.
*If you were primarily searching with a prefix (i.e. matching from the start of the name), you could change the predicate to the following and create an index over the column.
where fname like 'prefix%'
(1) is probably overkill for this, unless the performance of the query is a big problem.
A: FTS can help in this scenario, the question is whether it is worth it or not.
To begin with, let's look at why LIKE may not be the most effective search. When you use LIKE, especially when you are searching with a % at the beginning of your comparison, SQL Server needs to perform both a table scan of every single row and a byte by byte check of the column you are checking.
FTS has some better algorithms for matching data as does some better statistics on variations of names. Therefore FTS can provide better performance for matching Smith, Smythe, Smithers, etc when you look for Smith.
It is, however, a bit more complex to use FTS, as you'll need to master CONTAINS vs FREETEXT and the arcane format of the search. However, if you want to do a search where either FName or LName match, you can do that with one statement instead of an OR.
To determine if FTS is going to be effective, determine how much data you have. I use FTS on a database of several hundred million rows and that's a real benefit over searching with LIKE, but I don't use it on every table.
If your table size is more reasonable, less than a few million, you can get similar speed by creating an index for each column that you're going to be searching on and SQL Server should perform an index scan rather than a table scan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
} |
Q: Best way to send an email from a .NET application? I'm working on a Windows Forms (.NET 3.5) application that has a built-in exception handler to catch any (heaven forbid) exceptions that may arise. I'd like the exception handler to be able to prompt the user to click a Send Error Report button, which would then cause the app to send an email to my FogBugz email address.
What's the best way to do this, and are there any "gotchas" to watch out for?
A: You shouldn't need to worry about client credentials and just use the SmtpClient as suggested by Esteban. You will need the user to provide a valid Smtp server url at configuration, but most ISPs allow anonymous smtp providing you are on their network (one of their clients) - as long as the user puts in the url for their ISPs smptp server then most people wouldn't have any problems.
Note: There is a predefined section of the .config file for storing the configuration options for the SmtpClient object. If you put the settings in there you don't have to explicitly set anything in you code when sending an email. An example of the section is below:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="[email protected]">
<network host="smtp.somewhere.com.au" />
</smtp>
</mailSettings>
</system.net>
The user name and password are optional. Intellisense works for these parts of the config file.
Edit: slight correction to my code example.
A: You'll want to use the SmtpClient class as outlined here.
There are no gotchas - sending email is about as easy as it gets.
A: In a controlled environment, using SmtpClient would be the answer. But on a user's machine you would need an SMTP server to send through.
You could prompt the user for their SMTP credentials, but I think that would be impractical for your case. As a user, I would not want to provide my SMTP credentials to a random app (think SPAM). You also don't want to hard-code your own SMTP credentials into the app, it would be trivial for a malicious user to sniff those credentials and use your server to send SPAM.
Ideally you would be able to use the user's mail agent to send the email. I was thinking you might be able to formulate and execute a mailto: URL, but I'm not sure if you'd be able to specify the body or any attachments for the message.
A: You mentioned you're using Fogbugz.
Try http://www.fogcreek.com/FogBugz/docs/60/topics/customers/BugzScout.html?isl=59722
or http://www.fogcreek.com/FogBugz/blog/post/C-wrapper-for-the-FogBugz-API.aspx?isl=59722
There is some sample code around, I think in your FB install directory.
I checked with Michael Pryor re: licensing and he said it was fine to use their code, but YMMV, so I'd check.
It provides a good starting point.
A: You might also want to check out the 3rd party aspNetEmail library, which has a lot of useful features to offer above what System.Net.Mail gives you.
A:
You'll want to use the SmtpClient class as outlined here.
There are no gotchas - sending email is about as easy as it gets.
An extensive System.Net.Mail FAQ is located here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What exactly is "managed" code? I've been writing C / C++ code for almost twenty years, and I know Perl, Python, PHP, and some Java as well, and I'm teaching myself JavaScript. But I've never done any .NET, VB, or C# stuff. What exactly does managed code mean?
Wikipedia describes it simply as
Code that executes under the management of a virtual machine
and it specifically says that Java is (usually) managed code, so
*
*why does the term only seem to apply to C# / .NET?
*Can you compile C# into a .exe that contains the VM as well, or do you have to package it up and give it to another .exe (a la java)?
In a similar vein,
*
*is .NET a language or a framework, and what exactly does "framework" mean here?
OK, so that's more than one question, but for someone who's been in the industry as long as I have, I'm feeling rather N00B-ish right now...
A: Under .NET and Visual C++ specifically, you can have both Unmanaged and Managed code. The terms refer to the manner in which memory is allocated and 'managed'.
Unmanaged code would be the C++ stuff you're used to. Dynamic memory allocation and explicit freeing of the memory. The .NET runtime does not manage the memory for you, hence 'unmanaged'.
Managed code on the other hand IS managed by the run-time. You allocate memory where required (by declaring variables, not memory space) and the run-time garbage collector determines when it's no longer needed and cleans it all up. The garbage collector will also move memory around to improve efficiency. The run-time 'manages' it all for you.
As I mentioned above, it is possible to write code that is both managed and unmanaged.
Unmanaged:
class Bar : public Foo {
private:
int fubar;
public:
Bar(int i) : fubar(i) {}
int * getFubar() { return * fubar; }
}
Managed:
public ref class Bar : public Foo
private:
int fubar;
public:
Bar(int i) : fubar(i) {}
int ^ getFubar() { return ^ fubar; }
}
Notice the ref? That pretty much designates a Managed class. It gets very confusing when you mix the two kinds of code however. For instance, you want to save a reference pointer, (^) the managed equivalent of a pointer, to a Picture Box control within your unmanaged class. Since the garbage collector can move memory around, the next time you try to dereference the picture box it can not be found. The run-time does not tell your unmanaged code about it's memory changes.
Therefore you need to pin down the managed object in memory to allow your unmanaged code to keep track of it. Then there's unboxing and all kinds of other quirks that allow you to intermix the two. Code complexity is enormous!
Officially, managed/unmanaged might come down to the way code executes on the .NET stack. However, if you're coming from a c++ background, I hope this will be a little more relevant to you.
A: When you compile C# code to a .exe, it is compiled to Common Intermediate Language(CIL) bytecode. Whenever you run a CIL executable it is executed on Microsofts Common Language Runtime(CLR) virtual machine. So no, it is not possible to include the VM withing your .NET executable file. You must have the .NET runtime installed on any client machines where your program will be running.
To answer your second question, .NET is a framework, in that it is a set of libraries, compilers and VM that is not language specific. So you can code on the .NET framework in C#, VB, C++ and any other languages which have a .NET compiler.
https://bitbucket.org/brianritchie/wiki/wiki/.NET%20Languages
The above page has a listing of languages which have .NET versions, as well as links to their pages.
A: The term managed is generally applied only to .NET because Microsoft uses the term. Microsoft generally doesn't use the term "virtual machine" in reference to a .NET managed execution environment.
.NET's "bytecode" (IL) is somewhat different from Java bytecode in that it was explicitly designed to be compiled into native code prior to execution in the managed environment, whereas Java was designed to be interpreted, but the concept of platform-independent code is similar.
The ".NET Framework" is basically a huge set of libraries provided by Microsoft, containing thousands of classes that can be used to develop applications.
A compiled C# .exe contains platform-independent code that can be run in any .NET-compatible environment, including Mono. However, the runtime is generally distributed separately from applications that use it.
A: Managed means that the code is not compiled to native code, and thus runs under the auspices of a virtual machine. Java compiles to an intermediate format called bytecode, which the Java VM knows how to interpret and execute. All the .NET languages do a similar thing, compiling to IL (intermediate language) which the .NET runtime interprets. It's a little confusing because the .NET IL have .dll and .exe file endings.
A: At the risk of offending some, I suspect that the word managed was used so they could use the word unmanaged instead of compiled. While managed may mean more, the reality is it seems to be the used to distinguish mostly between what is pretty much just in time compiling (as the replacement for what was one once interpreted or pcode) and native compiled code.
Or put another way, which would you prefer to use:
a) Unmanaged code that may do uncontrollable things to the system.
b) Native compiled code that is fast, solid and is close to the OS.
Of course, they are actually the same thing.
A:
In a similar vein, is .NET a language or a framework, and what exactly does "framework" mean here? <<
.NET is Microsoft's current enterprise software platform. It consists of:
• A single universal interface for accessing Windows functionality:
o The .NET Framework Class Library (FCL).
o The FCL provides a rich set of high-level functionality for developers.
• A single universal language and runtime for executing .NET applications:
o Common Language Runtime (CLR) executes Common Intermediate Language (CIL).
o The CLR is God: it runs, controls, and polices everything.
• The choice of multiple languages for developing .NET applications:
o Every development language is compiled to CIL, which is run by the CLR.
o C# and VB are the two main development languages.
A: I don't think you are alone in being confused about what .Net is. There are already other answers that should have you covered but I'll throw out this tidbit of info for others.
To see what .Net "really" is simply go to c:\Windows\Microsoft.Net\Framework
In there you'll see folders that are specfic to the version(s) you have installed. Go into the v2.0.xxxxx folder if you have it installed for example.
In that folder is the framework. You will basically see a bunch of .exe files and .dll files. All the DLL files that start with System.*.dll is essentially the .Net framework.
The .exe files you'll see in that folder are utilities for developers as well as compilers. You mentioned C#. Find the csc.exe file. That's your C# compiler.
Building a program is really simple. Throw the following code into a hello.cs file.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello world");
}
}
Then on the command line type> csc hello.cs
That will generate you a .exe file. Run it and it will spit out 'hello world' obviously.
The line that says Console.WriteLine() is calling into the Framework. Console is an object that lives within the System namespace and WriteLine() is a static method.
This is the disassembled code for that Console.WriteLine() method:
[HostProtection(SecurityAction.LinkDemand, UI=true)]
public static void WriteLine(string value)
{
Out.WriteLine(value);
}
When people say things like, "Should I use PHP or .Net?", or "Should I use Python or .Net" you start to see how that's the wrong thing to be discussing. They are obviously comparing a language to a Framework. C# is a language and it is just one of the many languages that can be used to write code on top of the .Net platform. That same method of Console.WriteLine() can be invoked from C#, VB.Net, Pascal, C++, Ruby, Python, F# and any other language that has been made to work on top of the .Net platform.
I hope that helps.
-Keith
A: Mostly its referring to the fact that all of your memory allocations are "managed" for you. If you are using managed code you don't have to worry about freeing your objects when you are done with them. Simply allowing them to go out of scope will mean that the VM will eventually recognize that there are no longer any references to them and will Garbage collect them returning the memory to the system.
Unmanaged code on the other hand will simply "leak" unless you explicitly free your pointers before you discard the references.
A: It's primarily used to describe .NET because that's the term Microsoft chose to differentiate .NET from C/C++ and other older languages. Microsoft chose it because it wasn't a term that was usually associated with Java because they didn't want to emphasize the similarities between C#/.NET and Java (as opposed to calling it something like 'virtual machine code' which would make it sound much more Java like). Basically, the use of "managed code" is marketing driven, rather than technically driven, terminology.
A: .NET is a framework. The Common language Runtime (CLR) executes the Microsoft Intermediate Language (MSIL) code that is generated when a solution is compiled (i.e., it does not compile to machine code). You cannot contain the API within the exe, nor would you want to as it is quite large. The major benefit here is memory management (among some other security advantages and possibly others that I do not know about.)
A: I can answer the framework question. .NET is a framework, C#, VB.NET, etc are languages. Basically .NET provides a common platform of libraries to call (All the System.... dlls) that any language using .NET can call. All the .NET languages are compiled into MSIL (Microsoft Intermediate Language, better known as just IL) which can then be run on any PC with the appropriate .NET framework installed.
A: .NET is a framework.
It can be used from many languages (VB.NET, C#, IronPython, boo, etc)
.NET always executes as interpreted, and no you cannot include the 'VM' inside the .exe. Any user wishing to run your .NET app must have the framework installed.
A: It can refer to any code executed by a virtual machine rather than directly by the CPU.
I think this enables things like garbage collection and array bounds checking.
A: Personally, I think the word "framework" is a bit of a misnomer.
.NET is a "platform", consisting of an execution environment (the CLR virtual machine) and a set of libraries. It's exactly analogous to Java or Perl or Python (none of which are ever referred to as "frameworks").
In most cases, the word "framework" is used for projects like Spring or Struts or QT, which sit on top of a platform (ie, providing no execution environment of their own) like a library.
But unlike a "library", a framework seeks to re-define the fundamental operations of the underlying platform. (Spring's dependency injection defies the constructor-calling logic of ordinary Java code. QT's signals-and-slots implementation defies ordinary C++ code.)
I know I'm just being a pedantic bastard, but to me, .NET is not a framework. It's a platform.
A: Managed Code--MSIL and IL and Managed Code are same.When we build our application the .dll or .exe files are generated in the Bin folder.These files are called as Managed code.Later these files are given to CLR to generate Native code which would be understood by OS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
} |
Q: Top ten ordering in Excel based on complex team rules I have an excel spreadsheet in a format similar to the following...
| NAME | CLUB | STATUS | SCORE |
| Fred | a | Gent | 145 |
| Bert | a | Gent | 150 |
| Harry | a | Gent | 195 |
| Jim | a | Gent | 150 |
| Clare | a | Lady | 99 |
| Simon | a | Junior | 130 |
| John | b | Junior | 130 |
:
:
| Henry | z | Gent | 200 |
I need to convert this table into a list of the "Top Ten" teams. The rules are
*
*Each team score is taken from the sum of four members of that club.
*These totals should be of the best four scores except...
*
*Each team must consist of at least one Junior or Lady
For example in the table above the team score for club A would be 625 not 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents.
My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural?
Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet.
A: Public Function TopTen(Club As String, Scores As Range)
Dim i As Long
Dim vaScores As Variant
Dim bLady As Boolean
Dim lCnt As Long
Dim lTotal As Long
vaScores = FilterOnClub(Scores.Value, Club)
vaScores = SortOnScore(vaScores)
For i = LBound(vaScores, 2) To UBound(vaScores, 2)
If lCnt = 3 And Not bLady Then
If vaScores(3, i) <> "Gent" Then
lTotal = lTotal + vaScores(4, i)
bLady = True
lCnt = lCnt + 1
End If
Else
lTotal = lTotal + vaScores(4, i)
lCnt = lCnt + 1
If vaScores(3, i) <> "Gent" Then bLady = True
End If
If lCnt = 4 Then Exit For
Next i
TopTen = lTotal
End Function
Private Function FilterOnClub(vaScores As Variant, sClub As String) As Variant
Dim i As Long, j As Long
Dim aTemp() As Variant
For i = LBound(vaScores, 1) To UBound(vaScores, 1)
If vaScores(i, 2) = sClub Then
j = j + 1
ReDim Preserve aTemp(1 To 4, 1 To j)
aTemp(1, j) = vaScores(i, 1)
aTemp(2, j) = vaScores(i, 2)
aTemp(3, j) = vaScores(i, 3)
aTemp(4, j) = vaScores(i, 4)
End If
Next i
FilterOnClub = aTemp
End Function
Private Function SortOnScore(vaScores As Variant) As Variant
Dim i As Long, j As Long, k As Long
Dim aTemp(1 To 4) As Variant
For i = 1 To UBound(vaScores, 2) - 1
For j = i To UBound(vaScores, 2)
If vaScores(4, i) < vaScores(4, j) Then
For k = 1 To 4
aTemp(k) = vaScores(k, j)
vaScores(k, j) = vaScores(k, i)
vaScores(k, i) = aTemp(k)
Next k
End If
Next j
Next i
SortOnScore = vaScores
End Function
Use as =TopTen(H2,$B$2:$E$30) where H2 contains the club letter.
A:
can this be done easily as a series of
Excel formula
Short answer, YES. (Depending on your definition of "easily").
Long answer...
(I think this works)
Here's my (brief) test data:
A B C D
1 NAME CLUB STATUS SCORE
2 Kevin a Gent 145
3 Lyle a Gent 150
4 Martin a Gent 195
5 Norm a Gent 150
6 Oonagh a Lady 100
7 Arthur b Gent 200
8 Brian b Gent 210
9 Charlie b Gent 190
10 Donald b Gent 220
11 Eddie b Junior 150
12 Quentin c Gent 145
13 Ryan c Gent 150
14 Sheila c Lady 195
15 Trevor c Gent 150
16 Ursula c Junior 200
Now, if I've understood the rules correctly, we want the best four scores, except that if the highest score by either a lady or a junior is not in the best four, we use that instead of the fourth highest. I've restated it somewhat, for reasons that may become apparent...
OK. Array formulae to the rescue! (I hope)
The highest score from team a should be
{=LARGE(IF(B2:B16="a",D2:D16,0),1)}
where the {} indicates an array formula created by using Control-Shift-Enter to input the formula. The top four are similarly created. For the Lady/Junior bit, we need a bit more complexity. Taking the Lady, we need this:
{=LARGE(IF($B$2:$B$16=$J3,IF($C$2:$C$16="Lady",$D$2:$D$16,0),0),1)}
Junior may safely be left as an exercise for the student, I hope.
I'm now looking at a table with the following layout for club "a"
J K L M N O P
1 Club 1 2 3 4 Lady Junior
2 a 195 150 150 145 100 0
The club score should be the top three "anyone" scores plus the best lady or junior if they're not already in the top four.
So in Q2 I'm putting this:
=SUM(K2:M2)+MIN(MAX(O2,P2),N2)
MAX(O2,P2) tells me the best lady or junior score, which has to be included. If it's higher than the fourth-highest team score, then it's already in the list and we just take the top four. Otherwise, we replace the fourth-highest score with the best lady/junior one.
Now we could do it all in one formula, by substituting the parts into the final formula:
{=LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),1)+
LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),2)+
LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),3)+
MIN(LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),4),
MAX(LARGE(IF($B$2:$B$18=$J3,IF($C$2:$C$18="Lady",$D$2:$D$18,0),0),1),
LARGE(IF($B$2:$B$18=$J3,IF($C$2:$C$18="Junior",$D$2:$D$18,0),0),1)))}
But I don't recommend it...
So for the above data, I end up with this:
Anyone Lady Junior
Club 1 2 3 4 1 1 Total
a 195 150 150 145 100 0 595
b 220 210 200 190 0 150 780
c 200 195 150 150 195 200 695
Rats. In my excitement at (I think) getting the hard part to work I forgot to mention that
*
*The list of scores can be in any order
*You can get the club rankings with RANK()
*You can then pull the top 10 into another table using MATCH() and INDEX()
A B C D E F G H
1 club Sc Rank UniqRk Pos Club Score
2 third-equal#1 80 3 79.999980 1 1 best 100
3 second 90 2 89.999970 2 2 second 90
4 third-equal#2 80 3 79.999960 3 3 third-equal#1 80
5 best 100 1 99.999950 4 3 third-equal#2 80
6 worst 70 5 69.999940 5 5 worst 70
Columns A and B are our calculated scores, column E is the order in which clubs will be output in the final table. The other formulae are as follows:
C: =RANK(B2,$B$2:$B$6) # what it says, with ties both getting the lower number
D: =B2-ROW()*0.00001 # score, modified slightly to ensure uniqueness
F: =SMALL($C$2:$C$6,E2) # first output column, ranks including ties
G: =INDEX($A$2:$A$6,MATCH(LARGE($D$2:$D$6,E2),$D$2:$D$6,0))
# club name for position, using the modified score in D
H: =INDEX($B$2:$B$6,MATCH(LARGE($D$2:$D$6,E2),$D$2:$D$6,0))
# as G, but indexes into scores
A: What I do is lame, but it works.
Just make a new column then insert this formula =If(a1=N,b1,0) where A1 is criteria column, N is criteria and B1 is in the column that you are trying to get the large from. Then I just do the large formula in another column.
Sometimes I get all fancy and instead of rolling out a N, I will make it say $C$1, then spell out the criteria in that cell.
The perfect answer would be to have Microsoft add in a largeifs (please read this Microsoft)
A: Use a pivot table which will act as a database query on the data you have. Pivot so that the teams go down the columns and team members along with their status type go across the pivot table. I'm not sure for 2003, but Excel 2007 lets you then sort so the highest scores appear to the left. Then your first sum can simply take the first three scores for the each team. However to get the last persons sum, you have to determine if you can use the 4th score, or if you have to use the max of the junior or Lady types. That could be done using a complex and brute force formula somewhat like this:
if (type of position 1 is a junior or a lady or ... 2 or 3... ) then use position 4 else if position 5 is a junior or lady then use 5 else if p 6 is ... and so on.
A: Writing a solution in VBA would be my first choice, especially if the rules have the possibility of becoming more complex.
A: I don't think that this can be done unless the table is sorted in some way. Most of Excel's lookup functions require ordered lists. This could certainly be done with a VBA function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Understanding .Net Configuration Options I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain.
So, for example, some of the applications I work with use settings which we access with:
string blah = AppLib.Properties.Settings.Default.TemplatePath;
Now, this option seems cool because the members are stongly typed, and I won't be able to type in a property name that doesn't exist in the Visual Studio 2005 IDE. We end up with lines like this in the App.Config of a command-line executable project:
<connectionStrings>
<add name="AppConnectionString" connectionString="XXXX" />
<add name="AppLib.Properties.Settings.AppConnectionString" connectionString="XXXX" />
</connectionStrings>
(If we don't have the second setting, someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek)
We also have settings accessed like this:
string blah = System.Configuration.ConfigurationManager.AppSettings["TemplatePath_PDF"];
Now, these seem cool because we can access the setting from the dll code, or the exe / aspx code, and all we need in the Web or App.config is:
<appSettings>
<add key="TemplatePath_PDF" value="xxx"/>
</appSettings>
However, the value of course may not be set in the config files, or the string name may be mistyped, and so we have a different set of problems.
So... if my understanding is correct, the former methods give strong typing but bad sharing of values between the dll and other projects. The latter provides better sharing, but weaker typing.
I feel like I must be missing something. For the moment, I'm not even concerned with the application being able to write-back values to the configuration files, encryption or anything like that. Also, I had decided that the best way to store any non-connection strings was in the DB... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues, so they must be stored outside the DB!
A: If you use the settings tab in VS 2005+, you can add strongly typed settings and get intellisense, such as in your first example.
string phoneNum = Properties.Settings.Default.EmergencyPhoneNumber;
This is physically stored in App.Config.
You could still use the config file's appSettings element, or even roll your own ConfigurationElementCollection, ConfigurationElement, and ConfigurationSection subclasses.
As to where to store your settings, database or config file, in the case of non-connection strings: It depends on your application architecture. If you've got an application server that is shared by all the clients, use the aforementioned method, in App.Config on the app server. Otherwise, you may have to use a database. Placing it in the App.Config on each client will cause versioning/deployment headaches.
A: Nij, our difference in thinking comes from our different perspectives. I'm thinking about developing enterprise apps that predominantly use WinForms clients. In this instance the business logic is contained on an application server. Each client would need to know the phone number to dial, but placing it in the App.config of each client poses a problem if that phone number changes. In that case it seems obvious to store application configuration information (or application wide settings) in a database and have each client read the settings from there.
The other, .NET way, (I make the distinction because we have, in the pre .NET days, stored application settings in DB tables) is to store application settings in the app.config file and access via way of the generated Settings class.
I digress. Your situation sounds different. If all different apps are on the same server, you could place the settings in a web.config at a higher level. However if they are not, you could also have a seperate "configuration service" that all three applications talk to get their shared settings. At least in this solution you're not replicating the code in three places, raising the potential of maintenance problems when adding settings. Sounds a bit over engineered though.
My personal preference is to use strong typed settings. I actually generate my own strongly typed settings class based on what it's my settings table in the database. That way I can have the best of both worlds. Intellisense to my settings and settings stored in the db (note: that's in the case where there's no app server).
I'm interested in learning other peoples strategies for this too :)
A: I think your confusion comes from the fact that it looks like your first example is a home-brewed library, not part of .NET.
The configurationmanager example is an example of built-in functionality.
A: I support Rob Grays answer, but wanted to add to it slightly. This may be overly obvious, but if you are using multiple clients, the app.config should store all settings that are installation specific and the database should store pretty much everything else.
Single client (or server) apps are somewhat different. Here it is more personal choice really. A noticable exception would be if the setting is the ID of a record in the database, in which case I would always store the setting in the database with a foreign key to ensure the reference doesn't get deleted.
A: Yes - I think I / we are in the headache situation Rob descibes - we have something like 5 or 6 different web-sites and applications across three independent servers that need to access the same DB. As things stand, each one has its own Web or App.config with the settings described setting and / or overriding settings in our main DB-access dll library.
Rob - when you say application server, I'm not sure what you mean? The nearest thing I can think is that we could at least share some settings between sites on the same machine by putting them in a web.config higher in the directory hierarchy... but this too is not something I've been able to investigate... having thought it more important to understand which of the strong or weak-typed routes is 'better'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: When to use HtmlControls vs WebControls I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees.
I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality.
Also, it looks weird to have code that mixes and matches:
<asp:Button id='btnOK' runat='server' Text='OK' />
<input id='btnCancel' runat='server' type='button' value='Cancel' />
(The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div)
Is there some definitive style guide out there? Should HtmlControls just be avoided?
A: It might be useful to think of HTML controls as an option when you want more control over the mark up that ends up getting emitted by your page. More control in the sense that you want EVERY browser to see exactly the same markup.
If you create System.Web.UI.HtmlControls like:
<input id='btnCancel' runat='server' type='button' value='Cancel' />
Then you know what kind of code is going to be emitted. Even though most of the time:
<asp:Button id='btnCancel' runat='server' Text='Cancel' />
will end up being the same markup. The same markup is not always emitted for all WebControls. Many WebControls have built in adaptive rendering that will render different HTML based on the browser user agent. As an example a DataGrid will look quite different in a mobile browser than it will in a desktop browser.
Using WebControls as opposed to HtmlControls also lets you take advantage of ASP.NET v2.0 ControlAdapters which I believe only works with WebControls, this will allow you programatic config driven control over the markup that gets emitted.
This might seem more valuable when you consider that certain mobile browsers or WebTVs are going to want WML or completely different sets of markups.
A: In my experience, there's very little difference. As Darren said, if you don't need server-side functionality, HTML controls are probably lower-impact.
And don't forget, you can bolt server-side functionality onto almost any HTML control just by adding a runat="server" directive and an ID to it.
A: well... i wouldn't use an html control if you don't need to do anything on it on the server. i would do
<input id='btnCancel' type='button' value='Cancel' />
fin.
A: By adding runat="server" you can get access to any HTML controls in server side..
and I believe HTML controls are less weight compared to ASP.NET server controls..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Writing into excel file with OLEDB Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:
OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection);
dbCmd.CommandTimeout = mTimeout;
results = dbCmd.ExecuteNonQuery();
But I get an OleDbException thrown with message:
"Cannot modify the design of table
'test$'. It is in a read-only
database."
My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?
A: You need to add ReadOnly=False; to your connection string
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";
A: I also had the same problem. Only remove the extended property IMEX=1. That will solve your problem. Your table will be created in your Excel file...
A: I was also looking for and answer but Zorantula's solution didn't work for me.
I found the solution on http://www.cnblogs.com/zwwon/archive/2009/01/09/1372262.html
I removed the ReadOnly=false parameter and the IMEX=1 extended property.
The IMEX=1 property opens the workbook in import mode, so structure-modifying commands (like CREATE TABLE or DROP TABLE) don't work.
My working connection string is:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=workbook.xls;Mode=ReadWrite;Extended Properties=\"Excel 8.0;HDR=Yes;\";"
A: A couple questions:
*
*Does the user that executes your app (you?) have permission to write to the file?
*Is the file read-only?
*What is your connection string?
If you're using ASP, you'll need to add the IUSER_* user as in this example.
A: *
*How do I check the permissions for writing to an excel file for my application (I'm using excel 2007)?
*The file is not read only, or protected (to my knowledge).
*My connection String is:
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=fifa_ng_db.xls;Mode=ReadWrite;Extended
Properties=\"Excel
8.0;HDR=Yes;IMEX=1\""
A: Further to Michael Haren's answer. The account you will need to grant Modify permissions to the XLS file will likely be NETWORK SERVICE if this code is running in an ASP.NET application (it's specified in the IIS Application Pool). To find out exactly what account your code is running as, you can do a simple:
Response.Write(Environment.UserDomainName + "\\" + Environment.UserName);
A: I was running under ASP.NET, and encountered both "Cannot modify the design..." and "Cannot locate ISAM..." error messages.
I found that I needed to:
a) Use the following connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Mode=ReadWrite;Extended Properties='Excel 8.0;HDR=Yes;';Data Source=" + {path to file};
Note I too had issues with IMEX=1 and with the ReadOnly=false attributes in the connection string.
b) Grant EVERYONE full permissions to the folder in which the file was being written. Normally, ASP.NET runs under the NETWORK SERVICE account, and that already had permissions. However, the OleDb code is unmanaged, so it must run under some other security context. (I am currently too lazy to figure out which account, so I just used EVERYONE.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What is the overhead cost associated with IoC containers like StructureMap? After attending a recent Alt.NET group on IoC, I got to thinking about the tools available and how they might work. StructureMap in particular uses both attributes and bootstrapper concepts to map requests for IThing to ConcreteThing. Attributes automatically throw up flags for me that either reflection or IL injection is going on. Does anyone know exactly how this works (for StructureMap or other IoC tools) and what the associated overhead might be either at run-time or compile-time?
A: 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.
A: I use Windsor from the CastleProject and have found it immensely useful in reducing dependencies. I haven't noticed a performance issue yet but one thing I do find is that the configuration can get a bit cumbersome. To help in this regard I'm starting to look at Binsor, which is a DSL for Windsor written in boo.
Another thing to be aware of is that when navigating code you wont be able to go to the code that will be executing at runtime.
A: They major problem is that code becomes hard to understand. It might become pure magical if one overuse IoC. Another problem is performance. In most cases performance lost is not noticeable. But when you start creating most of your objects via IoC container, it can suddenly drop below ocean level.
A: I built a very lightweight and basic IOC, here:
http://blogs.microsoft.co.il/blogs/shay/archive/2008/09/30/building-custom-object-mapper.aspx
It's not an alternative to the libraries You mentioned but if all that You need is to resolve a type by giving its interface it might be a perfect solution.
I don't handle instantiation types (singleton, transient, thread, pool...), all object will be instantiated as singletons, you call it like:
IRepository _repository = ObjectFactory.BuildFactory<IRepository>();
Shay
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the difference between dllexport and dllimport? I'm just looking for a simple, concise explanation of the difference between these two. MSDN doesn't go into a hell of a lot of detail here.
A: __declspec( dllexport ) - The class or function so tagged will be exported from the DLL it is built in. If you're building a DLL and you want an API, you'll need to use this or a separate .DEF file that defines the exports (MSDN). This is handy because it keeps the definition in one place, but the .DEF file provides more options.
__declspec( dllimport ) - The class or function so tagged will be imported from a DLL. This is not actually required - you need an import library anyway to make the linker happy. But when properly marked with dllimport, the compiler and linker have enough information to optimize the call; without it, you get normal static linking to a stub function in the import library, which adds unnecessary indirection. ONT1 ONT2
A: *
*__declspec(dllexport) tells the linker that you want this object to be made available for other DLL's to import. It is used when creating a DLL that others can link to.
*__declspec(dllimport) imports the implementation from a DLL so your application can use it.
I'm only a novice C/C++ developer, so perhaps someone's got a better explanation than I.
A: Two different use cases:
1) You are defining a class implementation within a dll. You want another program to use the class. Here you use dllexport as you are creating a class that you wish the dll to expose.
2) You are using a function provided by a dll. You include a header supplied with the dll. Here the header uses dllimport to bring in the implementation to be used by the current program.
Often the same header file is used in both cases and a macro defined. The build configuration defines the macro to be import or export depending which it needs.
A: Dllexport is used to mark a function as exported. You implement the function in your DLL and export it so it becomes available to anyone using your DLL.
Dllimport is the opposite: it marks a function as being imported from a DLL. In this case you only declare the function's signature and link your code with the library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
} |
Q: Building Flex projects in ant/nant 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 FlexBuilder/eclipse and the build machine is using the command line compilers. Inevitably, the {projectname}-config.xml 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.
We started down the path of writing a utility program to convert FlexBuilder's project files into a {projectname}-config.xml file, but it's a) undocumented and b) a horrible hack.
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.
Tomorrow, we are going to discuss a couple of options, neither of which I'm terribly fond of:
a) Add a post check-in event to Subversion to remove these absolute references, or
b) add a pre-build process that removes the absolute reference.
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?
A: 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:
<!– 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}”/>
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.
HTH
A: While not a solution to your specific problem, a workaround is to use a continuous integration server.
Using something like Cruise Control you can have an automated build kick off every time someone submits something to source control. Then if the build fails for any reason (including environment inconsistencies) it's up to the developer who broke it to fix it. You can configure it to send emails on failure/success in various ways.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Open a URL from Windows Forms I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser.
What is the best way to open a URL in the user's default browser from a Windows Forms application?
A: I like approach described here. It takes into account possible exceptions and delays when launching the browser.
For best practice make sure you don't just ignore the exception, but catch it and perform an appropriate action (for example notify user that opening the browser to navigate him to the url failed).
A: using System.Diagnostics;
Process.Start("http://www.google.com/");
This approach has worked for me, but I could be missing something important.
A: For those getting a "Win32Exception: The System cannot find the file specified"
This should do the work:
ProcessStartInfo psInfo = new ProcessStartInfo
{
FileName = "https://www.google.com",
UseShellExecute = true
};
Process.Start(psInfo);
UseShellExecute is descriped further here
For me the issue was due to the .NET runtime as descriped here
A: This article will walk you through it.
Short answer:
ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/");
Process.Start(sInfo);
A: Here is the best of both worlds:
Dim sInfo As New ProcessStartInfo("http://www.mysite.com")
Try
Process.Start(sInfo)
Catch ex As Exception
Process.Start("iexplore.exe", sInfo.FileName)
End Try
I found that the answer provided by Blorgbeard will fail when a desktop application is run on a Windows 8 device. To Camillo's point, you should attempt to open this with the user's default browser application, but if the browswer application is not assigned, an unhandled exception will be thrown.
I am posting this as the answer since it handles the exception while still attempting to open the link in the default browser.
A: The above approach is perfect, I would like to recommend this approach to where you can pass your parameters.
Process mypr;
mypr = Process.Start("iexplore.exe", "pass the name of website");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "84"
} |
Q: How to embed command shell in Visual Studio I would like to be able to embed a command line interpreter inside a dockable window in Visual Studio. Is there any nice way to do this?
A: See the VS Command shell project
A: Checkout Open Command Line by Mads Kristensen. note it doesn't really "embed" the shell in VS, rather it adds a keyboard shortcut to open the shell at the project directory
it supports bash, powershell, git bash, ...etc
A: In Visual Studio click Tools -> NuGet Package Manager -> Package Manager Console
It embeds a cmd prompt with everything on your %PATH% you'd expect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Loading different versions of the same assembly Using reflection, I need to load 2 different versions of the same assembly. Can I load the 2 versions in 2 different AppDomains in the same process?
I need to do some data migration from the old version of the app to the new version.
Please let me know if this is possible or should I use 2 separate processes.
A: UPDATE: I thought I will post my findings as an answer. Reflection proved too complex in terms of development effort, tracking run time errors etc. I remember doing a different approach using 2 different processes when faced with a similar situation long time back (Thank you Brandon).
This is the plan: Nothing elegant but easier in terms of development and troubleshooting. Since it is a one time job, we just have to make it work.
Host a remoting process (which i call the server) having the new version of the application. A remoting client has references for the older version.
Remoting client instantiates and loads the objects with data required for migration.
Convert the old objects into common serializable objects and pass as parameters to the server.
Remoting Server uses the common data to instantiate and load the new objects. Invokes the functions on the new types to persist their data.
A: If you are doing it at design time (which you indicate you are not) this should help you:
http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx
If you are doing it dynamically through reflection (looks like the case here) this might help you:
https://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: How did my process exit? From C# on a Windows box, is there a way to find out how a process was stopped?
I've had a look at the Process class, managed to get a nice friendly callback from the Exited event once I set EnableRaisingEvents = true; but I have not managed to find out whether the process was killed or whether it exited naturally?
A: Fire up Process Monitor (from Sysinternals, part of Microsoft), run your process and let it die, then filter the Process Monitor results by your process name -- you will be able to see everything that it did, including exit codes.
A: You can use the return code of the process for that. If your process returns a non-zero value from its Main method, you can then check whether or not the process exited by itself (the return value matches).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I replace newline characters using JSP and JSTL? I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.
A: This solution is more elegant than your own solution which is setting the pagecontext attribute directly. You should use the <c:set> tag for this:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="newLine" value="\n"/>
${fn:replace(data, newLine, "; ")}
BTW: ${fn:replace(data, "\n", ";")} does NOT work.
A: Here is a solution I found. It doesn't seem very elegant, though:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<% pageContext.setAttribute("newLineChar", "\n"); %>
${fn:replace(item.comments, newLineChar, "; ")}
A: You could create your own JSP function.
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html
This is roughly what you need to do.
Create a tag library descriptor file
/src/META-INF/sf.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>sf</short-name>
<uri>http://www.stackoverflow.com</uri>
<function>
<name>clean</name>
<function-class>com.stackoverflow.web.tag.function.TagUtils</function-class>
<function-signature>
java.lang.String clean(java.lang.String)
</function-signature>
</function>
</taglib>
Create a Java class for the functions logic.
com.stackoverflow.web.tag.function.TagUtils
package com.stackoverflow.web.tag.function;
import javax.servlet.jsp.tagext.TagSupport;
public class TagUtils extends TagSupport {
public static String clean(String comment) {
return comment.replaceAll("\n", "; ");
}
}
In your JSP you can access your function in the following way.
<%@ taglib prefix="sf" uri="http://www.stackoverflow.com"%>
${sf:clean(item.comments)}
A: This does not work for me:
<c:set var="newline" value="\n"/>
${fn:replace(data, newLine, "; ")}
This does:
<% pageContext.setAttribute("newLineChar", "\n"); %>
${fn:replace(item.comments, newLineChar, "; ")}
A: If what you really need is a \n symbol you can use the advice from here:
${fn:replace(text, "
", "<br/>")}
or
<c:set var="nl" value="
" /><%-- this is a new line --%>
This includes the new line in your string literal.
A: You should be able to do it with fn:replace.
You will need to import the tag library into your JSP with the following declaration:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Then you can use the following expression to replace occurrences of newline in ${data} with a semicolon:
${fn:replace(data, "\n", ";")}
The documentation is not great on this stuff and I have not had the opportunity to test it.
A: \n does not represent the newline character in an EL expression.
The solution which sets a pageContext attribute to the newline character and then uses it with JSTL's fn:replace function does work.
However, I prefer to use the Jakarta String Tab Library to solve this problem:
<%@ taglib prefix="str" uri="http://jakarta.apache.org/taglibs/string-1.1" %>
...
<str:replace var="result" replace="~n" with=";" newlineToken="~n">
Text containing newlines
</str:replace>
...
You can use whatever you want for the newlineToken; "~n" is unlikely to show up in the text I'm doing the replacement on, so it was a reasonable choice for me.
A: This is a valid solution for the JSP EL:
"${fn:split(string1, Character.valueOf(10))}"
A: Just use fn:replace() function to replace \n by ;.
${fn:replace(data, '\n', ';')}
In case you're using Apache's EL implementation instead of Oracle's EL reference implementation (i.e. when you're using Tomcat, TomEE, JBoss, etc instead of GlassFish, Payara, WildFly, WebSphere, etc), then you need to re-escape the backslash.
${fn:replace(data, '\\n', ';')}
A: This is similar to the accepted answer (because it is using Java to represent the newline rather than EL) but here the <c:set/> element is used to set the attribute:
<c:set var="newline" value="<%= \"\n\" %>" />
${fn:replace(myAddress, newline, "<br />")}
The following snippet also works, but the second line of the <c:set/> element cannot be indented (and may look uglier):
<c:set var="newline" value="
" /><!--this line can't be indented -->
${fn:replace(myAddress, newline, "<br />")}
A: More easily:
<str:replace var="your_Var_replaced" replace="\n" with="Your ney caracter" newlineToken="\n">${your_Var_to_replaced}</str:replace>
A: You could write your own JSP function to do the replacement.
This means you'd end up with something like:
<%@ taglib prefix="ns" uri="..." %>
...
${ns:replace(data)}
Where ns is a namespace prefix you define and replace is your JSP function.
These functions are pretty easy to implement (they're just a static method) although I can't seem to find a good reference for writing these at the moment.
A: In the value while setting the var, press ENTER between the double quotes.
${fn:replace(data, newLineChar, ";")}
A: For the record, I came across this post while tackling this problem:
A multi-line string in JSTL gets added as the title attribute of a textarea. Javascript then adds this as the default text of the textarea. In order to clear this text on focus the value needs to equal the title... but fails as many text-editors put \r\n instead of \n. So the follownig will get rid of the unwanted \r:
<% pageContext.setAttribute("newLineChar", "\r"); %>
<c:set var="textAreaDefault" value="${fn:replace(textAreaDefault, newLineChar, '')}" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Using C++ classes in .so libraries I'm trying to write a small class library for a C++ course.
I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) that C++ classes only worked with MFC .dlls and not plain ones, but that's just the windows side.
A: As I understand it, this is fine so long as you are linking .so files which were all compiled using the same compiler. Different compilers mangle the symbols in different ways and will fail to link.
That is one of the advantages in using COM on Windows, it defines a standard for putting OOP objects in DLLs. I can compile a DLL using GNU g++ and link it to an EXE compiled with MSVC - or even VB!
A: C++ classes work fine in .so shared libraries (they also work in non-MFC DLLs on Windows, but that's not really your question). It's actually easier than Windows, because you don't have to explicitly export any symbols from the libraries.
This document will answer most of your questions: http://people.redhat.com/drepper/dsohowto.pdf
The main things to remember are to use the -fPIC option when compiling, and the -shared option when linking. You can find plenty of examples on the net.
A: My solution/testing
Here's my solution and it does what i expected.
Code
cat.hh :
#include <string>
class Cat
{
std::string _name;
public:
Cat(const std::string & name);
void speak();
};
cat.cpp :
#include <iostream>
#include <string>
#include "cat.hh"
using namespace std;
Cat::Cat(const string & name):_name(name){}
void Cat::speak()
{
cout << "Meow! I'm " << _name << endl;
}
main.cpp :
#include <iostream>
#include <string>
#include "cat.hh"
using std::cout;using std::endl;using std::string;
int main()
{
string name = "Felix";
cout<< "Meet my cat, " << name << "!" <<endl;
Cat kitty(name);
kitty.speak();
return 0;
}
Compilation
You compile the shared lib first:
$ g++ -Wall -g -fPIC -c cat.cpp
$ g++ -shared -Wl,-soname,libcat.so.1 -o libcat.so.1 cat.o
Then compile the main executable or C++ program using the classes in the libraries:
$ g++ -Wall -g -c main.cpp
$ g++ -Wall -Wl,-rpath,. -o main main.o libcat.so.1 # -rpath linker option prevents the need to use LD_LIBRARY_PATH when testing
$ ./main
Meet my cat, Felix!
Meow! I'm Felix
$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to use getaddrinfo_a to do async resolve with glibc An often overlooked function that requires no external library, but basically has no documentation whatsoever.
A: UPDATE (2010-10-11): The linux man-pages now have documentation of the getaddrinfo_a, you can find it here: http://www.kernel.org/doc/man-pages/online/pages/man3/getaddrinfo_a.3.html
As a disclaimer I should add that I'm quite new to C but not exactly a newbie, so there might be bugs, or bad coding practices, please do correct me (and my grammar sucks too).
I personally didn't know about it until I came upon this post by Adam Langley, I shall give a few code snippets to illustrate the usage of it and clarify some things that might not be that clear on first use. The benefits of using this is that you get back data readily usable in socket(), listen() and other functions, and if done right you won't have to worry about ipv4/v6 either.
So to start off with the basics, as taken from the link above (you will need to link against libanl (-lanl)) :
Here is the function prototype:
int getaddrinfo_a(int mode, struct gaicb *list[], int ent,
struct sigevent *);
*
*The mode is either GAI_WAIT (which is probably not what you want) and GAI_NOWAIT for async lookups
*The gaicb argument accepts an array of hosts to lookup with the ent argument specifying how many elements the array has
*The sigevent will be responsible for telling the function how we are to be notified, more on this in a moment
A gaicb struct looks like this:
struct gaicb {
const char *ar_name;
const char *ar_service;
const struct addrinfo *ar_request;
struct addrinfo *ar_result;
};
If you're familiar with getaddrinfo, then these fields correspond to them like so:
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints,
struct addrinfo **res);
The node is the ar_name field, service is the port, the hints argument corresponds to the ar_request member and the result is stored in the rest.
Now you specify how you want to be notified through the sigevent structure:
struct sigevent {
sigval_t sigev_value;
int sigev_signo;
int sigev_notify;
void (*sigev_notify_function) (sigval_t);
pthread_addr_t *sigev_notify_attributes;
};
*
*You can ignore the notification via setting _sigev_notify_ to SIGEV_NONE
*You can trigger a signal via setting sigev_notify to SIGEV_SIGNAL and sigev_signo to the desired signal. Note that when using a real-time signal (SIGRTMIN-SIGRTMAX, always use it via the macros and addition SIGRTMIN+2 etc.) you can pass along a pointer or value in the sigev_value.sival_ptr or sigev_value.sival_int member respectivley
*You can request a callback in a new thread via setting sigev_notify to SIGEV_NONE
So basically if you want to look up a hostname you set ar_name to the host and set everything else to NULL, if you want to connect to a host you set ar_name and ar_service , and if you want to create a server you specify ar_service and the ar_result field. You can of course customize the ar_request member to your hearts content, look at man getaddrinfo for more info.
If you have an event loop with select/poll/epoll/kqueue you might want to use signalfd for convenience. Signalfd creates a file descriptor on which you can use the usuall event polling mechanisms like so:
#define _GNU_SOURCE //yes this will not be so standardish
#include <netdb.h>
#include <signal.h>
#include <sys/signalfd.h>
void signalfd_setup(void) {
int sfd;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGRTMIN);
sigprocmask(SIG_BLOCK, &mask, NULL); //we block the signal
sfd = signalfd(-1, &mask, 0);
//add it to the event queue
}
void signalfd_read(int fd) {
ssize_t s;
struct signalfd_siginfo fdsi;
struct gaicb *host;
while((s = read(fd, &fdsi, sizeof(struct signalfd_siginfo))) > 0){
if (s != sizeof(struct signalfd_siginfo)) return; //thats bad
host = fdsi.ssi_ptr; //the pointer passed to the sigevent structure
//the result is in the host->ar_result member
create_server(host);
}
}
void create_server(struct gaicb *host) {
struct addrinfo *rp, *result;
int fd;
result = host->ar_result;
for(rp = result; rp != NULL; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
bind(fd, rp->ai_addr, rp->ai_addrlen);
listen(fd, SOMAXCONN);
//error checks are missing!
freeaddrinfo(host->ar_request);
freeaddrinfo(result);
//you should free everything you put into the gaicb
}
}
int main(int argc, char *argv[]) {
struct gaicb *host;
struct addrinfo *hints;
struct sigevent sig;
host = calloc(1, sizeof(struct gaicb));
hints = calloc(1, sizeof(struct addrinfo));
hints->ai_family = AF_UNSPEC; //we dont care if its v4 or v6
hints->ai_socktype = SOCK_STREAM;
hints->ai_flags = AI_PASSIVE;
//every other field is NULL-d by calloc
host->ar_service = "8888"; //the port we will listen on
host->ar_request = hints;
sig.sigev_notify = SIGEV_SIGNAL;
sig.sigev_value.sival_ptr = host;
sig.sigev_signo = SIGRTMIN;
getaddrinfo_a(GAI_NOWAIT, &host, 1, &sig);
signalfd_setup();
//start your event loop
return 0;
}
You can of course use a simple signal handler for this job too, look at man sigaction for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: OOP class design, Is this design inherently 'anti' OOP? I remember back when MS released a forum sample application, the design of the application was like this:
/Classes/User.cs
/Classes/Post.cs
...
/Users.cs
/Posts.cs
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:
public class Posts
{
public static Post GetPostByID(int postID)
{
SqlDataProvider dp = new SqlDataProvider();
return dp.GetPostByID(postID);
}
}
Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs).
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?
A: 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.
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).
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.
A: Well it depends where and how you define your separation of concerns. If you put the code to populate the Post in the Post class, then your Business Layer is interceded with Data Access Code, and vice versa.
To me it makes sense to do the data fetching and populating outside the actual domain object, and let the domain object be responsible for using the data.
A: Are you sure the classes aren't partial classes. In which case they really aren't two classes, just a single class spread across multiple files for better readability.
A: Based on your code snippet, Posts is primarily a class of static helper methods. Posts is not the same object as Post. Instead of Posts, a better name might be PostManager or PostHelper. If you think of it that way, it may help you understand why they broke it out that way.
A: This is also an important step for a decoupling (or loosely coupling) you applications.
A: What's anti-OOP or pro-OOP depends entirely on the functionality of the software and what's needed to make it work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does re.compile() or any given Python library call throw an exception? I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are?
A: Unlike Java, where there are exceptions that must be declared to be raised (and some that don't have to be, but that's another story), any Python code may raise any exception at any time.
There are a list of built-in exceptions, which generally has some description of when these exceptions might be raised. Its up to you as to how much exception handling you will do, and if you will handle stuff gracefully, or just fail with a traceback.
A: Well, re.compile certainly may:
>>> import re
>>> re.compile('he(lo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\lib\re.py", line 180, in compile
return _compile(pattern, flags)
File "C:\Python25\lib\re.py", line 233, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
The documentation does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the error exception.
Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to decompile them (if written in Python) or even look at the source, if they're in the standard library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Get current System.Web.UI.Page from HttpContext? This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object?
And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface:
private IWebBase FindWebBase()
{
if (HttpContext.Current as IWebBase != null)
{
return (IWebBase)HttpContext.Current.;
}
throw new NotImplementedException("Crawling for IWebBase not implemented yet");
}
The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework.
I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work.
The compiler error is:
Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.
A: You're looking for HttpContext.Handler. Since Page implements IHttpHandler, you'll obtain a reference to the currently executing page.You'll have to cast it, or at least try to cast it to the particular type you're looking for.
HttpContext.Current simply returns the singleton instance of HttpContext. Therefore, it is not and can never be, a page.
A: You may want to use HttpContext.Current.CurrentHandler if you want the precise page that is currently executing. For example, a request for Default.aspx is sent, but an error is thrown and you do a Response.Transfer to your custom ErrorHandler.aspx page. CurrentHandler will return the instance of ErrorHandler.aspx (if called after the error) whereas HttpContext.Current.Handler would return an instance of Default.aspx.
A: No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request."
In other words it is an HttpContext object, not a Page.
You can get to the Page object via HttpContext using:
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
// Use page instance.
}
A: Please see my answer :
Why HttpContext.Current.Handler is null?
Maybe resolved your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "85"
} |
Q: Why is it considered bad practice to use cursors in SQL Server? I knew of some performance reasons back in the SQL 7 days, but do the same issues still exist in SQL Server 2005? If I have a resultset in a stored procedure that I want to act upon individually, are cursors still a bad choice? If so, why?
A: SQL is a set based language--that's what it does best.
I think cursors are still a bad choice unless you understand enough about them to justify their use in limited circumstances.
Another reason I don't like cursors is clarity. The cursor block is so ugly that it's difficult to use in a clear and effective way.
All that having been said, there are some cases where a cursor really is best--they just aren't usually the cases that beginners want to use them for.
A: Cursors are usually not the disease, but a symptom of it: not using the set-based approach (as mentioned in the other answers).
Not understanding this problem, and simply believing that avoiding the "evil" cursor will solve it, can make things worse.
For example, replacing cursor iteration by other iterative code, such as moving data to temporary tables or table variables, to loop over the rows in a way like:
SELECT * FROM @temptable WHERE Id=@counter
or
SELECT TOP 1 * FROM @temptable WHERE Id>@lastId
Such an approach, as shown in the code of another answer, makes things much worse and doesn't fix the original problem. It's an anti-pattern called cargo cult programming: not knowing WHY something is bad and thus implementing something worse to avoid it! I recently changed such code (using a #temptable and no index on identity/PK) back to a cursor, and updating slightly more than 10000 rows took only 1 second instead of almost 3 minutes. Still lacking set-based approach (being the lesser evil), but the best I could do that moment.
Another symptom of this lack of understanding can be what I sometimes call "one object disease": database applications which handle single objects through data access layers or object-relational mappers. Typically code like:
var items = new List<Item>();
foreach(int oneId in itemIds)
{
items.Add(dataAccess.GetItemById(oneId);
}
instead of
var items = dataAccess.GetItemsByIds(itemIds);
The first will usually flood the database with tons of SELECTs, one round trip for each, especially when object trees/graphs come into play and the infamous SELECT N+1 problem strikes.
This is the application side of not understanding relational databases and set based approach, just the same way cursors are when using procedural database code, like T-SQL or PL/SQL!
A: Sometimes the nature of the processing you need to perform requires cursors, though for performance reasons it's always better to write the operation(s) using set-based logic if possible.
I wouldn't call it "bad practice" to use cursors, but they do consume more resources on the server (than an equivalent set-based approach) and more often than not they aren't necessary. Given that, my advice would be to consider other options before resorting to a cursor.
There are several types of cursors (forward-only, static, keyset, dynamic). Each one has different performance characteristics and associated overhead. Make sure you use the correct cursor type for your operation. Forward-only is the default.
One argument for using a cursor is when you need to process and update individual rows, especially for a dataset that doesn't have a good unique key. In that case you can use the FOR UPDATE clause when declaring the cursor and process updates with UPDATE ... WHERE CURRENT OF.
Note that "server-side" cursors used to be popular (from ODBC and OLE DB), but ADO.NET does not support them, and AFAIK never will.
A: There are very, very few cases where the use of a cursor is justified. There are almost no cases where it will outperform a relational, set-based query. Sometimes it is easier for a programmer to think in terms of loops, but the use of set logic, for example to update a large number of rows in a table, will result in a solution that is not only many less lines of SQL code, but that runs much faster, often several orders of magnitude faster.
Even the fast forward cursor in Sql Server 2005 can't compete with set-based queries. The graph of performance degradation often starts to look like an n^2 operation compared to set-based, which tends to be more linear as the data set grows very large.
A: @ Daniel P -> you don't need to use a cursor to do it. You can easily use set based theory to do it. Eg: with Sql 2008
DECLARE @commandname NVARCHAR(1000) = '';
SELECT @commandname += 'truncate table ' + tablename + '; ';
FROM tableNames;
EXEC sp_executesql @commandname;
will simply do what you have said above. And you can do the same with Sql 2000 but the syntax of query would be different.
However, my advice is to avoid cursors as much as possible.
Gayam
A: The above comments about SQL being a set-based environment are all true. However there are times when row-by-row operations are useful. Consider a combination of metadata and dynamic-sql.
As a very simple example, say I have 100+ records in a table that define the names of tables that I want to copy/truncate/whatever. Which is best? Hardcoding the SQL to do what I need to? Or iterate through this resultset and use dynamic-SQL (sp_executesql) to perform the operations?
There is no way to achieve the above objective using set-based SQL.
So, to use cursors or a while loop (pseudo-cursors)?
SQL Cursors are fine as long as you use the correct options:
INSENSITIVE will make a temporary copy of your result set (saving you from having to do this yourself for your pseudo-cursor).
READ_ONLY will make sure no locks are held on the underlying result set. Changes in the underlying result set will be reflected in subsequent fetches (same as if getting TOP 1 from your pseudo-cursor).
FAST_FORWARD will create an optimised forward-only, read-only cursor.
Read about the available options before ruling all cursors as evil.
A: Cursors do have their place, however I think it's mainly because they are often used when a single select statement would suffice to provide aggregation and filtering of results.
Avoiding cursors allows SQL Server to more fully optimize the performance of the query, very important in larger systems.
A: There is a work around about cursors that I use every time I need one.
I create a table variable with an identity column in it.
insert all the data i need to work with in it.
Then make a while block with a counter variable and select the data I want from the table variable with a select statement where the identity column matches the counter.
This way i dont lock anything and use alot less memory and its safe, i will not lose anything with a memory corruption or something like that.
And the block code is easy to see and handle.
This is a simple example:
DECLARE @TAB TABLE(ID INT IDENTITY, COLUMN1 VARCHAR(10), COLUMN2 VARCHAR(10))
DECLARE @COUNT INT,
@MAX INT,
@CONCAT VARCHAR(MAX),
@COLUMN1 VARCHAR(10),
@COLUMN2 VARCHAR(10)
SET @COUNT = 1
INSERT INTO @TAB VALUES('TE1S', 'TE21')
INSERT INTO @TAB VALUES('TE1S', 'TE22')
INSERT INTO @TAB VALUES('TE1S', 'TE23')
INSERT INTO @TAB VALUES('TE1S', 'TE24')
INSERT INTO @TAB VALUES('TE1S', 'TE25')
SELECT @MAX = @@IDENTITY
WHILE @COUNT <= @MAX BEGIN
SELECT @COLUMN1 = COLUMN1, @COLUMN2 = COLUMN2 FROM @TAB WHERE ID = @COUNT
IF @CONCAT IS NULL BEGIN
SET @CONCAT = ''
END ELSE BEGIN
SET @CONCAT = @CONCAT + ','
END
SET @CONCAT = @CONCAT + @COLUMN1 + @COLUMN2
SET @COUNT = @COUNT + 1
END
SELECT @CONCAT
A: I think cursors get a bad name because SQL newbies discover them and think "Hey a for loop! I know how to use those!" and then they continue to use them for everything.
If you use them for what they're designed for, I can't find fault with that.
A: Because cursors take up memory and create locks.
What you are really doing is attempting to force set-based technology into non-set based functionality. And, in all fairness, I should point out that cursors do have a use, but they are frowned upon because many folks who are not used to using set-based solutions use cursors instead of figuring out the set-based solution.
But, when you open a cursor, you are basically loading those rows into memory and locking them, creating potential blocks. Then, as you cycle through the cursor, you are making changes to other tables and still keeping all of the memory and locks of the cursor open.
All of which has the potential to cause performance issues for other users.
So, as a general rule, cursors are frowned upon. Especially if that's the first solution arrived at in solving a problem.
A: The basic issue, I think, is that databases are designed and tuned for set-based operations -- selects, updates, and deletes of large amounts of data in a single quick step based on relations in the data.
In-memory software, on the other hand, is designed for individual operations, so looping over a set of data and potentially performing different operations on each item serially is what it is best at.
Looping is not what the database or storage architecture are designed for, and even in SQL Server 2005, you are not going to get performance anywhere close to you get if you pull the basic data set out into a custom program and do the looping in memory, using data objects/structures that are as lightweight as possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: Hierarchical Data In ASP.NET MVC I am trying to come up with the best way to render some hierarchical data in to a nested unordered list using ASP.NET MVC. Does anyone have any tips on how to do this?
A: You mean... you want some sort of tree view?
You can actually get the treeview control to work... but you have to wrap it in server side form tag to function. You'll get the usual nastiness that that brings (like generated ids and viewstate) but it will work from a rendering perspective.
If you want to just create tags and nest them, it would be pretty easy to do with foreach() loops.
A: I suggest jquery tree view plugins for making it function like a tree, but as for render, just put it in a recursive lambda helper to do the nesting.
A: I believe currently there is no such control.... TreeViews are complex by nature. You can of course "draw" a hierarchy as much as you like using all sorts of repeaters and loops, but to achieve functionality of a tree view like the one in the Web forms toolbox... you have to wait !
A: Why don't you pass your model in the form of a tree to the view?
/// This is the model class
public class MyTreeNode<T>
{
public ICollection<MyTreeNode> ChildNodes {get;}
public T MyValue { get; set; }
bool HasChildren { get { return ChildNodes.Any(); } }
}
///This is the html helper:
public static string RenderTree<T>(this HtmlHelper html, MyTreeNode<T> root, Func<T, string> renderNode)
{
var sb = new StringBuilder();
sb.Append(renderNode(root.MyValue));
if (root.HasChildren)
{
foreach(var child in root.ChildNodes)
{
sb.Append(RenderTree<T>(html, child, renderNode));
}
}
return sb.ToString();
}
I didn't actually test this code, but it's about the idea. You can imagine creating your own recursive html helper to render a tree.
A: For that (rendering hierarchical menu, treeview, etc) i use recursive calls of custom component (ascx, or aspx in new preview5).
I give component first level of items (List of items), and component then check for each item in list if there's any child items and call itself with list of that child items.
You can build hierarchical graph of objects in controller, or just 1 dimensional list with ParentID property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When can/should you go whole hog with the ORM approach? It seems to me that introducing an ORM tool is supposed to make your architecture cleaner, but for efficiency I've found myself bypassing it and iterating over a JDBC Result Set on occasion. This leads to an uncoordinated tangle of artifacts instead of a cleaner architecture.
Is this because I'm applying the tool in an invalid Context, or is it deeper than that?
When can/should you go whole hog with the ORM approach?
Any insight would be greatly appreciated.
A little of background:
In my environment I have about 50 client computers and 1 reasonably powerful SQL Server.
I have a desktop application in which all 50 clients are accessing the data at all times.
The project's Data Model has gone through a number of reorganizations for various reasons including clarity, efficiency, etc.
My Data Model's history
*
*JDBC calls directly
*DAO + POJO without relations between Pojos (basically wrapping the JDBC).
*Added Relations between POJOs implementing Lazy Loading, but just hiding the inter-DAO calls
*Jumped onto the Hibernate bandwagon after seeing how "simple" it made data access (it made inter POJO relations trivial) and because it could decrease the number of round trips to the database when working with many related entities.
*Since it was a desktop application keeping Sessions open long term was a nightmare so it ended up causing a whole lot of issues
*Stepped back to a partial DAO/Hibernate approach that allows me to make direct JDBC calls behind the DAO curtain while at the same time using Hibernate.
A: Hibernate makes more sense when your application works on object graphs, which are persisted in the RDBMS. Instead, if your application logic works on a 2-D matrix of data, fetching those via direct JDBC works better. Although Hibernate is written on top of JDBC, it has capabilities which might be non-trivial to implement in JDBC. For eg:
*
*Say, the user views a row in the UI and changes some of the values and you want to fire an update query for only those columns that did indeed change.
*To avoid getting into deadlocks you need to maintain a global order for SQLs in a transaction. Getting this right JDBC might not be easy
*Easily setting up optimistic locking. When you use JDBC, you need to remember to have this in every update query.
*Batch updates, lazy materialization of collections etc might also be non-trivial to implement in JDBC.
(I say "might be non-trivial", because it of course can be done - and you might be a super hacker:)
Hibernate lets you fire your own SQL queries also, in case you need to.
Hope this helps you to decide.
PS: Keeping the Session open on a remote desktop client and running into trouble is really not Hibernate's problem - you would run into the same issue if you keep the Connection to the DB open for long.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does anyone know where to find free database design templates? I'm obviously not talking about a full solution, but just a good starting point for common applications for software architects. It could be for a CMS, e-commerce storefront, address book, etc. A UML diagram is not essential, but a table schema with data types in the least. Thanks!
A: Check out the Library of Free Data Models from DatabaseAnswers.org -- might be a good starting point. I can't vouch for the quality, but there is a lot here...
A: Open source?
DB-UML might work for you.
EDIT:
Oh! The MySQL Workbench is good.
A: The mondial database. Is used for learning about DBMSs. If you need something quick and dirty to bang around.
A: try this one... database design document template.
very good and usefull template.
but it isnt free.. you have to buy it.. :(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Something special about Safari for Windows and AJAX? Is there something special about Safari for Windows and AJAX?
In other words: Are there some common pitfalls I should keep in mind?
A: Safari is really standards compliant. Unless you're using some really esoteric browser features, in general if something works in Firefox, I've found it works without modification in Windows Safari.
Apple has a developer center for web developers, but I didn't find anything too useful there.
A: In your event handlers, instead of return false, use event.preventDefault() or event.stopPropagation(). The event methods are the standard/compatible way, but lots of old tutorials still recommend return.
A: One word of warning: Safari on Windows does not support XSLT.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Are CLR stored procedures preferred over TSQL stored procedures in SQL 2005+? 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.
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.
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).
I'd be very interested in hearing your experience as it's seems it is not a simple choice.
A: Hosting the CLR within SQL Server is meant to give database developers more flexible options in how they sought to accomplish tasks. Like others have mentioned, SQL is great for operations and modifications on sets of data. Anybody who has done extensive large application development with complex business/domain rules would likely tell you - trying to enforce some of these rules using pure SQL (some times into a single macro query) can get truly nightmarish.
There are just certain tasks that are better handled in a procedural or OO fashion. By having the choice of using .NET code to break down the sequence of logic, query operations can get easier to read and debug. Having used CLR stored procs I can tell you stepping through with the debugger really makes it easier to follow through with what is happening at the database level.
Just one example, we frequently use CLR stored procs here as a "gateway" for dynamic search queries. Say a search request that can have up to 30 different search parameters. Users obviously don't use all 30 of them, so the data structure passed in will have 30 parameters but mostly DBNULL. The client side has no option to generate a dynamic statement, for obvious security reasons. The resulting dynamic statement is generated internally without fear of external "extras".
A: In general you use the CLR if you have something that doesn't need to interface with the database much. So let's say you are parsing, or decoding a value. This is easier to do in the CLR and then return the value.
Trying to do a compelx query in the CLR is just not the way to go.
BTW this didn't change in 2008 either.
A: I believe those two aren't equivalent... fit to square off against each other.
CLR Integration is supposed to phase out "extended stored procedures" of yore. We have some of these in our workplace... essentially blocks of processing/logic over SQL data that was too hard/impossible to do via conventional DB Stored procedures/T SQL. So they wrote it up as extended stored procedures in C++ DLLs that can be invoked similarly.
Now they have been phased out and CLR integration is the replacement
*
*DB Stored procedures: if it can be done in T SQL Stored procs, do it.
*CLR Stored procedures: if the logic is too complex or tedious to do via T SQL... if its something that will take fewer lines of CLR code to tackle it (string manipulation, complex/custom sorting or filtering, etc.) use this approach.
A: Aside from the file system access (where CLR procs has a very pronounced advantage) I would use T-SQL procs. If you have especially complex calculations you could possibly put that piece into a CLR function and call this from within your proc (udf's are where I've found the CLR integration really shines). Then you get the benefits of the CLR integration for that particular part of your task but keep as much of your stored proc logic in the DB as you can.
A: Given what you said, I would rather you get the deveopers properly trained in t-SQl and databases in general than allow them to create posssibly much more damage to performance by allowing them to do t-sql tasks in CLRs. Developers who don't understand databases use that as an excuse to avoid doing things the way that is best for database performance because they want to take what they see as the easier route.
A: It always comes down to the right tool for the job, so it really depends on what you are trying to accomplish.
However, as a general rule, you're right that CLR procs have a greater overhead and will never perform on set operations like T-SQL. My guideline is do it all in T-SQL unless what you need becomes overly complicated in T-SQL. Then, try harder to get the T-SQL approach to work. :-)
CLR procs are great and do have their place, but their use should be the exception, not the rule.
A: The SQL Server Books Online's page on the subject lists these benefits:
*
*A better programming model. The .NET Framework languages are in many respects richer than Transact-SQL, offering constructs and capabilities previously not available to SQL Server developers. Developers may also leverage the power of the .NET Framework Library, which provides an extensive set of classes that can be used to quickly and efficiently solve programming problems.
*Improved safety and security. Managed code runs in a common language run-time environment, hosted by the Database Engine. SQL Server leverages this to provide a safer and more secure alternative to the extended stored procedures available in earlier versions of SQL Server.
*Ability to define data types and aggregate functions. User defined types and user defined aggregates are two new managed database objects which expand the storage and querying capabilities of SQL Server.
*Streamlined development through a standardized environment. Database development is integrated into future releases of the Microsoft Visual Studio .NET development environment. Developers use the same tools for developing and debugging database objects and scripts as they use to write middle-tier or client-tier .NET Framework components and services.
*Potential for improved performance and scalability. In many situations, the .NET Framework language compilation and execution models deliver improved performance over Transact-SQL.
A: We ran into a situation with a CLR function that was called thousands of times in a regular SQL proc. This was a proc for importing data from another system. The function validated the data and handled nulls nicely.
If we did the operation in TSQL, the proc finished in about 15 seconds. If we used the CLR function, the proc finished in 20 - 40 minutes. The CLR function looked more elegant, but as far as we could tell, there was a startup hit for each use of the CLR function. So if you have a large operation done using one CLR function, that's fine since the startup time is small compared to the time for the operation. Or if you a calling the CLR function a modest number of times, the total startup time for all invocations of the function would be small. But be careful of loops.
Also, for maintainability, it's nicer not to have more languages than you really need.
A: 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.
A: CLR stored procedures are not meant to replace set-based queries. If you need to query the database, you are still going to need to put SQL into your CLR code, just as if it was embedded in regular code. This would be a waste of effort.
CLR stored procedures are for two main things: 1) interaction with the OS, such as reading from a file or dropping a message in MSMQ, and 2) performing complex calculations, especially when you already have the code written in a .NET language to do the calculation.
A: I would add a couple of reasons to use CLR that may not have been mentioned.
*
*Replace and extend basic query, non-query, and scalar sql functions.
A) Error reporting and alerts can be integrated based upon defined requirements.
B) Easily define debugging levels.
C) Enable an easier way to interact with foreign SQL servers
*Move legacy code to a managed environment.
A: I posted the following answer to a similar question: Advantage of SQL SERVER CLR.
I will add here though, that C# / VB.net / etc being a language someone is more comfortable with than T-SQL should not be a reason to use SQLCLR over T-SQL. If someone doesn't know how to accomplish something in T-SQL, first ask for help in finding a T-SQL solution. If one does not exist, then go the CLR route.
SQLCLR / CLR Integration within SQL Server is just another tool to help solve certain (not all) problems. There are a few things that it does better than what can be done in pure T-SQL, and there are some things that can only be done via SQLCLR. I wrote an article for SQL Server Central, Stairway to SQLCLR Level 1: What is SQLCLR? (free registration is required to read articles there), that addresses this question. The basics are (see the linked article for details):
*
*Streaming Table-Valued Functions (sTVF)
*Dynamic SQL (within Functions)
*Better Access to External Resources / Replace xp_cmdshell
*
*Passing data in is easier
*Getting multiple columns of a result set back is easier
*No external dependencies (e.g. 7zip.exe)
*Better security via Impersonation
*Ability to Multi-thread
*Error Handling (within Functions)
*Custom Aggregates
*Custom Types
*Modify State (within a Function and without OPENQUERY / OPENROWSET)
*Execute a Stored Procedure (read-only; within a Function and without OPENQUERY / OPENROWSET)
*Performance (note: this is not meaning in all cases, but definitely in some cases depending on the type and complexity of the operation)
*Can capture output (i.e. what is sent to the Messages tab in SSMS) (e.g. PRINT and RAISERROR with a severity = 0 to 10) -- I forgot to mention this one in the article ;-).
One other thing to consider is, sometimes it is beneficial to be able to share code between the app and the DB so that the DB has insight into certain business logic without having to build custom, internal-only screens just to access that app code. For example, I have worked on a system that imported data files from customers and use a custom hash of most of the fields and saved that value to the row in the DB. This allowed for easily skipping rows when importing their data again as the app would hash the values from the input file and compare to the hash value stored on the row. If they were the same then we knew instantly that none of the fields had changed so we went onto the next row, and it was a simple INT comparison. But that algorithm for doing the hash was only in the app code so whether for debugging a customer case or looking for ways to offload some processing to back-end services by flagging rows that had at least one field with changes (changes coming from our app as opposed to looking for changes within a newer import file), there was nothing I could do. That would have been a great opportunity to have a rather simple bit of business logic in the DB, even if not for normal processing; having what amounts to an encoded value in the DB with no ability to understand its meaning makes it much hard to solve problems.
If interested in seeing some of these capabilities in action without having to write any code, the Free version of SQL# (of which I am the author) has RegEx functions, custom Aggregates (UDAs), custom Types (UDTs), etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Using the result of a command as an argument in bash? To create a playlist for all of the music in a folder, I am using the following command in bash:
ls > list.txt
I would like to use the result of the pwd command for the name of the playlist.
Something like:
ls > ${pwd}.txt
That doesn't work though - can anyone tell me what syntax I need to use to do something like this?
Edit: As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!
A: The best way to do this is with "$(command substitution)" (thanks, Landon):
ls > "$(pwd).txt"
You will sometimes also see people use the older backtick notation, but this has several drawbacks in terms of nesting and escaping:
ls > "`pwd`.txt"
Note that the unprocessed substitution of pwd is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a .txt extension. Thomas Kammeyer pointed out that the basename command strips the leading directory, so this would create a text file in the current directory with the name of that directory:
ls > "$(basename "$(pwd)").txt"
Also thanks to erichui for bringing up the problem of spaces in the path.
A: This is equivalent to the backtick solution:
ls > $(pwd).txt
A: To do literally what you said, you could try:
ls > `pwd`.txt
which will use the full pathname, which should be fine.
Note that if you do this in your home directory, which might
be in /home/hoboben, you will be trying the create /home/hoboben.txt,
a text file in the directory above.
Is this what you wanted?
If you wanted the directory to contain a file named after it, you would get
the basename of the current directory and append that with .txt to the pwd.
Now, rather than use the pwd command... why not use the PWD environment variable?
For example:
ls > $PWD.txt
or
ls > ${PWD}.txt
is probably what you were trying to remember with your second example.
If you're in /home/hoboben and you want to create /home/hoboben/hoboben.txt, try:
ls > ${PWD}/${PWD##*/}.txt
If you do this, the file will contain its own name, so most often, you would remedy this in one of a few ways. You could redirect to somewhere else and move the file or name the file beginning with a dot to hide it from the ls command as long as you don't use the -a flag (and then optionally rename the resulting file).
I write my own scripts to manage a directory hierarchy of music files and I use subdirectories named ".info", for example, to contain track data in some spare files (basically, I "hide" metadata this way). It works out okay because my needs are simple and my collection small.
A: I suspect the problem may be that there are spaces in one of the directory names. For example, if your working directory is "/home/user/music/artist name". Bash will be confused thinking that you are trying to redirect to /home/user/music/artist and name.txt. You can fix this with double quotes
ls > "$(pwd).txt"
Also, you may not want to redirect to $(pwd).txt. In the example above, you would be redirecting the output to the file "/home/user/music/artist name.txt"
A: The syntax is:
ls > `pwd`.txt
That is the '`' character up underneath the '~', not the regular single quote.
A: Using the above method will create the files one level above your current directory. If you want the play lists to all go to one directory you'd need to do something like:
#!/bin/sh
MYVAR=`pwd | sed "s|/|_|g"`
ls > /playlistdir/$MYVAR-list.txt
A: to strip all but the directory name
ls >/playlistdir/${PWD##/*}.txt
this is probably not what you want because then you don't know where the files are (unless you change the ls command)
to replace "/" with "_"
ls >/playlistdir/${PWD//\//_}.txt
but then the playlist would look ugly and maybe not even fit in the selection window
So this will give you both a short readable name and usable paths inside the file
ext=.mp3 #leave blank for all files
for FILE in "$PWD/*$ext"; do echo "$FILE";done >/playlistdir/${PWD##/*}.txt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
} |
Q: Rendering graphics in C# Is there another way to render graphics in C# beyond GDI+ and XNA?
(For the development of a tile map editor.)
A: Yes, I have written a Windows Forms control that wraps DirectX 9.0 and provides direct pixel level manipulation of the video surface.
I actually wrote another post on Stack Overflow asking if there are other better approaches: Unsafe C# and pointers for 2D rendering, good or bad?
While it is relatively high performance, it requires the unsafe compiler option as it uses pointers to access the memory efficiently. Hence the reason for this earlier post.
This is a high level of the required steps:
*
*Download the DirectX SDK.
*Create a new C# Windows Forms project and reference the installed
Microsoft DirectX assembly.
*Initialize a new DirectX Device object with Presentation Parameters
(windowed, back buffering, etc.) you require.
*Create the Device, taking care to record the surface "Pitch" and
current display mode (bits per pixel).
*When you need to display something, Lock the backbuffer
surface and store the returned pointer to the start of surface
memory.
*Use pointer arithmetic, calculate the actual pixel position in the
data based on the surface pitch,
bits per pixel and the actual x/y pixel coordinate.
*In my case for simplicity I am sticking to 32 bpp, meaning setting a pixel is as simple as: *(surfacePointer + (y * pitch + x))=Color.FromARGB(255,0,0);
*When finished drawing, Unlock the back buffer surface. Present the surface.
*Repeat from step 5 as required.
Be aware that taking this approach you need to be very careful about checking the current display mode (pitch and bits per pxiel) of the target surface. Also you will need to have a strategy in place to deal with window resizing or changes of screen format while your program is running.
A: *
*Managed DirectX (Microsoft.DirectX namespace) for faster 3D graphics. It's a solid .NET wrapper over DirectX API, which comes with a bit of performance hit for creating .NET objects and marshalling. Unless you are writing a full featured modern 3D engine, it will work fine.
*Window Presentation Foundation (WPF) (Windows.Media namespace) - best choice for 2D graphics. Also has limited 3D abilities. Aimed to replace Windows Forms with vector, hardware accelerated resolution-independent framework. Very convenient, supports several flavours of custom controls, resources, data binding, events and commands... also has a few WTFs. Speed is usually faster than GDI and slower than DirectX, and depends greatly on how you do things (seen something to work 60 times faster after rewriting in a sensible way). We had a success implementing 3 1280x1024 screens full of real-time indicators, graphs and plots on a single (and not the best) PC.
A: SDL.NET 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.
A: You could try looking into WPF, using Visual Studio and/or Expression Blend. I'm not sure how sophisticated you're trying to get, but it should be able to handle a simple editor. Check out this MSDN Article for more info.
A: You might look into the Cairo graphics library. The Mono project has bindings for C#.
A: Cairo is an option. I'm currently rewriting my mapping software using both GDI+ and Cairo. It has a tile map generator, among other features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Showing a tooltip for a MenuItem I've got a menu that contains, among other things, some most-recently-used file paths. The paths to these files can be long, so the text sometimes gets clipped like "C:\Progra...\foo.txt"
I'd like to pop a tooltip with the full path when the user hovers over the item, but this doesn't seem possible with the Tooltip class in .NET 2.0.
Am I missing something obvious?
A: On the MenusTrip set "ShowItemToolTips = True" and on the ToolStripMenuItem set your ToolTipText
yourMenuStrip.ShowItemToolTips = true;
yourToolStripMenuItem.ToolTipText = "some txt";
A: If you are creating your menu items using the System.Windows.Forms.MenuItem class you won't have a "ToolTipText" property.
You should use the System.Windows.Forms.ToolStripMenuItem class which is new as of .Net Framework 2.0 and DOES include the "ToolTipText" property.
You also have to remember to specify ShowItemToolTips = True on the MenuStrip control
A: May be that I misunderstood you problem, but why do you need to use the Tooltip class? You can assign your text to the ToolTipText property and it will be shown to the user.
A: Tooltip is set manually by:
testToolStripMenuItem2.ToolTipText = "My tooltip text";
The MenuItem can for example be part of this menu constellation: a menu strip with a menu item and a sub menu item. (This plumbing code is generated automatically for you in the code behind designer file if you use visual studio)
MenuStrip menuStrip1;
ToolStripMenuItem testToolStripMenuItem; // Menu item on menu bar
menuStrip1.Items.Add(testToolStripMenuItem);
ToolStripMenuItem testToolStripMenuItem2; // Sub menu item
testToolStripMenuItem.DropDownItems.Add(testToolStripMenuItem2)
A: There is an article on CodeProject that implements a derived version of ToolStrip with custom tool tip support. This could be useful in situations where the default tool tip support is not flexible enough.
http://www.codeproject.com/Tips/376643/ToolStrip-with-custom-ToolTip
A: Maybe you forgot to associate the tooltip with the control using SetToolTip.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Compiling code on an external drive To make things easier when switching between machines (my workstation at the office and my personal laptop) I have thought about trying an external hard drive to store my working directory on. Specifically I am looking at Firewire 800 drives (most are 5400 rpm 8mb cache). What I am wondering is if anyone has experience with doing this with Visual Studio projects and what sort of performance hit they see.
A: It depends on the size of the project. The throughput is low and the latency is high, so you're going to get hit every which way, but due to the latency you'll be hit harder if you have a lot of little files rather than a few large ones.
Have you considered simply carrying around a GIT or other distributed repository and updating the machine repositories as you move around? Then you can compile locally and treat the drive and a roving server. Since only changes will be moved across, it should be faster, and your code will be 'backed up' in more places.
If you forget the drive, it breaks, or is lost/stolen, then you can still sit down at a PC and program with no code missing if you're at the last PC you used, or very little code missing (which will be updated later with a resync anyway).
And it's just a hop skip and a jump away from simply using the network to move the changes between the systems if you don't want to carry the drive around later.
A: I use vmware and the virtual machines are on an external usb drive. Performance is fine. You might have some issues with the drive name changing - not an issue if you use virtual machines.
A: Granted I work in an industry were Personal Information and Intellectual Property are king, but I don't like that idea at all. That hard drive disappears and you have a big problem.
Why not Remote Desktop into the work machine?
EDIT Stipud Spelingg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UnhandledException handler in a .Net Windows Service Is it possible to use an UnhandledException Handler in a Windows Service?
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:
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
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?
A: You can subscribe to the AppDomain.UnhandledException event. If you have a message loop, you can tie to the Application.ThreadException event.
A: 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:
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
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.
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.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Excel like server side control for ASP.NET We have a requirement to increase the functionality of a grid we are using to edit on our webapp, and our manager keeps citing Excel as the perfect example for a data grid :/ He still doesn't really get that a Spreadsheet like control doesn't exist out of the box, but I thought I'd do a bit of searching nonetheless.
I've found a couple of products on Google, but was wondering if anyone else has any feedback around any such controls (obviously the cheaper or ahem freer the better)
EDIT We do currently have the Telerik controls, but what the 'current' requirement is, is a control that can copy and paste (e.g) 3 cells from one row and paste them on another, the row by row editing of Telerik doesn't really cut it. We are currently in competition with an 'Excel' based solution, which is always a nightmare in winning users around, who always prefer flexibility to structure
A: Update: with Silverlight fast approaching, maybe you can use a real excel control.
Devexpress has a powerful grid control for both web and windows. It is not free and I guess nothing really matches Excel. But once the users started using it, they wanted every app with it. Check these videos especially the data grouping one.
A: You may consider 3rd party tools of native Excel functionality. There are most buzzed on the forums:
*
*Aspose Excel Cells
*ComponentOne XLS for .NET
*Or Excel Jetcell .NET.
A: This may not be directly related to your question, but on the server side have you considered what operations you will need to perform that will mimic Excel? You may want to check out SpreadsheetGear which will give you complete macro functionality.
They have new charting features that I haven't used yet, but they are supposed to work with Asp.net.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I get the external IP of a socket in Python? When I call socket.getsockname() on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?
A: This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.
A: The only way I can think of that's guaranteed to give it to you is to hit a service like http://whatismyip.com/ to get it.
A: https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py
'''
Finds your external IP address
'''
import urllib
import re
def get_ip():
group = re.compile(u'(?P<ip>\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()
return group['ip']
if __name__ == '__main__':
print get_ip()
A: You'll need to use an external system to do this.
DuckDuckGo's IP answer will give you exactly what you want, and in JSON!
import requests
def detect_public_ip():
try:
# Use a get request for api.duckduckgo.com
raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
# load the request as json, look for Answer.
# split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
answer = raw.json()["Answer"].split()[4]
# if there are any connection issues, error out
except Exception as e:
return 'Error: {0}'.format(e)
# otherwise, return answer
else:
return answer
public_ip = detect_public_ip()
print(public_ip)
A: import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("msn.com",80))
s.getsockname()
A: print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())
A: The most simple method of getting a public IP is by using this
import requests
IP = requests.get('https://api.ipify.org/').text
print(f'Your IP is: {IP}')
A: Using the address suggested in the source of http://whatismyip.com
import urllib
def get_my_ip_address():
whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'
return urllib.urlopen(whatismyip).readlines()[0]
A:
You need to make connection to an external Server And Get Your Public IP From The Response
like this:
import requests
myPublic_IP = requests.get("http://wtfismyip.com/text").text.strip()
print("\n[+] My Public IP: "+ myPublic_IP+"\n")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Tools for manipulating PowerPoint files 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.
A: Well, 100% managed could be going the hard route, however, you can use the Office PIAs from your .NET code. Joel Spolsky has an article discussing your various options.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to take a screenshot using Java and save it to some sort of image? Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?
A: import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class HelloWorldFrame extends JFrame implements ActionListener {
JButton b;
public HelloWorldFrame() {
this.setVisible(true);
this.setLayout(null);
b = new JButton("Click Here");
b.setBounds(380, 290, 120, 60);
b.setBackground(Color.red);
b.setVisible(true);
b.addActionListener(this);
add(b);
setSize(1000, 700);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b)
{
this.dispose();
try {
Thread.sleep(1000);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
Rectangle rec = new Rectangle(0, 0, d.width, d.height);
Robot ro = new Robot();
BufferedImage img = ro.createScreenCapture(rec);
File f = new File("myimage.jpg");//set appropriate path
ImageIO.write(img, "jpg", f);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
HelloWorldFrame obj = new HelloWorldFrame();
}
}
A: GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
}
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write( bufferedImage, "png", fos );
bufferedImage will contain a full screenshot, this was tested with three monitors
A: I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:
public static final void makeScreenshot(JFrame argFrame) {
Rectangle rec = argFrame.getBounds();
BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
argFrame.paint(bufferedImage.getGraphics());
try {
// Create temp file
File temp = File.createTempFile("screenshot", ".png");
// Use the ImageIO API to write the bufferedImage to a temporary file
ImageIO.write(bufferedImage, "png", temp);
// Delete temp file when program exits
temp.deleteOnExit();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
A: Believe it or not, you can actually use java.awt.Robot to "create an image containing pixels read from the screen." You can then write that image to a file on disk.
I just tried it, and the whole thing ends up like:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));
NOTE: This will only capture the primary monitor. See GraphicsConfiguration for multi-monitor support.
A: If you'd like to capture all monitors, you can use the following code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);
A: public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
A: You can use java.awt.Robot to achieve this task.
below is the code of server, which saves the captured screenshot as image in your Directory.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class ServerApp extends Thread
{
private ServerSocket serverSocket=null;
private static Socket server = null;
private Date date = null;
private static final String DIR_NAME = "screenshots";
public ServerApp() throws IOException, ClassNotFoundException, Exception{
serverSocket = new ServerSocket(61000);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
date = new Date();
DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
String fileName = server.getInetAddress().getHostName().replace(".", "-");
System.out.println(fileName);
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
System.out.println("Image received!!!!");
//lblimg.setIcon(img);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!"+st.toString());
//createLogFile("[stocktimeoutexception]"+stExp.getMessage());
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
ServerApp serverApp = new ServerApp();
serverApp.createDirectory(DIR_NAME);
Thread thread = new Thread(serverApp);
thread.start();
}
private void createDirectory(String dirName) {
File newDir = new File("D:\\"+dirName);
if(!newDir.exists()){
boolean isCreated = newDir.mkdir();
}
}
}
And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.
package com.viremp.client;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import javax.imageio.ImageIO;
public class ClientApp implements Runnable {
private static long nextTime = 0;
private static ClientApp clientApp = null;
private String serverName = "192.168.100.18"; //loop back ip
private int portNo = 61000;
//private Socket serverSocket = null;
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
clientApp = new ClientApp();
clientApp.getNextFreq();
Thread thread = new Thread(clientApp);
thread.start();
}
private void getNextFreq() {
long currentTime = System.currentTimeMillis();
Random random = new Random();
long value = random.nextInt(180000); //1800000
nextTime = currentTime + value;
//return currentTime+value;
}
@Override
public void run() {
while(true){
if(nextTime < System.currentTimeMillis()){
System.out.println(" get screen shot ");
try {
clientApp.sendScreen();
clientApp.getNextFreq();
} catch (AWTException e) {
// TODO Auto-generated catch block
System.out.println(" err"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(" statrted ....");
}
}
private void sendScreen()throws AWTException, IOException {
Socket serverSocket = new Socket(serverName, portNo);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimensions = toolkit.getScreenSize();
Robot robot = new Robot(); // Robot class
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
serverSocket.close();
}
}
A: Toolkit returns pixels based on PPI, as a result, a screenshot is not created for the entire screen when using PPI> 100% in Windows.
I propose to do this:
DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();
Rectangle screenRectangle = new Rectangle(displayMode.getWidth(), displayMode.getHeight());
BufferedImage screenShot = new Robot().createScreenCapture(screenRectangle);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "135"
} |
Q: Graph Algorithm To Find All Connections Between Two Arbitrary Vertices I am trying to determine the best time efficient algorithm to accomplish the task described below.
I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges.
All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set).
I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only).
Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles).
For example:
If I have the following records:
A, B, C, D, E
and the following represents the connections:
(A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E),
(C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E)
[where (A,B) means record A connects to record B]
If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E.
All paths connecting B to E:
B->E
B->F->E
B->F->C->E
B->A->C->E
B->A->C->F->E
This is an example, in practice I may have sets containing hundreds of thousands of records.
A: Since the existing non-recursive DFS implementation given in this answer seems to be broken, let me provide one that actually works.
I've written this in Python, because I find it pretty readable and uncluttered by implementation details (and because it has the handy yield keyword for implementing generators), but it should be fairly easy to port to other languages.
# a generator function to find all simple paths between two nodes in a
# graph, represented as a dictionary that maps nodes to their neighbors
def find_simple_paths(graph, start, end):
visited = set()
visited.add(start)
nodestack = list()
indexstack = list()
current = start
i = 0
while True:
# get a list of the neighbors of the current node
neighbors = graph[current]
# find the next unvisited neighbor of this node, if any
while i < len(neighbors) and neighbors[i] in visited: i += 1
if i >= len(neighbors):
# we've reached the last neighbor of this node, backtrack
visited.remove(current)
if len(nodestack) < 1: break # can't backtrack, stop!
current = nodestack.pop()
i = indexstack.pop()
elif neighbors[i] == end:
# yay, we found the target node! let the caller process the path
yield nodestack + [current, end]
i += 1
else:
# push current node and index onto stacks, switch to neighbor
nodestack.append(current)
indexstack.append(i+1)
visited.add(neighbors[i])
current = neighbors[i]
i = 0
This code maintains two parallel stacks: one containing the earlier nodes in the current path, and one containing the current neighbor index for each node in the node stack (so that we can resume iterating through the neighbors of a node when we pop it back off the stack). I could've equally well used a single stack of (node, index) pairs, but I figured the two-stack method would be more readable, and perhaps easier to implement for users of other languages.
This code also uses a separate visited set, which always contains the current node and any nodes on the stack, to let me efficiently check whether a node is already part of the current path. If your language happens to have an "ordered set" data structure that provides both efficient stack-like push/pop operations and efficient membership queries, you can use that for the node stack and get rid of the separate visited set.
Alternatively, if you're using a custom mutable class / structure for your nodes, you can just store a boolean flag in each node to indicate whether it has been visited as part of the current search path. Of course, this method won't let you run two searches on the same graph in parallel, should you for some reason wish to do that.
Here's some test code demonstrating how the function given above works:
# test graph:
# ,---B---.
# A | D
# `---C---'
graph = {
"A": ("B", "C"),
"B": ("A", "C", "D"),
"C": ("A", "B", "D"),
"D": ("B", "C"),
}
# find paths from A to D
for path in find_simple_paths(graph, "A", "D"): print " -> ".join(path)
Running this code on the given example graph produces the following output:
A -> B -> C -> D
A -> B -> D
A -> C -> B -> D
A -> C -> D
Note that, while this example graph is undirected (i.e. all its edges go both ways), the algorithm also works for arbitrary directed graphs. For example, removing the C -> B edge (by removing B from the neighbor list of C) yields the same output except for the third path (A -> C -> B -> D), which is no longer possible.
Ps. It's easy to construct graphs for which simple search algorithms like this one (and the others given in this thread) perform very poorly.
For example, consider the task of find all paths from A to B on an undirected graph where the starting node A has two neighbors: the target node B (which has no other neighbors than A) and a node C that is part of a clique of n+1 nodes, like this:
graph = {
"A": ("B", "C"),
"B": ("A"),
"C": ("A", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"),
"D": ("C", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"),
"E": ("C", "D", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"),
"F": ("C", "D", "E", "G", "H", "I", "J", "K", "L", "M", "N", "O"),
"G": ("C", "D", "E", "F", "H", "I", "J", "K", "L", "M", "N", "O"),
"H": ("C", "D", "E", "F", "G", "I", "J", "K", "L", "M", "N", "O"),
"I": ("C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O"),
"J": ("C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "O"),
"K": ("C", "D", "E", "F", "G", "H", "I", "J", "L", "M", "N", "O"),
"L": ("C", "D", "E", "F", "G", "H", "I", "J", "K", "M", "N", "O"),
"M": ("C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "N", "O"),
"N": ("C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "O"),
"O": ("C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"),
}
It's easy to see that the only path between A and B is the direct one, but a naïve DFS started from node A will waste O(n!) time uselessly exploring paths within the clique, even though it's obvious (to a human) that none of those paths can possibly lead to B.
One can also construct DAGs with similar properties, e.g. by having the starting node A connect target node B and to two other nodes C1 and C2, both of which connect to the nodes D1 and D2, both of which connect to E1 and E2, and so on. For n layers of nodes arranged like this, a naïve search for all paths from A to B will end up wasting O(2n) time examining all the possible dead ends before giving up.
Of course, adding an edge to the target node B from one of the nodes in the clique (other than C), or from the last layer of the DAG, would create an exponentially large number of possible paths from A to B, and a purely local search algorithm can't really tell in advance whether it will find such an edge or not. Thus, in a sense, the poor output sensitivity of such naïve searches is due to their lack of awareness of the global structure of the graph.
While there are various preprocessing methods (such as iteratively eliminating leaf nodes, searching for single-node vertex separators, etc.) that could be used to avoid some of these "exponential-time dead ends", I don't know of any general preprocessing trick that could eliminate them in all cases. A general solution would be to check at every step of the search whether the target node is still reachable (using a sub-search), and backtrack early if it isn't — but alas, that would significantly slow down the search (at worst, proportionally to the size of the graph) for many graphs that don't contain such pathological dead ends.
A: Here is a logically better-looking recursive version as compared to the second floor.
public class Search {
private static final String START = "B";
private static final String END = "E";
public static void main(String[] args) {
// this graph is directional
Graph graph = new Graph();
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "A");
graph.addEdge("B", "D");
graph.addEdge("B", "E"); // this is the only one-way connection
graph.addEdge("B", "F");
graph.addEdge("C", "A");
graph.addEdge("C", "E");
graph.addEdge("C", "F");
graph.addEdge("D", "B");
graph.addEdge("E", "C");
graph.addEdge("E", "F");
graph.addEdge("F", "B");
graph.addEdge("F", "C");
graph.addEdge("F", "E");
List<ArrayList<String>> paths = new ArrayList<ArrayList<String>>();
String currentNode = START;
List<String> visited = new ArrayList<String>();
visited.add(START);
new Search().findAllPaths(graph, seen, paths, currentNode);
for(ArrayList<String> path : paths){
for (String node : path) {
System.out.print(node);
System.out.print(" ");
}
System.out.println();
}
}
private void findAllPaths(Graph graph, List<String> visited, List<ArrayList<String>> paths, String currentNode) {
if (currentNode.equals(END)) {
paths.add(new ArrayList(Arrays.asList(visited.toArray())));
return;
}
else {
LinkedList<String> nodes = graph.adjacentNodes(currentNode);
for (String node : nodes) {
if (visited.contains(node)) {
continue;
}
List<String> temp = new ArrayList<String>();
temp.addAll(visited);
temp.add(node);
findAllPaths(graph, temp, paths, node);
}
}
}
}
Program Output
B A C E
B A C F E
B E
B F C E
B F E
A: Solution in C code. It is based on DFS which uses minimum memory.
#include <stdio.h>
#include <stdbool.h>
#define maxN 20
struct nodeLink
{
char node1;
char node2;
};
struct stack
{
int sp;
char node[maxN];
};
void initStk(stk)
struct stack *stk;
{
int i;
for (i = 0; i < maxN; i++)
stk->node[i] = ' ';
stk->sp = -1;
}
void pushIn(stk, node)
struct stack *stk;
char node;
{
stk->sp++;
stk->node[stk->sp] = node;
}
void popOutAll(stk)
struct stack *stk;
{
char node;
int i, stkN = stk->sp;
for (i = 0; i <= stkN; i++)
{
node = stk->node[i];
if (i == 0)
printf("src node : %c", node);
else if (i == stkN)
printf(" => %c : dst node.\n", node);
else
printf(" => %c ", node);
}
}
/* Test whether the node already exists in the stack */
bool InStack(stk, InterN)
struct stack *stk;
char InterN;
{
int i, stkN = stk->sp; /* 0-based */
bool rtn = false;
for (i = 0; i <= stkN; i++)
{
if (stk->node[i] == InterN)
{
rtn = true;
break;
}
}
return rtn;
}
char otherNode(targetNode, lnkNode)
char targetNode;
struct nodeLink *lnkNode;
{
return (lnkNode->node1 == targetNode) ? lnkNode->node2 : lnkNode->node1;
}
int entries = 8;
struct nodeLink topo[maxN] =
{
{'b', 'a'},
{'b', 'e'},
{'b', 'd'},
{'f', 'b'},
{'a', 'c'},
{'c', 'f'},
{'c', 'e'},
{'f', 'e'},
};
char srcNode = 'b', dstN = 'e';
int reachTime;
void InterNode(interN, stk)
char interN;
struct stack *stk;
{
char otherInterN;
int i, numInterN = 0;
static int entryTime = 0;
entryTime++;
for (i = 0; i < entries; i++)
{
if (topo[i].node1 != interN && topo[i].node2 != interN)
{
continue;
}
otherInterN = otherNode(interN, &topo[i]);
numInterN++;
if (otherInterN == stk->node[stk->sp - 1])
{
continue;
}
/* Loop avoidance: abandon the route */
if (InStack(stk, otherInterN) == true)
{
continue;
}
pushIn(stk, otherInterN);
if (otherInterN == dstN)
{
popOutAll(stk);
reachTime++;
stk->sp --; /* back trace one node */
continue;
}
else
InterNode(otherInterN, stk);
}
stk->sp --;
}
int main()
{
struct stack stk;
initStk(&stk);
pushIn(&stk, srcNode);
reachTime = 0;
InterNode(srcNode, &stk);
printf("\nNumber of all possible and unique routes = %d\n", reachTime);
}
A: This may be late, but here's the same C# version of DFS algorithm in Java from Casey to traverse for all paths between two nodes using a stack. Readability is better with recursive as always.
void DepthFirstIterative(T start, T endNode)
{
var visited = new LinkedList<T>();
var stack = new Stack<T>();
stack.Push(start);
while (stack.Count != 0)
{
var current = stack.Pop();
if (visited.Contains(current))
continue;
visited.AddLast(current);
var neighbours = AdjacentNodes(current);
foreach (var neighbour in neighbours)
{
if (visited.Contains(neighbour))
continue;
if (neighbour.Equals(endNode))
{
visited.AddLast(neighbour);
printPath(visited));
visited.RemoveLast();
break;
}
}
bool isPushed = false;
foreach (var neighbour in neighbours.Reverse())
{
if (neighbour.Equals(endNode) || visited.Contains(neighbour) || stack.Contains(neighbour))
{
continue;
}
isPushed = true;
stack.Push(neighbour);
}
if (!isPushed)
visited.RemoveLast();
}
}
This is a sample graph to test:
// Sample graph. Numbers are edge ids
// 1 3
// A --- B --- C ----
// | | 2 |
// | 4 ----- D |
// ------------------
A: The National Institute of Standards and Technology (NIST) online Dictionary of Algorithms and Data Structures lists this problem as "all simple paths" and recommends a depth-first search. CLRS supplies the relevant algorithms.
A clever technique using Petri Nets is found here
A: Here is the pseudocode I came up with. This is not any particular pseudocode dialect, but should be simple enough to follow.
Anyone want to pick this apart.
*
*[p] is a list of vertices representing the current path.
*[x] is a list of paths where meet the criteria
*[s] is the source vertex
*[d] is the destination vertex
*[c] is the current vertex (argument to the PathFind routine)
Assume there is an efficient way to look up the adjacent vertices (line 6).
1 PathList [p]
2 ListOfPathLists [x]
3 Vertex [s], [d]
4 PathFind ( Vertex [c] )
5 Add [c] to tail end of list [p]
6 For each Vertex [v] adjacent to [c]
7 If [v] is equal to [d] then
8 Save list [p] in [x]
9 Else If [v] is not in list [p]
10 PathFind([v])
11 Next For
12 Remove tail from [p]
13 Return
A: It appears that this can be accomplished with a depth-first search of the graph. The depth-first search will find all non-cyclical paths between two nodes. This algorithm should be very fast and scale to large graphs (The graph data structure is sparse so it only uses as much memory as it needs to).
I noticed that the graph you specified above has only one edge that is directional (B,E). Was this a typo or is it really a directed graph? This solution works regardless. Sorry I was unable to do it in C, I'm a bit weak in that area. I expect that you will be able to translate this Java code without too much trouble though.
Graph.java:
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class Graph {
private Map<String, LinkedHashSet<String>> map = new HashMap();
public void addEdge(String node1, String node2) {
LinkedHashSet<String> adjacent = map.get(node1);
if(adjacent==null) {
adjacent = new LinkedHashSet();
map.put(node1, adjacent);
}
adjacent.add(node2);
}
public void addTwoWayVertex(String node1, String node2) {
addEdge(node1, node2);
addEdge(node2, node1);
}
public boolean isConnected(String node1, String node2) {
Set adjacent = map.get(node1);
if(adjacent==null) {
return false;
}
return adjacent.contains(node2);
}
public LinkedList<String> adjacentNodes(String last) {
LinkedHashSet<String> adjacent = map.get(last);
if(adjacent==null) {
return new LinkedList();
}
return new LinkedList<String>(adjacent);
}
}
Search.java:
import java.util.LinkedList;
public class Search {
private static final String START = "B";
private static final String END = "E";
public static void main(String[] args) {
// this graph is directional
Graph graph = new Graph();
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "A");
graph.addEdge("B", "D");
graph.addEdge("B", "E"); // this is the only one-way connection
graph.addEdge("B", "F");
graph.addEdge("C", "A");
graph.addEdge("C", "E");
graph.addEdge("C", "F");
graph.addEdge("D", "B");
graph.addEdge("E", "C");
graph.addEdge("E", "F");
graph.addEdge("F", "B");
graph.addEdge("F", "C");
graph.addEdge("F", "E");
LinkedList<String> visited = new LinkedList();
visited.add(START);
new Search().depthFirst(graph, visited);
}
private void depthFirst(Graph graph, LinkedList<String> visited) {
LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());
// examine adjacent nodes
for (String node : nodes) {
if (visited.contains(node)) {
continue;
}
if (node.equals(END)) {
visited.add(node);
printPath(visited);
visited.removeLast();
break;
}
}
for (String node : nodes) {
if (visited.contains(node) || node.equals(END)) {
continue;
}
visited.addLast(node);
depthFirst(graph, visited);
visited.removeLast();
}
}
private void printPath(LinkedList<String> visited) {
for (String node : visited) {
System.out.print(node);
System.out.print(" ");
}
System.out.println();
}
}
Program Output:
B E
B A C E
B A C F E
B F E
B F C E
A: I have solved a similar problem to this recently, instead of all solutions I was only interested in the shortest.
I used a 'breadth first' iterative search which used a queue of status' each of which held a record containing a current point on the graph and the path taken to get there.
you start with a single record in the queue, which has the starting node and an empty path.
Each iteration through the code takes the item off the head of the list, and checks to see if it is a solution (the node arrived at is the one you want, if it is, we are done), otherwise, it constructs a new queue item with the nodes connecting to the current node, and amended paths that are based on the path of the previous node, with the new jump attached at the end.
Now, you could use something similar, but when you find a solution, instead of stopping, add that solution to your 'found list' and continue.
You need to keep track of a visited nodes list, so that you never backtrack on yourself otherwise you have an infinite loop.
if you want a bit more pseudocode post a comment or something, and I will elaborate.
A: I think you should describe your real problem behind this. I say this because you ask for something time efficient, yet the answer set to the problem seems to grow exponentially!
Therefore I wouldn't expect a better algorithm than something exponential.
I'd do backtracking and going through the whole graph. In order to avoid cycles, save all visited nodes along the way. When you go back, unmark the node.
Using recursion:
static bool[] visited;//all false
Stack<int> currentway; initialize empty
function findnodes(int nextnode)
{
if (nextnode==destnode)
{
print currentway
return;
}
visited[nextnode]=true;
Push nextnode to the end of currentway.
for each node n accesible from nextnode:
findnodes(n);
visited[nextnode]=false;
pop from currenteay
}
Or is that wrong?
edit:
Oh, and I forgot:
You should eliminate the recursive calls by utilizing that node stack
A: The basic principle is you need not worry about graphs.This is standard problem known as Dynamic connectivity problem. There are following types of methods from which you can achieve nodes are connected or not:
*
*Quick Find
*Quick Union
*Improved Algorithm (Combination of both)
Here is The C Code That I've tried with minimum time complexity O(log*n) That means for 65536 list of edges, it requires 4 search and for 2^65536, it requires 5 search. I am sharing my implementation from the algorithm: Algorithm Course from Princeton university
TIP: You can find Java solution from link shared above with proper explanations.
/* Checking Connection Between Two Edges */
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
/*
Data structure used
vertex[] - used to Store The vertices
size - No. of vertices
sz[] - size of child's
*/
/*Function Declaration */
void initalize(int *vertex, int *sz, int size);
int root(int *vertex, int i);
void add(int *vertex, int *sz, int p, int q);
int connected(int *vertex, int p, int q);
int main() //Main Function
{
char filename[50], ch, ch1[MAX];
int temp = 0, *vertex, first = 0, node1, node2, size = 0, *sz;
FILE *fp;
printf("Enter the filename - "); //Accept File Name
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("File does not exist");
exit(1);
}
while (1)
{
if (first == 0) //getting no. of vertices
{
ch = getc(fp);
if (temp == 0)
{
fseek(fp, -1, 1);
fscanf(fp, "%s", &ch1);
fseek(fp, 1, 1);
temp = 1;
}
if (isdigit(ch))
{
size = atoi(ch1);
vertex = (int*) malloc(size * sizeof(int)); //dynamically allocate size
sz = (int*) malloc(size * sizeof(int));
initalize(vertex, sz, size); //initialization of vertex[] and sz[]
}
if (ch == '\n')
{
first = 1;
temp = 0;
}
}
else
{
ch = fgetc(fp);
if (isdigit(ch))
temp = temp * 10 + (ch - 48); //calculating value from ch
else
{
/* Validating the file */
if (ch != ',' && ch != '\n' && ch != EOF)
{
printf("\n\nUnkwown Character Detected.. Exiting..!");
exit(1);
}
if (ch == ',')
node1 = temp;
else
{
node2 = temp;
printf("\n\n%d\t%d", node1, node2);
if (node1 > node2)
{
temp = node1;
node1 = node2;
node2 = temp;
}
/* Adding the input nodes */
if (!connected(vertex, node1, node2))
add(vertex, sz, node1, node2);
}
temp = 0;
}
if (ch == EOF)
{
fclose(fp);
break;
}
}
}
do
{
printf("\n\n==== check if connected ===");
printf("\nEnter First Vertex:");
scanf("%d", &node1);
printf("\nEnter Second Vertex:");
scanf("%d", &node2);
/* Validating The Input */
if( node1 > size || node2 > size )
{
printf("\n\n Invalid Node Value..");
break;
}
/* Checking the connectivity of nodes */
if (connected(vertex, node1, node2))
printf("Vertex %d and %d are Connected..!", node1, node2);
else
printf("Vertex %d and %d are Not Connected..!", node1, node2);
printf("\n 0/1: ");
scanf("%d", &temp);
} while (temp != 0);
free((void*) vertex);
free((void*) sz);
return 0;
}
void initalize(int *vertex, int *sz, int size) //Initialization of graph
{
int i;
for (i = 0; i < size; i++)
{
vertex[i] = i;
sz[i] = 0;
}
}
int root(int *vertex, int i) //obtaining the root
{
while (i != vertex[i])
{
vertex[i] = vertex[vertex[i]];
i = vertex[i];
}
return i;
}
/* Time Complexity for Add --> logn */
void add(int *vertex, int *sz, int p, int q) //Adding of node
{
int i, j;
i = root(vertex, p);
j = root(vertex, q);
/* Adding small subtree in large subtree */
if (sz[i] < sz[j])
{
vertex[i] = j;
sz[j] += sz[i];
}
else
{
vertex[j] = i;
sz[i] += sz[j];
}
}
/* Time Complexity for Search -->lg* n */
int connected(int *vertex, int p, int q) //Checking of connectivity of nodes
{
/* Checking if root is same */
if (root(vertex, p) == root(vertex, q))
return 1;
return 0;
}
A: find_paths[s, t, d, k]
This question is old and answered already. However, none show perhaps a more flexible algorithm for accomplishing the same thing. So I'll throw my hat into the ring.
I personally find an algorithm of the form find_paths[s, t, d, k] useful, where:
*
*s is the starting node
*t is the target node
*d is the maximum depth to search
*k is the number of paths to find
Using your programming language's form of infinity for d and k will give you all paths§.
§ obviously if you are using a directed graph and you want all undirected paths between s and t you will have to run this both ways:
find_paths[s, t, d, k] <join> find_paths[t, s, d, k]
Helper Function
I personally like recursion, although it can difficult some times, anyway first lets define our helper function:
def find_paths_recursion(graph, current, goal, current_depth, max_depth, num_paths, current_path, paths_found)
current_path.append(current)
if current_depth > max_depth:
return
if current == goal:
if len(paths_found) <= number_of_paths_to_find:
paths_found.append(copy(current_path))
current_path.pop()
return
else:
for successor in graph[current]:
self.find_paths_recursion(graph, successor, goal, current_depth + 1, max_depth, num_paths, current_path, paths_found)
current_path.pop()
Main Function
With that out of the way, the core function is trivial:
def find_paths[s, t, d, k]:
paths_found = [] # PASSING THIS BY REFERENCE
find_paths_recursion(s, t, 0, d, k, [], paths_found)
First, lets notice a few thing:
*
*the above pseudo-code is a mash-up of languages - but most strongly resembling python (since I was just coding in it). A strict copy-paste will not work.
*[] is an uninitialized list, replace this with the equivalent for your programming language of choice
*paths_found is passed by reference. It is clear that the recursion function doesn't return anything. Handle this appropriately.
*here graph is assuming some form of hashed structure. There are a plethora of ways to implement a graph. Either way, graph[vertex] gets you a list of adjacent vertices in a directed graph - adjust accordingly.
*this assumes you have pre-processed to remove "buckles" (self-loops), cycles and multi-edges
A: Here's a thought off the top of my head:
*
*Find one connection. (Depth-first search is probably a good algorithm for this, since the path length doesn't matter.)
*Disable the last segment.
*Try to find another connection from the last node before the previously disabled connection.
*Goto 2 until there are no more connections.
A: As far as I can tell the solutions given by Ryan Fox (58343, Christian (58444), and yourself (58461) are about as good as it get. I do not believe that breadth-first traversal helps in this case, as you will not get all paths. For example, with edges (A,B), (A,C), (B,C), (B,D) and (C,D) you will get paths ABD and ACD, but not ABCD.
A: I found a way to enumerate all the paths including the infinite ones containing loops.
http://blog.vjeux.com/2009/project/project-shortest-path.html
Finding Atomic Paths & Cycles
Definition
What we want to do is find all the possible paths going from point A to point B. Since there are cycles involved, you can't just go through and enumerate them all. Instead, you will have to find atomic path that doesn't loop and the smallest possible cycles (you don't want your cycle to repeat itself).
The first definition I took of an atomic path is a path that does not go through the same node twice. However, I found out that is was not taking all possibilities. After some reflexion, I figured out that nodes aren't important, however edges are! So an atomic path is a path that does not go through the same edge twice.
This definition is handy, it also works for cycles: an atomic cycle of point A is an atomic path that goes from point A and ends to point A.
Implementation
Atomic Paths A -> B
In order to get all the path starting from point A, we are going to traverse the graph recursively from the point A. While going through a child, we are going to make a link child -> parent in order to know all the edges we have already crossed. Before we go to that child, we must traverse that linked list and make sure the specified edge has not been already walked through.
When we arrive to the destination point, we can store the path we found.
Freeing the list
A problem occurs when you want to free the linked list. It is basically a tree chained in the reverse order. A solution would be to double-link that list and when all the atomic paths been found, free the tree from the starting point.
But a clever solution is to use a reference counting (inspired from Garbage Collection). Each time you add a link to a parent you adds one to its reference count. Then, when you arrive at the end of a path, you go backward and free while the reference count equals to 1. If it is higher, you just remove one and stop.
Atomic Cycle A
Looking for the atomic cycle of A is the same as looking for the atomic path from A to A. However there are several optimizations we can do. First, when we arrive at the destination point, we want to save the path only if the sum of the edges cost is negative: we only want to go through absorbing cycles.
As you have seen previously, the whole graph is being traversed when looking for an atomic path. Instead, we can limit the search area to the strongly connected component containing A. Finding these components requires a simple traverse of the graph with Tarjan's algorithm.
Combining Atomic Paths and Cycles
At this point, we have all the atomic paths that goes from A to B and all the atomic cycles of each node, left to us to organize everything to get the shortest path. From now on we are going to study how to find the best combination of atomic cycles in an atomic path.
A: As ably described by some of the other posters, the problem in a nutshell is that of using a depth-first search algorithm to recursively search the graph for all combinations of paths between the communicating end nodes.
The algorithm itself commences with the start node you give it, examines all its outgoing links and progresses by expanding the first child node of the search tree that appears, searching progressively deeper and deeper until a target node is found, or until it encounters a node that has no children.
The search then backtracks, returning to the most recent node it hasn’t yet finished exploring.
I blogged about this very topic quite recently, posting an example C++ implementation in the process.
A: Adding to Casey Watson's answer, here is another Java implementation,.
Initializing the visited node with the start node.
private void getPaths(Graph graph, LinkedList<String> visitedNodes) {
LinkedList<String> adjacent = graph.getAdjacent(visitedNodes.getLast());
for(String node : adjacent){
if(visitedNodes.contains(node)){
continue;
}
if(node.equals(END)){
visitedNodes.add(node);
printPath(visitedNodes);
visitedNodes.removeLast();
}
visitedNodes.add(node);
getPaths(graph, visitedNodes);
visitedNodes.removeLast();
}
}
A: gg1=nx.from_edgelist([('A','B'),('A','C'),('B','A'),('B','D'),('B','E'),('B','F'),('C','A'),('C','E'),
('C','F'),('D','B'),('E','C'),('E','F'),('F','B'),('F','C'),('F','E')],create_using=nx.DiGraph)
pd.Series(nx.all_simple_paths(gg1, source='B', target='E'))
out
0 [B, A, C, E]
1 [B, A, C, F, E]
2 [B, E]
3 [B, F, C, E]
4 [B, F, E]
dtype: object
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "121"
} |
Q: CSS / JavaScript Navigation Menu on top of Flash in Firefox My site has a drop-down menu built in CSS and JavaScript that drops down over a Flash animation. In IE (6&7) the drop-down menus drop over the Flash animation, however, in Firefox (2&3) the menus appear underneath the Flash animation. Is there any way to get this dynamic menu to flow OVER the Flash in Firefox?
In IE 7 menu appears over the Flash:
In Firefox the menu appears under the Flash: (How can I fix this?!)
A: Try setting wmode to transparent - see here
A: wmode=opaque seemed to work for me
I did it here:www.toolgal.com, hover over the products menu on the top navigation
Dan
A: Use z-index and set the menu to something like 100 and the flash movie to something in the negative like.....say -1.
Cheers
A: Have you tried the iframe trick (i.e. floating an iframe behind the menu, thus putting hte flash layers behind.)
A: The iframe-trick is only for IE (below IE7), so it probably would never help in Firefox.
I'd try to enable wmode=transparent, so that the Flash content won't get its own HWND
A: Enabling wmode=transparent is the way to go. But also note, that Firefox in Linux does not obey that, and the flash will always be on top.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to test a WPF user interface? Using win forms with an MVC/MVP 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.
Would this be a viable approach to testing a WPF app? Is there a better way? Are there any gotchas to watch out for?
A: Because the Coded UI framework expires after Visual Studio version 2019 (Deprecated Coded UI), Microsoft recommends Appium with WinAppDriver for testing Windows applications (Desktop and UWP). You can use Appium (with WinAppDriver) or WinAppDriver directly to run the tests (WinAppDriver with or without Appium).
WinAppDriver directly
Here is a short description to work with the WinAppDriver directly:
*
*download and install WinAppDriver:
WinAppDriver Release
*enable Developer Mode in Windows settings
*start the WinAppDriver:
C:\Program Files (x86)\Windows Application Driver\WinAppDriver.exe
*create a new Visual Studio 2019 Unit Test Project (.NET Framework)
*add the NuGet-Package: Appium.WebDriver Microsoft.WinAppDriver.Appium.WebDriver (comment from Microsoft: it is recommenced to use the WinAppDriver NuGet package to take full advantage of the advanced input with the Actions API.)
*add a new class DesktopSession:
public class DesktopSession
{
protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
private const string NotepadAppId = @"C:\Windows\System32\notepad.exe";
protected static WindowsDriver<WindowsElement> session;
protected static WindowsElement editBox;
public static void Setup(TestContext context)
{
// Launch a new instance of Notepad application
if (session == null)
{
// Create a new session to launch Notepad application
var appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", NotepadAppId);
appCapabilities.SetCapability("platformName", "Windows");
appCapabilities.SetCapability("deviceName ", "WindowsPC");
session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
Assert.IsNotNull(session);
Assert.IsNotNull(session.SessionId);
// Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1.5);
// Keep track of the edit box to be used throughout the session
editBox = session.FindElementByClassName("Edit");
Assert.IsNotNull(editBox);
}
}
public static void TearDown()
{
// Close the application and delete the session
if (session != null)
{
session.Close();
try
{
// Dismiss Save dialog if it is blocking the exit
session.FindElementByName("Nicht speichern").Click();
}
catch { }
session.Quit();
session = null;
}
}
[TestInitialize]
public void TestInitialize()
{
// Select all text and delete to clear the edit box
editBox.SendKeys(Keys.Control + "a" + Keys.Control);
editBox.SendKeys(Keys.Delete);
Assert.AreEqual(string.Empty, editBox.Text);
}
}
*
*Change the code from the UnitTest1 class
[TestClass]
public class UnitTest1 : DesktopSession
{
[TestMethod]
public void EditorEnterText()
{
Thread.Sleep(TimeSpan.FromSeconds(2));
editBox.SendKeys("abcdeABCDE 12345");
Assert.AreEqual(@"abcdeABCDE 12345", editBox.Text);
}
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
Setup(context);
}
[ClassCleanup]
public static void ClassCleanup()
{
TearDown();
}
}
*
*run your test
(the sample code is mainly copied from WinAppDriver
.NotepadTest).
Appium with WinAppDriver
If you want to run your tests using Appium, then you must have installed the correct version of the WinAppDriver on your machine. The installer of Appium should also install the WinAppDriver with the correct version on your machine (please install Appium for all users).
In my case, unfortunately, this did not work. So I take a look in the file:
C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-windows-driver\lib\installer.js
Here you will find the correct version and the download path:
const WAD_VER = "1.1";
const WAD_DL = `https://github.com/Microsoft/WinAppDriver/releases/download/v${WAD_VER}/WindowsApplicationDriver.msi`;
If you have installed the correct WinAppDriver you can start Appium.
Important: you have to change the ApplicationDriverUrl
protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723/wd/hub";
Tools:
*
*WindowsAppDriver UI Recorder
WindowsAppDriver and UI REcorder releases
or
Donwload the WinAppDriver repository and build the WinAppDriverUIRecorder.sln in the subdirectory tools\UIRecorder
Introducing WinAppDriver UI Recorder
*
*inspect.exe: Windows SDK is required (look in C:\Program Files (x86)\Windows Kits\10\bin)
Other links:
WinAppDriver FAQ
Appium
A: As for the testing itself, you're probably best off using the UI Automation framework. Or if you want a more fluent and wpf/winforms/win32/swt-independent way of using the framework, you could download White from Codeplex (provided that you're in a position to use open source code in your environment).
For the gotchas; If you're trying to 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). Mike Two 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 this post, and he also points to this article by Chris Hedgate. Chris uses a modified version of Peter Provost's CrossThreadTestRunner to wrap the MTA/STA issues in a bit more friendly way.
A: The question is still relevant, but many of the answers got obsolete. @deadpikle
suggested a very good solution in the comment, I tried it and I want to make it as an answer in order to more people see it.
So, here is a library https://github.com/FlaUI/FlaUI. Here is a quick start guide for WPF app:
*
*Install FlaUI.UIA3 from nuget
*Write this to test if app runs correctly (but insert your string literals):
using FlaUI.Core;
using FlaUI.Core.AutomationElements;
using FlaUI.UIA3;
using FluentAssertions;
using System;
using Xunit;
namespace Functional
{
public sealed class General : IDisposable
{
private readonly Application _app = Application.Launch(@"..\App.exe");
[Fact]
public void AppStarts()
{
using var automation = new UIA3Automation();
Window window = _app.GetMainWindow(automation, TimeSpan.FromSeconds(3));
window.Should().NotBeNull("null means the window failed to load");
window.Title.Should().Be("App title",
"otherwise, it could be message box with error in case of the wrong configuration");
}
public void Dispose()
{
_app.Close();
_app.Dispose();
}
}
}
This code also works well in the GitHub Actions pipeline.
A: 2016 Update: Use the free TestStack.White framework to automate WPF UI testing
*
*Project White has been abandoned, but its successor TestStack.White is available via a NuGet package.
*TestStack.White has utility methods for starting WPF apps, finding window/user control elements, clicking buttons/elements, simulating mouse and keyboard events, waiting, etc..
*An example that will launch a WPF app, click a button, and check for result looks like the following:
using TestStack.White;
using TestStack.White.UIItems;
using TestStack.White.Factory;
[TestMethod]
public void TestDoSomething()
{
//Opens the app
var app = Application.Launch("MyApp.exe");
//Finds the main window (this and above line should be in [TestInitialize])
var window = app.GetWindow("My App Window Title", InitializeOption.NoCache);
//Finds the button (see other Get...() methods for options)
var btnMyButton = window.Get<Button>("btnMyButtonWPFname");
//Simulate clicking
btnMyButton.Click();
//Gets the result text box
//Note: TextBox/Button is in TestStack.White.UIItems namespace
var txtMyTextBox = window.Get<TextBox>("txtMyTextBox");
//Check for the result
Assert.IsTrue(txtMyTextBox.Text == "my expected result");
//Close the main window and the app (preferably in [TestCleanup])
app.Close();
}
A: @Matt David,
Please read documentation and take a look at the code samples for Microsoft CompositeWPF (aka Prism). It's a project created specifically to teach how to deal with MVP/MVC architecture in test-driven manner. Their sample application contains unit tests for presenters\controllers and very cool acceptance tests for UI (they use White framework to simulate user actions)
A: Manually. I'm not a big fan of automated UI testing if that is what you're getting at. I'm not sure about the WPF guidances (need to read thru aku's links).. because they are still solidifying so to speak... WPF has not stabilized from the point of 'what is the right way'. Unless you're using one of these evolving frameworks.. I'd be conservative w.r.t. effort
*
*Test (Automated preferably TDDed) the logic/presenters/controllers ruthlessly. I'm not advocating sloppiness or lethargy.
*Keep the UI skin thin and get some nasty testers to go have a (manual) crack at it with exploratory testing - nothing is as good as a 'tester from Hell' when it comes to UIs. The effort : gain ratio from automating this kind of testing is huge, doesn't catch everything and doesn't make sense... except to pacify the higher ups 'Look Mgr! No hands! self-testing UIs!'
PS: you may want to watch this (Mary Poppendieck's Google Talk on Lean).. especially the part about what to automate in testing
A: Definitely look at TestAutomationFX.com. One can invest (OK, I did) a lot of time trying to capture / record events with White. (At the start of my quest I ignored the post or two in other places referring to it).
I of course second the other points about the best type of testing not being UI testing.
But if someone is going to do something automatable in the UI to get around shortcomings in other types of testing coverage, TAFX seems the quickest route there.
A: Try Ranorex V2.0 for WPF automation. With RanoreXPath and Ranorex repository test automation code could be completely seperated from identification information. Ranorex also provides a capture/replay editor based on RanoreXPath objects.
A: I would recommend TestAutomationFX as well for simple automation of ui testing. TestAutomationFX lets you work with netAdvantage tools for wpf aswell , which doesnt work with white and QTP. TestAutomationFX has a easy to use interface , it integrates with visual studio and has a good recorder for recording user events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
} |
Q: Recent Projects panel on VS2008 not working for fresh installs The Recent Projects panel on the Start Page of VS2008 Professional doesn't appear to work, and constantly remains empty.
I've noticed this on 3 of our developers VS2008 installations, in fact all the installations that weren't updated from 2005 but installed from scratch. I generally treat this as a bit of a curiosity, but now I have a new laptop and fresh install of VS2008, it's also happening to me, and I've upgraded the phenomena from a curio to an annoyance.
Anyone know if this is a bug or if there is a setting I'm missing somewhere.
Thanks
EDIT Thanks, but Tools | Options | Environment | General | "items shown in recently used lists" was and is set to 6 by default
A: Is Tools | Options | Environment | General | "items shown in recently used lists" set to a number greater than 0?
A: Finally worked it out!
The recent projects is driven by (or at least shares a 'Show' flag with) the Recent Documents in the Start Menu.
For some reason our SOE has this hidden.
Both the following need th be set to 0:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoRecentDocsHistory HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoRecentDocsMenu
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Algorithm/Data Structure Design Interview Questions What are some simple algorithm or data structure related "white boarding" problems that you find effective during the candidate screening process?
I have some simple ones that I use to validate problem solving skills and that can be simply expressed but have some opportunity for the application of some heuristics.
One of the basics that I use for junior developers is:
Write a C# method that takes a string which contains a set of words (a sentence) and rotates those words X number of places to the right. When a word in the last position of the sentence is rotated it should show up at the front of the resulting string.
When a candidate answers this question I look to see that they available .NET data structures and methods (string.Join, string.Split, List, etc...) to solve the problem. I also look for them to identify special cases for optimization. Like the number of times that the words need to be rotated isn't really X it's X % number of words.
What are some of the white board problems that you use to interview a candidate and what are some of the things you look for in an answer (do not need to post the actual answer).
A: *
*Write a method that takes a string, and returns true if that string is a number.(anything with regex as the most effective answer for an interview)
*Please write an abstract factory method, that doesn't contain a switch and returns types with the base type of "X". (Looking for patterns, looking for reflection, looking for them to not side step and use an if else if)
*Please split the string "every;thing|;|else|;|in|;|he;re" by the token "|;|".(multi character tokens are not allowed at least in .net, so looking for creativity, the best solution is a total hack)
A: Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
A: Follow up any question like this with: "How could you improve this code so the developer who maintains it can figure out how it works easily?"
A: Implement a function that, given a linked list that may be circular, swaps the first two elements, the third with the fourth, etc...
A: I like to go over a code the person actually wrote and have them explain it to me.
A: I enjoy the classic "what's the difference between a LinkedList and an ArrayList (or between a linked list and an array/vector) and why would you choose one or the other?"
The kind of answer I hope for is one that includes discussion of:
*
*insertion performance
*iteration performance
*memory allocation/reallocation impact
*impact of removing elements from the beginning/middle/end
*how knowing (or not knowing) the maximum size of the list can affect the decision
A: Once when I was interviewing for Microsoft in college, the guy asked me how to detect a cycle in a linked list.
Having discussed in class the prior week the optimal solution to the problem, I started to tell him.
He told me, "No, no, everybody gives me that solution. Give me a different one."
I argued that my solution was optimal. He said, "I know it's optimal. Give me a sub-optimal one."
At the same time, it's a pretty good problem.
A: A trivial one is to ask them to code up a breadth-first search of a tree from scratch. Yeah, if you know what you're doing it is trivial. But a lot of programmers don't know how to tackle it.
One that I find more useful still is as follows. I've given this in a number of languages, here is a Perl version. First I give them the following code sample:
# @a and @b are two arrays which are already populated.
my @int;
OUTER: for my $x (@a) {
for my $y (@b) {
if ($x eq $y) {
push @int, $x;
next OUTER;
}
}
}
Then I ask them the following questions. I ask them slowly, give people time to think, and am willing to give them nudges:
*
*What is in @int when this code is done?
*This code is put into production and there is a performance problem that is tracked back to this code. Explain the potential performance problem. (If they are struggling I'll ask how many comparisons it takes if @a and @b each have 100,000 elements. I am not looking for specific terminology, just a back of the envelope estimate.)
*Without code, suggest to make this faster. (If they propose a direction that is easy to code, I'll ask them to code it. If they think of a solution that will result in @int being changed in any way (eg commonly order), I'll push to see whether they realize that they shouldn't code the fix before checking whether that matters.)
If they come up with a slightly (or very) wrong solution, the following silly data set will find most mistakes you run across:
@a = qw(
hello
world
hello
goodbye
earthlings
);
@b = qw(
earthlings
say
hello
earthlings
);
I'd guess that about 2/3 of candidates fail this question. I have yet to encounter a competent programmer who had trouble with it. I've found that people with good common sense and very little programming background do better on this than average programmers with a few years of experience.
I would suggest using these questions as filters. Don't hire someone because they can answer these. But if they can't answer these, then don't hire them.
A: Asking them to write a recursive algorithm for a well known iterative solution (i.e. Fibonacci etc. -- we give them an iterative function, if needed) and then have them compute the run time for it.
Many times the recursive function involves a tree data structure. The number of times the person has failed to recognize that baffles me. It becomes slightly difficult to calculate the run time until you can see that it's a tree structure...
I find that this problem covers many areas. Namely, their code-reading ability (if they are given an iterative function), code-writing ability (since they write a recursive function), algorithm, data-structure (for run-time)...
A: When interviewing recently, I was often asked to implement a data structure, usually LinkedList or HashMap. Both of these are easy enough to be doable in a short time, and difficult enough to eliminate the clueless.
A: This doesn't necessarily touch on OOP capabilities but in our last set of interviews we used a selection of buggy code from the Bug of the Month list. Watching the candidates find the bugs shows their analytical capabilities, shows the know how to interpret somebody elses code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: Avoiding first chance exception messages when the exception is safely handled The following bit of code catches the EOS Exception
using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
So why do I still receive first-chance exceptions in my console?
A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll
Is there a way to hide these first chance exception messages?
A: The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it.
There's nothing to be concerned with. This is normal behavior.
A: I had this problem and couldn't figure out where the exception was thrown. So my solution was to enable Visual Studio to stop executing on this kind of exception.
*
*Navigate to "Debug/Exceptions"
*Expand the "Common Language Runtime Exceptions" tree.
*Expand the "System" branch.
*Scroll down to where "NullReferenceException" is, and check the
"throw" checkbox, and uncheck the "user-handled".
*Debug your project.
A: If you want more control over these messages, you can add a handler:
Friend Sub AddTheHandler()
AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceExceptionHandler
End Sub
<Conditional("DEBUG")>
Friend Sub FirstChanceExceptionHandler( source As Object, e As Runtime.ExceptionServices.FirstChanceExceptionEventArgs)
' Process first chance exception
End Sub
This allows you to silence them as mentioned in other comments, but still makes sure you are able to be aware of them. I find it is good to see how many I am really throwing if I log a message and timestamp to a text file.
A: *
*In Visual Studio you can change the settings for the way the Debugger handles (breaks on) exceptions.
Go to Debug > Exceptions. (Note this may not be in your menu depending on your Visual Studio Environment setting. If not just add it to your menu using the Customize menu.)
There you are presented with a dialog of exceptions and when to break on them.
In the line "Common Language Runtime Exceptions" you can deselect thrown (which should then stop bothering you about first-chance exceptions) and you can also deselect User-unhandeled (which I would not recommend) if want to.
*The message you are getting should not be in the console, but should be appearing in the 'Output' window of Visual Studio. If the latter is the case, then I have not found a possibility to remove that, but it doesn't appear if you run the app without Visual Studio.
A: Actually if are having many exceptions per second, you would achieve must better performance by checking reader.EndOfStream-value.. Printing out those exception messages is unbelievably slow, and hiding them in visual studio won't speed up anything.
A: To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages".
However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.
A: Unlike Java, .NET exceptions are fairly expensive in terms of processing power, and handled exceptions should be avoided in the normal and successful execution path.
Not only will you avoid clutter in the console window, but your performance will improve, and it will make performance counters like .NET CLR Exceptions more meaningful.
In this example you would use
while (reader.PeekChar() != -1)
{
bodyByteList.Add(reader.ReadByte());
}
A: I think the stream is throwing this exception, so your try is scoped to narrow to catch it.
Add a few more try catch combos around the different scopes until you catch it where its actually being thrown, but it appears to be happening either at our outside of your using, since the stream object is not created in the using's scope.
A: in VB.NET:
<DebuggerHidden()> _
Public Function Write(ByVal Text As String) As Boolean
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
} |
Q: Saving an open generic type in an array? I am facing a problem with .NET generics. The thing I want to do is saving an array of generics types (GraphicsItem):
public class GraphicsItem<T>
{
private T _item;
public void Load(T item)
{
_item = item;
}
}
How can I save such open generic type in an array?
A: Implement a non-generic interface and use that:
public class GraphicsItem<T> : IGraphicsItem
{
private T _item;
public void Load(T item)
{
_item = item;
}
public void SomethingWhichIsNotGeneric(int i)
{
// Code goes here...
}
}
public interface IGraphicsItem
{
void SomethingWhichIsNotGeneric(int i);
}
Then use that interface as the item in the list:
var values = new List<IGraphicsItem>();
A: If you want to store heterogeneous GrpahicsItem's i.e. GraphicsItem< X> and GrpahicsItem< Y> you need to derive them from common base class, or implement common interface. Another option is to store them in List< object>
A: Are you trying to create an array of GraphicsItem in a non-generic method?
You cannot do the following:
static void foo()
{
var _bar = List<GraphicsItem<T>>();
}
and then fill the list later.
More probably you are trying to do something like this?
static GraphicsItem<T>[] CreateArrays<T>()
{
GraphicsItem<T>[] _foo = new GraphicsItem<T>[1];
// This can't work, because you don't know if T == typeof(string)
// _foo[0] = (GraphicsItem<T>)new GraphicsItem<string>();
// You can only create an array of the scoped type parameter T
_foo[0] = new GraphicsItem<T>();
List<GraphicsItem<T>> _bar = new List<GraphicsItem<T>>();
// Again same reason as above
// _bar.Add(new GraphicsItem<string>());
// This works
_bar.Add(new GraphicsItem<T>());
return _bar.ToArray();
}
Remember you are going to need a generic type reference to create an array of a generic type. This can be either at method-level (using the T after the method) or at class-level (using the T after the class).
If you want the method to return an array of GraphicsItem and GraphicsItem, then let GraphicsItem inherit from a non-generic base class GraphicsItem and return an array of that. You will lose all type safety though.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mac font rendering on Windows I love the way Mac OS beautifully renders fonts (not just browsers). I was wondering if we could somehow get the same rendering in browsers running on Windows?
Someone recommended sIFR but I guess that's useful when I need to use non-standard fonts?
A: Check out GDI++/FreeType (link, link). It's a highly configurable font-rendering replacement for Windows. With some configuration of hinting, anti-aliasing, etc, you should be able to approximate OSX style font rendering fairly close.
A: use mactype
https://github.com/snowie2000/mactype
A: Not sure if this is a setup, but of course, Safari on Windows renders using the OS X rendering algorithm.
A: Brad is right: use Safari if you want the Mac font rendering algorithm.
Jeff and Joel have both blogged about this before (not surprisingly, around the time that Safari was released for Windows), if you would like more details:
http://www.codinghorror.com/blog/archives/000885.html
A: I'm assuming you would like to be ablt to use if globally, or at least in IE/Firefox, not just be installing Safari as other have suggested.
Back in the days wen Mac OS X was still in development, there was a plan to release the Cocoa framework for windows, to allow applications written to it to run natively on Windows with a recompile. I suspect that set of Cocoa windows libraries (Yellow Box wasn't it?) would have given you Mac OS X style font rendering but I don't think it was ever released (though you may be able to get very old beta versions of it from somewhere, and I have a feeling some of it was somehow part of WebObjects or something like that).
I suspect the windows version of Safari is using an internal version of the Cocoa libraries for Windows, whcih is why it has Mac OS X font rendering (though I believe recent nightly builds at least have the option to use Windows' native font rendering for those who were complaining about it looking out of place).
Anyway, long store short, unless you're going to write your own font renderer, I don't think there's any easy way to do it (other than using Safari)
A:
Someone recommended sIFR but I guess that's useful when I need to use non-standard fonts?
sIFR will not give you the intended effect. Like Windows's ClearType, Flash's anti-aliasing (which sIFR uses) optimizes towards the pixel grid, not towards accurate representation of the typeface.
You may be able to use Safari's bundled CoreGraphics library to do your font rendering, but you'd likely break Apple's license agreements (especially once you try to ship your app…).
A: I'm writing a Java application doing some interesting things with fonts and working with some graphic designers, and they want the same kind of font rendering you're talking about. I was able to get pretty close by turning on fractional metrics aka sub-pixel glyph placement accuracy, and anti-aliasing, which are the key differences between Mac and Windows font rendering. Looks pretty good for larger TrueType fonts.
Here's the Java code I used. It's all done with their native font rendering engine (which I believe may be FreeType, not sure exactly).
g.setFont(new Font("Century Schoolbook", Font.PLAIN, 36));
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Now if only I could figure out how to make OpenType CFF fonts work.
A: Microsoft Powertoy Cleartype Tuner lets you tweak the way Cleartype works. It might help a little bit. Not sure it works on anything newer than Windows XP though.
A: You could wait until IE9, which apparently has much better text rendering, using DirectX: http://blogs.msdn.com/ie/archive/2009/11/18/an-early-look-at-ie9-for-developers.aspx
A: If you want mac osx rendering in firefox, you must use extension Anti-Aliasing Tuner:
https://addons.mozilla.org/firefox/addon/anti-aliasing-tuner/
Just set anti-aliasing mode as Default and rendering mode as Outline for small and large fonts and you're done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: WPF Application fails on startup with TypeInitializationException I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".
The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."
Here is my app.xaml:
<Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
And here is my app.xaml.cs (exception thrown at "public App()"):
public partial class App : Application
{
public App()
{
Bootstrapper bootStrapper = new Bootstrapper();
bootStrapper.Run();
}
}
I have set the "App" class as the startup object in the project.
What is going astray?
A: Do you use .config file? If so, check it for errors. Initialization errors of such sort are often triggered by invalid XML: if there are no errors in XAML, XML config is the first place to look.
A: Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this:
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" sku="Client"/>
</startup>
<configSections>
<section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
<module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/>
</modules>
</configuration>
It seems the problem was the <startup> element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the "Client Profile" available in 3.5 SP1.
After some mucking about checking and un-checking the box I ended up with a configuration file like this:
<configuration>
<configSections>
<section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
<module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/>
</modules>
<startup>
<supportedRuntime version="v2.0.50727" sku="Client"/>
</startup>
</configuration>
Which works!
I'm not sure why the order of elements in the app.config is important - but it seems it is.
A: Tracking the InnerExceptions deep down , you might find the following error:
"Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element"
This order change happened after Visual Studio EntityFramework Wizard added the connectionStrings element to the top
A: If you only see the TypeInitializationException with no reason or no details on what's wrong, then disable Just My Code in the Visual Studio options.
A: For me, I had copied app settings over from another application into my app.config into a new section called "userSettings". However, there needs to be a "configSections" also added to the app.config which defines "userSettings". I deleted the userSettings section then edited the app settings and saved it. VS automatically creates the correct "userSettings" and "configSections" for you if they are absent.
A: Anything wrong in the App.config file may cause the error, such as a typo of * at the end of a line, eg ...</startup> has an additional "*" at the end of the line ...</startup>*.
A: You have two sections named "modules". Place both module definitions in one section named "modules".
A: I ran into a similar situation.
After searching for a week time, I found the resolution and it really worked for me.
It solved 2-3 problems arising due to same problem.
Follow these steps:
Check the WPF key (absence) in registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0\Setup\Windows Presentation Foundation
My problem was due to the absence of above mentioned key in registry.
You can modify and use following details in your registry: (Actually, you can save in file and import in registry)
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0\Setup\Windows Presentation Foundation]
@="WPF v3.0.6920.1453"
"Version"="3.0.6920.1453"
"WPFReferenceAssembliesPathx86"="C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\"
"WPFCommonAssembliesPathx86"="C:\Windows\System32\"
"InstallRoot"="C:\Windows\Microsoft.NET\Framework\v3.0\WPF\"
"InstallSuccess"=dword:00000001
"ProductVersion"="3.0.6920.1453"
"WPFNonReferenceAssembliesPathx86"="C:\Windows\Microsoft.NET\Framework\v3.0\WPF\"
I am sure it will work.
all the best.
Regards,
Umesh
A: In my case this is need to be added:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
Section at App.config (VS 2015 .NET 4.5.2)
Open any WPF project what builded before, check build, if OK - check and compare App.config's at both projects
A: For me I renamed my Application name and caused this error. I had a server and client app. the server app was not having this issue. so i checked App.config file of both server and client. I found
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup> tag above <configSections> tag in client and server had the other way so I copy pasted startup tag down configSections tag and it worked. Like this.
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
A: I was getting the same error. The suggestions mentioned above did not work for me. i was getting the following error after running
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'System.Windows.Application' threw an exception.
Source=PresentationFramework
StackTrace:
at System.Windows.Application..ctor()
at ShortBarDetectionSystem.App..ctor()
at ShortBarDetectionSystem.App.Main()
Inner Exception 1:
TypeInitializationException: The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception.
Inner Exception 2:
TypeInitializationException: The type initializer for 'MS.Internal.TraceDependencyProperty' threw an exception.
Inner Exception 3:
ConfigurationErrorsException: Configuration system failed to initialize
Inner Exception 4:
ConfigurationErrorsException: Section or group name 'oracle.manageddataaccess.client' is already defined. Updates to this may only occur at the configuration level where it is defined. (C:\ShortBarDetectionSystem\code\framework\TypeInitializationException\ver0_1\ShortBarDetectionSystem\ShortBarDetectionSystem\bin\x64\Debug\GrateBarDefectDetectionSystem.exe.Config line 4)
I was getting an error in my exe.config file line 4. The .exe.config file was :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
However after trial and error i figured out that deleting the configSections
<configSections>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: SQL set-based range How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.
I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range.
For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:
select sum(n) from numbers where n between 100 and 200
Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.
[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. See below.
A: I think the very short answer to your question is to use WITH clauses to generate your own.
Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a huge failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity.
So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly.
Oracle and T-SQL both support a WITH clause that can be used to do this. They work a little differently in the different DBMS's, and MS calls them "common table expressions", but they are very similar in form. Using these with recursion, you can generate a sequence of numbers or text values fairly easily. Here is what it might look like...
In Oracle SQL:
WITH
digits AS -- Limit recursion by just using it for digits.
(SELECT
LEVEL - 1 AS num
FROM
DUAL
WHERE
LEVEL < 10
CONNECT BY
num = (PRIOR num) + 1),
numrange AS
(SELECT
ones.num
+ (tens.num * 10)
+ (hundreds.num * 100)
AS num
FROM
digits ones
CROSS JOIN
digits tens
CROSS JOIN
digits hundreds
WHERE
hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed.
SELECT
-- Some columns and operations
FROM
numrange
-- Join to other data if needed
This is admittedly quite verbose. Oracle's recursion functionality is limited. The syntax is clunky, it's not performant, and it is limited to 500 (I think) nested levels. This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers.
I haven't used SQL Server's Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle. Whether performance is comparable, and what the nesting limits are, I don't know.
At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets. Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data. Aggregations, duplications, combinations, permutations, and so on. You can even use such generated data to aid in rolling up or drilling down into other data.
UPDATE: I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL. It's not just a scripting language. It's a fairly robust data-driven declarative language. Sometimes it's a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations. But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms.
A: I created a SQL CLR table valued function that works great for this purpose.
SELECT n FROM dbo.Range(1, 11, 2) -- returns odd integers 1 to 11
SELECT n FROM dbo.RangeF(3.1, 3.5, 0.1) -- returns 3.1, 3.2, 3.3 and 3.4, but not 3.5 because of float inprecision. !fault(this)
Here's the code:
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
[assembly: CLSCompliant(true)]
namespace Range {
public static partial class UserDefinedFunctions {
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = "FillRow", TableDefinition = "n bigint")]
public static IEnumerable Range(SqlInt64 start, SqlInt64 end, SqlInt64 incr) {
return new Ranger(start.Value, end.Value, incr.Value);
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = "FillRowF", TableDefinition = "n float")]
public static IEnumerable RangeF(SqlDouble start, SqlDouble end, SqlDouble incr) {
return new RangerF(start.Value, end.Value, incr.Value);
}
public static void FillRow(object row, out SqlInt64 n) {
n = new SqlInt64((long)row);
}
public static void FillRowF(object row, out SqlDouble n) {
n = new SqlDouble((double)row);
}
}
internal class Ranger : IEnumerable {
Int64 _start, _end, _incr;
public Ranger(Int64 start, Int64 end, Int64 incr) {
_start = start; _end = end; _incr = incr;
}
public IEnumerator GetEnumerator() {
return new RangerEnum(_start, _end, _incr);
}
}
internal class RangerF : IEnumerable {
double _start, _end, _incr;
public RangerF(double start, double end, double incr) {
_start = start; _end = end; _incr = incr;
}
public IEnumerator GetEnumerator() {
return new RangerFEnum(_start, _end, _incr);
}
}
internal class RangerEnum : IEnumerator {
Int64 _cur, _start, _end, _incr;
bool hasFetched = false;
public RangerEnum(Int64 start, Int64 end, Int64 incr) {
_start = _cur = start; _end = end; _incr = incr;
if ((_start < _end ^ _incr > 0) || _incr == 0)
throw new ArgumentException("Will never reach end!");
}
public long Current {
get { hasFetched = true; return _cur; }
}
object IEnumerator.Current {
get { hasFetched = true; return _cur; }
}
public bool MoveNext() {
if (hasFetched) _cur += _incr;
return (_cur > _end ^ _incr > 0);
}
public void Reset() {
_cur = _start; hasFetched = false;
}
}
internal class RangerFEnum : IEnumerator {
double _cur, _start, _end, _incr;
bool hasFetched = false;
public RangerFEnum(double start, double end, double incr) {
_start = _cur = start; _end = end; _incr = incr;
if ((_start < _end ^ _incr > 0) || _incr == 0)
throw new ArgumentException("Will never reach end!");
}
public double Current {
get { hasFetched = true; return _cur; }
}
object IEnumerator.Current {
get { hasFetched = true; return _cur; }
}
public bool MoveNext() {
if (hasFetched) _cur += _incr;
return (_cur > _end ^ _incr > 0);
}
public void Reset() {
_cur = _start; hasFetched = false;
}
}
}
and I deployed it like this:
create assembly Range from 'Range.dll' with permission_set=safe -- mod path to point to actual dll location on disk.
go
create function dbo.Range(@start bigint, @end bigint, @incr bigint)
returns table(n bigint)
as external name [Range].[Range.UserDefinedFunctions].[Range]
go
create function dbo.RangeF(@start float, @end float, @incr float)
returns table(n float)
as external name [Range].[Range.UserDefinedFunctions].[RangeF]
go
A: This is basically one of those things that reveal SQL to be less than ideal. I'm thinking maybe the right way to do this is to build a function that creates the range. (Or a generator.)
I believe the correct answer to your question is basically, "you can't".
(Sorry.)
A: You can use a common table expression to do this in SQL2005+.
WITH CTE AS
(
SELECT 100 AS n
UNION ALL
SELECT n + 1 AS n FROM CTE WHERE n + 1 <= 200
)
SELECT n FROM CTE
A: If using SQL Server 2000 or greater, you could use the table datatype to avoid creating a normal or temporary table. Then use the normal table operations on it.
With this solution you have essentially a table structure in memory that you can use almost like a real table, but much more performant.
I found a good discussion here: Temporary tables vs the table data type
A: Here's a hack you should never use:
select sum(numberGenerator.rank)
from
(
select
rank = ( select count(*)
from reallyLargeTable t1
where t1.uniqueValue > t2.uniqueValue ),
t2.uniqueValue id1,
t2.uniqueValue id2
from reallyLargeTable t2
) numberGenerator
where rank between 1 and 10
You can simplify this using the Rank() or Row_Number functions in SQL 2005
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Algorithm for joining e.g. an array of strings I have wondered for some time, what a nice, clean solution for joining an array of strings might look like.
Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".
Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented.
When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string).
I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).
Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?
A: Most languages nowadays - e.g. perl (mention by Jon Ericson), php, javascript - have a join() function or method, and this is by far the most elegant solution. Less code is better code.
In response to Mendelt Siebenga, if you do require a hand-rolled solution, I'd go with the ternary operator for something like:
separator = ","
foreach (item in stringCollection)
{
concatenatedString += concatenatedString ? separator + item : item
}
A: I usually go with something like...
list = ["Alpha", "Beta", "Gamma"];
output = "";
separator = "";
for (int i = 0; i < list.length ; i++) {
output = output + separator;
output = output + list[i];
separator = ", ";
}
This works because on the first pass, separator is empty (so you don't get a comma at the start, but on every subsequent pass, you add a comma before adding the next element.
You could certainly unroll this a little to make it a bit faster (assigning to the separator over and over isn't ideal), though I suspect that's something the compiler could do for you automatically.
In the end though, I suspect pretty this is what most language level join functions come down to. Nothing more than syntax sugar, but it sure is sweet.
A: For pure elegance, a typical recursive functional-language solution is quite nice. This isn't in an actual language syntax but you get the idea (it's also hardcoded to use comma separator):
join([]) = ""
join([x]) = "x"
join([x, rest]) = "x," + join(rest)
In reality you would write this in a more generic way, to reuse the same algorithm but abstract away the data type (doesn't have to be strings) and the operation (doesn't have to be concatenation with a comma in the middle). Then it usually gets called 'reduce', and many functional languages have this built in, e.g. multiplying all numbers in a list, in Lisp:
(reduce #'* '(1 2 3 4 5)) => 120
A: The most elegant solution i found for problems like this is something like this (in pseudocode)
separator = ""
foreach(item in stringCollection)
{
concatenatedString += separator + item
separator = ","
}
You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.
A: @Mendelt Siebenga
Strings are corner-stone objects in programming languages. Different languages implement strings differently. An implementation of join() strongly depends on underlying implementation of strings. Pseudocode doesn't reflect underlying implementation.
Consider join() in Python. It can be easily used:
print ", ".join(["Alpha", "Beta", "Gamma"])
# Alpha, Beta, Gamma
It could be easily implemented as follow:
def join(seq, sep=" "):
if not seq: return ""
elif len(seq) == 1: return seq[0]
return reduce(lambda x, y: x + sep + y, seq)
print join(["Alpha", "Beta", "Gamma"], ", ")
# Alpha, Beta, Gamma
And here how join() method is implemented in C (taken from trunk):
PyDoc_STRVAR(join__doc__,
"S.join(sequence) -> string\n\
\n\
Return a string which is the concatenation of the strings in the\n\
sequence. The separator between elements is S.");
static PyObject *
string_join(PyStringObject *self, PyObject *orig)
{
char *sep = PyString_AS_STRING(self);
const Py_ssize_t seplen = PyString_GET_SIZE(self);
PyObject *res = NULL;
char *p;
Py_ssize_t seqlen = 0;
size_t sz = 0;
Py_ssize_t i;
PyObject *seq, *item;
seq = PySequence_Fast(orig, "");
if (seq == NULL) {
return NULL;
}
seqlen = PySequence_Size(seq);
if (seqlen == 0) {
Py_DECREF(seq);
return PyString_FromString("");
}
if (seqlen == 1) {
item = PySequence_Fast_GET_ITEM(seq, 0);
if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
Py_INCREF(item);
Py_DECREF(seq);
return item;
}
}
/* There are at least two things to join, or else we have a subclass
* of the builtin types in the sequence.
* Do a pre-pass to figure out the total amount of space we'll
* need (sz), see whether any argument is absurd, and defer to
* the Unicode join if appropriate.
*/
for (i = 0; i < seqlen; i++) {
const size_t old_sz = sz;
item = PySequence_Fast_GET_ITEM(seq, i);
if (!PyString_Check(item)){
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(item)) {
/* Defer to Unicode join.
* CAUTION: There's no gurantee that the
* original sequence can be iterated over
* again, so we must pass seq here.
*/
PyObject *result;
result = PyUnicode_Join((PyObject *)self, seq);
Py_DECREF(seq);
return result;
}
#endif
PyErr_Format(PyExc_TypeError,
"sequence item %zd: expected string,"
" %.80s found",
i, Py_TYPE(item)->tp_name);
Py_DECREF(seq);
return NULL;
}
sz += PyString_GET_SIZE(item);
if (i != 0)
sz += seplen;
if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"join() result is too long for a Python string");
Py_DECREF(seq);
return NULL;
}
}
/* Allocate result space. */
res = PyString_FromStringAndSize((char*)NULL, sz);
if (res == NULL) {
Py_DECREF(seq);
return NULL;
}
/* Catenate everything. */
p = PyString_AS_STRING(res);
for (i = 0; i < seqlen; ++i) {
size_t n;
item = PySequence_Fast_GET_ITEM(seq, i);
n = PyString_GET_SIZE(item);
Py_MEMCPY(p, PyString_AS_STRING(item), n);
p += n;
if (i < seqlen - 1) {
Py_MEMCPY(p, sep, seplen);
p += seplen;
}
}
Py_DECREF(seq);
return res;
}
Note that the above Catenate everything. code is a small part of the whole function.
In pseudocode:
/* Catenate everything. */
for each item in sequence
copy-assign item
if not last item
copy-assign separator
A: All of these solutions are decent ones, but for an underlying library, both independence of separator and decent speed are important. Here is a function that fits the requirement assuming the language has some form of string builder.
public static string join(String[] strings, String sep) {
if(strings.length == 0) return "";
if(strings.length == 1) return strings[0];
StringBuilder sb = new StringBuilder();
sb.append(strings[0]);
for(int i = 1; i < strings.length; i++) {
sb.append(sep);
sb.append(strings[i]);
}
return sb.toString();
}
EDIT: I suppose I should mention why this would be speedier. The main reason would be because any time you call c = a + b; the underlying construct is usually c = (new StringBuilder()).append(a).append(b).toString();. By reusing the same string builder object, we can reduce the amount of allocations and garbage we produce.
And before someone chimes in with optimization is evil, we're talking about implementing a common library function. Acceptable, scalable performance is one of the requirements them. A join that takes a long time is one that's going to be not oft used.
A: ' Pseudo code Assume zero based
ResultString = InputArray[0]
n = 1
while n (is less than) Number_Of_Strings
ResultString (concatenate) ", "
ResultString (concatenate) InputArray[n]
n = n + 1
loop
A: In Perl, I just use the join command:
$ echo "Alpha
Beta
Gamma" | perl -e 'print(join(", ", map {chomp; $_} <> ))'
Alpha, Beta, Gamma
(The map stuff is mostly there to create a list.)
In languages that don't have a built in, like C, I use simple iteration (untested):
for (i = 0; i < N-1; i++){
strcat(s, a[i]);
strcat(s, ", ");
}
strcat(s, a[N]);
Of course, you'd need to check the size of s before you add more bytes to it.
You either have to special case the first entry or the last.
A: collecting different language implementations ?
Here is, for your amusement, a Smalltalk version:
join:collectionOfStrings separatedBy:sep
|buffer|
buffer := WriteStream on:''.
collectionOfStrings
do:[:each | buffer nextPutAll:each ]
separatedBy:[ buffer nextPutAll:sep ].
^ buffer contents.
Of course, the above code is already in the standard library found as:
Collection >> asStringWith:
so, using that, you'd write:
#('A' 'B' 'C') asStringWith:','
But here's my main point:
I would like to put more emphasis on the fact that using a StringBuilder (or what is called "WriteStream" in Smalltalk) is highly recommended. Do not concatenate strings using "+" in a loop - the result will be many many intermediate throw-away strings. If you have a good Garbage Collector, thats fine. But some are not and a lot of memory needs to be reclaimed. StringBuilder (and WriteStream, which is its grand-grand-father) use a buffer-doubling or even adaptive growing algorithm, which needs MUCH less scratch memory.
However, if its only a few small strings you are concatenating, dont care, and "+" them; the extra work using a StringBuilder might be actually counter-productive, up to an implementation- and language-dependent number of strings.
A: The following is no longer language-agnostic (but that doesn't matter for the discussion because the implementation is easily portable to other languages). I tried to implement Luke's (theretically best) solution in an imperative programming language. Take your pick; mine's C#. Not very elegant at all. However, (without any testing whatsoever) I could imagine that its performance is quite decent because the recursion is in fact tail recursive.
My challenge: give a better recursive implementation (in an imperative language). You say what “better” means: less code, faster, I'm open for suggestions.
private static StringBuilder RecJoin(IEnumerator<string> xs, string sep, StringBuilder result) {
result.Append(xs.Current);
if (xs.MoveNext()) {
result.Append(sep);
return RecJoin(xs, sep, result);
} else
return result;
}
public static string Join(this IEnumerable<string> xs, string separator) {
var i = xs.GetEnumerator();
if (!i.MoveNext())
return string.Empty;
else
return RecJoin(i, separator, new StringBuilder()).ToString();
}
A: join() function in Ruby:
def join(seq, sep)
seq.inject { |total, item| total << sep << item } or ""
end
join(["a", "b", "c"], ", ")
# => "a, b, c"
A: join() in Perl:
use List::Util qw(reduce);
sub mjoin($@) {$sep = shift; reduce {$a.$sep.$b} @_ or ''}
say mjoin(', ', qw(Alpha Beta Gamma));
# Alpha, Beta, Gamma
Or without reduce:
sub mjoin($@)
{
my ($sep, $sum) = (shift, shift);
$sum .= $sep.$_ for (@_);
$sum or ''
}
A: Perl 6
sub join( $separator, @strings ){
my $return = shift @strings;
for @strings -> ( $string ){
$return ~= $separator ~ $string;
}
return $return;
}
Yes I know it is pointless because Perl 6 already has a join function.
A: In Java 5, with unit test:
import junit.framework.Assert;
import org.junit.Test;
public class StringUtil
{
public static String join(String delim, String... strings)
{
StringBuilder builder = new StringBuilder();
if (strings != null)
{
for (String str : strings)
{
if (builder.length() > 0)
{
builder.append(delim);
}
builder.append(str);
}
}
return builder.toString();
}
@Test
public void joinTest()
{
Assert.assertEquals("", StringUtil.join(", ", null));
Assert.assertEquals("", StringUtil.join(", ", ""));
Assert.assertEquals("", StringUtil.join(", ", new String[0]));
Assert.assertEquals("test", StringUtil.join(", ", "test"));
Assert.assertEquals("foo, bar", StringUtil.join(", ", "foo", "bar"));
Assert.assertEquals("foo, bar, baz", StringUtil.join(", ", "foo", "bar", "baz"));
}
}
A: I wrote a recursive version of the solution in lisp. If the length of the list is greater that 2 it splits the list in half as best as it can and then tries merging the sublists
(defun concatenate-string(list)
(cond ((= (length list) 1) (car list))
((= (length list) 2) (concatenate 'string (first list) "," (second list)))
(t (let ((mid-point (floor (/ (- (length list) 1) 2))))
(concatenate 'string
(concatenate-string (subseq list 0 mid-point))
","
(concatenate-string (subseq list mid-point (length list))))))))
(concatenate-string '("a" "b"))
I tried applying the divide and conquer strategy to the problem, but I guess that does not give a better result than plain iteration. Please let me know if this could have been done better.
I have also performed an analysis of the recursion obtained by the algorithm, it is available here.
A: Use the String.join method in C#
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Random Weighted Choice in T-SQL How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows?
For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.
A: You simply need to sum the weights of all candidate rows, then choose a random point within that sum, then select the record that coordinates with that chosen point (each record is incrementally carrying an accumulating weight sum with it).
DECLARE @id int, @weight_sum int, @weight_point int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)
SELECT TOP 1 @id = t1.id
FROM @table t1, @table t2
WHERE t1.id >= t2.id
GROUP BY t1.id
HAVING SUM(t2.weight) >= @weight_point
ORDER BY t1.id
SELECT @id
A: The "incrementally carrying a an accumlating[sic] weight sum" part is expensive if you have a lot of records. If you also already have a wide range of scores/weights (ie: the range is wide enough that most records weights are unique. 1-5 stars probably wouldn't cut it), you can do something like this to pick a weight value. I'm using VB.Net here to demonstrate, but this could easily be done in pure Sql as well:
Function PickScore()
'Assume we have a database wrapper class instance called SQL and seeded a PRNG already
'Get count of scores in database
Dim ScoreCount As Double = SQL.ExecuteScalar("SELECT COUNT(score) FROM [MyTable]")
' You could also approximate this with just the number of records in the table, which might be faster.
'Random number between 0 and 1 with ScoreCount possible values
Dim rand As Double = Random.GetNext(ScoreCount) / ScoreCount
'Use the equation y = 1 - x^3 to skew results in favor of higher scores
' For x between 0 and 1, y is also between 0 and 1 with a strong bias towards 1
rand = 1 - (rand * rand * rand)
'Now we need to map the (0,1] vector to [1,Maxscore].
'Just find MaxScore and mutliply by rand
Dim MaxScore As UInteger = SQL.ExecuteScalar("SELECT MAX(Score) FROM Songs")
Return MaxScore * rand
End Function
Run this, and pick the record with the largest score less than the returned weight. If more than one record share that score, pick it at random. The advantages here are that you don't have to maintain any sums, and you can tweak the probability equation used to suit your tastes. But again, it works best with a larger distribution of scores.
A: The way to do this with random number generators is to integrate the probabiliity density function. With a set of discrete values you can calculate the prefix sum (sum of all values up to this one) and store it. With this you select the minumum prefix sum (aggregate to date) value greater than the random number.
On a database the subsequent values after an insertion have to be updated. If the relative frequency of updates and size of the data set doesn't make the cost of doing this prohibitive it means that the appropriate value can be obtained in from a single s-argable (predicate that can be resolved by an index lookup) query.
A: If you need to do get a group of samples (say, you want to sample 50 rows from a collection of 5M rows) where each row has a column called Weight which is an int and where larger values means more weight, you can use this function:
SELECT *
FROM
(
SELECT TOP 50 RowData, Weight
FROM MyTable
ORDER BY POWER(RAND(CAST(NEWID() AS VARBINARY)), (1.0/Weight)) DESC
) X
ORDER BY Weight DESC
The key here is using the POWER( ) function as illustrated here
A reference on the choice of a random function is here and here
Alternatively you can use:
1.0 * ABS(CAST(CHECKSUM(NEWID()) AS bigint)) / CAST(0x7FFFFFFF AS INT)
You cast checksum as BIGINT instead of INT because of this issue:
Because checksum returns an int, and the range of an int is -2^31
(-2,147,483,648) to 2^31-1 (2,147,483,647), the abs() function can
return an overflow error if the result happens to be exactly
-2,147,483,648! The chances are obviously very low, about 1 in 4 billion, however we were running it over a ~1.8b row table every day,
so it was happening about once a week! Fix is to cast the checksum to
bigint before the abs.
A: Dane's answer includes a self joins in a way that introduces a square law. (n*n/2) rows after the join where there are n rows in the table.
What would be more ideal is to be able to just parse the table once.
DECLARE @id int, @weight_sum int, @weight_point int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1))
SELECT
@id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END,
@weight_point = @weight_point - [table].weight
FROM
@table [table]
ORDER BY
[table].Weight DESC
This will go through the table, setting @id to each record's id value while at the same time decrementing @weight point. Eventually, the @weight_point will go negative. This means that the SUM of all preceding weights is greater than the randomly chosen target value. This is the record we want, so from that point onwards we set @id to itself (ignoring any IDs in the table).
This runs through the table just once, but does have to run through the entire table even if the chosen value is the first record. Because the average position is half way through the table (and less if ordered by ascending weight) writing a loop could possibly be faster... (Especially if the weightings are in common groups):
DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)
SELECT @next_weight = MAX(weight) FROM @table
SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight
SET @weight_point = @weight_point - (@next_weight * @row_count)
WHILE (@weight_point > 0)
BEGIN
SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight
SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight
SET @weight_point = @weight_point - (@next_weight * @row_count)
END
-- # Once the @weight_point is less than 0, we know that the randomly chosen record
-- # is in the group of records WHERE [table].weight = @next_weight
SELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1))
SELECT
@id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END,
@row_count = @row_count - 1
FROM
@table [table]
WHERE
[table].weight = @next_weight
ORDER BY
[table].Weight DESC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: What is the preferred operating system for web programmers, client or server? Which OS do you prefer to program on? Client or Server
There is a school of though that if you are doing (mostly) web programming (or other server based code), you should use a server OS for your dev machine, since that's closer to the environment where your app will be running.
Update: I should add, this is really directed to the Windows crowd
A: OK, I know you're mainly talking about windows but...
I used to develop on windows for deployment on *nix servers. Sure there were lots of gotchas with this way of working, but you just kind of get used to it.
In October 2005 I switched to Linux, initially as an experiment, but I never went back. There was a steep learning curve. I thought I knew *nix pretty well after 10 years of dealing with it, but I knew nothing compared with the amount I learned using it on my desktop machine.
Workflow has been so much smoother developing and deploying to similar platforms.
More recently, we have even started to pick servers running Ubuntu server, so that they most closely match our Ubuntu desktop development machines.
If you are talking about the difference between a desktop and a server edition, I'd guess you needn't worry about it. If you're developing on one OS for deployment on another, I'd consider changing your desktop platform.
A:
There is a school of though that if you are doing (mostly) web programming (or other server based code), you should use a server OS for your dev machine
I think that applies more to 'system programmers' rather than web 'application programmers'. Why? There is definitely great value in knowing the platform intimately, like one would get in living with the OS, etc. day in and day out. But not everyone can or should need to go there.
While my main production environment is RHEL4, Linux just does not work for me on the desktop--in fact, it drives me crazy. I find working on OSX close enough, though. And I just love working on my Mac rather than an XP box.
I'm doing the Java thing, and the "write once, run everywhere" hype actually works for me. :)
Update: I should add, this is really directed to the Windows crowd
Minute late, bit short ;) Maybe you should edit the title too...
A: It seems like the question is more about whether to use the server or client version of the same OS. So my answer is this: the client should be just fine. You can develop and test web applications of many flavors on client versions of Windows, OS X, and Linux. OS X and Linux obviously make Apache-based apps a little easier by coming with Apache pre-installed, but a download of XAMPP or WAMPP can quickly turn a Windows box into a solid development platform for LAMP applications, as well.
And if you're doing ASP.NET, your development tools (if you're using something in the Visual Studio line) have test server mechanisms built in.
So unless you have some other need for wanting the server version, I would stick with the client. It's less money, and you really don't need the server version.
A: The client vs. server OS issue is only relevant on MS platforms. And even there it depends on what you're developing for.
As far as I understand for Sharepoint development you need a server OS to run your code
If you're just doing vanilla ASP.Net stuff then it's mostly personal taste.
Edit
As Tyler commented, you can run MOSS/WSS on Vista but it's not supported. Or you could develop on a client OS and run sharepoint on a server OS in a VM.
A: Regardless of the operating system you're actually talking about, it shouldn't matter. Most applications you might write won't need to worry about the differences (if there indeed are any). Only in rare cases might you use some specific functionality that might only be available on a "server" edition of your OS.
There are other considerations, for example Windows server editions are tuned by default to give less priority and attention to desktop programs, and more attention to things like the file cache. Personally, I would always choose a "client" edition of my chosen OS.
A: Personally I use Windows Vista but that's because it's what I like and I can use it well. But in all honesty it doesn't matter, your OS should be something you are comfortable in and has the tools you need to be productive.
I would say your test environment is the one you need to have as close to your production environment as possible. I write in RoR on Vista but test it in a Linux VM setup the same as my web server and at work we have a Win2k3 server with IIS6 installed to test our .Net sites on but I develop on Vista using IIS7.
A: I use Windows Server 2003 set up as a workstation.This is the guide i have used for several years. Really like it.
A: This is going to be a bit of a weird answer but I'm a big fan of Windows 2008 and Hyper-V, as a workstation (I know). Essentially I'll only install Office like software on my workstation and all the development will be in Virtual Machines.
Assuming there's no Win2k8/Hyper-V availiable I'd gladly settle for some old WinXP (but w/Virtual PC).
Hyper-V allows you to get great performance out of any .VHD VM that you run. Both Virtual PC and Virtual Server are free (as in beer) and you can set up a ton of infrastructure that allows you to re-purpose virtual machines (ie. Base Machines, Differencing Disks, Undo Disks). The .VHDs are also interchangeable so you can re-host a previously enjoyed .VHD for other developers to enjoy on some virtual server, OR they can take a copy of it, rename the virtual machine and enjoy your ready-to-go environment with some Virtual PC!
This is awesome for bringing team members up to speed (environment wise) in less than 10 min. YOu can also use it to VERY QUICKLY provision machines that would otherwise take days to setup/configure.
Never mind the much better ability to test from different OS', or be able to roll back changes using Undo disks, VMs are a life saver! Start virtualizing people!
For some of the great benefits of Virtual Machines/Differencing Disks consider this post by Andrew Connell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I send mail from a Ruby program? I want to send email from a Ruby application. Is there a call in the core language to do this or is there a library I should use? What's the best way to do this?
A: If you don't want to use ActionMailer you can use Net::SMTP (for the actual sending) together with tmail for easily creating emails (with multiple parts, etc.).
A: require 'net/smtp'
SMTP_SERVER = 'mailserver01' #change to your server
def send_emails(sender_address, recipients, subject, message_body)
recipients.each do |recipient_address|
message_header =''
message_header << "From: <#{sender_address}>\r\n"
message_header << "To: <#{recipient_address}>\r\n"
message_header << "Subject: #{subject}\r\n"
message_header << "Date: " + Time.now.to_s + "\r\n"
message = message_header + "\r\n" + message_body + "\r\n"
Net::SMTP.start(SMTP_SERVER, 25) do |smtp|
smtp.send_message message, sender_address, recipient_address
end
end
end
send_emails('[email protected]',['[email protected]', '[email protected]'],'test Email',"Hi there this is a test email hope you like it")
A: I use the Net::SMTP library
A: RubyMail is an email handling library for Ruby.
A: I know this is a late answer to this, but this was just released:
http://adam.blog.heroku.com/past/2008/11/2/pony_the_express_way_to_send_email_from_ruby/
Might be useful.
A: You might also consider taking a look at the ActionMailer component that ships as part of, but is not dependent on Rails.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Access variables programmatically by name in Ruby I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:
foo = ["goo", "baz"]
How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?
Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:
[foo, goo, bar].each { |param|
if param.class != Array
puts "param_name wasn't an Array. It was a/an #{param.class}"
return "Error: param_name wasn't an Array"
end
}
My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala dbr's answer)
A: It seems you are trying to solve a problem that has a far easier solution..
Why not just store the data in a hash? If you do..
data_container = {'foo' => ['goo', 'baz']}
..it is then utterly trivial to get the 'foo' name.
That said, you've not given any context to the problem, so there may be a reason you can't do this..
[edit] After clarification, I see the issue, but I don't think this is the problem.. With [foo, bar, bla], it's equivalent like saying ['content 1', 'content 2', 'etc']. The actual variables name is (or rather, should be) utterly irrelevant. If the name of the variable is important, that is exactly why hashes exist.
The problem isn't with iterating over [foo, bar] etc, it's the fundamental problem with how the SOAP server is returing the data, and/or how you're trying to use it.
The solution, I would say, is to either make the SOAP server return hashes, or, since you know there is always going to be three elements, can you not do something like..
{"foo" => foo, "goo" => goo, "bar"=>bar}.each do |param_name, param|
if param.class != Array
puts "#{param_name} wasn't an Array. It was a/an #{param.class}"
puts "Error: #{param_name} wasn't an Array"
end
end
A: OK, it DOES work in instance methods, too, and, based on your specific requirement (the one you put in the comment), you could do this:
local_variables.each do |var|
puts var if (eval(var).class != Fixnum)
end
Just replace Fixnum with your specific type checking.
A: What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names:
["foo", "goo", "bar"].each { |param_name|
param = eval(param_name)
if param.class != Array
puts "#{param_name} wasn't an Array. It was a/an #{param.class}"
return "Error: #{param_name} wasn't an Array"
end
}
If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception...
A: You need to re-architect your solution. Even if you could do it (you can't), the question simply doesn't have a reasonable answer.
Imagine a get_name method.
a = 1
get_name(a)
Everyone could probably agree this should return 'a'
b = a
get_name(b)
Should it return 'b', or 'a', or an array containing both?
[b,a].each do |arg|
get_name(arg)
end
Should it return 'arg', 'b', or 'a' ?
def do_stuff( arg )
get_name(arg)
do
do_stuff(b)
Should it return 'arg', 'b', or 'a', or maybe the array of all of them? Even if it did return an array, what would the order be and how would I know how to interpret the results?
The answer to all of the questions above is "It depends on the particular thing I want at the time." I'm not sure how you could solve that problem for Ruby.
A: I do not know of any way to get a local variable name. But, you can use the instance_variables method, this will return an array of all the instance variable names in the object.
Simple call:
object.instance_variables
or
self.instance_variables
to get an array of all instance variable names.
A: Building on joshmsmoore, something like this would probably do it:
# Returns the first instance variable whose value == x
# Returns nil if no name maps to the given value
def instance_variable_name_for(x)
self.instance_variables.find do |var|
x == self.instance_variable_get(var)
end
end
A: There's Kernel::local_variables, but I'm not sure that this will work for a method's local vars, and I don't know that you can manipulate it in such a way as to do what you wish to acheive.
A: Great question. I fully understand your motivation. Let me start by noting, that there are certain kinds of special objects, that, under certain circumstances, have knowledge of the variable, to which they have been assigned. These special objects are eg. Module instances, Class instances and Struct instances:
Dog = Class.new
Dog.name # Dog
The catch is, that this works only when the variable, to which the assignment is performed, is a constant. (We all know that Ruby constants are nothing more than emotionally sensitive variables.) Thus:
x = Module.new # creating an anonymous module
x.name #=> nil # the module does not know that it has been assigned to x
Animal = x # but will notice once we assign it to a constant
x.name #=> "Animal"
This behavior of objects being aware to which variables they have been assigned, is commonly called constant magic (because it is limited to constants). But this highly desirable constant magic only works for certain objects:
Rover = Dog.new
Rover.name #=> raises NoMethodError
Fortunately, I have written a gem y_support/name_magic, that takes care of this for you:
# first, gem install y_support
require 'y_support/name_magic'
class Cat
include NameMagic
end
The fact, that this only works with constants (ie. variables starting with a capital letter) is not such a big limitation. In fact, it gives you freedom to name or not to name your objects at will:
tmp = Cat.new # nameless kitty
tmp.name #=> nil
Josie = tmp # by assigning to a constant, we name the kitty Josie
tmp.name #=> :Josie
Unfortunately, this will not work with array literals, because they are internally constructed without using #new method, on which NameMagic relies. Therefore, to achieve what you want to, you will have to subclass Array:
require 'y_support/name_magic'
class MyArr < Array
include NameMagic
end
foo = MyArr.new ["goo", "baz"] # not named yet
foo.name #=> nil
Foo = foo # but assignment to a constant is noticed
foo.name #=> :Foo
# You can even list the instances
MyArr.instances #=> [["goo", "baz"]]
MyArr.instance_names #=> [:Foo]
# Get an instance by name:
MyArr.instance "Foo" #=> ["goo", "baz"]
MyArr.instance :Foo #=> ["goo", "baz"]
# Rename it:
Foo.name = "Quux"
Foo.name #=> :Quux
# Or forget the name again:
MyArr.forget :Quux
Foo.name #=> nil
# In addition, you can name the object upon creation even without assignment
u = MyArr.new [1, 2], name: :Pair
u.name #=> :Pair
v = MyArr.new [1, 2, 3], ɴ: :Trinity
v.name #=> :Trinity
I achieved the constant magic-imitating behavior by searching all the constants in all the namespaces of the current Ruby object space. This wastes a fraction of second, but since the search is performed only once, there is no performance penalty once the object figures out its name. In the future, Ruby core team has promised const_assigned hook.
A: You can't, you need to go back to the drawing board and re-engineer your solution.
A: Foo is only a location to hold a pointer to the data. The data has no knowledge of what points at it. In Smalltalk systems you could ask the VM for all pointers to an object, but that would only get you the object that contained the foo variable, not foo itself. There is no real way to reference a vaiable in Ruby. As mentioned by one answer you can stil place a tag in the data that references where it came from or such, but generally that is not a good apporach to most problems. You can use a hash to receive the values in the first place, or use a hash to pass to your loop so you know the argument name for validation purposes as in DBR's answer.
A: The closest thing to a real answer to you question is to use the Enumerable method each_with_index instead of each, thusly:
my_array = [foo, baz, bar]
my_array.each_with_index do |item, index|
if item.class != Array
puts "#{my_array[index]} wasn't an Array. It was a/an #{item.class}"
end
end
I removed the return statement from the block you were passing to each/each_with_index because it didn't do/mean anything. Each and each_with_index both return the array on which they were operating.
There's also something about scope in blocks worth noting here: if you've defined a variable outside of the block, it will be available within it. In other words, you could refer to foo, bar, and baz directly inside the block. The converse is not true: variables that you create for the first time inside the block will not be available outside of it.
Finally, the do/end syntax is preferred for multi-line blocks, but that's simply a matter of style, though it is universal in ruby code of any recent vintage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Getting Good Google PageRank In SEO people talk a lot about Google PageRank. It's kind of a catch 22 because until your site is actually big and you don't really need search engines as much, it's unlikely that big sites will link to you and increase your PageRank!
I've been told that it's easiest to simply get a couple high quality links to point to a site to raise it's PageRank. I've also been told that there are certain Open Directories like dmoz.org that Google pays special attention to (since they're human managed links). Can anyone speak to the validity of this or suggest another site/technique to increase a site's PageRank?
A: Good content.
Update it often.
Read and digest everything at Creating a Google-friendly site: Best practices.
Be active on the web. Comment in blogs, correspond genuinely with people, in email, im, twitter.
I'm not too sure about the domain name. Wikipedia? What does that mean? Mozilla? What word is that? Google? Was a typo. Yahoo? Sounds like that chocolate drink Yoohoo.
Trying to keyword the domain name shoehorns you anyway. And it can be construed as a SEO technique in the future (if it isn't already!)
Answer all email. Answer blog comments. Be nice and helpful.
Go watch garyvee's Better Than Zero. That'll motivate you.
A: If it's appropriate, having a blog is a good way of keeping content fresh, especially if you post often. A CMS would be handy too, as it reduces the friction of updating. The best way would be user-generated content, as other people make your site bigger and updated, and they may well link to their content from their other sites.
A: Have great content
Nothing helps your google rank more than having content or offering a service people are interested in. If your web site is better than the competition and solves a real need you will naturally generate more traffic and inbound links.
Keep your content fresh
Use friendly url's that contain keywords
Good: http://cars.com/products/cars/ford/focus/
Bad: http://cars.com/p?id=1232
Make sure the page title is relevant and well constructed
For example: Buy A House In France :. Property Purchasing in France
Use a domain name that describes your site
Good: http://cars.com/
Bad: http://somerandomunrelateddomainname.com/
Example
Type car into Google, out of the top 5 links all 4 have car in the domain: http://www.google.co.uk/search?q=car
Make it accessible
Make sure people can read your content. This includes a variety of different audiences
*
*People with disabilities: Sight, motor, cognitive disabilities etc..
*Search bots
In particular make sure search bots can read every single relevant page on your site. Quite often search bots get blocked by the use of javascript to link between pages or the use of frames / flash / silverlight. One easy way to do this is have a site map page that gives access to the whole site, dividing it into categories / sub categories etc..
*Down level browsers
Submit your site map automatically
Most search engines allow you to submit a list of pages on your site including when they were last updated.
Google: https://www.google.com/webmasters/tools/docs/en/about.html
Inbound links
Generate as much buzz about your website as possible, to increase the likely hood of people linking to you. Blog / podcast about your website if appropriate. List it in online directories (if appropriate).
References
*
*Google Search Engine Ranking Factors, by an SEO company
*Creating a Google-friendly site: Best practices
*Wikipedia - Search engine optimization
A: Google doesn't want you to have to engineer your site specifically to get a good PageRank. Having popular content and a well designed website should naturally get you the results you want.
A: A easy trick is to use
Google webmaster tool https://www.google.com/webmasters/tools
And you can generate a sitemap using http://www.xml-sitemaps.com/
Then, don't miss to use www.google.com/analytics/
And be careful, most SEO guides are not correct, playing fair is not always the good approach. For example,everyone says that spamming .edu sites is bad and ineffective but it is effective.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Algorithm to find a common multiplier to convert decimal numbers to whole numbers I have an array of numbers that potentially have up to 8 decimal places and I need to find the smallest common number I can multiply them by so that they are all whole numbers. I need this so all the original numbers can all be multiplied out to the same scale and be processed by a sealed system that will only deal with whole numbers, then I can retrieve the results and divide them by the common multiplier to get my relative results.
Currently we do a few checks on the numbers and multiply by 100 or 1,000,000, but the processing done by the *sealed system can get quite expensive when dealing with large numbers so multiplying everything by a million just for the sake of it isn’t really a great option. As an approximation lets say that the sealed algorithm gets 10 times more expensive every time you multiply by a factor of 10.
What is the most efficient algorithm, that will also give the best possible result, to accomplish what I need and is there a mathematical name and/or formula for what I’m need?
*The sealed system isn’t really sealed. I own/maintain the source code for it but its 100,000 odd lines of proprietary magic and it has been thoroughly bug and performance tested, altering it to deal with floats is not an option for many reasons. It is a system that creates a grid of X by Y cells, then rects that are X by Y are dropped into the grid, “proprietary magic” occurs and results are spat out – obviously this is an extremely simplified version of reality, but it’s a good enough approximation.
So far there are quiet a few good answers and I wondered how I should go about choosing the ‘correct’ one. To begin with I figured the only fair way was to create each solution and performance test it, but I later realised that pure speed wasn’t the only relevant factor – an more accurate solution is also very relevant. I wrote the performance tests anyway, but currently the I’m choosing the correct answer based on speed as well accuracy using a ‘gut feel’ formula.
My performance tests process 1000 different sets of 100 randomly generated numbers.
Each algorithm is tested using the same set of random numbers.
Algorithms are written in .Net 3.5 (although thus far would be 2.0 compatible)
I tried pretty hard to make the tests as fair as possible.
*
*Greg – Multiply by large number
and then divide by GCD – 63
milliseconds
*Andy – String Parsing
– 199 milliseconds
*Eric – Decimal.GetBits – 160 milliseconds
*Eric – Binary search – 32
milliseconds
*Ima – sorry I couldn’t
figure out a how to implement your
solution easily in .Net (I didn’t
want to spend too long on it)
*Bill – I figure your answer was pretty
close to Greg’s so didn’t implement
it. I’m sure it’d be a smidge faster
but potentially less accurate.
So Greg’s Multiply by large number and then divide by GCD” solution was the second fastest algorithm and it gave the most accurate results so for now I’m calling it correct.
I really wanted the Decimal.GetBits solution to be the fastest, but it was very slow, I’m unsure if this is due to the conversion of a Double to a Decimal or the Bit masking and shifting. There should be a
similar usable solution for a straight Double using the BitConverter.GetBytes and some knowledge contained here: http://blogs.msdn.com/bclteam/archive/2007/05/29/bcl-refresher-floating-point-types-the-good-the-bad-and-the-ugly-inbar-gazit-matthew-greig.aspx but my eyes just kept glazing over every time I read that article and I eventually ran out of time to try to implement a solution.
I’m always open to other solutions if anyone can think of something better.
A: I'd multiply by something sufficiently large (100,000,000 for 8 decimal places), then divide by the GCD of the resulting numbers. You'll end up with a pile of smallest integers that you can feed to the other algorithm. After getting the result, reverse the process to recover your original range.
A: If you want to find some integer N so that N*x is also an exact integer for a set of floats x in a given set are all integers, then you have a basically unsolvable problem. Suppose x = the smallest positive float your type can represent, say it's 10^-30. If you multiply all your numbers by 10^30, and then try to represent them in binary (otherwise, why are you even trying so hard to make them ints?), then you'll lose basically all the information of the other numbers due to overflow.
So here are two suggestions:
*
*If you have control over all the related code, find another
approach. For example, if you have some function that takes only
int's, but you have floats, and you want to stuff your floats into
the function, just re-write or overload this function to accept
floats as well.
*If you don't have control over the part of your system that requires
int's, then choose a precision to which you care about, accept that
you will simply have to lose some information sometimes (but it will
always be "small" in some sense), and then just multiply all your
float's by that constant, and round to the nearest integer.
By the way, if you're dealing with fractions, rather than float's, then it's a different game. If you have a bunch of fractions a/b, c/d, e/f; and you want a least common multiplier N such that N*(each fraction) = an integer, then N = abc / gcd(a,b,c); and gcd(a,b,c) = gcd(a, gcd(b, c)). You can use Euclid's algorithm to find the gcd of any two numbers.
A: *
*Multiple all the numbers by 10
until you have integers.
*Divide
by 2,3,5,7 while you still have all
integers.
I think that covers all cases.
2.1 * 10/7 -> 3
0.008 * 10^3/2^3 -> 1
That's assuming your multiplier can be a rational fraction.
A: What language are you programming in? Something like
myNumber.ToString().Substring(myNumber.ToString().IndexOf(".")+1).Length
would give you the number of decimal places for a double in C#. You could run each number through that and find the largest number of decimal places(x), then multiply each number by 10 to the power of x.
Edit: Out of curiosity, what is this sealed system which you can pass only integers to?
A: Greg: Nice solution but won't calculating a GCD that's common in an array of 100+ numbers get a bit expensive? And how would you go about that? Its easy to do GCD for two numbers but for 100 it becomes more complex (I think).
Evil Andy: I'm programing in .Net and the solution you pose is pretty much a match for what we do now. I didn't want to include it in my original question cause I was hoping for some outside the box (or my box anyway) thinking and I didn't want to taint peoples answers with a potential solution. While I don't have any solid performance statistics (because I haven't had any other method to compare it against) I know the string parsing would be relatively expensive and I figured a purely mathematical solution could potentially be more efficient.
To be fair the current string parsing solution is in production and there have been no complaints about its performance yet (its even in production in a separate system in a VB6 format and no complaints there either). It's just that it doesn't feel right, I guess it offends my programing sensibilities - but it may well be the best solution.
That said I'm still open to any other solutions, purely mathematical or otherwise.
A: In a loop get mantissa and exponent of each number as integers. You can use frexp for exponent, but I think bit mask will be required for mantissa. Find minimal exponent. Find most significant digits in mantissa (loop through bits looking for last "1") - or simply use predefined number of significant digits.
Your multiple is then something like 2^(numberOfDigits-minMantissa). "Something like" because I don't remember biases/offsets/ranges, but I think idea is clear enough.
A: So basically you want to determine the number of digits after the decimal point for each number.
This would be rather easier if you had the binary representation of the number. Are the numbers being converted from rationals or scientific notation earlier in your program? If so, you could skip the earlier conversion and have a much easier time. Otherwise you might want to pass each number to a function in an external DLL written in C, where you could work with the floating point representation directly. Or you could cast the numbers to decimal and do some work with Decimal.GetBits.
The fastest approach I can think of in-place and following your conditions would be to find the smallest necessary power-of-ten (or 2, or whatever) as suggested before. But instead of doing it in a loop, save some computation by doing binary search on the possible powers. Assuming a maximum of 8, something like:
int NumDecimals( double d )
{
// make d positive for clarity; it won't change the result
if( d<0 ) d=-d;
// now do binary search on the possible numbers of post-decimal digits to
// determine the actual number as quickly as possible:
if( NeedsMore( d, 10e4 ) )
{
// more than 4 decimals
if( NeedsMore( d, 10e6 ) )
{
// > 6 decimal places
if( NeedsMore( d, 10e7 ) ) return 10e8;
return 10e7;
}
else
{
// <= 6 decimal places
if( NeedsMore( d, 10e5 ) ) return 10e6;
return 10e5;
}
}
else
{
// <= 4 decimal places
// etc...
}
}
bool NeedsMore( double d, double e )
{
// check whether the representation of D has more decimal points than the
// power of 10 represented in e.
return (d*e - Math.Floor( d*e )) > 0;
}
PS: you wouldn't be passing security prices to an option pricing engine would you? It has exactly the flavor...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using .NET, how can you find the mime type of a file based on the file signature not the extension I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to this question only in .Net.
A: In Urlmon.dll, there's a function called FindMimeFromData.
From the documentation
MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
So, read the first (up to) 256 bytes from the file and pass it to FindMimeFromData.
A: I use an hybrid solution:
using System.Runtime.InteropServices;
[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
);
private string GetMimeFromRegistry (string Filename)
{
string mime = "application/octetstream";
string ext = System.IO.Path.GetExtension(Filename).ToLower();
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (rk != null && rk.GetValue("Content Type") != null)
mime = rk.GetValue("Content Type").ToString();
return mime;
}
public string GetMimeTypeFromFileAndRegistry (string filename)
{
if (!File.Exists(filename))
{
return GetMimeFromRegistry (filename);
}
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);
if (string.IsNullOrWhiteSpace (mime) ||
mime =="text/plain" || mime == "application/octet-stream")
{
return GetMimeFromRegistry (filename);
}
return mime;
}
catch (Exception e)
{
return GetMimeFromRegistry (filename);
}
}
A: I wrote a validator of mime type. Kindly share it with you.
private readonly Dictionary<string, byte[]> _mimeTypes = new Dictionary<string, byte[]>
{
{"image/jpeg", new byte[] {255, 216, 255}},
{"image/jpg", new byte[] {255, 216, 255}},
{"image/pjpeg", new byte[] {255, 216, 255}},
{"image/apng", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},
{"image/png", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},
{"image/bmp", new byte[] {66, 77}},
{"image/gif", new byte[] {71, 73, 70, 56}},
};
private bool ValidateMimeType(byte[] file, string contentType)
{
var imageType = _mimeTypes.SingleOrDefault(x => x.Key.Equals(contentType));
return file.Take(imageType.Value.Length).SequenceEqual(imageType.Value);
}
A: I think the right answer is a combination of Steve Morgan's and Serguei's answers. That's how Internet Explorer does it. The pinvoke call to FindMimeFromData works for only 26 hard-coded mime types. Also, it will give ambigous mime types (such as text/plain or application/octet-stream) even though there may exist a more specific, more appropriate mime type. If it fails to give a good mime type, you can go to the registry for a more specific mime type. The server registry could have more up-to-date mime types.
Refer to: http://msdn.microsoft.com/en-us/library/ms775147(VS.85).aspx
A: This class use previous answers to try in 3 different ways: harcoded based on extension, FindMimeFromData API and using registry.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace YourNamespace
{
public static class MimeTypeParser
{
[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 GetMimeType(string sFilePath)
{
string sMimeType = GetMimeTypeFromList(sFilePath);
if (String.IsNullOrEmpty(sMimeType))
{
sMimeType = GetMimeTypeFromFile(sFilePath);
if (String.IsNullOrEmpty(sMimeType))
{
sMimeType = GetMimeTypeFromRegistry(sFilePath);
}
}
return sMimeType;
}
public static string GetMimeTypeFromList(string sFileNameOrPath)
{
string sMimeType = null;
string sExtensionWithoutDot = Path.GetExtension(sFileNameOrPath).Substring(1).ToLower();
if (!String.IsNullOrEmpty(sExtensionWithoutDot) && spDicMIMETypes.ContainsKey(sExtensionWithoutDot))
{
sMimeType = spDicMIMETypes[sExtensionWithoutDot];
}
return sMimeType;
}
public static string GetMimeTypeFromRegistry(string sFileNameOrPath)
{
string sMimeType = null;
string sExtension = Path.GetExtension(sFileNameOrPath).ToLower();
RegistryKey pKey = Registry.ClassesRoot.OpenSubKey(sExtension);
if (pKey != null && pKey.GetValue("Content Type") != null)
{
sMimeType = pKey.GetValue("Content Type").ToString();
}
return sMimeType;
}
public static string GetMimeTypeFromFile(string sFilePath)
{
string sMimeType = null;
if (File.Exists(sFilePath))
{
byte[] abytBuffer = new byte[256];
using (FileStream pFileStream = new FileStream(sFilePath, FileMode.Open))
{
if (pFileStream.Length >= 256)
{
pFileStream.Read(abytBuffer, 0, 256);
}
else
{
pFileStream.Read(abytBuffer, 0, (int)pFileStream.Length);
}
}
try
{
UInt32 unMimeType;
FindMimeFromData(0, null, abytBuffer, 256, null, 0, out unMimeType, 0);
IntPtr pMimeType = new IntPtr(unMimeType);
string sMimeTypeFromFile = Marshal.PtrToStringUni(pMimeType);
Marshal.FreeCoTaskMem(pMimeType);
if (!String.IsNullOrEmpty(sMimeTypeFromFile) && sMimeTypeFromFile != "text/plain" && sMimeTypeFromFile != "application/octet-stream")
{
sMimeType = sMimeTypeFromFile;
}
}
catch {}
}
return sMimeType;
}
private static readonly Dictionary<string, string> spDicMIMETypes = new Dictionary<string, string>
{
{"ai", "application/postscript"},
{"aif", "audio/x-aiff"},
{"aifc", "audio/x-aiff"},
{"aiff", "audio/x-aiff"},
{"asc", "text/plain"},
{"atom", "application/atom+xml"},
{"au", "audio/basic"},
{"avi", "video/x-msvideo"},
{"bcpio", "application/x-bcpio"},
{"bin", "application/octet-stream"},
{"bmp", "image/bmp"},
{"cdf", "application/x-netcdf"},
{"cgm", "image/cgm"},
{"class", "application/octet-stream"},
{"cpio", "application/x-cpio"},
{"cpt", "application/mac-compactpro"},
{"csh", "application/x-csh"},
{"css", "text/css"},
{"dcr", "application/x-director"},
{"dif", "video/x-dv"},
{"dir", "application/x-director"},
{"djv", "image/vnd.djvu"},
{"djvu", "image/vnd.djvu"},
{"dll", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"dms", "application/octet-stream"},
{"doc", "application/msword"},
{"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"docm","application/vnd.ms-word.document.macroEnabled.12"},
{"dotm","application/vnd.ms-word.template.macroEnabled.12"},
{"dtd", "application/xml-dtd"},
{"dv", "video/x-dv"},
{"dvi", "application/x-dvi"},
{"dxr", "application/x-director"},
{"eps", "application/postscript"},
{"etx", "text/x-setext"},
{"exe", "application/octet-stream"},
{"ez", "application/andrew-inset"},
{"gif", "image/gif"},
{"gram", "application/srgs"},
{"grxml", "application/srgs+xml"},
{"gtar", "application/x-gtar"},
{"hdf", "application/x-hdf"},
{"hqx", "application/mac-binhex40"},
{"htc", "text/x-component"},
{"htm", "text/html"},
{"html", "text/html"},
{"ice", "x-conference/x-cooltalk"},
{"ico", "image/x-icon"},
{"ics", "text/calendar"},
{"ief", "image/ief"},
{"ifb", "text/calendar"},
{"iges", "model/iges"},
{"igs", "model/iges"},
{"jnlp", "application/x-java-jnlp-file"},
{"jp2", "image/jp2"},
{"jpe", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"kar", "audio/midi"},
{"latex", "application/x-latex"},
{"lha", "application/octet-stream"},
{"lzh", "application/octet-stream"},
{"m3u", "audio/x-mpegurl"},
{"m4a", "audio/mp4a-latm"},
{"m4b", "audio/mp4a-latm"},
{"m4p", "audio/mp4a-latm"},
{"m4u", "video/vnd.mpegurl"},
{"m4v", "video/x-m4v"},
{"mac", "image/x-macpaint"},
{"man", "application/x-troff-man"},
{"mathml", "application/mathml+xml"},
{"me", "application/x-troff-me"},
{"mesh", "model/mesh"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"mif", "application/vnd.mif"},
{"mov", "video/quicktime"},
{"movie", "video/x-sgi-movie"},
{"mp2", "audio/mpeg"},
{"mp3", "audio/mpeg"},
{"mp4", "video/mp4"},
{"mpe", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mpga", "audio/mpeg"},
{"ms", "application/x-troff-ms"},
{"msh", "model/mesh"},
{"mxu", "video/vnd.mpegurl"},
{"nc", "application/x-netcdf"},
{"oda", "application/oda"},
{"ogg", "application/ogg"},
{"pbm", "image/x-portable-bitmap"},
{"pct", "image/pict"},
{"pdb", "chemical/x-pdb"},
{"pdf", "application/pdf"},
{"pgm", "image/x-portable-graymap"},
{"pgn", "application/x-chess-pgn"},
{"pic", "image/pict"},
{"pict", "image/pict"},
{"png", "image/png"},
{"pnm", "image/x-portable-anymap"},
{"pnt", "image/x-macpaint"},
{"pntg", "image/x-macpaint"},
{"ppm", "image/x-portable-pixmap"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ps", "application/postscript"},
{"qt", "video/quicktime"},
{"qti", "image/x-quicktime"},
{"qtif", "image/x-quicktime"},
{"ra", "audio/x-pn-realaudio"},
{"ram", "audio/x-pn-realaudio"},
{"ras", "image/x-cmu-raster"},
{"rdf", "application/rdf+xml"},
{"rgb", "image/x-rgb"},
{"rm", "application/vnd.rn-realmedia"},
{"roff", "application/x-troff"},
{"rtf", "text/rtf"},
{"rtx", "text/richtext"},
{"sgm", "text/sgml"},
{"sgml", "text/sgml"},
{"sh", "application/x-sh"},
{"shar", "application/x-shar"},
{"silo", "model/mesh"},
{"sit", "application/x-stuffit"},
{"skd", "application/x-koan"},
{"skm", "application/x-koan"},
{"skp", "application/x-koan"},
{"skt", "application/x-koan"},
{"smi", "application/smil"},
{"smil", "application/smil"},
{"snd", "audio/basic"},
{"so", "application/octet-stream"},
{"spl", "application/x-futuresplash"},
{"src", "application/x-wais-source"},
{"sv4cpio", "application/x-sv4cpio"},
{"sv4crc", "application/x-sv4crc"},
{"svg", "image/svg+xml"},
{"swf", "application/x-shockwave-flash"},
{"t", "application/x-troff"},
{"tar", "application/x-tar"},
{"tcl", "application/x-tcl"},
{"tex", "application/x-tex"},
{"texi", "application/x-texinfo"},
{"texinfo", "application/x-texinfo"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"tr", "application/x-troff"},
{"tsv", "text/tab-separated-values"},
{"txt", "text/plain"},
{"ustar", "application/x-ustar"},
{"vcd", "application/x-cdlink"},
{"vrml", "model/vrml"},
{"vxml", "application/voicexml+xml"},
{"wav", "audio/x-wav"},
{"wbmp", "image/vnd.wap.wbmp"},
{"wbmxl", "application/vnd.wap.wbxml"},
{"wml", "text/vnd.wap.wml"},
{"wmlc", "application/vnd.wap.wmlc"},
{"wmls", "text/vnd.wap.wmlscript"},
{"wmlsc", "application/vnd.wap.wmlscriptc"},
{"wrl", "model/vrml"},
{"xbm", "image/x-xbitmap"},
{"xht", "application/xhtml+xml"},
{"xhtml", "application/xhtml+xml"},
{"xls", "application/vnd.ms-excel"},
{"xml", "application/xml"},
{"xpm", "image/x-xpixmap"},
{"xsl", "application/xml"},
{"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xltm","application/vnd.ms-excel.template.macroEnabled.12"},
{"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xslt", "application/xslt+xml"},
{"xul", "application/vnd.mozilla.xul+xml"},
{"xwd", "image/x-xwindowdump"},
{"xyz", "chemical/x-xyz"},
{"zip", "application/zip"}
};
}
}
A: If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.
Documentation is at http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping
A: You can also look in the registry.
using System.IO;
using Microsoft.Win32;
string GetMimeType(FileInfo fileInfo)
{
string mimeType = "application/unknown";
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(
fileInfo.Extension.ToLower()
);
if(regKey != null)
{
object contentType = regKey.GetValue("Content Type");
if(contentType != null)
mimeType = contentType.ToString();
}
return mimeType;
}
One way or another you're going to have to tap into a database of MIMEs - whether they're mapped from extensions or magic numbers is somewhat trivial - windows registry is one such place.
For a platform independent solution though one would have to ship this DB with the code (or as a standalone library).
A: I found this one useful.
For VB.NET developers:
Public Shared Function GetFromFileName(ByVal fileName As String) As String
Return GetFromExtension(Path.GetExtension(fileName).Remove(0, 1))
End Function
Public Shared Function GetFromExtension(ByVal extension As String) As String
If extension.StartsWith("."c) Then
extension = extension.Remove(0, 1)
End If
If MIMETypesDictionary.ContainsKey(extension) Then
Return MIMETypesDictionary(extension)
End If
Return "unknown/unknown"
End Function
Private Shared ReadOnly MIMETypesDictionary As New Dictionary(Of String, String)() From { _
{"ai", "application/postscript"}, _
{"aif", "audio/x-aiff"}, _
{"aifc", "audio/x-aiff"}, _
{"aiff", "audio/x-aiff"}, _
{"asc", "text/plain"}, _
{"atom", "application/atom+xml"}, _
{"au", "audio/basic"}, _
{"avi", "video/x-msvideo"}, _
{"bcpio", "application/x-bcpio"}, _
{"bin", "application/octet-stream"}, _
{"bmp", "image/bmp"}, _
{"cdf", "application/x-netcdf"}, _
{"cgm", "image/cgm"}, _
{"class", "application/octet-stream"}, _
{"cpio", "application/x-cpio"}, _
{"cpt", "application/mac-compactpro"}, _
{"csh", "application/x-csh"}, _
{"css", "text/css"}, _
{"dcr", "application/x-director"}, _
{"dif", "video/x-dv"}, _
{"dir", "application/x-director"}, _
{"djv", "image/vnd.djvu"}, _
{"djvu", "image/vnd.djvu"}, _
{"dll", "application/octet-stream"}, _
{"dmg", "application/octet-stream"}, _
{"dms", "application/octet-stream"}, _
{"doc", "application/msword"}, _
{"dtd", "application/xml-dtd"}, _
{"dv", "video/x-dv"}, _
{"dvi", "application/x-dvi"}, _
{"dxr", "application/x-director"}, _
{"eps", "application/postscript"}, _
{"etx", "text/x-setext"}, _
{"exe", "application/octet-stream"}, _
{"ez", "application/andrew-inset"}, _
{"gif", "image/gif"}, _
{"gram", "application/srgs"}, _
{"grxml", "application/srgs+xml"}, _
{"gtar", "application/x-gtar"}, _
{"hdf", "application/x-hdf"}, _
{"hqx", "application/mac-binhex40"}, _
{"htm", "text/html"}, _
{"html", "text/html"}, _
{"ice", "x-conference/x-cooltalk"}, _
{"ico", "image/x-icon"}, _
{"ics", "text/calendar"}, _
{"ief", "image/ief"}, _
{"ifb", "text/calendar"}, _
{"iges", "model/iges"}, _
{"igs", "model/iges"}, _
{"jnlp", "application/x-java-jnlp-file"}, _
{"jp2", "image/jp2"}, _
{"jpe", "image/jpeg"}, _
{"jpeg", "image/jpeg"}, _
{"jpg", "image/jpeg"}, _
{"js", "application/x-javascript"}, _
{"kar", "audio/midi"}, _
{"latex", "application/x-latex"}, _
{"lha", "application/octet-stream"}, _
{"lzh", "application/octet-stream"}, _
{"m3u", "audio/x-mpegurl"}, _
{"m4a", "audio/mp4a-latm"}, _
{"m4b", "audio/mp4a-latm"}, _
{"m4p", "audio/mp4a-latm"}, _
{"m4u", "video/vnd.mpegurl"}, _
{"m4v", "video/x-m4v"}, _
{"mac", "image/x-macpaint"}, _
{"man", "application/x-troff-man"}, _
{"mathml", "application/mathml+xml"}, _
{"me", "application/x-troff-me"}, _
{"mesh", "model/mesh"}, _
{"mid", "audio/midi"}, _
{"midi", "audio/midi"}, _
{"mif", "application/vnd.mif"}, _
{"mov", "video/quicktime"}, _
{"movie", "video/x-sgi-movie"}, _
{"mp2", "audio/mpeg"}, _
{"mp3", "audio/mpeg"}, _
{"mp4", "video/mp4"}, _
{"mpe", "video/mpeg"}, _
{"mpeg", "video/mpeg"}, _
{"mpg", "video/mpeg"}, _
{"mpga", "audio/mpeg"}, _
{"ms", "application/x-troff-ms"}, _
{"msh", "model/mesh"}, _
{"mxu", "video/vnd.mpegurl"}, _
{"nc", "application/x-netcdf"}, _
{"oda", "application/oda"}, _
{"ogg", "application/ogg"}, _
{"pbm", "image/x-portable-bitmap"}, _
{"pct", "image/pict"}, _
{"pdb", "chemical/x-pdb"}, _
{"pdf", "application/pdf"}, _
{"pgm", "image/x-portable-graymap"}, _
{"pgn", "application/x-chess-pgn"}, _
{"pic", "image/pict"}, _
{"pict", "image/pict"}, _
{"png", "image/png"}, _
{"pnm", "image/x-portable-anymap"}, _
{"pnt", "image/x-macpaint"}, _
{"pntg", "image/x-macpaint"}, _
{"ppm", "image/x-portable-pixmap"}, _
{"ppt", "application/vnd.ms-powerpoint"}, _
{"ps", "application/postscript"}, _
{"qt", "video/quicktime"}, _
{"qti", "image/x-quicktime"}, _
{"qtif", "image/x-quicktime"}, _
{"ra", "audio/x-pn-realaudio"}, _
{"ram", "audio/x-pn-realaudio"}, _
{"ras", "image/x-cmu-raster"}, _
{"rdf", "application/rdf+xml"}, _
{"rgb", "image/x-rgb"}, _
{"rm", "application/vnd.rn-realmedia"}, _
{"roff", "application/x-troff"}, _
{"rtf", "text/rtf"}, _
{"rtx", "text/richtext"}, _
{"sgm", "text/sgml"}, _
{"sgml", "text/sgml"}, _
{"sh", "application/x-sh"}, _
{"shar", "application/x-shar"}, _
{"silo", "model/mesh"}, _
{"sit", "application/x-stuffit"}, _
{"skd", "application/x-koan"}, _
{"skm", "application/x-koan"}, _
{"skp", "application/x-koan"}, _
{"skt", "application/x-koan"}, _
{"smi", "application/smil"}, _
{"smil", "application/smil"}, _
{"snd", "audio/basic"}, _
{"so", "application/octet-stream"}, _
{"spl", "application/x-futuresplash"}, _
{"src", "application/x-wais-source"}, _
{"sv4cpio", "application/x-sv4cpio"}, _
{"sv4crc", "application/x-sv4crc"}, _
{"svg", "image/svg+xml"}, _
{"swf", "application/x-shockwave-flash"}, _
{"t", "application/x-troff"}, _
{"tar", "application/x-tar"}, _
{"tcl", "application/x-tcl"}, _
{"tex", "application/x-tex"}, _
{"texi", "application/x-texinfo"}, _
{"texinfo", "application/x-texinfo"}, _
{"tif", "image/tiff"}, _
{"tiff", "image/tiff"}, _
{"tr", "application/x-troff"}, _
{"tsv", "text/tab-separated-values"}, _
{"txt", "text/plain"}, _
{"ustar", "application/x-ustar"}, _
{"vcd", "application/x-cdlink"}, _
{"vrml", "model/vrml"}, _
{"vxml", "application/voicexml+xml"}, _
{"wav", "audio/x-wav"}, _
{"wbmp", "image/vnd.wap.wbmp"}, _
{"wbmxl", "application/vnd.wap.wbxml"}, _
{"wml", "text/vnd.wap.wml"}, _
{"wmlc", "application/vnd.wap.wmlc"}, _
{"wmls", "text/vnd.wap.wmlscript"}, _
{"wmlsc", "application/vnd.wap.wmlscriptc"}, _
{"wrl", "model/vrml"}, _
{"xbm", "image/x-xbitmap"}, _
{"xht", "application/xhtml+xml"}, _
{"xhtml", "application/xhtml+xml"}, _
{"xls", "application/vnd.ms-excel"}, _
{"xml", "application/xml"}, _
{"xpm", "image/x-xpixmap"}, _
{"xsl", "application/xml"}, _
{"xslt", "application/xslt+xml"}, _
{"xul", "application/vnd.mozilla.xul+xml"}, _
{"xwd", "image/x-xwindowdump"}, _
{"xyz", "chemical/x-xyz"}, _
{"zip", "application/zip"} _
}
A: If someone was up for it they could port the excellent perl module File::Type to .NET. In the code is a set of file header magic number look ups for each file type or regex matches.
Here's a .NET file type detecting library http://filetypedetective.codeplex.com/ but it only detects a smallish number of files at the moment.
A: This answer is a copy of the author's answer (Richard Gourlay), but improved to solve issues on IIS 8 / win2012 (where function would cause app pool to crash), based on Rohland's comment pointing to http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata
using System.Runtime.InteropServices;
...
public static string GetMimeFromFile(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException(filename + " not found");
const int maxContent = 256;
var buffer = new byte[maxContent];
using (var fs = new FileStream(filename, FileMode.Open))
{
if (fs.Length >= maxContent)
fs.Read(buffer, 0, maxContent);
else
fs.Read(buffer, 0, (int) fs.Length);
}
var mimeTypePtr = IntPtr.Zero;
try
{
var result = FindMimeFromData(IntPtr.Zero, null, buffer, maxContent, null, 0, out mimeTypePtr, 0);
if (result != 0)
{
Marshal.FreeCoTaskMem(mimeTypePtr);
throw Marshal.GetExceptionForHR(result);
}
var mime = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
return mime;
}
catch (Exception e)
{
if (mimeTypePtr != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(mimeTypePtr);
}
return "unknown/unknown";
}
}
[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
private static extern int FindMimeFromData(IntPtr pBC,
[MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,
int cbSize,
[MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
int dwMimeFlags,
out IntPtr ppwzMimeOut,
int dwReserved);
A: @Steve Morgan and @Richard Gourlay this is a great solution, thank you for that. One small drawback is that when the number of bytes in a file is 255 or below, the mime type will sometimes yield "application/octet-stream", which is slightly inaccurate for files which would be expected to yield "text/plain". I have updated your original method to account for this situation as follows:
If the number of bytes in the file is less than or equal to 255 and the deduced mime type is "application/octet-stream", then create a new byte array that consists of the original file bytes repeated n-times until the total number of bytes is >= 256. Then re-check the mime-type on that new byte array.
Modified method:
Imports System.Runtime.InteropServices
<DllImport("urlmon.dll", CharSet:=CharSet.Auto)> _
Private Shared Function FindMimeFromData(pBC As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzUrl As System.String, <MarshalAs(UnmanagedType.LPArray)> pBuffer As Byte(), cbSize As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzMimeProposed As System.String, dwMimeFlags As System.UInt32, _
ByRef ppwzMimeOut As System.UInt32, dwReserverd As System.UInt32) As System.UInt32
End Function
Private Function GetMimeType(ByVal f As FileInfo) As String
'See http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature
Dim returnValue As String = ""
Dim fileStream As FileStream = Nothing
Dim fileStreamLength As Long = 0
Dim fileStreamIsLessThanBByteSize As Boolean = False
Const byteSize As Integer = 255
Const bbyteSize As Integer = byteSize + 1
Const ambiguousMimeType As String = "application/octet-stream"
Const unknownMimeType As String = "unknown/unknown"
Dim buffer As Byte() = New Byte(byteSize) {}
Dim fnGetMimeTypeValue As New Func(Of Byte(), Integer, String)(
Function(_buffer As Byte(), _bbyteSize As Integer) As String
Dim _returnValue As String = ""
Dim mimeType As UInt32 = 0
FindMimeFromData(0, Nothing, _buffer, _bbyteSize, Nothing, 0, mimeType, 0)
Dim mimeTypePtr As IntPtr = New IntPtr(mimeType)
_returnValue = Marshal.PtrToStringUni(mimeTypePtr)
Marshal.FreeCoTaskMem(mimeTypePtr)
Return _returnValue
End Function)
If (f.Exists()) Then
Try
fileStream = New FileStream(f.FullName(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
fileStreamLength = fileStream.Length()
If (fileStreamLength >= bbyteSize) Then
fileStream.Read(buffer, 0, bbyteSize)
Else
fileStreamIsLessThanBByteSize = True
fileStream.Read(buffer, 0, CInt(fileStreamLength))
End If
returnValue = fnGetMimeTypeValue(buffer, bbyteSize)
If (returnValue.Equals(ambiguousMimeType, StringComparison.OrdinalIgnoreCase) AndAlso fileStreamIsLessThanBByteSize AndAlso fileStreamLength > 0) Then
'Duplicate the stream content until the stream length is >= bbyteSize to get a more deterministic mime type analysis.
Dim currentBuffer As Byte() = buffer.Take(fileStreamLength).ToArray()
Dim repeatCount As Integer = Math.Floor((bbyteSize / fileStreamLength) + 1)
Dim bBufferList As List(Of Byte) = New List(Of Byte)
While (repeatCount > 0)
bBufferList.AddRange(currentBuffer)
repeatCount -= 1
End While
Dim bbuffer As Byte() = bBufferList.Take(bbyteSize).ToArray()
returnValue = fnGetMimeTypeValue(bbuffer, bbyteSize)
End If
Catch ex As Exception
returnValue = unknownMimeType
Finally
If (fileStream IsNot Nothing) Then fileStream.Close()
End Try
End If
Return returnValue
End Function
A: 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.
using System.Runtime.InteropServices;
...
[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";
}
}
A: HeyRed.Mime.MimeGuesser.GuessMimeType from Nuget would be the ultimate solution if you want to host your ASP.NET solution on non-windows environments.
File extension mapping is very insecure. If an attacker would upload invalid extensions, a mapping dictionary would e.g. allow executables to be distributed inside .jpg files.
Therefore, always use a content-sniffing library to know the real content-type.
public static string MimeTypeFrom(byte[] dataBytes, string fileName)
{
var contentType = HeyRed.Mime.MimeGuesser.GuessMimeType(dataBytes);
if (string.IsNullOrEmpty(contentType))
{
return HeyRed.Mime.MimeTypesMap.GetMimeType(fileName);
}
return contentType;
A: Edit: Just use Mime Detective
I use byte array sequences to determine the correct MIME type of a given file. The advantage of this over just looking at the file extension of the file name is that if a user were to rename a file to bypass certain file type upload restrictions, the file name extension would fail to catch this. On the other hand, getting the file signature via byte array will stop this mischievous behavior from happening.
Here is an example in C#:
public class MimeType
{
private static readonly byte[] BMP = { 66, 77 };
private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };
private static readonly byte[] EXE_DLL = { 77, 90 };
private static readonly byte[] GIF = { 71, 73, 70, 56 };
private static readonly byte[] ICO = { 0, 0, 1, 0 };
private static readonly byte[] JPG = { 255, 216, 255 };
private static readonly byte[] MP3 = { 255, 251, 48 };
private static readonly byte[] OGG = { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 };
private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };
private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };
private static readonly byte[] RAR = { 82, 97, 114, 33, 26, 7, 0 };
private static readonly byte[] SWF = { 70, 87, 83 };
private static readonly byte[] TIFF = { 73, 73, 42, 0 };
private static readonly byte[] TORRENT = { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 };
private static readonly byte[] TTF = { 0, 1, 0, 0, 0 };
private static readonly byte[] WAV_AVI = { 82, 73, 70, 70 };
private static readonly byte[] WMV_WMA = { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };
private static readonly byte[] ZIP_DOCX = { 80, 75, 3, 4 };
public static string GetMimeType(byte[] file, string fileName)
{
string mime = "application/octet-stream"; //DEFAULT UNKNOWN MIME TYPE
//Ensure that the filename isn't empty or null
if (string.IsNullOrWhiteSpace(fileName))
{
return mime;
}
//Get the file extension
string extension = Path.GetExtension(fileName) == null
? string.Empty
: Path.GetExtension(fileName).ToUpper();
//Get the MIME Type
if (file.Take(2).SequenceEqual(BMP))
{
mime = "image/bmp";
}
else if (file.Take(8).SequenceEqual(DOC))
{
mime = "application/msword";
}
else if (file.Take(2).SequenceEqual(EXE_DLL))
{
mime = "application/x-msdownload"; //both use same mime type
}
else if (file.Take(4).SequenceEqual(GIF))
{
mime = "image/gif";
}
else if (file.Take(4).SequenceEqual(ICO))
{
mime = "image/x-icon";
}
else if (file.Take(3).SequenceEqual(JPG))
{
mime = "image/jpeg";
}
else if (file.Take(3).SequenceEqual(MP3))
{
mime = "audio/mpeg";
}
else if (file.Take(14).SequenceEqual(OGG))
{
if (extension == ".OGX")
{
mime = "application/ogg";
}
else if (extension == ".OGA")
{
mime = "audio/ogg";
}
else
{
mime = "video/ogg";
}
}
else if (file.Take(7).SequenceEqual(PDF))
{
mime = "application/pdf";
}
else if (file.Take(16).SequenceEqual(PNG))
{
mime = "image/png";
}
else if (file.Take(7).SequenceEqual(RAR))
{
mime = "application/x-rar-compressed";
}
else if (file.Take(3).SequenceEqual(SWF))
{
mime = "application/x-shockwave-flash";
}
else if (file.Take(4).SequenceEqual(TIFF))
{
mime = "image/tiff";
}
else if (file.Take(11).SequenceEqual(TORRENT))
{
mime = "application/x-bittorrent";
}
else if (file.Take(5).SequenceEqual(TTF))
{
mime = "application/x-font-ttf";
}
else if (file.Take(4).SequenceEqual(WAV_AVI))
{
mime = extension == ".AVI" ? "video/x-msvideo" : "audio/x-wav";
}
else if (file.Take(16).SequenceEqual(WMV_WMA))
{
mime = extension == ".WMA" ? "audio/x-ms-wma" : "video/x-ms-wmv";
}
else if (file.Take(4).SequenceEqual(ZIP_DOCX))
{
mime = extension == ".DOCX" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/x-zip-compressed";
}
return mime;
}
}
Notice I handled DOCX file types differently since DOCX is really just a ZIP file. In this scenario, I simply check the file extension once I verified that it has that sequence. This example is far from complete for some people, but you can easily add your own.
If you want to add more MIME types, you can get the byte array sequences of many different file types from here. Also, here is another good resource concerning file signatures.
What I do a lot of times if all else fails is step through several files of a particular type that I am looking for and look for a pattern in the byte sequence of the files. In the end, this is still basic verification and cannot be used for 100% proof of determining file types.
A: I've found a hard-coded solution, I hope i will help somebody:
public static class MIMEAssistant
{
private static readonly Dictionary<string, string> MIMETypesDictionary = new Dictionary<string, string>
{
{"ai", "application/postscript"},
{"aif", "audio/x-aiff"},
{"aifc", "audio/x-aiff"},
{"aiff", "audio/x-aiff"},
{"asc", "text/plain"},
{"atom", "application/atom+xml"},
{"au", "audio/basic"},
{"avi", "video/x-msvideo"},
{"bcpio", "application/x-bcpio"},
{"bin", "application/octet-stream"},
{"bmp", "image/bmp"},
{"cdf", "application/x-netcdf"},
{"cgm", "image/cgm"},
{"class", "application/octet-stream"},
{"cpio", "application/x-cpio"},
{"cpt", "application/mac-compactpro"},
{"csh", "application/x-csh"},
{"css", "text/css"},
{"dcr", "application/x-director"},
{"dif", "video/x-dv"},
{"dir", "application/x-director"},
{"djv", "image/vnd.djvu"},
{"djvu", "image/vnd.djvu"},
{"dll", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"dms", "application/octet-stream"},
{"doc", "application/msword"},
{"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"docm","application/vnd.ms-word.document.macroEnabled.12"},
{"dotm","application/vnd.ms-word.template.macroEnabled.12"},
{"dtd", "application/xml-dtd"},
{"dv", "video/x-dv"},
{"dvi", "application/x-dvi"},
{"dxr", "application/x-director"},
{"eps", "application/postscript"},
{"etx", "text/x-setext"},
{"exe", "application/octet-stream"},
{"ez", "application/andrew-inset"},
{"gif", "image/gif"},
{"gram", "application/srgs"},
{"grxml", "application/srgs+xml"},
{"gtar", "application/x-gtar"},
{"hdf", "application/x-hdf"},
{"hqx", "application/mac-binhex40"},
{"htm", "text/html"},
{"html", "text/html"},
{"ice", "x-conference/x-cooltalk"},
{"ico", "image/x-icon"},
{"ics", "text/calendar"},
{"ief", "image/ief"},
{"ifb", "text/calendar"},
{"iges", "model/iges"},
{"igs", "model/iges"},
{"jnlp", "application/x-java-jnlp-file"},
{"jp2", "image/jp2"},
{"jpe", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"kar", "audio/midi"},
{"latex", "application/x-latex"},
{"lha", "application/octet-stream"},
{"lzh", "application/octet-stream"},
{"m3u", "audio/x-mpegurl"},
{"m4a", "audio/mp4a-latm"},
{"m4b", "audio/mp4a-latm"},
{"m4p", "audio/mp4a-latm"},
{"m4u", "video/vnd.mpegurl"},
{"m4v", "video/x-m4v"},
{"mac", "image/x-macpaint"},
{"man", "application/x-troff-man"},
{"mathml", "application/mathml+xml"},
{"me", "application/x-troff-me"},
{"mesh", "model/mesh"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"mif", "application/vnd.mif"},
{"mov", "video/quicktime"},
{"movie", "video/x-sgi-movie"},
{"mp2", "audio/mpeg"},
{"mp3", "audio/mpeg"},
{"mp4", "video/mp4"},
{"mpe", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mpga", "audio/mpeg"},
{"ms", "application/x-troff-ms"},
{"msh", "model/mesh"},
{"mxu", "video/vnd.mpegurl"},
{"nc", "application/x-netcdf"},
{"oda", "application/oda"},
{"ogg", "application/ogg"},
{"pbm", "image/x-portable-bitmap"},
{"pct", "image/pict"},
{"pdb", "chemical/x-pdb"},
{"pdf", "application/pdf"},
{"pgm", "image/x-portable-graymap"},
{"pgn", "application/x-chess-pgn"},
{"pic", "image/pict"},
{"pict", "image/pict"},
{"png", "image/png"},
{"pnm", "image/x-portable-anymap"},
{"pnt", "image/x-macpaint"},
{"pntg", "image/x-macpaint"},
{"ppm", "image/x-portable-pixmap"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ps", "application/postscript"},
{"qt", "video/quicktime"},
{"qti", "image/x-quicktime"},
{"qtif", "image/x-quicktime"},
{"ra", "audio/x-pn-realaudio"},
{"ram", "audio/x-pn-realaudio"},
{"ras", "image/x-cmu-raster"},
{"rdf", "application/rdf+xml"},
{"rgb", "image/x-rgb"},
{"rm", "application/vnd.rn-realmedia"},
{"roff", "application/x-troff"},
{"rtf", "text/rtf"},
{"rtx", "text/richtext"},
{"sgm", "text/sgml"},
{"sgml", "text/sgml"},
{"sh", "application/x-sh"},
{"shar", "application/x-shar"},
{"silo", "model/mesh"},
{"sit", "application/x-stuffit"},
{"skd", "application/x-koan"},
{"skm", "application/x-koan"},
{"skp", "application/x-koan"},
{"skt", "application/x-koan"},
{"smi", "application/smil"},
{"smil", "application/smil"},
{"snd", "audio/basic"},
{"so", "application/octet-stream"},
{"spl", "application/x-futuresplash"},
{"src", "application/x-wais-source"},
{"sv4cpio", "application/x-sv4cpio"},
{"sv4crc", "application/x-sv4crc"},
{"svg", "image/svg+xml"},
{"swf", "application/x-shockwave-flash"},
{"t", "application/x-troff"},
{"tar", "application/x-tar"},
{"tcl", "application/x-tcl"},
{"tex", "application/x-tex"},
{"texi", "application/x-texinfo"},
{"texinfo", "application/x-texinfo"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"tr", "application/x-troff"},
{"tsv", "text/tab-separated-values"},
{"txt", "text/plain"},
{"ustar", "application/x-ustar"},
{"vcd", "application/x-cdlink"},
{"vrml", "model/vrml"},
{"vxml", "application/voicexml+xml"},
{"wav", "audio/x-wav"},
{"wbmp", "image/vnd.wap.wbmp"},
{"wbmxl", "application/vnd.wap.wbxml"},
{"wml", "text/vnd.wap.wml"},
{"wmlc", "application/vnd.wap.wmlc"},
{"wmls", "text/vnd.wap.wmlscript"},
{"wmlsc", "application/vnd.wap.wmlscriptc"},
{"wrl", "model/vrml"},
{"xbm", "image/x-xbitmap"},
{"xht", "application/xhtml+xml"},
{"xhtml", "application/xhtml+xml"},
{"xls", "application/vnd.ms-excel"},
{"xml", "application/xml"},
{"xpm", "image/x-xpixmap"},
{"xsl", "application/xml"},
{"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xltm","application/vnd.ms-excel.template.macroEnabled.12"},
{"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xslt", "application/xslt+xml"},
{"xul", "application/vnd.mozilla.xul+xml"},
{"xwd", "image/x-xwindowdump"},
{"xyz", "chemical/x-xyz"},
{"zip", "application/zip"}
};
public static string GetMIMEType(string fileName)
{
//get file extension
string extension = Path.GetExtension(fileName).ToLowerInvariant();
if (extension.Length > 0 &&
MIMETypesDictionary.ContainsKey(extension.Remove(0, 1)))
{
return MIMETypesDictionary[extension.Remove(0, 1)];
}
return "unknown/unknown";
}
}
A: IIS 7 or more
Use this code, but you need to be the admin on the server
public bool CheckMimeMapExtension(string fileExtension)
{
try
{
using (
ServerManager serverManager = new ServerManager())
{
// connects to default app.config
var config = serverManager.GetApplicationHostConfiguration();
var staticContent = config.GetSection("system.webServer/staticContent");
var mimeMap = staticContent.GetCollection();
foreach (var mimeType in mimeMap)
{
if (((String)mimeType["fileExtension"]).Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
return true;
}
}
return false;
}
catch (Exception ex)
{
Console.WriteLine("An exception has occurred: \n{0}", ex.Message);
Console.Read();
}
return false;
}
A: When working with Windows Azure Web role or any other host that runs your app in Limited Trust do not forget that you will not be allowed to access registry or unmanaged code. Hybrid approach - combination of try-catch-for-registry and in-memory dictionary looks like a good solution that has a bit of everything.
I use this code to do it :
public class DefaultMimeResolver : IMimeResolver
{
private readonly IFileRepository _fileRepository;
public DefaultMimeResolver(IFileRepository fileRepository)
{
_fileRepository = fileRepository;
}
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private static extern 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 string GetMimeTypeFromFileExtension(string fileExtension)
{
if (string.IsNullOrEmpty(fileExtension))
{
throw new ArgumentNullException("fileExtension");
}
string mimeType = GetMimeTypeFromList(fileExtension);
if (String.IsNullOrEmpty(mimeType))
{
mimeType = GetMimeTypeFromRegistry(fileExtension);
}
return mimeType;
}
public string GetMimeTypeFromFile(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException("filePath");
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found : ", filePath);
}
string mimeType = GetMimeTypeFromList(Path.GetExtension(filePath).ToLower());
if (String.IsNullOrEmpty(mimeType))
{
mimeType = GetMimeTypeFromRegistry(Path.GetExtension(filePath).ToLower());
if (String.IsNullOrEmpty(mimeType))
{
mimeType = GetMimeTypeFromFileInternal(filePath);
}
}
return mimeType;
}
private string GetMimeTypeFromList(string fileExtension)
{
string mimeType = null;
if (fileExtension.StartsWith("."))
{
fileExtension = fileExtension.TrimStart('.');
}
if (!String.IsNullOrEmpty(fileExtension) && _mimeTypes.ContainsKey(fileExtension))
{
mimeType = _mimeTypes[fileExtension];
}
return mimeType;
}
private string GetMimeTypeFromRegistry(string fileExtension)
{
string mimeType = null;
try
{
RegistryKey key = Registry.ClassesRoot.OpenSubKey(fileExtension);
if (key != null && key.GetValue("Content Type") != null)
{
mimeType = key.GetValue("Content Type").ToString();
}
}
catch (Exception)
{
// Empty. When this code is running in limited mode accessing registry is not allowed.
}
return mimeType;
}
private string GetMimeTypeFromFileInternal(string filePath)
{
string mimeType = null;
if (!File.Exists(filePath))
{
return null;
}
byte[] byteBuffer = new byte[256];
using (FileStream fileStream = _fileRepository.Get(filePath))
{
if (fileStream.Length >= 256)
{
fileStream.Read(byteBuffer, 0, 256);
}
else
{
fileStream.Read(byteBuffer, 0, (int)fileStream.Length);
}
}
try
{
UInt32 MimeTypeNum;
FindMimeFromData(0, null, byteBuffer, 256, null, 0, out MimeTypeNum, 0);
IntPtr mimeTypePtr = new IntPtr(MimeTypeNum);
string mimeTypeFromFile = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
if (!String.IsNullOrEmpty(mimeTypeFromFile) && mimeTypeFromFile != "text/plain" && mimeTypeFromFile != "application/octet-stream")
{
mimeType = mimeTypeFromFile;
}
}
catch
{
// Empty.
}
return mimeType;
}
private readonly Dictionary<string, string> _mimeTypes = new Dictionary<string, string>
{
{"ai", "application/postscript"},
{"aif", "audio/x-aiff"},
{"aifc", "audio/x-aiff"},
{"aiff", "audio/x-aiff"},
{"asc", "text/plain"},
{"atom", "application/atom+xml"},
{"au", "audio/basic"},
{"avi", "video/x-msvideo"},
{"bcpio", "application/x-bcpio"},
{"bin", "application/octet-stream"},
{"bmp", "image/bmp"},
{"cdf", "application/x-netcdf"},
{"cgm", "image/cgm"},
{"class", "application/octet-stream"},
{"cpio", "application/x-cpio"},
{"cpt", "application/mac-compactpro"},
{"csh", "application/x-csh"},
{"css", "text/css"},
{"dcr", "application/x-director"},
{"dif", "video/x-dv"},
{"dir", "application/x-director"},
{"djv", "image/vnd.djvu"},
{"djvu", "image/vnd.djvu"},
{"dll", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"dms", "application/octet-stream"},
{"doc", "application/msword"},
{"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"docm", "application/vnd.ms-word.document.macroEnabled.12"},
{"dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{"dtd", "application/xml-dtd"},
{"dv", "video/x-dv"},
{"dvi", "application/x-dvi"},
{"dxr", "application/x-director"},
{"eps", "application/postscript"},
{"etx", "text/x-setext"},
{"exe", "application/octet-stream"},
{"ez", "application/andrew-inset"},
{"gif", "image/gif"},
{"gram", "application/srgs"},
{"grxml", "application/srgs+xml"},
{"gtar", "application/x-gtar"},
{"hdf", "application/x-hdf"},
{"hqx", "application/mac-binhex40"},
{"htc", "text/x-component"},
{"htm", "text/html"},
{"html", "text/html"},
{"ice", "x-conference/x-cooltalk"},
{"ico", "image/x-icon"},
{"ics", "text/calendar"},
{"ief", "image/ief"},
{"ifb", "text/calendar"},
{"iges", "model/iges"},
{"igs", "model/iges"},
{"jnlp", "application/x-java-jnlp-file"},
{"jp2", "image/jp2"},
{"jpe", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"kar", "audio/midi"},
{"latex", "application/x-latex"},
{"lha", "application/octet-stream"},
{"lzh", "application/octet-stream"},
{"m3u", "audio/x-mpegurl"},
{"m4a", "audio/mp4a-latm"},
{"m4b", "audio/mp4a-latm"},
{"m4p", "audio/mp4a-latm"},
{"m4u", "video/vnd.mpegurl"},
{"m4v", "video/x-m4v"},
{"mac", "image/x-macpaint"},
{"man", "application/x-troff-man"},
{"mathml", "application/mathml+xml"},
{"me", "application/x-troff-me"},
{"mesh", "model/mesh"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"mif", "application/vnd.mif"},
{"mov", "video/quicktime"},
{"movie", "video/x-sgi-movie"},
{"mp2", "audio/mpeg"},
{"mp3", "audio/mpeg"},
{"mp4", "video/mp4"},
{"mpe", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mpga", "audio/mpeg"},
{"ms", "application/x-troff-ms"},
{"msh", "model/mesh"},
{"mxu", "video/vnd.mpegurl"},
{"nc", "application/x-netcdf"},
{"oda", "application/oda"},
{"ogg", "application/ogg"},
{"pbm", "image/x-portable-bitmap"},
{"pct", "image/pict"},
{"pdb", "chemical/x-pdb"},
{"pdf", "application/pdf"},
{"pgm", "image/x-portable-graymap"},
{"pgn", "application/x-chess-pgn"},
{"pic", "image/pict"},
{"pict", "image/pict"},
{"png", "image/png"},
{"pnm", "image/x-portable-anymap"},
{"pnt", "image/x-macpaint"},
{"pntg", "image/x-macpaint"},
{"ppm", "image/x-portable-pixmap"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ps", "application/postscript"},
{"qt", "video/quicktime"},
{"qti", "image/x-quicktime"},
{"qtif", "image/x-quicktime"},
{"ra", "audio/x-pn-realaudio"},
{"ram", "audio/x-pn-realaudio"},
{"ras", "image/x-cmu-raster"},
{"rdf", "application/rdf+xml"},
{"rgb", "image/x-rgb"},
{"rm", "application/vnd.rn-realmedia"},
{"roff", "application/x-troff"},
{"rtf", "text/rtf"},
{"rtx", "text/richtext"},
{"sgm", "text/sgml"},
{"sgml", "text/sgml"},
{"sh", "application/x-sh"},
{"shar", "application/x-shar"},
{"silo", "model/mesh"},
{"sit", "application/x-stuffit"},
{"skd", "application/x-koan"},
{"skm", "application/x-koan"},
{"skp", "application/x-koan"},
{"skt", "application/x-koan"},
{"smi", "application/smil"},
{"smil", "application/smil"},
{"snd", "audio/basic"},
{"so", "application/octet-stream"},
{"spl", "application/x-futuresplash"},
{"src", "application/x-wais-source"},
{"sv4cpio", "application/x-sv4cpio"},
{"sv4crc", "application/x-sv4crc"},
{"svg", "image/svg+xml"},
{"swf", "application/x-shockwave-flash"},
{"t", "application/x-troff"},
{"tar", "application/x-tar"},
{"tcl", "application/x-tcl"},
{"tex", "application/x-tex"},
{"texi", "application/x-texinfo"},
{"texinfo", "application/x-texinfo"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"tr", "application/x-troff"},
{"tsv", "text/tab-separated-values"},
{"txt", "text/plain"},
{"ustar", "application/x-ustar"},
{"vcd", "application/x-cdlink"},
{"vrml", "model/vrml"},
{"vxml", "application/voicexml+xml"},
{"wav", "audio/x-wav"},
{"wbmp", "image/vnd.wap.wbmp"},
{"wbmxl", "application/vnd.wap.wbxml"},
{"wml", "text/vnd.wap.wml"},
{"wmlc", "application/vnd.wap.wmlc"},
{"wmls", "text/vnd.wap.wmlscript"},
{"wmlsc", "application/vnd.wap.wmlscriptc"},
{"wrl", "model/vrml"},
{"xbm", "image/x-xbitmap"},
{"xht", "application/xhtml+xml"},
{"xhtml", "application/xhtml+xml"},
{"xls", "application/vnd.ms-excel"},
{"xml", "application/xml"},
{"xpm", "image/x-xpixmap"},
{"xsl", "application/xml"},
{"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{"xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xslt", "application/xslt+xml"},
{"xul", "application/vnd.mozilla.xul+xml"},
{"xwd", "image/x-xwindowdump"},
{"xyz", "chemical/x-xyz"},
{"zip", "application/zip"}
};
}
A: I ended up using Winista MimeDetector from Netomatix. The sources can be downloaded for free after you created an account: http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx
MimeTypes g_MimeTypes = new MimeTypes("mime-types.xml");
sbyte [] fileData = null;
using (System.IO.FileStream srcFile = new System.IO.FileStream(strFile, System.IO.FileMode.Open))
{
byte [] data = new byte[srcFile.Length];
srcFile.Read(data, 0, (Int32)srcFile.Length);
fileData = Winista.Mime.SupportUtil.ToSByteArray(data);
}
MimeType oMimeType = g_MimeTypes.GetMimeType(fileData);
This is part of another question answered here: Alternative to FindMimeFromData method in Urlmon.dll one which has more MIME types
The best solution to this problem in my opinion.
A: I found several problems of running this code:
UInt32 mimetype;
FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
If you will try to run it with x64/Win10 you will get
AccessViolationException "Attempted to read or write protected memory.
This is often an indication that other memory is corrupt"
Thanks to this post PtrToStringUni doesnt work in windows 10 and @xanatos
I modified my solution to run under x64 and .NET Core 2.1:
[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true,
SetLastError = false)]
static extern int FindMimeFromData(IntPtr pBC,
[MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1,
SizeParamIndex=3)]
byte[] pBuffer,
int cbSize,
[MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
int dwMimeFlags,
out IntPtr ppwzMimeOut,
int dwReserved);
string getMimeFromFile(byte[] fileSource)
{
byte[] buffer = new byte[256];
using (Stream stream = new MemoryStream(fileSource))
{
if (stream.Length >= 256)
stream.Read(buffer, 0, 256);
else
stream.Read(buffer, 0, (int)stream.Length);
}
try
{
IntPtr mimeTypePtr;
FindMimeFromData(IntPtr.Zero, null, buffer, buffer.Length,
null, 0, out mimeTypePtr, 0);
string mime = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
return mime;
}
catch (Exception ex)
{
return "unknown/unknown";
}
}
Thanks
A: Hello I have adapted Winista.MimeDetect project into .net core/framework with fallback into urlmon.dll Fell free to use it: nuget package.
//init
var mimeTypes = new MimeTypes();
//usage by filepath
var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "264"
} |
Q: Unit testing ASP.NET MVC redirection How do I Unit Test a MVC redirection?
public ActionResult Create(Product product)
{
_productTask.Save(product);
return RedirectToAction("Success");
}
public ActionResult Success()
{
return View();
}
Is Ayende's approach still the best way to go, with preview 5:
public static void RenderView(this Controller self, string action)
{
typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} );
}
Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.
A: [TestFixture]
public class RedirectTester
{
[Test]
public void Should_redirect_to_success_action()
{
var controller = new RedirectController();
var result = controller.Index() as RedirectToRouteResult;
Assert.That(result, Is.Not.Null);
Assert.That(result.Values["action"], Is.EqualTo("success"));
}
}
public class RedirectController : Controller
{
public ActionResult Index()
{
return RedirectToAction("success");
}
}
A: This works for ASP.NET MVC 5 using NUnit:
[Test]
public void ShouldRedirectToSuccessAction()
{
var controller = new RedirectController();
var result = controller.Index() as RedirectToRouteResult;
Assert.That(result.RouteValues["action"], Is.EqualTo("success"));
}
If you want to test that you are redirecting to a different controller (say NewController), the assertion would be:
Assert.That(result.RouteValues["controller"], Is.EqualTo("New"));
A: You can assert on the ActionResult that is returned, you'll need to cast it to the appropriate type but it does allow you to use state-based testing. A search on the Web should find some useful links, here's just one though.
A: you can use Mvc.Contrib.TestHelper which provides assertions for testing redirections. Take a look at http://kbochevski.blogspot.com/2010/06/unit-testing-mvcnet.html and the code sample. It might be helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Combining Enums Is there a way to combine Enums in VB.net?
A: I believe what you want is a flag type enum.
You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword.
Like this:
<Flags()> _
Enum CombinationEnums As Integer
HasButton = 1
TitleBar = 2
[ReadOnly] = 4
ETC = 8
End Enum
Note: The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set.
Combine the desired flags using the Or keyword:
Dim settings As CombinationEnums
settings = CombinationEnums.TitleBar Or CombinationEnums.Readonly
This sets TitleBar and Readonly into the enum
To check what's been set:
If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then
Window.TitleBar = True
End If
A: You can use the FlagsAttribute to decorate an Enum like so which will let you combine the Enum:
<FlagsAttribute> _
Public Enumeration SecurityRights
None = 0
Read = 1
Write = 2
Execute = 4
And then call them like so (class UserPriviltes):
Public Sub New ( _
options As SecurityRights _
)
New UserPrivileges(SecurityRights.Read OR SecurityRights.Execute)
They effectively get combined (bit math) so that the above user has both Read AND Execute all carried around in one fancy SecurityRights variable.
To check to see if the user has a privilege you use AND (more bitwise math) to check the users enum value with the the Enum value you're checking for:
//Check to see if user has Write rights
If (user.Privileges And SecurityRights.Write = SecurityRigths.Write) Then
//Do something clever...
Else
//Tell user he can't write.
End If
HTH,
Tyler
A: If I understand your question correctly you want to combine different enum types. So one variable can store a value from one of two different enum's right? If you're asking about storing combining two different values of one enum type you can look at Dave Arkell's explanation
Enums are just integers with some syntactic sugar. So if you make sure there's no overlap you can combine them by casting to int.
It won't make for pretty code though. I try to avoid using enums most of the time. Usually if you let enums breed in your code it's just a matter of time before they give birth to repeated case statements and other messy antipatterns.
A: The key to combination Enums is to make sure that the value is a power of two (1, 2, 4, 8, etc.) so that you can perform bit operations on them (|= &=). Those Enums can be be tagged with a Flags attribute. The Anchor property on Windows Forms controls is an example of such a control. If it's marked as a flag, Visual Studio will let you check values instead of selecting a single one in a drop-down in the properties designer.
A: If you taking about using enum flags() there is a good article here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Version control of deliverables 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.
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.
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.
Are there any tools better suited for the task? Or may be a completely different approach?
Update:
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.
A: I'd probably take a look at rsync.
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.
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.
A: Another option is unison
A: You should look into continuous integration and having some kind of centralised build process. I can only imagine the kind of hell you're going through with your current approach.
Obviously that doesn't help with the keeping your local files in sync, but I think you have bigger problems with your process.
A: Building the project should be a centralized process in order to allow for better control soon your solution will be caos in the long run. Anyway here is what I'd do.
*
*Create the usual repositories for
source files, resources,
documentation, etc for each project.
*Create a repository for resources.
There will be the latest binary
versions for each project as well as
any required resources, files, etc.
Keep a good folder structure for
each project so developers can
"reference" the files directly.
*Create a repository for final buidls
which will hold the actual stable
release. This will get the stable
files, done in an automatic way (if
possible) from the checked in
sources. This will hold the real
product, the real version for
integration testing and so on.
While far from being perfect you'll be able to define well established protocols. Check in your latest dll here, generate the "real" versión from latest source here.
A: What about embedding a 'what' string in the executables and libraries. Then you can synchronise the desired list of versions with a manifest.
We tend to use CVS id strings as a part of the what string.
const char cvsid[] = "@(#)INETOPS_filter_ip_$Revision: 1.9 $";
Entering the command
what filter_ip | grep INETOPS
returns
INETOPS_filter_ip_$Revision: 1.9 $
We do this for all deliverables so we can see if the versions in a bundle of libraries and executables match the list in a associated manifest.
HTH.
cheers,
Rob
A: Subversion handles binary files really well, is pretty fast, and scriptable. VisualSVN and TortoiseSVN make dealing with Subversion very easy too.
You could set up a folder that's checked out from Subversion with all your binary files (that all developers can push and update to) then just type "svn update" at the command line, or use TortoiseSVN: right click on the folder, click "SVN Update" and it'll update all the files and tell you what's changed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do you create an event log source using WiX I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.
Does anyone know the best way to do this using the WiX framework.
A: Wix has out-of-the-box support for creating event log sources.
Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component :
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
<Component ...>
...
<util:EventSource Log="Application" Name="*source name*"
EventMessageFile="*path to message file*"/>
...
</Component>
If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.
A: Just to save people some time - if you are trying to use the Application log and the .NET messages you can cut paste the below code:
<Util:EventSource
xmlns:Util="http://schemas.microsoft.com/wix/UtilExtension"
Name="ROOT Builder"
Log="Application"
EventMessageFile="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll"
/>
NOTE: the path above is now correct..
A: How about the more flexible stuff built in:
EventMessageFile="[NETFRAMEWORK20INSTALLROOTDIR]EventLogMessages.dll"
or
EventMessageFile="[NETFRAMEWORK40FULLINSTALLROOTDIR]EventLogMessages.dll"
And
EventMessageFile="[NETFRAMEWORK40FULLINSTALLROOTDIR64]EventLogMessages.dll"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: How to resolve SQL query parameters mapping issues while using Oracle OLE DB provider? When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:
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.
ADDITIONAL INFORMATION:
Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle)
I have tried following the suggestion here but don't quite understand what is required:Parameterized queries against Oracle
Any ideas?
A: To expand on the link given in the question:
*
*Create a package variable
*Double click on the package variable name. (This allows you to access the properties of the variable)
*Set the property 'EvaluateAsExpression' to true
*Enter the query in the expression builder.
*Set the OLE DB source query to SQL Command from Variable
The expression builder can dynamically create expressions using variable to create 'parametised queries'.
So the following 'normal' query:
select * from book where book.BOOK_ID = ?
Can be written in the expression builder as:
"select * from book where book.BOOK_ID = " + @[User::BookID]
You can then do null handling and data conversion using the expression builder.
A: If You use Data Flow Task and use OLE DB Source, and you need parameterize your Query :
*
*Create Variable to save "Full" of Query statement : Right Click on blank area outside the package - and Click Variables :
Click Add Variables on Variables Window :
Make the name is SQL_DTFLOW_FULL or something that can you understand easily. The variable data type is STRING
*Create Variable(s) to save your parameter(s).
i.e, the full of Query stamements is :
SELECT * FROM BOOK WHERE BOOK_ID = @BookID --@BookID is SQL Parameter
at the sample above, I have just one parameter : @BookID, so I need to create one variable to save my parameter. Add more variables depends on your Queries.
Give it name SQL_DTFLOW_BOOKID
The variable data type is STRING
So, you need make your SSIS neat, and the variables is sorted in understandable parts.
Try to make the variable name is SQL_{TASK NAME}_{VariableName}
*Make Expression for SQL_DTFLOW_FULL variable, click on number 1, and start fill number 2. Make Your SQL Statements to be a correct SQL Statement using string block. String block usually using "Double Quote" at the beginning and the end. Concat the variables with the string block.
Click evaluate Expression, to showing result, to make sure your query is correct, copy-paste the Query result at SSMS.
Make sure by yourself that the variables is free from SQL Injection using your own logic. (Use your developer instinct)
*Open the Data Flow Task, open the OLE DB Source Editor by double click the item.
*
*Select the Data Access Mode : SQL Command From Variable
*Select the Variable Name : SQL_DTFLOW_FULL
*Click Preview to make sure it works.
That is all, my way to prevent this SSIS failure case. Since I use this way, I never got that problem, you know, SSIS something is weird.
To change the variable value, set it before Data Flow Task, the SQL Result of SQL_DTFLOW_FULL variable will changed every you change your variable value.
A: In my case the issue was that i had comments within the sql in the normal form of /* */ and i also had column aliases as "Column name" instead of [Column Name].
Once i removed them it works.
Also try to have your parameter ? statement within the WHERE clause and not within the JOINS, that was part of the issue too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: - How to show the whole height of referenced page? I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an <iframe>.
Easy: just set height and width to 100%! Except, it doesn't work.
I did find out about setting frameborder to 0, so it at least looks like part of the site, but I'd prefer not to have an ugly scrollbar inside a page that allready has one.
Do you know of any tricks to do this?
EDIT: I think I need to clarify my question somewhat:
*
*the company CMS displays the fluff and stuff for our whole website
*most pages created through the CMS
*my application isn't, but they will let me embedd it in an <iframe>
*I have no control over the iframe, so any solution must work from the referenced page (according to the src attribute of the iframe tag)
*the CMS displays a footer, so setting the height to 1 million pixels is not a good idea
Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...
This technique seems to work (gleaned from several sources, but inspired by the link from the accepted answer:
In parent document:
<iframe id="MyIFRAME" name="MyIFRAME"
src="http://localhost/child.html"
scrolling="auto" width="100%" frameborder="0">
no iframes supported...
</iframe>
In child:
<!-- ... -->
<body>
<script type="text/javascript">
function resizeIframe() {
var docHeight;
if (typeof document.height != 'undefined') {
docHeight = document.height;
}
else if (document.compatMode && document.compatMode != 'BackCompat') {
docHeight = document.documentElement.scrollHeight;
}
else if (document.body
&& typeof document.body.scrollHeight != 'undefined') {
docHeight = document.body.scrollHeight;
}
// magic number: suppress generation of scrollbars...
docHeight += 20;
parent.document.getElementById('MyIFRAME').style.height = docHeight + "px";
}
parent.document.getElementById('MyIFRAME').onload = resizeIframe;
parent.window.onresize = resizeIframe;
</script>
</body>
BTW: This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...
A: You could either just use a scripting language to include the page into the parent page, other wise, you might want to try one of these javascript methods:
http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html
A: Provided that your iframe is hosted on the same server as the containing page, you can access it via javascript.
There are a number of suggested methods for setting the iframe to the full height of the contents, each with varying degrees of success - a google for this problem shows that it's quite a common one, with no real, one-size-fits-all consensus solution i'm afraid!
Several people have reported that this script does the trick, but may need some modification for your specific case (again, assuming your iframe and parent page are on the same domain).
A: I might be missing something here, but adding scrolling=no as an attribute to the iframe tag normally gets rid of the scrollbars.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Painless resource management in java In C++ we acquiring a resource in a constructor and release it in a destructor.
So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.
AFAIK java classes don't have destructors. So how does one do the resource management in Java.
For example:
public int foo() {
Resource f = new Resource();
DoSomething(f);
f.Release();
}
How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?
A: Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand "using" statement, but in Java you are stuck with:
public int foo() {
Resource f = new Resource();
try {
DoSomething(f);
}
finally {
f.Release();
}
}
A: This question dates to 2008 and therefore pertains to Java 6. Since then Java 7 has been released, which contains a new feature for Automatic Resource Management. For a more recent question that is relevant to Java 7 see this question:
java techniques for automatic resource release? "prompt cleanup"?
A: It is possible to factor out try/finally (and exception and algorithms) using the Execute around idiom. However the syntax is highly verbose.
public int foo() {
withResource(new WithResource() { public void run(Resource resource) {
doSomething(resource);
}});
}
...
public interface WithResource {
void run(Resource resource);
}
public static void withResource(WithResource handler) {
Resource resource = new Resource();
try {
handler.run(resource);
} finally {
resource.release();
}
}
This sort of thing makes more sense if you are abstracting more than try/finally. For instance, with JDBC you can execute a statement, loop through the results, close resources and wrap the exception.
A: If you want the using block get involved in the java closure debate :S
A: Sorry to disappoint you but in Java we do use try\catch\finally blocks a lot. And with "a lot", I mean A LOT. I do sometimes wish that Java has the C# using block. Most of the time you won't need to free up resources as Java's garbage collector will take care of that.
However exceptions do have their uses in making error handling a lot cleaner. You can write your own exceptions and catch them for whatever you are doing. No more returning arbitrary error codes to the user!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I configure Firebug to use Eclipse/Netbeans as editor I want to use a real IDE for editing javascript files in combination with Firebug. In the 'Add editor' dialog for Firebug I'm allowed to specify executable and arguments. So the question is really how do I open a file in Eclipse/Netbeans from the command line.
Extra points for allowing me to choose between opening a new Eclipse/netbeans instance and reusing an already running one.
A: Not an exact answer I'm afraid, but this information might help.
Eclipse Help - Running Eclipse
Fireclipse: Debug from FF straight into Eclipse
A: I havent tried this yet but looks interesting Javascript Debug Toolkit 2.0.0
Also I have heard that aptana is pretty good
A: Ever though about the other way round? That means to start eclipse, start there a debug session with Firebug included?
If that could be an answer, see the explanation under Installing the JavaScript degbugger for the Aptana Studio. There is an option to install Aptana inside eclipse instead of loading the whole thing.
Caveat: I have never tried that, but I use currently Aptana for programming Rails, perhaps I will use that in the near future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to tweak Eclipse's C++ Indexer? I'm using Eclipse as my IDE for a C++ project, and I would love for it to tell me where a given symbol is defined and what the parameters are for a function.
However, there's a catch: I also use Lazy C++, a tool that takes a single source file and generates the .h and the .cpp files. Those .lzz files look like headers, but this tool supports some very mild syntactic benefits, like combining nested namespaces into a qualified name. Additionally, it has some special tags to tell the tool specifically where to put what (in header or in source file).
So my typical SourceFile.lzz looks like this:
$hdr
#include <iosfwd>
#include "ProjectA/BaseClass.h"
$end
$src
#include <iostream>
#include "ProjectB/OtherClass.h"
$end
// Forward declarations
namespace BigScope::ProjectB
{
class OtherClass;
}
namespace BigScope::ProjectA
{
class MyClass : public ProjectA::BaseClass
{
void SomeMethod(const ProjectB::OtherClass& Foo) { }
}
}
As you see, it's still recognizable C++, but with a few extras.
For some reason, CDT's indexer does not seem to want to index anything, and I don't know what's wrong. In the Indexer View, it shows me an empty tree, but tells me that it has some 15000 symbols and more stuff, none of which I can seem to access.
So here's my question: how can I make the Indexer output some more information about what it's doing and why it fails when it does so, and can I tweak it more than with just the GUI-accessible options?
Thanks,
Carl
A: I'd imagine its one of:
*
*Eclipse doesn't want to display non-C++ resources in the tree (I've had problems with this)
*You don't have "Preferences > C/C++ > Indexer > Index All Files" enabled.
*You want to use the "Full C/C++ Indexer" rather than the "Fast C/C++ Indexer"
A: The CDT parser/indexer won't recognize weird extensions like that. The only thing you can do is to define macros on the Paths and Symbols property page to trick the parser. Try creating macros for $hdr, $end and $src that have empty bodies. That way the preprocessor will remove them and the parser won't choke on them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I remotely get a checksum for a file on a Windows machine? I'm trying to check, using an automated discovery tool, when JAR files in remote J2EE application servers have changed content. Currently, the system downloads the whole JAR using WMI to checksum it locally, which is slow for large JARs.
For UNIXy servers (and Windows servers with Cygwin), I can just log in over SSH and run md5sum foo.jar. Ideally, I'd like to avoid installing extra software on the remote servers (there may be thousands), so is there a good way to do this on vanilla Windows servers?
A: You could try the Sysinternals PSExec tool. You would need a checksum utility available on the remote machine. Unfortunately since they became part of Microsoft they don't make any source code available.
Alternatively, you could install the Cygwin SSH daemon on the remote machines and use ssh but that's a bit more involved.
A: Microsoft has a free checksum tool you could run with PSExec above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use hibernate criteria to return only one element of an object instead the entire object? I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?
An example :
final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
.append( bob.class.getName() ).append( " bob " )
.append( "where bob.id > 10");
final Query query = session.createQuery( hql.toString() );
return query.list();
A: or setProjection(Projections.id())
A: I think you could do that with Projections, something like
Criteria.forClass(bob.class.getName())
.add(Restrictions.gt("id", 10))
.setProjection(Projections.property("id"))
);
A: Similarly you can also:
Criteria criteria = session.createCriteria(bob.class);
criteria.add(Expression.gt("id", 10));
criteria.setProjection(Projections.property("id"));
criteria.addOrder(Order.asc("id"));
return criteria.list();
A: http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/2/
A: SessionFactory sessionFactory;
Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.setProjection(Projections.property("id"));
List result = crit.list();
This code code will give you list of ids in the model class like [1,2,3].
if you wants to get the array list like [{"id":1},{"id":2}] then use the following code
SessionFactory sessionFactory;
Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.setProjection(Projections.property("id").as("id"));
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
A: Another option (though a bit un hibernate-esque) is to use "raw" sql, like this:
List<Long> myList = session.createSQLQuery("select single_column from table_name")
.addScalar("single_column", StandardBasicTypes.LONG).list();
A: You can do that like this
bob bb=null;
Criteria criteria = session.createCriteria(bob.class);
criteria.add(Restrictions.eq("id",id));
bb = (bob) criteria.uniqueResult();
as Restrictions you can add your condition
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: core dump files on Linux: how to get info on opened files? I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.
A: Your best bet is to install a signal handler for whatever signal is crashing your program (SIGSEGV, etc.).
Then, in the signal handler, inspect /proc/self/fd, and save the contents to a file. Here is a sample of what you might see:
Anderson cxc # ls -l /proc/8247/fd
total 0
lrwx------ 1 root root 64 Sep 12 06:05 0 -> /dev/pts/0
lrwx------ 1 root root 64 Sep 12 06:05 1 -> /dev/pts/0
lrwx------ 1 root root 64 Sep 12 06:05 10 -> anon_inode:[eventpoll]
lrwx------ 1 root root 64 Sep 12 06:05 11 -> socket:[124061]
lrwx------ 1 root root 64 Sep 12 06:05 12 -> socket:[124063]
lrwx------ 1 root root 64 Sep 12 06:05 13 -> socket:[124064]
lrwx------ 1 root root 64 Sep 12 06:05 14 -> /dev/driver0
lr-x------ 1 root root 64 Sep 12 06:05 16 -> /temp/app/whatever.tar.gz
lr-x------ 1 root root 64 Sep 12 06:05 17 -> /dev/urandom
Then you can return from your signal handler, and you should get a core dump as usual.
A: One of the ways I jump to this information is just running strings on the core file. For instance, when I was running file on a core recently, due to the length of the folders I would get a truncated arguments list. I knew my run would have opened files from my home directory, so I just ran:
strings core.14930|grep jodie
But this is a case where I had a needle and a haystack.
A: You can try using strace to see the open, socket and close calls the program makes.
Edit: I don't think you can get the information from the core; at most it will have the file descriptors somewhere, but this still doesn't give you the actual file/socket. (Assuming you can distinguish open from closed file descriptors, which I also doubt.)
A: If the program forgot to close those resources it might be because something like the following happened:
fd = open("/tmp/foo",O_CREAT);
//do stuff
fd = open("/tmp/bar",O_CREAT); //Oops, forgot to close(fd)
now I won't have the file descriptor for foo in memory.
If this didn't happen, you might be able to find the file descriptor number, but then again, that is not very useful because they are continuously changing, by the time you get to debug you won't know which file it actually meant at the time.
I really think you should debug this live, with strace, lsof and friends.
If there is a way to do it from the core dump, I'm eager to know it too :-)
A: Recently during my error troubleshooting and analysis , my customer provided me a coredump which got generated in his filesystem and he went out of station in order to quickly scan through the file and read its contents i used the command
strings core.67545 > coredump.txt
and later i was able to open the file in file editor.
A: If you have a core file and you have compiled the program with debugging options (-g), you can see where the core was dumped:
$ gcc -g -o something something.c
$ ./something
Segmentation fault (core dumped)
$ gdb something core
You can use this to do some post-morten debugging. A few gdb commands: bt prints the stack, fr jumps to given stack frame (see the output of bt).
Now if you want to see which files are opened at a segmentation fault, just handle the SIGSEGV signal, and in the handler, just dump the contents of the /proc/PID/fd directory (i.e. with system('ls -l /proc/PID/fs') or execv).
With these information at hand you can easily find what caused the crash, which files are opened and if the crash and the file descriptor leak are connected.
A: A core dump is a copy of the memory the process had access to when crashed. Depending on how the leak is occurring, it might have lost the reference to the handles, so it may prove to be useless.
lsof lists all currently open files in the system, you could check its output to find leaked sockets or files. Yes, you'd need to have the process running. You could run it with a specific username to easily discern which are the open files from the process you are debugging.
I hope somebody else has better information :-)
A: Another way to find out what files a process has opened - again, only during runtime - is looking into /proc/PID/fd/ , which contains symlinks to open files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: In Vim, what is the best way to select, delete, or comment out large portions of multi-screen text? Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?
I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?
And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?
A: Use the visual block command v (or V for whole lines and C-V for rectangular blocks). While in visual block mode, you can use any motion commands including search; I use } frequently to skip to the next blank line. Once the block is marked, you can :w it to a file, delete, yank, or whatever. If you execute a command and the visual block goes away, re-select the same block with gv. See :help visual-change for more.
I think there are language-specific scripts that come with vim that do things like comment out blocks of code in a way that fits your language of choice.
A: Press V (uppercase V) and then press 40j to select 40 lines and then press d to delete them. Or as @zigdon replied, you can comment them out.
A: The visual mode is the solution for your main problem. As to commenting out sections of code, there are many plugins for that on vim.org, I am using tComment.vim at the moment.
There is also a neat way to comment out a block without a plugin. Lets say you work in python and # is the comment character. Make a visual block selection of the column you want the hash sign to be in, and type I#ESCAPE. To enter a visual block mode press C-q on windows or C-v on linux.
A: My block comment technique:
Ctrl+V to start blockwise visual mode.
Make your selection.
With the selection still active, Shift+I. This put you into column insert mode.
Type you comment characters '#' or '//' or whatever.
ESC.
A: Or you may want to give this script a try...
http://www.vim.org/scripts/script.php?script_id=23
A: For commenting out lines, I would suggest one of these plugins:
EnhancedCommentify
NERD Commenter
I find myself using NERD more these days, but I've used EnhancedCommentify for years.
A: Well, first of all, you can set vim to work with the mouse, which would allow you to select text just like you would in Eclipse.
You can also use the Visual selection - v, by default. Once selected, you can yank, cut, etc.
As far as commenting out the block, I usually select it with VISUAL, then do
:'<,'>s/^/# /
Replacing the beginning of each line with a #. (The '< and '> markers are the beginning and and of the visual selection.
A: Use markers.
Go to the top of the text block you want to delete and enter
ma
anywhere on that line. No need for the colon.
Then go to the end of the block and enter the following:
:'a,.d
Entering ma has set marker a for the character under the cursor.
The command you have entered after moving to the bottom of the text block says "from the line containing the character described by marker a ('a) to the current line (.) delete."
This sort of thing can be used for other things as well.
:'a,.ya b - yank from 'a to current line and put in buffer 'b'
:'a,.ya B - yank from 'a to current line and append to buffer 'b'
:'a,.s/^/#/ - from 'a to current line, substitute '#' for line begin
(i.e. comment out in Perl)
:'s,.s#^#//# - from 'a to current line, substitute '//' for line begin
(i.e. comment out in C++)
N.B. 'a (apostrophe-a) refers to the line containing the character marked by a. ``a(backtick-a) refers to the character marked bya`.
A: Use Shift+V to go in visual mode, then you can select lines and delete / change them.
A: If you want to perform an action on a range of lines, and you know the line numbers, you can put the range on the command line. For instance, to delete lines 20 through 200 you can do:
:20,200d
To move lines 20 through 200 to where line 300 is you can use:
:20,200m300
And so on.
A: To insert comments select the beginning characters of the lines using CTRL-v (blockwise-visual, not 'v' character wise-visual or 'V' linewise-visual). Then go to insert-mode using 'I', enter your comment-character(s) on the first line (for example '#') and finally escape to normal mode using 'Esc'. Voila!
To remove the comments use blockwise-visual to select the comments and just delete them using 'x'.
A: My usual method for commenting out 40 lines would be to put the cursor on the first line and enter the command:
:.,+40s/^/# /
(For here thru 40 lines forward, substitute start-of-line with hash, space)
Seems a bit longer than some other methods suggested, but I like to do things with the keyboard instead of the mouse.
A: You should be aware of the normal mode command [count]CTRL-D.
It optionally changes the 'scroll' option from 10 to [count], and then scrolls down that many lines. Pressing CTRL-D again will scroll down that same lines again.
So try entering
V "visual line selection mode
30 "optionally set scroll value to 30
CTRL-D "jump down a screen, repeated as necessary
y " yank your selection
CTRL-U works the same way but scrolls up.
A: First answer is currently not quite right?
To comment out selection press ':' and type command
:'<,'>s/^/# /g
('<, '> - will be there automatically)
A: v enters visual block mode, where you can select as if with shift in most common editors, later you can do anything you can normally do with normal commands (substitution :'<,'>s/^/#/ to prepend with a comment, for instance) where '<,'> means the selected visual block instead of all the text.
A: marks would be the simplest mb where u want to begin and me where u want to end once this is done you can do pretty much anything you want
:'b,'ed
deletes from marker b to marker e
commenting out 40 lines you can do in the visual mode
V40j:s/^/#/
will comment out 40 lines from where u start the sequence
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Measuring stack usage for Linux multi-threaded app I'm developing a multi-threaded app for a Linux embedded platform.
At the moment I'm setting the stack size for each thread (via pthread_set_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming.
I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.)
Thanks
A: Here are two tools that measure (native pthreads) stack usage in Linux applications:
*
*Valgrind
*Stackusage
Valgrind
Usage:
valgrind --tool=drd --show-stack-usage=yes PROG
Valgrind is a stable and powerful tool, useful not only for measuring stack usage. It may not support all embedded CPU models though.
Stackusage
Usage:
stackusage PROG
Stackusage is a light-weight tool specifically designed for measuring thread stack usage which should be portable for most embedded Linux platforms equipped with glibc. It is likely not as well-tested or mature as Valgrind/drd at this point.
Full disclosure: I'm the author of Stackusage.
A: I do not know any good tools but as last resort you could include some code in your application to check it, similar to the following:
__thread void* stack_start;
__thread long stack_max_size = 0L;
void check_stack_size() {
// address of 'nowhere' approximates end of stack
char nowhere;
void* stack_end = (void*)&nowhere;
// may want to double check stack grows downward on your platform
long stack_size = (long)stack_start - (long)stack_end;
// update max_stack_size for this thread
if (stack_size > stack_max_size)
stack_max_size = stack_size;
}
The check_stack_size() function would have to be called in some of the functions that are most deeply nested.
Then as last statement in the thread you could output stack_max_size to somewhere.
The stack_start variable would have to be initialized at start of your thread:
void thread_proc() {
char nowhere;
stack_start = (void*)&nowhere;
// do stuff including calls to check_stack_size()
// in deeply nested functions
// output stack_max_size here
}
A: Referencing Tobi's answer: You can use pthread_attr_getstackaddr to get the base of the stack at any time, if setting a variable at thread initialization is difficult. You can then get the address of an automatic variable in your own function to determine how deep the stack is at that moment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Delphi Network programming I have a classic client/server (fat client and database) program written in Delphi 2006. When certain conditions are met in the client, I need to notify all the other clients very quickly. Up until now this has been done using UDP broadcasts, but this is no longer viable as clients now connect from outside the LAN and the UDP broadcast is limited to the local network.
I'm aware of the Indy libraries but am not really sure of which components to use and how to structure it. I'm guessing I'll need to have a server that the clients connect to which will receive and distribute the messages...? Any samples out there to get me started?
Are there any other component sets or technologies I should look at instead/as well?
A: The simple answer is that the standard protocols available in Delphi (and other tools) don't allow for notification in reverse. I looked into this for a project where I wanted to use SOAP. They all assume client asks server, server responds and that's it.
For me, the solution was the RemObjects SDK. This allows you to send notifications to clients, and the notification can have any data you like (just like the client to server). Myself I use the SuperTCP connection, but it works with others too. It can still offer a SOAP interface for clients that must use it, but for where you have control of both client and server it works extremely well.
A: There are a few really easy ways to do this with Delphi, although I am sure the RemObjects SDK works really well too.
*
*Have a central server that has a * TIdTCPServer listening* on it. Then each client has a TIdTCPClient on it. They connect to the server and block on a read waiting for the server to write. Once the server receives a notification via a listening socket it broadcasts to each of the waiting clients. This is pretty much immediate notification of all the clients.
*Have a central server that has a TIdTCPServer listening on it. Then each client has a TIdTCPClient on it. Those clients can "ping" the server to ask for updates at a regular interval (use a session token to maintain state). The frequency of the interval determines how quick the notification will be. When once one of the clients needs to notify the others, it just notifies the server. The server then uses a message queue to make a list of all active client sessions and adds a notification for each. Then the next time each of the clients connects it gives it the notification and remove it from the queue.
*Maintain a session table in the database where each client updates regularly that they have an active session, and removes itself when it disconnects. You will need a maintenance process that removes dead sessions. Then you have a message queue table that a client can write an update to with one row for each current active session. Then the other clients can regularly ping that table to see if there are any pending notifications for its session, if there are it can read them, act on them and then remove them.
*Some sort of peer to peer approach were the clients are aware of each other through information in the database and then they connect directly to each other and notify or ask for notifications (depending on firewall and NAT configurations). A little more complex, but possible.
Obviously the choice of implementation will depend on your setup and needs. Tunning will be necessary to achieve the best results.
The components you need for this are the TIdTCPServer (listener) and TIdTCPClient (sender). Both of which are in the Indy libraries in Delphi.
A: ICS components from http://www.overbyte.be are great.
a.) Better compatibility than Indy
b.) PostCard ware
Good examples and support. Use TClientSocket and TServerSocket
A: FirebirdSQL project use the concept of notifications as being server-client connections that send a string to the client. For this, the db server uses an other port. And require the client to register it's interesting of receiving a certain type of notification through an API call.
You could use the same idea.
A: RabbitMQ should fit your bill. The server is free and ready to use. You just need a client side to connect, push/send out message and get/pull notified message
Server: http://www.rabbitmq.com/download.html
Do a google for client or implement yourself
Cheers
A: You should be able to use Multicast UDP for the same purpose. The only difference will be to join the multicast group from every client.
http://en.wikipedia.org/wiki/IP_Multicast
http://en.wikipedia.org/wiki/Internet_Group_Management_Protocol
Edit: Just to clarify, multicast let you join a given "group" associated to a multicast ip address. Any packet sent to that address will reach every client who has join the group
A: You can watch weonlydo wodVPN component which permit you to create a robust UDP hole punching and gain a port-forwading or a normal VPN (with a fornished network adapter) so you can connect two PC behind a NAT.
I'm using this control for our communication program and works very fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Default button size? How do I create a button control (with CreateWindow of a BUTTON 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.
Remark: Using USE_CW_DEFAULT for width and height results in a 0, 0 size button, so that's not a solution.
A: This is what MSDN has to say: Design Specifications and Guidelines - Visual Design: Layout.
The default size of a button is 50x14 DLUs, which can be calculated to pixels using the examples shown for GetDialogBaseUnits.
The MapDialogRect function seems to do the calculation for you.
A: In the perfect, hassle-free world...
To create a standard size button we would have to do this:
LONG units = GetDialogBaseUnits();
m_hButton = CreateWindow(TEXT("BUTTON"), TEXT("Close"),
WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8),
hwnd, NULL, hInst, NULL);
where 50 and 14 are respective DLU dimensions, 4 and 8 are horizontal and vertical dialog template units respectively, based on GetDialogBaseUnits() function documentation remarks.
Nothing's perfect
BUT as Anders pointed out, those metrics are based on the system font. If your window uses a shell dialog font or simply anything not making your eyes bleed, you're pretty much on your own.
To get your own "dialog" base units, you have to retrieve current text metrics with GetTextMetrics() and use character height and average width (tmHeight and tmAveCharWidth of the TEXTMETRIC struct respectively) and translate them with MulDiv by your own, unless you are in a dialog, then MapDialogRect() will do all the job for you.
Note that tmAveCharWidth only approximates the actual average character width so it's recommended to use a GetTextExtentPoint32() function on an alphabetic character set instead.
See:
*
*How to calculate dialog box units based on the current font in Visual C++
*How To Calculate Dialog Base Units with Non-System-Based Font
Simpler alternative
If buttons are the only control you want to resize automatically, you can also use BCM_GETIDEALSIZE message Button_GetIdealSize() macro (Windows XP and up only) to retrieve optimal width and height that fits anything the button contains, though it looks pretty ugly without any margins applied around the button's text.
A: @macbirdie: you should NOT use GetDialogBaseUnits(), it is based on the default system font (Ugly bitmap font). You should use MapDialogRect()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I hash a string with Delphi? How do I make an MD5 hash of a string with Delphi?
A: This is a modification of devstopfix's answer which was accepted.
In current Indy version you can hash strings and streams more easily. Example:
function MD5String(str: String): String;
begin
with TIdHashMessageDigest5.Create do
try
Result := HashStringAsHex(str);
finally
Free;
end;
end;
Use HashString, HashStringAsHex, HashBytes, HashBytesAsHex, HashStream, HashStreamAsHex. The advantage is that you can also specify a text encoding
A: Spring For Delphi project - http://www.spring4d.org - has implementation for a number of SHAxxx hashes, MD5 hash, and also number of CRC functions
A: If all you want to do is use a dictionary, and you're not looking for security then:
In Delphi 2009 and higher, hash values for strings can be created with
BobJenkinsHash(Value, Length(Value) * SizeOf(Value), 0)
where Value is a string.
http://docwiki.embarcadero.com/VCL/en/Generics.Defaults.BobJenkinsHash
A: You can also use the WindowsCrypto API with Delphi:
*
*General Crypto & Hash demo and resources
There is a unit in there that wraps all the CryptoAPI. You can also use Lockbox, which is now open source.
In the end you can support pretty much any Hash algorithms with Delphi. The Indy example is probably the closest you will get to natively in Delphi since Indy is included with most versions of Delphi. For the rest you will need to either use a library or write some more code to access the CryptoAPI or implement it yourself.
A: TurboPower Lockbox supports:
*
*MD-5,
*SHA-1 and
*the entire SHA-2 family including the recently published SHA-512/224 & SHA-512/256 hashes.
A: If you want an MD5 digest and have the Indy components installed, you can do this:
uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;
with TIdHashMessageDigest5.Create do
try
Result := TIdHash128.AsHex(HashValue('Hello, world'));
finally
Free;
end;
Most popular algorithms are supported in the Delphi Cryptography Package:
*
*Haval
*MD4, MD5
*RipeMD-128, RipeMD-160
*SHA-1, SHA-256, SHA-384, SHA-512,
*Tiger
Update
DCPCrypt is now maintained by Warren Postma and source can be found here.
A: If you want an MD5 hash string as hexadeciamal and you have Delphi XE 1 installed, so you have Indy 10.5.7 components you can do this:
uses IdGlobal, IdHash, IdHashMessageDigest;
class function getMd5HashString(value: string): string;
var
hashMessageDigest5 : TIdHashMessageDigest5;
begin
hashMessageDigest5 := nil;
try
hashMessageDigest5 := TIdHashMessageDigest5.Create;
Result := IdGlobal.IndyLowerCase ( hashMessageDigest5.HashStringAsHex ( value ) );
finally
hashMessageDigest5.Free;
end;
end;
A: Why not use the system.Hash unit from RTL, that contains also a hash algorithm for MD5 since Delphi Seattle?
MD5HashCode := THashMD5.GetHashString(ClearTextString);
A: I usually use DCPCrypt2 (Delphi Cryptography Package) from David Barton (City in the Sky).
It is also contains the following Encryption Algorithms:
*
*Blowfish
*Cast 128
*Cast 256
*DES, 3DES
*Ice, Thin Ice, Ice2
*IDEA
*Mars
*Misty1
*RC2, RC4, RC5, RC6
*Rijndael (the new AES)
*Serpent
*Tea
*Twofish
Update
DCPCrypt is now maintained by Warren Postma and source can be found here.
A: Using ICS, you simply call StrMD5 function which is located in OverbytecsMD5 unit.
Beside that specific function, there are a lot more MD5 function for other datatypes and scenarios. There are also other hash methods such as SHA.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: How to document Python code using Doxygen I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments, and also has its own self-documentation facility which seems to be the pythonic way to document.
Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?
A: The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.
A: This is documented on the doxygen website, but to summarize here:
You can use doxygen to document your Python code. You can either use the Python documentation string syntax:
"""@package docstring
Documentation for this module.
More details.
"""
def func():
"""Documentation for a function.
More details.
"""
pass
In which case the comments will be extracted by doxygen, but you won't be able to use any of the special doxygen commands.
Or you can (similar to C-style languages under doxygen) double up the comment marker (#) on the first line before the member:
## @package pyexample
# Documentation for this module.
#
# More details.
## Documentation for a function.
#
# More details.
def func():
pass
In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting OPTMIZE_OUTPUT_JAVA to YES.
Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?
A: In the end, you only have two options:
You generate your content using Doxygen, or you generate your content using Sphinx*.
*
*Doxygen: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using doxypypy.
*Sphinx: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like).
*
*For manual API documentation you have Sphinx autodoc. This is great to write a user guide with embedded API generated elements.
*For semi-automatic you have Sphinx autosummary. You can either setup your build system to call sphinx-autogen or setup your Sphinx with the autosummary_generate config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.
*Fully automatic. This have been criticized many times and for long we didn't have a good fully automatic Python API generator integrated with Sphinx until AutoAPI came, which is a new kid in the block. This is by far the best for automatic API generation in Python (note: shameless self-promotion).
There are other options to note:
*
*Breathe: this started as a very good idea, and makes sense when you work with several related project in other languages that use Doxygen. The idea is to use Doxygen XML output and feed it to Sphinx to generate your API. So, you can keep all the goodness of Doxygen and unify the documentation system in Sphinx. Awesome in theory. Now, in practice, the last time I checked the project wasn't ready for production.
*pydoctor*: Very particular. Generates its own output. It has some basic integration with Sphinx, and some nice features.
A: Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.
For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.
Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.
A: An other very good documentation tool is sphinx. It will be used for the upcoming python 2.6 documentation and is used by django and a lot of other python projects.
From the sphinx website:
*
*Output formats: HTML (including Windows HTML Help) and LaTeX, for printable PDF versions
*Extensive cross-references: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information
*Hierarchical structure: easy definition of a document tree, with automatic links to siblings, parents and children
*Automatic indices: general index as well as a module index
*Code handling: automatic highlighting using the Pygments highlighter
*Extensions: automatic testing of code snippets, inclusion of docstrings from Python modules, and more
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "103"
} |
Q: "Quoted-printable line longer than 76 chars" warning when sending HTML E-Mail I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder).
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:
MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars
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.
Can anyone point me in the right direction?
Thanks!
A: Quoted printable expands 8 bit characters to "={HEX-Code}", thus making the messages longer. Maybe you are just hitting this limit?
Have you tried to break the message at, say, 70 characters? That should provide space for a couple of characters per line.
Or you just encode the email with Base64 - all mail client can handle that.
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.
A: This is a bug in the implementation of the Quoted-Printable encoding in System.Net.Mail.MailMessage, which has been there for a long time, but is apparently now fixed, as of .Net 4 Beta 2.
http://connect.microsoft.com/VisualStudio/feedback/details/156052/mailmessage-body-encoding-quoted-printable-violates-rfcs-soft-line-breaks-requirements
One work-around is to use Base64 encoding instead (even though it would not otherwise be good practice to send a plain-text MIME part in a non-human readable encoding like this). Asking the user of the class to manually split the lines of the message before sending it is not a general solution, as the modified message is not what they wanted to send (e.g. it might include a link which is longer than 76 chars, and so cannot be split). Quoted-Printable can handle messages with lines which are longer than 76 chars before encoding, as long as it is implemented correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I keep RecipientTime when executing MailItem.Move in an Outlook macro? In an Outlook 2003 macro; Is there a way to move a message between folders without changing the ReceivedTime-header?
I currently use the method MailItem.Move. But that automatically sets the ReceivedTime property to the current time, which isn't really what I want.
A: I just tried moving a mailitem from my inbox to the deleted items folder, and it seems to have kept the receivedtime without a problem...
You may want to try using the MailItem.copy function and moving the resulting mailitem object, but like I said I'm not seeing the same problem...
Hope that helps...
A: Do an item.Save() and then do item.Move(), It will stamp current timestamp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I convert a set of polygons into a bitmap How do I take a set of polygons which contain arbitrary values and create a corresponding bitmap where each pixel contains the value of the polygon at that location?
To put the question into context, my polygons contain information about the average number of people per square kilometre within the polygon. I need to create a raster/bitmap that contains pixels representing the population in 200 metre bins.
I've done something similar in the past where I've used a polygon to create a mask by drawing into a bitmap and filling values, then converting the bitmap into an array that I can manipulate. I'm sure there's a better method for doing this!
I'm clarifying the question a bit more as requested.
*
*There are multiple polygons, each polygon is a set of vectors
*Each polygon will have a single unique value
*The polygons don't overlap
Thanks
Nick
A: What GIS software are you using? ArcGIS offers the Polygon to Raster tool in ArcGIS 9.2 or later, which is scriptable as the PolygonToRaster_conversion function.
PolygonToRaster_conversion (in_features, value_field, out_raster_dataset, cell_assignment, priority_field, cellsize)
A: This probably isn't what you need, but if you want to draw a polygon (or conversely read a polygon image's pixels on a polygon basis) then one solution is to roll your own polygon fill tool. Quite frankly, this is a ton of fun, and really neat to learn about.
But your question isn't very clear to me. Can you give a better description?
*
*Is your set of arbitrary polygons actual images, or vector (ie, list of points) points, or ???
*Does each polygon have one value, or does each polygon have an array of values you are trying to draw?
*So each polygon has an associated array of population values that you want to essentially texture the polygon with?
-Adam
A: It is a fun project. Here's what I would do, assuming the polygons are convex:
have a NY * 2 array of x positions: int x[NY][2]
foreach polygon
clear the array to -1
for each edge line
foreach horizontal raster line iy intersecting the line
generate ix, the x position where the raster intersects the line
if x[iy][0] == -1, set it to ix, else set x[iy][1] to ix
end foreach iy
end foreach edge
foreach iy
fill the pixels between x[iy][0] and x[iy][1] with the polygons label
end foreach iy
end foreach polygon
This is a little more tricky than it sounds, because you need the mental discipline to think of raster coordinates NOT as the pixels to be labeled, but as the invisible lines BETWEEN them. Otherwise, you get all confused by boundary issues.
A good test of this is if you have a polygon of zero area, like it consists of edges from point A to point B and back to A, it should light up no pixels. Another test is if you have a parallelogram that is 2 units high, and it's top and bottom edges are 2 units wide, it should light up exactly 4 pixels.
If the polygons are NOT convex, it's a little different. Wherever an edge crosses a raster line, toggle all the pixels from there to some arbitrarily chosen X coordinate, such as the left edge of the "screen". When you have completed all the edges, only the interior pixels will have been toggled an odd number of times.
A: ImageMagick can convert from svg to png, maybe you can take a look at the code, or simply create svg and use IM for the conversion? Scruffy does that.
A: @Nick R
I was originally using ArcGIS 9.2, but that doesn't work well with C# and 64 bit, so I am now using GDAL (http://www.gdal.org).
Doesn't gdal_rasterize do exactly what you want?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get the EXIF data from a file using C# I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...).
Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks!
A: Here is a link to another similar SO question, which has an answer pointing to this good article on "Reading, writing and photo metadata" in .Net.
A: Image class has PropertyItems and PropertyIdList properties. You can use them.
A: As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:
*
*System.Drawing.Image.PropertyItems Property
*System.Drawing.Imaging.PropertyItem Class
*How to: Read Image Metadata
I say "it’s the most flexible" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.
Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.
Edit: It's possible to do it without loading the full image following this answer: https://stackoverflow.com/a/552642/2097240
A: Getting EXIF data from a JPEG image involves:
*
*Seeking to the JPEG markers which mentions the beginning of the EXIF data,. e.g. normally oxFFE1 is the marker inserted while encoding EXIF data, which is a APPlication segment, where EXIF data goes.
*Parse all the data from say 0xFFE1 to 0xFFE2 . This data would be stream of bytes, in the JPEG encoded file.
*ASCII equivalent of these bytes would contain various information related to Image Date, Camera Model Name, Exposure etc...
A: The command line tool ExifTool by Phil Harvey works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.
Very easy to use, lightweight, impressive application.
A: Check out this metadata extractor. It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.
EDIT metadata-extractor supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.
It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...
var directories = ImageMetadataReader.ReadMetadata(imagePath);
// print out all metadata
foreach (var directory in directories)
foreach (var tag in directory.Tags)
Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");
// access the date time
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);
It's available via NuGet and the code's on GitHub.
A: You can use TagLib# which is used by applications such as F-Spot. Besides Exif, it will read a good amount of metadata formats for image, audio and video.
I also like ExifUtils API but it is buggy and is not actively developed.
A: Recently, I used this .NET Metadata API. I have also written a blog post about it, that shows reading, updating, and removing the EXIF data from images using C#.
using (Metadata metadata = new Metadata("image.jpg"))
{
IExif root = metadata.GetRootPackage() as IExif;
if (root != null && root.ExifPackage != null)
{
Console.WriteLine(root.ExifPackage.DateTime);
}
}
A: fastest way is to use windows api codec that doesn't open file and instead uses cached exif information
var prop = ShellFile.FromFilePath(f).Properties;
var Dimensions = prop.GetProperty("Dimensions").ValueAsObject.ToString();
//1280 x 800
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
} |
Q: Windows CDROM Eject 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.
I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.
A: Here is an easy way using the Win32 API:
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)]
protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback);
public void OpenCloseCD(bool Open)
{
if (Open)
{
mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);
}
else
{
mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);
}
}
A: I noticed that Andreas Magnusson's answer didn't quite work exactly the same as Explorer's 'Eject' button did. Specifically, the drive wasn't grayed out in Explorer using Andreas' code, but was if you used the Eject command. So I did some investigating.
I ran API Monitor while running the Eject command from Explorer (Windows 7 SP1 64-bit). I also found a good (now-defunct) MSKB article 165721 titled How To Ejecting Removable Media in Windows NT/Windows 2000/Windows XP. The most interesting part of the article is quoted below:
*
*Call CreateFile with GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, and OPEN_EXISTING. The lpFileName parameter should be \\.\X: (where X is the real drive letter). All other parameters can be zero.
*Lock the volume by issuing the FSCTL_LOCK_VOLUME IOCTL via DeviceIoControl. If any other application or the system is using the volume, this IOCTL fails. Once this function returns successfully, the application is guaranteed that the volume is not used by anything else in the system.
*Dismount the volume by issuing the FSCTL_DISMOUNT_VOLUME IOCTL. This causes the file system to remove all knowledge of the volume and to discard any internal information that it keeps regarding the volume.
*Make sure the media can be removed by issuing the IOCTL_STORAGE_MEDIA_REMOVAL IOCTL. Set the PreventMediaRemoval member of the PREVENT_MEDIA_REMOVAL structure to FALSE before calling this IOCTL. This stops the device from preventing the removal of the media.
*Eject the media with the IOCTL_STORAGE_EJECT_MEDIA IOCTL. If the device doesn't allow automatic ejection, then IOCTL_STORAGE_EJECT_MEDIA can be skipped and the user can be instructed to remove the media.
*Close the volume handle obtained in the first step or issue the FSCTL_UNLOCK_VOLUME IOCTL. This allows the drive to be used by other
processes.
Andreas's answer, the MSKB article, and my API sniffing of Explorer can be summarized as follows:
*
*CreateFile called to open the volume. (All methods).
*DeviceIoControl called with FSCTL_LOCK_VOLUME. (All methods).
*DeviceIoControl called with FSCTL_DISMOUNT_VOLUME. (Andreas's and MSKB methods only. Explorer does not call this for some reason. This IOCTL seems to be what affects whether the drive is grayed out in Explorer or not. I am not sure why Explorer doesn't call this).
*DeviceIoControl called with IOCTL_STORAGE_MEDIA_REMOVAL and PREVENT_MEDIA_REMOVAL member set to FALSE (MSKB and Explorer methods. This step is missing from Andreas's answer).
*DeviceIoControl called with IOCTL_STORAGE_EJECT_MEDIA (Andreas and MSKB article) or IOCTL_DISK_EJECT_MEDIA (Explorer; note this IOCTL was obsoleted and replaced with the STORAGE IOCTL. Not sure why Explorer still uses the old one).
To conclude, I decided to follow the procedure outlined in the MSKB article, as it seemed to be the most thorough and complete procedure, backed up with an MSKB article.
A: Nircmd is a very handy freeware command line utility with various options, including opening and closing the CD tray.
A: 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):
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;
}
A: To close the drive tray do as described here but instead of using DeviceIoControl with IOCTL_STORAGE_EJECT_MEDIA you need to call DeviceIoControl with IOCTL_STORAGE_LOAD_MEDIA.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Example of modern text editor architecutre I'm looking for design\architectual guidance for modern text editors.
Modern text editor means that:
*
*It has support for syntax highlighting
*It has auto-completion (something like IntelliSense)
*It has advanced navigation capabilities (incremental search, etc.)
Following properties will be a plus:
*
*Implemented in managed language (Java, any .NET language)
*Modular architecutre
*Add-in support
I'm very interested in text editor related design\architecure documents\articles, links to open source projects.
I'm not interested in general recommendations, OOP/design patterns books advertisement.
Currently I'm analyzing SharpDevelop code editor source code. Links to similar projects will be appreciated.
A: The ultimate text editor is, of course, emacs. I found The Craft of Text Editing, or, Emacs for the Modern World to be an excellent self-study guide for the basics of writing an editor. The examples are all in plain old C, and the text might look a bit dated (it is from 1991), but the basic ideas are still valid, and you thoroughly understand why the editor works the way it does.
A: The editor of SharpDevelop is good and it's open source too.
A: The Java-based editor "jEdit", is a good example of text editor architecture, complete with plugin support, a strong user community, and good abstractions.
A: You could also look at the source code for Scintilla.
A: You can check out xacc.ide
A: It's probably not what you're looking for, it's based on Mozilla, but for completeness sake:
Open Komodo is an initiative by ActiveState to create an open source platform for building developer environments.
A: Have you looked at vim? It supports autocompletion, syntax highlighting, incremental search, integrated building, etc, etc. It is modular and many of its more advanced features are implemented as plugins that either ship with it or can be found separately (e.g., svn integration, code indexing with cscope/ctags, transparent reading/writing over ssh).
It has apis for writing plugins in several langauges (e.g., python, ruby, perl) as well as its own extension language ('vimscript').
I don't know what they have in terms of high-level architecture documentation, but there is an active community and a developer mailing list that should be able to answer specific questions about how it works if you start digging through the source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Visual Studio 2008 complains about trusted locations. What to do? I was messing around with RhinoMocks this morning and couldn't run my tests because RhinoMocks.dll was not in a "trusted location". The assembly is in my c:\documents and settings\\My Documents\Visual Studio 2008\Projects (and so on) folder. What's the deal?
A: Did you download a zip file from the internet and then extract it using the standard explorer tools. I think this marks the directory as untrusted and Visual studio detects this.
A: From my reading, there are a number of things that can cause this. The fix for my particular situation, however, was to "unblock" the DLL file. Because I had downloaded the zip from the Internet, XP had put a block on the file. Right-clicking the file and clicking "Unblock" did the trick.
A: Right click the file or location and choose Properties. At the very bottom, you should see the button "Unblock". Click it and press OK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.