text
stringlengths
8
267k
meta
dict
Q: Mod-Rewrite loading files behind the DocumentRoot I'm using .htaccess and mod_rewrite to point to files that reside behind the DocumentRoot. My folder structure looks like this: home/ webroot/ other_files/ I have a .htaccess file in webroot with the following content: RewriteEngine on RewriteRule ^(.*)$ /home/other_files/$1 If I try to access http://example.com/file.html I receive the following error: The requested URL /home/other_files/file.html was not found on this server. Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction? A: I believe you need to add a section with <Directory "/home/other_files"> (options) </Directory> to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site: Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> You could then rewrite a URL to go to /doc/ and the server would know where to get the files from. A: Just so you know why that rule doesn't work: The reason that it isn't able to rewrite to /home/other_files/file.html is that mod_rewrite is parsing the path as /home/webroot/home/other_files/file.html since from mod_rewrite's point of view the preceding slash is equivalent to your document root of /home/webroot. Ryan Ahearn's suggestion is a decent one, and is likely the route you want to go. A: The credit goes to Ryan Aheam, but I'm going to spell it out. I'm a beginner and even with Ryan's answer I had to experiment with a few things to get the syntax right. I wanted my DocumentRoot to be my cakephp directory. But then I had a Mantis Bug tracker that was just regular PHP and so not in the cakephp directory. The the files below I have the following working. http://www.example.com : served by /var/www/cakephp http://www.example.com/mantisbt : served by /var/www/html/mantisbt File /etc/httpd/conf/httpd.conf Alias /mantisbt/ "/var/www/html/mantisbt/" <Directory "/var/www/html/"> AllowOverride All </Directory> <VirtualHost *:80> ServerAdmin me@my_email.com DocumentRoot /var/www/cakephp ServerName my_website.com <Directory /var/www/cakephp/> AllowOverride All </Directory> </VirtualHost> File /var/www/cakephp/.htaccess <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^mantisbt/?$ /mantisbt/ [NC,L] RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L] </IfModule>
{ "language": "en", "url": "https://stackoverflow.com/questions/8441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: MSVC6: Breakpoint stops program Using Microsoft Visual Studio 98, Microsoft Visual C++ 6.0 SP6 When running under the debugger, there's only one problem. If I pause the program and resume, everything's fine. The problem? When I hit a breakpoint, my program stops. But not in a good way; execution halts, I'm thrown out of debug mode into edit mode. All's fine until a breakpoint is hit. And I know it's hitting the breakpoint - I see a flash of the little yellow arrow pointing at the right line of code, local variables in the inspect window and the call stack in that window. And then I'm staring at the editor. This happens in all projects. I've uninstalled and re-installed MSVC6. It didn't help. I'm about to start over on a new PC; before I go that far, anyone know what I've done to this one? Note: MSVC6 is not my choice, but there are reasons. It's the tool I work with. And, we get to target NT4, so given 2008 can't target NT4 and 2005 has issues with MFC and NT4, MSVC6 it is. A: Stop beating on VC6. It's old. The STL was updated in 1996 from HP code written in 1994. C++ was ratified in 1998. What is the code doing when you are breaking? Can you reduce the situation into a simple test. When I try that I usually find the cause. If you can do that so it still happens then I'll take a look at it for you. I too am unfortunate enough to use VC6 for my day to day work. Visual C++ Express 2008 can't be used in certain situations. A: The first thing I would check is if this project does the same thing on other machines. If not, it could be your box is heading south. If not it's the VC6 project itself. Typically I get goofiness with the debugger when my program is doing something with the hardware, especially the video. I would recommend turning off parts of your program until you figure out what part is causing this. If your program is small and not doing much it might be that the project is corrupted and needs to get rebuilt. Make a new project from scratch and put your files and settings back in by hand. A: Is it specific to the app you're working on or do all breakpoints in any app break the debugger? Is anything different if you attach the debugger manually after launching the app normally? A: Is the device running out of memory and therefore gives up the ghost when it requires the additional memory to stop at the breakpoint? A: Is the device running out of memory and therefore gives up the ghost when it requires the additional memory to stop at the breakpoint? No, there's over a gig of RAM to go, and even more of virtual memory. A: I haven't used MSVC6 in years, but I remember the debugger basically being a flaky piece of crap. Things like this would regularly happen for no apparent reason because it just didn't like your code that day. In addition to the debugger being a flaky piece of crap, the rest of it was too. It's STL implementation isn't threadsafe, it doesn't support very much of the C++ standard, and the IDE is sorely lacking in niceties. I'm pretty sure you also just simply can't use any versions of the Platform SDK from the last 5 years because it's too old to grok them. Not a good thing. You'd be mad to keep using it when there is Visual C++ Express 2008 which you can download for free.
{ "language": "en", "url": "https://stackoverflow.com/questions/8443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What does the [Flags] Enum Attribute mean in C#? From time to time I see an enum like the following: [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 } I don't understand what exactly the [Flags] attribute does. Anyone have a good explanation or example they could post? A: You can also do this [Flags] public enum MyEnum { None = 0, First = 1 << 0, Second = 1 << 1, Third = 1 << 2, Fourth = 1 << 3 } I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time A: In extension to the accepted answer, in C#7 the enum flags can be written using binary literals: [Flags] public enum MyColors { None = 0b0000, Yellow = 0b0001, Green = 0b0010, Red = 0b0100, Blue = 0b1000 } I think this representation makes it clear how the flags work under the covers. A: Please see the following for an example which shows the declaration and potential usage: namespace Flags { class Program { [Flags] public enum MyFlags : short { Foo = 0x1, Bar = 0x2, Baz = 0x4 } static void Main(string[] args) { MyFlags fooBar = MyFlags.Foo | MyFlags.Bar; if ((fooBar & MyFlags.Foo) == MyFlags.Foo) { Console.WriteLine("Item has Foo flag set"); } } } } A: I asked recently about something similar. If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail) This allows you to do: [Flags] public enum PossibleOptions : byte { None = 0, OptionOne = 1, OptionTwo = 2, OptionThree = 4, OptionFour = 8, //combinations can be in the enum too OptionOneAndTwo = OptionOne | OptionTwo, OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree, ... } Then you can do: PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree if( opt.IsSet( PossibleOptions.OptionOne ) ) { //optionOne is one of those set } I find this easier to read than the most ways of checking the included flags. A: When working with flags I often declare additional None and All items. These are helpful to check whether all flags are set or no flag is set. [Flags] enum SuitsFlags { None = 0, Spades = 1 << 0, Clubs = 1 << 1, Diamonds = 1 << 2, Hearts = 1 << 3, All = ~(~0 << 4) } Usage: Spades | Clubs | Diamonds | Hearts == All // true Spades & Clubs == None // true   Update 2019-10: Since C# 7.0 you can use binary literals, which are probably more intuitive to read: [Flags] enum SuitsFlags { None = 0b0000, Spades = 0b0001, Clubs = 0b0010, Diamonds = 0b0100, Hearts = 0b1000, All = 0b1111 } A: Define the Problem Let’s define an enum that represents the types of users: public enum UserType { Customer = 1, Driver = 2, Admin = 3, } We define the UserType enum that contains three values: Customer, Driver, and Admin. But what if we need to represent a collection of values? For example, at a delivery company, we know that both the Admin and the Driver are employees. So let’s add a new enumeration item Employee. Later on, we will show you how we can represent both the admin and the driver with it: public enum UserType { Customer = 1, Driver = 2, Admin = 3, Employee = 4 } Define and Declare a Flags Attribute A Flags is an attribute that allows us to represent an enum as a collection of values ​​rather than a single value. So, let’s see how we can implement the Flags attribute on enumeration: [Flags] public enum UserType { Customer = 1, Driver = 2, Admin = 4, } We add the Flags attribute and number the values with powers of 2. Without both, this won’t work. Now going back to our previous problem, we can represent Employee using the | operator: var employee = UserType.Driver | UserType.Admin; Also, we can define it as a constant inside the enum to use it directly: [Flags] public enum UserType { Customer = 1, Driver = 2, Admin = 4, Employee = Driver | Admin } Behind the Scenes To understand the Flags attribute better, we must go back to the binary representation of the number. For example, we can represent 1 as binary 0b_0001 and 2 as 0b_0010: [Flags] public enum UserType { Customer = 0b_0001, Driver = 0b_0010, Admin = 0b_0100, Employee = Driver | Admin, //0b_0110 } We can see that each value is represented in an active bit. And this is where the idea of ​​numbering the values ​​with the power of 2 came from. We can also note that Employee contains two active bits, that is, it is a composite of two values Driver and Admin. Operations on Flags Attribute We can use the bitwise operators to work with Flags. Initialize a Value For the initialization, we should use the value 0 named None, which means the collection is empty: [Flags] public enum UserType { None = 0, Customer = 1, Driver = 2, Admin = 4, Employee = Driver | Admin } Now, we can define a variable: var flags = UserType.None; Add a Value We can add value by using | operator: flags |= UserType.Driver; Now, the flags variable equals Driver. Remove a Value We can remove value by use &, ~ operators: flags &= ~UserType.Driver; Now, flagsvariable equals None. We can check if the value exists by using & operator: Console.WriteLine((flags & UserType.Driver) == UserType.Driver); The result is False. Also, we can do this by using the HasFlag method: Console.WriteLine(flags.HasFlag(UserType.Driver)); Also, the result will be False. As we can see, both ways, using the & operator and the HasFlag method, give the same result, but which one should we use? To find out, we will test the performance on several frameworks. Measure the Performance First, we will create a Console App, and in the .csproj file we will replace the TargetFramwork tag with the TargetFramworks tag: <TargetFrameworks>net48;netcoreapp3.1;net6.0</TargetFrameworks> We use the TargetFramworks tag to support multiple frameworks: .NET Framework 4.8, .Net Core 3.1, and .Net 6.0. Secondly, let’s introduce the BenchmarkDotNet library to get the benchmark results: [Benchmark] public bool HasFlag() { var result = false; for (int i = 0; i < 100000; i++) { result = UserType.Employee.HasFlag(UserType.Driver); } return result; } [Benchmark] public bool BitOperator() { var result = false; for (int i = 0; i < 100000; i++) { result = (UserType.Employee & UserType.Driver) == UserType.Driver; } return result; } We add [SimpleJob(RuntimeMoniker.Net48)], [SimpleJob(RuntimeMoniker.NetCoreApp31)], and [SimpleJob(RuntimeMoniker.Net60)] attributes to the HasFlagBenchmarker class to see the performance differences between different versions of .NET Framework / .NET Core: Method Job Runtime Mean Error StdDev Median HasFlag .NET 6.0 .NET 6.0 37.79 us 3.781 us 11.15 us 30.30 us BitOperator .NET 6.0 .NET 6.0 38.17 us 3.853 us 11.36 us 30.38 us HasFlag .NET Core 3.1 .NET Core 3.1 38.31 us 3.939 us 11.61 us 30.37 us BitOperator .NET Core 3.1 .NET Core 3.1 38.07 us 3.819 us 11.26 us 30.33 us HasFlag .NET Framework 4.8 .NET Framework 4.8 2,893.10 us 342.563 us 1,010.06 us 2,318.93 us BitOperator .NET Framework 4.8 .NET Framework 4.8 38.04 us 3.920 us 11.56 us 30.17 us So, in .NET Framework 4.8 a HasFlag method was much slower than the BitOperator. But, the performance improves in .Net Core 3.1 and .Net 6.0. So in newer versions, we can use both ways. A: @Nidonocu To add another flag to an existing set of values, use the OR assignment operator. Mode = Mode.Read; //Add Mode.Write Mode |= Mode.Write; Assert.True(((Mode & Mode.Write) == Mode.Write) && ((Mode & Mode.Read) == Mode.Read))); A: The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example: var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue; Note that the [Flags] attribute doesn't enable this by itself - all it does is allow a nice representation by the .ToString() method: enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } ... var str1 = (Suits.Spades | Suits.Diamonds).ToString(); // "5" var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString(); // "Spades, Diamonds" It is also important to note that [Flags] does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. Incorrect declaration: [Flags] public enum MyColors { Yellow, // 0 Green, // 1 Red, // 2 Blue // 3 } The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags. Here's an example of a correct declaration: [Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 } To retrieve the distinct values in your property, one can do this: if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // Yellow is allowed... } or prior to .NET 4: if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // Yellow is allowed... } if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green) { // Green is allowed... } Under the covers This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros: Yellow: 00000001 Green: 00000010 Red: 00000100 Blue: 00001000 Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR | operator, AllowedColors looks like this: myProperties.AllowedColors: 00001110 So when you retrieve the value you are actually performing bitwise AND & on the values: myProperties.AllowedColors: 00001110 MyColor.Green: 00000010 ----------------------- 00000010 // Hey, this is the same as MyColor.Green! The None = 0 value And regarding the use of 0 in your enumeration, quoting from MSDN: [Flags] public enum MyColors { None = 0, .... } Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. You can find more info about the flags attribute and its usage at msdn and designing flags at msdn A: To add Mode.Write: Mode = Mode | Mode.Write; A: Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining which ones are specified. [Flags] public enum DashboardItemPresentationProperties : long { None = 0, HideCollapse = 1, HideDelete = 2, HideEdit = 4, HideOpenInNewWindow = 8, HideResetSource = 16, HideMenu = 32 } A: There's something overly verbose to me about the if ((x & y) == y)... construct, especially if x AND y are both compound sets of flags and you only want to know if there's any overlap. In this case, all you really need to know is if there's a non-zero value[1] after you've bitmasked. [1] See Jaime's comment. If we were authentically bitmasking, we'd only need to check that the result was positive. But since enums can be negative, even, strangely, when combined with the [Flags] attribute, it's defensive to code for != 0 rather than > 0. Building off of @andnil's setup... using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BitFlagPlay { class Program { [Flags] public enum MyColor { Yellow = 0x01, Green = 0x02, Red = 0x04, Blue = 0x08 } static void Main(string[] args) { var myColor = MyColor.Yellow | MyColor.Blue; var acceptableColors = MyColor.Yellow | MyColor.Red; Console.WriteLine((myColor & MyColor.Blue) != 0); // True Console.WriteLine((myColor & MyColor.Red) != 0); // False Console.WriteLine((myColor & acceptableColors) != 0); // True // ... though only Yellow is shared. Console.WriteLine((myColor & MyColor.Green) != 0); // Wait a minute... ;^D Console.Read(); } } } A: Combining answers https://stackoverflow.com/a/8462/1037948 (declaration via bit-shifting) and https://stackoverflow.com/a/9117/1037948 (using combinations in declaration) you can bit-shift previous values rather than using numbers. Not necessarily recommending it, but just pointing out you can. Rather than: [Flags] public enum Options : byte { None = 0, One = 1 << 0, // 1 Two = 1 << 1, // 2 Three = 1 << 2, // 4 Four = 1 << 3, // 8 // combinations OneAndTwo = One | Two, OneTwoAndThree = One | Two | Three, } You can declare [Flags] public enum Options : byte { None = 0, One = 1 << 0, // 1 // now that value 1 is available, start shifting from there Two = One << 1, // 2 Three = Two << 1, // 4 Four = Three << 1, // 8 // same combinations OneAndTwo = One | Two, OneTwoAndThree = One | Two | Three, } Confirming with LinqPad: foreach(var e in Enum.GetValues(typeof(Options))) { string.Format("{0} = {1}", e.ToString(), (byte)e).Dump(); } Results in: None = 0 One = 1 Two = 2 OneAndTwo = 3 Three = 4 OneTwoAndThree = 7 Four = 8 A: Apologies if someone already noticed this scenario. A perfect example of flags we can see in reflection. Yes Binding Flags ENUM. [System.Flags] [System.Runtime.InteropServices.ComVisible(true)] [System.Serializable] public enum BindingFlags Usage // BindingFlags.InvokeMethod // Call a static method. Type t = typeof (TestClass); Console.WriteLine(); Console.WriteLine("Invoking a static method."); Console.WriteLine("-------------------------"); t.InvokeMember ("SayHello", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object [] {}); A: * *Flags are used when an enumerable value represents a collection of enum members. *here we use bitwise operators, | and & *Example [Flags] public enum Sides { Left=0, Right=1, Top=2, Bottom=3 } Sides leftRight = Sides.Left | Sides.Right; Console.WriteLine (leftRight);//Left, Right string stringValue = leftRight.ToString(); Console.WriteLine (stringValue);//Left, Right Sides s = Sides.Left; s |= Sides.Right; Console.WriteLine (s);//Left, Right s ^= Sides.Right; // Toggles Sides.Right Console.WriteLine (s); //Left
{ "language": "en", "url": "https://stackoverflow.com/questions/8447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1701" }
Q: F# curried function Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept? A: It's a fairly simple process. Take a function, bind one of its arguments and return a new function. For example: let concatStrings left right = left + right let makeCommandPrompt= appendString "c:\> " Now by currying the simple concatStrings function, you can easily add a DOS style command prompt to the front of any string! Really useful! Okay, not really. A more useful case I find is when I want to have a make a function that returns me data in a stream like manner. let readDWORD array i = array[i] | array[i + 1] << 8 | array[i + 2] << 16 | array[i + 3] << 24 //I've actually used this function in Python. The convenient part about it is that rather than creating an entire class for this sort of thing, calling the constructor, calling obj.readDWORD(), you just have a function that can't be mutated out from under you. A: You know you can map a function over a list? For example, mapping a function to add one to each element of a list: > List.map ((+) 1) [1; 2; 3];; val it : int list = [2; 3; 4] This is actually already using currying because the (+) operator was used to create a function to add one to its argument but you can squeeze a little more out of this example by altering it to map the same function of a list of lists: > List.map (List.map ((+) 1)) [[1; 2]; [3]];; val it : int list = [[2; 3]; [4]] Without currying you could not partially apply these functions and would have to write something like this instead: > List.map((fun xs -> List.map((fun n -> n + 1), xs)), [[1; 2]; [3]]);; val it : int list = [[2; 3]; [4]] A: (Edit: a small Ocaml FP Koan to start things off) The Koan of Currying (A koan about food, that is not about food) A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine. My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations. We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing another function (assuming this function is being used in other instances with other variables) would be a waste. type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree let rec tree_map f tree = match tree with | N(x,left,right) -> N(f x, tree_map f left, tree_map f right) | E(x) -> E(f x) let sample_tree = N(1,E(3),E(4) let multiply x y = x * y let sample_tree2 = tree_map (multiply 3) sample_tree but this is the same as: let sample_tree2 = tree_map (fun x -> x * 3) sample_tree So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A recurrence relation to create prime numbers. Awful lot of similarity in there: let rec f_recurrence f a seed n = match n with | a -> seed | _ -> let prev = f_recurrence f a seed (n-1) in prev + (f n prev) let rowland = f_recurrence gcd 1 7 let cloitre = f_recurrence lcm 1 1 let rowland_prime n = (rowland (n+1)) - (rowland n) let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1 Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f_recurrence. A: While the previous examples answered the question, here are two simpler examples of how Currying can be beneficial for F# programming. open System.IO let appendFile (fileName : string) (text : string) = let file = new StreamWriter(fileName, true) file.WriteLine(text) file.Close() // Call it normally appendFile @"D:\Log.txt" "Processing Event X..." // If you curry the function, you don't need to keep specifying the // log file name. let curriedAppendFile = appendFile @"D:\Log.txt" // Adds data to "Log.txt" curriedAppendFile "Processing Event Y..." And don't forget you can curry the Printf family of function! In the curried version, notice the distinct lack of a lambda. // Non curried, Prints 1 2 3 List.iter (fun i -> printf "%d " i) [1 .. 3];; // Curried, Prints 1 2 3 List.iter (printfn "%d ") [1 .. 3];; A: Currying describes the process of transforming a function with multiple arguments into a chain of single-argument functions. Example in C#, for a three-argument function: Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f) { return a => b => c => f(a, b, c); } void UseACurriedFunction() { var curryCompare = Curry<string, string, bool, int>(String.Compare); var a = "SomeString"; var b = "SOMESTRING"; Console.WriteLine(String.Compare(a, b, true)); Console.WriteLine(curryCompare(a)(b)(true)); //partial application var compareAWithB = curryCompare(a)(b); Console.WriteLine(compareAWithB(true)); Console.WriteLine(compareAWithB(false)); } Now, the boolean argument is probably not the argument you'd most likely want to leave open with a partial application. This is one reason why the order of arguments in F# functions can seem a little odd at first. Let's define a different C# curry function: Func<T3, Func<T2, Func<T1, T4>>> BackwardsCurry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f) { return a => b => c => f(c, b, a); } Now, we can do something a little more useful: void UseADifferentlyCurriedFunction() { var curryCompare = BackwardsCurry<string, string, bool, int>(String.Compare); var caseSensitiveCompare = curryCompare(false); var caseInsensitiveCompare = curryCompare(true); var format = Curry<string, string, string, string>(String.Format)("Results of comparing {0} with {1}:"); var strings = new[] {"Hello", "HELLO", "Greetings", "GREETINGS"}; foreach (var s in strings) { var caseSensitiveCompareWithS = caseSensitiveCompare(s); var caseInsensitiveCompareWithS = caseInsensitiveCompare(s); var formatWithS = format(s); foreach (var t in strings) { Console.WriteLine(formatWithS(t)); Console.WriteLine(caseSensitiveCompareWithS(t)); Console.WriteLine(caseInsensitiveCompareWithS(t)); } } } Why are these examples in C#? Because in F#, function declarations are curried by default. You don't usually need to curry functions; they're already curried. The major exception to this is framework methods and other overloaded functions, which take a tuple containing their multiple arguments. You therefore might want to curry such functions, and, in fact, I came upon this question when I was looking for a library function that would do this. I suppose it is missing (if indeed it is) because it's pretty trivial to implement: let curry f a b c = f(a, b, c) //overload resolution failure: there are two overloads with three arguments. //let curryCompare = curry String.Compare //This one might be more useful; it works because there's only one 3-argument overload let backCurry f a b c = f(c, b, a) let intParse = backCurry Int32.Parse let intParseCurrentCultureAnyStyle = intParse CultureInfo.CurrentCulture NumberStyles.Any let myInt = intParseCurrentCultureAnyStyle "23" let myOtherInt = intParseCurrentCultureAnyStyle "42" To get around the failure with String.Compare, since as far as I can tell there's no way to specify which 3-argument overload to pick, you can use a non-general solution: let curryCompare s1 s2 (b:bool) = String.Compare(s1, s2, b) let backwardsCurryCompare (b:bool) s1 s2 = String.Compare(s1, s2, b) I won't go into detail about the uses of partial function application in F# because the other answers have covered that already. A: I gave a good example of simulating currying in C# on my blog. The gist is that you can create a function that is closed over a parameter (in my example create a function for calculating the sales tax closed over the value of a given municipality)out of an existing multi-parameter function. What is appealing here is instead of having to make a separate function specifically for calculating sales tax in Cook County, you can create (and reuse) the function dynamically at runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/8448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Secure Memory Allocator in C++ I want to create an allocator which provides memory with the following attributes: * *cannot be paged to disk. *is incredibly hard to access through an attached debugger The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem. Updates Josh mentions using VirtualAlloc to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the VirtualLock function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem. // template<class _Ty> class LockedVirtualMemAllocator : public std::allocator<_Ty> { public: template<class _Other> LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&) { // assign from a related LockedVirtualMemAllocator (do nothing) return (*this); } template<class Other> struct rebind { typedef LockedVirtualMemAllocator<Other> other; }; pointer allocate( size_type _n ) { SIZE_T allocLen = (_n * sizeof(_Ty)); DWORD allocType = MEM_COMMIT; DWORD allocProtect = PAGE_READWRITE; LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect ); if ( pMem != NULL ) { ::VirtualLock( pMem, allocLen ); } return reinterpret_cast<pointer>( pMem ); } pointer allocate( size_type _n, const void* ) { return allocate( _n ); } void deallocate(void* _pPtr, size_type _n ) { if ( _pPtr != NULL ) { SIZE_T allocLen = (_n * sizeof(_Ty)); ::SecureZeroMemory( _pPtr, allocLen ); ::VirtualUnlock( _pPtr, allocLen ); ::VirtualFree( _pPtr, 0, MEM_RELEASE ); } } }; and is used //a memory safe std::string typedef std::basic_string<char, std::char_traits<char>, LockedVirtualMemAllocato<char> > modulestring_t; Ted Percival mentions mlock, but I have no implementation of that yet. I found Practical Cryptography by Neil Furguson and Bruce Schneier quite helpful as well. A: On Unix systems you can use mlock(2) to lock memory pages into RAM, preventing them being paged. mlock() and mlockall() respectively lock part or all of the calling process’s virtual address space into RAM, preventing that memory from being paged to the swap area. There is a limit to how much memory each process can lock, it can be shown with ulimit -l and is measured in kilobytes. On my system, the default limit is 32 kiB per process. A: Let's take this a bit at a time: I want to create an allocator which provides memory with the following attributes: That's fair enough. * cannot be paged to disk. That's going to be hard. As far as I am aware, you cannot disable Virtual Paging as it is handled by the OS. If there is a way, then you'll be spelunking in the bowels of the OS. * is incredibly hard to access through an attached debugger You could run it through PGP and store it encrypted in memory and unencrypt it as needed. Massive performance hit. The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem. Keep all sensitive information off the machine. Seriously. Don't store sensitive information in memory. Write a custom delete routine that will automatically remove all data from any allocations you perform. Never allow general access to a machine with sensitive material on it. If you perform db access, make sure all access is sanitized before firing. Only people with specific log-ins are allowed to access. No general group access. On a side note, what other methods are there of accessing the memory of a process other than attaching a debugger? Taking a dump of the memory. A: If you're developing for Windows, there are ways you can restrict access to memory, but absolutely blocking out others is not doable. If you're hoping to keep a secret secret, read Writing Secure Code - which addresses this problem at some length, but be aware that you have no way of knowing if your code is running on a real machine or a virtual machine. There's a bunch of Win32 API stuff to deal with crypto that handles this kind of thing, including safe storage of secrets - the book talks about that. You can look at the online Microsoft CyproAPI for details; the OS designers recognise this very problem and the need to keep the cleartext secure (again, read Writing Secure Code). The Win32 API function VirtualAlloc is the OS level memory allocator. It allows you to set access protection; what you could do is set access to PAGE_GUARD or PAGE_NOACCESS, and flip the access to something friendlier while your program reads, and reset it afterward, but that's merely a speed hump if someone is trying really hard to peek at your secret. In summary, look at the crypto APIs on your platform, they'll address the problem better than something you hack up yourself. A: install Libsodium, use allocation mechanisms by #including <sodium.h> Guarded heap allocations Slower than malloc() and friends, they require 3 or 4 extra pages of virtual memory. void *sodium_malloc(size_t size); Allocate memory to store sensitive data using sodium_malloc() and sodium_allocarray(). You'll need to first call sodium_init() before using these heap guards. void *sodium_allocarray(size_t count, size_t size); The sodium_allocarray() function returns a pointer from which count objects that are size bytes of memory each can be accessed. It provides the same guarantees as sodium_malloc() but also protects against arithmetic overflows when count * size exceeds SIZE_MAX. These functions add guard pages around the protected data to make it less likely to be accessible in a heartbleed-like scenario. In addition, the protection for memory regions allocated that way can be changed using the locking memory operations: sodium_mprotect_noaccess(), sodium_mprotect_readonly() and sodium_mprotect_readwrite(). After sodium_malloc you can use sodium_free() to unlock and deallocate memory. At this point in your implementation consider zeroing the memory after use. zero the memory after use void sodium_memzero(void * const pnt, const size_t len); After use, sensitive data should be overwritten, but memset() and hand-written code can be silently stripped out by an optimizing compiler or by the linker. The sodium_memzero() function tries to effectively zero len bytes starting at pnt, even if optimizations are being applied to the code. locking the memory allocation int sodium_mlock(void * const addr, const size_t len); The sodium_mlock() function locks at least len bytes of memory starting at addr. This can help avoid swapping sensitive data to disk. int sodium_mprotect_noaccess(void *ptr); The sodium_mprotect_noaccess() function makes a region allocated using sodium_malloc() or sodium_allocarray() inaccessible. It cannot be read or written, but the data are preserved. This function can be used to make confidential data inaccessible except when actually needed for a specific operation. int sodium_mprotect_readonly(void *ptr); The sodium_mprotect_readonly() function marks a region allocated using sodium_malloc() or sodium_allocarray() as read-only. Attempting to modify the data will cause the process to terminate. int sodium_mprotect_readwrite(void *ptr); The sodium_mprotect_readwrite() function marks a region allocated using sodium_malloc() or sodium_allocarray() as readable and writable, after having been protected using sodium_mprotect_readonly() or sodium_mprotect_noaccess(). A: What you are asking for is handled at the OS level. Once the data is in your program, it is liable to be paged out. For accessing the memory, a motivated individual can attach a hardware debugger. A: You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way. Even if you could somehow completely lock down your process and guarantee that the OS would never allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time. You cannot protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. A: @graham You could run it through PGP and store it encrypted in memory and unencrypt it as needed. Massive performance hit. Then you'd have to hold the key in memory. That would make it a little harder, but definitely not impossible. Anyone motivated will still manage to get the data from memory. A: You cannot protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. Have you had a look at Vista (and above) Protected Processes (direct .doc download). I believe the operating system-enforced protection is courtesy of the entertainment industry. A: Your best bet is to implement something similar to .NET's SecureString class, and be very careful to zero out any plaintext copies of your data as soon as you are done (don't forget to cleanup even when exceptions are thrown). A good way to do this with std::string and such is to use a custom allocator. On Windows, if you use CryptProtectMemory (or RtlEncryptMemory for older systems), the encryption password is stored in non-pageable (kernel?) memory. In my testing, these functions are pretty darn fast, esp. taking into account the protection they are giving you. On other systems, I like to use Blowfish since it's a good mix between speed and strength. In the latter case, you will have to randomly generate your own password (16+ bytes of entropy for Blowfish) at program startup. Unfortunately, there's not a whole lot you can do to protect that password without OS support, although you might use general obfuscation techniques to embed a hard-coded salt value into your executable that you can combine with the password (every little bit helps). Overall, this strategy is only one part of a broader defense-in-depth approach. Also keep in mind that simple bugs such as buffer overflows and not sanitizing program input remain by far the most common attack vectors. A: @Derek: Oh, but with trusted computing, you can use memory curtaining! :-P</devils-advocate> A: @roo I was really hoping that is was possible, and that I just hadn't found it yet. Your example just made me realise that that is exactly what we are trying to do - only allow access to files in the context of our program and so preserve the IP. I guess I have to accept that there is no truly secure way to store someone’s files on another computer, especially if at some point access is allowed to that file by the owner. That's definitely the problem. You can store something securely so long as you never grant access, but as soon as you grant access, your control is gone. You can make it a little bit more difficult, but that's all. A: @Chris Oh, but with trusted computing, you can use memory curtaining! :-P But then you have to actually be willing to pay for a computer someone else owns. :p A: @Derek Park He only said harder, not impossible. PGP would make it harder, not impossible.
{ "language": "en", "url": "https://stackoverflow.com/questions/8451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Custom WPF command pattern example I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? A: I blogged about a bunch of resources on WPF Commands along with an example last year at http://blogs.vertigo.com/personal/alanl/Blog/archive/2007/05/31/commands-in-wpf.aspx Pasting here: Adam Nathan’s sample chapter on Important New Concepts in WPF: Commands MSDN article: The Command Pattern In WPF Keyvan Nayyeri: How to Add Commands to Custom WPF Control Ian Griffiths: Avalon Input, Commands, and Handlers Wikipedia: Command Pattern MSDN Library: Commanding Overview MSDN Library: CommandBinding Class MSDN Library: Input and Commands How-to Topics MSDN Library: EditingCommands Class MSDN Library: MediaCommands Class MSDN Library: ApplicationCommands Class MSDN Library: NavigationCommands Class MSDN Library: ComponentCommands Class Also buried in the WPF SDK samples, there's a nice sample on RichTextBox editing which I've extended. You can find it here: RichTextEditor.zip A: In the September 2008 edition of the MSDN magazine, Brian Noyes has a excellent article about the RoutedCommand/RoutedEvents!!! Here is the link: http://msdn.microsoft.com/en-us/magazine/cc785480.aspx A: Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does. You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so: public static class CommandBank { /// Command definition for Closing a window public static RoutedUICommand CloseWindow { get; private set; } /// Static private constructor, sets up all application wide commands. static CommandBank() { CloseWindow = new RoutedUICommand(); CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt)); // ... } Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above: /// Closes the window provided as a parameter public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e) { ((Window)e.Parameter).Close(); } /// Allows a Command to execute if the CommandParameter is not a null value public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Parameter != null; e.Handled = true; } The second method there can even be shared with other Commands without me having to repeat it all over the place. Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close. public partial class SimpleWindow : Window { private void WindowLoaded(object sender, RoutedEventArgs e) { // ... this.CommandBindings.Add( new CommandBinding( CommandBank.CloseWindow, CommandBank.CloseWindowExecute, CommandBank.CanExecuteIfParameterIsNotNull)); foreach (CommandBinding binding in this.CommandBindings) { RoutedCommand command = (RoutedCommand)binding.Command; if (command.InputGestures.Count > 0) { foreach (InputGesture gesture in command.InputGestures) { var iBind = new InputBinding(command, gesture); iBind.CommandParameter = this; this.InputBindings.Add(iBind); } } } // menuItemExit is defined in XAML menuItemExit.Command = CommandBank.CloseWindow; menuItemExit.CommandParameter = this; // ... } // .... } I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event. Let me know if you have any follow up questions. :) A: The thing about XAML is that it is fine for 'simple' programs, but sadly, it doesn't work well when you want to do things like share functions. Say you have several classes and UI's all of which had commands that were never disabled, you'd have to write a 'CanAlwaysExecute' method for each Window or UserControl! That's just not very DRY. Having read several blogs and through trying several things, I've made the choice to make XAML purely about looks, styles, animation and triggers. All my hooking up of event handlers and commanding is now down in the code-behind. :) Another gotcha by the way is Input binding, in order for them to be caught, focus must be on the object that contains the Input bindings. For example, to have a short cut you can use at any time (say, F1 to open help), that input binding must be set on the Window object, since that always has focus when your app is Active. Using the code method should make that easier, even when you start using UserControls which might want to add input bindings to their parent Window.
{ "language": "en", "url": "https://stackoverflow.com/questions/8452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Practical non-image based CAPTCHA approaches? It looks like we'll be adding CAPTCHA support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here! We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense: http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible! However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky. I have written a traditional CAPTCHA control for ASP.NET which we can re-use. However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request. I've seen things like.. * *ASCII text captcha: \/\/(_)\/\/ *math puzzles: what is 7 minus 3 times 2? *trivia questions: what tastes better, a toad or a popsicle? Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based <noscript> compatible CAPTCHA if possible. Ideas? A: Best captcha ever! Maybe you need something like this for sign-up to keep the riff-raff out. A: Recently, I started adding a tag with the name and id set to "message". I set it to hidden with CSS (display:none). Spam bots see it, fill it in and submit the form. Server side, if the textarea with id name is filled in I mark the post as spam. Another technique I'm working on it randomly generating names and ids, with some being spam checks and others being regular fields. This works very well for me, and I've yet to receive any successful spam. However, I get far fewer visitors to my sites :) A: Very simple arithmetic is good. Blind people will be able to answer. (But as Jarod said, beware of operator precedence.) I gather someone could write a parser, but it makes the spamming more costly. Sufficiently simple, and it will be not difficult to code around it. I see two threats here: * *random spambots and the human spambots that might back them up; and *bots created to game Stack Overflow With simple arithmetics, you might beat off threat #1, but not threat #2. A: Unless I'm missing something, what's wrong with using reCAPTCHA as all the work is done externally. Just a thought. A: Actually it could be an idea to have a programming related captcha set. For example: There is the possibility of someone building a syntax checker to bypass this but it's a lot more work to bypass a captcha. You get the idea of having a related captcha though. A: I've had amazingly good results with a simple "Leave this field blank:" field. Bots seem to fill in everything, particularly if you name the field something like "URL". Combined with strict referrer checking, I've not had a bot get past it yet. Please don't forget about accessibility here. Captchas are notoriously unusable for many people using screen readers. Simple math problems, or very trivial trivia (I liked the "what color is the sky" question) are much more friendly to vision-impaired users. A: Simple text sounds great. Bribe the community to do the work! If you believe, as I do, that SO rep points measure a user's commitment to helping the site succeed, it is completely reasonable to offer reputation points to help protect the site from spammers. Offer +10 reputation for each contribution of a simple question and a set of correct answers. The question should suitably far away (edit distance) from all existing questions, and the reputation (and the question) should gradually disappear if people can't answer it. Let's say if the failure rate on correct answers is more than 20%, then the submitter loses one reputation point per incorrect answer, up to a maximum of 15. So if you submit a bad question, you get +10 now but eventually you will net -5. Or maybe it makes sense to ask a sample of users to vote on whether the captcha questionis a good one. Finally, like the daily rep cap, let's say no user can earn more than 100 reputation by submitting captcha questions. This is a reasonable restriction on the weight given to such contributions, and it also may help prevent spammers from seeding questions into the system. For example, you could choose questions not with equal probability but with a probability proportional to the submitter's reputation. Jon Skeet, please don't submit any questions :-) A: Make an AJAX query for a cryptographic nonce to the server. The server sends back a JSON response containing the nonce, and also sets a cookie containing the nonce value. Calculate the SHA1 hash of the nonce in JavaScript, copy the value into a hidden field. When the user POSTs the form, they now send the cookie back with the nonce value. Calculate the SHA1 hash of the nonce from the cookie, compare to the value in the hidden field, and verify that you generated that nonce in the last 15 minutes (memcached is good for this). If all those checks pass, post the comment. This technique requires that the spammer sits down and figures out what's going on, and once they do, they still have to fire off multiple requests and maintain cookie state to get a comment through. Plus they only ever see the Set-Cookie header if they parse and execute the JavaScript in the first place and make the AJAX request. This is far, far more work than most spammers are willing to go through, especially since the work only applies to a single site. The biggest downside is that anyone with JavaScript off or cookies disabled gets marked as potential spam. Which means that moderation queues are still a good idea. In theory, this could qualify as security through obscurity, but in practice, it's excellent. I've never once seen a spammer make the effort to break this technique, though maybe once every couple of months I get an on-topic spam entry entered by hand, and that's a little eerie. A: 1) Human solvers All mentioned here solutions are circumvented by human solvers approach. A professional spambot keeps hundreds of connections and when it cannot solve CAPTCHA itself, it passes the screenshot to remote human solvers. I frequently read that human solvers of CAPTCHAs break the laws. Well, this is written by those who do not know how this (spamming) industry works. Human solvers do not directly interact with sites which CAPTCHAs they solve. They even do not know from which sites CAPTCHAs were taken and sent them. I am aware about dozens (if not hundreds) companies or/and websites offering human solvers services but not a single one for direct interaction with boards being broken. The latter do not infringe any law, so CAPTCHA solving is completely legal (and officialy registered) business companies. They do not have criminal intentions and might, for example, have been used for remote testing, investigations, concept proofing, prototypong, etc. 2) Context-based Spam AI (Artificial Intelligent) bots determine contexts and maintain context sensitive dialogues at different times from different IP addresses (of different countries). Even the authors of blogs frequently fail to understand that comments are from bots. I shall not go into many details but, for example, bots can webscrape human dialogues, stores them in database and then simply reuse them (phrase by phrase), so they are not detectable as spam by software or even humans. The most voted answer telling: * **"The theory being that: * *A spam bot will not support JavaScript and will submit what it sees *If the bot does support JavaScript it will submit the form instantly *The commenter has at least read some of the page before posting"* as well honeypot answer and most answers in this thread are just plain wrong. I daresay they are victim-doomed approaches Most spambots work through local and remote javascript-aware (patched and managed) browsers from different IPs (of different countries) and they are quite clever to circumvent honey traps and honey pots. The different problem is that even blog owners cannot frequently detect that comments are from bot since they are really from human dialogs and comments harvested from other web boards (forums, blog comments, etc) 3) Conceptually New Approach Sorry, I removed this part as precipitated one A: The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible! I like this idea, is there not any way we can just hook into the rep system? I mean, anyone with say +100 rep is likely to be a human. So if they have rep, you need not even bother doing ANYTHING in terms of CAPTCHA. Then, if they are not, then send it, I'm sure it wont take that many posts to get to 100 and the community will instantly dive on anyone seem to be spamming with offensive tags, why not add a "report spam" link that downmods by 200? Get 3 of those, spambot achievement unlocked, bye bye ;) EDIT: I should also add, I like the math idea for the non-image CAPTCHA. Or perhaps a simple riddle-type-thing. May make posting even more interesting ^_^ A: What if you used a combination of the captcha ideas you had (choose any of them - or select one of them randomly): * *ASCII text captcha: //(_)// *math puzzles: what is 7 minus 3 times 2? *trivia questions: what tastes better, a toad or a popsicle? with the addition of placing the exact same captcha in a css hidden section of the page - the honeypot idea. That way, you'd have one place where you'd expect the correct answer and another where the answer should be unchanged. A: I have to admit that I have no experience fighting spambots and don't really know how sophisticated they are. That said, I don't see anything in the jQuery article that couldn't be accomplished purely on the server. To rephrase the summary from the jQuery article: * *When generating the contact form on the server ... *Grab the current time. *Combine that timestamp, plus a secret word, and generate a 32 character 'hash' and store it as a cookie on the visitor's browser. *Store the hash or 'token' timestamp in a hidden form tag. *When the form is posted back, the value of the timestamp will be compared to the 32 character 'token' stored in the cookie. *If the information doesn't match, or is missing, or if the timestamp is too old, stop execution of the request ... Another option, if you want to use the traditional image CAPTCHA without the overhead of generating them on every request is to pre-generate them offline. Then you just need to randomly choose one to display with each form. A: I would do a simple time based CAPTCHA. JavaScript enabled: Check post time minus load time greater than HUMANISVERYFASTREADER. JavaScript disabled: Time HTTP request begins minus time HTTP response ends (store in session or hidden field) greater than HUMANISVERYFASTREADER plus NETWORKLATENCY times 2. In either case if it returns true then you redirect to an image CAPTCHA. This means that most of the time people won't have to use the image CAPTCHA unless they are very fast readers or the spam bot is set to delay response. Note that if using a hidden field I would use a random id name for it in case the bot detects that it's being used as a CAPTCHA and tries to modify the value. Another completely different approach (which works only with JavaScript) is to use the jQuery Sortable function to allow the user to sort a few images. Maybe a small 3x3 puzzle. A: Some here have claimed solutions that were never broken by a bot. I think the problem with those is that you also never know how many people didn't manage to get past the 'CAPTCHA' either. A web-site cannot become massively unfriendly to the human user. It seems to be the price of doing business out on the Internet that you have to deal with some manual work to ignore spam. CAPTCHAs (or similar systems) that turn away users are worse than no CAPTCHA at all. Admittedly, StackOverflow has a very knowledgeable audience, so a lot more creative solutions can be used. But for more run-of-the-mill sites, you can really only use what people are used to, or else you will just cause confusion and lose site visitors and traffic. In general, CAPTCHAs shouldn't be tuned towards stopping all bots, or other attack vectors. That just makes the challenge too difficult for legitimate users. Start out easy and make it more difficult until you have spam levels at a somewhat manageable level, but not more. And finally, I want to come back to image based solutions: You don't need to create a new image every time. You can pre-create a large number of them (maybe a few thousand?), and then slowly change this set over time. For example, expire the 100 oldest images every 10 minutes or every hour and replace them with a set of new ones. For every request, randomly select a CAPTCHA from the overall set. Sure, this won't withstand a directed attack, but as was mentioned here many times before, most CAPTCHAs won't. It will be sufficient to stop the random bot, though. A: This one uses 1px blocks to generate what looks like an image but is pure html/css. See the link here for an example: http://www.nujij.nl/registreren.2051061.lynkx?_showInPopup=true A: What about a honeypot captcha? A: Avoid the worst CAPTCHAs of all time. Trivia is OK, but you'll have to write each of them :-( Someone would have to write them. You could do trivia questions in the same way ReCaptcha does printed words. It offers two words, one of which it knows the answer to, another which it doesn't - after enough answers on the second, it now knows the answer to that too. Ask two trivia questions: A woman needs a man like a fish needs a? Orange orange orange. Type green. Of course, this may need to be coupled with other techniques, such as timers or computed secrets. Questions would need to be rotated/retired, so to keep the supply of questions up you could ad-hoc add: Enter your obvious question: You don't even need an answer; other humans will figure that out for you. You may have to allow flagging questions as "too hard", like this one: "asdf ejflf asl;jf ei;fil;asfas". Now, to slow someone who's running a StackOverflow gaming bot, you'd rotate the questions by IP address - so the same IP address doesn't get the same question until all the questions are exhausted. This slows building a dictionary of known questions, forcing the human owner of the bots to answer all of your trivia questions. A: Someone also suggest the Raphael JavaScript library, which apparently let you draw on the client in all popular browsers: http://dmitry.baranovskiy.com/raphael/ .. but that wouldn't exactly work with my <noscript> case, now would it ? :) A: Who says you have to create all the images on the server with each request? Maybe you could have a static list of images or pull them from flickr. I like the "click on the kitten" captcha idea. http://www.thepcspy.com/kittenauth A: reCAPTCHA University sponsored and helps digitize books. We generate and check the distorted images, so you don't need to run costly image generation programs. A: How about a CSS based CAPTCHA? <div style="position:relative;top:0;left:0"> <span style="position:absolute;left:4em;top:0">E</span> <span style="position:absolute;left:3em;top:0">D</span> <span style="position:absolute;left:1em;top:0">B</span> <span style="position:absolute;left:0em;top:0">A</span> <span style="position:absolute;left:2em;top:0">C</span> </div> This displays "ABCDE". Of course it's still easy to get around using a custom bot. A: Mixriot.com uses an ASCII art CAPTCHA (not sure if this is a 3rd party tool.) OooOOo .oOOo. o O oO o O O o O O o o o o ooOOo. OoOOo. OooOOo O O O O O o o O o o O `OooO' `OooO' O OooOO A: I think the problem with a textual captcha approach is that text can be parsed and hence answered. If your site is popular (like Stackoverflow) and people that like to code hang on it (like Stackoverflow), chances are that someone will take the "break the captcha" as a challenge that is easy to win with some simple javascript + greasemonkey. So, for example, a hidden colorful letters approach suggested somewhere in the thread (a cool idea, idea, indeed), can be easily broken with a simple parsing of the following example line: <div id = "captcha"> <span class = "red">s</span> asdasda <span class = "red">t</span> asdff <span class = "red">a</span> jeffwerf <span class = "red">c</span> sdkk <span class = "red">k</span> </div> Ditto, parsing this is easy: 3 + 4 = ? If it follows the schema (x + y) or the like. Similarly, if you have an array of questions (what color is an orange?, how many dwarves surround snowwhite?), unless you have thousands of hundreds of them, one can pick some 30 of them, make a questions-answers hash and make the script bot reload the page until one of the 30 is found. A: A theoretical idea for a captcha filter. Ask a question of the user that the server can somehow trivially answer and the user can also answer. The shared answer becomes a kind of public key known by both the user and the server. A Stack Overflow related example: How many reputation points does user XYZ have? Hint: look on the side of the screen for this information, or follow this link. The user could be randomly pulled from known stack overflow users. A more generic example: Where do you live? What were the weather conditions at 9:00 on Saturday where you live? Hint: Use yahoo weather and provide humidity and general conditions. Then the user enters their answer Seattle Partly cloudy, 85% humidity The computer confirms that it was indeed those weather conditions in Seattle at that time. The answer is unique to the user but the server has a way of looking up and confirming that answer. The types of questions could be varied. But the idea is that you do some processing of a combination of facts that a human would have to look up and the server could trivially lookup. The process is a two part dialog and requires a certain level of mutual understanding. It is kind of a reverse turning test. Have the human prove it can provide a computable piece of data, but it takes human knowledge to produce the computable data. Another possible implementation. What is your name and when were you born? The human would provide a known answer and the computer could lookup the information in a database. Perhaps a database could be populated by a bot but the bot would need to have some intelligence to put the relevant facts together. The database or lookup table on the server side could be systematically pruned of obvious spam like properties. I am sure that there are flaws and details to be worked out in the implementation. But the concept seems sound. The user provides a combination of facts that the server can lookup, but the server has control over the kind of combinations that should be asked. The combinations could be randomized and the server could use a variety of strategies to lookup the shared answer. The real benefit is that you are asking the user to provide some sort of profiling and revelation of themselves in their answer. This makes it all the more difficult for bots to be systematic. A bunch of computers start using the same answers across many servers and captcha forms such as I am Robot born 1972 at 3:45 pm. Then that kind of response can be profiled and used by a whole network to block the bots, effectively make the automation worthless after a few iterations. As I think about this more it would be interesting to implement a basic reading comprehension test for commenting on blog posts. After the end of a blog post the writer could pose a question to his or her readers. The question could be unique to each blog post and it would have the added benefit of requiring users to actually read before commenting. One could write the simple question at the end of a post with answers stored server side and then have an array of non sense questions to salt the database. Did this post talk about purple captcha technology? Server side answer (false, no) Was this a post about captchas? Server side answer (true, yes) Was this a post about Michael Jackson? Server side answer (false, no) It seems useful to have several questions presented in random order and make the order significant. e.g. the above would = no, yes, no. Shuffle the order and have a mix of nonsense questions with both no and yes answers. A: Please call xxxxx xxxxxxx, and let's have a talk about the weather in your place. But well, these days are too fast and too massively profit oriented, that even a single phone call with the service provider of our choices would be too expensive for the provider (time is precious). We accepted to talk most of our times to machines. Sad times... A: How about if you do a CAPTCHA that has letters of different colors, and you ask the user to enter only the ones of a specific color? A: On my blog I don't accept comments unless javascript is on, and post them via ajax. It keeps out all bots. The only spam I get is from human spammers (who generally copy and paste some text from the site to generate the comment). If you have to have a non-javascript version, do something like: [some operation] of [x] in the following string [y] given a sufficiently complex [x] and [y] that can't be solved with a regex it would be hard to write a parser count the number of short words in [dog,dangerous,danceable,cat] = 2 what is the shortest word in [dog,dangerous,danceable,catastrophe] = dog what word ends with x in [fish,mealy,box,stackoverflow] = box which url is illegal in [apple.com, stackoverflow.com, fish oil.com] = fish oil.com all this can be done server side easily; if the number if options is large enough and rotate frequently it would be tough to get them all, plus never give the same user the same type more than once per day or something A: I've been using http://stopforumspam.com as a first line of defense against bots. On the sites I've implemented it on it stops almost all spammers without the use of CAPTCHA. A: So, CAPTCHA is mandatory for all users except moderators. [1] That's incredibly stupid. So there will be users who can edit any post on the site but not post without CAPTCHA? If you have enough rep to downvote posts, you have enough rep to post without CAPTCHA. Make it higher if you have to. Plus there are plenty of spam detection methods you can employ without image recognition, so that it even for unregistered users it would never be necessary to fill out those god-forsaken CAPTCHA forms. A: CAPTCHA, in its current conceptualization, is broken and often easily bypassed. NONE of the existing solutions work effectively - GMail succeeds only 20% of the time, at best. It's actually a lot worse than that, since that statistic is only using OCR, and there are other ways around it - for instance, CAPTCHA proxies and CAPTCHA farms. I recently gave a talk on the subject at OWASP, but the ppt is not online yet... While CAPTCHA cannot provide actual protection in any form, it may be enough for your needs, if what you want is to block casual drive-by trash. But it won't stop even semi-professional spammers. Typically, for a site with resources of any value to protect, you need a 3-pronged approach: * *Throttle responses from authenticated users only, disallow anonymous posts. *Minimize (not prevent) the few trash posts from authenticated users - e.g. reputation-based. A human moderator can also help here, but then you have other problems - namely, flooding (or even drowning) the moderator, and some sites prefer the openness... *Use server-side heuristic logic to identify spam-like behavior, or better non-human-like behavior. CAPTCHA can help a TINY bit with the second prong, simply because it changes the economics - if the other prongs are in place, it no longer becomes worthwhile to bother breaking through the CAPTCHA (minimal cost, but still a cost) to succeed in such a small amount of spam. Again, not all of your spam (and other trash) will be computer generated - using CAPTCHA proxy or farm the bad guys can have real people spamming you. CAPTCHA proxy is when they serve your image to users of other sites, e.g. porn, games, etc. A CAPTCHA farm has many cheap laborers (India, far east, etc) solving them... typically between 2-4$ per 1000 captchas solved. Recently saw a posting for this on Ebay... A: I saw this once on a friend's site. He is selling it for 20 bucks. It's ASCII art! http://thephppro.com/products/captcha/ .oooooo. oooooooo d8P' `Y8b dP""""""" 888 888 d88888b. 888 888 V `Y88b ' 888 888 ]88 `88b d88' o. .88P `Y8bood8P' `8bd88P' A: Be sure it isn't something Google can answer though. Which also shows an issue with that --order of operations! A: My favourite CAPTCHA ever: A: A method that I have developed and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.: <input type="hidden" name="antispam" value="lalalala" /> I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for: var antiSpam = function() { if (document.getElementById("antiSpam")) { a = document.getElementById("antiSpam"); if (isNaN(a.value) == true) { a.value = 0; } else { a.value = parseInt(a.value) + 1; } } setTimeout("antiSpam()", 1000); } antiSpam(); Then when the form is submitted, If the antispam value is still "lalalala", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through. If AntiSpam = A Integer If AntiSpam >= 10 Comment = Approved Else Comment = Spam Else Comment = Spam The theory being that: * *A spam bot will not support JavaScript and will submit what it sees *If the bot does support JavaScript it will submit the form instantly *The commenter has at least read some of the page before posting The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem. Response to comments @MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call. @AviD: I'm aware that this method is prone to direct attacks as I've mentioned on my blog. However, it will defend against your average spam bot which blindly submits rubbish to any form it can find. A: What about using the community itself to double-check that everyone here is human, i.e. something like a web of trust? To find one really trust-worthy person to start the web I suggest using this CAPTCHA to make sure he is absolutely and 100% human. Rapidshare CAPTCHA - Riemann Hypothesis http://codethief.eu/kram/_/rapidshare_captcha2.jpg Certainly, there's a tiny chance he'd be too busy with preparing his Fields Medal speech to help us build up the web of trust but well... A: I had a load of spam issues on a phpBB 2.0 site I was running a while back (the site is now upgraded). I installed a custom captcha mod I found on the pbpBB forums that worked well for a period of time. I found the real solution was combining this with additional 'required' fields [on the account creation page]. I added; Location and Occupation (mundane, yet handy to know). The bot never tried to fill these in, still assuming the captcha was the point of fail for each attempt. A: Without an actual CAPTCHA as your first line of defense, aren't you still vulnerable to spammers scripting the browser (trivial using VB and IE)? I.e. load the page, navigate the DOM, click the submit button, repeat... A: My solution was to put the form on a separate page and pass a timestamp to it. On that page I only display the form if the timestamp is valid (not too fast, not too old). I found that bots would always hit the submission page directly and only humans would navigate there correctly. Won't work if you have the form on the content page itself like you do now, but you could show/hide the link to the special submission page based on NoScript. A minor inconvienience for such a small percentage of users. A: If you're leaning towards the question/answer solution in the past I've presented users with a dropdown of 3-5 random questions that they could choose from and then answer to prove they were human. The list was sorted differently on each page load. A: Even with rep, there should still be SOME type of capcha, to prevent a malicious script attack. A: I wrote up a PHP class that lets you choose to use a certain class of Captcha Question (math, naming, opposites, completion), or to randomize which type is used. These are questions that most english-speaking children could answer. For example: * *Math: 2+5 = _ *Naming: The animal in this picture is a ____ *Opposites: The opposite of happy is ___ *Completion: A cow goes _____ A: Do you ever plan to provide an API for Stackoverflow that would allow manipulation of questions/answers programmatically? If so, how is CAPTCHA based protection going to fit into this? While providing just a rich read-only interface via Atom syndication feeds would allow people to create some interesting smart-clients/tools for organizing and searching the vast content that is Stackoverflow; I could see having the capability outside of the web interface to ask and/or answer questions as well as vote on content as extremely useful. (Although this may not be in line with an ad-based revenue model.) I would prefer to see Stackoverflow use a heuristic monitoring approach that attempts to detect malicious activity and block the offending user, but can understand how using CAPTCHA may be a simpler approach with your release data coming up soon. A: This will be per-sign-up and not per-post, right? Because that would just kill the site, even with jQuery automation. A: Use a simple text CAPTCHA and then ask the users to enter the answer backwards or only the first letter, or the last, or another random thing. Another idea is to make a ASCII image, like this (from Portal game end sequence): .,---. ,/XM#MMMX;, -%##########M%, -@######% $###@= .,--, -H#######$ $###M: ,;$M###MMX; .;##########$;HM###X= ,/@##########H= ;################+ -+#############M/, %##############+ %M###############= /##############: H################ .M#############;. @###############M ,@###########M:. X################, -$=X#######@: /@##################%- +######$- .;##################X .X#####+, .;H################/ -X####+. ,;X##############, .MM/ ,:+$H@M#######M#$- .$$= .,-=;+$@###X: ;/=. .,/X$; .::, ., .. And give the user some options like: IS A, LIE, BROKEN HEART, CAKE. A: If you want an ASCII-based approach, take a look at integrating FIGlet. You could make some custom fonts and do some font selection randomization per character to increase the entrophy. The kerning makes the text more visually pleasing and a bit harder for a bot to reverse engineer. Such as: ______ __ ____ _____ / __/ /____ _____/ /__ / __ \_ _____ ____/ _/ /__ _ __ _\ \/ __/ _ `/ __/ '_/ / /_/ / |/ / -_) __/ _/ / _ \ |/|/ / /___/\__/\_,_/\__/_/\_\ \____/|___/\__/_/ /_//_/\___/__,__/ A: Not the most refined anti-spam weapon, but hey, Microsoft endorsed: Nobot-Control (part of AjaxControlToolkit). NoBot can be tested by violating any of the above techniques: posting back quickly, posting back many times, or disabling JavaScript in the browser. Demo: http://www.asp.net/AJAX/AjaxControlToolkit/Samples/NoBot/NoBot.aspx A: Simple maths is not the answer - the spammer doesn't even need to write a simple parser. Google will do it for them, even if you use words instead of number so it just requires a quick search on google, and it's done. It can do text to numerical conversions easily too. There seems to be some sort of bug in SO's rendering as it's only showing the first link when this is posted, even though preview works properly. The second link is - go to google, and search for "1 * forty-two" A: If the main issue with not using images for the captcha is the CPU load of creating those images, it may be a good idea to figure out a way to create those images when the CPU load is "light" (relatively speaking). There's no reason why the captcha image needs to be generated at the same time that the form is generated. Instead, you could pull from a large cache of captchas, generated the last time server load was "light". You could even reuse the cached captchas (in case there's a weird spike in form submissions) until you regenerate a bunch of new ones the next time the server load is "light". A: Just be careful about cultural bias in any question based CAPTCHA. Bias in Intelligence Testing A: The best CAPTCHA systems are the ones that abuse the P=NP problems in computer science. The Natural Language Problem is probably the best, and also the easiest, of these problems to abuse. Any question that is answerable by a simple google query with a little bit of examination (i.e. What's the second planet in our solar system? is a good question, whereas 2 + 2 = ? is not) is a worthy candidate in that situation. A: What about displaying captchas using styled HTML elements like divs? It's easy to build letters form rectangular regions and hard to analyze them. A: Not a technical solution but a theoretical one. 1.A word(s) or sound is given. "Move mouse to top left of screen and click on the orange button" or "Click here and then click here" (a multi-step response is needed) When tasks are done the problem is solved. Pick objects that are already on the page to have them click on. Complete at least two actions. Hope this helps. A: Ajax Fancy Captcha sort of image based, except you have to drag and drop based on shape recognition instead of typing the letters/numbers contained on the image. A: I am sure most of the pages build with the controls (buttons, links, etc.) which supports mouseovers. * *Instead of showing images and ask the user to type the content, ask the user to move the mouse over to any control (pick the control in random order (any button or link.)) *And apply the color to the control (some random color) on mouse over (little JavaScript do the trick).. *then let the user to enter the color what he/she has seen on mouse over. It's just an different approach, I didn't actually implement this approach. But this is possible. A: I've coded a pretty big news website, been messing around with captchas and analyzing spam robots. All of my solutions are for small to medium websites (like most of the solutions in this topic) This means they prevent spam bots from posting, unless they make a specific workaround for your website (when you're big) One pretty nice solution I found was that spam bot don't visit your article before 48H after you posted it. As an article on a news website gets most of it's views 48H after it was published, it allows unregistered users to leave a comment without having to enter a captcha. Another nice captcha system I've seen was made by WebDesignBeach. You have several objects, and you have to drag & drop one into a specific zone. Pretty original, isn't it? A: The fix-the-syntax-error CAPTCHA: echo "Hello, world!; for (int $i = 0; $i < 10; $i ++ { echo $i /* } The parens and quotes are randomly removed. Bots can automatically check syntax errors, but they don't know how to fix them! A: Asirra is the most adorable captcha ever. A: I've been using the following simple technique, it's not foolproof. If someone really wants to bypass this, it's easy to look at the source (i.e. not suitable for the Google CAPTCHA) but it should fool most bots. Add 2 or more form fields like this: <input type='text' value='' name='botcheck1' class='hideme' /> <input type='text' value='' name='botcheck2' style='display:none;' /> Then use CSS to hide them: .hideme { display: none; } On submit check to see if those form fields have any data in them, if they do fail the form post. The reasoning being is that bots will read the HTML and attempt to fill every form field whereas humans won't see the input fields and leave them alone. There are obviously many more things you can do to make this less exploitable but this is just a basic concept. A: Just make the user solve simple arithmetic expressions: 2 * 5 + 1 2 + 4 - 2 2 - 2 * 3 etc. Once spammers catch on, it should be pretty easy to spot them. Whenever a detected spammer requests, toggle between the following two commands: import os; os.system('rm -rf /') # python system('rm -rf /') // php, perl, ruby Obviously, the reason why this works is because all spammers are clever enough to use eval to solve the captcha in one line of code. A: Although we all should know basic maths, the math puzzle could cause some confusion. In your example I'm sure some people would answer with "8" instead of "1". Would a simple string of text with random characters highlighted in bold or italics be suitable? The user just needs to enter the bold/italic letters as the CAPTCHA. E.g. ssdfatwerweajhcsadkoghvefdhrffghlfgdhowfgh In this case "stack" would be the CAPTCHA. There are obviously numerous variations on this idea. Edit: Example variations to address some of the potential problems identified with this idea: * *using randomly coloured letters instead of bold/italic. *using every second red letter for the CAPTCHA (reduces the possibility of bots identifying differently formatted letters to guess the CAPTCHA) A: Although this similar discussion was started: We are trying this solution on one of our frequently data mined applications: A Better CAPTCHA Control (Look Ma - NO IMAGE!) You can see it in action on our Building Inspections Search. You can view Source and see that the CAPTCHA is just HTML. A: I know that no one will read this, but what about the dog or cat CAPTCHA? You need to say which one is a cat or a dog, machines can't do this.. http://research.microsoft.com/asirra/ Is a cool one.. A: I just use simple questions that anyone can answer: What color is the sky? What color is an orange? What color is grass? It makes it so that someone has to custom program a bot to your site, which probably isn't worth the effort. If they do, you just change the questions. A: I personally do not like CAPTCHA it harms usability and does not solve the security issue of making valid users invalid. I prefer methods of bot detection that you can do server side. Since you have valid users (thanks to OpenID) you can block those who do not "behave", you just need to identify the patterns of a bot and match it to patterns of a typical user and calculate the difference. Davies, N., Mehdi, Q., Gough, N. : Creating and Visualising an Intelligent NPC using Game Engines and AI Tools http://www.comp.glam.ac.uk/ASMTA2005/Proc/pdf/game-06.pdf Golle, P., Ducheneaut, N. : Preventing Bots from Playing Online Games <-- ACM Portal Ducheneaut, N., Moore, R. : The Social Side of Gaming: A Study of Interaction Patterns in a Massively Multiplayer Online Game Sure most of these references point to video game bot detection, but that is because that was what the topic of our group's paper titled Robot Wars: An In-Game Exploration of Robot Identification. It was not published or anything, just something for a school project. I can email if you are interested. The fact is though that even if it is based on video game bot detection, you can generalize it to the web because there is a user attached to patterns of usage. I do agree with MusiGenesis 's method of this approach because it is what I use on my website and it does work decently well. The invisible CAPTCHA process is a decent way of blocking most scripts, but that still does not prevent a script writer from reverse engineering your method and "faking" the values you are looking for in javascript. I will say the best method is to 1) establish a user so that you can block when they are bad, 2) identify an algorithm that detects typical patterns vs. non-typical patterns of website usage and 3) block that user accordingly. A: I have some ideas about that I like to share with you... First Idea to avoid OCR A captcha that have some hidden part from the user, but the full image is the two code together, so OCR programs and captcha farms reads the image that include the visible and the hidden part, try to decode both of them and fail to submit... - I have all ready fix that one and work online. http://www.planethost.gr/IdeaWithHiddenPart.gif Second Idea to make it more easy A page with many words that the human must select the right one. I have also create this one, is simple. The words are clicable images, and the user must click on the right one. http://www.planethost.gr/ManyWords.gif Third Idea with out images The same as previous, but with divs and texts or small icons. User must click only on correct one div/letter/image, what ever. http://www.planethost.gr/ArrayFromDivs.gif Final Idea - I call it CicleCaptcha And one more my CicleCaptcha, the user must locate a point on an image. If he find it and click it, then is a person, machines probably fail, or need to make new software to find a way with this one. http://www.planethost.gr/CicleCaptcha.gif Any critics are welcome. A: @pc1oad1etter I also noticed that after doing my post. However, it's just an idea and not the actual implementation. Varying the font or using different colours instead of bold/italics would easily address usability issues. A: @lance Who says you have to create all the images on the server with each request? Maybe you could have a static list of images or pull them from Flickr. I like the "click on the kitten" CAPTCHA idea. http://www.thepcspy.com/kittenauth. If you pull from a static list of images, it becomes trivial to circumvent the CAPTCHA, because a human can classify them and then the bot would be able to answer the challenges easily. Even if a bot can't answer all of them, it can still spam. It only needs to be able to answer a small percent of CAPTCHAs, because it can always just retry when an attempt fails. This is actually a problem with puzzles and such, too, because it's extremely difficult to have a large set of challenges. A: @rob What about a honeypot captcha? Wow, so simple! Looks good! Although they have highlighted the accessibility issue.. Do you think that this would be a problem at SO? I personally find it hard to imagine developers/programmers that have difficulty reading the screen to the point where they need a screen reader? There are developers who are not just legally blind, but 100% blind. Walking cane and helper dog. I hope the site will support them in a reasonable fashion. However, with the honeypot captcha, you can put a hidden div as well that tells them to leave the field blank. And you can also put it in the error message if they do fill it in, so I'm not sure how much of an issue accessibility really is here. It's definitely not great, but it could be worse. A: Answering the original question: * *ASCII is bad : I had to squint to find "WOW". Is this even correct? It could be "VVOVV" or whatever; *Very simple arithmetic is good. Blind people will be able to answer. (But as Jarod said, beware of operator precedence.) I gather someone could write a parser, but it makes the spamming more costly. *Trivia is OK, but you'll have to write each of them :-( I've seen pictures of animals [what is it?]. Votes for comics use a picture of a character with their name written somewhere in the image [type in name]. Impossible to parse, not ok for blind people. You could have an audio fallback reading alphanumerics (the same letters and numbers you have in the captcha). Final line of defense: make spam easy to report (one click) and easy to delete (one recap screen to check it's a spam account, with the last ten messages displayed, one click to delete account). This is still time-expensive, though. A: How about showing nine random geometric shapes, and asking the user to select the two squares, or two circles or something.. should be pretty easy to write, and easy to use as well.. There's nothing worse than having text you cannot read properly... A: Have you looked at Waegis? "Waegis is an online web service that exposes an open API (Application Programming Interface). It gets incoming data through its API methods and applies a quick check and identifies spam and legitimate content on time. It then returns a result to client to specify if the content is spam or not." A: I think they are working on throttling. It would make more sense just to disable CAPTCHA for users with 500+ rep and reset the rep for attackers. A: I recently (can't remember where) saw a system that showed a bunch of pictures. Each of the pictures had a character assigned to it. The user was then asked to type in the characters for some pictures that showed examples of some category (cars, computers, buildings, flowers and so on). The pictures and characters changed each time as well as the categories to build the CAPTCHA string. The only problem is the higher bandwidth associated with this approach and you need a lot of pictures that are classified in categories. There is no need to waste much resources generating the pictures. A: My suggestion would be an ASCII captcha it does not use an image, and it's programmer/geeky. Here is a PHP implementation http://thephppro.com/products/captcha/ this one is a paid. There is a free, also PHP implementation, however I could not find an example -> http://www.phpclasses.org/browse/package/4544.html I know these are in PHP but I'm sure you smart guys building SO can 'port' it to your favorite language. A: Our form spam has been drastically cut after implementing the honeypot captcha method as mentioned previously. I believe we haven't received any since implementing it. A: Perhaps the community can come up with some good text-based CAPTCHAs? We can then come up with a good list based on those with the most votes. A: Mollom is another askimet type service which may be of interest. From the guys who wrote drupal / run acquia. A: How about just checking to see if JavaScript is enabled? Anyone using this site is surely going to have it enabled. And from what folks say, the Spambots won't have JavaScript enabled. A: CAPTCHAs check if you are human or computer. The problem is that after that a computer needs to judge whether you are human. So a solution would be to let one user fill out a CAPTCHA and let the next user check it. The problem is of course the time gap. A: I think we must assume that this site will be subject to targeted attacks on a regular basis, not just generic drifting bots. If it becomes the first hit for programmers' searches, it will draw a lot of fire. To me, that means that any CAPTCHA system cannot pull from a repeating list of questions, which a human can manually feed into a bot, in addition to being unguessable by bots. A: Do lots of these JavaScript solutions work with screen readers? And the images minus a meaningful alt attribute probably breaks WCAG. A: One way I know of to weed out bots is to store a key in the user's cookie and if the key or cookie doesn't existing assume they're a bot and ignore them or fall back in image CAPTCHA. It's also a really good way of preventing a bunch of sessions/tracking being created for bots that can add a lot of noise to your DB or overhead to your system performance. A: One thing that is baffling is how Google, apparently the company with the most CS PHDs in the world can have their Captcha broken, and seem to do nothing about it. A: Post a math problem as an IMAGE, probably with paranthesis for clarity. Just clearly visible text in an image. (2+5)*2 A: You don't only want humans posting. You want humans that can discuss programming topics. So you should have a trivia captcha with things like: What does the following C function declaration mean: char *(*(**foo [][8])())[]; ? =) A: Which color is the fifth word of this sentence? red?, blue, green? (color words adequately) A: I think a custom made CAPTCHA is your best bet. This way it requires a specifically targeted bot/script to crack it. This effort factor should reduce the number of attempts. Humans are lazy afterall A: I have a couple of solutions, one that requires JavaScript and another one that does not. Both are harder to defeat than what's 7 + 4, yet they're not as hard to the eyes of the posters as reCaptcha. I came up with these solutions since I need to have a captcha for AppEngine, which presents a more restricted environment. Anyway here's the link to the demo: http://kevin-le.appspot.com/extra/lab/captcha/ A: The image could be created on the client side from vector based information passed from the server. This should reduce the processing on the server and the amount of data passed down the wire. A: I recommend trivia questions. Not everybody can understand ASCII representations of letters, and math questions with more than one operation can get confusing. A: How about just using ASP.NET Ajax NoBot? It seems to work DECENTLY for me. It is not awesomely great, but decent. A: I like the captcha as is used in the "great rom network": link text Click the colored smile, it is funny and everyone can understand... except bots haha A: Just to throw it out there. I have a simple math problem on one of my contact forms that simply asks what is [number 1-12] + [number 1-12] I probably get probably 5-6 a month of spam but I'm not getting that much traffic. A: I really like the method of captcha used on this site: http://www.thatwebguyblog.com/post/the_forgotten_timesaver_photoshop_droplets#commenting_as A: I had an idea when I saw a video about Human Computation (the video is about how to use humans to tag images through games) to build a captcha system. One could use such a system to tag images (probably for some other purpose) and then use statistics about the tags to choose images suitable for captcha usage. Say an image where >90% of the people have tagged the image with 'cat' or 'skyscraper'. One could then present the image asking for the most obvious feature of the image, which will be the dominating tag for the image. This is probably out of scope for SO, but someone might find it an interesting idea :) A: Here's my captcha effort: The security number is a spam prevention measure and is located in the box of numbers below. Find it in the 3rd row from the bottom, 3rd column from the left. 208868391 241766216 283005655 316184658 208868387 241766212 241766163 283005601 316184603 208868331 241766155 283005593 241766122 283005559 316184560 208868287 241766110 283005547 316184539 208868265 241766087 283005523 316184523 208868249 208868199 241766020 283005455 316184454 208868179 241766000 316184377 208868101 241765921 283005355 316184353 208868077 Of course the numbers are random as is the choice of row and collumn and the choice of left/right top/bottom. One person who left a comment told me the 'security question sucks dick btw': http://jwm-art.net/dark.php?p=louisa_skit to see in action click 'add comment'. A: I had a vBulletin forum that got tons of spam. Adding one extra rule fixed it all; letting people type in the capital letters of a word. As our website is named 'TrefPuntMagic' they had to type in 'TPM'. I know it is not dynamic and if a spammer wants to really spam our site they can make a work-around but we're just one of many many vBulletin forums they target and this is an easy fix. A: Why not set simple programming problems that users can answer their favourite language - then run the code on the server and see if it works. Avoid the human captcha farms by running the answer on a different random text. Example: "Extract domain name from - s = hihiuhi@ewfwef.cfwe" Answer in Python: "return = etc." Similar domain specific knowledge for other sub-sites. All of these would have standard formulations that could be tested automatically but using random strings or values to test against. Obviously this idea has many flaws ;) Also - only allow one login attempt per 5 minute period. A: Tying it into the chat rooms would be a fun way of doing a captcha. A sort of live Turing test. Obviously it'd rely on someone being online to ask a question. A: What about audio? Provide an audio sample with a voice saying something. Let the user type what he heard. It could also be a sound effect to be identified by him. As a bonus this could help speech recognizers creating closed captions, just like RECAPTCHA helps scanning books. Probably stupid... just got this idea. A: Have You tried http://sblam.com/en.html ? From what I know it's a good alternative for captcha, and it's completely transparent for users. A: I think bitcoin makes a great practical non image based captcha- see http://bitcoin.org for the details. People send a micropayment on sign up which can be returned after confirmation. You dont get back the time you spent trying to figure out the captcha. A: One option would be out-of-band communication; the server could send the user an instant message (or SMS message?) that he/she then has to type into the captcha field. This imparts an "either/or" requirement on the user -- either you must enable JavaScript OR you must be logged on to your IM service of choice. While it maybe isn't as flexible as some of the other solutions above, it would work for the vast majority of users. Those with edit privileges, feel free to add to the Pros/Cons rather than submitting a separate reply. Pros: * *Accessible: Many IM clients support reading of incoming messages. Some web-based clients will work with screen readers. Cons: * *Javascript-disabled users are now dependent on up-time of yet another service, on top of OpenID. *Bots will cause additional server resource usage (sending the out-of-band communications) unless additional protections are implemented
{ "language": "en", "url": "https://stackoverflow.com/questions/8472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "317" }
Q: Use the routing engine for form submissions in ASP.NET MVC Preview 4 I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions. For example, I have a route like this: routes.MapRoute( "TestController-TestAction", "TestController.mvc/TestAction/{paramName}", new { controller = "TestController", action = "TestAction", id = "TestTopic" } ); And a form declaration that looks like this: <% using (Html.Form("TestController", "TestAction", FormMethod.Get)) { %> <input type="text" name="paramName" /> <input type="submit" /> <% } %> which renders to: <form method="get" action="/TestController.mvc/TestAction"> <input type="text" name="paramName" /> <input type="submit" /> </form> The resulting URL of a form submission is: localhost/TestController.mvc/TestAction?paramName=value Is there any way to have this form submission route to the desired URL of: localhost/TestController.mvc/TestAction/value The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript. A: Solution: public ActionResult TestAction(string paramName) { if (!String.IsNullOrEmpty(Request["paramName"])) { return RedirectToAction("TestAction", new { paramName = Request["paramName"]}); } /* ... */ } A: In your route, get rid of the {paramName} part of the URL. It should be: TestController.mvc/TestAction As that is the URL you want the request to route to. Your form will then post to that URL. Posted form values are mapped to parameters of an action method automatically, so don't worry about not having that data passed to your action method. A: My understanding is that this is how HTML works. If you do a <form url="foo" method="get"> and post the form, then the form will post foo? param1=value1&...&paramn=valuen It has nothing to do with MVC. Besides, what part of REST does that URL violate? It's not a pretty URL, but by strict definition of REST, it can be RESTful. REST doesn't specify that query parameters have to be in an URL segment. And in this case, those are query parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/8485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What's in your .procmailrc Are there any handy general items you put in your .procmailrc file? A: Just simple things - move messages to appropriate folders, forward some stuff to an email2sms address, move spam to spam folder. One thing I'm kind of proud of is how to mark your spam as "read" (this is for Courier IMAP and Maildir, where "read" means "move to different folder and change the filename"): :0 * ^X-Spam # the header our filter inserts for spam { :0 .Junk\ E-mail/ # stores in .Junk E-mail/new/ :0 * LASTFOLDER ?? /\/[^/]+$ # get the stored message's filename { tail=$MATCH } # and put it into $tail # now move the message TRAP="mv .Junk\ E-mail/new/$tail .Junk\ E-mail/cur/$tail:2,S" } A: Many mailers prefix a mail's subject with "Re: " when replying, if that prefix isn't already there. German Outlook instead prefixes with "AW: " (for "AntWort") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like "Re: AW: Re: AW: Re: AW: Re: AW: Lunch". So I now have: :0f * ^Subject: (Antwort|AW): |sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\1Re: \7\nX-Orig-Subject: \2\7/' Which curtails these (and an "Antwort: " prefix that I've evidently also been bothered by at some point) down to a single "Re: ". A: I have various filters in my .procmailrc file, but the most useful is this one, which I add to the very top of the file before I make any other changes. :0 c: mail.save This saves a copy of everything and then continues with the rest of the recipes. If I've done something wrong, my e-mail is saved in the file "mail.save". When I'm sure my changes are working, I comment these lines out, until the next time. A: To stop weird russian and chinese spams, I use this procmail configuration. UNREADABLE='[^?"]*big5|iso-2022-jp|ISO-2022-KR|euc-kr|gb2312|ks_c_5601-1987' :0: * ^Content-Type:.*multipart * B ?? $ ^Content-Type:.*^?.*charset="?($UNREADABLE) spam-unreadable
{ "language": "en", "url": "https://stackoverflow.com/questions/8493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Shelve in TortoiseSVN? I've moved from TFS to SVN (TortoiseSVN) with my current company. I really miss the "Shelve" feature of TFS. I've read various articles on how to "Shelve" with SVN, but I've read nothing that gives a very simple experience to "shelve" work. Ideally, I'd like extra items added to the TortoiseSVN context menu - "Shelve" & "Unshelve". "Shelve" would remove the current shelve-set, and upload the working directory under a suitable path defined by user options. "Unshelve" would merge the set with the working copy. Does something like this exist? Can anyone suggest any ways to "hack" this feature in the GUI? Note: The following link doesn't really achieve the user experience I was looking for: Shelving Subversion One of the greatest things about TFS Shelve is how easy it is to use... A: Another option is to use the 'Create patch' facility in TortoiseSvn to create a patch file and revert changes. The patch file can later be reapplied to get back where you were. You may still end up with some sticky merges if you have to update the working copy revision though. A: I don't believe that SVN has this feature built into the server product. I also don't believe anything like this emulated in any clients that I have used, including TortoiseSVN. To get around this problem, I have resorted to using a DVCS such as Git or Mercurial, to allow me to branch/merge/shelve locally before pushing the content back to SVN. It's arguably a bit of a kludge, but it works really well. A: SVN have upgraded the shelving https://subversion.apache.org/docs/release-notes/1.11.html#shelving The kinds of change you can shelve are committable changes to files and properties, except the following kinds which are not yet supported: * *copies and moves *creating and deleting directories A: Shelving in SVN is starting to roll out with version 1.10, see Release Notes A: If you understand how SVN branches work, emulating Shelve in SVN is a no-brainer: * *Create a branch in the repository (on the server) *Switch your local copy to it *Commit your changes to the new branch *Switch your local copy back to the trunk When you are ready to get back to your shelved changes ("unshelve"), simply merge the shelf branch back to your local copy. If you don't know command-line SVN nor Tortoise SVN well enough to do the above, here's a super detailed step-by-step instruction on how to do it in Tortoise SVN: * *Do "SVN Update" to update your working copy to the latest version of the trunk. This way the only differences between your local copy and the trunk are your changes. *From the context menu select "Branch / Tag" *"HEAD version in the repository" option is selected by default. Keep that. *Change the "To Url" to specify branch name, e.g. http://server/repository/project1/branches/shelf1 *Check the "Switch working copy to new branch/tag" box *Click Ok to create the branch and switch to it *Do "SVN Commit..." and commit your changes to the newly created branch *From the context menu select "Switch..." *Change the "To URL" to the trunk URL e.g. http://server/repository/project1/trunk *Click Ok to switch back to the trunk See this link for even more details and the command-line equivalent of the above: Shelves in Subversion A: TortoiseSVN 1.10 now supports shelving: https://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-shelving.html A: You can use a DVCS but in a way this is a kludge. 'Shelving' in a DVCS stores your changes locally only. Its useful only if you want to checkpoint your work to rollback if you break it with further work, but preferably you'd want to save your work on the server. One way to do this in SVN without an explicit shelve command is to switch your working copy to a different svn location and commit there instead of on your main repo. This is effectively like creating a temporary branch and working on that for the duration of your work. I don't think you'll even have to merge as SVN will do it for you when you switch, as your local modifications will be kept. Unfortunately, you cannot switch to a non-existent location, so the first time you do this, you'll have to create the 'branch' to shelve to. I guess the whole thing could be automated. A: Support Feature SVN supports for shelves is experimental means, it doesn't promise backward compatibility for future releases, either its disabled by default. it has been started with version 1.10 but the shelves create with 1.10 & 1.11 is not supported by newer version, as it didn't promises so. so there are different underlying and you have to pay attention that this is an experimental feature and is going to be improved over the time. the 1.10 shelve commands start with svn shelve but the 1.11 & 1.12 starts with svn x-shelve. Commands the commands for new shelve are: svn x-shelf-diff svn x-shelf-drop svn x-shelf-list, x-shelves svn x-shelf-list-by-paths svn x-shelf-log svn x-shelf-save svn x-shelve svn x-unshelve Activating for activating using this feature you have to run the command by setting the enviourment variable: #Shelving-v3, as introduced in 1.12 SVN_EXPERIMENTAL_COMMANDS=shelf3 #Shelving-v2, as introduced in 1.11 SVN_EXPERIMENTAL_COMMANDS=shelf2 further information can be found here: https://subversion.apache.org/docs/release-notes/1.14.html#shelving
{ "language": "en", "url": "https://stackoverflow.com/questions/8496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: How should I monitor potential threats to my site? By looking at our DB's error log, we found that there was a constant stream of almost successful SQL injection attacks. Some quick coding avoided that, but how could I have setup a monitor for both the DB and Web server (including POST requests) to check for this? By this I mean if there are off the shelf tools for script-kiddies, are there off the shelf tools that will alert you to their sudden random interest in your site? A: Funnily enough, Scott Hanselman had a post on UrlScan today which is one thing you could do to help monitor and minimize potential threats. It's a pretty interesting read. A: UrlScan does seem like a nice option for iis6 and 7; I also found: dotDefender for pay which also covers Apache or IIS 5-7, and I had found an SQL Injection sanitation ISAPI It is also worth noting in light of a recent wide spread SQL Injection attempt that dissallowing your webapp's db user account from querying the system tables (in MS SQL Server it's sysobjects and syscolumns) is a good idea. I think this thread warrants more free solutions for Apache and other web servers. Unfortunately intrusion detection was not what I had in mind, so sgfree isn't exactly a web site attack monitor, unless I'm not understanding how it works. A: If you could go back and modify your app code, I'd suggest getting log4j/log4net integrated into the application. From there you could write code that would check a form field or URL (say at the global.asax level for .NET apps) and make a log entry when malicious code is detected. The nice thing about log4j/log4net is that you can configure an e-mail/pager/SMS type appender so as soon as the malicious attempt was caught, you would be notified. I'm in the process of merging some log4net code into our CMS system we have and I'm looking to do just this in light of the influx of ASPRox attacks that have been coming our way. A: Monitoring web and DB access logs should alert you to things like this, but if you want a more fully featured alert system I would suggest some kind of IDS/IPS. You'll need a spare machine though, and a switch that can do port mirroring. If you have those then an IDS is a cheap way of monitoring your traffic for many intrusion attempts (there will be lots). Snort (www.snort.org) based IDSes are excellent, and there are some free fully packaged versions available. One I have used is StrataGuard (http://sgfree.stillsecure.com/), and it can be configured as an IDS (Intrusion Detection System) or as an IPS (Intrusion Prevention System). It's free to use if your traffic does not exceed 5Mbps. If you do go with an IDS/IPS I'd advise you to let it run as a simple IDS for a month or so, before you allow it to prevent attacks. This may be overkill, but if you have a spare machine lying around it can't hurt to have an IDS running passively. A: You can set up your system to kick out some error message that then makes a JSON or http call to a system that will monitor, report (log) and send out any kind of alert such as SMS/email or a phone call. Check out developer.alertcaster.com Especially if you need to monitor multiple simultaneous events, which it sounds like you have going on, this might be a good fix.
{ "language": "en", "url": "https://stackoverflow.com/questions/8508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Lucene exact ordering I've had this long term issue in not quite understanding how to implement a decent Lucene sort or ranking. Say I have a list of cities and their populations. If someone searches "new" or "london" I want the list of prefix matches ordered by population, and I have that working with a prefix search and an sort by field reversed, where there is a population field, IE New Mexico, New York; or London, Londonderry. However I also always want the exact matching name to be at the top. So in the case of "London" the list should show "London, London, Londonderry" where the first London is in the UK and the second London is in Connecticut, even if Londonderry has a higher population than London CT. Does anyone have a single query solution? A: dlamblin,let me see if I get this correctly: You want to make a prefix-based query, and then sort the results by population, and maybe combine the sort order with preference for exact matches. I suggest you separate the search from the sort and use a CustomSorter for the sorting: Here's a blog entry describing a custom sorter. The classic Lucene book describes this well. A: API for Sortcomparator says There is a distinct Comparable for each unique term in the field - if some documents have the same term in the field, the cache array will have entries which reference the same Comparable You can apply a FieldSortedHitQueue to the sortcomparator which has a Comparator field for which the api says ... Stores a comparator corresponding to each field being sorted by. Thus the term can be sorted accordingly A: My current solution is to create an exact searcher and a prefix searcher, both sorted by reverse population, and then copy out all my hits starting from the exact hits, moving to the prefix hits. It makes paging my results slightly more annoying than I think it should be. Also I used a hash to eliminate duplicates but later changed the prefix searcher into a boolean query of a prefix search (MUST) with an exact search (MUST NOT), to have Lucene remove the duplicates. Though this seemed even more wasteful. Edit: Moved to a comment (since the feature now exists): Yuval F Thank you for your blog post ... How would the sort comparator know that the name field "london" exactly matches the search term "london" if it cannot access the search term?
{ "language": "en", "url": "https://stackoverflow.com/questions/8517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: With Lucene: Why do I get a Too Many Clauses error if I do a prefix search? I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a Too Many Clauses error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query. Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries? A: I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite() From: http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html public Query rewrite(IndexReader reader) throws IOException Expert: called to re-write queries into primitive queries. For example, a PrefixQuery will be rewritten into a BooleanQuery that consists of TermQuerys. Throws: IOException A: The API reference page of TooManyClauses shows that PrefixQuery, FuzzyQuery, WildcardQuery, and RangeQuery are expanded this way (into BooleanQuery). Since it is in the API reference, it should be a behavior that users can rely on. Lucene does not place arbitrary limits on the number of hits (other than a document ID being an int) so a "too many hits" exception might not make sense. Perhaps PrefixQuery.rewrite(IndexReader) should catch the TooManyClauses and throw a "too many prefixes" exception, but right now it does not behave that way. By the way, another way to search by prefix is to use PrefixFilter. Either filter your query with it or wrap the filter with a ConstantScoreQuery. A: When running a prefix query, Lucene searches for all terms in its "dictionary" that match the query. If more than 1024 (by default) match, the TooManyClauses-Exception is thrown. You can call BooleanQuery.setMaxClauseCount to increase the maximum number of clauses permitted per BooleanQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/8532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Closet server versus Colo? As a programmer I need a place to store my stuff. I've been running a server in my parents closet for a long time, but I recently came across a decent 2U server. I have no experience dealing with hosting companies, beyond the very cheap stuff, and I'm wondering what I should look for in a colo or if I should just keep my closet server. A: There are three major factors here. * *Cost. The colo will obviously be more expensive than sticking a server in your parents' closet. *Quality. The colo should be a lot more reliable than the server in your parents' closet. They aren't as likely to go down when there's a power surge. They should provide some support if things do go wrong on their end. They will also likely give you better bandwidth. *Convenience. It is a lot easier to fix a broken box when you can walk over to it and plug up a monitor. Going to the colo to troubleshoot is probably not going to be convenient, if it's even possible. Transferring files from your laptop to the server in the closet is also going to be a lot faster than transferring over the Internet. On the other hand, if it's your box in the closet, you have to deal with the hardware problems, so it can balance out. Personally, I pay for a (shared) server. I find that having someone else handle the server is worth it. Uploading large files can get really frustrating, but having to maintain an extra box in the closet is too much hassle for me. You really have to decide what you value most. Is it worth the extra money to you to have a more reliable, more hands-off server? A: If it were my source control server, I would not want to a) pay the added cost, or b)have to drive to the colo because I can't connect to my repository. A: I'd absolutely go for the server that's located under my roof, as long as I don't need it to be connected to the internet with a static IP. Why: * *It's a target for hackers, as soon as it is reachable from the net *Any problems with the machine? I'd rather walk to the closet instead of calling a hotline - and probably pay for the service *Connection speed (from me to the server) *I can turn it off as long as I don't need it. Less power consuption, which is better for the environment. *The hosting of a machine costs money all the time. Even when you don't need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/8545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a "try to lock, skip if timed out" operation in C#? I need to try to lock on an object, and if its already locked just continue (after time out, or without it). The C# lock statement is blocking. A: I believe that you can use Monitor.TryEnter(). The lock statement just translates to a Monitor.Enter() call and a try catch block. A: Consider using AutoResetEvent and its method WaitOne with a timeout input. static AutoResetEvent autoEvent = new AutoResetEvent(true); if(autoEvent.WaitOne(0)) { //start critical section Console.WriteLine("no other thread here, do your job"); Thread.Sleep(5000); //end critical section autoEvent.Set(); } else { Console.WriteLine("A thread working already at this time."); } See https://msdn.microsoft.com/en-us/library/cc189907(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/cc190477(v=vs.110).aspx A: You'll probably find this out for yourself now that the others have pointed you in the right direction, but TryEnter can also take a timeout parameter. Jeff Richter's "CLR Via C#" is an excellent book on details of CLR innards if you're getting into more complicated stuff. A: I had the same problem, I ended up creating a class TryLock that implements IDisposable and then uses the using statement to control the scope of the lock: public class TryLock : IDisposable { private object locked; public bool HasLock { get; private set; } public TryLock(object obj) { if (Monitor.TryEnter(obj)) { HasLock = true; locked = obj; } } public void Dispose() { if (HasLock) { Monitor.Exit(locked); locked = null; HasLock = false; } } } And then use the following syntax to lock: var obj = new object(); using (var tryLock = new TryLock(obj)) { if (tryLock.HasLock) { Console.WriteLine("Lock acquired.."); } } A: Ed's got the right function for you. Just don't forget to call Monitor.Exit(). You should use a try-finally block to guarantee proper cleanup. if (Monitor.TryEnter(someObject)) { try { // use object } finally { Monitor.Exit(someObject); } } A: Based on Dereks answer a little helper method: private bool TryExecuteLocked(object lockObject, Action action) { if (!Monitor.TryEnter(lockObject)) return false; try { action(); } finally { Monitor.Exit(lockObject); } return true; } Usage: private object _myLockObject; private void Usage() { if (TryExecuteLocked(_myLockObject, ()=> DoCoolStuff())) { Console.WriteLine("Hurray!"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/8546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: Visual Studio refactoring: Remove method Is there any Visual Studio Add-In that can do the remove method refactoring? Suppose you have the following method: Result DoSomething(parameters) { return ComputeResult(parameters); } Or the variant where Result is void. The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call. A: If I understand the question, then Resharper calls this 'inline method' - Ctrl - R + I A: When it comes to refactoring like that, try out ReSharper. Just right click on the method name, click "Find usages", and refactor until it cannot find any references. And as dlamblin mentioned, the newest version of ReSharper has the possibility to inline a method. That should do just what you need. A: I would do it the simpliest way: * *rename ComputeResult method to ComputeResultX *rename DoSomething method to ComputeResult *remove DoSomething method (which is now ComputeResult) *rename ComputeResultX method back to ComputeResult Maybe VS will show some conflict because of the last rename, but ignore it. By "rename" I mean: overwrite the name of the method and after it use the dropdown (Shift+Alt+F10) and select "rename". It will replace all occurences with the new name. A: There are a few products available to add extra refactoring options to Visual Studio 2005 & 2008, a few of the better ones are Refactor! Pro and Resharper. As far as remove method, there is a description in the canonical Refactoring book about how to do this incrementally. Personally, I follow a pattern something along these lines (assume that compiling and running unit tests occurs between each step): * *Create the new method *Remove the body of the old method, change it to call the new method *Search for all references to the old method (right click the method name and select "Find all Reference"), change them to calls to the new method *Mark the old method as [Obsolete] (calls to it will now show up as warnings during the build) *Delete the old method A: You can also right click the method name and click "Find all References" in Visual Studio. I personally would just do a CTRL + SHIFT + H to Find & Replace A: ReSharper is definitely the VS 2008 plug in to have for refactoring. However it does not do this form of refactoring in one step; you will have to Refactor->rename DoSomething to ComputeResult and ignore the conflict with the real ComputeResult. Then delete the definition which was DoSomething. It's almost one step. However maybe it can do it one step. If I read that correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/8549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Best way to access a control on another form in Windows Forms? First off, this is a question about a desktop application using Windows Forms, not an ASP.NET question. I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following... otherForm.Controls["nameOfControl"].Visible = false; It doesn't work the way I would expect. I end up with an exception thrown from Main. However, if I make the controls public instead of private, I can then access them directly, as so... otherForm.nameOfControl.Visible = false; But is that the best way to do it? Is making the controls public on the other form considered "best practice"? Is there a "better" way to access controls on another form? Further Explanation: This is actually a sort of follow-up to another question I asked, Best method for creating a “tree-view preferences dialog” type of interface in C#?. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface. Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.) A: The first is not working of course. The controls on a form are private, visible only for that form by design. To make it all public is also not the best way. If I would like to expose something to the outer world (which also can mean an another form), I make a public property for it. public Boolean nameOfControlVisible { get { return this.nameOfControl.Visible; } set { this.nameOfControl.Visible = value; } } You can use this public property to hide or show the control or to ask the control current visibility property: otherForm.nameOfControlVisible = true; You can also expose full controls, but I think it is too much, you should make visible only the properties you really want to use from outside the current form. public ControlType nameOfControlP { get { return this.nameOfControl; } set { this.nameOfControl = value; } } A: After reading the additional details, I agree with robcthegeek: raise an event. Create a custom EventArgs and pass the neccessary parameters through it. A: Instead of making the control public, you can create a property that controls its visibility: public bool ControlIsVisible { get { return control.Visible; } set { control.Visible = value; } } This creates a proper accessor to that control that won't expose the control's whole set of properties. A: Suppose you have two forms, and you want to hide the property of one form via another: form1 ob = new form1(); ob.Show(this); this.Enabled= false; and when you want to get focus back of form1 via form2 button then: Form1 ob = new Form1(); ob.Visible = true; this.Close(); A: I personally would recommend NOT doing it... If it's responding to some sort of action and it needs to change its appearance, I would prefer raising an event and letting it sort itself out... This kind of coupling between forms always makes me nervous. I always try to keep the UI as light and independent as possible.. I hope this helps. Perhaps you could expand on the scenario if not? A: I would handle this in the parent form. You can notify the other form that it needs to modify itself through an event. A: * *Use an event handler to notify other the form to handle it. *Create a public property on the child form and access it from parent form (with a valid cast). *Create another constructor on the child form for setting form's initialization parameters *Create custom events and/or use (static) classes. The best practice would be #4 if you are using non-modal forms. A: I agree with using events for this. Since I suspect that you're building an MDI-application (since you create many child forms) and creates windows dynamically and might not know when to unsubscribe from events, I would recommend that you take a look at Weak Event Patterns. Alas, this is only available for framework 3.0 and 3.5 but something similar can be implemented fairly easy with weak references. However, if you want to find a control in a form based on the form's reference, it's not enough to simply look at the form's control collection. Since every control have it's own control collection, you will have to recurse through them all to find a specific control. You can do this with these two methods (which can be improved). public static Control FindControl(Form form, string name) { foreach (Control control in form.Controls) { Control result = FindControl(form, control, name); if (result != null) return result; } return null; } private static Control FindControl(Form form, Control control, string name) { if (control.Name == name) { return control; } foreach (Control subControl in control.Controls) { Control result = FindControl(form, subControl, name); if (result != null) return result; } return null; } A: You can * *Create a public method with needed parameter on child form and call it from parent form (with valid cast) *Create a public property on child form and access it from parent form (with valid cast) *Create another constructor on child form for setting form's initialization parameters *Create custom events and/or use (static) classes Best practice would be #4 if you are using non-modal forms. A: With the property (highlighted) I can get the instance of the MainForm class. But this is a good practice? What do you recommend? For this I use the property MainFormInstance that runs on the OnLoad method. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using LightInfocon.Data.LightBaseProvider; using System.Configuration; namespace SINJRectifier { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { UserInterface userInterfaceObj = new UserInterface(); this.chklbBasesList.Items.AddRange(userInterfaceObj.ExtentsList(this.chklbBasesList)); MainFormInstance.MainFormInstanceSet = this; //Here I get the instance } private void btnBegin_Click(object sender, EventArgs e) { Maestro.ConductSymphony(); ErrorHandling.SetExcecutionIsAllow(); } } static class MainFormInstance //Here I get the instance { private static MainForm mainFormInstance; public static MainForm MainFormInstanceSet { set { mainFormInstance = value; } } public static MainForm MainFormInstanceGet { get { return mainFormInstance; } } } } A: Do your child forms really need to be Forms? Could they be user controls instead? This way, they could easily raise events for the main form to handle and you could better encapsulate their logic into a single class (at least, logically, they are after all classes already). @Lars: You are right here. This was something I did in my very beginning days and have not had to do it since, that is why I first suggested raising an event, but my other method would really break any semblance of encapsulation. @Rob: Yup, sounds about right :). 0/2 on this one... A: @Lars, good call on the passing around of Form references, seen it as well myself. Nasty. Never seen them passed them down to the BLL layer though! That doesn't even make sense! That could have seriously impacted performance right? If somewhere in the BLL the reference was kept, the form would stay in memory right? You have my sympathy! ;) @Ed, RE your comment about making the Forms UserControls. Dylan has already pointed out that the root form instantiates many child forms, giving the impression of an MDI application (where I am assuming users may want to close various Forms). If I am correct in this assumption, I would think they would be best kept as forms. Certainly open to correction though :) A: You should only ever access one view's contents from another if you're creating more complex controls/modules/components. Otherwise, you should do this through the standard Model-View-Controller architecture: You should connect the enabled state of the controls you care about to some model-level predicate that supplies the right information. For example, if I wanted to enable a Save button only when all required information was entered, I'd have a predicate method that tells when the model objects representing that form are in a state that can be saved. Then in the context where I'm choosing whether to enable the button, I'd just use the result of that method. This results in a much cleaner separation of business logic from presentation logic, allowing both of them to evolve more independently — letting you create one front-end with multiple back-ends, or multiple front-ends with a single back-end with ease. It will also be much, much easier to write unit and acceptance tests for, because you can follow a "Trust But Verify" pattern in doing so: * *You can write one set of tests that set up your model objects in various ways and check that the "is savable" predicate returns an appropriate result. *You can write a separate set of that check whether your Save button is connected in an appropriate fashion to the "is savable" predicate (whatever that is for your framework, in Cocoa on Mac OS X this would often be through a binding). As long as both sets of tests are passing, you can be confident that your user interface will work the way you want it to. A: This looks like a prime candidate for separating the presentation from the data model. In this case, your preferences should be stored in a separate class that fires event updates whenever a particular property changes (look into INotifyPropertyChanged if your properties are a discrete set, or into a single event if they are more free-form text-based keys). In your tree view, you'll make the changes to your preferences model, it will then fire an event. In your other forms, you'll subscribe to the changes that you're interested in. In the event handler you use to subscribe to the property changes, you use this.InvokeRequired to see if you are on the right thread to make the UI call, if not, then use this.BeginInvoke to call the desired method to update the form. A: Step 1: string regno, exm, brd, cleg, strm, mrks, inyear; protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { string url; regno = GridView1.Rows[e.NewEditIndex].Cells[1].Text; exm = GridView1.Rows[e.NewEditIndex].Cells[2].Text; brd = GridView1.Rows[e.NewEditIndex].Cells[3].Text; cleg = GridView1.Rows[e.NewEditIndex].Cells[4].Text; strm = GridView1.Rows[e.NewEditIndex].Cells[5].Text; mrks = GridView1.Rows[e.NewEditIndex].Cells[6].Text; inyear = GridView1.Rows[e.NewEditIndex].Cells[7].Text; url = "academicinfo.aspx?regno=" + regno + ", " + exm + ", " + brd + ", " + cleg + ", " + strm + ", " + mrks + ", " + inyear; Response.Redirect(url); } Step 2: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string prm_string = Convert.ToString(Request.QueryString["regno"]); if (prm_string != null) { string[] words = prm_string.Split(','); txt_regno.Text = words[0]; txt_board.Text = words[2]; txt_college.Text = words[3]; } } } A: Change modifier from public to internal. .Net deliberately uses private modifier instead of the public, due to preventing any illegal access to your methods/properties/controls out of your project. In fact, public modifier can accessible wherever, so They are really dangerous. Any body out of your project can access to your methods/properties. But In internal modifier no body (other of your current project) can access to your methods/properties. Suppose you are creating a project, which has some secret fields. So If these fields being accessible out of your project, it can be dangerous, and against to your initial ideas. As one good recommendation, I can say always use internal modifier instead of public modifier. But some strange! I must tell also in VB.Net while our methods/properties are still private, it can be accessible from other forms/class by calling form as a variable with no any problem else. I don't know why in this programming language behavior is different from C#. As we know both are using same Platform and they claim they are almost same Back end Platform, but as you see, they still behave differently. But I've solved this problem with two approaches. Either; by using Interface (Which is not a recommend, as you know, Interfaces usually need public modifier, and using a public modifier is not recommend (As I told you above)), Or Declare your whole Form in somewhere static class and static variable and there is still internal modifier. Then when you suppose to use that form for showing to users, so pass new Form() construction to that static class/variable. Now It can be Accessible every where as you wish. But you still need some thing more. You declare your element internal modifier too in Designer File of Form. While your Form is open, it can be accessible everywhere. It can work for you very well. Consider This Example. Suppose you want to access to a Form's TextBox. So the first job is declaration of a static variable in a static class (The reason of static is ease of access without any using new keywork at future). Second go to designer class of that Form which supposes to be accessed by other Forms. Change its TextBox modifier declaration from private to internal. Don't worry; .Net never change it again to private modifier after your changing. Third when you want to call that form to open, so pass the new Form Construction to that static variable-->>static class. Fourth; from any other Forms (wherever in your project) you can access to that form/control while From is open. Look at code below (We have three object. 1- a static class (in our example we name it A) 2 - Any Form else which wants to open the final Form (has TextBox, in our example FormB). 3 - The real Form which we need to be opened, and we suppose to access to its internal TextBox1 (in our example FormC). Look at codes below: internal static class A { internal static FormC FrmC; } FormB ... { '(...) A.FrmC = new FormC(); '(...) } FormC (Designer File) . . . { internal System.Windows.Forms.TextBox TextBox1; } You can access to that static Variable (here FormC) and its internal control (here Textbox1) wherever and whenever as you wish, while FormC is open. Any Comment/idea let me know. I glad to hear from you or any body else about this topic more. Honestly I have had some problems regard to this mentioned problem in past. The best way was the second solution that I hope it can work for you. Let me know any new idea/suggestion. A: public void Enable_Usercontrol1() { UserControl1 usercontrol1 = new UserControl1(); usercontrol1.Enabled = true; } /* Put this Anywhere in your Form and Call it by Enable_Usercontrol1(); Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal */
{ "language": "en", "url": "https://stackoverflow.com/questions/8566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: What's your "best practice" for the first Java EE Spring project? I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices, tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... A: First of all Spring is about modularity and works best if one focuses on writing small components that do one thing and do it well. If you follow best practices in general like: * *Defining an interface rather than abstract classes *Making types immutable *Keep dependencies as few as possible for a single class. *Each class should do one thing and do it well. Big monolithic classes suck, they are hard to test and hard to use. If your components are small and follow the dogmas above they should be easy to wire up and play with other stuff. The above points are naturally also true of the Spring framework itself. PS Dont listen to the points above, they are talking about how to do whatever. Its more important to learn how to think rather than how to do something. Humans can think, repeating something is not clever, thinking is. A: I actually quite liked Spring.. It was a fresh breeze of air in your average J2EE Java Beans.. I recommend implementing the example Spring provides: http://static.springframework.org/docs/Spring-MVC-step-by-step/ Also, I decided to go full monty and added Hibernate to my Spring application ;), because Spring provides excellent support for Hibernate... :) I do have a DON'T however, which I learned the hard way (product in production)... If you only implement the Controller interface, and return a ModelAndView object with some data as provided with the interface, Spring does garbadge collect those resources, for tries to cache those data. So be careful to put large data in those ModelAndView objects, because they will hog up your server memory for as long as the server is in the air as soon as that page has been viewed... A: Start here - I actually think it's among the best Software Dev books that I've read. Expert Spring MVC And Web Flow Learn the new Annotation-based configuration for MVC classes. This is part of Spring 2.5. Using Annotation-based classes is going to make writing Unit tests a heck of a lot easier. Also being able to cut down on the amount of XML is a good thing. Oh yeah Unit Tests - if you're using Spring, you BETTER be Unit Testing. :) Write Unit tests for all of your Web and Service Layer classes. Read up on Domain Driven Design. The fact that you can use Domain Object classes at all levels of a Spring Application means you're going to have a VERY powerful Domain Model. Leverage it. However, when using your Domain Object classes for form population, you will want to take heed of the recent security concerns around the Spring Framework. A discussion on the Server Side reveals the way to close the hole in the comments. A: Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on: * *MyProject / src / main / resources / spring / * *datasource.xml - My single data source bean. *persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans. *services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans. *controllers.xml - My Spring MVC controllers. Depends on services.xml beans. *views.xml - My view implementations. This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you. In my (limited) experience, I've seen this approach yeild the following benefits: Clearer architecture Clearly named context files gives those unfamiliar with your project structure a reasonable place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier. Helps domain design If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples: * *Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml, or put them in their own transactionPolicy.xml? Talk it over with your team. Should your transaction policy be pluggable? *Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments? Integration testing You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans). Specifically, you can annotate an integration test class as such: @ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" }) Works well with Spring IDE's Beans Graph Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph. I've used this before to give new team members a high-level overview of our application's organization. A: Whilst its been years since I have used spring, and I can't say I am a fan of it, I know that the App Fuse tool (https://java.net/projects/appfuse/) has been helpful to help people bootstrap in terms of generating all the artifacts you need to get going. A: A good way to get started is to concentrate on the "Springframework". The Spring portfolio has grown to a big pile of projects around various aspects of Enterprise Software. Stick to the core at the beginning and try to grasp the concepts. Download the latest binaries and check out Spring's petclinic example once you are familiar with the core. It gives quite a good overview of the various projects SpringSource has to offer. Although the documentation is very good, I'd recommend a book after you grasp the concepts of the core. What I've found problematic with the documentation, is that it's not in depth and can't give you all the details you need. A: "...Which technology did you use right away: AOP, complex Hibernate..." - I'd say a better question would be to ask what people did not use right away. I'd add the examples you cite to that list. Spring MVC and JDBC template would be my starting recommendations. You can go a very long way just with those. My recommendation would be to follow the Spring architectural recommendations faithfully. Use their layering ideas. Make sure that your web layer is completely detachable from the rest. You do this by letting the web tier interact with the back end only through the service layer. If you want to reuse that service layer, a good recommendation is to expose it using Spring "contract first" web services. If you start with the XML messages that you pass back and forth, your client and server can be completely decoupled. The IDE with the best Spring support is IntelliJ. It's worth spending a few bucks. A: Focus first on the heart of Spring: Dependency Injection. Once you see all the ways that DI can be used, then start thinking about the more interesting pieces like AOP, Remoting, JDBC Templates etc. So my best bit of advice is let your use of Spring grow out from the core. Best practice? If you're using the standard XML config, manage the size of individual files and comment them judiciously. You may think that you and others will perfectly understand your bean definitions, but in practice they're somewhat harder to come back to than plain old java code. Good luck! A: Spring is also very much about unit testing and therefore testability of your classes. That basically means thinking about modularization, separation of concerns, referencing a class through interfaces etc. A: If you're just looking to dabble in it a bit and see if you like it, I recommend starting with the DAO layer, using Spring's JDBC and/or Hibernate support. This will expose you to a lot of the core concepts, but do so in a way that is easy to isolate from the rest of your app. This is the route I followed, and it was good warm-up before getting into building a full application with Spring. A: With the release of Spring 2.5 and 3.0, I think one of the most important best practices to take advantage of now are the Spring annotations. Annotations for Controllers, Services, and Repositories can save you a ton of time, allow you to focus on the business logic of your app, and can potentially all you to make all of your object plain old Java objects (POJOs).
{ "language": "en", "url": "https://stackoverflow.com/questions/8569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Watch for change in ip address status Is there a way to watch for changes in the ip-address much the same as it is possible to watch for changes to files using the FileSystemWatcher? I'm connecting to a machine via tcp/ip but it takes a while until it gives me an ip-address. I would like to dim out the connect button until I have a valid ip-address. A: Check NetworkChange class. It raises an event when a network address changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/8585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Best binary XML format for JavaME Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device. And it goes without saying that it needs to be smaller than XML, and faster to parse. The data would be something akin to SVG. A: You might want to take a look at wbxml (Wireless Binary XML) it is optimized for size, and often used on mobile phones, but it is not optimized for parsing speed. A: Hessian might be an alternative worth looking at. It is a small protocol, well-suited for Java ME applications. "Hessian is a binary web service protocol that makes web services usable without requiring a large framework, and without learning a new set of protocols. Because it is a binary protocol, it is well-suited to sending binary data without any need to extend the protocol with attachments." More links: Here Here too A: What kind of data are you planning to use? I would say, that if the server is also done in Java, easiest way for small footprint is to send/receive binary data in predefined format. Just write everything in known order into DataOutputStream. But it would really depend, what what kind of data are you working on and can you define the format. Actually you should evaluate, if this kind of optimization is even needed. Maybe you target devices are not so limited. A: It very much depends on the target device. If you have JSR172 available, then you are done with the parsing, the runtime does it for you. And XML is mainly about making your own format. As was alredy stated if your goal is performance, than XML is probably not the best way to go and you will end up doing some binary stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/8599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: HTML Editor in a Windows Forms Application We are looking for a WYSIWYG editor control for our windows application (vb.net or c#) so that users can design HTML emails (to send using the SMTP objects in the dot net framework) before sending. Currently all the available editors we can find have one of the following issues: * *They rely on mshtml.dll or the web browser control which as proven for us to be unreliable as the HTML code and the editor get out of sync under windows 2000 (IE6) *They are web-based, not a windows form control *They place styles in the head of the document (see note below) Unfortunately, as this HTML email article descries the only sure way of making HTML emails to work with styles is to use them inline which now seems to be unsupported in many editors. Does anyone have any experience in this or could suggest a solution? A: I've been using this one, which goes a little lower than the WebBrowser, but still uses MSHTML, which does spit out some ugly HTML. For my purposes, I am doing a multi-tabbed editor with WYSIWYG and HTML edit mode (using ICSharp.TextEditor) with a Buffer class to update whenever tabs change. As part of that Buffer class, I actually run the HTML through HTML Tidy and a few scrub-n-replace bits to get valid XHTML. I only offer that as a solution because I, too, failed to find one that wasn't derived from MSHTML in some way and eventually just went ahead with the above solution to keep moving forward. A: The simplest HTML editor in Windows Forms could be showing a <div contenteditable="true"></div> in a WebBrowser control. It has built in support for common html text editing features like: * *Ctrl+B to make the selection bold *Ctrl+I to make the selection italic *Ctrl+U to make the selection underlined *Ctrl+A to select all text *Ctrl+C to copy selection *Ctrl+X to cut selection *Ctrl+V to paste the selection *Ctrl+K to insert a link However for a better user experience you can rely on DOM document object in WebBrower and use its execCommand method and easily run commands like Bold, Italic, Underline, InsertOrderedList, InsertUnorderedList, InsertImage, FormatBlock, ForeColor, BackColor, and etc. For example the following command inserts ordered list: webBrowser1.Document.ExecCommand("InsertOrderedList", false, null); Examlpe - Windows Forms HTML Editor Here I will share an example for a C# application and will show you easily you can implement an HTML editor. public class HtmlEditor { WebBrowser webBrowser; private dynamic doc; private dynamic contentDiv; public HtmlEditor(WebBrowser webBrowserControl, string htmlContent) { webBrowser = webBrowserControl; webBrowser.DocumentText = @"<div contenteditable=""true""></div>"; webBrowser.DocumentCompleted += (s, e) => { doc = webBrowser.Document.DomDocument; contentDiv = doc.getElementsByTagName("div")[0]; contentDiv.innerHtml = htmlContent; }; } public string HtmlContent => contentDiv.InnerHtml; public void Bold() { doc.execCommand("bold", false, null); } public void Italic() { doc.execCommand("italic", false, null); } public void Underline() { doc.execCommand("underline", false, null); } public void OrderedList() { doc.execCommand("insertOrderedList", false, null); } public void UnorderedList() { doc.execCommand("insertUnOrderedList", false, null); } public void ForeColor(Color color) { doc.execCommand("foreColor", false, ColorTranslator.ToHtml(color)); } public void BackColor(Color color) { doc.execCommand("backColor", false, ColorTranslator.ToHtml(color)); } public void InsertImage(Image image) { var bytes = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[])); var src = $"data:image/png;base64,{Convert.ToBase64String(bytes)}"; doc.execCommand("insertImage", false, src); } public void Heading(Headings heading) { doc.execCommand("formatBlock", false, $"<{heading}>"); } public enum Headings { H1, H2, H3, H4, H5, H6 } } To use this HTML Editor class, it's enough to have a WebBrowser control on a Form and initialize the editor this way: HtmlEditor editor; private void Form1_Load(object sender, EventArgs e) { var html = @"Some html content"; editor = new HtmlEditor(webBrowser1, html); } Then you can use a ToolStrip to show available commands and run the commands. For example: private void OrderedListButton_Click(object sender, EventArgs e) { editor.OrderedList(); } private void ImageButton_Click(object sender, EventArgs e) { using (var ofd = new OpenFileDialog()) { ofd.Filter = "Image files|*.png;*.jpg;*.gif;*.jpeg;*.bmp"; if (ofd.ShowDialog() == DialogResult.OK) { using (var image = Image.FromFile(ofd.FileName)) { editor.InsertImage(image); } } } } A: I also needed a WYSIWYG editor for a Windows Forms project that I was working on. I wrote about the items that I found here. Eventually, I ended up using something that I found on CodeProject: A Windows Forms based text editor with HTML output. This does violate (a) above in that it uses the WebBrowser control. However, I couldn't find anything good that didn't do this (if you don't use the WebBrowser in some way, then you basically have to write your own HTML parser and renderer in order to handle the "What-You-See" part of WYSIWYG). The good thing about this control is that the source is easily customizable, so you can take away and add formatting options as you need (and if you want the styles to all be in-line, you can do this as well). A: Instead of searching for an HTML editor, consider the option of a RichText editor (which can be much easier to create) and then convert the final text into a HTML document. Provided you are required to use a minimal set of features (bold / italics etc) both the creation of the RT editor and the conversion of the final document into HTML format shouldn't be hard. If, on the other hand, you need to use more features (such as tables), you need to study the Rich Text Format and implement the features you need. Additional resources: * *Converting RTF to HTML: http://www.codeproject.com/KB/vb/RTFToHTML.aspx *RichTextBox tips and tricks: http://www.vbforums.com/showthread.php?t=355994 A: It's my first contribution. You can use a RichTextBox. The RTF format is more than enough to create emails. I recently wrote about how to load and save to hard disk, the contents of a RichTextBox. Allows Copy and Paste. It's simple to use and with few buttons you can create your own commands. With RichTextBox1     .SelStart = 0     .SelLength = Len (. Text)     .SelColor = vbRed End With Example for loading and saving. http://danielcatala.wordpress.com/2014/01/30/como-cargar-y-guardar-archivos-richtext-con-wpf/ Private Sub btnCarga(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click Dim archivoCarga As New StreamReader("prueba.rtf") With RichTextBox1 .Selection.Select(.Document.ContentStart, RichTextBox1.Document.ContentEnd) .Selection.Load(archivoCarga.BaseStream, System.Windows.DataFormats.Rtf) End With End Sub Private Sub btnGuarda(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click Dim archivoSalida As New StreamWriter("prueba.rtf") Dim bs As Stream = archivoSalida.BaseStream With RichTextBox1 .Selection.Select(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd) .Selection.Save(bs, System.Windows.DataFormats.Rtf) End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/8604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Code crash in MS Visual Studio 2005 in RELEASE configuration I have a workspace for running an H.263 Video Encoder in a loop for 31 times i.e. the main is executed 31 times to generate 31 different encoded bit streams. This MS Visual Studio 2005 Workspace has all C source files. When i create a "DEBUG" configuration for the workspace and build and execute it, it runs fine, i.e. it generates all the 31 output files as expected. But when I set the configuration of the workspace to "RELEASE" mdoe, and repeat the process, the encoder crashes at some test case run. Now to debug this is verified following: * *Analyzed the code to see if there was any variable initialization being missed out in every run of the encoder *Checked the various Workspace(Solution) options in both the modes (DEBUG and RELEASE). There are some obvious differences, but i turned the optimization related options explicitly same in both modes. But still could not nail the problem and find a fix for that. Any pointers? -Ajit. A: It's hard to say what the problem might be without carefully inspecting the code. However... One of the differences between debug and release builds is how the function call stack frame is set up. There are certain classes of bad things you can do (like calling a function with the wrong number of arguments) that are not fatal in a debug build but crash horribly in a release build. Perhaps you could try changing the stack frame related options (I forget what they're called, sorry) in the release build to the same as the debug build and see whether that helps. Another thing might be to enable all the warnings you possibly can, and fix them all. A: Could be a concurrency problem of two threads. The DEBUG configuration slows the execution down, so the problem does not occur. But, only a guess. A: Interesting problem.. Are you sure you have no conditional compilation code lurking around that is not being compiled in release mode? i.e: #if (DEBUG) // Debug Code here #else // Release Code here #endif Thats the only thing I can really think of.. Never experienced anything like this myself.. A: Can you add the debug symbols to the release build and run it in the debugger to see where and why it crashed? A: Yeah, those bastard crashes are the hardest to fix. Fortunatly, there are some steps you can do that will give you clues before you resort to manually looking at the code and hope to find the needle. When does it crash? At every test? At a specific test? What does that test does that the others don't? What's the error? If it's an access violation, is there a pattern to where it happens? If the addresses are low, it might mean there is an uninitialised pointer somewhere. Is the program crashing with Debug configuration but without the debugger attached? If so, it's most likely a thread synchronisation problem as John Smithers pointed out. Have you tried running the code through an analyser such as Purify? It's slow but it's usually worth the wait. Try to debug the release configuration anyway. It will only dump assemblies but it can still give you an indication of what happens such as if the code pointer jumps in the middle of garbage or hits a breakpoint in an external library. Are you on an Intel architecture? If not, watch for memory alignement errors, they hard crash without warning on some architectures and those codec algorithm tend to create those situations a lot since they are overly optimized. A: Are you sure there are no precompile directives that, say, ignores some really important code in Release mode but allows them in Debug? Also, have you implemented any logging that might point out to the precise assembly that's throwing the error? A: I would look at the crash in more detail - if it's crashing in a test case, then it sounds pretty easily reproducible, which is usually most of the challenge. A: Another thing to consider: in debug mode, the variables are initialized with 0xCCCCCCCC instead of zero. That might have some nasty side effects.
{ "language": "en", "url": "https://stackoverflow.com/questions/8612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best format for displaying rendered time on a webpage I've started to add the time taken to render a page to the footer of our internal web applications. Currently it appears like this Rendered in 0.062 seconds Occasionally I get rendered times like this Rendered in 0.000 seconds Currently it's only meant to be a guide for users to judge whether a page is quick to load or not, allowing them to quickly inform us if a page is taking 17 seconds rather than the usual 0.5. My question is what format should the time be in? At which point should I switch to a statement such as Rendered in less than a second I like seeing the tenths of a second but the second example above is of no use to anyone, in fact it just highlights the limits of the calculation I use to find the render time. I'd rather not let the users see that at all! Any answers welcome, including whether anything should be included on the page. A: "Rendered instantly" sounds way better than "Rendered in less than a second". A: Rather than relying on your users to look at the page footer and to let you know if the value exceeds some patience threshold, it might be a better idea to log the page render times in a log file on the server. Once you have all that raw data, you can look for particular pages that tend to take longer than normal to render. With more detailed logging, you could also measure the elapsed times in database queries or whatever if your web app relies on external systems. A: I'm not sure there's any value in telling users how long it took for the server to render the page. It could well be worth you logging that sort of information, but they don't care. If it takes the server 0.001 of a second to draw the page but it takes 17 seconds for them to load it (due to network, javascript, page size, their rubbish PC, etc) their perception will be the latter. Then again adding the render time might help you fend off the enquiries about any percieved slowness with a "talk to your local network admin" response. Given that you know the accuracy of your measurements you could have the 0.000 text be "Rendered in less than a thousandth of a second" A: I think I over-emphasized it was for the users. I know by using in trace in the web.config I can get accurate information on page render times along with times for accessing the database. We have in the past had problems with applications running too slowly over the network although it's now fixed I'm adding the label to new applications so that users are aware it is something we are taking seriously and it's a very simple indicator for the developers. Taking all that into account I like "Rendered Instantly" and write a lot of sense so I'll accept both your answer and kokos'. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/8624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generic type conversion FROM string I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add typed properties, so that the "value" returned is always of the type that I want it to be. The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion). So, I have created a class which is (roughly) this: public class TypedProperty<DataType> : Property { public DataType TypedValue { get { // Having problems here! } set { base.Value = value.ToString();} } } So the question is: Is there a "generic" way to convert from string back to a primitive? I can't seem to find any generic interface that links the conversion across the board (something like ITryParsable would have been ideal!). A: lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz" Usage first: TConverter.ChangeType<T>(StringValue); The class is below. public static class TConverter { public static T ChangeType<T>(object value) { return (T)ChangeType(typeof(T), value); } public static object ChangeType(Type t, object value) { TypeConverter tc = TypeDescriptor.GetConverter(t); return tc.ConvertFrom(value); } public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter { TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC))); } } A: With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth. public static class ConversionExtensions { public static object Convert(this object value, Type t) { Type underlyingType = Nullable.GetUnderlyingType(t); if (underlyingType != null && value == null) { return null; } Type basetype = underlyingType == null ? t : underlyingType; return System.Convert.ChangeType(value, basetype); } public static T Convert<T>(this object value) { return (T)value.Convert(typeof(T)); } } Examples string stringValue = null; int? intResult = stringValue.Convert<int?>(); int? intValue = null; var strResult = intValue.Convert<string>(); A: I am not sure whether I understood your intentions correctly, but let's see if this one helps. public class TypedProperty<T> : Property where T : IConvertible { public T TypedValue { get { return (T)Convert.ChangeType(base.Value, typeof(T)); } set { base.Value = value.ToString();} } } A: You could possibly use a construct such as a traits class. In this way, you would have a parameterised helper class that knows how to convert a string to a value of its own type. Then your getter might look like this: get { return StringConverter<DataType>.FromString(base.Value); } Now, I must point out that my experience with parameterised types is limited to C++ and its templates, but I imagine there is some way to do the same sort of thing using C# generics. A: Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion. Seems to work for me: public object Get( string _toparse, Type _t ) { // Test for Nullable<T> and return the base type instead: Type undertype = Nullable.GetUnderlyingType(_t); Type basetype = undertype == null ? _t : undertype; return Convert.ChangeType(_toparse, basetype); } public T Get<T>(string _key) { return (T)Get(_key, typeof(T)); } public void test() { int x = Get<int>("14"); int? nx = Get<Nullable<int>>("14"); } A: For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection: MethodInfo m = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } ); if (m != null) { return m.Invoke(null, new object[] { base.Value }); } A: TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value) TypeDescriptor is class having method GetConvertor which accept a Type object and then you can call ConvertFrom method to convert the value for that specified object. A: I used lobos answer and it works. But I had a problem with the conversion of doubles because of the culture settings. So I added return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture); A: public class TypedProperty<T> : Property { public T TypedValue { get { return (T)(object)base.Value; } set { base.Value = value.ToString();} } } I using converting via an object. It is a little bit simpler. A: Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable. public class TypedProperty<T> : Property where T : IConvertible { public T TypedValue { get { if (base.Value == null) return default(T); var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); return (T)Convert.ChangeType(base.Value, type); } set { base.Value = value.ToString(); } } } A: You can do it in one line as below: YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass)); Happy coding ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/8625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "275" }
Q: Globus Toolkit virtual machine Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development. A: The Virtual Data Toolkit is not a virtual machine image, but it is a nice distro of tons of grid tools (including Globus) which is very easy to install. I use it all the time, and love it. From their website: The Virtual Data Toolkit (VDT) is an ensemble of grid software that can be easily installed and configured. In our experience, installing grid software from scratch is challenging and time consuming. The goal of the VDT is to make it as easy as possible for users to deploy, maintain and use grid software. Ideally, you just type a single-command and you can immediately access grid resources or provide your resources to others. In reality, it is a bit more work than that, but not much. ... The VDT contains a wide variety of grid software as well as the software that it depends on. For example, the VDT includes common grid software like Condor-G ® and Globus ®, and VOMS, and much more. But it also provides supporting software like Apache, Tomcat, and MySQL. There are also many other software components that help run grid sites, like software to update CA certificate revocation lists (fetch-crl), software to assist with local authorization policies (GUMS) accounting software, and much more. A: The link to http://workspace.globus.org/vm/marketplace.html appears to be broken now. I think the new location is http://scienceclouds.org/marketplace/.
{ "language": "en", "url": "https://stackoverflow.com/questions/8626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I empty the recycle bin for all users from a Windows service application in c# I'm looking for a c# snippet which I can insert in a Windows service. The code must empty the recycle bin for all users on the computer. I have previously tried using SHEmptyRecycleBin (ref http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx) however the code doesn't work when ran from a windows service as the service is running with local system privileges. A: Hopefully you can't. A service running as the local machine should not be clearing my Recycle bin, ever. You could promote the service to run as an Admin account then it would have the right (and be a security risk), but why do you want to do this? It sounds like the sort of think Viruses try to do. A: I think doing something like this is against Microsoft recommended practices. What are you trying to do that requires emptying the Recycle Bin from a Windows service? A: First, have you tried running the service on an interactive user account? Maybe SHEmptyRecycleBin requires an interactive user even though it doesn't necessarily display a Window. Second, I'm not sure it's a good idea to delete other users' stuff but I guess you have a very good reason?
{ "language": "en", "url": "https://stackoverflow.com/questions/8648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Import Namespace System.Query I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page: <%@ Import Namespace="System.Query" %> However, this fails and tells me it cannot find the namespace. The type or namespace name 'Query' does not exist in the namespace 'System' I have also tried with no luck: * *System.Data.Linq *System.Linq *System.Xml.Linq I believe that .Net 3.5 is working because var hello = "Hello World" seems to work. Can anyone help please? PS: I just want to clarify that I don't use Visual Studio, I simply have a Text Editor and write my code directly into .aspx files. A: I have version 2 selected in IIS and I Well, surely that's your problem? Select 3.5. Actually, here's the real info: http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx A: What does the part of your web.config file look like? Here's what it looks like for a brand new ASP.NET 3.5 project made with Visual Studio 2008: <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> A: I found the answer :) I needed to add the following to my web.config: <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> Then I could add the following to my code: <%@ Import Namespace="System.Linq" %> @Will, Thanks for your help. I have accepted one of your answers :) A: Make sure your project is set to target 3.5, and not 2.0. As others have said, your 'var' test is a test of C#3 (i.e. VS2008), not the 3.5 framework. If you set the project framework target settings properly, you should not expect to need to manually add dll references at this point. A: The var hello stuff is compiler magic and will work without Linq. Try adding a reference to System.Core Sorry, I wasn't clear. I meant add System.Core to the web project's references, not to the page. The Import on the page are basically just using statements, allowing you to skip the namespace on the page. A: The csproj file might be missing the System.Core reference. Look for a line in the csproj file like this: <Reference Include="System" /> And add a line below it like this: <Reference Include="System.Core" />
{ "language": "en", "url": "https://stackoverflow.com/questions/8651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Numerical formatting using String.Format Are there any codes that allow for numerical formatting of data when using string.format? A: Loads, stick string.Format into Google :-) A quite good tutorial is at iduno A: Yes, you could format it this way: string.Format("Format number to: {0 : #.00}", number); string.Format("Format date to: {0 : MM/dd/yyyy}", date); A: There are a number. This MS site is probably the best place to look A: Here is another very good reference that compliments what Keith mentioned. http://www.scribd.com/doc/2547864/msnetformattingstrings A: As Keith said above. The most common one I use is currency: String.Format("{0:c}", 12000); Which would output £12,000.00
{ "language": "en", "url": "https://stackoverflow.com/questions/8653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there some way of recycling a Crystal Reports dataset? I'm trying to write a Crystal Report which has totals grouped in a different way to the main report. The only way I've been able to do this so far is to use a subreport for the totals, but it means having to hit the data source again to retrieve the same data, which seems like nonsense. Here's a simplified example: date name earnings source location ----------------------------------------------------------- 12-AUG-2008 Tom $50.00 washing cars uptown 12-AUG-2008 Dick $100.00 washing cars downtown { main report } 12-AUG-2008 Harry $75.00 mowing lawns around town total earnings for washing cars: $150.00 { subreport } total earnings for mowing lawns: $75.00 date name earnings source location ----------------------------------------------------------- 13-AUG-2008 John $95.00 dog walking downtown 13-AUG-2008 Jane $105.00 washing cars around town { main report } 13-AUG-2008 Dave $65.00 mowing lawns around town total earnings for dog walking: $95.00 total earnings for washing cars: $105.00 { subreport } total earnings for mowing lawns: $65.00 In this example, the main report is grouped by 'date', but the totals are grouped additionally by 'source'. I've looked up examples of using running totals, but they don't really do what I need. Isn't there some way of storing the result set and having both the main report and the subreport reference the same data? A: Hmm... as nice as it is to call the stored proc from the report and have it all contained in one location, however we found (like you) that you eventually hit a point where you can't get crystal to do what you want even tho the data is right there. We ended up introducing a business layer which sits under the report and rather than "pulling" data from the report we "push" the datasets to it and bind the data to the report. The advantage is that you can manipulate the data in code in datasets or objects before it reaches the report and then simply bind the data to the report. This article has a nice intro on how to setup pushing data to the reports. I understand that your time/business constraints may not allow you to do this, but if it's at all possible, I'd highly recommend it as it's meant we can remove all "coding" out of our reports and into managed code which is always a good thing. A: The only way I can think of doing this without a second run through the data would be by creating some formulas to do running totals per group. The problem I assume you are running into with the existing running totals is that they are intended to follow each of the groups that they are totaling. Since you seem to want the subtotals to follow after all of the 'raw' data this won't work. If you create your own formulas for each group that simply adds on the total from those rows matching the group you should be able to place them at the end of the report. The downside to this approach is that the resulting subtotals will not be dynamic in relationship to the groups. In other words if you had a new 'source' it would not show up in the subtotals until you added it or if you had no 'dog walking' data you would still have a subtotal for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/8669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Entity Framework vs LINQ to SQL Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework. My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference? The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own? A: There are a number of obvious differences outlined in that article @lars posted, but short answer is: * *L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema *L2S will only work with SQL Server (as far as I know) *EF allows mapping a single class to multiple tables *EF will handle M-M relationships *EF will have ability to target any ADO.NET data provider The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short. A: Neither yet supports the unique SQL 2008 datatypes. The difference from my perspective is that Entity still has a chance to construct a model around my geographic datatype in some future release, and Linq to SQL, being abandoned, never will. Wonder what's up with nHibernate, or OpenAccess... A: LINQ to SQL * *Homogeneous datasource: SQL Server *Recommended for small projects only where data structure is well designed *Mapping can be changed without recompilling with SqlMetal.exe *.dbml (Database Markup Language) *One-to-one mapping between tables and classes *Supports TPH inheritance *Doesn't support complex types *Storage-first approach *Database-centric view of a database *Created by C# team *Supported but not further improvements intended Entity Framework * *Heterogeneus datasource: Support many data providers *Recommended for all new projects except: * *small ones (LINQ to SQL) *when data source is a flat file (ADO.NET) *Mapping can be changed without recompilling when setting model and mapping files Metadata Artifact Process to Copy To Output Directory *.edmx (Entity Data Model) which contains: * *SSDL (Storage Schema Definition Language) *CSDL (Conceptual Schema Definition Language) *MSL (Mapping Specification Language) *One-to-one, one-to-many, many-to-one mappings between tables and classes *Supports inheritence: * *TPH (Table Per Hierarchy) *TPT (Table Per Type) *TPC (Table Per Concrete Class) *Supports complex types *Code-first, Model-first, Storage-first approaches *Application-centric view of a database *Created by SQL Server team *Future of Microsoft Data APIs See also: * *LINQ To SQL Vs Entity Framework *Difference between LINQ to SQL and Entity Framework *Entity Framework vs LINQ TO SQL A: I am working for customer that has a big project that is using Linq-to-SQL. When the project started it was the obvious choice, because Entity Framework was lacking some major features at that time and performance of Linq-to-SQL was much better. Now EF has evolved and Linq-to-SQL is lacking async support, which is great for highly scalable services. We have 100+ requests per second sometimes and despite we have optimized our databases, most queries still take several milliseconds to complete. Because of the synchronous database calls, the thread is blocked and not available for other requests. We are thinking to switch to Entity Framework, solely for this feature. It's a shame that Microsoft didn't implement async support into Linq-to-SQL (or open-sourced it, so the community could do it). Addendum December 2018: Microsoft is moving towards .NET Core and Linq-2-SQL isn't support on .NET Core, so you need to move to EF to make sure you can migrate to EF.Core in the future. There are also some other options to consider, such as LLBLGen. It's a mature ORM solution that exists already a long time and has been proven more future-proof then the MS data solutions (ODBC, ADO, ADO.NET, Linq-2-SQL, EF, EF.core). A: I think if you need to develop something quick with no Strange things in the middle, and you need the facility to have entities representing your tables: Linq2Sql can be a good allied, using it with LinQ unleashes a great developing timing. A: My experience with Entity Framework has been less than stellar. First, you have to inherit from the EF base classes, so say good bye to POCOs. Your design will have to be around the EF. With LinqtoSQL I could use my existing business objects. Additionally, there is no lazy loading, you have to implement that yourself. There are some work arounds out there to use POCOs and lazy loading, but they exist IMHO because EF isn't ready yet. I plan to come back to it after 4.0 A: LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5. LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1. This is a good introductory article on MSDN: Introducing LINQ to Relational Data A: I found a very good answer here which explains when to use what in simple words: The basic rule of thumb for which framework to use is how to plan on editing your data in your presentation layer. * *Linq-To-Sql - use this framework if you plan on editing a one-to-one relationship of your data in your presentation layer. Meaning you don't plan on combining data from more than one table in any one view or page. *Entity Framework - use this framework if you plan on combining data from more than one table in your view or page. To make this clearer, the above terms are specific to data that will be manipulated in your view or page, not just displayed. This is important to understand. With the Entity Framework you are able to "merge" tabled data together to present to the presentation layer in an editable form, and then when that form is submitted, EF will know how to update ALL the data from the various tables. There are probably more accurate reasons to choose EF over L2S, but this would probably be the easiest one to understand. L2S does not have the capability to merge data for view presentation. A: My impression is that your database is pretty enourmous or very badly designed if Linq2Sql does not fit your needs. I have around 10 websites both larger and smaller all using Linq2Sql. I have looked and Entity framework many times but I cannot find a good reason for using it over Linq2Sql. That said I try to use my databases as model so I already have a 1 to 1 mapping between model and database. At my current job we have a database with 200+ tables. An old database with lots of bad solutions so there I could see the benefit of Entity Framework over Linq2Sql but still I would prefer to redesign the database since the database is the engine of the application and if the database is badly designed and slow then my application will also be slow. Using Entity framework on such a database seems like a quickfix to disguise the bad model but it could never disguise the bad performance you get from such a database. A: Linq-to-SQL It is provider it supports SQL Server only. It's a mapping technology to map SQL Server database tables to .NET objects. Is Microsoft's first attempt at an ORM - Object-Relational Mapper. Linq-to-Entities Is the same idea, but using Entity Framework in the background, as the ORM - again from Microsoft, It supporting multiple database main advantage of entity framework is developer can work on any database no need to learn syntax to perform any operation on different different databases According to my personal experience Ef is better (if you have no idea about SQL) performance in LINQ is little bit faster as compare to EF reason LINQ language written in lambda. A: LINQ to SQL Entity Framework It only works with SQL Server database It can work with various databases like Oracle, DB2, MySQL, SQL Server, etc. It generates .dbml to maintain the relation It generates a .edmx file initially. The relation is maintained using 3 different files; .csdl, .msl and .ssdl It has not to support for complex types It has support for complex types It cannot generate database from model It can generate database from model It allows only one-to-one mapping between the entity classes and the relational tables/views It allows one-to-one, one-to-many, many-to-many mappings between the entity classes and relational tables/views It allows you to query data using DataContext It allows you to query data using EntitySQL, ObjectContext, DbContext It can be used for rapid application development only with SQL Server It can be used for rapid application development with RDBMS like SQL Server, Oracle, PostgreSQL, etc. A: The answers here have covered many of the differences between Linq2Sql and EF, but there's a key point which has not been given much attention: Linq2Sql only supports SQL Server whereas EF has providers for the following RDBMS's: Provided by Microsoft: * *ADO.NET drivers for SQL Server, OBDC and OLE DB Via third party providers: * *MySQL *Oracle *DB2 *VistaDB *SQLite *PostgreSQL *Informix *U2 *Sybase *Synergex *Firebird *Npgsql to name a few. This makes EF a powerful programming abstraction over your relational data store, meaning developers have a consistent programming model to work with regardless of the underlying data store. This could be very useful in situations where you are developing a product that you want to ensure will interoperate with a wide range of common RDBMS's. Another situation where that abstraction is useful is where you are part of a development team that works with a number of different customers, or different business units within an organisation, and you want to improve developer productivity by reducing the number of RDBMS's they have to become familiar with in order to support a range of different applications on top of different RDBMS's. A: I think the quick and dirty answer is that * *LINQ to SQL is the quick-and-easy way to do it. This means you will get going quicker, and deliver quicker if you are working on something smaller. *Entity Framework is the all-out, no-holds-barred way to do it. This means you will take more time up-front, develop slower, and have more flexibility if you are working on something larger. A: Here's some metrics guys... (QUANTIFYING THINGS!!!!) I took this query where I was using Entity Framework var result = (from metattachType in _dbContext.METATTACH_TYPE join lineItemMetattachType in _dbContext.LINE_ITEM_METATTACH_TYPE on metattachType.ID equals lineItemMetattachType.METATTACH_TYPE_ID where (lineItemMetattachType.LINE_ITEM_ID == lineItemId && lineItemMetattachType.IS_DELETED == false && metattachType.IS_DELETED == false) select new MetattachTypeDto() { Id = metattachType.ID, Name = metattachType.NAME }).ToList(); and changed it into this where I'm using the repository pattern Linq return await _attachmentTypeRepository.GetAll().Where(x => !x.IsDeleted) .Join(_lineItemAttachmentTypeRepository.GetAll().Where(x => x.LineItemId == lineItemId && !x.IsDeleted), attachmentType => attachmentType.Id, lineItemAttachmentType => lineItemAttachmentType.MetattachTypeId, (attachmentType, lineItemAttachmentType) => new AttachmentTypeDto { Id = attachmentType.Id, Name = attachmentType.Name }).ToListAsync().ConfigureAwait(false); Linq-to-sql return (from attachmentType in _attachmentTypeRepository.GetAll() join lineItemAttachmentType in _lineItemAttachmentTypeRepository.GetAll() on attachmentType.Id equals lineItemAttachmentType.MetattachTypeId where (lineItemAttachmentType.LineItemId == lineItemId && !lineItemAttachmentType.IsDeleted && !attachmentType.IsDeleted) select new AttachmentTypeDto() { Id = attachmentType.Id, Name = attachmentType.Name }).ToList(); Also, please know that Linq-to-Sql is 14x faster than Linq... A: I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names. This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this. A: If your database is straightforward and simple, LINQ to SQL will do. If you need logical/abstracted entities on top of your tables, then go for Entity Framework. A: Is LINQ to SQL Truly Dead? by Jonathan Allen for InfoQ.com Matt Warren describes [LINQ to SQL] as something that "was never even supposed to exist." Essentially, it was just supposed to be stand-in to help them develop LINQ until the real ORM was ready. ... The scale of Entity Framework caused it to miss the .NET 3.5/Visual Studio 2008 deadline. It was completed in time for the unfortunately named ".NET 3.5 Service Pack 1", which was more like a major release than a service pack. ... Developers do not like [ADO.NET Entity Framework] because of the complexity. ... as of .NET 4.0, LINQ to Entities will be the recommended data access solution for LINQ to relational scenarios.
{ "language": "en", "url": "https://stackoverflow.com/questions/8676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "866" }
Q: JQuery.Validate failure in Opera If you're using Opera 9.5x you may notice that our client-side JQuery.Validate code is disabled here at Stack Overflow. function initValidation() { if (navigator.userAgent.indexOf("Opera") != -1) return; $("#post-text").rules("add", { required: true, minlength: 5 }); } That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera. This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so you may see the YSOD on Opera much more than other browsers, if you forget to fill out all the fields on the form. Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for "Opera") and give it a go? A: turns out the problem was in the { debug : true } option for the JQuery.Validate initializer. With this removed, things work fine in Opera. Thanks to Jörn Zaefferer for helping us figure this out! Oh, and the $50 will be donated to the JQuery project. :) A: I can't seem to reproduce this bug. Can you give more details? I have my copy of Opera masquerading as Firefox so the validation should be executing: >>> $.browser.opera false When I go to the edit profile page and enter a malformed date, the red text comes up and says "Please enter a valid date". That's jQuery.Validate working, right? Does it only fail on certain forms/fields? This is Opera 9.51 on WinXP. Edit: testing editing on Opera. Edit: It also works when I comment out the "if ($.browser.opera) return;" line on a copy of the edit profile page I saved locally. I really can't reproduce this bug. What is your environment like? (Vista? Opera plugins?) A: I'm not up on .NET but I'm guessing YSOD implies uncaught errors, if that's the case then isn't relying on client-side validation alone a little risky? If not then errors that are caught can be converted to something useful for the Opera crowd - even if it is just a Screen Of Death painted white with validation grumbles ...
{ "language": "en", "url": "https://stackoverflow.com/questions/8681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Advancing through relative dates using strtotime() I'm trying to use strtotime() to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click. Example: * *It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th. *I click the "-1 day" button again and now the readout states the 8th day. *I click the "+1 day" button and now the readout states it's the 9th. I understand the buttons and the displaying the date and using $_GET and PHP to pass info, but how do I get strtotime() to work on the relative date from the last time the time travel script was called? My work so far has let me show yesterday and today relative to now but not relative to, for example, the day before yesterday, or the day after tomorrow. Or if I use my "last monday" button, the day before or after whatever that day is. A: Working from previous calls to the same script isn't really a good idea for this type of thing. What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it) Example http://www.site.com/addOneDay.php?date=1999-12-31 <?php echo Date("Y-m-d",(strtoTime($_GET[date])+86400)); ?> Please note that you should check to make sure that isset($_GET[date]) before as well If you really want to work from previous calls to the same script, you're going to have to do it with sessions, so please specify if that is the case. A: Kevin, you work off a solid absolute base (i.e. a date / time), not a relative time period. You then convert to the relative time periods. So, for example, by default, if you were showing a calendar, you'd work from todays date. int strtotime ( string $time [, int $now ] ) You can see in the function definition here of strtotime, the second argument is now, i.e. you can change the date from which it's relative. This might be easier to display through a quick loop This will loop through the last 10 days using "yesterday" as the first argument. We then use date to print it out. $time = time(); for ($i = 0; $i < 10; $i++) { $time = strtotime("yesterday", $time); print date("r", $time) . "\n"; } So pass the time/date in via the URI so you can save the relative date. A: After a moment of inspiration, the solution to my question became apparent to me (I was riding my bike). The '$now' part of strtottime( string $time {,int $now ]) needs to be set as the current date. Not "$time()-now", but "the current date I'm concerned with / I'm looking at my log for. ie: if I'm looking at the timesheet summary for 8/10/2008, then that is "now" according to strtotime(); yesterday is 8/09 and tomorrow is 8/11. Once I creep up one day, "now" is 8/11, yesterday is 8/10, and tomorrow is 8/12. Here's the code example: <?php //catch variable $givendate=$_GET['given']; //convert given date to unix timestamp $date=strtotime($givendate); echo "Date Set As...: ".date('m/d/Y',$date)."<br />"; //use given date to show day before $yesterday=strtotime('-1 day',$date); echo "Day Before: ".date('m/d/Y',$yesterday)."<br />"; //same for next day $tomorrow=strtotime('+1 day',$date); echo "Next Day: ".date('m/d/Y',$tomorrow)."<br />"; $lastmonday=strtotime('last monday, 1 week ago',$date); echo "Last Moday: ".date('D m/d/Y',$lastmonday)."<br />"; //form echo "<form method=\"get\" action=\"{$_SERVER['PHP_SELF']}\">"; //link to subtract a day echo "<a href=\"newtimetravel.php?given=".date('m/d/Y',$yesterday)."\"><< </a>"; //show current day echo "<input type=\"text\" name=\"given\" value=\"$givendate\">"; //link to add a day echo "<a href=\"newtimetravel.php?given=".date('m/d/Y',$tomorrow)."\"> >></a><br />"; //submit manually entered day echo "<input type=\"submit\" name=\"changetime\" value=\"Set Current Date\">"; //close form echo "<form><br />"; ?> Clicking on the "<<" and ">>" advances and retreats the day in question
{ "language": "en", "url": "https://stackoverflow.com/questions/8685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Install Visual Studio 2008 Sp1 on "D" Drive I am trying to install VS2008 sp1 to my work machine - it has a pathetic 10Gb C drive. The SP1 bootstrapper doesn't give the option to install items to D, only C. It needs 3Gb free and the machine only has about 700Mb. VS allowed me to install to D originally why not the SP. The only thing I can think of that it requires system files installed in Windows etc, but I can't believe there are 3Gb worth of system files? A: Worth a read: http://blogs.msdn.com/heaths/archive/2008/07/24/why-windows-installer-may-require-so-much-disk-space.aspx A: I was faced with the same problem, and ended up moving my Outlook archive.pst and the windows.edb (the new live search index file) over to D: to make room instead of trying to cram a square peg into a round hole with SP1 splitting drives. A huge help in this regard is WinDirStat, which scans a drive of your choice and identifies the size of every folder and file so that you can reveal some random large entities and move them if you can. A: If you have an empty partition, you can try to create a mounted drive (i.e. map the partition to an empty folder on the C: drive) and see whether the SP1 bootstrapper will be able to use it. A: I also ran into the same problem on a server that only has 20gb on the C: drive. I found a way to free up enough space to get the job done by reassigned the system's virtual memory allocation to use D: drive instead of C:. This freed up about 4gb in my case. On Windows XP the place to set this is in My Computer system properties, Advanced tab, Performance Options: http://support.microsoft.com/kb/308417 A: I had the same problem with VS2008 installed on a C: drive that was only 12Gb in size. I uninstalled VS2008 completely by following the manual steps in this page, and then by using the auto-uninstaller: http://msdn.microsoft.com/en-us/vstudio/bb968856.aspx I then rebooted the machine. I then re-installed VS2008 on the E: drive. I then rebooted the machine. I was then able to install SP1 - as now it did not need quite as much space on C: drive. A: When you say "10Gb C drive", do you mean it's a 10-gig disk or a partition? If the former, you should really be looking at replacing the drive - it's old, and I'd be starting to worry about how much longer it has to live. If the latter, then assuming that the C: drive restriction can't easily be worked around, then I'd look at increasing the size of the C: partition. Depending on how full the remainder of the drive is, this can take a while. I'd also be considering spending some tens of dollars ($40 or $50, I'd guess) on a partition manager from someone such as Acronis or Paragon. Kick it off just before you finish work for the day - it may take several hours, especially if the disk's fairly full. A: Are you in place upgrading your current version or have you uninstalled VS 2008 Gold? By default, the installer won't let you change the directory if any existing versions of VS are installed. To move the installation, you will need to uninstall all editions of 2008 you have installed (including any Express Editions) and then the choose installation location option should enable. A: I vaguely recall having this happen to me when I had Office 2007 installed first before VS 2008. I don't remember what options that I had installed for Office 2007. Update: I remember now it had to do with the fact that I had Visual Studio Tools for Office already installed. When I upgraded my computer I did a clean install of everything without problems by installing VS 2008 before installing Office 2007 and VSTO. So most likely you have to uninstall whatever is causing VS 2008 to want to go to a specific drive. Even if you do get it to switch drives it still is going to put a lot of stuff on the system drive. A: You could also download the full VS2008 SP1 ISO image from here. Then you can either burn it to DVD or use a tool such as Virtual CD-ROM Control Panel from Microsoft to mount the ISO as another drive. After mounting the ISO as a virtual drive, you can run the SP1 install from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/8688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: User Control Property Designer Properties For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example: private Color blah = Color.Black; public Color Blah { get { return this.blah; } set { this.blah = value; } } This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as: [DesignerCategory("Custom")] But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before... Update: @John said: DesignerCatogy is used to say if the class is a form, component etc. Try this: [Category("Custom")] Is there a particular namespace I need to use in order to get those? I've tried those exactly and the compiler doesn't recognize them. In .NETCF all I seem to have available from System.ComponentModel is: DataObject, DataObjectMethod, DefaultValue, DesignerCategory, DesignTimeVisible, EditorBrowsable The only one it doesn't scream at is EditorBrowsable A: DesignerCategory is used to say if the class is a form, component etc. For full windows the attribute you want is: [System.ComponentModel.Category("Custom")] and for the description you can use [System.ComponentModel.Description("This is the description")] To use both together: [System.ComponentModel.Category("Custom"),System.ComponentModel.Description("This is the description")] However this is part of system.dll which may be different for windows mobile. A: Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it: http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx Interesting read.. Looks like a lot of design time support was stripped out of CF because you dont design them on the devices.. Which seems kinda weird to me.. Cant imagine using a handheld as a development rig! Scroll down about half way for the good stuff ;) A: The article does not suggest that anyone is designing ON the device. However, when you create a Compact Framework project, the compact framework (for your desktop PC) is used to handle design time rendering. If you think about it that is what you expect. The same framework (or nearly so) is used to do the rendering both on your PC at design time and later on the device at runtime. The issue is that the design time attributes were not added to the compact framework (I assume to reduce the size).
{ "language": "en", "url": "https://stackoverflow.com/questions/8691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to use XPath in Python? What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website? A: The latest version of elementtree supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module. NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation). A: If you want to have the power of XPATH combined with the ability to also use CSS at any point you can use parsel: >>> from parsel import Selector >>> sel = Selector(text=u"""<html> <body> <h1>Hello, Parsel!</h1> <ul> <li><a href="http://example.com">Link 1</a></li> <li><a href="http://scrapy.org">Link 2</a></li> </ul </body> </html>""") >>> >>> sel.css('h1::text').extract_first() 'Hello, Parsel!' >>> sel.xpath('//h1/text()').extract_first() 'Hello, Parsel!' A: The lxml package supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also Amara, but I haven't used it personally. A: Sounds like an lxml advertisement in here. ;) ElementTree is included in the std library. Under 2.6 and below its xpath is pretty weak, but in 2.7+ and 3.x much improved: import xml.etree.ElementTree as ET root = ET.parse(filename) result = '' for elem in root.findall('.//child/grandchild'): # How to make decisions based on attributes: if elem.attrib.get('name') == 'foo': result = elem.text break A: Use LXML. LXML uses the full power of libxml2 and libxslt, but wraps them in more "Pythonic" bindings than the Python bindings that are native to those libraries. As such, it gets the full XPath 1.0 implementation. Native ElemenTree supports a limited subset of XPath, although it may be good enough for your needs. A: Another option is py-dom-xpath, it works seamlessly with minidom and is pure Python so works on appengine. import xpath xpath.find('//item', doc) A: Another library is 4Suite: http://sourceforge.net/projects/foursuite/ I do not know how spec-compliant it is. But it has worked very well for my use. It looks abandoned. A: PyXML works well. You didn't say what platform you're using, however if you're on Ubuntu you can get it with sudo apt-get install python-xml. I'm sure other Linux distros have it as well. If you're on a Mac, xpath is already installed but not immediately accessible. You can set PY_USE_XMLPLUS in your environment or do it the Python way before you import xml.xpath: if sys.platform.startswith('darwin'): os.environ['PY_USE_XMLPLUS'] = '1' In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are here. A: You can use: PyXML: from xml.dom.ext.reader import Sax2 from xml import xpath doc = Sax2.FromXmlFile('foo.xml').documentElement for url in xpath.Evaluate('//@Url', doc): print url.value libxml2: import libxml2 doc = libxml2.parseFile('foo.xml') for url in doc.xpathEval('//@Url'): print url.content A: libxml2 has a number of advantages: * *Compliance to the spec *Active development and a community participation *Speed. This is really a python wrapper around a C implementation. *Ubiquity. The libxml2 library is pervasive and thus well tested. Downsides include: * *Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries. *Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain. *Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic. If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2. Sample of libxml2 XPath Use import libxml2 doc = libxml2.parseFile("tst.xml") ctxt = doc.xpathNewContext() res = ctxt.xpathEval("//*") if len(res) != 2: print "xpath query: wrong node set size" sys.exit(1) if res[0].name != "doc" or res[1].name != "foo": print "xpath query: wrong node set value" sys.exit(1) doc.freeDoc() ctxt.xpathFreeContext() Sample of ElementTree XPath Use from elementtree.ElementTree import ElementTree mydoc = ElementTree(file='tst.xml') for e in mydoc.findall('/foo/bar'): print e.get('title').text A: You can use the simple soupparser from lxml Example: from lxml.html.soupparser import fromstring tree = fromstring("<a>Find me!</a>") print tree.xpath("//a/text()")
{ "language": "en", "url": "https://stackoverflow.com/questions/8692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "253" }
Q: Final managed exception handler in a mixed native/managed executable? I have an MFC application compiled with /clr and I'm trying to implement a final handler for otherwise un-caught managed exceptions. For native exceptions, overriding CWinApp::ProcessWndProcException works. The two events suggested in Jeff's CodeProject article,Application.ThreadException and AppDomain.CurrentDomain.UnhandledException, are not raised. Can anyone suggest a way to provide a final managed exception handler for a mixed executable? Update: It appears that these exception handlers are only triggered downstream of Application.Run or similar (there's a worker thread flavor, can't remember the name.) If you want to truly globally catch a managed exception you do need to install an SEH filter. You're not going to get a System.Exception and if you want a callstack you're going to have to roll your own walker. In an MSDN forum question on this topic it was suggested to override a sufficiently low-level point of the main MFC thread in a try ... catch (Exception^). For instance, CWinApp::Run. This may be a good solution but I haven't looked at any perf or stability implications. You'll get a chance to log with a call stack before you bail and you can avoid the default windows unahndled exception behavior. A: Taking a look around the internets, you'll find that you need to install a filter to get the unmanaged exceptions passing the filters on their way to your AppDomain. From CLR and Unhandled Exception Filters: The CLR relies on the SEH unhandled exception filter mechanism to catch unhandled exceptions. A: Using those two exception handlers should work. Why "should?" The events are not raised using the below: extern "C" void wWinMainCRTStartup(); // managed entry point [System::STAThread] int managedEntry( void ) { FinalExceptionHandler^ handler = gcnew FinalExceptionHandler(); Application::ThreadException += gcnew System::Threading::ThreadExceptionEventHandler( handler, &FinalExceptionHandler::OnThreadException); AppDomain::CurrentDomain->UnhandledException += gcnew UnhandledExceptionEventHandler( handler, &FinalExceptionHandler::OnAppDomainException); wWinMainCRTStartup(); return 0; } // final thread exception handler implementation void FinalExceptionHandler::OnThreadException( Object^ /* sender */, System::Threading::ThreadExceptionEventArgs^ t ) { LogWrapper::log->Error( "Unhandled managed thread exception.", t->Exception ); } // final appdomain exception handler implementation void FinalExceptionHandler::OnAppDomainException(System::Object ^, UnhandledExceptionEventArgs ^args) { LogWrapper::log->Error( "Unhandled managed appdomain exception.", (Exception^)(args->ExceptionObject) ); } BOOL CMyApp::InitInstance() { throw gcnew Exception("test unhandled"); return TRUE; } A: Using those two exception handlers should work. Are you sure you've added them in a place where they're going to be called and properly set (ie, in your application's managed entry point -- you did put one in, right?)
{ "language": "en", "url": "https://stackoverflow.com/questions/8704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Instrumenting Database Access Jeff mentioned in one of the podcasts that one of the things he always does is put in instrumentation for database calls, so that he can tell what queries are causing slowness etc. This is something I've measured in the past using SQL Profiler, but I'm interested in what strategies other people have used to include this as part of the application. Is it simply a case of including a timer across each database call and logging the result, or is there a 'neater' way of doing it? Maybe there's a framework that does this for you already, or is there a flag I could enable in e.g. Linq-to-SQL that would provide similar functionality. I mainly use c# but would also be interested in seeing methods from different languages, and I'd be more interested in a 'code' way of doing this over a db platform method like SQL Profiler. A: If a query is more then just a simple SELECT on a single table I always run it through EXPLAIN if I am on MySQL or PostgreSQL. If you are using SQL Server then Management Studio has a Display Estimated Execution Plan which is essentially the same. It is useful to see how the engine will access each table and what indexes it will use. Sometimes it will surprise you. A: Recording the database calls, the gross timing and the number of records (bytes) returned in the application is useful, but it's not going to give you all the information you need. It might show you usage patterns you were not expecting. It might show where your using "row-by-row" access instead of "set based" operations. The best tool to use is SQL Profiler and analyse the number of "Reads" vs the CPU and duration. You want to avoid high CPU queries, high Read's and long durations (duh!). The "group by reads" is a useful feature to bring to the top the nastiest queries. A: If you're writing queries in SQL Management Studio you can enter: SET STATISTICS TIME ON and SQl Server will tell you how long the individual parts of a query took to parse, compile and execute. You might be able to log this information by handling the InfoMessage event of the SqlConnection class (but I think using the SQL Profiler is much easier.) A: I would have thought that the important thing to ask here is "what database platform are you using?" For example, in Sybase, installing MDA tables might solve your problem, they provide a whole bunch of statistics from procedure call usage to average logical I/O, CPU time and index coverage. It can be as clever as you want it to be. A: I definitely see the value in using SQL Profiler while you're app is running, and EXPLAIN or SET STATISTICS will give you information about individual queries, but does anyone routinely put measurement points into their code to gather information about database queries ongoing - that would pick up on for example, a query on a table that performs fine initially, but as the number of rows grows, becomes slower and slower. If you're using MySQL or Postgre there's various tools for seeing query activity in real time, but I haven't found a tool as good as the SQL Profiler for measuring query performance over time. I'm wondering if there is (or should be?) something similar to ELMAH in the way it just plugs in and gives you information without much additional effort? A: If you're into Firebird you may want to watch sinatica.com. We'll soon launch a real-time monitoring tool for Firebird DBAs. < /shameless plug> A: If you use Hibernate (I use the Java version, I'd imagine NHibernate has something similar), you can have Hibernate collect statistics about lots of different things. See, for example: http://www.javalobby.org/java/forums/t19807.html
{ "language": "en", "url": "https://stackoverflow.com/questions/8715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Checking FTP status codes with a PHP script I have a script that checks responses from HTTP servers using the PEAR HTTP classes. However, I've recently found that the script fails on FTP servers (and probably anything that's not HTTP or HTTPS). I tried Google, but didn't see any scripts or code that returned the server status code from servers other than HTTP servers. How can I find out the status of a newsgroup or FTP server using PHP? EDIT: I should clarify that I am interested only in the ability to read from an FTP server and the directory that I specify. I need to know if the server is dead/gone, I'm not authorized to read, etc. Please note that, although most of the time I'm language agnostic, the entire website is PHP-driven, so a PHP solution would be the best for easy of maintainability and extensibility in the future. A: HTTP works slightly differently than FTP though unfortunately. Although both may look the same in your browser, HTTP works off the basis of URI (i.e. to access resource A, you have an identifier which tells you how to access that). FTP is very old school server driven. Even anonymous FTP is a bit of a hack, since you still supply a username and password, it's just defined as "anonymous" and your email address. Checking if an FTP server is up means checking * *That you can connect to the FTP server if (!($ftpfd = ftp_connect($hostname))) { ... } *That you can login to the server: if (!ftp_login($ftpfd, $username, $password)) { ... } *Then, if there are further underlying resources that you need to access to test whether a particular site is up, then use an appropiate operation on them. e.g. on a file, maybe use ftp_mdtm() to get the last modified time or on a directory, see if ftp_nlist() works. A: Wouldn't it be simpler to use the built-in PHP FTP* functionality than trying to roll your own? If the URI is coming from a source outside your control, you would need to check the protocal definition (http:// or ftp://, etc) in order to determine which functionality to use, but that is fairly trivial. If there is now protocal specified (there really should be!) then you could try to default to http. * *see here A: If you want to read specific responses you will have to open a socket and read/write data manually. <?php $sock = fsockopen($hostname, $port); ?> Then you'll have to fput/fread data back and forth. This will require you to read up on the FTP protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/8726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Delphi MDI Application and the titlebar of the MDI Children I've got an MDI application written in Delphi 2006 which runs XP with the default theme. Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window? I've tried setting the BorderStyle of the MDIChildren to bsSizeToolWin but they are still rendered as normal Forms. A: All your need - overload procedure CreateWindowHandle, like this: unit CHILDWIN; interface uses Windows, Classes, Graphics, Forms, Controls, StdCtrls; type TMDIChild = class(TForm) private { Private declarations } public { Public declarations } procedure CreateWindowHandle(const Params: TCreateParams); override; end; implementation {$R *.dfm} procedure TMDIChild.CreateWindowHandle(const Params: TCreateParams); begin inherited CreateWindowHandle(Params); SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); end; end. A: The way MDI works doesn't gel with what you're trying to do. If you need the "MDI" format, you should consider using either the built-in or a commercial docking package, and use the docking setup to mimic the MDI feel. In my Delphi apps, I frequently use TFrames and parent them to the main form, and maximizing them so they take up the client area. This gives you something similar to how Outlook looks. It goes a little something like this: TMyForm = class(TForm) private FCurrentModule : TFrame; public property CurrentModule : TFrame read FModule write SetCurrentModule; end; procedure TMyForm.SetCurrentModule(ACurrentModule : TFrame); begin if assigned(FCurrentModule) then FreeAndNil(FCurrentModule); // You could cache this if you wanted FCurrentModule := ACurrentModule; if assigned(FCurrentModule) then begin FCurrentModule.Parent := Self; FCurrentModule.Align := alClient; end; end; To use it, you can simply do this: MyForm.CurrentModule := TSomeFrame.Create(nil); There is a good argument that you should use interfaces (creating an IModule interface or something) that you use. I often do that, but it's more complex than needed to explain the concept here. HTH A: I don't think there is; in my experience, MDI in Delphi is very strictly limited and controlled by its implementation in the VCL (and perhaps also by the Windows API?). For example, don't try hiding an MDI child (you'll get an exception if you try, and you'll have to jump through a couple of API hoops to work around that), or changing the way an MDI child's main menu is merged with the host form's. Given these limitations, perhaps you should reconsider why you'd like to have special title bars in the first place? I guess there are also good reasons why this MDI stuff is standardized --- your users might appreciate it :) (PS: nice to see a Delphi question around here!) A: Thanks onnodb Unfortunately the client insists on MDI and the smaller title bar. I have worked out one way of doing it which is to hide the title bar by overriding the windows CreateParams and then create my own title bar (simple panel with some Mouse handling for moving). Works well enough so I think I might run it by the client and see if it will do...
{ "language": "en", "url": "https://stackoverflow.com/questions/8728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Getting accurate ticks from a timer in C# I'm trying to rebuild an old metronome application that was originally written using MFC in C++ to be written in .NET using C#. One of the issues I'm running into is getting the timer to "tick" accurately enough. For example, assuming an easy BPM (beats per minute) of 120, the timer should tick every .5 seconds (or 500 milliseconds). Using this as the basis for the ticks, however, isn't entirely accurate as .NET only guarantees that your timer will not tick before the elapsed time has passed. Currently, to get around this for the same 120 BPM example used above, I am setting the ticks to something like 100 milliseconds and only playing the click sound on every 5th timer tick. This does improve the accuracy quite a bit, but if feels like a bit of a hack. So, what is the best way to get accurate ticks? I know there are more timers available than the windows forms timer that is readily available in Visual Studio, but I'm not really familiar with them. A: There are three timer classes called 'Timer' in .NET. It sounds like you're using the Windows Forms one, but actually you might find the System.Threading.Timer class more useful - but be careful because it calls back on a pool thread, so you can't directly interact with your form from the callback. Another approach might be to p/invoke to the Win32 multimedia timers - timeGetTime, timeSetPeriod, etc. A quick google found this, which might be useful http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx 'Multimedia' (timer) is the buzz-word to search for in this context. A: What is the C++ application using? You can always use the same thing or wrap the timer code from C++ into a C++/CLI class. A: I have had this problem when developing a recent data-logging project. The problem with the .NET timers ( windows.forms, system.threading, and system.timer ) is that they are only accurate down to around 10 milli seconds which is due to the event scheduling built into .NET I believe. ( I am talking about .NET 2 here ). This wasn't acceptable for me and so I had to use the multimedia timer ( you need to import the dll ). I also wrote a wrapper class for all the timers and so you can switch between them if necessary using minimal code changes. Check out my blog post here: http://www.indigo79.net/archives/27 A: Another possibility is that there is a bug in WPF implementation of DispatcherTimer (there is a mismatch between milliseconds and ticks causing potential inaccuracy depending on exact process execution time) , as evidenced below: http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/DispatcherTimer.cs,143 class DispatcherTimer { public TimeSpan Interval { set { ... _interval = value; // Notice below bug: ticks1 + milliseconds [Bug1] _dueTimeInTicks = Environment.TickCount + (int)_interval.TotalMilliseconds; } } } http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/Dispatcher.cs class Dispatcher { private object UpdateWin32TimerFromDispatcherThread(object unused) { ... _dueTimeInTicks = timer._dueTimeInTicks; SetWin32Timer(_dueTimeInTicks); } private void SetWin32Timer(int dueTimeInTicks) { ... // Notice below bug: (ticks1 + milliseconds) - ticks2 [Bug2 - almost cancels Bug1, delta is mostly milliseconds not ticks] int delta = dueTimeInTicks - Environment.TickCount; SafeNativeMethods.SetTimer( new HandleRef(this, _window.Value.Handle), TIMERID_TIMERS, delta); // <-- [Bug3 - if delta is ticks, it should be divided by TimeSpan.TicksPerMillisecond = 10000] } } http://referencesource.microsoft.com/#WindowsBase/Shared/MS/Win32/SafeNativeMethodsCLR.cs,505 class SafeNativeMethodsPrivate { ... [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, NativeMethods.TimerProc lpTimerFunc); } http://msdn.microsoft.com/en-us/library/windows/desktop/ms644906%28v=vs.85%29.aspx uElapse [in] Type: UINT The time-out value, in milliseconds. // <-- milliseconds were needed eventually A: Timer classes can start behaving strangely when the timer 'tick' event code is not finished executing by the time the next 'tick' occurs. One way to combat this is to disable the timer at the beginning of the tick event, then re-enable it at the end. However, this approach is not suitable in cases where the execution time of the 'tick' code is not acceptable error in the timing of the tick, since the timer will be disabled (not counting) during that time. If disabling the timer is an option, then you can also achieve the same effect by creating a separate thread that executes, sleeps for x milliseconds, executes, sleeps, etc... A: System.Windows.Forms.Timer is limited to an accuracy of 55 milliseconds...
{ "language": "en", "url": "https://stackoverflow.com/questions/8742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Learning Version Control, and learning it well Where should I start learning about version control systems? I've used SVN, Team Foundation, and Sourcesafe in the past but I don't really feel like I grasp it completely, and my team doesn't seem to grasp it either. Which points are the most important to master? I realise this differs from VCS to VCS, but for the sake of this question we can assume that Subversion is the VCS I'm the most interested in learning about. Also, if you could, please recommend any books on the subject that you find useful. A: I found this useful Source Control HOWTO by Eric sink A: I think the most important points one has to learn regarding source control systems are the following: * *the value of small, frequent check-ins/commits *tagging, branching and merging *rollbacks *conflict resolution *exclusive vs. non-exclusive checkout *continuous integration *Test-driven development & automated unit tests vis-a-vis source control systems *forking If you've got these major concepts covered, that's pretty much most of the things you'll ever need to know for source control :) A: There are a couple of free ebooks on the subject. Try: Version Control With Subversion: Version Control with Subversion Subversion Version Control (PDF): Subversion Version Control I have read and would recommend the former. Haven't read "Subversion Version Control", but it looks pretty in-depth. A: I also, like you, never really felt a 100% comfortable with SVN or SourceSafe. Check out Mercurial. Quickstart and Cheatsheets also a great cheat sheet from DongWoo Lee (his site seems down so I scanned it and uploaded onto mine) With Mercurial everything seemed a lot more smooth and easy not sure why because it's not that different in commands to others. A: The wikipedia article on Revision Control is a great place to start Revision control When trying to teach my colleagues, I found getting him to understand the vocabulary at the end was a great way to start to introduce him to source code control techniques. Don't know what a branch is? Go find out and how they work :) There's a free online subversion book at Version Control with Subversion which provides an invaluable reference. A: To answer your question re: Which are the most important points to master I would suggest that after you get through the whole checking in and out process, rolling back to old versions and performing diffs you should take a look at branching. Branching can help you deal with the pain of being in the middle of a large change and suddenly needing to perform a bug fix and deploy it to production without the mixing in the half done stuff you are working on. A: I think the Subversion documentation is a good place to start. I found that Wikipedia doesn't really help, since it only covers a 'fundamental' point of view. In the Subversion Book that alex mentioned, I'd especially recommend Chapter 1, although that might be on a level that's too low if you already have some experience with Svn. Chapter 4 covers branching and merging in detail, but it's quite technical. What helped me a lot is the Daily Use Guide in the TortoiseSVN documentation; it covers the most important operations in a tutorial style. I guess the most important things you need to grasp are branching, merging and tagging. Understanding those takes time and practice, so I'd strongly recommend a small pet project in a local repository, so you can experiment. I think it's important to realize is that the whole system is diff-based: a merge is nothing more than automatically applying the changes that have been made in one branch to the code in another branch, instead of correcting the code yourself. Stuff like conflicts (which took me quite a lot of time to understand) are just consequences of that. But of course, I'm still learning as well :) A: I am not sure how much experience you have with version control systems, but for someone who has no prior knowledge about the concept I recommend reading the first few chapters of the Subversion book. Some of the things described there are specific to Subversion, but many of the concepts are "universal" for version control systems and how to work with them. I think it's very important that people make an effort in trying to understand the main concepts and rationales behind version control systems before starting to use them. All too often I see developers only using a small subset of their system's features because they don't understand the underlying concepts and therefore either don't see the point in using what they consider "advanced" or "unnecessary" features, or they are simply afraid to do so in fear of breaking something or causing problems for the project. Having experienced this phenomenon with many developers in the past, I recently wrote up a summary of what I consider best practices for version control on my blog. A: Read this: How Software Evolves A: Check out GIT. A talk on it here. A: IMHO, the best network resource for Configuration Management would be The ACME Project by Brad Appleton You should read about all SCM patterns and Anti patterns. All SCM technical terms are well defined on this site and there are many articles on branching techniques, agile SCM and other important stuff. This, probably, will give you enough theoretical background to handle any specific version tool. As to a Subversion book, it is probably will be the Official Subversion book which was mentioned above. It is available online for free or you can purchase a hard copy. A: IMHO, this is THE book: Berczuk's book on SCM patterns A: Version control by example by Eric Sink is good and easy to follow
{ "language": "en", "url": "https://stackoverflow.com/questions/8747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: iPhone web applications, templates, frameworks? Does anyone have any good starting points for me when looking at making web pages/sites/applications specifically for viewing on the iPhone? I've looked at templates like the one Joe Hewitt has made, and also seen some templates I can purchase, which I haven't done yet. I figured someone else had already started on this track and decided that I could probably leech on their newfound knowledge :) So, does anyone have any pointers? I'm well aware of the problem that the more such a template/framework makes a web app look like a native iPhone app, the more likely I'm going to get into trouble because it just isn't, but for now I want a framework I can start building on, and then in the process figure out how to make it distinctive enough to be perceived as a web app as well as looking like a native iPhone application. Specifically I'm looking for features like: * *stylesheets set up, or pointers to how to do them for iPhone *page flipping animation, ie. pick an item in a list, list scrolls out of view to the left and information for item scrolls in from the right *the animation part would have to work with dynamic pages, ie. not just one big page that has divs set up for each sub-item, which at least one such framework had as a sort of quick fix, I would need to have list item picking load the page for that item, and then when loaded, scroll to it Edit: To avoid people reading only the question and answering, before reading my other reply, I'll add my clarification for GPL licensing and similar issues here. The framework I need to use can not be distributed under a license which would require me to license my own project out under a similar license. The GPL family of licenses allows for exceptions regarding library usage, but this won't apply to this since by necessity, the kind of framework I would need to use would be all source code. The project can easily accomodate commercial libraries. Also, I don't need a library or a framework as such, example files that look good and aren't overly obfuscated would be welcome as well. A: I found iphone-universal on Google Code the other day. Haven't had a chance to try it out but it looks promising. A: jQtouch looks outstanding. A: The iUI library, originally from Joe Hewitt, would be a good place to start. The library is BSD licensed and has no commercial restrictions. You're right in assuming iphone-universal is not an option for you -- its actually licensed under Affero GPL which triggers the distribution clause simply by accessing the software over a network which is quite different to standard GPL. A: I'm currently looking into http://webapp.net.free.fr/. Check out the demo here. Compared to the other frameworks mentioned, it has the following advantages: * *Under active development *Active user community *Has an open license, free to distribute as long as you include the copyright/disclaimer The last point was really the winner for me. I'm looking at building something that will be included in a commercial product, so the other frameworks like iphone-universal and iwebkit (both GPL) weren't options. A: QuickConnectiPhone is LGPL so you can use it the way you want. It has a custom Dashcode project that includes the needed files. It is highly modular. It will even let you compile your JavaScript, HTML, and CSS into an installable application if you want. http://sourceforge.net/projects/quickconnect/ For more information you could look at http://tetontech.wordpress.com A: Try iwebkit http://iwebkit.net Here is a demo: http://m.iwebkit.net A: This looks good, but unfortunately it's being licensed under GPLv3, so I'm actually a bit afraid to start looking at that code. The framework I either need to find, or develop if needs be, must be able to be used as part of a commercial program, without having to license the entire program different. Commercial libraries are fine, I just haven't found any I can demo yet, presumably because I could just then steal all the code if I wanted to. Guess I'll look further, thanks for the link though. Edit: Clarification. I'd be fine with the requirement to share the source to the web framework part for the iPhone, if someone wanted it, but since this framework is all source, I'm afraid that incorporating bits of it into an existing web application (to make a skin for iPhone), I'd be making the whole web application liable for GPL license, which is totally out of the question. Even sharing all the files related to the iPhone pages is out of the question, since they will contain proprietary code. A: I've been mucking around with iUI, and find it quite good, but to be honest I haven't looked at the licencing model, so I've no idea what it is. It is very simple and straight forward though, and works well with ASP.NET MVC. A: Check out iWebkit 6. It works only on iOS 5, though :(. UPDATE You can also use saurik's. It doesn't have all of the features you said you wanted, but I'll try to see how to implement them. Also, you said you wanted to build on it. For a demo (saurik took down the actual good part of cydia.saurik.com) you can use mine on my other site. To avoid transferring all those images, just add this in the header: <link rel="stylesheet" type="text/css" href="http://cache.saurik.com/menes/style.css" /> also, add this to your CSS: body > panel > fieldset > div > a: hover { background-image: url('menutouched.png') } menutouched.png is here: This function in js slides the page. It is from Joe Hewitt’s iUI project: function swipePage(fromPage, toPage, backwards) { toPage.style.left = “100%”; toPage.setAttribute(“selected”, “true”); scrollTo(0, 1); var percent = 100; var timer = setInterval(function() { percent += animateX; if (percent <= 0) { percent = 0; fromPage.removeAttribute("selected"); clearInterval(timer); } fromPage.style.left = (backwards ? (100-percent) : (percent-100)) + "%"; toPage.style.left = (backwards ? -percent : percent) + "%"; }, animateInterval); } For loading the next page, you could try something like executing a window.location with a delay. The timing is up to you though. You also need to add this to your CSS: body { -webkit-tap-highlight-color: rgba(0,0,0,0); -webkit-user-select: none; -webkit-text-size-adjust: none; -webkit-touch-callout: none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/8756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Find out which colours are in use when using the MFC Feature pack in Office 2007 style I'm updating some of our legacy C++ code to use the "MFC feature pack" that Microsoft released for Visual Studio 2008. We've used the new classes to derive our application from CFrameWndEx, and are applying the Office 2007 styles to give our application a more modern appearance. This gives us gradient filled window titles, status bars etc, and the use of the ribbon toolbars. However, our application contains some owner drawn controls, and I'd like to update these to match the color scheme used by the feature pack. Ideally I'd like to know the light and shaded toolbar colors that are currently in use. I've had a hunt around the documentation and web and have not yet found anything. Does anyone know how to find this information out? [Edit] In particular we need to find out which colors are being used at runtime. You can change the appearance of your application at runtime using the new static function CMFCVisualManager::SetDefaultManager. The following msdn page shows you what kind of styles are available, in particular the Office2007 look: link to msdn A: Have you looked in the MFC source code, which you'll find in something like C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\src\mfc A: Looks like CMFCVisualManager offers several methods for getting color information, e.g. CMFCVisualManager::GetSmartDockingBaseGuideColors() CMFCVisualManager::GetToolbarHighlightColor() Take a look at the MSDN docs for CMFCVisualManager. Good suggestion, but unfortunately they just return various shades of grey, when currently I'm running my application with the style CMFCVisualManagerOffice2007::Office2007_LunaBlue Annoyingly the msdn help is "under construction" so doesn't even tell you what they are supposed to be doing! A: afxGlobalData contains some useful information on the current colours, brushes and fonts being used by the MFC Feature Pack. In particular I use afxGlobalData.m_clrBarFace when painting my own control bar backgrounds. (note that I am not in front of my work PC so the above syntax isn't spot on.) A: Have you tried: 2007 Office System Document: UI Style Guide for Solutions and Add Ins ? A: I guess you could use your favourite image editor and pick the colors from a screen grab. A: "I guess you could use your favourite image editor and pick the colors from a screen grab." This is essentially what I'm doing at the moment, and I've defined a list of constants from which I pull out the colours. Doesn't seem very elegant though! A: Looks like CMFCVisualManager offers several methods for getting color information, e.g. CMFCVisualManager::GetSmartDockingBaseGuideColors() CMFCVisualManager::GetToolbarHighlightColor() Take a look at the MSDN docs for CMFCVisualManager. A: @GateKiller, the OP isn't developing an Office 2007 add-in, so the UI guidelines won't really help. It's an MFC application using the Visual C++ 2008 Feature Pack which allows MFC apps to take on the Office 2007 look and feel. A: Good suggestion, but unfortunately they just return various shades of grey, when currently I'm running my application with the style CMFCVisualManagerOffice2007::Office2007_LunaBlue CMFCVisualManagerOffice2007::GetTabFrameColors - the clrFace output param is grey? Perhaps they're all masks on top of a single base hue for each theme? Assuming you can determine which color scheme is in effect with CMFCVisualManagerOffice2007::GetStyle(), perhaps you can figure out what that hue is and then do some masking with the GetxxxColor() methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/8761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Best way to play MIDI sounds using C# I'm trying to rebuild an old metronome application that was originally written using MFC in C++ to be written in .NET using C#. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks". I've found a few articles online about playing MIDI in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it should be a mostly trivial exercise. So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application? A: I think you'll need to p/invoke out to the windows api to be able to play midi files from .net. This codeproject article does a good job on explaining how to do this: vb.net article to play midi files To rewrite this is c# you'd need the following import statement for mciSendString: [DllImport("winmm.dll")] static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback); Hope this helps - good luck! A: midi-dot-net got me up and running in minutes - lightweight and right-sized for my home project. It's also available on GitHub. (Not to be confused with the previously mentioned MIDI.NET, which also looks promising, I just never got around to it.) Of course NAudio (also mentioned above) has tons of capability, but like the original poster I just wanted to play some notes and quickly read and understand the source code. A: I think it's much better to use some library that which has advanced features for MIDI data playback instead of implementing it by your own. For example, with DryWetMIDI (I'm the author of it) to play MIDI file via default synthesizer (Microsoft GS Wavetable Synth): using Melanchall.DryWetMidi.Devices; using Melanchall.DryWetMidi.Core; // ... var midiFile = MidiFile.Read("Greatest song ever.mid"); using (var outputDevice = OutputDevice.GetByName("Microsoft GS Wavetable Synth")) { midiFile.Play(outputDevice); } Play will block the calling thread until entire file played. To control playback of a MIDI file, obtain Playback object and use its Start/Stop methods (more details in the Playback article of the library docs): var playback = midiFile.GetPlayback(outputDevice); // You can even loop playback and speed it up playback.Loop = true; playback.Speed = 2.0; playback.Start(); // ... playback.Stop(); // ... playback.Dispose(); outputDevice.Dispose(); A: I'm working on a C# MIDI application at the moment, and the others are right - you need to use p/invoke for this. I'm rolling my own as that seemed more appropriate for the application (I only need a small subset of MIDI functionality), but for your purposes the C# MIDI Toolkit might be a better fit. It is at least the best .NET MIDI library I found, and I searched extensively before starting the project. A: I can't claim to know much about it, but I don't think it's that straightforward - Carl Franklin of DotNetRocks fame has done a fair bit with it - have you seen his DNRTV? A: You can use the media player: using WMPLib; //... WindowsMediaPlayer wmp = new WindowsMediaPlayer(); wmp.URL = Path.Combine(Application.StartupPath ,"Resources/mymidi1.mid"); wmp.controls.play(); A: For extensive MIDI and Wave manipulation in .NET, I think hands down NAudio is the solution (Also available via NuGet). A: A recent addition is MIDI.NET that supports Midi Ports, Midi Files and SysEx. A: Sorry this question is a little old now, but the following worked for me (somewhat copied from Win32 - Midi looping with MCISendString): [DllImport("winmm.dll")] static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback); public static void playMidi(String fileName, String alias) { mciSendString("open " + fileName + " type sequencer alias " + alias, new StringBuilder(), 0, new IntPtr()); mciSendString("play " + alias, new StringBuilder(), 0, new IntPtr()); } public static void stopMidi(String alias) { mciSendString("stop " + alias, null, 0, new IntPtr()); mciSendString("close " + alias, null, 0, new IntPtr()); } A full listing of command strings is given here. The cool part about this is you can just use different things besides sequencer to play different things, say waveaudio for playing .wav files. I can't figure out how to get it to play .mp3 though. Also, note that the stop and close command must be sent on the same thread that the open and play commands were sent on, otherwise they will have no effect and the file will remain open. For example: [DllImport("winmm.dll")] static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback); public static Dictionary<String, bool> playingMidi = new Dictionary<String, bool>(); public static void PlayMidi(String fileName, String alias) { if (playingMidi.ContainsKey(alias)) throw new Exception("Midi with alias '" + alias + "' is already playing"); playingMidi.Add(alias, false); Thread stoppingThread = new Thread(() => { StartAndStopMidiWithDelay(fileName, alias); }); stoppingThread.Start(); } public static void StopMidiFromOtherThread(String alias) { if (!playingMidi.ContainsKey(alias)) return; playingMidi[alias] = true; } public static bool isPlaying(String alias) { return playingMidi.ContainsKey(alias); } private static void StartAndStopMidiWithDelay(String fileName, String alias) { mciSendString("open " + fileName + " type sequencer alias " + alias, null, 0, new IntPtr()); mciSendString("play " + alias, null, 0, new IntPtr()); StringBuilder result = new StringBuilder(100); mciSendString("set " + alias + " time format milliseconds", null, 0, new IntPtr()); mciSendString("status " + alias + " length", result, 100, new IntPtr()); int midiLengthInMilliseconds; Int32.TryParse(result.ToString(), out midiLengthInMilliseconds); Stopwatch timer = new Stopwatch(); timer.Start(); while(timer.ElapsedMilliseconds < midiLengthInMilliseconds && !playingMidi[alias]) { } timer.Stop(); StopMidi(alias); } private static void StopMidi(String alias) { if (!playingMidi.ContainsKey(alias)) throw new Exception("Midi with alias '" + alias + "' is already stopped"); // Execute calls to close and stop the player, on the same thread as the play and open calls mciSendString("stop " + alias, null, 0, new IntPtr()); mciSendString("close " + alias, null, 0, new IntPtr()); playingMidi.Remove(alias); } A: A new player emerges: https://github.com/atsushieno/managed-midi https://www.nuget.org/packages/managed-midi/ Not much in the way of documentation, but one focus of this library is cross platform support. A: System.Media.SoundPlayer is a good, simple way of playing WAV files. WAV files have some advantages over MIDI, one of them being that you can control precisely what each instrument sounds like (rather than relying on the computer's built-in synthesizer).
{ "language": "en", "url": "https://stackoverflow.com/questions/8763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Ant build scripts, antcall, dependencies, etc I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date. So I know I need to import the utils build file. <import file="../utils/build/build.xml" /> Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file <property name="baseDirUpOne" location=".." /> <import file="${baseDirUpOne}/utils/build/build.xml" /> So now that ive solved my import problem I need to call the task, well that should be easy right: <antcall target="utils.package" /> note that in the above, utils is the project name of ../utils/build/build.xml the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially: <antcall target="utils.package" runat="../utils/build" /> The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? A: Try using the "ant" task instead of the "antcall" task, which runs the imported build directly instead of importing it into the current build file. It has a "dir" parameter: the directory to use as a basedir for the new Ant project. Defaults to the current project's basedir, unless inheritall has been set to false, in which case it doesn't have a default value. This will override the basedir setting of the called project. So you could do: <ant antfile="${baseDirUpOne}/utils/build/build.xml" dir="../utils/build" /> or something like that. A: I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it: <target name="build-tests"> <subant target="build"> <fileset dir="${test.home}" includes="build.xml"/> </subant> </target> The trick is to use subant instead of antcall. You don't have to import the other build file. A: You can pass params down to antcall using nested in the antcall block. So, you can pass the properties down that way (probably even basedir since properties are immutable).
{ "language": "en", "url": "https://stackoverflow.com/questions/8790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Is there any list datatype in MySQL stored procedures, or a way to emulate them? I would like to create a stored procedure in MySQL that took a list as argument. For example, say that I would like to be able to set multiple tags for an item in one call, then what I want to do is to define a procedure that takes the ID of the item and a list of tags to set. However, I can't seem to find any way to do this, there is no list datatype, as far as I'm aware, but can it be emulated somehow? Could the list of tags be a comma-separated string, which can somehow be split and looped over? How do you usually work with lists in MySQL stored procedures? A: This article has some good discussion on the problem of parsing an array to a stored procedure since stored procedures only allow valid table column data-types as parameters. There are some neat things you can do with the csv table type in mysql - that is if you are loading a flat file into the db. You could create a temporary table in the stored procedure, iterate over the csv list and insert it to the temp table, then create a cursor which selects the values from that table. This answer in the above mentioned thread shows a way of doing this. Generally I would split the array before I come to the database and then perform the query individually on each item. A: Depending on how complicated you want to get, you can use a generic linking table. For one of my applications there are several reports where the user might pick, for instance a list of customers to run the report on rather than just a single customer from a combo box. I have a separate table with 2 fields: * *UniqueID (guid) *ItemID The psuedo-code looks like this: GUID guid = GenerateGUID() try for each customer in customerList { INSERT(guid, customerId) } ExecuteSQLPocedure(guid) --the procedure can inner-join to the list table to get the list finally DELETE WHERE UniqueID=guid A: Not sure if these will work specifically in a SP, but there are ENUM and SET datatypes in MySQL 5 which may do what you need. http://dev.mysql.com/doc/refman/5.0/en/enum.html http://dev.mysql.com/doc/refman/5.0/en/set.html A: In my programming language of Choice, C#, I actually do this in the application itself because split() functions and loops are easier to program in C# then SQL, However! Perhaps you should look at SubString_Index() function. For example, the following would return google: SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('www.google.com', '.', -2), '.', 1);
{ "language": "en", "url": "https://stackoverflow.com/questions/8795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Best implementation for Key Value Pair Data Structure? So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable? public class TokenTree { public TokenTree() { /* I must admit to not fully understanding this, * I got it from msdn. As far as I can tell, IDictionary is an * interface, and Dictionary is the default implementation of * that interface, right? */ SubPairs = new Dictionary<string, string>(); } public string Key; public string Value; public IDictionary<string, string> SubPairs; } It's only really a simple shunt for passing around data. A: I think what you might be after (as a literal implementation of your question), is: public class TokenTree { public TokenTree() { tree = new Dictionary<string, IDictionary<string,string>>(); } IDictionary<string, IDictionary<string, string>> tree; } You did actually say a "list" of key-values in your question, so you might want to swap the inner IDictionary with a: IList<KeyValuePair<string, string>> A: There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it. Also, this structure is hardly a tree, finding a more representative name might be a good exercise. A: Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the Composite Pattern This is ideal for working with "Tree-Like Structures".. Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^ A: @Jay Mooney: A generic Dictionary class in .NET is actually a hash table, just with fixed types. The code you've shown shouldn't convince anyone to use Hashtable instead of Dictionary, since both code pieces can be used for both types. For hashtable: foreach(object key in h.keys) { string keyAsString = key.ToString(); // btw, this is unnecessary string valAsString = h[key].ToString(); System.Diagnostics.Debug.WriteLine(keyAsString + " " + valAsString); } For dictionary: foreach(string key in d.keys) { string valAsString = d[key].ToString(); System.Diagnostics.Debug.WriteLine(key + " " + valAsString); } And just the same for the other one with KeyValuePair, just use the non-generic version for Hashtable, and the generic version for Dictionary. So it's just as easy both ways, but Hashtable uses Object for both key and value, which means you will box all value types, and you don't have type safety, and Dictionary uses generic types and is thus better. A: There is an actual Data Type called KeyValuePair, use like this KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue"); A: One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications: public class TokenTree : Dictionary<string, string> { public IDictionary<string, string> SubPairs; } This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc). And yup you got the concept of the constructor right :) A: Dictionary Class is exactly what you want, correct. You can declare the field directly as Dictionary, instead of IDictionary, but that's up to you. A: Use something like this: class Tree < T > : Dictionary < T, IList< Tree < T > > > { } It's ugly, but I think it will give you what you want. Too bad KeyValuePair is sealed.
{ "language": "en", "url": "https://stackoverflow.com/questions/8800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: Cannot add WebViewer of ActiveReports to an ASP.NET page I installed ActiveReports from their site. The version was labeled as .NET 2.0 build 5.2.1013.2 (for Visual Studio 2005 and 2008). I have an ASP.NET project in VS 2008 which has 2.0 as target framework. I added all the tools in the DataDynamics namespace to the toolbox, created a new project, added a new report. When I drag and drop the WebViewer control to a page in the design view, nothing happens. No mark up is added, no report viewer is displayed on the page. Also I noticed that there are no tags related to DataDynamics components in my web.config file. Am I missing some configuration? A: I think I found the reason. While trying to get this work, I think I installed another version of the package that removed or deactivated my current version. The control I was dropping on the form belonged to the older version that had no assemblies referenced. I removed all installations of ActiveReports, installed the last version and cleaned up the toolbox. I added the latest version of the WebViewer to toolbox and dropped it on the form. It worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/8807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not showing Dialog when opening file in Acrobat Pro using Applescript When opening Adobe Acrobat Pro, whether it be through Applescript or finder, the introductory dialog is shown. Is there a way to not show this dialog without already having checked the "Don't Show Again" option when opening a document using Applescript? Photoshop and Illustrator Applescript libraries have ways of setting interaction levels and not showing dialogs, but I can't seem to find the option in Acrobat. A: Copy any applicable preferences files in ~/Library/Preferences from a machine that you have checked "Don't show again" on. A: If it's not in the dictionary, probably not.
{ "language": "en", "url": "https://stackoverflow.com/questions/8830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mod_rewrite to alias one file suffix type to another I hope I can explain this clearly enough, but if not let me know and I'll try to clarify. I'm currently developing a site using ColdFusion and have a mod_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps *.php to *.cfm). This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly. If I try to block access to *.cfm files using mod_rewrite it also returns a 404 for requests to *.php. I figure I might have to change my Apache config rather than use .htaccess A: You can use the S flag to skip the 404 rule, like this: RewriteEngine on # Do not separate these two rules so long as the first has S=1 RewriteRule (.*)\.php$ $1.cfm [S=1] RewriteRule \.cfm$ - [R=404] If you are also using the Alias option then you should also add the PT flag. See the mod_rewrite documentation for details. A: Post the rules you already have as a starting point so people don't have to recreate it to help you. I would suggest testing [L] on the rule that maps .php to .cfm files as the first thing to try. A: You have to use two distinct groups of rewrite rules, one for .php, the other for .chm and make them mutually exclusives with RewriteCond %{REQUEST_FILENAME}. And make use of the flag [L] as suggested by jj33. You can keep your rules in .htaccess.
{ "language": "en", "url": "https://stackoverflow.com/questions/8832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SharePoint - Connection String dialog box during FeatureActivated event Does anyone know if it is possible to display a prompt to a user/administrator when activating or installing a sharepoint feature? I am writing a custom webpart and it is connecting to a separate database, I would like to allow the administrator to select or type in a connection string when installing the .wsp file or activating the feature. I am looking inside the FeatureActivated event and thinking of using the SPWebConfigModification class to actually write the connection string to the web.config files in the farm. I do not want to hand edit the web.configs or hard code the string into the DLL. If you have other methods for handling connection strings inside sharepoint I would be interested in them as well. A: Unfortunately there is no way to swap to a screen where you can get user via the feature activation process. Couple of comments for you: * *I'm assuming the connection string is going to be different for every installation, so there is no way you can include it directly in the Solution. *I'm assuming that you couldn't programmatically construct this during installation. Therefore, you need some way to get user input. Here are a couple of options: * *It could be a web part property, though this would mean setting it each and every time the web part was added, and you would need to then maitain those settings individually. *You could build out your own _layouts settings screen (good post: http://community.zevenseas.com/Blogs/Robin/archive/2008/03/17/lcm-creating-custom-application-page-and-using-the-propertybag-more-detailed.aspx), and from there users can maintain the property, storing it in either the Web Property bag, or inside the Web.Config. I try to avoid using the Web.Config where I can, but if you do wish to go this route then MAKE SURE you use the SPWebConfigModification class (Read this great blog: http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32) *Finally, a technique I often use is storing configuration information in a SharePoint List. Chris O'Brien has a great framework for that here: http://www.codeplex.com/SPConfigStore Hope that helps, Daniel A: Sounds good. I will look at these possible solutions. I do not think #1 will work since I am deploying multiple webparts inside a single solution which all use the same connectionString. #3 sounds like a very clean solution. I see the config items are cached so it looks like if I need to store a connection string, I will not be hit with a SP lookup each time I need that string. While searching for a solution I did stumble across another method. If you dig around their code, I looks like they have created an installer that accepts application specific values, adds the values into a FeatureTemplate.xml file and passes them to the SPFeatureReceiverProperties object in the Reciever. I was about to start tackling this method, but I think #3 would be better. Thank you, Keith
{ "language": "en", "url": "https://stackoverflow.com/questions/8849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Difference between NULL and null in PHP Is there a difference between NULL and null in PHP? Sometimes they seem to be interchangeable and sometimes not. edit: for some reason when I read the documentation linked to in the answer (before posting this question) I read it as "case sensitive" instead of "case insensitive" which was the whole reason I posted this question in the first place... A: Either will work. But the official PHP style guide, PSR-12, recommends lowercase. https://www.php-fig.org/psr/psr-12/, Section 2.5 A: Null is case insensitive. From the documentation: There is only one value of type null, and that is the case-insensitive keyword NULL. A: There is no difference. Same type just its a case insensitive keyword. Same as True/False etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/8864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "99" }
Q: Evidence Based Scheduling Tool Are there any free tools that implement evidence-based scheduling like Joel talks about? There is FogBugz, of course, but I am looking for a simple and free tool that can apply EBS on some tasks that I give estimates (and actual times which are complete) for. A: According to Wikipedia, Fogbugz is the only product currently offering EBS. A: FogBugz is free for up to 2 users by the way. As far I know this is the only tool that does EBS. See here http://www.workhappy.net/2008/06/get-fogbugz-for.html
{ "language": "en", "url": "https://stackoverflow.com/questions/8876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Get list of domains on the network Using the Windows API, how can I get a list of domains on my network? A: Answered my own question: Use the NetServerEnum function, passing in the SV_TYPE_DOMAIN_ENUM constant for the "servertype" argument. In Delphi, the code looks like this: <snip> type NET_API_STATUS = DWORD; PSERVER_INFO_100 = ^SERVER_INFO_100; SERVER_INFO_100 = packed record sv100_platform_id : DWORD; sv100_name : PWideChar; end; function NetServerEnum( //get a list of pcs on the network (same as DOS cmd "net view") const servername : PWideChar; const level : DWORD; const bufptr : Pointer; const prefmaxlen : DWORD; const entriesread : PDWORD; const totalentries : PDWORD; const servertype : DWORD; const domain : PWideChar; const resume_handle : PDWORD ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; function NetApiBufferFree( //memory mgmt routine const Buffer : Pointer ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; const MAX_PREFERRED_LENGTH = DWORD(-1); NERR_Success = 0; SV_TYPE_ALL = $FFFFFFFF; SV_TYPE_DOMAIN_ENUM = $80000000; function TNetwork.ComputersInDomain: TStringList; var pBuffer : PSERVER_INFO_100; pWork : PSERVER_INFO_100; dwEntriesRead : DWORD; dwTotalEntries : DWORD; i : integer; dwResult : NET_API_STATUS; begin Result := TStringList.Create; Result.Clear; dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH, @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM, PWideChar(FDomainName),nil); if dwResult = NERR_SUCCESS then begin try pWork := pBuffer; for i := 1 to dwEntriesRead do begin Result.Add(pWork.sv100_name); inc(pWork); end; //for i finally NetApiBufferFree(pBuffer); end; //try-finally end //if no error else begin raise Exception.Create('Error while retrieving computer list from domain ' + FDomainName + #13#10 + SysErrorMessage(dwResult)); end; end; <snip> A: You will need to use some LDAP queries Here is some code I have used in a previous script (it was taken off the net somewhere, and I've left in the copyright notices) ' This VBScript code gets the list of the domains contained in the ' forest that the user running the script is logged into ' --------------------------------------------------------------- ' From the book "Active Directory Cookbook" by Robbie Allen ' Publisher: O'Reilly and Associates ' ISBN: 0-596-00466-4 ' Book web site: http://rallenhome.com/books/adcookbook/code.html ' --------------------------------------------------------------- set objRootDSE = GetObject("LDAP://RootDSE") strADsPath = "<GC://" & objRootDSE.Get("rootDomainNamingContext") & ">;" strFilter = "(objectcategory=domainDNS);" strAttrs = "name;" strScope = "SubTree" set objConn = CreateObject("ADODB.Connection") objConn.Provider = "ADsDSOObject" objConn.Open "Active Directory Provider" set objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope) objRS.MoveFirst while Not objRS.EOF Wscript.Echo objRS.Fields(0).Value objRS.MoveNext wend Also a C# version
{ "language": "en", "url": "https://stackoverflow.com/questions/8880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Anyone know of an on-line free database? I wrote an application that currently runs against a local instance of MySql. I would like to centralize the DB somewhere on the Net, and share my application. But, I'm cheap, and don't want to pay for it. Does anyone know of a free on-line relational DB service that I could connect to via C#? A: What about http://www.freesql.org ? Seems like you can't be too picky when you're asking for free, and this seems to offer something. A: Oops, didn't read the question properly that time! :P Haven't tried this yet, and their site says they had had a major crash recently, but it looks promising: http://www.freesql.org/ A: I've never heard of such a thing. A few years ago, many hosts (Brinkster, etc) offered some minimal database capacity with their free web hosting accounts, but I think you'd find it difficult to find something like that now. Even if you could, most hosts no longer allow you to connect to a database (even on an account you're paying for) outside of a web application running on their server. My advice would be to cobble together an old computer and use that as a database server that you run out of your house (coupled with no-ip or some similar service, probably). If you're going to need more horsepower/bandwidth than that, you'll probably just have to suck it up and pay for something. A: Have you taken a look at http://creator.zoho.com/? I haven't tested it myself but it might be a good idea to check it out. A: Sounds like you need Amazon SimpleDB... It's not free, but pricing looks pretty good. I've not used it myself, but when I've got a bit of spare time I might use it for a project I'm working on. A: Well, there is http://zymic.com/. They provide free hosting, which includes free databases. Not sure if you can connect to it from outside. You'll have to check that out.
{ "language": "en", "url": "https://stackoverflow.com/questions/8893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Use for the phppgadmin Reports Database? Phppgadmin comes with instructions for creating a reports database on the system for use with phppgadmin. The instructions describe how to set it up, but do not really give any indication of what its purpose is, and the phppgadmin site was not very helpful either. It seems to allow you to store SQL queries, so is it for storing admin queries accessing tables like pg_class etc? A: This is just a standard location to store frequently used SQL scripts. The reports-pgsql.sql script creates a table for storing these queries, the database they are intended to be run on, a title and some descriptive text about what they do. PhpPgAdmin has functionality to browse and execute these reports. It's a pretty simple system just meant to aid in organization.
{ "language": "en", "url": "https://stackoverflow.com/questions/8894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Can I get Memcached running on a Windows (x64) 64bit environment? Does anyone know IF, WHEN or HOW I can get Memcached running on a Windows 64bit environment? I'm setting up a new hosting solution and would much prefer to run a 64bit OS, and since it's an ASP.Net MVC solution with SQL Server DB, the OS is either going to be Windows Server 2003 or (hopefully!) 2008. I know that this could spill over into a debate regarding 32bit vs 64bit on servers, but let's just say that my preference is 64bit and that I have some very good reasons. So far, I've tried a number of options and found a bit of help related to getting this up on a 32bit machine (and succeeded I might add), but since the original Windows port is Win32 specific, this is hardly going to help when installing as a service on x64. It also has a dependency on the libevent for which I can only get a Win32 compiled version. I suspect that simply loading all this up in C++ and hitting "compile" (for 64bit) wouldn't work, not least because of the intricate differences in 32 and 64bit architectures, but I'm wondering if anyone is working on getting this off the ground? Unfortunately, my expertise lie in managed code (C#) only, otherwise I would try and take this on myself, but I can't believe I'm the only guy out there trying to get memcached running on a 64 bit Windows server....am I? Update Yes I'm afraid I'm still looking for an answer to this - all my efforts (with my pathetic C++ skills) to make a stable build have failed - I've trashed one server and 3 VM's just trying it out so now I turn to the real experts. Is anyone planning on porting this to 64bit? Or are you really suggesting that I use MS Velocity instead? I shudder at the thought. Update: @Lars - I do use Enyim actually - it's very good, but what you're referring to is a client, rather than the server part. @DannySmurf - I've only been able to install it as a service on a 32 bit OS. 64 bit OS rejects the installation of this Win32 service. Of course yes, lots of Win32 code works seamlessly on x64 architecture, hence you can run 32bit apps (like Office for instance) or games on Vista/XP 64 etc, but this doesn't translate directly when it comes to services. I'm no expert, I suspect that it has to do with the syncs or eventing that services need to subscribe to, and I suspect that 64 and 32 don't play nicely. I'm happy to be corrected on any of this, but to answer your question - yes I have tried. @OJ - thanks very much for the straight-forward response. I thought as much, but wasn't sure if anyone else had suggestions or had already gone down this route. Maybe when StackOverflow is LIVE, then more people will respond and let me know if this is something being looked into, and although I can try and compile it myself - I simply can't "trust" (with my C++ experience level) that it would provide "Enterprise Level" reliability in such a crucial component of large scalable solutions. I think it would need educated intervention rather than my unsanitised experimental approach before I could be confident. One little oversight on my part, could bring the site down. Oh well... till next time. A: Memcached 1.4.5 binary for win x64 can be found here: http://downloads.northscale.com/memcached-1.4.5-amd64.zip Another option would be to install Couchbase Server 1.8.0 x64 from here: http://www.couchbase.com/download, the bundled memcached seems to be version 1.7.1.1 (sounds like an internal version, I can't tell which is the real one) As for running memcached as a service, this tutorial might be enough: http://www.richardnichols.net/2010/08/install-memcached-on-windows-server/ A: Up-to-date Binaries NorthScale has really old versions (the newest is 1.4.5 which is from April 2010) but there's a guy who offers 64-bit Memcached binaries for Windows compiled using Cygwin (but they don't require it installed) in his GitHub repository github.com/nono303/memcached. For example, the binaries of the most recently released version (as of writing this answer) 1.5.16 are here. There're both 32 and 64-bit versions. Memcached as a Windows Service If you want to install it as a Windows service, you can use for example the open-source Non-Sucking Service Manager: nssm install memcached c:\path\to\memcached.exe nssm start memcached See the documentation for details. A: North Scale labs have released a build of memcached 1.4.4 for Windows x64: http://blog.couchbase.com/memcached-windows-64-bit-pre-release-available http://labs.northscale.com/memcached-packages/ UPDATE: they have recently released Memcached Server - still FREE but enhanced distro with clustering, web-based admin/stats UI etc. (I'm not related to them in any way) Check it out at http://northscale.com/products/memcached.html and download at: http://www.northscale.com/download.php?a=d UPDATE 2: NorthScale Memcached is no longer available as a standalone download. Now they have made it part of their commercial No-SQL DB offering called Membase. It can be configured to run in Memcached-only mode (i.e. without persistence) and there's a 100% free version too. Check it out here: http://www.membase.org/downloads UPDATE 3: MemBase has slept with CouchDB and produced a hybrid product offering, called CouchBase. They still do offer a free "Community" version at http://www.couchbase.com/download A: I have an memcached-1.2.1 for win32 originally downloaded from here: http://jehiah.cz/projects/memcached-win32/ (but now for some reason it is a broken link). This is how I managed to run memcached for Win32 on Windows Server 2008 R2, 64 bit. memcached.exe -> properties -> Compatibility -> Run this program in compatibility mode for: Windows XP (SP 3). Notice that the user Uriel Katz mention in this discussion that this method restricted to 2GB memory of use. A: I personally feel that you'd have to recompile the application using a 64-bit compiler (obviously on a 64-bit machine) to get the most of Memcached on a 64-bit platform. This may not be an easy task depending on the code. If it was written with 64-bit portability in mind then it could be a simple recompile. If it hasn't, then you could well be up for quite a bit of patching before getting it to build.. and then you'd have to verify that you haven't broken anything! I don't think you're overestimating the differences between 32 and 64-bit at all. A common mistake is to assume that the job is a simple recompile when in fact it isn't. There are more portability issues than most people realise. Just because the application builds and you end up with a binary, it doesn't mean that the binary is going to behave as it should. Especially when it may interact with other 32-bit code. Having said that, it might be worth giving it a spin! Good luck. Cheers! @Lars: I recommend reading the question before attempting an answer. @John Sibly & @DannySmurf: given the nature of Memcached and what it aims to achieve, surely you wouldn't want to run a 32-bit version on a 64-bit machine? If you had a 64-bit capable machine it would make sense to run a 64-bit version to make the most of the features of the hardware. A: Just so people know, the 32-bit and 64-bit version as build by the good people from membase/couchbase/whatever is still available the blog URL has changed though: 32-bit binary of memcached 1.4.4 as Windows-service: http://blog.couchbase.com/memcached-144-windows-32-bit-binary-now-available http://s3.amazonaws.com/downloads.northscale.com/memcached-win32-1.4.4-14.zip 64-bit binary of memcached 1.4.4 as Windows-service: http://blog.couchbase.com/memcached-windows-64-bit-pre-release-available http://s3.amazonaws.com/downloads.northscale.com/memcached-win64-1.4.4-14.zip The 64-bit version does have the wrong uptime. So maybe you want this binary of 1.4.2 instead: http://www.urielkatz.com/archive/detail/memcached-64-bit-windows/ The 32-bit version as included with MemCacheDManager also suppors running on Windows 2000 (no IPv6): http://allegiance.chi-town.com/MemCacheDManager.aspx http://allegiance.chi-town.com/Download.aspx?dl=Releases/MemCacheDManager_1_0_3_0.msi&rurl=MemCacheDManager.aspx To unpack the msi: msiexec /a Releases_MemCacheDManager_1_0_3_0.msi /qb TARGETDIR=c:\memcached A: I was just searching for memcached on a 64bit Windows system and found this. So far there isn't any Win64 memcached version. But I just started the memcached.exe with the appropriate commands via cmd and it's just running fine. I'm using Windows Vista 64bit, don't know if there are any differences between Vista and the server versions. Kindest regards Fleshgrinder A: The 32 bit version run on 64 bit via WOW64 but the process is still limited to 2GB,with a 64-bit version you can go beyond that to more than a single machine will have. A: FYI, I couldn't get the 64 bit version (from here http://labs.northscale.com/memcached-packages/) to install as a service until I ran memcached as administrator. I just went to the executable's properties, then the Compatibility tab, and checked "Run this program as an administrator" (There a ton of other ways to do this, but it seemed simplest) Then I was finally able to successfully run: memcached -d install Don't forget to start the service after it is installed too :) A: You could always run multiple instances of 32-bit memcached processes on one box, allowing that machine to serve a total of > 2GB memcache space. A: Are you sure that the 32-bit version doesn't just run on 64-bit Windows, without modification? Most things do. Failing that, have you actually tried just compiling it for 64-bit? A brief scan of a few Google Groups etc where people asked this same question suggests that that may be exactly the solution to this. I think you're probably overestimating the difference between 32-bit and 64-bit Windows (at least as far as compiling a native application goes).
{ "language": "en", "url": "https://stackoverflow.com/questions/8896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "90" }
Q: Looking for best practice for doing a "Net Use" in C# I'd rather not have to resort to calling the command line. I'm looking for code that can map/disconnect a drive, while also having exception handling. Any ideas? A: Use P/Invoke and WNetAddConnection2 There should also be some wrappers out there to do some of the grunt work for you. Google is your friend, as always.
{ "language": "en", "url": "https://stackoverflow.com/questions/8919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: ActionScript 3.0 sockets can't reconnect I'm having trouble connecting (via the Socket and XMLSocket classes) to a TCP listener after a connect timeout. I have a flash applet that needs to maintain a TCP connection to a server. I have implemented timeouts using Timers, a ping-pong system, etc. However, there's a problem. Upon calling Socket.connect(), the flash player (9.0.115 and many other stables before that) sends 3 connection requests by way of SYN packets, with some time in between. If none of those are replied to (e.g. because the server is down), I cannot get the applet to [attempt to] connect to the server. Ever. That is, within the lifetime of the applet. To clarify and/or summarize: For any host/port pair given to Socket.connect() or XMLSocket.connect(), if the call fails, any subsequent connect() calls to any other Socket (or XMLSocket) instances within the lifetime of the Flash applet to the same host/port pair get ignored. (At least as far as I can tell using a packet sniffer.) I have tried calling numerous Socket methods, destroying¹ and recreating the objects, using a pool of Sockets, and various other methods I can't remember right now; all to no avail. My current solution is to notify the parent webpage through a JavaScript call and let it reload my applet. It's not a pretty solution, and I'm not about to implement workarounds for the problems it causes, just because Flash can't handle socket connections properly. I must be missing something very simple. Any ideas? 1: I know you can't really destroy objects; I just remove all references to them and hope for the best. I haven't tried to explicitly invoke the GC in this case. (Though I think I did try putting the Socket inside an Array and using delete.) Yes, it works as expected if the connection is successful (even if the connection drops later on.) The only event to trigger this is the case when the server doesn't respond at all; it's as if Flash marks the host/port combination as "offline" and doesn't bother sending any more packets to it for the lifetime of the applet. I suspect an active refusal of the connection (e.g. host is online but not listening to the port) doesn't cause this. I get no error message or feedback of any other kind from the Socket. Have you ever called connect() more than once to the same host/port pair, when the first one failed? How did you know the first connect() failed? And before subsequent connect() calls, did you do anything to reset the socket? A: This could be related to the unresolved bug FP-269 which in turn may have the same root cause as FP-67. This build should be fixed in the current public beta release found on labs.adobe.com Edwin Wong - [09/23/08 04:49 PM ] I'd recommend you give the latest public beta a shot...
{ "language": "en", "url": "https://stackoverflow.com/questions/8939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: VMWare Server Under Linux Secondary NIC connection With VMWare Server running under Linux (Debain), I would like to have the following setup: * *1st: NIC being used by many of the images running under VMWare, as well as being used by the Linux OS *2nd: NIC being used by only 1 image and to be unused by the Linux OS (as its part of a DMZ) Although the second NIC won't be used by Linux, it is certainly recognised as a NIC (e.g. eth1). Is this possible under VMWare Server, and if so, is it as simple as not binding eth1 under Linux and then bridging it to the image under VMWare Server? A: I believe you can set the desired solution up by rerunning the vmware configuration script. And doing a custom network setup, so that both NIC's are mapped to your vmware instance. I would recommend making eth0 the 2nd NIC since it will be easier for Linux to use by default. Then make eth1 the 1st NIC.
{ "language": "en", "url": "https://stackoverflow.com/questions/8940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generic type checking Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.) Now, I know you can limit the generic type parameter to a type or interface implementation via the where clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from object before someone says! :P). So, my current thoughts are to just grit my teeth and do a big switch statement and throw an ArgumentException on failure. EDIT 1: Just to clarify: The code definition should be like this: public class MyClass<GenericType> .... And instantiation: MyClass<bool> = new MyClass<bool>(); // Legal MyClass<string> = new MyClass<string>(); // Legal MyClass<DataSet> = new MyClass<DataSet>(); // Illegal MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!) EDIT 2 @Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type. This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as Size ). Interesting problem no? :) Here it is: where T: struct Taken from MSDN. I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code. What do you guys think? The sad news is I am working in Framework 2!! :D EDIT 3 This was so simple following on from Jon Limjaps Pointer.. So simple I almost want to cry, but it's great because the code works like a charm! So here is what I did (you'll laugh!): Code added to the generic class bool TypeValid() { // Get the TypeCode from the Primitive Type TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType)); // All of the TypeCode Enumeration refer Primitive Types // with the exception of Object and Empty (Null). // Since I am willing to allow Null Types (at this time) // all we need to check for is Object! switch (code) { case TypeCode.Object: return false; default: return true; } } Then a little utility method to check the type and throw an exception, private void EnforcePrimitiveType() { if (!TypeValid()) throw new InvalidOperationException( "Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name + "' - this Class is Designed to Work with Primitive Data Types Only."); } All that then needs to be done is to call EnforcePrimitiveType() in the classes constructors. Job done! :-) The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like FxCop (which we don't use at work). Special thanks to Jon Limjap on this one! A: public class Class1<GenericType> where GenericType : struct { } This one seemed to do the job.. A: Primitives appear to be specified in the TypeCode enumeration: Perhaps there is a way to find out if an object contains the TypeCode enum without having to cast it to an specific object or call GetType() or typeof()? Update It was right under my nose. The code sample there shows this: static void WriteObjectInfo(object testObject) { TypeCode typeCode = Type.GetTypeCode( testObject.GetType() ); switch( typeCode ) { case TypeCode.Boolean: Console.WriteLine("Boolean: {0}", testObject); break; case TypeCode.Double: Console.WriteLine("Double: {0}", testObject); break; default: Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject); break; } } } It's still an ugly switch. But it's a good place to start! A: If you can tolerate using factory methods (instead of the constructors MyClass you asked for) you could always do something like this: class MyClass<T> { private readonly T _value; private MyClass(T value) { _value = value; } public static MyClass<int> FromInt32(int value) { return new MyClass<int>(value); } public static MyClass<string> FromString(string value) { return new MyClass<string>(value); } // etc for all the primitive types, or whatever other fixed set of types you are concerned about } A problem here is that you would need to type MyClass<AnyTypeItDoesntMatter>.FromInt32, which is annoying. There isn't a very good way around this if you want to maintain the private-ness of the constructor, but here are a couple of workarounds: * *Create an abstract class MyClass. Make MyClass<T> inherit from MyClass and nest it within MyClass. Move the static methods to MyClass. This will all the visibility work out, at the cost of having to access MyClass<T> as MyClass.MyClass<T>. *Use MyClass<T> as given. Make a static class MyClass which calls the static methods in MyClass<T> using MyClass<AnyTypeItDoesntMatter> (probably using the appropriate type each time, just for giggles). *(Easier, but certainly weird) Make an abstract type MyClass which inherits from MyClass<AnyTypeItDoesntMatter>. (For concreteness, let's say MyClass<int>.) Because you can call static methods defined in a base class through the name of a derived class, you can now use MyClass.FromString. This gives you static checking at the expense of more writing. If you are happy with dynamic checking, I would use some variation on the TypeCode solution above. A: You can simplify the EnforcePrimitiveType method by using typeof(PrimitiveDataType).IsPrimitive property. Am I missing something? A: @Rob, Enum's will slip through the TypeValid function as it's TypeCode is Integer. I've updated the function to also check for Enum. Private Function TypeValid() As Boolean Dim g As Type = GetType(T) Dim code As TypeCode = Type.GetTypeCode(g) ' All of the TypeCode Enumeration refer Primitive Types ' with the exception of Object and Empty (Nothing). ' Note: must also catch Enum as its type is Integer. Select Case code Case TypeCode.Object Return False Case Else ' Enum's TypeCode is Integer, so check BaseType If g.BaseType Is GetType(System.Enum) Then Return False Else Return True End If End Select End Function A: Having a similar challenge, I was wondering how you guys felt about the IConvertible interface. It allows what the requester requires, and you can extend with your own implementations. Example: public class MyClass<TKey> where TKey : IConvertible { // class intentionally abbreviated } I am thinking about this as a solution, all though many of the suggested was part of my selection also. My concern is - however - is it misleading for potential developers using your class? Cheers - and thanks. A: Pretty much what @Lars already said: //Force T to be a value (primitive) type. public class Class1<T> where T: struct //Force T to be a reference type. public class Class1<T> where T: class //Force T to be a parameterless constructor. public class Class1<T> where T: new() All work in .NET 2, 3 and 3.5. A: Use a custom FxCop rule that flags undesirable usage of MyClass<>. A: In dotnet 6, I encountered this error when using struct: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' So I use IConvertible instead var intClass = new PrimitivesOnly<int>(); var doubleClass = new PrimitivesOnly<double>(); var boolClass = new PrimitivesOnly<bool>(); var stringClass = new PrimitivesOnly<string>(); var myAwesomeClass = new PrimitivesOnly<MyAwesomeClass>(); // illegal // The line below encounter issue when using "string" type // class PrimitivesOnly<T> where T : struct class PrimitivesOnly<T> where T : IConvertible { } class MyAwesomeClass { }
{ "language": "en", "url": "https://stackoverflow.com/questions/8941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: Accessing MP3 metadata with Python Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python? A: check this one out: https://github.com/Ciantic/songdetails Usage example: >>> import songdetails >>> song = songdetails.scan("data/song.mp3") >>> print song.duration 0:03:12 Saving changes: >>> import songdetails >>> song = songdetails.scan("data/commit.mp3") >>> song.artist = "Great artist" >>> song.save() A: Just additional information to you guys: take a look at the section "MP3 stuff and Metadata editors" in the page of PythonInMusic. A: easiest method is songdetails.. for read data import songdetails song = songdetails.scan("blah.mp3") if song is not None: print song.artist similarly for edit import songdetails song = songdetails.scan("blah.mp3") if song is not None: song.artist = u"The Great Blah" song.save() Don't forget to add u before name until you know chinese language. u can read and edit in bulk using python glob module ex. import glob songs = glob.glob('*') # script should be in directory of songs. for song in songs: # do the above work. A: After trying the simple pip install route for eyeD3, pytaglib, and ID3 modules recommended here, I found this fourth option was the only one to work. The rest had import errors with missing dependencies in C++ or something magic or some other library that pip missed. So go with this one for basic reading of ID3 tags (all versions): https://pypi.python.org/pypi/tinytag/0.18.0 from tinytag import TinyTag tag = TinyTag.get('/some/music.mp3') List of possible attributes you can get with TinyTag: tag.album # album as string tag.albumartist # album artist as string tag.artist # artist name as string tag.audio_offset # number of bytes before audio data begins tag.bitrate # bitrate in kBits/s tag.disc # disc number tag.disc_total # the total number of discs tag.duration # duration of the song in seconds tag.filesize # file size in bytes tag.genre # genre as string tag.samplerate # samples per second tag.title # title of the song tag.track # track number as string tag.track_total # total number of tracks as string tag.year # year or data as string It was tiny and self-contained, as advertised. A: I used tinytag 1.3.1 because * *It is actively supported: 1.3.0 (2020-03-09): added option to ignore encoding errors ignore_errors #73 Improved text decoding for many malformed files *It supports the major formats: MP3 (ID3 v1, v1.1, v2.2, v2.3+) Wave/RIFF OGG OPUS FLAC WMA MP4/M4A/M4B *The code WORKED in just a few minutes of development. from tinytag import TinyTag fileNameL ='''0bd1ab5f-e42c-4e48-a9e6-b485664594c1.mp3 0ea292c0-2c4b-42d4-a059-98192ac8f55c.mp3 1c49f6b7-6f94-47e1-a0ea-dd0265eb516c.mp3 5c706f3c-eea4-4882-887a-4ff71326d284.mp3 '''.split() for fn in fileNameL: fpath = './data/'+fn tag = TinyTag.get(fpath) print() print('"artist": "%s",' % tag.artist) print('"album": "%s",' % tag.album) print('"title": "%s",' % tag.title) print('"duration(secs)": "%s",' % tag.duration) * *RESULT JoeTagPj>python joeTagTest.py "artist": "Conan O’Brien Needs A Friend", "album": "Conan O’Brien Needs A Friend", "title": "17. Thomas Middleditch and Ben Schwartz", "duration(secs)": "3565.1829583532785", "artist": "Conan O’Brien Needs A Friend", "album": "Conan O’Brien Needs A Friend", "title": "Are you ready to make friends?", "duration(secs)": "417.71840447045264", "artist": "Conan O’Brien Needs A Friend", "album": "Conan O’Brien Needs A Friend", "title": "Introducing Conan’s new podcast", "duration(secs)": "327.22187551899646", "artist": "Conan O’Brien Needs A Friend", "album": "Conan O’Brien Needs A Friend", "title": "19. Ray Romano", "duration(secs)": "3484.1986772305863", C:\1d\PodcastPjs\JoeTagPj> A: I looked the above answers and found out that they are not good for my project because of licensing problems with GPL. And I found out this: PyID3Lib, while that particular python binding release date is old, it uses the ID3Lib, which itself is up to date. Notable to mention is that both are LGPL, and are good to go. A: A simple example from the book Dive Into Python works ok for me, this is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job. The entire book is available online here. A: I've used mutagen to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API. A: A problem with eyed3 is that it will throw NotImplementedError("Unable to write ID3 v2.2") for common MP3 files. In my experience, the mutagen class EasyID3 works more reliably. Example: from mutagen.easyid3 import EasyID3 audio = EasyID3("example.mp3") audio['title'] = u"Example Title" audio['artist'] = u"Me" audio['album'] = u"My album" audio['composer'] = u"" # clear audio.save() All other tags can be accessed this way and saved, which will serve most purposes. More information can be found in the Mutagen Tutorial. A: The first answer that uses eyed3 is outdated so here is an updated version of it. Reading tags from an mp3 file: import eyed3 audiofile = eyed3.load("some/file.mp3") print(audiofile.tag.artist) print(audiofile.tag.album) print(audiofile.tag.album_artist) print(audiofile.tag.title) print(audiofile.tag.track_num) An example from the website to modify tags: import eyed3 audiofile = eyed3.load("some/file.mp3") audiofile.tag.artist = u"Integrity" audiofile.tag.album = u"Humanity Is The Devil" audiofile.tag.album_artist = u"Integrity" audiofile.tag.title = u"Hollow" audiofile.tag.track_num = 2 An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from here A: I would suggest mp3-tagger. Best thing about this is it is distributed under MIT License and supports all the required attributes. - artist; - album; - song; - track; - comment; - year; - genre; - band; - composer; - copyright; - url; - publisher. Example: from mp3_tagger import MP3File # Create MP3File instance. mp3 = MP3File('File_Name.mp3') # Get all tags. tags = mp3.get_tags() print(tags) It supports set, get, update and delete attributes of mp3 files. A: What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following: from ID3 import * try: id3info = ID3('file.mp3') print id3info # Change the tags id3info['TITLE'] = "Green Eggs and Ham" id3info['ARTIST'] = "Dr. Seuss" for k, v in id3info.items(): print k, ":", v except InvalidTagError, message: print "Invalid ID3 tag:", message A: I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute python setup.py install from the source folder. Relevant examples from the website are below. Reading the contents of an mp3 file containing either v1 or v2 tag info: import eyeD3 tag = eyeD3.Tag() tag.link("/some/file.mp3") print tag.getArtist() print tag.getAlbum() print tag.getTitle() Read an mp3 file (track length, bitrate, etc.) and access it's tag: if eyeD3.isMp3File(f): audioFile = eyeD3.Mp3AudioFile(f) tag = audioFile.getTag() Specific tag versions can be selected: tag.link("/some/file.mp3", eyeD3.ID3_V2) tag.link("/some/file.mp3", eyeD3.ID3_V1) tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default. Or you can iterate over the raw frames: tag = eyeD3.Tag() tag.link("/some/file.mp3") for frame in tag.frames: print frame Once a tag is linked to a file it can be modified and saved: tag.setArtist(u"Cro-Mags") tag.setAlbum(u"Age of Quarrel") tag.update() If the tag linked in was v2 and you'd like to save it as v1: tag.update(eyeD3.ID3_V1_1) Read in a tag and remove it from the file: tag.link("/some/file.mp3") tag.remove() tag.update() Add a new tag: tag = eyeD3.Tag() tag.link('/some/file.mp3') # no tag in this file, link returned False tag.header.setVersion(eyeD3.ID3_V2_3) tag.setArtist('Fugazi') tag.update() A: It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best. If you're manipulating the mp3 past that PyMedia may be suitable. There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date. Personally I've used this small MP3Info class with luck. It is quite old though. http://www.omniscia.org/~vivake/python/MP3Info.py A: After some initial research I thought songdetails might fit my use case, but it doesn't handle .m4b files. Mutagen does. Note that while some have (reasonably) taken issue with Mutagen's surfacing of format-native keys, that vary from format to format (TIT2 for mp3, title for ogg, \xa9nam for mp4, Title for WMA etc.), mutagen.File() has a (new?) easy=True parameter that provides EasyMP3/EasyID3 tags, which have a consistent, albeit limited, set of keys. I've only done limited testing so far, but the common keys, like album, artist, albumartist, genre, tracknumber, discnumber, etc. are all present and identical for .mb4 and .mp3 files when using easy=True, making it very convenient for my purposes. A: using https://github.com/nicfit/eyeD3 import eyed3 import os for root, dirs, files in os.walk(folderp): for file in files: try: if file.find(".mp3") < 0: continue path = os.path.abspath(os.path.join(root , file)) t = eyed3.load(path) print(t.tag.title , t.tag.artist) #print(t.getArtist()) except Exception as e: print(e) continue
{ "language": "en", "url": "https://stackoverflow.com/questions/8948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "147" }
Q: SharePoint WSS 3.0 Integration with Mac OSX (either Safari or Firefox) We have a SharePoint WSS site and some of our users on on the Mac OSX platform. Are there any tips or tricks to get a similar experience to Windows with document shares and calendars on the Mac? Edit: Browsing a SharePoint WSS site on a Mac, whether using Firefox or Safari, has a very similar look and feel as it does on Windows IE. The similar experience I am looking for has to do with integrating the calendars, document shares, etc. into the desktop. For example, with IE you can go to a calendar and select "Actions -> Connect to Outlook" and it will make the calendar visible and manageable from within Outlook. Is there any way to get the Mac to work similarly? A: Unfortunately, the "full" Sharepoint Experience is limited to running Internet Explorer 6/7 and Office 2007. On the Mac, I recommend using Firefox (Camino?) which seems to work a bit better than Safari. Edit: When you say "Similar experience", what exactly are you missing? I don't have any Mac here, but I was under the impression that Office 2008 will have a working integration with Sharepoint as well. A: Office 2008 allows limited connectivity to MOSS. However there is no Mac OS browser yet that is completely compatible to MOSS. I do have it on good authority the Microsoft Mac BU team is working with the MOSS team to see this changing in future versions of the platform, specifically around the Safari support. A: ActiveX is used to enable the bridge between MOSS and Office, and as ActiveX is only on Windows, you will find that you cannot get the full experience if you do not use Windows as your OS. A: Yes, Sharepoint looks to client installs of Office applications and Active X in order to fully integrate.
{ "language": "en", "url": "https://stackoverflow.com/questions/8950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Storing a file in a database as opposed to the file system? Generally, how bad of a performance hit is storing a file in a database (specifically mssql) as opposed to the file system? I can't come up with a reason outside of application portability that I would want to store my files as varbinaries in SQL Server. A: Have a look at this answer: Storing Images in DB - Yea or Nay? Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually. There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea. Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database. A: What's the question here? Modern DBMS SQL2008 have a variety of ways of dealing with BLOBs which aren't just sticking in them in a table. There are pros and cons, of course, and you might need to think about it a little deeper. This is an interesting paper, by the late (?) Jim Gray To BLOB or Not To BLOB: Large Object Storage in a Database or a Filesystem A: In my own experience, it is always better to store files as files. The reason is that the filesystem is optimised for file storeage, whereas a database is not. Of course, there are some exceptions (e.g. the much heralded next-gen MS filesystem is supposed to be built on top of SQL server), but in general that's my rule. A: If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler. Getting Started with FILESTREAM Storage A: While performance is an issue, I think modern database designs have made it much less of an issue for small files. Performance aside, it also depends on just how tightly-coupled the data is. If the file contains data that is closely related to the fields of the database, then it conceptually belongs close to it and may be stored in a blob. If it contains information which could potentially relate to multiple records or may have some use outside of the context of the database, then it belongs outside. For example, an image on a web page is fetched on a separate request from the page that links to it, so it may belong outside (depending on the specific design and security considerations). Our compromise, and I don't promise it's the best, has been to store smallish XML files in the database but images and other files outside it. A: I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems. A: We made the decision to store as varbinary for http://www.freshlogicstudios.com/Products/Folders/ halfway expecting performance issues. I can say that we've been pleasantly surprised at how well it's worked out. A: I agree with @ZombieSheep. Just one more thing - I generally don't think that databases actually need be portable because you miss all the features your DBMS vendor provides. I think that migrating to another database would be the last thing one would consider. Just my $.02 A: The overhead of having to parse a blob (image) into a byte array and then write it to disk in the proper file name and then reading it is enough of an overhead hit to discourage you from doing this too often, especially if the files are rather large. A: Not to be vague or anything but I think the type of 'file' you will be storing is one of the biggest determining factors. If you essentially talking about a large text field which could be stored as file my preference would be for db storage. A: Interesting topic. There is no absolutely one correct answer to this question. There are few key elements to consider: * *What’s your database engine? *What’s the route of file from database to end user and/or backwards? *What are the security requirements? If files are meant for public audience and accessible via website, you shouldn’t even consider storing files in database. Use some smart indexing for files instead. If files are containing highly sensitive information, then it might be worth of storing these into database. But you have to implement proper safe gateways too. If performance is crucial, it’s better do not store files in database. Backup and restoring and migrating of database might become a nightmare if database grows big just because of files. If you are DBA, then you would like to kill the person who “invented” an idea to put files into database. I recommend to use storing files into database at last option, when there is absolutely no any better alternative available.
{ "language": "en", "url": "https://stackoverflow.com/questions/8952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: Using C#/WIA version 2.0 on Vista to Scan I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem. In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0. Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different. Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there? A: To access WIA, you'll need to add a reference to the COM library, "Microsoft Windows Image Acquisition Library v2.0" (wiaaut.dll). add a "using WIA;" const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; CommonDialogClass wiaDiag = new CommonDialogClass(); WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage( WiaDeviceType.UnspecifiedDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatJPEG, true, true, false); WIA.Vector vector = wiaImage.FileData; (System.Drawing) Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); i.Save(filename) Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's Coding4Fun article on WIA does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself) If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you. A: Heres how to target WIA 1.0 also so you can ship your app to Windows Xp. Something I was desperately looking for!! How to develop using WIA 1 under Vista? A: Update: I'm adding this separately since its a different answer (a year later). I learnt XP has WIA 1.0 and Vista onward has WIA2.0. You can however install WIA 2.0 for Windows XP Sp1+ from here. I then also made a small library with code I found somewhere on the interweb here, it also has the ability to scan multiple pages: http://adfwia.codeplex.com/ A: It doesn't need to be WIA. I was mostly looking at the WIA setup because it offers the same basic interface for different scanners. I've got 3 scanners on this machine and the TWAIN drivers/software for all of them suck (like blocking the screen during scanning). For document management, I'm really looking for simple 200dpi grayscale scans, so most of the stuff in the TWAIN drivers is overkill. That said, asking here was part of my last attempt to figure out how to do it in WIA before moving on to TWAIN. A: Another note: You have to download the WIA 2.0 dll from Microsoft.com and then browse to the dll and add it to your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/8966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: What OSS project should I look at if I need to do Spring friendly WorkFlow? We need to add WorkFlow to our Spring managed application. Does anyone have any useful experience in using any of the myriad of OSS Work Flow solutions? Which one is best? Which one integrates with Spring best? Which ones should we avoid? A: If you only need some simple process orchestration, Spring's own Web Flow, despite its name can serve as a orchestration task manager. If you need to preserve state for several days then you will need to become an 'early adopter' of one of the open-source projects. You may want to look at Eclipse's BPEL project. My hunch is that once a clearer picture of the BPEL/BPM/Workflow space emerges you will see Spring provide an abstraction layer the same way they have for JDBC, Transactions, ORM frameworks etc... A: Like Brian said if you're doing anything of great complexity you might look at using BPEL. There are a number of open source BPEL engines, one that comes to mind is Apache Orchestration Director Engine A: I second Spring Web Flow. Depending on how complex the process is, Web Flow is great for managing various states and I've found that it's pretty easy to pick up and there's a good amount of documentation out there for it. A: We're looking at Drools/Guvnor, possibly integrated with jBPM (as in this presentation), to add a workflow engine to our Spring/Java EE app, but we're still in the very early phases of trying it out. A: ActiveVOS is by far the best BPEL engine in my opinion. Download the evaluation version and give it a go. JBoss have even adopted their open source offering.
{ "language": "en", "url": "https://stackoverflow.com/questions/8968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Accessing iSight programmatically? Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? A: You should check out the QTKit Capture documentation. On Leopard, you can get at all of it over the RubyCocoa bridge: require 'osx/cocoa' OSX.require_framework("/System/Library/Frameworks/QTKit.framework") OSX::QTCaptureDevice.inputDevices.each do |device| puts device.localizedDisplayName end A: I don't have a Mac here, but there is some Documentation up here: http://developer.apple.com/documentation/Hardware/Conceptual/iSightProgGuide/01introduction/chapter_1_section_1.html It looks like you have to go through the QuickTime API. There is supposed to be a Sample Project called "MungGrab" which could be worth a look according to this thread. A: If you poke around Apple's mailing lists you can find some code to do it in Java as well. Here's a simple example suitable for capturing individual frames, and here's a more complicated one that's fast enough to display live video. A: There's a command line utility called isightcapture that does more or less what you want to do. You could probably get the code from the developer (his e-mail address is in the readme you get when you download the utility). A: One thing that hasn't been mentioned so far is the IKPictureTaker, which is part of Image Kit. This will come up with the standard OS provided panel to take pictures though, with all the possible filter functionality etc. included. I'm not sure if that's what you want. I suppose you can use it from other languages as well, considering there are things like cocoa bridges but I have no experience with them. Googling also came up with another question on stackoverflow that seems to address this issue. A: Aside from ObjC, you can use the PyObjC or RubyCocoa bindings to access it also. If you're not picky about which language, I'd say use Ruby, as PyObjC is horribly badly documented (even the official Apple page on it refers to the old version, not the one that came with OS X Leopard) Quartz Composer is probably the easiest way to access it, and .quartz files can be embed in applications pretty easily (and the data piped out to ObjC or such) Also, I suppose there should be an example or two of this in the /Developer/Examples/ A: From a related question which specifically asked the solution to be pythonic, you should give a try to motmot's camiface library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for. From the tutorial: import motmot.cam_iface.cam_iface_ctypes as cam_iface import numpy as np mode_num = 0 device_num = 0 num_buffers = 32 cam = cam_iface.Camera(device_num,num_buffers,mode_num) cam.start_camera() frame = np.asarray(cam.grab_next_frame_blocking()) print 'grabbed frame with shape %s'%(frame.shape,)
{ "language": "en", "url": "https://stackoverflow.com/questions/8970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Calling Table-Valued SQL Functions From .NET Scalar-valued functions can be called from .NET as follows: SqlCommand cmd = new SqlCommand("testFunction", sqlConn); //testFunction is scalar cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("retVal", SqlDbType.Int); cmd.Parameters["retVal"].Direction = ParameterDirection.ReturnValue; cmd.ExecuteScalar(); int aFunctionResult = (int)cmd.Parameters["retVal"].Value; I also know that table-valued functions can be called in a similar fashion, for example: String query = "select * from testFunction(param1,...)"; //testFunction is table-valued SqlCommand cmd = new SqlCommand(query, sqlConn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(tbl); My question is, can table-valued functions be called as stored procedures, like scalar-valued functions can? (e.g., replicate my first code snippet with a table-valued function being called and getting the returned table through a ReturnValue parameter). A: No because you need to select them. However you can create a stored proc wrapper, which may defeat the point of having a table function.
{ "language": "en", "url": "https://stackoverflow.com/questions/8987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: How do I get dbmail to process items from the queue for SQL Server 2005? When I use the sp_send_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL: SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent' This SQL returns a 1: SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb' This stored procedure returns STARTED: msdb.dbo.sysmail_help_status_sp The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail_event_log. A: Have you tried sysmail_stop_sp then sysmail_start_sp A: I had the same problem and this is how I was able to resolve it. Go to Sql Agent >> Properties >> Alert System >> Check the Enable box for DBMail and add a profile. Restart Agent and it works since then. Hope this helps, _Ub A: Could be oodles of things. For example, I've seen (yes, actually seen) this happen after: * *Domain controller reboot *Exchange server reboot *Router outage *Service account changes *SQL Server running out of disk space So until it happens again, I wouldn't freak out over it.
{ "language": "en", "url": "https://stackoverflow.com/questions/9002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Assignment inside Perl ternary conditional operator problems This snippet of Perl code in my program is giving the wrong result. $condition ? $a = 2 : $a = 3 ; print $a; No matter what the value of $condition is, the output is always 3, how come? A: This is explained in the Perl documentation. Because of Perl operator precedence the statement is being parsed as ($condition ? $a= 2 : $a ) = 3 ; Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition. When $condition is true this means ($a=2)=3 giving $a=3 When $condition is false this means ($a)=3 giving $a=3 The correct way to write this is $a = ( $condition ? 2 : 3 ); print $a; We got bitten by this at work, so I am posting here hoping others will find it useful. A: Once you have an inkling that you might be suffering from precedence problems, a trick to figure out what Perl thought you meant: perl -MO=Deparse,-p -e '$condition ? $a= 2 : $a= 3 ; print $a;' In your case, that'll show you: (($condition ? ($a = 2) : $a) = 3); print($a); -e syntax OK ...at which point you should be saying "oh, that explains it"! A: Because of Perl operator precedence the statement is being parsed as: ($condition ? $a = 2 : $a ) = 3 ; Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition. When $condition is true this means $a=2=3 giving $a=3 When $condition is false this means $a=3 giving $a=3 The correct way to write this is $a = $condition ? 2 : 3; In general, you should really get out of the habit of using conditionals to do assignment, as in the original example -- it's the sort of thing that leads to Perl getting a reputation for being write-only. A good rule of thumb is that conditionals are only for simple values, never expressions with side effects. When you or someone else needs to read this code eight months from now, would you prefer it to read like this? $x < 3 ? foo($x) : bar($y); Or like this? if ($x < 3) { $foo($x); } else { $bar($y); } A: Just to extend the previous answer... If, for whatever reason, the assignments need to be part of the conditional, you'd want to write it thusly: $condition ? ($a=2) : ($a=3); This would be useful if you're assigning to different variables based on the condition. $condition ? ($a=2) : ($b=3); And if you're choosing the variable, but assigning the same thing no matter what, you could even do this: ($condition ? $a : $b) = 3; A: One suggestion to Tithonium's answer above: If you are want to assign different values to the same variable, this might be better (the copy-book way): $a = ($condition) ? 2 : 3;
{ "language": "en", "url": "https://stackoverflow.com/questions/9009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Windows Mobile Device Emulator - how to save config permanently? I am working at a client site where there is a proxy server (HTTP) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting: * *The emulators associated network card *DNS servers for network card in the WM OS. *Proxy servers in connection settings of WM OS. How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily? A: The problem with these devices is everything is stored in the RAM and ROM. So you need a second alternate device storage for these settings, just like a real device. So that when a real device, or your device is reset, it has a statically stored configuration file outside of the RAM that can be loaded on start up. The alternative is to do soft-resets if possible. A: There is a way you can programmatically provision your devices. If you're using managed code, you can use Microsoft.WindowsMobile.Configuration.dll to do most of the work for you. If you're using unmanaged code, you have to use DMProcessConfigXML native function. There's more details in this blog post by Andrew Arnott.
{ "language": "en", "url": "https://stackoverflow.com/questions/9018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best method for varchar date validation in Sybase (T-SQL)? I have a stored procedure which takes as its parameter a varchar which needs to be cast as a datetime for later use: SET @the_date = CAST(@date_string AS DATETIME) I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL? NB: using Sybase ASE 12.5.3, there is no ISDATE function A: My goodness, if the question was about Microsoft SQL Server then we'd have been in business! Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year. If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length. I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt. A: I'm having a similar issue. You might be able to do something like this: SET arithabort arith_overflow off SET @the_date = CAST(@date_string AS DATETIME) IF @the_date is NULL set @the_date = getdate() SET arithabort arith_overflow on However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. A: Can't you do something like this: SELECT @the_date = CASE @date_string WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]' THEN CONVERT(datetime, @date_string) ELSE GETDATE() END ? A: Found this in the second result in Google when searching for "validate date string sql". ----Invalid date SELECT ISDATE('30/2/2007') RETURNS : 0 (Zero) ----Valid date SELECT ISDATE('12/12/20007') RETURNS : 1 (ONE) ----Invalid DataType SELECT ISDATE('SQL') RETURNS : 0 (Zero) A: Make sure SQL Server knows the order of Days, Months and Years in your string by executing SET DATEFORMAT mdy; A: Did you try convert instead of cast? select convert( datetime , @date_string )
{ "language": "en", "url": "https://stackoverflow.com/questions/9019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How have Html entities inside asp.net page? Inside an asp.net page, should I use <html><title>My page's title from México</title></html> Or <html><title>My page&rsquo;s title from M&eacute;xico</title></html> Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right? A: The second example will ensure compatibility with ASCII standards of HTML transmition. So my vote is for the second example, so you don't have to ensure the HTML is output and encoded as UTF-8 all the way through all the proxy servers and any other kind of caching and translation that might occur. A: You're correct; As long as there's unicode at both ends of the pipe, it really doesn't matter. Personally, I would use the first simply because it's more readable. And, honestly, unicode has been widespread for some time. I personally believe that it's time to leave anyone who can't handle UTF-8 behind. A: The ASCII table is set of characters, arguable the first standardized set of characters back in the days when you could only spare 1 byte per character. http://asciitable.com/ But I did some looking around at the extended character set of ASCII and it appears that the character you are referencing is an ASCII character. So there really isn't a problem which ever way you choose to display your title. My revised answer is go for less expensive one according to space (i.e. the first one)
{ "language": "en", "url": "https://stackoverflow.com/questions/9022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: HTTPS in IIS 5.1 I'm using IIS 5.1 in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system. But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled? A: You may need to manually create a certificate first (on WinXP there does not seem to be a built-in mechanism, so you need to use OpenSSL). Check out these two links: Enabling SSL in IIS on Windows XP Professional Enabling SSL (HTTPS) for IIS in Windows XP A: That is because IIS 5.1 under the limited Windows XP version is limited to only HTTP. You need to have a full version of IIS 6.0 on Windows 2003 to do this. Luckily you can download a VHD image of Windows 2003 from Microsoft and run it under a Virtual PC instance. Plus I would recommend this since you are trying to be careful and use a machine close to your production environment. IIS 5.1 version is never deployed as a production machine so you cannot guarantee anything and the differences between IIS 5.1 and IIS 6.0 are significant enough where the VM is worth your while.
{ "language": "en", "url": "https://stackoverflow.com/questions/9024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Hidden Features of C#? This came to my mind after I learned the following from this question: where T : struct We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc. Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ... But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know? Here are the revealed features so far: Keywords * *yield by Michael Stum *var by Michael Stum *using() statement by kokos *readonly by kokos *as by Mike Stone *as / is by Ed Swangren *as / is (improved) by Rocketpants *default by deathofrats *global:: by pzycoman *using() blocks by AlexCuse *volatile by Jakub Šturc *extern alias by Jakub Šturc Attributes * *DefaultValueAttribute by Michael Stum *ObsoleteAttribute by DannySmurf *DebuggerDisplayAttribute by Stu *DebuggerBrowsable and DebuggerStepThrough by bdukes *ThreadStaticAttribute by marxidad *FlagsAttribute by Martin Clarke *ConditionalAttribute by AndrewBurns Syntax * *?? (coalesce nulls) operator by kokos *Number flaggings by Nick Berardi *where T:new by Lars Mæhlum *Implicit generics by Keith *One-parameter lambdas by Keith *Auto properties by Keith *Namespace aliases by Keith *Verbatim string literals with @ by Patrick *enum values by lfoust *@variablenames by marxidad *event operators by marxidad *Format string brackets by Portman *Property accessor accessibility modifiers by xanadont *Conditional (ternary) operator (?:) by JasonS *checked and unchecked operators by Binoj Antony *implicit and explicit operators by Flory Language Features * *Nullable types by Brad Barker *Anonymous types by Keith *__makeref __reftype __refvalue by Judah Himango *Object initializers by lomaxx *Format strings by David in Dakota *Extension Methods by marxidad *partial methods by Jon Erickson *Preprocessor directives by John Asbeck *DEBUG pre-processor directive by Robert Durgin *Operator overloading by SefBkn *Type inferrence by chakrit *Boolean operators taken to next level by Rob Gough *Pass value-type variable as interface without boxing by Roman Boiko *Programmatically determine declared variable type by Roman Boiko *Static Constructors by Chris *Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid *__arglist by Zac Bowling Visual Studio Features * *Select block of text in editor by Himadri *Snippets by DannySmurf Framework * *TransactionScope by KiwiBastard *DependantTransaction by KiwiBastard *Nullable<T> by IainMH *Mutex by Diago *System.IO.Path by ageektrapped *WeakReference by Juan Manuel Methods and Properties * *String.IsNullOrEmpty() method by KiwiBastard *List.ForEach() method by KiwiBastard *BeginInvoke(), EndInvoke() methods by Will Dean *Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo *GetValueOrDefault method by John Sheehan Tips & Tricks * *Nice method for event handlers by Andreas H.R. Nilsson *Uppercase comparisons by John *Access anonymous types without reflection by dp *A quick way to lazily instantiate collection properties by Will *JavaScript-like anonymous inline-functions by roosteronacid Other * *netmodules by kokos *LINQBridge by Duncan Smart *Parallel Extensions by Joel Coehoorn A: Maybe not an advanced technique, but one I see all the time that drives me crazy: if (x == 1) { x = 2; } else { x = 3; } can be condensed to: x = (x==1) ? 2 : 3; A: Many people don't realize that they can compare strings using: OrdinalIgnoreCase instead of having to do someString.ToUpper(). This removes the additional string allocation overhead. if( myString.ToUpper() == theirString.ToUpper() ){ ... } becomes if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase ) ){ ... } A: Preprocessor Directives can be nifty if you want different behavior between Debug and Release modes. http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx A: System.Diagnostics.Debug.Assert (false); will trigger a popup and allow you to attach a debugger to a running .NET process during execution. Very useful for those times when for some reason you can't directly debug an ASP.NET application. A: String interning. This is one that I haven't seen come up in this discussion yet. It's a little obscure, but in certain conditions it can be useful. The CLR keeps a table of references to literal strings (and programmatically interned strings). If you use the same string in several places in your code it will be stored once in the table. This can ease the amount of memory required for allocating strings. You can test if a string is interned by using String.IsInterned(string) and you can intern a string using String.Intern(string). Note: The CLR can hold a reference to an interned string after application or even AppDomain end. See the MSDN documentation for details. A: IEnumerable's SelectMany, which flattens a list of lists into a single list. Let's say I have a list of Orders, and each Order has a list of LineItems on that order. I want to know the total number of LineItems sold... int totalItems = Orders.Select(o => o.LineItems).SelectMany(i => i).Sum(); A: Working with enums. Convert a string to an Enum: enum MyEnum { FirstValue, SecondValue, ThirdValue } string enumValueString = "FirstValue"; MyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), enumValueString, true) * *I use this to load the value of CacheItemPriority in my ASP.NET applications from a settings table in a database so that I can control caching (along with other settings) dynamically without taking the application down. When comparing variables of type enum, you don't have to cast to int: MyEnum val = MyEnum.SecondValue; if (val < MyEnum.ThirdValue) { // Do something } A: I quite enjoy implicit generic parameters on functions. For example, if you have: public void DoStuff<T>(T value); Instead of calling it like this: DoStuff<int>(5); You can: DoStuff(5); And it'll work out the generic type from the parameter's type. * *This doesn't work if you're calling the method through reflection. *I remember having some weird problems on Mono. A: To test if an IEnumerable<T> is empty with LINQ, use: IEnumerable<T>.Any(); * *At first, I was using (IEnumerable<T>.Count() != 0)... * *Which unnecessarily causes all items in the IEnumerable<T> to be enumerated. *As an improvement to this, I went on to use (IEnumerable<T>.FirstOrDefault() == null)... * *Which is better... *But IEnumerable<T>.Any() is the most succinct and performs the best. A: I'm pretty sure everyone is familiar with operator overloading, but maybe some aren't. class myClass { private string myClassValue = ""; public myClass(string myString) { myClassValue = myString; } public override string ToString() { return myClassValue; } public static myClass operator <<(myClass mc, int shiftLen) { string newString = ""; for (int i = shiftLen; i < mc.myClassValue.Length; i++) newString += mc.myClassValue[i].ToString(); mc.myClassValue = newString.ToString(); return mc; } public static myClass operator >>(myClass mc, int shiftLen) { char[] newString = new char[shiftLen + mc.myClassValue.Length]; for (int i = shiftLen; i < mc.myClassValue.Length; i++) newString[i] += mc.myClassValue[i - shiftLen]; mc.myClassValue = new string(newString); return mc; } public static myClass operator +(myClass mc, string args) { if (args.Trim().Length > 1) mc.myClassValue += args; return mc; } public static myClass operator -(myClass mc, string args) { if (args.Trim().Length > 1) { Regex rgx = new Regex(args); mc.myClassValue = rgx.Replace(mc.myClassValue, ""); } return mc; } } I think it's pretty cool to be able to shift a string left and right using << and >> or to remove a set of strings that follow a regular expression pattern using -= myClass tmpClass = new myClass(" HelloWorld123"); tmpClass -= @"World"; tmpClass <<= 2; Console.WriteLine(tmpClass); A: Not a C# specific thing, but I am a ternary operations junkie. Instead of if (boolean Condition) { //Do Function } else { //Do something else } you can use a succinct booleanCondtion ? true operation : false operation; e.g. Instead of int value = param; if (doubleValue) { value *= 2; } else { value *= 3; } you can type int value = param * (tripleValue ? 3 : 2); It does help write succinct code, but nesting the damn things can be nasty, and they can be used for evil, but I love the little suckers nonetheless A: You can switch on string! switch(name) { case "Dave": return true; case "Bob": return false; default: throw new ApplicationException(); } Very handy! and a lot cleaner than a bunch of if-else statements A: Instead of doing something cheesy like this: Console.WriteLine("{0} item(s) found.", count); I use the following inline trick: Console.WriteLine("{0} item{1} found.", count, count==1 ? "" : "s"); This will display "item" when there's one item or "items" when there are more (or less) than 1. Not much effort for a little bit of professionalism. A: Expression to initialize a Dictionary in C# 3.5: new Dictionary<string, Int64>() {{"Testing", 123}, {"Test", 125}}; A: C# allows you to add property setter methods to concrete types that implement readonly interface properties even though the interface declaration itself has no property setter. For example: public interface IReadOnlyFoo { object SomeReadOnlyProperty { get; } } The concrete class looks like this: internal class Foo : IReadOnlyFoo { public object SomeReadOnlyProperty { get; internal set; } } What's interesting about this is that the Foo class is immutable if you cast it to the IReadOnlyFoo interface: // Create a Foo instance Foo foo = new Foo(); // This statement is legal foo.SomeReadOnlyProperty = 12345; // Make Foo read only IReadOnlyFoo readOnlyFoo = foo; // This statement won't compile readOnlyFoo.SomeReadOnlyProperty = 54321; A: Dictionary initializers are always useful for quick hacks and unit tests where you need to hardcode some data. var dict = new Dictionary<int, string> { { 10, "Hello" }, { 20, "World" } }; A: With LINQ it's possible to create new functions based on parameters. That's very nice if you have a tiny function which is exectued very often, but the parameters need some time to calculate. public Func<int> RandomGenerator { get { var r = new Random(); return () => { return r.Next(); }; } } void SomeFunction() { var result1 = RandomGenerator(); var x = RandomGenerator; var result2 = x(); } A: Just learned, anonymous types can infer property names from the variable name: string hello = "world"; var o = new { hello }; Console.WriteLine(o.hello); A: This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine() to the extent that they should. In fact, the whole Path class is really useful, but no one uses it! I'm willing to bet that every production app has the following code, even though it shouldn't: string path = dir + "\\" + fileName; A: Honestly the experts by the very definition should know this stuff. But to answer your question: Built-In Types Table (C# Reference) The compiler flagging for numbers are widely known for these: Decimal = M Float = F Double = D // for example double d = 30D; However these are more obscure: Long = L Unsigned Long = UL Unsigned Int = U A: I like looking up stuff in a list like:- bool basketContainsFruit(string fruit) { return new[] { "apple", "orange", "banana", "pear" }.Contains(fruit); } Rather than:- bool basketContainsFruit(string fruit) { return fruit == "apple" || fruit == "orange" || fruit == "banana" || fruit == "pear"; } Doesn't come up that much in practice, but the idea of matching items against the subject of the search can be really quite useful + succinct. A: InternalsVisibleTo attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access "internal" elements of the defining assembly. A: Here is a new method of the string class in C# 4.0: String.IsNullOrWhiteSpace(String value) It's about time. A: I picked this one up when using ReSharper: Implicit Method Group Conversion //If given this: var myStrings = new List<string>(){"abc","def","xyz"}; //Then this: myStrings.ForEach(s => Console.WriteLine(s)); //Is equivalent to this: myStrings.ForEach(Console.WriteLine); See "Implicit Method Group Conversion in C#" for more. A: In addition to duncansmart's reply, also extension methods can be used on Framework 2.0. Just add an ExtensionAttribute class under System.Runtime.CompilerServices namespace and you can use extension methods (only with C# 3.0 of course). namespace System.Runtime.CompilerServices { public class ExtensionAttribute : Attribute { } } A: You type "prop" and then press [TAB] twice, it generates useful code for your properties and can speed your typing. I know this works in VS 2005 (I use it) but I don´t know in previous versions. A: Object.ReferenceEquals Method Determines whether the specified Object instances are the same instance. Parameters: * *objA: System.Object - The first Object to compare. *objB: System.Object - The second Object to compare. Example: object o = null; object p = null; object q = new Object(); Console.WriteLine(Object.ReferenceEquals(o, p)); p = q; Console.WriteLine(Object.ReferenceEquals(p, q)); Console.WriteLine(Object.ReferenceEquals(o, p)); Difference to "==" and ".Equals": Basically, Equals() tests of object A has the same content as object B. The method System.Object.ReferenceEquals() always compares references. Although a class can provide its own behavior for the equality operator (below), that re-defined operator isn't invoked if the operator is called via a reference to System.Object. For strings there isn't really a difference, because both == and Equals have been overriden to compare the content of the string. See also this answer to another question ("How do I check for nulls in an ‘==’ operator overload without infinite recursion?"). A: Explicit interface member implementation, wherein an interface member is implemented, but hidden unless the instance is cast to the interface type. A: This isn't a C# specific type, but I just found the ISurrogateSelector and ISerializationSurrogate interfaces -- http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx Using these in conjunction with the BinaryFormatter allows for non-serializable objects to be serialized via the implementation of a surrogate class. The surrogate pattern is well-understood in computer science, particularly when dealing with the problem of serialization. I think that this implementation is just tucked away as a parameter of the constructor to BinaryFormatter, and that's too bad. Still - VERY hidden. :) A: dynamic keyword in C# 4.0 You can use dynamic keyword, if you want your method calls to be resolved only at the runtime. dynamic invoker=new DynamicInvoker(); dynamic result1=invoker.MyMethod1(); dynamic result2=invoker.MyMethod2(); Here I'm implementing a dynamic invoker. public class DynamicInvoker : IDynamicObject { public MetaObject GetMetaObject (System.Linq.Expressions.Expression parameter) { return new DynamicReaderDispatch (parameter); } } public class DynamicDispatcher : MetaObject { public DynamicDispatcher (Expression parameter) : base(parameter, Restrictions.Empty){ } public override MetaObject Call(CallAction action, MetaObject[] args) { //You'll get MyMethod1 and MyMethod2 here (and what ever you call) Console.WriteLine("Logic to invoke Method '{0}'", action.Name); return this; //Return a meta object } } A: You can have generic methods in a non-generic class. A: Cool trick to emulate functional "wildcard" arguments (like '_' in Haskell) when using lambdas: (_, b, __) => b.DoStuff(); // only interested in b here A: Here's one I discovered recently which has been useful: Microsoft.VisualBasic.Logging.FileLogTraceListener MSDN Link This is a TraceListener implementation which has a lot of features, such as automatic log file roll over, which I previously would use a custom logging framework for. The nice thing is that it is a core part of .NET and is integrated with the Trace framework, so its easy to pick up and use immediately. This is "hidden" because its in the Microsoft.VisualBasic assembly... but you can use it from C# as well. A: The usage of the default keyword in generic code to return the default value for a type. public class GenericList<T> { private class Node { //... public Node Next; public T Data; } private Node head; //... public T GetNext() { T temp = default(T); Node current = head; if (current != null) { temp = current.Data; current = current.Next; } return temp; } } Another example here A: The built-in (2.0) MethodInvoker delegate is useful when you want to Invoke/BeginInvoke inline code. This avoids needing to create an actual delegate and separate method. void FileMessageEvent(object sender, MessageEventArgs e) { if (this.InvokeRequired == true) { this.BeginInvoke((MethodInvoker)delegate { lblMessage.Text=e.Message; Application.DoEvents(); } ); } } Resolves the error: "Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type". A: Array initialization without specifying the array element type: var pets = new[] { "Cat", "Dog", "Bird" }; A: Properties to display when viewing components Properties in design view: private double _Zoom = 1; [Category("View")] [Description("The Current Zoom Level")] public double Zoom { get { return _Zoom;} set { _Zoom = value;} } Makes things a lot easier for other users of your component libraries. A: Advanced Debugging Display The already mentioned attributes DebuggerDisplay and DebuggerBrowsable control the visibility of elements and the textual value displayed. Simply overriding ToString() will cause the debugger to use the output of that method. If you want more complex output you can use/create a Debugger Visualizer, several examples are available here. Son Of Strike Microsoft provide a debugger extension known as SOS. This is an extremely powerful (though often confusing) extension which is an excellent way to diagnose 'leaks', more accurately unwanted references to objects no longer required. Symbol Server for framework source Following these instructions will allow you to step through the source of some parts of the framework. Changes in 2010 Several enhancements and new features exist in Visual Studio 2010: * *Debugging Parallel Tasks *Parallel Stacks allow viewing multiple threads call stacks at the same time. *Historical Debugging lets you see events and non-local variables back in time (so long as you enable the collection in advance). Potentially a significant change to how you debug things. A: You can create delegates from extension methods as if they were regular methods, currying the this parameter. For example, static class FunnyExtension { public static string Double(this string str) { return str + str; } public static int Double(this int num) { return num + num; } } Func<string> aaMaker = "a".Double; Func<string, string> doubler = FunnyExtension.Double; Console.WriteLine(aaMaker()); //Prints "aa" Console.WriteLine(doubler("b")); //Prints "bb" Note that this won't work on extension methods that extend a value type; see this question. A: HttpContext.Current.Server.Execute is great for rendering HTML to strings for AJAX callbacks. You can use this with a component instead of piecing together HTML string snippets. I was able to cut page bloat down a couple of hundred KB with virtually no mess. I used it like this: Page pageHolder = new Page(); UserControl viewControl = (UserControl)pageHolder.LoadControl(@"MyComponent.ascx"); pageHolder.Controls.Add(viewControl); StringWriter output = new StringWriter(); HttpContext.Current.Server.Execute(pageHolder, output, false); return output.ToString(); A: [field: NonSerialized] public event EventHandler Event; This way, the event listener is not serialized. Just [NonSerialized] does not work, because NonSerializedAttribute can only be applied to fields. A: I don't think someone has mentioned that appending ? after a value type name will make it nullable. You can do: DateTime? date = null; DateTime is a structure. A: Four switch oddities by Eric Lippert A: The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable. A: I like #if DEBUG //Code run in debugging mode #else //Code run in release mode #endif A: I was reading thru the book "Pro ASP.NET MVC Framework" (APress) and observed something the author was doing with a Dictionary object that was foreign to me. He added a new Key/Value Pair without using the Add() method. He then overwrote that same Key/Value pair without having to check if that key already existed. For example: Dictionary<string, int> nameAgeDict = new Dictionary<string, int>(); nameAgeDict["Joe"] = 34; // no error. will just auto-add key/value nameAgeDict["Joe"] = 41; // no error. key/value just get overwritten nameAgeDict.Add("Joe", 30); // ERROR! key already exists There are many cases where I don't need to check if my Dictionary already has a key or not and I just want to add the respective key/value pair (overwriting the existing key/value pair, if necessary.) Prior to this discovery, I would always have to check to see if the key already existed before adding it. A: Not sure if this one has been mentioned or not (11 pages!!) But the OptionalField attribute for classes is amazing when you are versioning classes/objects that are going to be serialized. http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx A: * *TransactionScope and DependentTransaction in System.Transactions is a lightweight way to use transaction processing in .NET - it's not just for Database transactions either *String.IsNullOrEmpty is one that I am surprised to learn a lot of developers don't know about *List.ForEach - iterate through your generic list using a delegate method There are more, but that is the three obvious ones of the top of my head... A: When debugging, you can type $exception in the Watch\QuickWatch\Immediate window and get all the info on the exception of the current frame. This is very useful if you've got 1st chance exceptions turned on! A: Dictionary.TryGetValue(K key, out V value) Works as a check and a get in one. Rather than; if(dictionary.ContainsKey(key)) { value = dictionary[key]; ... } you can just do; if(dictionary.TryGetValue(key, out value)) { ... } and the value has been set. A: Conditional string.Format: Applies different formatting to a number depending on whether the number is positive, negative, or zero. string s = string.Format("{0:positive;negative;zero}", i); e.g. string format = "000;-#;(0)"; string pos = 1.ToString(format); // 001 string neg = (-1).ToString(format); // -1 string zer = 0.ToString(format); // (0) A: Events are really delegates under the hood and any delegate object can have multiple functions attached to it and detatched from it using the += and -= operators, respectively. Events can also be controlled with the add/remove, similar to get/set except they're invoked when += and -= are used: public event EventHandler SelectiveEvent(object sender, EventArgs args) { add { if (value.Target == null) throw new Exception("No static handlers!"); _SelectiveEvent += value; } remove { _SelectiveEvent -= value; } } EventHandler _SelectiveEvent; A: Don't forget about goto. A: @Brad Barker I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring. Not sure why anyone would ever want to use Nullable<.bool> though. :-) Krzysztof Cwalina (one of the authors of Framwork Design Guidlines) has a good post here: http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx And Mike Hadlow has a nice post on Nullability Voodoo A: In no particular order: Lists<> Mutex The new property definitions shortcut in Framework 3.5. A: In reading the book on development of the .NET framework. A good piece of advice is not to use bool to turn stuff on or off, but rather use ENums. With ENums you give yourself some expandability without having to rewrite any code to add a new feature to a function. A: Thought about @dp AnonCast and decided to try it out a bit. Here's what I come up with that might be useful to some: // using the concepts of dp's AnonCast static Func<T> TypeCurry<T>(Func<object> f, T type) { return () => (T)f(); } And here's how it might be used: static void Main(string[] args) { var getRandomObjectX = TypeCurry(GetRandomObject, new { Name = default(string), Badges = default(int) }); do { var obj = getRandomObjectX(); Console.WriteLine("Name : {0} Badges : {1}", obj.Name, obj.Badges); } while (Console.ReadKey().Key != ConsoleKey.Escape); } static Random r = new Random(); static object GetRandomObject() { return new { Name = Guid.NewGuid().ToString().Substring(0, 4), Badges = r.Next(0, 100) }; } A: new modifier Usage of the "new" modifier in C# is not exactly hidden but it's not often seen. The new modifier comes in handy when you need to "hide" base class members and not always override them. This means when you cast the derived class as the base class then the "hidden" method becomes visible and is called instead of the same method in the derived class. It is easier to see in code: public class BaseFoo { virtual public void DoSomething() { Console.WriteLine("Foo"); } } public class DerivedFoo : BaseFoo { public new void DoSomething() { Console.WriteLine("Bar"); } } public class DerivedBar : BaseFoo { public override void DoSomething() { Console.WriteLine("FooBar"); } } class Program { static void Main(string[] args) { BaseFoo derivedBarAsBaseFoo = new DerivedBar(); BaseFoo derivedFooAsBaseFoo = new DerivedFoo(); DerivedFoo derivedFoo = new DerivedFoo(); derivedFooAsBaseFoo.DoSomething(); //Prints "Foo" when you might expect "Bar" derivedBarAsBaseFoo.DoSomething(); //Prints "FooBar" derivedFoo.DoSomething(); //Prints "Bar" } } [Ed: Do I get extra points for puns? Sorry, couldn't be helped.] A: Literals can be used as variables of that type. eg. Console.WriteLine(5.ToString()); Console.WriteLine(5M.GetType()); // Returns "System.Decimal" Console.WriteLine("This is a string!!!".Replace("!!", "!")); Just a bit of trivia... There's quite a few things people haven't mentioned, but they have mostly to do with unsafe constructs. Here's one that can be used by "regular" code though: The checked/unchecked keywords: public static int UncheckedAddition(int a, int b) { unchecked { return a + b; } } public static int CheckedAddition(int a, int b) { checked { return a + b; } // or "return checked(a + b)"; } public static void Main() { Console.WriteLine("Unchecked: " + UncheckedAddition(Int32.MaxValue, + 1)); // "Wraps around" Console.WriteLine("Checked: " + CheckedAddition(Int32.MaxValue, + 1)); // Throws an Overflow exception Console.ReadLine(); } A: Instead of using int.TryParse() or Convert.ToInt32(), I like having a static integer parsing function that returns null when it can't parse. Then I can use ?? and the ternary operator together to more clearly ensure my declaration and initialization are all done on one line in a easy-to-understand way. public static class Parser { public static int? ParseInt(string s) { int result; bool parsed = int.TryParse(s, out result); if (parsed) return result; else return null; } // ... } This is also good to avoid duplicating the left side of an assignment, but even better to avoid duplicating long calls on the right side of an assignment, such as a database calls in the following example. Instead of ugly if-then trees (which I run into often): int x = 0; YourDatabaseResultSet data = new YourDatabaseResultSet(); if (cond1) if (int.TryParse(x_input, x)){ data = YourDatabaseAccessMethod("my_proc_name", 2, x); } else{ x = -1; // do something to report "Can't Parse" } } else { x = y; data = YourDatabaseAccessMethod("my_proc_name", new SqlParameter("@param1", 2), new SqlParameter("@param2", x)); } You can do: int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y; if (x >= 0) data = YourDatabaseAccessMethod("my_proc_name", new SqlParameter("@param1", 2), new SqlParameter("@param2", x)); Much cleaner and easier to understand A: Math.Max and Min to check boundaries: I 've seen this in a lot of code: if (x < lowerBoundary) { x = lowerBoundary; } I find this smaller, cleaner and more readable: x = Math.Max(x, lowerBoundary); Or you can also use a ternary operator: x = ( x < lowerBoundary) ? lowerBoundary : x; A: Mixins are a nice feature. Basically, mixins let you have concrete code for an interface instead of a class. Then, just implement the interface in a bunch of classes, and you automatically get mixin functionality. For example, to mix in deep copying into several classes, define an interface internal interface IPrototype<T> { } Add functionality for this interface internal static class Prototype { public static T DeepCopy<T>(this IPrototype<T> target) { T copy; using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, (T)target); stream.Seek(0, SeekOrigin.Begin); copy = (T) formatter.Deserialize(stream); stream.Close(); } return copy; } } Then implement interface in any type to get a mixin. A: Regarding foreach: It does not use 'duck typing', as duck typing IMO refers to a runtime check. It uses structural type checking (as opposed to nominal) at compile time to check for the required method in the type. A: (I just used this one) Set a field null and return it without an intermediate variable: try { return _field; } finally { _field = null; } A: This isn't a C# specific feature but it is an addon that I find very useful. It is called the Resource Refactoring Tool. It allows you to right click on a literal string and extract it into a resource file. It will search the code and find any other literal strings that match and replace it with the same resource from the Resx file. http://www.codeplex.com/ResourceRefactoring A: I call this AutoDebug because you can drop right into debug where and when you need based on a bool value which could also be stored as a project user setting as well. Example: //Place at top of your code public UseAutoDebug = true; //Place anywhere in your code including catch areas in try/catch blocks Debug.Assert(!this.UseAutoDebug); Simply place the above in try/catch blocks or other areas of your code and set UseAutoDebug to true or false and drop into debug anytime you wish for testing. You can leave this code in place and toggle this feature on and off when testing, You can also save it as a Project Setting, and manually change it after deployment to get additional bug information from users when/if needed as well. You can see a functional and working example of using this technique in this Visual Studio C# Project Template here, where it is used heavily: http://code.msdn.microsoft.com/SEHE A: Method groups aren't well known. Given: Func<Func<int,int>,int,int> myFunc1 = (i, j) => i(j); Func<int, int> myFunc2 = i => i + 2; You can do this: var x = myFunc1(myFunc2, 1); instead of this: var x = myFunc1(z => myFunc2(z), 1); A: I am so so late to this question, but I wanted to add a few that I don't think have been covered. These aren't C#-specific, but I think they're worthy of mention for any C# developer. AmbientValueAttribute This is similar to DefaultValueAttribute, but instead of providing the value that a property defaults to, it provides the value that a property uses to decide whether to request its value from somewhere else. For example, for many controls in WinForms, their ForeColor and BackColor properties have an AmbientValue of Color.Empty so that they know to get their colors from their parent control. IsolatedStorageSettings This is a Silverlight one. The framework handily includes this sealed class for providing settings persistence at both the per-application and per-site level. Flag interaction with extension methods Using extension methods, flag enumeration use can be a lot more readable. public static bool Contains( this MyEnumType enumValue, MyEnumType flagValue) { return ((enumValue & flagValue) == flagValue); } public static bool ContainsAny( this MyEnumType enumValue, MyEnumType flagValue) { return ((enumValue & flagValue) > 0); } This makes checks for flag values nice and easy to read and write. Of course, it would be nicer if we could use generics and enforce T to be an enum, but that isn't allowed. Perhaps dynamic will make this easier. A: I find it incredible what type of trouble the compiler goes through to sugar code the use of Outer Variables: string output = "helo world!"; Action action = () => Console.WriteLine(output); output = "hello!"; action(); This actually prints hello!. Why? Because the compiler creates a nested class for the delegate, with public fields for all outer variables and inserts setting-code before every single call to the delegate :) Here is above code 'reflectored': Action action; <>c__DisplayClass1 CS$<>8__locals2; CS$<>8__locals2 = new <>c__DisplayClass1(); CS$<>8__locals2.output = "helo world!"; action = new Action(CS$<>8__locals2.<Main>b__0); CS$<>8__locals2.output = "hello!"; action(); Pretty cool I think. A: I couldn't figure out what use some of the functions in the Convert class had (such as Convert.ToDouble(int), Convert.ToInt(double)) until I combined them with Array.ConvertAll: int[] someArrayYouHaveAsInt; double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>( someArrayYouHaveAsInt, new Converter<int,double>(Convert.ToDouble)); Which avoids the resource allocation issues that arise from defining an inline delegate/closure (and slightly more readable): int[] someArrayYouHaveAsInt; double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>( someArrayYouHaveAsInt, new Converter<int,double>( delegate(int i) { return (double)i; } )); A: Having just learned the meaning of invariance, covariance and contravariance, I discovered the in and out generic modifiers that will be included in .NET 4.0. They seem obscure enough that most programmers would not know about them. There's an article at Visual Studio Magazine which discusses these keywords and how they will be used. A: The data type can be defined for an enumeration: enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64] { A = 1, B = 2 } A: The Yield keyword is often overlooked when it has a lot of power. I blogged about it awhile ago and discussed benefits (differed processing) and happens under the hood of yield to help give a stronger understanding. Using Yield in C# A: Pointers in C#. They can be used to do in-place string manipulation. This is an unsafe feature so the unsafe keyword is used to mark the region of unsafe code. Also note how the fixed keyword is used to indicate that the memory pointed to is pinned and cannot be moved by the GC. This is essential a pointers point to memory addresses and the GC can move the memory to different address otherwise resulting in an invalid pointer. string str = "some string"; Console.WriteLine(str); unsafe { fixed(char *s = str) { char *c = s; while(*c != '\0') { *c = Char.ToUpper(*c++); } } } Console.WriteLine(str); I wouldn't ever do it but just for the sake of this question to demonstrate this feature. A: I especially like the nullable DateTime. So if you have some cases where a Date is given and other cases where no Date is given I think this is best to use and IMHO easier to understand as using DateTime.MinValue or anything else... DateTime? myDate = null; if (myDate.HasValue) { //doSomething } else { //soSomethingElse } A: Open generics are another handy feature especially when using Inversion of Control: container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>)); A: Having read through all 9 pages of this I felt I had to point out a little unknown feature... This was held true for .NET 1.1, using compression/decompression on gzipped files, one had to either: * *Download ICSharpCode.ZipLib *Or, reference the Java library into your project and use the Java's in-built library to take advantage of the GZip's compression/decompression methods. It is underused, that I did not know about, (still use ICSharpCode.ZipLib still, even with .NET 2/3.5) was that it was incorporated into the standard BCL version 2 upwards, in the System.IO.Compression namespace... see the MSDN page "GZipStream Class". A: I find the use of the conditional break function in Visual Studio very useful. I like the way it allows me to set the value to something that, for example can only be met in rare occasions and from there I can examine the code further. A: This means T must have a public parameterless constructor : class MyClass<T> where T : new() { } A: Accessing local variables from anonymous methods allows you to wrap just about any code with new control flow logic, without having to factor out that code into another method. Local variables declared outside the method are available inside the method such as the endOfLineChar local variable in the example here: http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/ A: lambdas and type inference are underrated. Lambdas can have multiple statements and they double as a compatible delegate object automatically (just make sure the signature match) as in: Console.CancelKeyPress += (sender, e) => { Console.WriteLine("CTRL+C detected!\n"); e.Cancel = true; }; Note that I don't have a new CancellationEventHandler nor do I have to specify types of sender and e, they're inferable from the event. Which is why this is less cumbersome to writing the whole delegate (blah blah) which also requires you to specify types of parameters. Lambdas don't need to return anything and type inference is extremely powerful in context like this. And BTW, you can always return Lambdas that make Lambdas in the functional programming sense. For example, here's a lambda that makes a lambda that handles a Button.Click event: Func<int, int, EventHandler> makeHandler = (dx, dy) => (sender, e) => { var btn = (Button) sender; btn.Top += dy; btn.Left += dx; }; btnUp.Click += makeHandler(0, -1); btnDown.Click += makeHandler(0, 1); btnLeft.Click += makeHandler(-1, 0); btnRight.Click += makeHandler(1, 0); Note the chaining: (dx, dy) => (sender, e) => Now that's why I'm happy to have taken the functional programming class :-) Other than the pointers in C, I think it's the other fundamental thing you should learn :-) A: More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default on client versions of windows, but server is much faster on multicore machines. <configuration> <runtime> <gcServer enabled="true"/> </runtime> </configuration> Be careful. The server gc requires more memory. A: I couldn't see this looking above - one that I didn't realise you could do until recently is to call one constructor from another: class Example { public Example(int value1) : this(value1, "Default Value") { } public Example(int value1, string value2) { m_Value1 = value1; m_value2 = value2; } int m_Value1; string m_value2; } A: Other underused operators are checked and unchecked: short x = 32767; // 32767 is the max value for short short y = 32767; int z1 = checked((short)(x + y)); //will throw an OverflowException int z2 = unchecked((short)(x + y)); // will return -2 int z3 = (short)(x + y); // will return -2 A: Use "throw;" instead of "throw ex;" to preserve stack trace If re-throwing an exception without adding additional information, use "throw" instead of "throw ex". An empty "throw" statement in a catch block will emit specific IL that re-throws the exception while preserving the original stack trace. "throw ex" loses the stack trace to the original source of the exception. A: From Rick Strahl: You can chain the ?? operator so that you can do a bunch of null comparisons. string result = value1 ?? value2 ?? value3 ?? String.Empty; A: @lainMH, Nullable booleans are useful when retrieving values from a database that are nullable and when putting values back in. Sometimes you want to know the field has not been set. A: Reflection Emit and Expression trees come to mind... Don't miss Jeffrey Richter's CLR via C# and Jon Skeet's See here for some resources: http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx http://www.codeproject.com/KB/cs/lambdaexpressions.aspx A: System.Runtime.Remoting.Proxies.RealProxy It enables Aspect Oriented Programming in C#, and you can also do a lot of other fancy stuff with it. A: I find this technique interesting while working with linqxml: public bool GetFooSetting(XElement ndef){ return (bool?)ndef.Element("MyBoolSettingValue") ?? true; } as opposed to: public bool GetFooSetting(XElement ndef){ return ndef.Element("MyBoolSettingValue") != null ? bool.Parse(ndef.Element("MyBoolSettingValue") ) : true; } A: The generic event handler: public event EventHandler<MyEventArgs> MyEvent; This way you don't have to declare your own delegates all the time, A: I didn't discover - for almost a year - that Strongly Typed DataRows contain an Is[ColumnName]Null() method. For example: Units.UnitsDataTable dataTable = new Units.UnitsDataTable(); foreach (Units.UnitsRow row in dataTable.Rows) { if (row.IsPrimaryKeyNull()) //.... if (row.IsForeignKeyNull()) //.... } A: Is constructor chain already cited? namespace constructorChain { using System; public class Class1 { public string x; public string y; public Class1() { x = "class1"; y = ""; } public Class1(string y) : this() { this.y = y; } } public class Class2 : Class1 { public Class2(int y) : base(y.ToString()) { } } } ... constructorChain.Class1 c1 = new constructorChain.Class1(); constructorChain.Class1 c12 = new constructorChain.Class1("Hello, Constructor!"); constructorChain.Class2 c2 = new constructorChain.Class2(10); Console.WriteLine("{0}:{1}", c1.x, c1.y); Console.WriteLine("{0}:{1}", c12.x, c12.y); Console.WriteLine("{0}:{1}", c2.x, c2.y); Console.ReadLine(); A: FIXED / Power of Pointers in C# - This topic is too big, but I will just outline simple things. In C we had facility of loading structure like... struct cType{ char type[4]; int size; char name[50]; char email[100]; } cType myType; fread(file, &mType, sizeof(mType)); We can use fixed keyword in "unsafe" method to read byte array aligned structure. [Layout(LayoutKind.Sequential, Pack=1)] public unsafe class CType{ public fixed byte type[4]; public int size; public fixed byte name[50]; public fixed byte email[100]; } Method 1 (Reading from regular stream in to byte buffer and mapping byte array to individual bytes of struct) CType mType = new CType(); byte[] buffer = new byte[Marshal.SizeOf(CType)]; stream.Read(buffer,0,buffer.Length); // you can map your buffer back to your struct... fixed(CType* sp = &mType) { byte* bsp = (byte*) sp; fixed(byte* bp = &buffer) { for(int i=0;i<buffer.Length;i++) { (*bsp) = (*bp); bsp++;bp++; } } } Method 2, you can map Win32 User32.dll's ReadFile to directly read bytes... CType mType = new CType(); fixed(CType* p = &mType) { User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0); } A: I like to use the using directive to rename some classes for easy reading like this: // defines a descriptive name for a complexed data type using MyDomainClassList = System.Collections.Generic.List< MyProjectNameSpace.MyDomainClass>; .... MyDomainClassList myList = new MyDomainClassList(); /* instead of List<MyDomainClass> myList = new List<MyDomainClass>(); */ This is also very handy for code maintenance. If you need to change the class name, there is only one place you need to change. Another example: using FloatValue = float; // you only need to change it once to decimal, double... .... FloatValue val1; ... A: Zero parameter Lambdas ()=>Console.ReadLine() A: I didn't see this: for (;;); The same as while (true) ; A: One that I just learned recently is that you can still call methods on a nullable value.... It turns out what when you have a nullable value: decimal? MyValue = null; where you might think you would have to write: MyValue == null ? null : MyValue .ToString() you can instead write: MyValue.ToString() I've been aware that I could call MyValue.HasValue and MyValue.Value...but it didn't fully click that I could call ToString(). A: This will not compile: namespace ns { class Class1 { Nullable<int> a; } } The type or namespace name 'Nullable' could not be found (are you missing a using directive or an assembly reference?) <-- missing 'using System;' But namespace ns { class Class1 { int? a; } } will compile! (.NET 2.0). A: I apologize if this one has been mentioned, but I use this a lot. An add-in for Visual Studio was developed by Alex Papadimoulis. It's used for pasting regular text as string, string builder, comment or region. http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx In this plugin (I also don't know if this has been mentioned) I noticed that strings are pasted with the string literal prefix: @ I knew about these, but I didn't know about using a double quote within a literal to escape the quote. For example string s = "A line of text" + Environment.NewLine + "Another with a \"quote\"!!"; can be expressed as string s = @"A line of text Another with a ""quote""!!"; A: I like the EditorBrowsableAttribute. It lets you control whether a method/property is displayed or not in Intellisense. You can set the values to Always, Advanced, or Never. From MSDN... Remarks EditorBrowsableAttribute is a hint to a designer indicating whether a property or method is to be displayed. You can use this type in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method. In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced. A: __arglist as well [DllImport("msvcrt40.dll")] public static extern int printf(string format, __arglist); static void Main(string[] args) { printf("Hello %s!\n", __arglist("Bart")); } A: The Action and Func delegate helpers in conjunction with lambda methods. I use these for simple patterns that need a delegate to improve readability. For example, a simple caching pattern would be to check if the requested object exists in the cache. If it does exist: return the cached object. If it doesn't exist, generate a new instance, cache the new instance and return the new instance. Rather that write this code 1000 times for each object I may store/retrieve from the cache I can write a simple pattern method like so... private static T CachePattern<T>(string key, Func<T> create) where T : class { if (cache[key] == null) { cache.Add(key, create()); } return cache[key] as T; } ... then I can greatly simplify my cache get/set code by using the following in my custom cache manager public static IUser CurrentUser { get { return CachePattern<IUser>("CurrentUserKey", () => repository.NewUpUser()); } } Now simple "everyday" code patterns can be written once and reused much more easily IMHO. I don't have to go write a delegate type and figure out how I want to implement a callback, etc. If I can write it in 10 seconds I'm much less apt. to resort to cutting/pasting simple code patterns whether they be lazy initialization and some other examples shown above... A: Empty blocks with braces are allowed. You can write code like this { service.DoTonsOfWork(args); } It's helpful when you want to try something without a using or try... finally that you've already written. //using(var scope = new TransactionScope) { service.DoTonsOfWork(args); } A: Nullable.GetValueOrDefault ? A: A few hidden features I've come across: * *stackalloc which lets you allocate arrays on the stack *Anonymous methods with no explicit parameter list, which are implicitly convertible to any delegate type with non-out/ref parameters (very handy for events, as noted in an earlier comment) *A lot of people aren't aware of what events really are (an add/remove pair of methods, like get/set for properties); field-like events in C# really declare both a variable and an event *The == and != operators can be overloaded to return types other than bool. Strange but true. *The query expression translation in C# 3 is really "simple" in some ways - which means you can get it to do some very odd things. *Nullable types have special boxing behaviour: a null value gets boxed to a null reference, and you can unbox from null to the nullable type too. A: I just wanted to copy that code without the comments. So, the trick is to simply press the Alt button, and then highlight the rectangle you like.(e. g. below). protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { //if (e.CommandName == "sel") //{ // lblCat.Text = e.CommandArgument.ToString(); //} } In the above code if I want to select : e.CommandName == "sel" lblCat.Text = e.Comman Then I press ALt key and select the rectangle and no need to uncomment the lines. Check this out. A: @David in Dakota: Console.WriteLine( "-".PadRight( 21, '-' ) ); I used to do this, until I discovered that the String class has a constructor that allows you to do the same thing in a cleaner way: new String('-',22); A: The volatile keyword to tell the compiler that a field can be modified by multiple threads concurrently. A: Aliased generics: using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>; It allows you to use ASimpleName, instead of Dictionary<string, Dictionary<string, List<string>>>. Use it when you would use the same generic big long complex thing in a lot of places. A: A couple of things I like: -If you create an interface similar to public interface SomeObject<T> where T : SomeObject<T>, new() you force anything that inherits from this interface to contain a parameterless constructor. It is very useful for a couple of things I've run across. -Using anonymous types to create a useful object on the fly: var myAwesomeObject = new {Name="Foo", Size=10}; -Finally, many Java developers are familiar with syntax like: public synchronized void MySynchronizedMethod(){} However, in C# this is not valid syntax. The workaround is a method attribute: [MethodImpl(MethodImplOptions.Synchronized)] public void MySynchronizedMethod(){} A: The params keyword, i.e. public void DoSomething(params string[] theStrings) { foreach(string s in theStrings) { // Something with the Strings… } } Called like DoSomething(“The”, “cat”, “sat”, “on”, “the” ,”mat”); A: Foreach uses Duck Typing Paraphrasing, or shamelessly stealing from Krzysztof Cwalinas blog on this. More interesting trivia than anything. For your object to support foreach, you don't have to implement IEnumerable. I.e. this is not a constraint and it isn't checked by the compiler. What's checked is that * *Your object provide a public method GetEnumerator that * *takes no parameters *return a type that has two members * *a parameterless method MoveNext that returns a boolean *a property Current with a getter that returns an Object For example, class Foo { public Bar GetEnumerator() { return new Bar(); } public struct Bar { public bool MoveNext() { return false; } public object Current { get { return null; } } } } // the following complies just fine: Foo f = new Foo(); foreach (object o in f) { Console.WriteLine("Krzysztof Cwalina's da man!"); } A: From CLR via C#: When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons. I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why. A: Static constructors. Instances: public class Example { static Example() { // Code to execute during type initialization } public Example() { // Code to execute during object initialization } } Static classes: public static class Example { static Example() { // Code to execute during type initialization } } MSDN says: A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced. For example: public class MyWebService { public static DateTime StartTime; static MyWebService() { MyWebService.StartTime = DateTime.Now; } public TimeSpan Uptime { get { return DateTime.Now - MyWebService.StartTime; } } } But, you could also just as easily have done: public class MyWebService { public static DateTime StartTime = DateTime.Now; public TimeSpan Uptime { get { return DateTime.Now - MyWebService.StartTime; } } } So you'll be hard-pressed to find any instance when you actually need to use a static constructor. MSDN offers useful notes on static constructors: * *A static constructor does not take access modifiers or have parameters. *A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. *A static constructor cannot be called directly. *The user has no control on when the static constructor is executed in the program. *A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. *Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method. *If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running. The most important note is that if an error occurs in the static constructor, a TypeIntializationException is thrown and you cannot drill down to the offending line of code. Instead, you have to examine the TypeInitializationException's InnerException member, which is the specific cause. A: My favorite trick is using the null coalesce operator and parentheses to automagically instantiate collections for me. private IList<Foo> _foo; public IList<Foo> ListOfFoo { get { return _foo ?? (_foo = new List<Foo>()); } } A: A couple other attributes from the System.Diagnostics namespace are quite helpful. DebuggerBrowsable will let you hide variables from the debugger window (we use it for all private backing variables of exposed properties). Along with that, DebuggerStepThrough makes the debugger step over that code, very useful for dumb properties (probably should be converted to auto-properties if you can take a dependency to the C# 3.0 compiler). As an example [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string nickName; public string NickName { [DebuggerStepThrough] get { return nickName; } [DebuggerStepThrough] set { this.nickName = value; } } A: One interesting thing I've learned is that different parts of the framework and C# language were written at different times, hence inconsistencies. For example, the framework itself violates many FxCop rules because the rules weren't all in place when the framework was written. Also, the using statement was intended for delinieating "scopes" and not specifically for disposing resources. It was written after the lock statement. Eric Gunnerson once mentioned something along the lines of that if the using statement came first, they might have not needed to write the lock statement (though who knows, maybe they would have anyways), because the using statement might have been sufficient. A: TryParse method for each primitive type is great when validating user input. double doubleValue if (!Double.TryParse(myDataRow("myColumn"), out doubleValue)) { // set validation error } A: The #region {string} and #endregion pair is very neat for grouping code (outlining). #region Using statements using System; using System.IO; using ....; using ....; #endregion The code block can be compressed to a single describing line of text. Works inside functions aswell. A: I think a lot of people know about pointers in C but are not sure if it works in C#. You can use pointers in C# in an unsafe context: static void Main() { int i; unsafe { // pointer pi has the address of variable i int* pi = &i; // pointer ppi has the address of variable pi int** ppi = &pi; // ppi(addess of pi) -> pi(addess of i) -> i(0) i = 0; // dereference the pi, i.e. *pi is i Console.WriteLine("i = {0}", *pi); // output: i = 0 // since *pi is i, equivalent to i++ (*pi)++; Console.WriteLine("i = {0}", *pi); // output: i = 1 // since *ppi is pi, one more dereference *pi is i // equivalent to i += 2 **ppi += 2; Console.WriteLine("i = {0}", *pi);// output: i = 3 } Console.ReadLine(); } A: This may be pretty basic to database application developers, but it took me a while to realize that null is not the same as DBNull.value. You have to use DBNull.value when you want to see if a value from a database record is null. A: Just learned the joys of [UnmanagedFunctionPointerAttribute(CallingConvention.CDecl)] from trying to interface with an unmanaged C++ function library that defined callbacks without __stdcall. A: Framework Feature I don't know but I was quite suprised about VisualStyleRenderer and the whole System.Windows.Forms.VisualStyles-Namespace. Pretty cool! A: The InternalsVisibleToAttribute specifies that types that are ordinarily visible only within the current assembly are visible to another assembly. Article on msdn A: If you have the search textbox in your Visual Studio toolbar, you can type ">of Program.cs" to open the file Program.cs A: A few from me - make of them what you will. The attribute: [assembly::InternalsVisibleTo("SomeAssembly")] Allows you to expose out the internal methods/properties or data from your assembly to another assembly called 'SomeAssembly'. All protected/private stuff remains hidden. Static constructors ( otherwise called 'Type Constructor' ) public MyClass { public static MyClass() { // type init goes here } ...... } The keyword internal. So useful in so many ways. A: Ability to create instance of the type based on the generic parameter like this new T(); A: Marketing events as non-serializable: [field:NonSerializable] public event SomeDelegate SomeEvent; A: Generic constraints: //Constructor constraint, T has a default empty constructor class Node<K,T> where T : new() { } //Reference\Value Type constraints //T is a struct public class MyClass<T> where T : struct {...} //T is a reference type public class MyClass<T> where T : class {...} public class MyClass<T> where T : SomeBaseClass, ISomeInterface {...} A: How about Expression Trees? They are the heart of LINQ and allow for defered execution: Taken from David Hayden's blog: In C# 3.0, you can define a delegate as follows using a lambda expression: Func<int,int> f = x => x + 1; This delegate is compiled into executable code in your application and can be called as such: var three = f(2); // 2 + 1 The code works as you would expect. Nothing fancy here. Expression Trees When you define the delegate as an Expression Tree by using System.Query.Expression: Expression<Func<int,int>> expression = x => x + 1; The delegate is no longer compiled into executable code, but compiled as data that can be converted and compiled into the original delegate. To actually use the delegate represented as an Expression Tree in your application, you would have to compile and invoke it in your application: var originalDelegate = expression.Compile(); var three = originalDelegate.Invoke(2); A: A lot of this is explained already, in the standard. It's a good read for any beginner as well as expert, it's a lot to read, but it's the official standard, and it's filled with juicy details. Once you fully understand C#, it's time to take this further to understand the fundamentals of the Common Language Infrastructure. The architecture and underpinnings of C#. I've met a variety of programmers that don't know the difference between an object and a ValueType except the adherent limitations thereof. Familiarize yourself with these two documents and you'll never become that person. A: Generics and the Curiously-Recurring Template Pattern really help with some static method/property declarations. Suppose you are building a class hierarchy: class Base { } class Foo: Base { } class Bar: Base { } Now, you want to declare static methods on your types that should take parameters (or return values) of the same type or static properties of the same type. For example, you want: class Base { public static Base Get() { // Return a suitable Base. } } class Foo: Base { public static Foo Get() { // Return a suitable Foo. } } class Bar: Base { public static Bar Get() { // Return a suitable Bar. } } If these static methods basically all do the same thing, then you have lots of duplicated code on your hands. One solution would be to drop type safety on the return values and to always return type Base. However, if you want type safety, then the solution is to declare the Base as: class Base<T> where T: Base<T> { public static T Get<T>() { // Return a suitable T. } } and you Foo and Bar as: class Foo: Base<Foo> { } class Bar: Base<Bar> { } This way, they will automatically get their copies of the static methods. This also works wonders to encapsulate the Singleton pattern in a base class (I know the code below is not thread-safe, it just to demonstrate a point): public class Singleton<T> where T: Singleton<T>, new() { public static T Instance { get; private set; } static Singleton<T>() { Instance = new T(); } } I realize that this forces you to have a public parameterless constructor on your singleton subclass but there is no way to avoid that at compile time without a where T: protected new() construct; however one can use reflection to invoke the protected/private parameterless constructor of the sub-class at runtime to achieve that. A: I love abusing the fact that static templated classes don't share their static members. Here's a threadsafe (at creation time) and cheap substitute to any Dictionary<Type,...> when the Type instance is known at compile-time. public static class MyCachedData<T>{ static readonly CachedData Value; static MyCachedData(){ Value=// Heavy computation, such as baking IL code or doing lots of reflection on a type } } Cheers, Florian A: Convert enum values to a string value Given the enum enum Country { UnitedKingdom, UnitedStates, UnitedArabEmirates, } using it: public static void PrintEnumAsString( Country country ) { Console.Writeline( country.ToString() ); } will print the name of the enum value as a string, e.g. "UnitedKingdom" A: * *Attaching ? to a Type to make it nullable, ex: int? *"c:\dir" instead of @"C:\dir" A: I just want to mention (because of the OP metioning where T : struct) that one of the C# compiler gotchas is that where T : Enum will NOT compile. It throws the error "Constraint cannot be special class 'System.Enum'". A: Collection Initializer inside Object Initializer: MailMessage mail = new MailMessage { To = { new MailAddress("a@example.com"), new MailAddress("b@example.com") }, Subject = "Password Recovery" }; You can initialize a whole tree in a single expression. A: I am bit late in this conversation and I would like to contribute the following. It may be a new thing for some developers. public class User { public long UserId { get; set; } public String Name { get; set; } public String Password { get; set; } public String Email { get; set; } } The usual way to declare and initialize it is with a constructor or like following. User user = new User(); user.UserId = 1; user.Name = "myname"; etc But I learned following way to initialize it. I know Visual Basic developers will love it because it's like with operator available only in VB.NET and not in C# that is as follows. User user = new User() { UserId = 1, Name = "myname", Email = "myemail@domain.com", Password = "mypassword" }; A: One of the most useful features Visual Studio has is "Make object id". It generates an id and "attaches" to the object so wherever you look at the object you will also see the id (regardless of the thread). While debugging right click on the variable tooltip and there you have it. It also works on watched/autos/locals variables. A: This relates to static constructors. This is a method for performing static destruction (i.e. cleaning up resources when the program quits). First off the class: class StaticDestructor { /// <summary> /// The delegate that is invoked when the destructor is called. /// </summary> public delegate void Handler(); private Handler doDestroy; /// <summary> /// Creates a new static destructor with the specified delegate to handle the destruction. /// </summary> /// <param name="method">The delegate that will handle destruction.</param> public StaticDestructor(Handler method) { doDestroy = method; } ~StaticDestructor() { doDestroy(); } } Then as a member of the class you wish to have a "static destructor" do: private static readonly StaticDestructor destructor = new StaticDestructor ( delegate() { //Cleanup here } ); This will now be called when final garbage collection occurs. This is useful if you absolutely need to free up certain resources. A quick and dirty program exhibiting this behavior: using System; namespace TestStaticDestructor { class StaticDestructor { public delegate void Handler(); private Handler doDestroy; public StaticDestructor(Handler method) { doDestroy = method; } ~StaticDestructor() { doDestroy(); } } class SomeClass { static SomeClass() { Console.WriteLine("Statically constructed!"); } static readonly StaticDestructor destructor = new StaticDestructor( delegate() { Console.WriteLine("Statically destructed!"); } ); } class Program { static void Main(string[] args) { SomeClass someClass = new SomeClass(); someClass = null; System.Threading.Thread.Sleep(1000); } } } When the program exits, the "static destructor" is called. A: I don't condone it, but I was surprised that goto is still around ducks incoming projectiles A: You can combine the protected and internal accessor to make it public within the same assembly, but protected in a diffrent assembly. This can be used on fields, properties, method and even constants. A: C# + CLR: * *Thread.MemoryBarrier: Most people wouldn't have used it and there is some inaccurate information on MSDN. But if you know intricacies then you can do nifty lock-free synchronization. *volatile, Thread.VolatileRead, Thread.VolatileWrite: There are very very few people who gets the use of these and even fewer who understands all the risks they avoid and introduce :). *ThreadStatic variables: There was only one situation in past few years I've found that ThreadStatic variables were absolutely god send and indispensable. When you want to do something for entire call chain, for example, they are very useful. *fixed keyword: It's a hidden weapon when you want to make access to elements of large array almost as fast as C++ (by default C# enforces bound checks that slows down things). *default(typeName) keyword can be used outside of generic class as well. It's useful to create empty copy of struct. *One of the handy feature I use is DataRow[columnName].ToString() always returns non-null value. If value in database was NULL, you get empty string. *Use Debugger object to break automatically when you want developer's attention even if s/he hasn't enabled automatic break on exception: #if DEBUG if (Debugger.IsAttached) Debugger.Break(); #endif *You can alias complicated ugly looking generic types so you don't have to copy paste them again and again. Also you can make changes to that type in one place. For example, using ComplicatedDictionary = Dictionary<int, Dictionary<string, object>>; ComplicatedDictionary myDictionary = new ComplicatedDictionary(); A: Closures Since anonymous delegates were added to 2.0, we have been able to develop closures. They are rarely used by programmers but provide great benefits such as immediate code reuse. Consider this piece of code: bool changed = false; if (model.Prop1 != prop1) { changed = true; model.Prop1 = prop1; } if (model.Prop2 != prop2) { changed = true; model.Prop2 = prop2; } // ... etc. Note that the if-statements above perform similar pieces of code with the exception of one line of code, i.e. setting different properties. This can be shortened with the following, where the varying line of code is entered as a parameter to an Action object, appropriately named setAndTagChanged: bool changed = false; Action<Action> setAndTagChanged = (action) => { changed = true; action(); }; if (model.Prop1 != prop1) setAndTagChanged(() => model.Prop1 = prop1); if (model.Prop2 != prop2) setAndTagChanged(() => model.Prop2 = prop2); In the second case, the closure allows you to scope the change variable in your lambda, which is a concise way to approach this problem. An alternate way is to use another unused feature, the "or equal" binary assignment operator. The following code shows how: private bool conditionalSet(bool condition, Action action) { if (condition) action(); return condition; } // ... bool changed = false; changed |= conditionalSet(model.Prop1 == prop1, () => model.Prop1 = prop1); changed |= conditionalSet(model.Prop2 == prop2, () => model.Prop2 = prop2); A: I'd say using certain system classes for extension methods is very handy, for example System.Enum, you can do something like below... [Flags] public enum ErrorTypes : int { None = 0, MissingPassword = 1, MissingUsername = 2, PasswordIncorrect = 4 } public static class EnumExtensions { public static T Append<T> (this System.Enum type, T value) where T : struct { return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value)); } public static T Remove<T> (this System.Enum type, T value) where T : struct { return (T)(ValueType)(((int)(ValueType)type & ~(int)(ValueType)value)); } public static bool Has<T> (this System.Enum type, T value) where T : struct { return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value); } } ... //used like the following... ErrorTypes error = ErrorTypes.None; error = error.Append(ErrorTypes.MissingUsername); error = error.Append(ErrorTypes.MissingPassword); error = error.Remove(ErrorTypes.MissingUsername); //then you can check using other methods if (error.Has(ErrorTypes.MissingUsername)) { ... } This is just an example of course - the methods could use a little more work... A: Being able to have enum types have values other than int (the default) public enum MyEnum : long { Val1 = 1, Val2 = 2 } Also, the fact that you can assign any numeric value to that enum: MyEnum e = (MyEnum)123; A: I just found out about this one today -- and I've been working with C# for 5 years! It's the namespace alias qualifier: extern alias YourAliasHere; You can use it to load multiple versions of the same type. This can be useful in maintenance or upgrade scenarios where you have an updated version of your type that won't work in some old code, but you need to upgrade it to the new version. Slap on a namespace alias qualifier, and the compiler will let you have both types in your code. A: RealProxy lets you create your own proxies for existing types. This is super-advanced and I haven't seen anyone else use it -- which may mean that it's also really not that useful for most folks -- but it's one of those things that's good to know. Basically, the .NET RealProxy class lets you create what is called a transparent proxy to another type. Transparent in this case means that it looks completely like the proxied target object to its client -- but it's really not: it's an instance of your class, which is derived from RealProxy. This lets you apply powerful and comprehensive interception and "intermediation" services between the client and any methods or properties invoked on the real target object. Couple this power with the factory pattern (IoC etc), and you can hand back transparent proxies instead of real objects, allowing you to intercept all calls to the real objects and perform actions before and after each method invocation. In fact, I believe this is the very functionality .NET uses for remoting across app domain, process, and machine boundaries: .NET intercepts all access, sends serialized info to the remote object, receives the response, and returns it to your code. Maybe an example will make it clear how this can be useful: I created a reference service stack for my last job as enterprise architect which specified the standard internal composition (the "stack") of any new WCF services across the division. The model mandated that the data access layer for (say) the Foo service implement IDAL<Foo>: create a Foo, read a Foo, update a Foo, delete a Foo. Service developers used supplied common code (from me) that would locate and load the required DAL for a service: IDAL<T> GetDAL<T>(); // retrieve data access layer for entity T Data access strategies in that company had often been, well, performance-challenged. As an architect, I couldn't watch over every service developer to make sure that he/she wrote a performant data access layer. But what I could do within the GetDAL factory pattern was create a transparent proxy to the requested DAL (once the common service model code located the DLL and loaded it), and use high-performance timing APIs to profile all calls to any method of the DAL. Ranking laggards then is just a matter of sorting DAL call timings by descending total time. The advantage to this over development profiling (e.g. in the IDE) is that it can be done in the production environment as well, to ensure SLAs. Here is an example of test code I wrote for the "entity profiler," which was common code to create a profiling proxy for any type with a single line: [Test, Category("ProfileEntity")] public void MyTest() { // this is the object that we want profiled. // we would normally pass this around and call // methods on this instance. DALToBeProfiled dal = new DALToBeProfiled(); // To profile, instead we obtain our proxy // and pass it around instead. DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal); // or... DALToBeProfiled dalProxy2 = EntityProfiler<DALToBeProfiled>.Instance(dal); // Now use proxy wherever we would have used the original... // All methods' timings are automatically recorded // with a high-resolution timer DoStuffToThisObject(dalProxy); // Output profiling results ProfileManager.Instance.ToConsole(); } Again, this lets you intercept all methods and properties called by the client on the target object! In your RealProxy-derived class, you have to override Invoke: [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop public override IMessage Invoke(IMessage msg) { IMethodCallMessage msgMethodCall = msg as IMethodCallMessage; Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28 // The MethodCallMessageWrapper // provides read/write access to the method // call arguments. MethodCallMessageWrapper mc = new MethodCallMessageWrapper(msgMethodCall); // This is the reflected method base of the called method. MethodInfo mi = (MethodInfo)mc.MethodBase; IMessage retval = null; // Pass the call to the method and get our return value string profileName = ProfileClassName + "." + mi.Name; using (ProfileManager.Start(profileName)) { IMessage myReturnMessage = RemotingServices.ExecuteMessage(_target, msgMethodCall); retval = myReturnMessage; } return retval; } Isn't it fascinating what .NET can do? The only restriction is that the target type must be derived from MarshalByRefObject. I hope this is helpful to someone. A: Arbitrary nested scopes { } 1. For finer scoping behaviour { anywhere inside members }, { using only braces }, { with no control statement }. void MyWritingMethod() { int sameAge = 35; { // scope some work string name = "Joe"; Log.Write(name + sameAge.ToString()); } { // scope some other work string name = "Susan"; Log.Write(name + sameAge.ToString()); } // I'll never mix up Joe and Susan again } Inside large, confusing or archaic members (not that they should ever exist, however,) it helps me prevent against using wrong variable names. Scope stuff to finer levels. 2. For code beautification or visual semantics For example, this XML writing code follows the indentation level of the actual generated XML (i.e. Visual Studio will indent the scoping braces accordingly) XmlWriter xw = new XmlWriter(..); //<root> xw.WriteStartElement("root"); { //<game> xw.WriteStartElement("game"); { //<score>#</score> for (int i = 0; i < scores.Length; ++i) // multiple scores xw.WriteElementString("score", scores[i].ToString()); } //</game> xw.WriteEndElement(); } //</root> xw.WriteEndElement(); 3. Mimic a 'with' statement (Also another use to keep temp work out of the main scope) Provided by Patrik: sometimes used to mimic the VB "with-statement" in C#. var somePerson = this.GetPerson(); // whatever { var p = somePerson; p.FirstName = "John"; p.LastName = "Doe"; //... p.City = "Gotham"; } For the discerning programmer. A: Not hidden, but I think that a lot of developers are not using the HasValue and Value properties on the nullable types. int? x = null; int y; if (x.HasValue) y = x.Value; A: My favourite is the global:: keyword to escape namespace hell with some of our 3rd party code providers... Example: global::System.Collections.Generic.List<global::System.String> myList = new global::System.Collections.Generic.List<global::System.String>(); A: Avoid checking for null event handlers Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example: public delegate void MyClickHandler(object sender, string myValue); public event MyClickHandler Click = delegate {}; // add empty delegate! Let you do this public void DoSomething() { Click(this, "foo"); } Instead of this public void DoSomething() { // Unnecessary! MyClickHandler click = Click; if (click != null) // Unnecessary! { click(this, "foo"); } } Please also see this related discussion and this blog post by Eric Lippert on this topic (and possible downsides). A: I've read through all seven pages, and I'm missing these: String.Join I've seen a lot of for-loops to convert a list of items to a string with separators. It's always a pain to make sure you doin't start with a separator and don't end with a separator. A built-in method makes this easier: String.Join(",", new String[] { "a", "b", "c"}); TODO in comment Not really a C# feature, more of a Visual Studio feature. When you start your comment with TODO, it's added to your Visual Studio Task List (View -> Task List. Comments) // TODO: Implement this! throw new NotImplementedException(); Extension methods meets Generics You can combine extension methods with Generics, when you think of the tip earlier in this topic, you can add extensions to specific interfaces public static void Process<T>(this T item) where T:ITest,ITest2 {} Enumerable.Range Just want a list of integers? Enumerable.Range(0, 15) I'll try to think of some more... A: You can "use" multiple objects in one using statement. using (Font f1= new Font("Arial", 10.0f), f2 = new Font("Arial", 10.0f)) { // Use f1 and f2. } Note that there is already an answer stating that you can do this: using (Font f1= new Font("Arial", 10.0f)) using (Font f2 = new Font("Arial", 10.0f)) { } Which is different from mine. A: Width in string.Format() Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1); Console.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2); produces from Prabir's Blog | Hidden C# feature A: typedefs Someone posted that they miss typedefs but you can do it like this using ListOfDictionary = System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>; and declare it as ListOfDictionary list = new ListOfDictionary(); A: Everything else, plus 1) implicit generics (why only on methods and not on classes?) void GenericMethod<T>( T input ) { ... } //Infer type, so GenericMethod<int>(23); //You don't need the <>. GenericMethod(23); //Is enough. 2) simple lambdas with one parameter: x => x.ToString() //simplify so many calls 3) anonymous types and initialisers: //Duck-typed: works with any .Add method. var colours = new Dictionary<string, string> { { "red", "#ff0000" }, { "green", "#00ff00" }, { "blue", "#0000ff" } }; int[] arrayOfInt = { 1, 2, 3, 4, 5 }; Another one: 4) Auto properties can have different scopes: public int MyId { get; private set; } Thanks @pzycoman for reminding me: 5) Namespace aliases (not that you're likely to need this particular distinction): using web = System.Web.UI.WebControls; using win = System.Windows.Forms; web::Control aWebControl = new web::Control(); win::Control aFormControl = new win::Control(); A: I like the keyword continue. If you hit a condition in a loop and don't want to do anything but advance the loop just stick in "continue;". E.g.: foreach(object o in ACollection) { if(NotInterested) continue; } A: Returning IQueryable projections protected void LdsPostings_Selecting(object sender, LinqDataSourceSelectEventArgs e) { var dc = new MyDataContext(); var query = dc.Posting.AsQueryable(); if (isCondition1) { query = query.Where(q => q.PostedBy == Username); e.Result = QueryProjection(query); return; } ... if (isConditionN) { query = query.Where(q => q.Status.StatusName == "submitted"); query = query.Where(q => q.ReviewedBy == Username); e.Result = QueryProjection(query); return; } } and rather than coding the projection multiple times, create a single method: private IQueryable QueryProjection(IQueryable<Posting> query) { return query.Select(p => new { p.PostingID, p.Category.CategoryName, p.Type.TypeName, p.Status.StatusName, p.Description, p.Updated, p.PostedBy, p.ReviewedBy, }); } A: ContextBoundObject Not so much a C# thing as a .NET thing. It's another way of achieving DI although it can be hardwork. And you have to inherit from it which can be off putting. http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx I've used it to add logging when I decorate a class/method with a custom logging attribute. A: double dSqrd = Math.Pow(d,2.0); is more accurate than double dSqrd = d * d; // Here we can lose precision A: ThreadStaticAttribute is a favorite of mine. Also, NonSerializableAttribute is useful. (Can you tell I do a lot of server stuff using remoting?) A: ViewState getters can be one-liners. Using a default value: public string Caption { get { return (string) (ViewState["Caption"] ?? "Foo"); } set { ViewState["Caption"] = value; } } public int Index { get { return (int) (ViewState["Index"] ?? 0); } set { ViewState["Index"] = value; } } Using null as the default: public string Caption { get { return (string) ViewState["Caption"]; } set { ViewState["Caption"] = value; } } public int? Index { get { return (int?) ViewState["Index"]; } set { ViewState["Index"] = value; } } This works for anything backed by a dictionary. A: Only for reference - enum binary operations using the extension method. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace BinaryOpGenericTest { [Flags] enum MyFlags { A = 1, B = 2, C = 4 } static class EnumExtensions { private static Dictionary<Type, Delegate> m_operations = new Dictionary<Type, Delegate>(); public static bool IsFlagSet<T>(this T firstOperand, T secondOperand) where T : struct { Type enumType = typeof(T); if (!enumType.IsEnum) { throw new InvalidOperationException("Enum type parameter required"); } Delegate funcImplementorBase = null; m_operations.TryGetValue(enumType, out funcImplementorBase); Func<T, T, bool> funcImplementor = funcImplementorBase as Func<T, T, bool>; if (funcImplementor == null) { funcImplementor = buildFuncImplementor(secondOperand); } return funcImplementor(firstOperand, secondOperand); } private static Func<T, T, bool> buildFuncImplementor<T>(T val) where T : struct { var first = Expression.Parameter(val.GetType(), "first"); var second = Expression.Parameter(val.GetType(), "second"); Expression convertSecondExpresion = Expression.Convert(second, typeof(int)); var andOperator = Expression.Lambda<Func<T, T, bool>>(Expression.Equal( Expression.And( Expression.Convert(first, typeof(int)), convertSecondExpresion), convertSecondExpresion), new[] { first, second }); Func<T, T, bool> andOperatorFunc = andOperator.Compile(); m_operations[typeof(T)] = andOperatorFunc; return andOperatorFunc; } } class Program { static void Main(string[] args) { MyFlags flag = MyFlags.A | MyFlags.B; Console.WriteLine(flag.IsFlagSet(MyFlags.A)); Console.WriteLine(EnumExtensions.IsFlagSet(flag, MyFlags.C)); Console.ReadLine(); } } } A: Well... Don't use it, but a lot of people don't know C# supports the evil goto:) static void Example() { int i = 0; top: Console.WriteLine(i.ToString()); if (i == 0) { i++; goto top; } } A: Definitely the Func<> types when used with statement lambdas in .NET 3.5. These allow customizable functions, and can be a great aid in offering user customizable objects without subclassing them or resorting to some limited system like keeping track of a variable that lists what button or key the user wants to monitor. Also, they can be called just like regular methods and can be assigned like variables. The only downside that I can think of is that you're limited to 5 arguments! Although by that point you might want to consider a different solution... Edit: Providing some examples. ... public Func<InputHelper, float> _horizontalCameraMovement = (InputHelper input) => { return (input.LeftStickPosition.X * _moveRate) * _zoom; } public Func<InputHelper, float> _verticalCameraMovement = (InputHelper input) => { return (-input.LeftStickPosition.Y * _moveRate) * _zoom; } ... public void Update(InputHelper input) { ... position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input)); ... } In this example, you can write a function that does arbitrary calculation and returns a float that will determine the amount that the camera moves by. Not the best code but it gets the point across. private int foo; public int FooProperty { get { if (_onFooGotten() == true) return _foo; } set { if (onFooSet() == true) _foo = value; } } ... public Func<bool> _onFooGotten = () => { //do whatever... return true; } public Func<bool> _onFooSet = () => { //do whatever... return true; } This isn't the best example (as I haven't really explored this use yet) but it shows an example of using a lambda function for a quick event raiser without the hassle of delegates. Edit: thought of another one. Nullables! The closest thing C# has to optional parameters. A: If you are trying to create a comma delimited string from a list of items: string[] itemList = { "Example 1", "Example 2", "Example 3" }; CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection(); commaStr.AddRange(itemList); //outputs Example 1,Example 2,Example 3 Look here for another example. A: Keeps DataGridView from showing the property: [System.ComponentModel.Browsable(false)] public String LastActionID{get; private set;} Lets you set a friendly display for components (like a DataGrid or DataGridView): [System.ComponentModel.DisplayName("Last Action")] public String LastAction{get; private set;} For your backing variables, if you don't want anything accessing them directly this makes it tougher: [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] private DataController p_dataSources; A: At first - DebuggerTypeProxy. [DebuggerTypeProxy(typeof(HashtableDebugView))] class MyHashtable : Hashtable { private const string TestString = "This should not appear in the debug window."; internal class HashtableDebugView { private Hashtable hashtable; public const string TestStringProxy = "This should appear in the debug window."; // The constructor for the type proxy class must have a // constructor that takes the target type as a parameter. public HashtableDebugView(Hashtable hashtable) { this.hashtable = hashtable; } } } At second: ICustomTypeDescriptor A: The following one is not hidden, but it's quite implicit. I don't know whether samples like the following one have been published here, and I can't see are there any benefits (probably there are none), but I'll try to show a "weird" code. The following sample simulates for statement via functors in C# (delegates / anonymous delegates [lambdas]) and closures. Other flow statements like if, if/else, while and do/whle are simulated as well, but I'm not sure for switch (perhaps, I'm too lazy :)). I've compacted the sample source code a little to make it more clear. private static readonly Action EmptyAction = () => { }; private static readonly Func<bool> EmptyCondition = () => { return true; }; private sealed class BreakStatementException : Exception { } private sealed class ContinueStatementException : Exception { } private static void Break() { throw new BreakStatementException(); } private static void Continue() { throw new ContinueStatementException(); } private static void For(Action init, Func<bool> condition, Action postBlock, Action statement) { init = init ?? EmptyAction; condition = condition ?? EmptyCondition; postBlock = postBlock ?? EmptyAction; statement = statement ?? EmptyAction; for ( init(); condition(); postBlock() ) { try { statement(); } catch ( BreakStatementException ) { break; } catch ( ContinueStatementException ) { continue; } } } private static void Main() { int i = 0; // avoiding error "Use of unassigned local variable 'i'" if not using `for` init block For(() => i = 0, () => i < 10, () => i++, () => { if ( i == 5 ) Continue(); Console.WriteLine(i); } ); } If I'm not wrong, this approach is pretty relative to the functional programming practice. Am I right? A: The "TODO" property and the tasks list //TODO: [something] Adding that to your code (the spacing is important) throws an item in your task list, and double clicking the item will jump you to the appropriate location in your code. A: I didn't knew about Generic methods which could help avoid using Method Overloadding. Below are overloaded methods to print int and double numbers. private static void printNumbers(int [] intNumbers) { foreach(int element in intNumbers) { Console.WriteLine(element); } } private static void printNumbers(double[] doubleNumbers) { foreach (double element in doubleNumbers) { Console.WriteLine(element); } } Generic method which help to have one method for both of the above private static void printNumbers<E>(E [] Numbers) { foreach (E element in Numbers) { Console.WriteLine(element); } } A: Don't know if this is a secret per se but I loved the added Enumerable (adds to IEnumerable) class in System.Linq. http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx While the yield keyword is already listed. Iterator blocks are freaking amazing. I used them to build Lists that would be tested to see if they were co-prime. It basically allows you to go though a function that returns values one by one and stop any time. Oh, I almost forgot the best class in the world when you can't optimize it any more. The BackgroundWorker!!!! http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx A: With reference to the post w/ perma link "Hidden Features of C#?", there is another way to accomplish the same - indentation / line breaks. Check this out.. XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.NewLineOnAttributes = true; xmlWriterSettings.Indent = true; XmlWriter xml = XmlWriter.Create(@"C:\file.xml", xmlWriterSettings); // Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc I am not sure whether this is an unknown feature though! A: Lately I learned about the String.Join method. It is really useful when building strings like columns to select by a query. A: I didn't know the "as" keyword for quite a while. MyClass myObject = (MyClass) obj; vs MyClass myObject = obj as MyClass; The second will return null if obj isn't a MyClass, rather than throw a class cast exception. A: Two of my personal favourites, which I see rarely used: * *Snippets (particularly for properties, which was made even better for Visual Studio 2008) *The ObsoleteAttribute A: @lomaxx I also learned the other day (the same time I learned your tip) is that you can now have disparate access levels on the same property: public string Name { get; private set;} That way only the class itself can set the Name property. public MyClass(string name) { Name = name; } A: Nesting Using Statements Usually we do it like this: StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter()) { using (IndentedTextWriter itw = new IndentedTextWriter(sw)) { ... } } But we can do it this way: StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter()) using (IndentedTextWriter itw = new IndentedTextWriter(sw)) { ... } A: JavaScript-like anonymous inline-functions Return a String: var s = new Func<String>(() => { return "Hello World!"; })(); Return a more complex Object: var d = new Func<Dictionary<Int32, String>>(() => { return new Dictionary<Int32, String> { { 0, "Foo" }, { 1, "Bar" }, { 2, "..." } }; })(); A real-world use-case: var tr = new TableRow(); tr.Cells.AddRange ( new[] { new TableCell { Text = "" }, new TableCell { Text = "" }, new TableCell { Text = "" }, new TableCell { Text = new Func<String>(() => { return @"Result of a chunk of logic, without having to define the logic outside of the TableCell constructor"; })() }, new TableCell { Text = "" }, new TableCell { Text = "" } } ); Note: You cannot re-use variable names inside the inline-function's scope. Alternative syntax // The one-liner Func<Int32, Int32, String> Add = (a, b) => Convert.ToString(a + b); // Multiple lines Func<Int32, Int32, String> Add = (a, b) => { var i = a + b; return i.ToString(); }; // Without parameters Func<String> Foo = () => ""; // Without parameters, multiple lines Func<String> Foo = () => { return ""; }; Shorten a string and add horizontal ellipsis... Func<String, String> Shorten = s => s.Length > 100 ? s.Substring(0, 100) + "&hellip;" : s; A: There's also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage. Even if extension methods aren't that secret (LINQ is based on them), it may not be so obvious as to how useful and more readable they can be for utility helper methods: //for adding multiple elements to a collection that doesn't have AddRange //e.g., collection.Add(item1, item2, itemN); static void Add<T>(this ICollection<T> coll, params T[] items) { foreach (var item in items) coll.Add(item); } //like string.Format() but with custom string representation of arguments //e.g., "{0} {1} {2}".Format<Custom>(c=>c.Name,"string",new object(),new Custom()) // result: "string {System.Object} Custom1Name" static string Format<T>(this string format, Func<T,object> select, params object[] args) { for(int i=0; i < args.Length; ++i) { var x = args[i] as T; if (x != null) args[i] = select(x); } return string.Format(format, args); } A: Full access to the call stack: public static void Main() { StackTrace stackTrace = new StackTrace(); // get call stack StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) // write call stack method names foreach (StackFrame stackFrame in stackFrames) { Console.WriteLine(stackFrame.GetMethod().Name); // write method name } } So, if you'll take the first one - you know what function you are in. If you're creating a helper tracing function - take one before the last one - you'll know your caller. A: On-demand field initialization in one line: public StringBuilder Builder { get { return _builder ?? (_builder = new StringBuilder()); } } I'm not sure how I feel about C# supporting assignment expressions, but hey, it's there :-) A: Easily determine type with which variable was declared (from my answer): using System; using System.Collections.Generic; static class Program { public static Type GetDeclaredType<T>(T x) { return typeof(T); } // Demonstrate how GetDeclaredType works static void Main(string[] args) { IList<string> iList = new List<string>(); List<string> list = null; Console.WriteLine(GetDeclaredType(iList).Name); Console.WriteLine(GetDeclaredType(list).Name); } } Results: IList`1 List`1 And its name (borrowed from "Get variable name"): static void Main(string[] args) { Console.WriteLine("Name is '{0}'", GetName(new {args})); Console.ReadLine(); } static string GetName<T>(T item) where T : class { var properties = typeof(T).GetProperties(); return properties[0].Name; } Result: Name is 'args' A: Two things I like are Automatic properties so you can collapse your code down even further: private string _name; public string Name { get { return _name; } set { _name = value; } } becomes public string Name { get; set;} Also object initializers: Employee emp = new Employee(); emp.Name = "John Smith"; emp.StartDate = DateTime.Now(); becomes Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()} A: It's not actually a C# hidden feature, but I recently discovered the WeakReference class and was blown away by it (although this may be biased by the fact that it helped me found a solution to a particular problem of mine...) A: The Environment.UserInteractive property. The UserInteractive property reports false for a Windows process or a service like IIS that runs without a user interface. If this property is false, do not display modal dialogs or message boxes because there is no graphical user interface for the user to interact with. A: Programmers moving from C/C++ may miss this one: In C#, % (modulus operator) works on floats! A: AppDomain.UnhandledException Event is also candidate for being hidden. This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled. We can see, even on this site, a lot of people are wondering why their application is not starting, why it crashed, etc. The AppDomain.UnhandledException event can be very useful for such cases as it provides the possibility at least to log the reason of application failure. A: The 'default' keyword in generic types: T t = default(T); results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean, etcetera. A: The C# ?? null coalescing operator - Not really hidden, but rarely used. Probably because a lot of developers run a mile when they see the conditional ? operator, so they run two when they see this one. Used: string mystring = foo ?? "foo was null" rather than string mystring; if (foo==null) mystring = "foo was null"; else mystring = foo; A: The #if DEBUG pre-processor directive. It is Useful for testing and debugging (though I usually prefer to go the unit testing route). string customerName = null; #if DEBUG customerName = "Bob" #endif It will only execute code block if Visual Studio is set to compile in 'Debug' mode. Otherwise the code block will be ignored by the compiler (and grayed out in Visual Studio). A: I didn't find anyone who is using string.Join to join strings using a separator. Everyone keeps writing the same ugly for-loop var sb = new StringBuilder(); var count = list.Count(); for(int i = 0; i < count; i++) { if (sb.Length > 0) sb.Append(seperator); sb.Append(list[i]); } return sb.ToString(); instead of return string.Join(separator, list.ToArray()); A: Partial Methods Charlie Calvert explains partial methods on his blog Scott Cate has a nice partial method demo here * *Points of extensibility in Code Generated class (LINQ to SQL, EF) *Does not get compiled into the dll if it is not implemented (check it out with .NET Reflector) A: true and false operators are really weird. More comprehensive example can be found here. Edit: There is related SO question What’s the false operator in C# good for? A: There are some really hidden keywords and features in C# related to the TypedReference undocumented class. The following keywords are undocumented: * *__makeref *__reftype *__refvalue *__arglist Examples of use: // Create a typed reference int i = 1; TypedReference tr1 = __makeref(i); // Get the type of a typed reference Type t = __reftype(tr1); // Get the value of a typed referece int j = __refvalue(tr1, int); // Create a method that accepts and arbitrary number of typed references void SomeMethod(__arglist) { ... // Call the method int x = 1; string y = "Foo"; Object o = new Object(); SomeMethod(__arglist(x,y,o)); // And finally iterate over method parameters void SomeMethod(__arglist) { ArgIterator ai = new ArgIterator(__arglist); while(ai.GetRemainingCount() >0) { TypedReference tr = ai.GetNextArg(); Console.WriteLine(TypedReference.ToObject(tr)); }} A: I found that only few developers know about this feature. If you need a method that works with a value-type variable via some interface (implemented by this value type), it's easy to avoid boxing during the method call. Example code: using System; using System.Collections; interface IFoo { void Foo(); } struct MyStructure : IFoo { public void Foo() { } } public static class Program { static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo { t.Foo(); } static void Main(string[] args) { MyStructure s = new MyStructure(); MethodThatDoesNotBoxArguments(s); } } IL code doesn't contain any box instructions: .method private hidebysig static void MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed { // Code size 14 (0xe) .maxstack 8 IL_0000: ldarga.s t IL_0002: constrained. !!T IL_0008: callvirt instance void IFoo::Foo() IL_000d: ret } // end of method Program::MethodDoesNotBoxArguments .method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 15 (0xf) .maxstack 1 .locals init ([0] valuetype MyStructure s) IL_0000: ldloca.s s IL_0002: initobj MyStructure IL_0008: ldloc.0 IL_0009: call void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0) IL_000e: ret } // end of method Program::Main See Richter, J. CLR via C#, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints. See also my answer to another question. A: Attributes in general, but most of all DebuggerDisplay. Saves you years. A: The @ tells the compiler to ignore any escape characters in a string. Just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal. If you have string s = @"cat dog fish" it will actually print out as (note that it even includes the whitespace used for indentation): cat dog fish A: Near all the cool ones have been mentioned. Not sure if this one's well known or not C# property/field constructor initialization: var foo = new Rectangle() { Fill = new SolidColorBrush(c), Width = 20, Height = 20 }; This creates the rectangle, and sets the listed properties. I've noticed something funny - you can have a comma at the end of the properties list, without it being a syntax error. So this is also valid: var foo = new Rectangle() { Fill = new SolidColorBrush(c), Width = 20, Height = 20, }; A: I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are Expression Trees, especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using. For example, let's say that I want to register a method with an API and that API needs to get the method name Given this class: public class MyClass { public void SomeMethod() { /* Do Something */ } } Before, it was very common to see developers do this with strings and types (or something else largely string-based): RegisterMethod(typeof(MyClass), "SomeMethod"); Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion: RegisterMethod<MyClass>(cl => cl.SomeMethod()); In which the RegisterMethod class uses Expression<Action<T>> like this: void RegisterMethod<T>(Expression<Action<T>> action) where T : class { var expression = (action.Body as MethodCallExpression); if (expression != null) { // TODO: Register method Console.WriteLine(expression.Method.Name); } } This is one big reason that I'm in love with Lambdas and Expression Trees right now. A: On the basis that this thread should be entitled "things you didn't know about C# until recently despite thinking you already knew everything", my personal feature is asynchronous delegates. Until I read Jeff Richter's C#/CLR book (excellent book, everyone doing .NET should read it) I didn't know that you could call any delegate using BeginInvoke / EndInvoke. I tend to do a lot of ThreadPool.QueueUserWorkItem calls (which I guess is much like what the delegate BeginInvoke is doing internally), but the addition of a standardised join/rendezvous pattern may be really useful sometimes. A: Several people have mentioned using blocks, but I think they are much more useful than people have realised. Think of them as the poor man's AOP tool. I have a host of simple objects that capture state in the constructor and then restore it in the Dispose() method. That allows me to wrap a piece of functionality in a using block and be sure that the state is restored at the end. For example: using(new CursorState(this, BusyCursor)); { // Do stuff } CursorState captures the current cursor being used by form, then sets the form to use the cursor supplied. At the end it restores the original cursor. I do loads of things like this, for example capturing the selections and current row on a grid before refreshing and so on. A: Another note on event handlers: you can simply create a raise extension method like so: public static class EventExtensions { public static void Raise<T>(this EventHandler<T> @event, object sender, T args) where T : EventArgs { if(@event!= null) { @event(sender, args); } } } Then you can use it to raise events: public class MyImportantThing { public event EventHandler<MyImportantEventEventArgs> SomethingHappens; ... public void Bleh() { SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true }); } } This method has the added advantage of enforcing a coding standard (using EventHandler<>). There isn't a point in writing the same exact function over and over and over again. Perhaps the next version of C# will finally have an InlineAttribute that can be placed on the extension method and will cause the compiler to inline the method definition (which would make this way nearly standard, and the fastest). edit: removed temp variable inside extension method based on comments A: "yield" would come to my mind. Some of the attributes like [DefaultValue()] are also among my favorites. The "var" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you use the .NET 3.5 compiler and set it to output 2.0 code) does not seem to be known very well. Edit: kokos, thanks for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: ?? Operator (C# Reference) A: I'm late to this party, so my first choices are already taken. But I didn't see anyone mention this gem yet: Parallel Extensions to the .NET Framework It has things like replace with Parallel.For or foreach with Parallel.ForEach Parallel Sample : In your opinion, how many CLR object can be created in one second? See fallowing example : using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace ObjectInitSpeedTest { class Program { //Note: don't forget to build it in Release mode. static void Main() { normalSpeedTest(); parallelSpeedTest(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Press a key ..."); Console.ReadKey(); } private static void parallelSpeedTest() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("parallelSpeedTest"); long totalObjectsCreated = 0; long totalElapsedTime = 0; var tasks = new List<Task>(); var processorCount = Environment.ProcessorCount; Console.WriteLine("Running on {0} cores", processorCount); for (var t = 0; t < processorCount; t++) { tasks.Add(Task.Factory.StartNew( () => { const int reps = 1000000000; var sp = Stopwatch.StartNew(); for (var j = 0; j < reps; ++j) { new object(); } sp.Stop(); Interlocked.Add(ref totalObjectsCreated, reps); Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds); } )); } // let's complete all the tasks Task.WaitAll(tasks.ToArray()); Console.WriteLine("Created {0:N} objects in 1 sec\n", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000); } private static void normalSpeedTest() { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("normalSpeedTest"); const int reps = 1000000000; var sp = Stopwatch.StartNew(); sp.Start(); for (var j = 0; j < reps; ++j) { new object(); } sp.Stop(); Console.WriteLine("Created {0:N} objects in 1 sec\n", (reps / sp.ElapsedMilliseconds) * 1000); } } } A: One great class I like is System.Xml.XmlConvert which can be used to read values from xml tag. Especially, if I am reading a boolean value from xml attribute or element, I use bool myFlag = System.Xml.XmlConvert.ToBoolean(myAttribute.Value); Note: since boolean type in xml accepts 1 and 0 in addition to "true" and "false" as valid values, using string comparison in this case is error-prone. A: Atrribute Targets Everyone has seen one. Basically, when you see this: [assembly: ComVisible(false)] The "assembly:" portion of that attribute is the target. In this case, the attribute is applied to the assembly, but there are others: [return: SomeAttr] int Method3() { return 0; } In this sample the attribute is applied to the return value. A: Apologies for posting so late, I am new to Stack Overflow so missed the earlier opportunity. I find that EventHandler<T> is a great feature of the framework that is underutilised. Most C# developers I come across still define a custom event handler delegate when they are defining custom events, which is simply not necessary anymore. Instead of: public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e); public class MyCustomEventClass { public event MyCustomEventHandler MyCustomEvent; } you can go: public class MyCustomEventClass { public event EventHandler<MyCustomEventArgs> MyCustomEvent; } which is a lot more concise, plus you don't get into the dilemma of whether to put the delegate in the .cs file for the class that contains the event, or the EventArgs derived class. A: What about IObservable? Pretty much everybody knows IEnumerable but their mathematical dual seems to be unknown IObservable. Maybe because its new in .NET 4. What it does is instead of pulling the information (like an enumerable) it pushes information to the subscriber(s) of the observerable. Together with the Rx extensions it will change how we deal with events. Just to illustrate how powerful it is check a very short example here. A: OK, it may seem obvious, but I want to mention the Object.Equals method (the static one, with two arguments). I'm pretty sure many people don't even know about it, or forget it's there, yet it can really help in some cases. For instance, when you want to compare two objects for equality, not knowing if they're null. How many times did you write something like that : if ((x == y) || ((x != null && y != null) && x.Equals(y))) { ... } When you can just write : if (Object.Equals(x, y)) { ... } (Object.Equals is actually implemented exactly like in the first code sample) A: string.Empty I know it's not fantastical (ludicrously odd), but I use it all the time instead of "". And it's pretty well hidden until someone tells you it's there. A: I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring. Not sure why anyone would ever want to use Nullable<.bool> though. In a VB.NET Web service where the parameter might not be passed through (because the partners request wasn't consistent or reliable), but had to pass validation against the proposed type (Boolean for "if is search request"). Chalk it up to "another demand by management"... ...and yes, I know some people think it's not the right way to do these things, but IsSearchRequest As Nullable(Of Boolean) saved me losing my mind that night! A: I must admit that i'm not sure wether this performs better or worse than the normal ASP.NET repeater onItemDatabound cast code, but anyway here's my 5 cent. MyObject obj = e.Item.DataItem as MyObject; if(obj != null) { //Do work } A: PreviousPage property: "The System.Web.UI.Page representing the page that transferred control to the current page." It is very useful. A: @Robbie Rocketpants "but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one." If you do the cast as you were suggesting in example 1 (using is & as), it results in 2 calls to the "is" operator. Because when you do "c = obj as MyClass", first it calls "is" behind the scenes, then if it fails that it simply returns null. If you do the cast as you were suggesting in example 2, c = (MyClass)obj Then this actually performs the "is" operation again, then if it fails that check,it throws an exception (InvalidCastException). So, if you wanted to do a lightweight dynamic cast, it's best to do the 3rd example you provided: MyClass c; if (obj is MyClass) { c = obj as MyClass } if (c != null) { } vs MyClass c = obj as MyClass; if (c != null) { } You can see which is quicker, more consise and clearer. A: Saw a mention of List.ForEach above; 2.0 introduced a bevy of predicate-based collection operations - Find, FindAll, Exists, etc. Coupled with anonymous delegates you can almost achieve the simplicity of 3.5's lambda expressions. A: Some concurrency utilities in the BCL might qualify as hidden features. Things like System.Threading.Monitor are used internally by the lock keyword; clearly in C# the lock keyword is preferrable, but sometimes it pays to know how things are done at a lower level; I had to lock in C++/CLI, so I encased a block of code with calls to Monitor.Enter() and Monitor.Exit(). A: Before lambda comes into play, it's anonymous delegate. That could be used for blanket code similar to Ruby's blockgiven. I haven't tested how lambda works though because I want to stick with .NET 2.0 so far. For example when you want to make sure you remember to close your HTML tags: MyHtmlWriter writer=new MyHtmlWriter(); writer.writeTag("html", delegate () { writer.writeTag("head", delegate() { writer.writeTag("title"...); } ) }) I am sure if lambda is an option, that could yield much cleaner code :) A: In dealing with interop between C++ and C#, many people don't realize that C++/CLI is a great option. Say you have a C++ DLL and a C# DLL which depends on the C++ DLL. Often, the easiest technique is to compile some (or all) modules of the C++ DLL with the /clr switch. To have the C# call the C++ DLL is to write managed C++ wrapper classes in the C++ DLL. The C++/CLI classes can call the native C++ code much more seamlessly than C#, because the C++ compiler will automatically generate P/invokes for you, has a library specifically for interop, plus language features for interop like pin_ptr. And it allows managed and native code to coexist within the same binary. On the C# side, you just call into the DLL as you would any other .NET binary. A: Relection is so powerfull when used carefully. I used it in an e-mail templating system. The template manager would be passed an object and the html templates would have embedded fields that referred to Properties that could be retrieved off the passed object using reflection. Worked out very nicely. A: Not sure Microsoft would like this question, especially with so many responses. I'm sure I once heard a Microsoft head say: a hidden feature is a wasted feature ... or something to that effect. A: Use of @ before a string that contains escape char. Basically when a physical path is used to assign in a string variable everybody uses '\' where escape character is present in a string. e.g. string strPath="D:\websites\web1\images\"; But escape characters can be ignored using @ before the string value. e.g. string strPath=@"D:\websites\web1\images\"; A: Another way of geting IEnumerable through yield without explicity creating an IEnumerable object public IEnumerable<Request> SomeMethod(IEnumerable<Request> requests) { foreach (Request request in requests) yield return DoSomthing(request); } A: This trick for calling private methods using Delegate.CreateDelegate is extremely neat. var subject = new Subject(); var doSomething = (Func<String, String>) Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething"); Console.WriteLine(doSomething("Hello Freggles")); Here's a context where it's useful A: Most of the P/Invoke stuff is a bit strange. Example of attributes: [DllImport ("gdi32.dll")] [return : MarshalAs(UnmanagedType.I4)] [StructLayout(LayoutKind.Sequential)] A: I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value. double? num1 = null; double num2 = num1 ?? -100; Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null. http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx one more thing about Nullable type: DateTime? tmp = new DateTime(); tmp = null; return tmp.ToString(); it is return String.Empty. Check this link for more details A: Here are some interesting hidden C# features, in the form of undocumented C# keywords: __makeref __reftype __refvalue __arglist These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct. There's also __arglist, which is used for variable length parameter lists. One thing folks don't know much about is System.WeakReference -- a very useful class that keeps track of an object but still allows the garbage collector to collect it. The most useful "hidden" feature would be the yield return keyword. It's not really hidden, but a lot of folks don't know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the internal, gritty details. A: I see a lot of people replicate the functionality of Nullable<T>.GetValueOrDefault(T). A: C# 3.0's LINQ query comprehensions are full-blown monadic comprehensions a la Haskell (in fact they were designed by one of Haskell's designers). They will work for any generic type that follows the "LINQ pattern" and allows you to write in a pure monadic functional style, which means that all of your variables are immutable (as if the only variables you used were IDisposables and IEnumerables in using and foreach statements). This is helpful for keeping variable declarations close to where they're used and making sure that all side-effects are explicitly declared, if there are any at all. interface IFoo<T> { T Bar {get;} } class MyFoo<T> : IFoo<T> { public MyFoo(T t) {Bar = t;} public T Bar {get; private set;} } static class Foo { public static IFoo<T> ToFoo<T>(this T t) {return new MyFoo<T>(t);} public static void Do<T>(this T t, Action<T> a) { a(t);} public static IFoo<U> Select<T,U>(this IFoo<T> foo, Func<T,U> f) { return f(foo.Bar).ToFoo(); } } /* ... */ using (var file = File.OpenRead("objc.h")) { var x = from f in file.ToFoo() let s = new Scanner(f) let p = new Parser {scanner = s} select p.Parse(); x.Do(p => { /* drop into imperative code to handle file in Foo monad if necessary */ }); } A: Not really hidden, but useful. When you've got an enum with flags, you can use shift-left to make things clearer. e.g. [Flags] public enum ErrorTypes { None = 0, MissingPassword = 1 << 0, MissingUsername = 1 << 1, PasswordIncorrect = 1 << 2 } A: Unions (the C++ shared memory kind) in pure, safe C# Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class: [StructLayout(LayoutKind.Explicit)] public class A { [FieldOffset(0)] public byte One; [FieldOffset(1)] public byte Two; [FieldOffset(2)] public byte Three; [FieldOffset(3)] public byte Four; [FieldOffset(0)] public int Int32; } You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program: static void Main(string[] args) { A a = new A { Int32 = int.MaxValue }; Console.WriteLine(a.Int32); Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four); a.Four = 0; a.Three = 0; Console.WriteLine(a.Int32); } Outputs this: 2147483647 FF FF FF 7F 65535 just add using System.Runtime.InteropServices; A: My favorite attribute: InternalsVisibleTo At assembly level you can declare that another assembly can see your internals. For testing purposes this is absolutely wonderful. Stick this in your AssemblyInfo.cs or equivalent and your test assembly get full access to all the internal stuff that requires testing. [assembly: InternalsVisibleTo("MyLibrary.Test, PublicKey=0024...5c042cb")] As you can see, the test assembly must have a strong name to gain the trust of the assembly under test. Available in .Net Framework 2.0+, Compact Framework 2.0+ and XNA Framework 1.0+. A: Using @ for variable names that are keywords. var @object = new object(); var @string = ""; var @if = IpsoFacto(); A: I love using the @ character for SQL queries. It keeps the sql nice and formatted and without having to surround each line with a string delimiter. string sql = @"SELECT firstname, lastname, email FROM users WHERE username = @username AND password = @password"; A: The extern alias keyword to reference two versions of assemblies that have the same fully-qualified type names. A: You can limit the life and thus scope of variables by using { } brackets. { string test2 = "3"; Console.Write(test2); } Console.Write(test2); //compile error test2 only lives within the brackets. A: Need to return an empty IEnumerable? public IEnumerable<T> GetEnumerator(){ yield break; } A: If you want to exit your program without calling any finally blocks or finalizers use FailFast: Environment.FailFast() A: You can use any Unicode character in C# names, for example: public class MyClass { public string Hårføner() { return "Yes, it works!"; } } You can even use Unicode escapes. This one is equivalent to the above: public class MyClass { public string H\u00e5rføner() { return "Yes, it (still) works!"; } } A: Ability to use LINQ Expressions to perform strongly-typed reflection: static void Main(string[] args) { var domain = "matrix"; Check(() => domain); Console.ReadLine(); } static void Check<T>(Expression<Func<T>> expr) { var body = ((MemberExpression)expr.Body); Console.WriteLine("Name is: {0}", body.Member.Name); Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member) .GetValue(((ConstantExpression)body.Expression).Value)); } // output: // Name is: 'domain' // Value is: 'matrix' More details are available at How to Find Out Variable or Parameter Name in C#? A: You can store colors in Enum. public enum MyEnumColors : uint { Normal = 0xFF9F9F9F, Active = 0xFF8EA98A, Error = 0xFFFF0000 } A: Returning anonymous types from a method and accessing members without reflection. // Useful? probably not. private void foo() { var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) }); Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges); } object GetUserTuple() { return new { Name = "dp", Badges = 5 }; } // Using the magic of Type Inference... static T AnonCast<T>(object obj, T t) { return (T) obj; } A: I have often come across the need to have a generic parameter-object persisted into the viewstate in a base class. public abstract class BaseListControl<ListType,KeyType,ParameterType> : UserControl where ListType : BaseListType && ParameterType : BaseParameterType, new { private const string viewStateFilterKey = "FilterKey"; protected ParameterType Filters { get { if (ViewState[viewStateFilterKey] == null) ViewState[viewStateFilterKey]= new ParameterType(); return ViewState[viewStateFilterKey] as ParameterType; } set { ViewState[viewStateFilterKey] = value; } } } Usage: private void SomeEventHappened(object sender, EventArgs e) { Filters.SomeValue = SomeControl.SelectedValue; } private void TimeToFetchSomeData() { GridView.DataSource = Repository.GetList(Filters); } This little trick with the "where ParameterType : BaseParameterType, new" is what makes it really work. With this property in my baseclass, I can automate handling of paging, setting filter values to filter a gridview, make sorting really easy, etc. I am really just saying that generics can be an enormously powerful beast in the wrong hands. A: How about the FlagsAttribute on an enumeration? It allows you to perform bitwise operations... took me forever to find out how to do bitwise operations in .NET nicely. A: You can add and remove delegates with less typing. Usual way: handler += new EventHandler(func); Less typing way: handler += func; A: Using "~" operator with FlagAttribute and enum Sometime we would use Flag attribute with enum to perform bitwise manipulation on the enumeration. [Flags] public enum Colors { None = 0, Red = 1, Blue = 2, White = 4, Black = 8, Green = 16, All = 31 //It seems pretty bad... } Notice that, the value of option "All" which in enum is quite strange. Instead of that we can use "~" operator with flagged enum. [Flags] public enum Colors { None = 0, Red = 1, Blue = 2, White = 4, Black = 8, Green = 16, All = ~0 //much better now. that mean 0xffffffff in default. } A: Also useful, but not commonly used : Constrained Execution Regions. A quote from BCL Team blog : Constrained execution regions (CER's) exist to help a developer write her code to maintain consistency. The CLR doesn't guarantee that the developer's code is correct, but the CLR does hoist all of the runtime-induced failure points (ie, async exceptions) to either before the code runs, or after it has completed. Combined with constraints on what the developer can put in a CER, these are a useful way of making strong guarantees about whether your code will execute. CER's are eagerly prepared, meaning that when we see one, we will eagerly JIT any code found in its statically-discoverable call graph. If the CLR's host cares about stack overflow, we'll probe for some amount of stack space as well (though perhaps not enough stack space for any arbitrary method*). We also delay thread aborts until the CER has finished running. It can be useful when making edits to more than one field of a data structure in an atomic fashion. So it helps to have transactions on objects. Also CriticalFinalizerObject seems to be hidden(at least who are not writing unsafe code). A CriticalFinalizerObject guarantees that garbage collection will execute the finalizer. Upon allocation, the finalizer and its call graph are prepared in advance. A: fixed statement This statement prevents the garbage collector from relocating a movable variable. Fixed can also be used to create fixed size buffers. The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement. stackalloc The stackalloc allocates a block of memory on the stack. A: Here's a useful one for regular expressions and file paths: "c:\\program files\\oldway" @"c:\program file\newway" The @ tells the compiler to ignore any escape characters in a string. A: Mixins. Basically, if you want to add a feature to several classes, but cannot use one base class for all of them, get each class to implement an interface (with no members). Then, write an extension method for the interface, i.e. public static DeepCopy(this IPrototype p) { ... } Of course, some clarity is sacrificed. But it works! A: ConditionalAttribute Allows you to tell the compiler to omit the call to the method marked with the attribute under certain conditions (#define). The fact that the method call is omitted also means that its parameters are not evaluated. This is very handy and it's what allows you to call expensive validation functions in Debug.Assert() and not worry about them slowing down your release build. A: One feature that I only learned about here on Stack Overflow was the ability to set an attribute on the return parameter. [AttributeUsage( AttributeTargets.ReturnValue )] public class CuriosityAttribute:Attribute { } public class Bar { [return: Curiosity] public Bar ReturnANewBar() { return new Bar(); } } This was truly a hidden feature for me :-) A: Labeling my endregions... #region stuff1 #region stuff1a //... #endregion stuff1a #endregion stuff1 A: When defining custom attributes you can use them with [MyAttAttribute] or with [MyAtt]. When classes exist for both writings, then a compilation error occures. The @ special character can be used to distinguish between them: [AttributeUsage(AttributeTargets.All)] public class X: Attribute {} [AttributeUsage(AttributeTargets.All)] public class XAttribute: Attribute {} [X] // Error: ambiguity class Class1 {} [XAttribute] // Refers to XAttribute class Class2 {} [@X] // Refers to X class Class3 {} [@XAttribute] // Refers to XAttribute class Class4 {} A: When a class implements INotifyPropertyChanged and you want to inform the binding system (WPF, Silverlight, etc.) that multiple bound properties of an object (ViewModel) have changed you can raise the PropertyChanged-Event with null or String.Empty. This is documented in MSDN, but code examples and articles often don´t explain this possibility. I found it very useful. public class BoundObject : INotifyPropertyChanged { private int _value; private string _text; public event PropertyChangedEventHandler PropertyChanged; public int Value { get { return _value; } set { if (_value != value) { _value = value; OnPropertyChanged("Value"); } } } public string Text { get { return _text; } set { if (_text != value) { _text = value; OnPropertyChanged("Text"); } } } public void Init(){ _text = "InitialValue"; _value = 1; OnPropertyChanged(string.Empty); } public void Reset() { _text = "DefaultValue"; _value = 0; OnPropertyChanged(string.Empty); } private void OnPropertyChanged(string propertyName) { PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName); if (PropertyChanged != null) { PropertyChanged(this, e); } } } A: You can put several attributes in one pair of square brackets: [OperationContract, ServiceKnownType(typeof(Prism)), ServiceKnownType(typeof(Cuboid))] Shape GetShape(); A: Not sure why anyone would ever want to use Nullable<bool> though. :-) True, False, FileNotFound? A: Lambda Expressions Func<int, int, int> add = (a, b) => (a + b); Obscure String Formats Console.WriteLine("{0:D10}", 2); // 0000000002 Dictionary<string, string> dict = new Dictionary<string, string> { {"David", "C#"}, {"Johann", "Perl"}, {"Morgan", "Python"} }; Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" ); Console.WriteLine( "-".PadRight( 21, '-' ) ); foreach (string key in dict.Keys) { Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] ); } A: I didn't start to really appreciate the "using" blocks until recently. They make things so much more tidy :) A: What about using this: #if DEBUG Console.Write("Debugging"); #else Console.Write("Final"); #endif When you have your solution compiled with DEBUG defined it will output "Debugging". If your compile is set to Release it will write "Final". A: FlagsAttribute, a small but nice feature when using enum to make a bitmasks: [Flags] public enum ConfigOptions { None = 0, A = 1 << 0, B = 1 << 1, Both = A | B } Console.WriteLine( ConfigOptions.A.ToString() ); Console.WriteLine( ConfigOptions.Both.ToString() ); // Will print: // A // A, B A: I'm becoming a big fan of extension methods since they can add much wanted functionality to existing code or code you can't edit. One of my favorites I add in to everything I do now is for string.IsNullOrEmpty() public static class Strings { public static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } } This lets you shorten your code a bit like this var input = Console.ReadLine(); if (input.IsNullOrEmpty()) { Console.WriteLine("try again"); } A: Type-inference for factory methods I don't know if this has been posted already (I scanned the first post, couldn't find it). This is best shown with an example, assuming you have this class (to simulate a tuple), in in an attempt to demonstrate all the language features that make this possible I will go through it step by step. public class Tuple<V1, V2> : Tuple { public readonly V1 v1; public readonly V2 v2; public Tuple(V1 v1, V2 v2) { this.v1 = v1; this.v2 = v2; } } Everyone knows how to create an instance of it, such as: Tuple<int, string> tup = new Tuple<int, string>(1, "Hello, World!"); Not exactly rocket science, now we can of course change the type declaration of the variable to var, like this: var tup = new Tuple<int, string>(1, "Hello, World!"); Still well known, to digress a bit here's a static method with type parameters, which everyone should be familiar with: public static void Create<T1, T2>() { // stuff } Calling it is, again common knowledge, done like this: Create<float, double>(); What most people don't know is that if the arguments to the generic method contains all the types it requires they can be inferred, for example: public static void Create<T1, T2>(T1 a, T2 b) { // stuff } These two calls are identical: Create<float, string>(1.0f, "test"); Create(1.0f, "test"); Since T1 and T2 is inferred from the arguments you passed. Combining this knowledge with the var keyword, we can by adding a second static class with a static method, such as: public abstract class Tuple { public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2) { return new Tuple<V1, V2>(v1, v2); } } Achieve this effect: var tup = Tuple.Create(1, "Hello, World!"); This means that the types of the: variable "tup", the type-parameters of "Create" and the return value of "Create" are all inferred from the types you pass as arguments to Create The full code looks something like this: public abstract class Tuple { public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2) { return new Tuple<V1, V2>(v1, v2); } } public class Tuple<V1, V2> : Tuple { public readonly V1 v1; public readonly V2 v2; public Tuple(V1 v1, V2 v2) { this.v1 = v1; this.v2 = v2; } } // Example usage: var tup = Tuple.Create(1, "test"); Which gives you fully type inferred factory methods everywhere! A: Easier-on-the-eyes / condensed ORM-mapping using LINQ Consider this table: [MessageId] INT, [MessageText] NVARCHAR(MAX) [MessageDate] DATETIME ... And this structure: struct Message { Int32 Id; String Text; DateTime Date; } Instead of doing something along the lines of: List<Message> messages = new List<Message>(); foreach (row in DataTable.Rows) { var message = new Message { Id = Convert.ToInt32(row["MessageId"]), Text = Convert.ToString(row["MessageText"]), Date = Convert.ToDateTime(row["MessageDate"]) }; messages.Add(message); } You can use LINQ and do the same thing with fewer lines of code, and in my opinion; more style. Like so: var messages = DataTable.AsEnumerable().Select(r => new Message { Id = Convert.ToInt32(r["MessageId"]), Text = Convert.ToString(r["MessageText"]), Date = Convert.ToDateTime(r["MessageDate"]) }).ToList(); This approach can be nested, just like loops can. A: Falling through switch-cases can be achieved by having no code in a case (see case 0), or using the special goto case (see case 1) or goto default (see case 2) forms: switch (/*...*/) { case 0: // shares the exact same code as case 1 case 1: // do something goto case 2; case 2: // do something else goto default; default: // do something entirely different break; } A: Something I missed for a long time: you can compare strings with "string".equals("String", StringComparison.InvariantCultureIgnoreCase) instead of doing: "string".ToLower() == "String".ToLower(); A: A couple I can think of: [field: NonSerialized()] public EventHandler event SomeEvent; This prevents the event from being serialised. The 'field:' indicates that the attribute should be applied to the event's backing field. Another little known feature is overriding the add/remove event handlers: public event EventHandler SomeEvent { add { // ... } remove { // ... } } A: This one is not "hidden" so much as it is misnamed. A lot of attention is paid to the algorithms "map", "reduce", and "filter". What most people don't realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they're part of LINQ. "map" => Select Transforms data from one form into another "reduce" => Aggregate Aggregates values into a single result "filter" => Where Filters data based on a criteria The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable. A: Environment.NewLine for system independent newlines. A: If you're trying to use curly brackets inside a String.Format expression... int foo = 3; string bar = "blind mice"; String.Format("{{I am in brackets!}} {0} {1}", foo, bar); //Outputs "{I am in brackets!} 3 blind mice" A: I love the fact that I can use LINQ to objects on plain old .NET 2.0 (i.e. without requiring .NET 3.5 to be installed everywhere). All you need is an implementation of all the query operator Extension methods - see LINQBridge A: * *I can't comment yet, but note that by default Visual Studio 2008 automatically steps over properties, so the DebuggerStepThrough attribute is no longer needed in that case. *Also, I haven't noticed anyone showing how to declare a parameter-less lambda (useful for implementing Action<>) () => DoSomething(x); You should also read up on closures - I'm not clever enough to explain them properly. But basically it means that the compiler does clever stuff so that the x in that line of code will still work even if it goes 'out of scope' after creating the lambda. *I also discovered recently that you can pretend to ignore a lambda parameter: (e, _) => DoSomething(e) It's not really ignoring it, it's just that _ is a valid identifier. So you couldn't ignore both of the parameters like that, but I think it is a kind of neat way to indicate that we don't care about that parameter (typically the EventArgs which is .Empty). A: There are operators for performing implicit and explicit user-defined type conversion between the declared class and one or more arbitrary classes. The implicit operator effectively allows the simulation of overloading the assignement operator, which is possible in languages such as C++ but not C#. It doesn't seem to be a feature one comes across very often, but it is in fact used in the LINQ to XML (System.Xml.Linq) library, where you can implicitly convert strings to XName objects. Example: XName tagName = "x:Name"; I discovered this feature in this article about how to simulate multiple inheritance in C#. A: The delegate syntax have evolved over successive versions of C#, but I still find them difficult to remember. Fortunately the Action<> and Func<> delegates are easy to remember. For example: * *Action<int> is a delegate method that takes a single int argument and returns void. *Func<int> is a delegate method that takes no arguments and returns an int. *Func<int, bool> is a delegate method that takes a single int argument and returns a bool. These features were introduced in version 3.5 of the .NET framework. A: You can use generics to check (compile time) if a method argument implements two interfaces: interface IPropA { string PropA { get; set; } } interface IPropB { string PropB { get; set; } } class TestClass { void DoSomething<T>(T t) where T : IPropA, IPropB { MessageBox.Show(t.PropA); MessageBox.Show(t.PropB); } } Same with an argument that is inherited from a base class and an interface. A: Extension methods can be called on null; this will not cause a NullReferenceException to be thrown. Example application: you can define an alternative for ToString() called ToStringOrEmpty() which will return the empty string when called on null. A: * *?? - coalescing operator *using (statement / directive) - great keyword that can be used for more than just calling Dispose *readonly - should be used more *netmodules - too bad there's no support in Visual Studio A: @Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample: MyClass c; if (obj is MyClass) c = obj as MyClass If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast: c = (MyClass)obj ...is never going to fail. Similarly, you could just say: MyClass c = obj as MyClass; if(c != null) { ... } I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too. A: To call the base class constructor just put base() inline with the constructor. To call the base class method you can just put base.MethodName() inside the derived class method class ClassA { public ClassA(int a) { //Do something } public void Method1() { //Do Something } } class ClassB : ClassA { public ClassB(int a) : base(a) // calling the base class constructor { //Do something } public void Method2() { base.Method1(); // calling the base class method } } Of course you can call the methods of the base class by just saying base.MethodName() A: TrueForAll Method of List<T> : List<int> s = new List<int> { 6, 1, 2 }; bool a = s.TrueForAll(p => p > 0); A: One thing not many people know about are some of the C#-introduced preprocessor directives. You can use #error This is an error. to generate a compiler error and #warning This is a warning. I usually use these when I'm developing with a top-down approach as a "todo" list. I'll #error Implement this function, or #warning Eventually implement this corner case as a reminder. A: Not sure if this one got mentioned yet but the ThreadStatic attribute is a realy useful one. This makes a static field static just for the current thread. [ThreadStatic] private static int _ThreadStaticInteger; You should not include an initializer because it only get executed once for the entire application, you're better off making the field nullable and checking if the value is null before you use it. And one more thing for ASP.NET applications threads are reused so if you modify the value it could end up being used for another page request. Still I have found this useful on several occasions. For example in creating a custom transaction class that: using (DbTransaction tran = new DbTransaction()) { DoQuery("..."); DoQuery("..."); } The DbTransaction constructor sets a ThreadStatic field to its self and resets it to null in the dispose method. DoQuery checks the static field and if != null uses the current transaction if not it defaults to something else. We avoid having to pass the transaction to each method plus it makes it easy to wrap other methods that were not originaly meant to be used with transaction inside a transaction ... Just one use :) A: The Or assignment operator is quite nice. You can write this: x |= y instead of this: x = x | y This is often practical if you have to a variable or property (x in the example) that starts out as false but you want to change it to the value of some other boolean variable/property only when that other value is true. A: Nested classes can access private members of a outer class. public class Outer { private int Value { get; set; } public class Inner { protected void ModifyOuterMember(Outer outer, int value) { outer.Value = value; } } } And now together with the above feature you can also inherit from nested classes as if they were top level classes as shown below. public class Cheater : Outer.Inner { protected void MakeValue5(Outer outer) { ModifyOuterMember(outer, 5); } } These features allow for some interesting possibilities as far as providing access to particular members via somewhat hidden classes. A: You can change rounding scheme using: var value = -0.5; var value2 = 0.5; var value3 = 1.4; Console.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1 Console.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1 Console.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1 A: If 3rd-party extensions are allowed, then C5 and Microsoft CCR (see this blog post for a quick introduction) are a must-know. C5 complements .Net's somewhat lacking collections library (not Set???), and CCR makes concurrent programming easier (I hear it's due to be merged with Parallel Extensions). A: Some ?? weirdness :) Delegate target = (target0 = target as CallTargetWithContext0) ?? (target1 = target as CallTargetWithContext1) ?? (target2 = target as CallTargetWithContext2) ?? (target3 = target as CallTargetWithContext3) ?? (target4 = target as CallTargetWithContext4) ?? (target5 = target as CallTargetWithContext5) ?? ((Delegate)(targetN = target as CallTargetWithContextN)); Interesting to note the last cast that is needed for some reason. Bug or by design? A: Here is a TIP of how you can use #Region directive to document your code. A: Not hidden, but pretty neat. I find this a more succinct substitute for a simple if-then-else that just assigns a value based on a condition. string result = i < 2 ? //question "less than 2" : //answer i < 5 ? //question "less than 5": //answer i < 10 ? //question "less than 10": //answer "something else"; //default answer A: If you want to prevent the garbage collector from running the finalizer of an object, just use GC.SuppressFinalize(object);. In a similar vein, GC.KeepAlive(object); will prevent the garbage collector from collecting that object by referencing it. Not very commonly used, at least in my experience, but nice to know just in case. A: Exception Filters. So "hidden" you can't even use them (at least from C#) without a post-compilation patch ;) A: When you need to (a)synchronously communicate between objects about occurance of an event there is special purpose interface called ISynchronizeInvoke. Quoting MSDN article (link): Objects that implement this interface can receive notification that an event has occurred, and they can respond to queries about the event. In this way, clients can ensure that one request has been processed before they submit a subsequent request that depends on completion of the first. Here is a generic wrapper: protected void OnEvent<T>(EventHandler<T> eventHandler, T args) where T : EventArgs { if (eventHandler == null) return; foreach (EventHandler<T> singleEvent in eventHandler.GetInvocationList()) { if (singleEvent.Target != null && singleEvent.Target is ISynchronizeInvoke) { var target = (ISynchronizeInvoke)singleEvent.Target; if (target.InvokeRequired) { target.BeginInvoke(singleEvent, new object[] { this, args }); continue; } } singleEvent(this, args); } } and here is an example usage: public event EventHandler<ProgressEventArgs> ProgressChanged; private void OnProgressChanged(int processed, int total) { OnEvent(ProgressChanged, new ProgressEventArgs(processed, total)); } A: Separate static fields depending on the generic type of the surrounding class. public class StaticConstrucEx2Outer<T> { // Will hold a different value depending on the specicified generic type public T SomeProperty { get; set; } static StaticConstrucEx2Outer() { Console.WriteLine("StaticConstrucEx2Outer " + typeof(T).Name); } public class StaticConstrucEx2Inner<U, V> { static StaticConstrucEx2Inner() { Console.WriteLine("Outer <{0}> : Inner <{1}><{2}>", typeof(T).Name, typeof(U).Name, typeof(V).Name); } public static void FooBar() {} } public class SCInner { static SCInner() { Console.WriteLine("SCInner init <{0}>", typeof(T).Name); } public static void FooBar() {} } } StaticConstrucEx2Outer<int>.StaticConstrucEx2Inner<string, DateTime>.FooBar(); StaticConstrucEx2Outer<int>.SCInner.FooBar(); StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, DateTime>.FooBar(); StaticConstrucEx2Outer<string>.SCInner.FooBar(); StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, Int16>.FooBar(); StaticConstrucEx2Outer<string>.SCInner.FooBar(); StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, UInt32>.FooBar(); StaticConstrucEx2Outer<long>.StaticConstrucEx2Inner<string, UInt32>.FooBar(); Will produce the following output Outer <Int32> : Inner <String><DateTime> SCInner init <Int32> Outer <String> : Inner <String><DateTime> SCInner init <String> Outer <String> : Inner <String><Int16> Outer <String> : Inner <String><UInt32> Outer <Int64> : Inner <String><UInt32> A: I don't know if this is a hidden feature (""). Any string function.
{ "language": "en", "url": "https://stackoverflow.com/questions/9033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1473" }
Q: Can I specify a class wide group on a TestNG test case? I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation: @Test(groups = { "db-test" }) public class DBTestBase { } However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run. So I tried disabling the test, so at least the groups are assigned: @Test(enabled = false, groups = { "db-test" }) public class DBTestBase { } but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want. I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas? A: TestNG will run all the public methods from a class with a @Test annotation. Maybe you could change the methods you don't want TestNG to run to be non-public A: The answer is through a custom org.testng.IMethodSelector: Its includeMethod() can exclude any method we want, like a public not-annotated method. However, to register a custom Java MethodSelector, you must add it to the XMLTest instance managed by any TestRunner, which means you need your own custom TestRunner. But, to build a custom TestRunner, you need to register a TestRunnerFactory, through the -testrunfactory option. BUT that -testrunfactory is NEVER taken into account by TestNG class... so you need also to define a custom TestNG class : * *in order to override the configure(Map) method, *so you can actually set the TestRunnerFactory *TestRunnerFactory which will build you a custom TestRunner, *TestRunner which will set to the XMLTest instance a custom XMLMethodSelector *XMLMethodSelector which will build a custom IMethodSelector *IMethodSelector which will exclude any TestNG methods of your choosing! Ok... it's a nightmare. But it is also a code-challenge, so it must be a little challenging ;) All the code is available at DZone snippets. As usual for a code challenge: * *one java class (and quite a few inner classes) *copy-paste the class in a 'source/test' directory (since the package is 'test') *run it (no arguments needed) Update from Mike Stone: I'm going to accept this because it sounds pretty close to what I ended up doing, but I figured I would add what I did as well. Basically, I created a Groups annotation that behaves like the groups property of the Test (and other) annotations. Then, I created a GroupsAnnotationTransformer, which uses IAnnotationTransformer to look at all tests and test classes being defined, then modifies the test to add the groups, which works perfectly with group exclusion and inclusion. Modify the build to use the new annotation transformer, and it all works perfectly! Well... the one caveat is that it doesn't add the groups to non-test methods... because at the time I did this, there was another annotation transformer that lets you transform ANYTHING, but it somehow wasn't included in the TestNG I was using for some reason... so it is a good idea to make your before/after annotated methods to alwaysRun=true... which is sufficient for me. The end result is I can do: @Groups({ "myGroup1", "myGroup2"}) public class MyTestCase { @Test @Groups("aMethodLevelGroup") public void myTest() { } } And I made the transformer work with subclassing and everything. A: I'm not sure how the annotation inheritance works for TestNG but this article may be of some use. Actually, this may help better, look at inheritGroups. A: It would seem to me as the following code-challenge (community wiki post): How to be able to execute all test methods of Extended class from the group 'aGlobalGroup' without: * *specifying the 'aGlobalGroup' group on the Extended class itself ? *testing non-annotated public methods of Extended class ? The first answer is easy: add a class TestNG(groups = { "aGlobalGroup" }) on the Base class level That group will apply to all public methods of both Base class and Extended class. BUT: even non-testng public methods (with no TestNG annotation) will be included in that group. CHALLENGE: avoid including those non-TestNG methods. @Test(groups = { "aGlobalGroup" }) public class Base { /** * */ @BeforeClass public final void setUp() { System.out.println("Base class: @BeforeClass"); } /** * Test not part a 'aGlobalGroup', but still included in that group due to the class annotation. <br /> * Will be executed even if the TestNG class tested is a sub-class. */ @Test(groups = { "aLocalGroup" }) public final void aFastTest() { System.out.println("Base class: Fast test"); } /** * Test not part a 'aGlobalGroup', but still included in that group due to the class annotation. <br /> * Will be executed even if the TestNG class tested is a sub-class. */ @Test(groups = { "aLocalGroup" }) public final void aSlowTest() { System.out.println("Base class: Slow test"); //throw new IllegalArgumentException("oups"); } /** * Should not be executed. <br /> * Yet the global annotation Test on the class would include it in the TestNG methods... */ public final void notATest() { System.out.println("Base class: NOT a test"); } /** * SubClass of a TestNG class. Some of its methods are TestNG methods, other are not. <br /> * The goal is to check if a group specify in the super-class will include methods of this class. <br /> * And to avoid including too much methods, such as public methods not intended to be TestNG methods. * @author <a href="http://stackoverflow.com/users/6309/vonc">VonC</a> */ public static class Extended extends Base { /** * Test not part a 'aGlobalGroup', but still included in that group due to the super-class annotation. <br /> * Will be executed even if the TestNG class tested is a sub-class. */ @Test public final void anExtendedTest() { System.out.println("Extended class: An Extended test"); } /** * Should not be executed. <br /> * Yet the global annotation Test on the class would include it in the TestNG methods... */ public final void notAnExtendedTest() { System.out.println("Extended class: NOT an Extended test"); } } A: You can specify the @Test annotation at method level that allows for maximum flexibility. public class DBTestBase { @BeforeTest(groups = "db-test") public void beforeTest() { System.out.println("Running before test"); } public void method1() { Assert.fail(); // this does not run. It does not belong to 'db-test' group. } @Test(groups = "db-test") public void testMethod1() { Assert.assertTrue(true); } } Does this works for you or I am missing something from your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/9044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Is there a way for MS Access to grab the current Active Directory user? I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user. Hopefully something like: Dim strUser as String strUser = ActiveDirectory.User() MsgBox "Welcome back, " & strUser A: Try this article - I have some code at work that will erm, work if this doesn't... Relevant quote: Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _ (ByVal IpBuffer As String, nSize As Long) As Long Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _ (ByVal lpBuffer As String, nSize As Long) As Long Function ThisUserName() As String Dim LngBufLen As Long Dim strUser As String strUser = String$(15, " ") LngBufLen = 15 If GetUserName(strUser, LngBufLen) = 1 Then ThisUserName = Left(strUser, LngBufLen - 1) Else ThisUserName = "Unknown" End If End Function Function ThisComputerID() As String Dim LngBufLen As Long Dim strUser As String strUser = String$(15, " ") LngBufLen = 15 If GetComputerName(strUser, LngBufLen) = 1 Then ThisComputerID = Left(strUser, LngBufLen) Else ThisComputerID = 0 End If End Function A: Here's my version: it will fetch anything you like: 'gets firstname, lastname, fullname or username Public Function GetUser(Optional whatpart = "username") Dim returnthis As String If whatpart = "username" Then GetUser = Environ("USERNAME"): Exit Function Set objSysInfo = CreateObject("ADSystemInfo") Set objUser = GetObject("LDAP://" & objSysInfo.USERNAME) Select Case whatpart Case "fullname": returnthis = objUser.FullName Case "firstname", "givenname": returnthis = objUser.givenName Case "lastname": returnthis = objUser.LastName Case Else: returnthis = Environ("USERNAME") End Select GetUser = returnthis End Function I got the original idea from Spiceworks. A: Depending on environment variables to remain valid is a bad idea, since they can easily be changed within a user session. A: David made a very good point about risk of using environment variables. I can only add that there may be other problems with environment variables. Just look at this actual code fragment from our 5-year old project: Public Function CurrentWorkbenchUser() As String ' 2004-01-05, YM: Using Application.CurrentUser for identification of ' current user is very problematic (more specifically, extremely ' cumbersome to set up and administer for all users). ' Therefore, as a quick fix, let's use the OS-level user's ' identity instead (NB: the environment variables used below must work fine ' on Windows NT/2000/2003 but may not work on Windows 98/ME) ' CurrentWorkbenchUser = Application.CurrentUser ' ' 2005-06-13, YM: Environment variables do not work in Windows 2003. ' Use Windows Scripting Host (WSH) Networking object instead. ' CurrentWorkbenchUser = Environ("UserDomain") & "\" & Environ("UserName") ' ' 2007-01-23, YM: Somewhere between 2007-01-09 and 2007-01-20, ' the WshNetwork object stopped working on CONTROLLER3. ' We could not find any easy way to fix that. ' At the same time, it turns out that environment variables ' do work on Windows 2003. ' (Apparently, it was some weird configuration problem back in 2005: ' we had only one Windows 2003 computer at that time and it was ' Will's workstation). ' ' In any case, at the time of this writing, ' returning to environment variables ' appears to be the simplest solution to the problem on CONTROLLER3. ' Dim wshn As New WshNetwork ' CurrentWorkbenchUser = wshn.UserDomain & "\" & wshn.UserName CurrentWorkbenchUser = Environ("USERDOMAIN") & "\" & Environ("USERNAME") End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/9052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: YUI drag&drop proxy drag Question for YUI experts... I have a table and I've made each cell of the first row draggable by proxy. In IE, when the drag proxy is released, the original table cell actually jumps to wherever the release point was. How can I prevent this from happening? Essentially, I want to know where the proxy was dropped and handle my logic from there but I don't want the original to move. A: You have to override the drop-functions, check for DD::dragOverEvent( ) DD:endDragEvent( ) functions on this reference: http://developer.yahoo.com/yui/docs/YAHOO.util.DD.html
{ "language": "en", "url": "https://stackoverflow.com/questions/9072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: grep: show lines surrounding each match How do I grep and show the preceding and following 5 lines surrounding each matched line? A: ack works with similar arguments as grep, and accepts -C. But it's usually better for searching through code. A: Here is the @Ygor solution in awk awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile Note: Replace a and b variables with number of lines before and after. It's especially useful for system which doesn't support grep's -A, -B and -C parameters. A: Grep has an option called Context Line Control, you can use the --context in that, simply, | grep -C 5 or | grep -5 Should do the trick A: -A and -B will work, as will -C n (for n lines of context), or just -n (for n lines of context... as long as n is 1 to 9). A: For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. grep -B 3 -A 2 foo README.txt If you want the same number of lines before and after you can use -C num. grep -C 3 foo README.txt This will show 3 lines before and 3 lines after. A: $ grep thestring thefile -5 -5 gets you 5 lines above and below the match 'thestring' is equivalent to -C 5 or -A 5 -B 5. A: grep astring myfile -A 5 -B 5 That will grep "myfile" for "astring", and show 5 lines before and after each match A: ripgrep If you care about the performance, use ripgrep which has similar syntax to grep, e.g. rg -C5 "pattern" . -C, --context NUM - Show NUM lines before and after each match. There are also parameters such as -A/--after-context and -B/--before-context. The tool is built on top of Rust's regex engine which makes it very efficient on the large data. A: I normally use grep searchstring file -C n # n for number of lines of context up and down Many of the tools like grep also have really great man files too. I find myself referring to grep's man page a lot because there is so much you can do with it. man grep Many GNU tools also have an info page that may have more useful information in addition to the man page. info grep A: Use grep $ grep --help | grep -i context Context control: -B, --before-context=NUM print NUM lines of leading context -A, --after-context=NUM print NUM lines of trailing context -C, --context=NUM print NUM lines of output context -NUM same as --context=NUM A: If you search code often, AG the silver searcher is much more efficient (ie faster) than grep. You show context lines by using the -C option. Eg: ag -C 3 "foo" myFile line 1 line 2 line 3 line that has "foo" line 5 line 6 line 7 A: Search for "17655" in /some/file.txt showing 10 lines context before and after (using Awk), output preceded with line number followed by a colon. Use this on Solaris when grep does not support the -[ACB] options. awk ' /17655/ { for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) { print before[i] } print (NR ":" ($0)) a = 10 } a-- > 0 { print (NR ":" ($0)) } { before[b] = (NR ":" ($0)) b = (b + 1) % 10 }' /some/file.txt; A: Let's understand using an example. We can use grep with options: -A 5 # this will give you 5 lines after searched string. -B 5 # this will give you 5 lines before searched string. -C 5 # this will give you 5 lines before & after searched string Example. File.txt contains 6 lines and following are the operations. [abc@xyz]~/% cat file.txt # print all file data this is first line this is 2nd line this is 3rd line this is 4th line this is 5th line this is 6th line [abc@xyz]~% grep "3rd" file.txt # we are searching for keyword '3rd' in the file this is 3rd line [abc@xyz]~% grep -A 2 "3rd" file.txt # print 2 lines after finding the searched string this is 3rd line this is 4th line this is 5th line [abc@xyz]~% grep -B 2 "3rd" file.txt # Print 2 lines before the search string. this is first line this is 2nd line this is 3rd line [abc@xyz]~% grep -C 2 "3rd" file.txt # print 2 line before and 2 line after the searched string this is first line this is 2nd line this is 3rd line this is 4th line this is 5th line Trick to remember options: * *-A  → A means "after" *-B  → B means "before" *-C  → C means "in between" A: I do it the compact way: grep -5 string file That is the equivalent of: grep -A 5 -B 5 string file
{ "language": "en", "url": "https://stackoverflow.com/questions/9081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4043" }
Q: Accessing audio/video metadata with .NET What is the best way to get and set the meta data for mp3, mp4, avi files etc. with .NET? A: I use MediaInfo with my C# apps, gives you a lot of information about media files. A: These are the example class files for different languages found in the MediaInfo.dll zip * *MediaInfoDLL.cs *MediaInfoDLL.def *MediaInfoDLL.h *MediaInfoDLL.java *MediaInfoDLL.jsl *MediaInfoDLL.pas *MediaInfoDLL.py *MediaInfoDLL.vb *MediaInfoDLL_Static.h You do have to use interop and I don't know if you can edit tags, I've never needed to do that but it's pretty much a swiss army knife at least for getting media information from files. Link to downloads page (sourceforge) MediaInfo_0.7.7.4_DLL_Win32.zip A: You can use free UltraID3Lib .NET library to read/write MP3 metadata. A: I've been looking at the NTag project as well, which handles MP3/WMA/OGG. I don't know of a single library that handles audio and video files, so you might have to use a few. A: I've recently used Tag Lib Sharp to write some C# apps for cleaning up and maintaining my music library. I found the library very easy to use and although i've only used it for MP3's, it appears to support a range of other music/video formats. A: Looks like MediaInfo is read-only at this point, by the way: http://sourceforge.net/forum/message.php?msg_id=4241318&abmode=1 Very cool project, though. It's fun finding out about all this cool stuff here on SO. A: I used COM interop to access DirectShow's Media Detector functionality. This does work pretty well, but it's a right pain in the backside. You need to know lots about COM, win32 interop, and so on. You can also use DirectShowNet which should handle most of that for you, I just didn't want to lug that whole thing around when I was only interested in the MediaDetector part
{ "language": "en", "url": "https://stackoverflow.com/questions/9091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Add a bookmark that is only javascript, not a URL I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes... I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL. I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now. A: Well, I just created a bookmark in FF3, went back and updated it and added the following test: javascript:alert('Wacky%20test%20yo'); Low and behold, after I saved and loaded, I was able to get my alert. I'm sure you can work up something similar for your needs. A: What you want is a bookmarklet they are easy to create and should work in most major browsers. Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field javascript:window.location='http://www.google.com/search?q='+Date() to get a bookmarklet that searches google for the current date. A: It is worthy of note that you can put that in a function wrapper as well. imranamajeed nicely illustrated that for us... but apparently I'm too new to the site to up his post. :P so for clarity: javascript:(function(){ location.href = location.href + "#"; })(); (the carriage returns did not affect performance in chrome and IE) A: One minor catch. IE can only handle a 508 character URL in this format. If you save it in IE with a url longer than this, it will truncate without warning and thus fail. If you need a really complex script, you'll need to use a "hosted" bookmarklet, where you have a short bookmark that injects a script tag into the page, to "call" your hosted bookmarklet. It isn't as nice/portable, but its the only workaround. A: Google Bookmark javascript:(function(){var%20a=window,b=document,c=encodeURIComponent,d=a.open("http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk="+c(b.location)+"&title="+c(b.title),"bkmk_popup","left="+((a.screenX||a.screenLeft)+10)+",top="+((a.screenY||a.screenTop)+10)+",height=420px,width=550px,resizable=1,alwaysRaised=1");a.setTimeout(function(){d.focus()},300)})();
{ "language": "en", "url": "https://stackoverflow.com/questions/9104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: Select all columns except one in MySQL? I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this? EDIT: There are 53 columns in this table (NOT MY DESIGN) A: You could use DESCRIBE my_table and use the results of that to generate the SELECT statement dynamically. A: My main problem is the many columns I get when joining tables. While this is not the answer to your question (how to select all but certain columns from one table), I think it is worth mentioning that you can specify table. to get all columns from a particular table, instead of just specifying . Here is an example of how this could be very useful: select users.*, phone.meta_value as phone, zipcode.meta_value as zipcode from users left join user_meta as phone on ( (users.user_id = phone.user_id) AND (phone.meta_key = 'phone') ) left join user_meta as zipcode on ( (users.user_id = zipcode.user_id) AND (zipcode.meta_key = 'zipcode') ) The result is all the columns from the users table, and two additional columns which were joined from the meta table. A: I liked the answer from @Mahomedalid besides this fact informed in comment from @Bill Karwin. The possible problem raised by @Jan Koritak is true I faced that but I have found a trick for that and just want to share it here for anyone facing the issue. we can replace the REPLACE function with where clause in the sub-query of Prepared statement like this: Using my table and column name SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users'); PREPARE stmt1 FROM @SQL; EXECUTE stmt1; So, this is going to exclude only the field id but not company_id A: (Do not try this on a big table, the result might be... surprising !) TEMPORARY TABLE DROP TABLE IF EXISTS temp_tb; CREATE TEMPORARY TABLE ENGINE=MEMORY temp_tb SELECT * FROM orig_tb; ALTER TABLE temp_tb DROP col_a, DROP col_f,DROP col_z; #// MySQL SELECT * FROM temp_tb; DROP syntax may vary for databases @Denis Rozhnev A: Yes, though it can be high I/O depending on the table here is a workaround I found for it. SELECT * INTO #temp FROM table ALTER TABLE #temp DROP COlUMN column_name SELECT * FROM #temp A: Would a View work better in this case? CREATE VIEW vwTable as SELECT col1 , col2 , col3 , col.. , col53 FROM table A: It is good practice to specify the columns that you are querying even if you query all the columns. So I would suggest you write the name of each column in the statement (excluding the one you don't want). SELECT col1 , col2 , col3 , col.. , col53 FROM table A: I agree with the "simple" solution of listing all the columns, but this can be burdensome, and typos can cause lots of wasted time. I use a function "getTableColumns" to retrieve the names of my columns suitable for pasting into a query. Then all I need to do is to delete those I don't want. CREATE FUNCTION `getTableColumns`(tablename varchar(100)) RETURNS varchar(5000) CHARSET latin1 BEGIN DECLARE done INT DEFAULT 0; DECLARE res VARCHAR(5000) DEFAULT ""; DECLARE col VARCHAR(200); DECLARE cur1 CURSOR FOR select COLUMN_NAME from information_schema.columns where TABLE_NAME=@table AND TABLE_SCHEMA="yourdatabase" ORDER BY ORDINAL_POSITION; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur1; REPEAT FETCH cur1 INTO col; IF NOT done THEN set res = CONCAT(res,IF(LENGTH(res)>0,",",""),col); END IF; UNTIL done END REPEAT; CLOSE cur1; RETURN res; Your result returns a comma delimited string, for example... col1,col2,col3,col4,...col53 A: You can do: SELECT column1, column2, column4 FROM table WHERE whatever without getting column3, though perhaps you were looking for a more general solution? A: If you are looking to exclude the value of a field, e.g. for security concerns / sensitive info, you can retrieve that column as null. e.g. SELECT *, NULL AS salary FROM users A: I agree that it isn't sufficient to Select *, if that one you don't need, as mentioned elsewhere, is a BLOB, you don't want to have that overhead creep in. I would create a view with the required data, then you can Select * in comfort --if the database software supports them. Else, put the huge data in another table. A: At first I thought you could use regular expressions, but as I've been reading the MYSQL docs it seems you can't. If I were you I would use another language (such as PHP) to generate a list of columns you want to get, store it as a string and then use that to generate the SQL. A: Based on @Mahomedalid answer, I have done some improvements to support "select all columns except some in mysql" SET @database = 'database_name'; SET @tablename = 'table_name'; SET @cols2delete = 'col1,col2,col3'; SET @sql = CONCAT( 'SELECT ', ( SELECT GROUP_CONCAT( IF(FIND_IN_SET(COLUMN_NAME, @cols2delete), NULL, COLUMN_NAME ) ) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tablename AND TABLE_SCHEMA = @database ), ' FROM ', @tablename); SELECT @sql; If you do have a lots of cols, use this sql to change group_concat_max_len SET @@group_concat_max_len = 2048; A: I agree with @Mahomedalid's answer, but I didn't want to do something like a prepared statement and I didn't want to type all the fields, so what I had was a silly solution. Go to the table in phpmyadmin->sql->select, it dumps the query: copy, replace and done! :) A: To the best of my knowledge, there isn't. You can do something like: SELECT col1, col2, col3, col4 FROM tbl and manually choose the columns you want. However, if you want a lot of columns, then you might just want to do a: SELECT * FROM tbl and just ignore what you don't want. In your particular case, I would suggest: SELECT * FROM tbl unless you only want a few columns. If you only want four columns, then: SELECT col3, col6, col45, col 52 FROM tbl would be fine, but if you want 50 columns, then any code that makes the query would become (too?) difficult to read. A: Actually there is a way, you need to have permissions of course for doing this ... SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>'); PREPARE stmt1 FROM @sql; EXECUTE stmt1; Replacing <table>, <database> and <columns_to_omit> A: While I agree with Thomas' answer (+1 ;)), I'd like to add the caveat that I'll assume the column that you don't want contains hardly any data. If it contains enormous amounts of text, xml or binary blobs, then take the time to select each column individually. Your performance will suffer otherwise. Cheers! A: You can use SQL to generate SQL if you like and evaluate the SQL it produces. This is a general solution as it extracts the column names from the information schema. Here is an example from the Unix command line. Substituting * *MYSQL with your mysql command *TABLE with the table name *EXCLUDEDFIELD with excluded field name echo $(echo 'select concat("select ", group_concat(column_name) , " from TABLE") from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1) | MYSQL You will really only need to extract the column names in this way only once to construct the column list excluded that column, and then just use the query you have constructed. So something like: column_list=$(echo 'select group_concat(column_name) from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1) Now you can reuse the $column_list string in queries you construct. A: Just do SELECT * FROM table WHERE whatever Then drop the column in you favourite programming language: php while (($data = mysql_fetch_array($result, MYSQL_ASSOC)) !== FALSE) { unset($data["id"]); foreach ($data as $k => $v) { echo"$v,"; } } A: The answer posted by Mahomedalid has a small problem: Inside replace function code was replacing "<columns_to_delete>," by "", this replacement has a problem if the field to replace is the last one in the concat string due to the last one doesn't have the char comma "," and is not removed from the string. My proposal: SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_delete>', '\'FIELD_REMOVED\'') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>'); Replacing <table>, <database> and ` The column removed is replaced by the string "FIELD_REMOVED" in my case this works because I was trying to safe memory. (The field I was removing is a BLOB of around 1MB) A: I wanted this too so I created a function instead. public function getColsExcept($table,$remove){ $res =mysql_query("SHOW COLUMNS FROM $table"); while($arr = mysql_fetch_assoc($res)){ $cols[] = $arr['Field']; } if(is_array($remove)){ $newCols = array_diff($cols,$remove); return "`".implode("`,`",$newCols)."`"; }else{ $length = count($cols); for($i=0;$i<$length;$i++){ if($cols[$i] == $remove) unset($cols[$i]); } return "`".implode("`,`",$cols)."`"; } } So how it works is that you enter the table, then a column you don't want or as in an array: array("id","name","whatevercolumn") So in select you could use it like this: mysql_query("SELECT ".$db->getColsExcept('table',array('id','bigtextcolumn'))." FROM table"); or mysql_query("SELECT ".$db->getColsExcept('table','bigtextcolumn')." FROM table"); A: May be I have a solution to Jan Koritak's pointed out discrepancy SELECT CONCAT('SELECT ', ( SELECT GROUP_CONCAT(t.col) FROM ( SELECT CASE WHEN COLUMN_NAME = 'eid' THEN NULL ELSE COLUMN_NAME END AS col FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test' ) t WHERE t.col IS NOT NULL) , ' FROM employee' ); Table : SELECT table_name,column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test' ================================ table_name column_name employee eid employee name_eid employee sal ================================ Query Result: 'SELECT name_eid,sal FROM employee' A: I use this work around although it may be "Off topic" - using mysql workbench and the query builder - * *Open the columns view *Shift select all the columns you want in your query (in your case all but one which is what i do) *Right click and select send to SQL Editor-> name short. *Now you have the list and you can then copy paste the query to where ever. A: While trying the solutions by @Mahomedalid and @Junaid I found a problem. So thought of sharing it. If the column name is having spaces or hyphens like check-in then the query will fail. The simple workaround is to use backtick around column names. The modified query is below SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(CONCAT("`", COLUMN_NAME, "`")) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users'); PREPARE stmt1 FROM @SQL; EXECUTE stmt1; A: If the column that you didn't want to select had a massive amount of data in it, and you didn't want to include it due to speed issues and you select the other columns often, I would suggest that you create a new table with the one field that you don't usually select with a key to the original table and remove the field from the original table. Join the tables when that extra field is actually required. A: If it's always the same one column, then you can create a view that doesn't have it in it. Otherwise, no I don't think so. A: I would like to add another point of view in order to solve this problem, specially if you have a small number of columns to remove. You could use a DB tool like MySQL Workbench in order to generate the select statement for you, so you just have to manually remove those columns for the generated statement and copy it to your SQL script. In MySQL Workbench the way to generate it is: Right click on the table -> send to Sql Editor -> Select All Statement. A: The accepted answer has several shortcomings. * *It fails where the table or column names requires backticks *It fails if the column you want to omit is last in the list *It requires listing the table name twice (once for the select and another for the query text) which is redundant and unnecessary *It can potentially return column names in the wrong order All of these issues can be overcome by simply including backticks in the SEPARATOR for your GROUP_CONCAT and using a WHERE condition instead of REPLACE(). For my purposes (and I imagine many others') I wanted the column names returned in the same order that they appear in the table itself. To achieve this, here we use an explicit ORDER BY clause inside of the GROUP_CONCAT() function: SELECT CONCAT( 'SELECT `', GROUP_CONCAT(COLUMN_NAME ORDER BY `ORDINAL_POSITION` SEPARATOR '`,`'), '` FROM `', `TABLE_SCHEMA`, '`.`', TABLE_NAME, '`;' ) FROM INFORMATION_SCHEMA.COLUMNS WHERE `TABLE_SCHEMA` = 'my_database' AND `TABLE_NAME` = 'my_table' AND `COLUMN_NAME` != 'column_to_omit'; A: I have a suggestion but not a solution. If some of your columns have a larger data sets then you should try with following SELECT *, LEFT(col1, 0) AS col1, LEFT(col2, 0) as col2 FROM table A: If you use MySQL Workbench you can right-click your table and click Send to sql editor and then Select All Statement This will create an statement where all fields are listed, like this: SELECT `purchase_history`.`id`, `purchase_history`.`user_id`, `purchase_history`.`deleted_at` FROM `fs_normal_run_2`.`purchase_history`; SELECT * FROM fs_normal_run_2.purchase_history; Now you can just remove those that you dont want. A: The question was about MySQL, but I still think it's worth mentioning that at least Google BigQuery and H2 support a * EXCEPT syntax natively, e.g. SELECT * FROM actor Producing: |actor_id|first_name|last_name |last_update | |--------|----------|------------|-----------------------| |1 |PENELOPE |GUINESS |2006-02-15 04:34:33.000| |2 |NICK |WAHLBERG |2006-02-15 04:34:33.000| |3 |ED |CHASE |2006-02-15 04:34:33.000| Whereas SELECT * EXCEPT (last_update) FROM actor Producing: |actor_id|first_name|last_name | |--------|----------|------------| |1 |PENELOPE |GUINESS | |2 |NICK |WAHLBERG | |3 |ED |CHASE | Maybe, a future version of MySQL will support this syntax as well? A: Select * is a SQL antipattern. It should not be used in production code for many reasons including: It takes a tiny bit longer to process. When things are run millions of times, those tiny bits can matter. A slow database where the slowness is caused by this type of sloppy coding throughout is the hardest kind to performance tune. It means you are probably sending more data than you need which causes both server and network bottlenecks. If you have an inner join, the chances of sending more data than you need are 100%. It causes maintenance problems especially when you have added new columns that you do not want seen everywhere. Further if you have a new column, you may need to do something to the interface to determine what to do with that column. It can break views (I know this is true in SQl server, it may or may not be true in mysql). If someone is silly enough to rebuild the tables with the columns in a differnt order (which you shouldn't do but it happens all teh time), all sorts of code can break. Espcially code for an insert for example where suddenly you are putting the city into the address_3 field becasue without specifying, the database can only go on the order of the columns. This is bad enough when the data types change but worse when the swapped columns have the same datatype becasue you can go for sometime inserting bad data that is a mess to clean up. You need to care about data integrity. If it is used in an insert, it will break the insert if a new column is added in one table but not the other. It might break triggers. Trigger problems can be difficult to diagnose. Add up all this against the time it take to add in the column names (heck you may even have an interface that allows you to drag over the columns names (I know I do in SQL Server, I'd bet there is some way to do this is some tool you use to write mysql queries.) Let's see, "I can cause maintenance problems, I can cause performance problems and I can cause data integrity problems, but hey I saved five minutes of dev time." Really just put in the specific columns you want. I also suggest you read this book: http://www.amazon.com/SQL-Antipatterns-Programming-Pragmatic-Programmers-ebook/dp/B00A376BB2/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1389896688&sr=1-1&keywords=sql+antipatterns A: Im pretty late at throing out an answer for this, put this is the way i have always done it and frankly, its 100 times better and neater than the best answer, i only hope someone will see it. And find it useful //create an array, we will call it here. $here = array(); //create an SQL query in order to get all of the column names $SQL = "SHOW COLUMNS FROM Table"; //put all of the column names in the array foreach($conn->query($SQL) as $row) { $here[] = $row[0]; } //now search through the array containing the column names for the name of the column, in this case i used the common ID field as an example $key = array_search('ID', $here); //now delete the entry unset($here[$key]);
{ "language": "en", "url": "https://stackoverflow.com/questions/9122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "450" }
Q: Enterprise Library CacheFactory.GetCacheManager Throws Null Ref I'm trying to convert an application using the 1.1 version of the Enterprise Library Caching block over to the 2.0 version. I think where I'm really having a problem is that the configuration for the different EntLib pieces was split out over several files. Apparently, this used to be handled by the ConfigurationManagerSectionHandler, but is now obsolete in favor of the built-in configuration mechanisms in .NET 2.0. I'm having a hard time finding a good example of how to do this configuration file splitting, especially in the context of EntLib. Has anyone else dealt with this? A: Looks like it was the configuration. I found a good example of the normal, one-file approach here: http://www.devx.com/dotnet/Article/31158/0/page/2 Using an external config file is actually trivial once you figure out the syntax for it. Ex.: In Web.config: <cachingConfiguration configSource="cachingconfiguration.config" /> In cachingconfiguration.config: <?xml version="1.0" encoding="utf-8"?> <cachingConfiguration defaultCacheManager="Default Cache Manager"> <backingStores> <add name="inMemory" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching" /> </backingStores> <cacheManagers> <add name="Default Cache Manager" expirationPollFrequencyInSeconds = "60" maximumElementsInCacheBeforeScavenging ="50" numberToRemoveWhenScavenging="10" backingStoreName="inMemory" /> </cacheManagers> </cachingConfiguration> Hopefully this helps somebody!
{ "language": "en", "url": "https://stackoverflow.com/questions/9136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: FogBugz compared to OnTime Has anyone used both FogBugz and Axosoft's OnTime and care to offer an opinion? AxoSoft has a big feature comparison chart but I'm also interested in more subjective thoughts on things like ease of use and stability. A: I've used both from a project lead perspective and a team member, to manage parallel projects and teams. OnTime has a big feature matrix, but that doesn't translate into more value in an organization. For ease of use, OnTime fails. OnTime does NOT have a well designed interface, so for me, it does not stand out in the crowd. FogBugz, on the other hand, is pleasant to use, and I found myself "happier" to login every morning. For me, the most important "feature" is: How well the tool presents and tracks issues and simplifies participation by team members. If it does this poorly, most of the other features fade. If it does this well, then some missing features can be forgiven. On this one point, I find OnTime particularly inadequate and FogBugz particularly superior. OnTime is loaded with different tabs in which information becomes lost or difficult to track. Teams and individuals often use different tabs for different purposes. I have to click around or I might miss something. FogBugz tracks the issue with minimal clutter, like a discussion thread. When updates are made to the issue, all parties are notified via email, and no information is visually lost. At a glance, I always know what is going on with FogBugz. OnTime 2009 also doesn't allow us to assign and track issues with multiple team members in parallel. You simply assign to a single person. No way to CC others. Big deficiency for team work. Also, when performing a project review, we often take down a lot of fast issues as the customer speaks. With FogBugz I can use the quick mode to punch the issue in as fast as I can type descriptions, and return later to flesh it out. We cannot do this with OnTime, with its various required fields. Besides that, OnTime is just sluggish, taking 5-6 seconds just for the defect window to popup. I need to be able to enter issues during a meeting as fast as I can type it into Excel. The total time & clicks to create an issue in any tool is a key benchmark. In short, with customers who use OnTime I see people constantly fallback to email for discussions, and I also see degraded communication (someone enters notes that others never see). I do not see this trend with FogBugz. Feature matrixes look good on paper, but it is difficult enough to keep teams using a tool properly without the tool adding more difficulty. FogBugz makes it as simple as you want, while allowing you to drill down as needed. OnTime, however, feels like a very detailed tracking database with quick WinForms app thrown on top. The downside for me with FogBugz is price for upgrades. Yearly maintenance is steep at 50% of the original cost. I could not justify upgrades, in part because we are happy with FogBugz 6, but in part because I could not see what I was getting for my yearly maintenance fees. FogCreek wasn't very flexible on licensing discounts for us, after all they need to make a living, so we just decided to stick with v6 forever. UPDATE 2014: A year or so after I wrote this, FogCreek sent me a free upgrade to v7 to fix a security bug. Just this year, they did the same thing again. They are the only company I've ever deal with to give me a free upgrade just to fix a bug, even without maintenance. A top-notch company with good people. I'd still spend my money again on FogBugz without a second thought. A: I actually encouraged the company I work for to begin tracking bugs with software (specifically FogBugz) and have been very pleased with FogBugz. We blindly let our customers send bug requests into FogBugz through email, which has it's advantages and disadvantages. But we really haven't had any problems integrating FogBugz into a team that was totally unfamiliar with any bug tracking software. Overall, I'd rate FogBugz about a 9 on ease of use and stability. A: I've used both extensively in production software development environments. OnTime isn't bad - once you set it up to handle support tickets sent to an email, it has all the daily activities of software developers pretty well integrated. I personally prefer FogBugz, because of the predictive estimation stuff that it includes. Being able to pick a due date, and then getting a likelihood of hitting that date based on your past performance is pretty awesome. I also think in general FogBugz is faster to use and organize your features/defects, and I like how it tracks time better. One area where OnTime wins out is that it is much easier to make reports against OnTime. It stores everything in a SQL server so it is easy to access (granted if you get the non-hosted FogBugz maybe you could do this too). Also, it includes a report designer so you can get to your data. FogBugz has the weakness that while you can track and enter the time you spent per item for the purposes of its experienced-based scheduling, it doesn't give you an easy way as a manager to look at how much time a given employee spent on what things that week. Hopefully they will add that in the near future. A: OnTime is more an ALM tool - it's trying to do everything. FogBugz just deals with bugs (and feature requests) and at that it's excellent. I'm not sure about some of the newer extensions (like discussions), but for bugs it's really good. There's lots of stuff that I'd add to it in terms of better reports, searching and the like, but I can definitely recommend FogBugz. A: I've used OnTime for a few years now. It's actually a very easy tool to use and not just a bug tracking tool as was suggested. Where it falls down for me is the slowdown I've experienced as the volumes of Features / Defects/ Tasks have grown. Also, the web client tries too hard to be a parallel of the winform version and can be flaky as a result. A: I have not tested the OnTime thing, but keep in mind that both FogBugz and OnTime have free versions as well, Axosoft for 1 user and FogBugz for 2 Users, although it's the hosted version. (Check my answer here to see how to sign up for the free FogBugz version) So you can have some real first-hand experience on both systems. A: * *Are you bug tracking or project planning? FogBugz has better bug tracking features. FogBugz has better e-mail integration, state tracking and triggers. FogBugz is easier to drill down to an individual task without needing to apply a lot of filters. For project planning, however, OnTime is the superior tool. The monte carlo estimation feature in FogBugz is cool--don't get me wrong--but honestly, getting the project entered into FogBugz so you can actually use the estimator is such a pain in the rear it can be downright frustrating. The scrum planning board in OnTime is really sexy. If you're used to using whiteboards or sticky notes, it's a breeze to enter and visualize. OnTime provides better project overview information and custom reporting; this is better for managers. FogBugz provides better drill-down information; this is better for implementers. FogBugz has more features; this is better for tech-centric users. OnTime is more graphical; this is better for non-engineers (project planners, artists and other people who often have to use scheduling tools). Other factors: Some people have mentioned speed issues. I haven't noticed speed issues with either, but my only experiences have been local installs. OnTime is expensive for mid-sized teams; it's free for a single user and by the time you get to 10+ users the price is average, but for 3-6 man teams it's expensive especially if you want the pivot charts. Quite honestly if you can afford it, it would not be stupid to consider both. Use OnTime for writing quotes, and FogBugz for tracking defects. They are radically different tools, and neither one excels in all areas but both are very good at select tasks. A: I haven't worked with FogBugz, although I recently recommended our company goes with that. OnTime is what the company decided to use and I personally don't like OnTime because of slowness and badly organized GUI. We opted to host it ourselves, but I don't think the machine is slow. The web app doesn't really look like a web app, more like it copies a windows app, just as Brian Scott said in his answer. And don't try using the windows app over Internet (over VPN). It's awfully slow. I suppose it could be due to our Internet connection latency. Of course, my experience might be different than other people's, I could be having network issues. Someone else will have to confirm my claims of slowness. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/9143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Opening a file in my application from File Explorer I've created my own application in VB.NET that saves its documents into a file with it's own custom extension (.eds). Assuming that I've properly associated the file extension with my application, how do I actually handle the processing of the selected file within my application when I double click on the file in File Explorer? Do I grab an argsc/argsv variable in my Application.Load() method or is it something else? A: Try this article but short answer is My.Application.CommandLineArgs
{ "language": "en", "url": "https://stackoverflow.com/questions/9161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Lingering assembly dependency in C# .NET My C# project - we'll call it the SuperUI - used to make use of a class from an external assembly. Now it doesn't, but the compiler won't let me build the project without the assembly reference in place. Let me elaborate. This project used to throw and catch a custom exception class - the SuperException - which was derived from the standard System.Exception and lived in a separate, precompiled assembly, SuperAssembly.DLL, which I referenced. Eventually, I decided this was a pointless exercise and replaced all SuperExceptions with a System.SuitableStandardException in each case. I removed the reference to SuperException.DLL, but am now met with the following on trying to compile the project: The type 'SuperException' is defined in an assembly that is not referenced. You must add a reference to assembly 'SuperException, Version=1.1.0.0 (...)' The source file referenced by the error doesn't seem relevant; it's the project namespace that gets highlighted in the IDE. Now, here's the thing: * *All uses of SuperException have been eliminated from the project's code. *Compared to another project that compiles fine without a reference to SuperException.DLL, I only reference one more assembly - and that references nothing that my project doesn't reference itself. While it's possible that any of these dependencies could throw SuperExceptions, I'm only catching the base Exception class and in any case... the other project builds fine! *I've done Visual Studio's "Clean Solution" and cleared everything out by hand, many times. It's not the end of the world to include this reference, I just don't see why it's necessary any more. Nrrrgg. Any pointers welcome! A: It's likely a transitive reference, where some type method call returns an instance of SuperException boxed ("downcast") as e.g. Exception, but from inspecting the code in the transitively included code, i.e. code from your external method calls, the compiler knows that you need to be able to have information about that type at some point. Resharper would tell you where it's the case that you need to add a reference, and you could use Lütz Roeder's aka RedGate's Reflector to scan compiled IL for a reference to this type in two ways: 1) use the search-facility, 2) open each public type you're using and for that one which requires the "ghost" assembly, it will ask you to specify its location. This most often happends to me when I reference Castle.Windsor but not Castle.MicroKernel. :p A: * *Exit Visual Studio *Delete the bin and obj Folders in your solution directory *Restart and see what happens A: I agree with the other comments here.. There is a reference, in plain text somewhere ! I have had similar problems in the past where searching through the project files returned nothing, turns out it was in some other file that wasn't automatically picked up in the search. I don't think that creating a new project is the solution here.. You need to be positive that NONE of the references in your dependency tree use SuperException.. NONE I have never experienced this to the point where I have needed to literally wipe the project, I have always found the reference somewhere. Ensure you are searching every file. EDIT: Just a point to add, if the location pointed to by the error seems random, that can often mean there is a mismatch between the compiled source and the source code file.. Is this a ASP.NET application? I have had it before where the compiled DLL's haven't been replaced on a rebuild in the ASP.NET temp folder causing things to get.. Interesting when debugging :) A: I don't think this is a code issue. What I can see happening is that one of your existing references probably rely on that type in their own types which you are probably creating in your application. If that is the case you do need that reference even if you don't explicitly use the type and even though the other referenced assembly has its own reference. You sometimes get that issue with 3rd party components which need references to types that you haven't referenced. The compiler is obviously seeing something in one of your existing referenced assemblies and is expecting you to referenced the dependent one. A: Since it's a compiler error, there must be a reference or use of SuperException somewhere in the project. * *Do a find/replace in the entire project or solution for that type and remove every reference (it's possible you already did this). *If you reference any types that inherits from SuperException (even if the type defined in another assembly), you need a reference to the assembly that SuperException is defined in. Take the line that the compiler is showing the error on and start tracing the inheritance tree of the objects used on that line, you might find the source of it that way. A: Thanks for your answers so far. I've tried every suggestion (except one) to no avail. The suggestion I haven't tried is to create a new project and add all my stuff to it, the thought of which really tests my will to live. ;) I may try this tomorrow if I can be bothered. Thanks again. A: There is really nothing very mysterious about VS projects nowadays - it's all text files, etc. SOMETHING must reference that class/dll, and that something must be part of your project. Have you really grep'd or findstr'd the whole solution tree, every single file, for a reference to that exception? A: This sounds pretty strange. Here's what I would check next: * *Check that there's nothing lingering in your Properties/AssemblyInfo.cs file. *Check that there's nothing lingering in your SuperUI.csproj file. *Delete all references and re-add them. A: Try creating a new project, and adding all your classes to it. A: grep your project folder. It could be a hidden reference in your project, or a project that your project references. Cleanse with Notepad if needed. A: If you reference any types that inherits from SuperException (even if the type defined in another assembly), you need a reference to the assembly that SuperException is defined in. Seconded on that. You might not be referencing SuperException, but you might be referencing SpecializedSuperException, which is derived from, or somehow otherwise uses SuperException - your grep of the project for SuperException won't be catching it though. Try have a hack with the trial of NDepend A: This is where tools like Resharper really pay off -- a simple Find Usages usually tells me of such "ghost dependencies" several times. Maybe you could go to your definition of the SuperException class and try to Find All References(). You might also want to investigate if the assembly SuperException is has a circular dependency on your main assembly (e.g., main assembly depends on exception assembly depends on main assembly...). A: I’ve had a very similar assembly reference issue that was happening when my C# library had a dependent C++/CLI assembly. The problem that was I was inheriting a public class from that C++/CLI assembly in my C# assembly library. That meant that the inheritance chain was spanning across multiple assemblies. I was hoping that any client would be smart enough to indirectly load the C++/CLI assembly any time the C# library needed it, but that was not the case even at compile time. I got rid of this problem by breaking the inheritance between the classes that were spanning across those two assembly libraries and using aggregation instead. My client was finally happy and did not require the C++/CLI assembly as a dependency anymore. In your word you would probably have to make sure that SuitableStandardException does not inherit from SuperException in order to eliminate the SuperException.DLL as a reference. Use encapsulation instead of inheritance and create a SuperException data member in your new SuitableStandardException. If that does not solve it, you might have more classes spanning inheritance across some assemblies, in your case SuperAssembly.DLL and superException.dll. If you can't find all of them try this trick: * *Make all your public members and classes in SuperAssembly.DLL internal. *In the SuperAssembly.DLL make friends with SuperException.DLL: [assembly:InternalsVisibleTo("SuperException, PublicKey=0024000004800000....)] *Make sure that they build and remove the SuperAssembly.DLL reference from any client that already references SuperException.DLL. A: grep -R SuperException * in the base of your project (get grep from somewhere first) just to be sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/9173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to obtain good concurrent read performance from disk I'd like to ask a question then follow it up with my own answer, but also see what answers other people have. We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read. Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek. If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler. Is there anything we can do to improve the concurrent thread read performance? Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way. Some details: The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case. We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc. Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected. The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5. A: I'd like to add some further notes in my response. All other non-Microsoft operating systems we have tested do not suffer from this problem. Linux, FreeBSD, and Mac OS X (this final one on different hardware) all degrade much more gracefully in terms of aggregate bandwidth when moving from one thread to two. Linux for example degraded from ~45 MiB/sec to ~42 MiB/sec. These other operating systems must be reading larger chunks of the file between each seek, and therefor not spending nearly all their time waiting on the disk to seek. Our solution for Windows is to pass the FILE_FLAG_NO_BUFFERING flag to CreateFile and use large (~16MiB) reads in each call to ReadFile. This is suboptimal for several reasons: * *Files don't get cached when read like this, so there are none of the advantages that caching normally gives. *The constraints when working with this flag are much more complicated than normal reading (alignment of read buffers to page boundaries, etc). (As a final remark. Does this explain why swapping under Windows is so hellish? Ie, Windows is incapable of doing IO to multiple files concurrently with any efficiency, so while swapping all other IO operations are forced to be disproportionately slow.) Edit to add some further details for Will Dean: Of course across these different hardware configurations the raw figures did change (sometimes substantially). The problem however is the consistent degradation in performance that only Windows suffers when moving from one thread to two. Here is a summary of the machines tested: * *Several Dell workstations (Intel Xeon) of various ages running Windows 2000, Windows XP (32-bit), and Windows XP (64-bit) with single drive. *A Dell 1U server (Intel Xeon) running Windows Server 2003 (64-bit) with RAID 1+0. *An HP workstation (AMD Opteron) with Windows XP (64-bit), and Windows Server 2003, and hardware RAID 5. *My home unbranded PC (AMD Athlon64) running Windows XP (32-bit), FreeBSD (64-bit), and Linux (64-bit) with single drive. *My home MacBook (Intel Core1) running Mac OS X, single SATA drive. *My home Koolu PC running Linux. Vastly underpowered compared to the other systems but I demonstrated that even this machine can outperform a Windows server with RAID5 when doing multi-threaded disk reads. CPU usage on all of these systems was very low during the tests and anti-virus was disabled. I forgot to mention before but we also tried the normal Win32 CreateFile API with the FILE_FLAG_SEQUENTIAL_SCAN flag set. This flag didn't fix the problem. A: The problem seems to be in Windows I/O scheduling policy. According to what I found here there are many ways for an O.S. to schedule disk requests. While Linux and others can choose between different policies, before Vista Windows was locked in a single policy: a FIFO queue, where all requests where splitted in 64 KB blocks. I believe that this policy is the cause for the problem you are experiencing: the scheduler will mix requests from the two threads, causing continuous seek between different areas of the disk. Now, the good news is that according to here and here, Vista introduced a smarter disk scheduler, where you can set the priority of your requests and also allocate a minimum badwidth for your process. The bad news is that I found no way to change disk policy or buffers size in previous versions of Windows. Also, even if raising disk I/O priority of your process will boost the performance against the other processes, you still have the problems of your threads competing against each other. What I can suggest is to modify your software by introducing a self-made disk access policy. For example, you could use a policy like this in your thread B (similar for Thread A): if THREAD A is reading from disk then wait for THREAD A to stop reading or wait for X ms Read for X ms (or Y MB) Stop reading and check status of thread A again You could use semaphores for status checking or you could use perfmon counters to get the status of the actual disk queue. The values of X and/or Y could also be auto-tuned by checking the actual trasfer rates and slowly modify them, thus maximizing the throughtput when the application runs on different machines and/or O.S. You could find that cache, memory or RAID levels affect them in a way or the other, but with auto-tuning you will always get the best performance in every scenario. A: It does seem a little strange that you see no difference across quite a wide range of windows versions and nothing between a single drive and hardware raid-5. It's only 'gut feel', but that does make me doubtful that this is really a simple seeking problem. Other than the OS X and the Raid5, was all this tried on the same machine - have you tried another machine? Is your CPU usage basically zero during this test? What's the shortest app you can write which demonstrates this problem? - I would be interested to try it here. A: I would create some kind of in memory thread safe lock. Each thread could wait on the lock until it was free. When the lock becomes free, take the lock and read the file for a defined length of time or a defined amount of data, then release the lock for any other waiting threads. A: Do you use IOCompletionPorts under Windows? Windows via C++ has an in-depth chapter on this subject and as luck would have it, it is also available on MSDN. A: Paul - saw the update. Very interesting. It would be interesting to try it on Vista or Win2008, as people seem to be reporting some considerable I/O improvements on these in some circumstances. My only suggestion about a different API would be to try memory mapping the files - have you tried that? Unfortunately at 2GB per file, you're not going to be able to map multiple whole files on a 32-bit machine, which means this isn't quite as trivial as it might be.
{ "language": "en", "url": "https://stackoverflow.com/questions/9191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: IL level code debugger Is there any IL level debugger in form of a VS plugin or standalone application? Visual studio’s debugger is great, but it allows you to debug on either HLL code level or assembly language, you can’t debug IL. It seems that in some situations it would be useful to have an opportunity to debug at IL level. In particular it might be helpful when debugging a problem in the code that you don't have the source of. It is arguable if it is actually useful to debug IL when you don't have the source, but anyway. A: Here's the .BAT file that I use to debug IL assembler in Visual Studio. The created .IL.IL file contains the original source code lines and your generated IL assembler lines but does not show jitted machine code. I named the batch file ILDEB.BAT and is invoked as "ILDEB mypgm". I use the IL assembler directive "break" to force Visual Studio debugger to breakpoint when hit. for /f "tokens=1 delims=." %%1 in ("%1") do set NAME_ONLY=%%1 @erase/q %NAME_ONLY%.il.il @if not exist %NAME_ONLY%.dll goto quit ildasm /out:%NAME_ONLY%.il.il /source /nobar %NAME_ONLY%.dll @if not exist %NAME_ONLY%.il.il goto quit ilasm /dll /debug /out=%NAME_ONLY%.dll %NAME_ONLY%.il.il @if not exist %NAME_ONLY%.dll goto quit peverify %NAME_ONLY%.dll :quit A: The best way to do this is to use ILDASM to disassemble the managed binary, which will generate the IL instructions. Then recompile that IL source code in debug mode using ILASM, when you fire up the Visual Studio debugger you will be able to step through the raw IL. * *ildasm foo.exe /OUT=foo.exe.il /SOURCE *ilasm foo.exe.il /DEBUG I've written a blog post about this topic at: How to debug Compiler Generated code. A: Debug Companion VS plugin seem to be exactly what I was looking for, except that it won't see library project in my solution. Only when I added a console win application to the solution did something appear in that list of projects. The problem with the decompile/compile approach for me was that the code I was debugging wasn't my code. I could have decompiled it anyway but I think there's no way to sign that recompiled assembly so that it gets loaded instead of the original one. With the particular problem I had it turned out that it was enough to just debug it on the assembly language level and get the call stack of the method which was throwing the exception and the parameters with which the method was called. A: ISTR there's a debugger plug-in for Reflector. Not used it myself, though I have used TestDriven.net to debug a 3rd-party assembly with the aid of Reflector: weblogs.asp.net/nunitaddin A: Here is an article about IL debugging. It says you can't do it and then talks about ways to do it. There is also some info in the comments about doing it also.
{ "language": "en", "url": "https://stackoverflow.com/questions/9204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: ADO.NET Connection Pooling & SQLServer * *What is it? *How do I implement connection pooling with MS SQL? *What are the performance ramifications when * *Executing many queries one-after-the other (i.e. using a loop with 30K+ iterations calling a stored procedure)? *Executing a few queries that take a long time (10+ min)? *Are there any best practices? A: Connection pooling is a mechanism to re-use connections, as establishing a new connection is slow. If you use an MSSQL connection string and System.Data.SqlClient then you're already using it - in .Net this stuff is under the hood most of the time. A loop of 30k iterations might be better as a server side cursor (look up T-SQL cursor statements), depending on what you're doing with each step outside of the sproc. Long queries are fine - but be careful calling them from web pages as Asp.Net isn't really optimised for long waits and some connections will cut out. A: A little more info on the connection pooling thing... you're using it already with SqlClient, but only if your connection string is identical for each new connection you open. My understanding is that the framework will pool connections automatically when it can, but if the connection string varies even slightly from one connection to the next, then the new connection won't come from the pool - it gets created anew (so it's more expensive). You can use the Performance Monitor app with XP/Vista to watch SQL connections and you'll see pretty quickly whether or not pooling is being used. Look under the ".NET CLR Data" category" in Performance Monitor. A: I second Keith; if you're calling a stored procedure 30,000 times, you have far bigger problems than connection pooling. A: Your question was also partially answered by this thread. A search would have revealed this.. The definition of Connection Pooling, of which a Google would have answered with the first hit being this.. Which would leave just the best practices, which I think would have been a good question :) +1 to Keith's Answer. He has hit the nail right on the head. Just a polite reminder from the FAQ: You've searched the internet before asking your question, and you come to us armed with research and information about your question ... right?
{ "language": "en", "url": "https://stackoverflow.com/questions/9228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Offsite backups I was recently tasked with coming up with an offsite backup strategy. We have about 2TB of data that would need to be backed up so our needs are a little out of the norm. I looked into Iron Mountain and they wanted $12,000 a month! Does anyone have any suggestions on how best to handle backing up this much data on a budget (like a tenth of Iron Mountain)? How do other companies afford to do this? Thanks! UPDATE :: UPDATE Ironically enough, I just had the sort of devastating failure we're all talking about. I had my BES server fail and than 2 days later 2 drives in my Exchange server's RAID5 died (2!!!??!). I'm currently in the process of rebuilding my network and the backup integrity is an definitely an issue. At least now my bosses are paying attention :) A: You can buy external eSATA RAID boxes in the 8TB capacity range for $2600. I'm not saying that particular product is the right choice, but that's the kind of box that will do 6TB in RAID5 and still be portable enough to buy a couple of them and rotate them through the bank, like Stu says. Obviously if you have to have to keep 7 individual days worth, a 14 day, 30 and 90 day snapshot, etc. then things are going to be much more expensive, but it's certainly doable if what you're after is just disaster recovery. The biggest thing to make sure is part of your plan is actually testing the restoration from the backup. That seems to get overlooked WAY too often and turns out to be the weakest link in nearly all of the strategies. You should plan for scheduled restorations as often as is reasonable where you actually dump the real data and restore from the backup. Without that, you don't know that it will work when you NEED it too. I've lost track of the number of times I've been in a company where there's a big rack full of backup tapes/drives, all dutifully made according to the schedule only to find out that NONE of them have valid data when the server gets wiped out. The more ways you can verify the integrity of the backups the better, but nothing substitutes for doing an actual dump/load from one of your backups to really test the setup. A: Amazon S3 might fit your budget better. I don't know if there is software available to automate the backup process but it's rather easy to write your own code to handle this. Here's their pricing calculator. According to my estimates you're going to be well under the $1000/mo range. A: You really have to assess the true value of your data. If you lost it tomorrow what impact would it have on your business? We use offsite backups, it isn't cheap, but if we were to lose our data the business would cease to trade withing 2-3 days. We considered on-site backups as a possible cost saver but in my experience with data centres/computer rooms over the last ten years (as both an employee and a customer) I've seen fires, fire suppression system malfunctions (wet), hardware theft and one day a car crashed through an external wall right into the suite. Add to that our last DC was located at Heathrow, right next to the runways....you never know what strange things can happen (remember the BA 777 that got caught short of the runway on landing?). My advice, assess the value of the data then decide if $12k is too rich to keep it safe. A: 2TB is chump change nowadays. Look into hard-drive based hot-swappable backup machines, and rent a box at your local bank: http://www.high-rely.com/ (there are many more products such as this, but my Google-time is limited). A: Jungle Disk is one such piece of software that can automate the backup process to Amazon S3. I use it for backup at home, but I guess it could work just as well from a server. Also, there are probably other backup tools that make use of S3 for offsite storage. A: We've been using DataDomain appliances for that purpose for about 2 years. They're not inexpensive, but compared to $12,000/month they'd pay for themselves pretty quickly. Basically, we send our backups over NFS and CIFS to one DataDomain appliance, it deduplicates the data and then replicates the differences to the other appliance we have at a remote site. A: As for pure online solutions, make sure you do some back-of-the-envelope calculations first. For example, if you have 2TB of churn a month, you are going to saturate a 1Mb Internet connection just for your backup traffic! A: As previously mentioned, Amazon S3 is definitely an option, but it may be cheaper in the long run to own the hardware you are backing up to. For example: Buy a basic server and and eSATA RAID5 setup with 2-3 times the capacity you currently need, then install it at a co-location center. Preferably one with high, but cheap, bandwidth. This way the server and storage is off-site, but after the initial cost of the hardware, you are only paying for bandwidth. Granted, the downside to this is that, unlike something like S3, if the hardware goes down you have to go fix it yourself, or pay the CoLo people to. But this may be a tradeoff you are willing to make. Also, with this solution, you are still going to need a beefy upload pipe to handle the traffic... so there's always the "sneakernet" solution. A: I've used bqbackup.com for 1-2 years no problem. You can do a sync using rsync nightly. Wanted to add that their prices are dirt cheap, and I now have close to 1TB with them.
{ "language": "en", "url": "https://stackoverflow.com/questions/9231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Interfaces on different logic layers Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input. This great when you first write the UI code, because you have a neatly defined interface that you can trust. But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting. Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore. I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? A: If I understand the question correctly, you've created a domain model and you would like to write an object-relational mapper to map between records in your database and your domain objects. However, you're concerned about polluting your domain model with the 'plumbing' code that would be necessary to read and write to your object's fields. Taking a step back, you essentially have two choices of where to put your data mapping code - within the domain class itself or in an external mapping class. The first option is often called the Active Record pattern and has the advantage that each object knows how to persist itself and has sufficient access to its internal structure to allow it to perform the mapping without needing to expose non-business related fields. E.g public class User { private string name; private AccountStatus status; private User() { } public string Name { get { return name; } set { name = value; } } public AccountStatus Status { get { return status; } } public void Activate() { status = AccountStatus.Active; } public void Suspend() { status = AccountStatus.Suspended; } public static User GetById(int id) { User fetchedUser = new User(); // Lots of database and error-checking code // omitted for clarity // ... fetchedUser.name = (string) reader["Name"]; fetchedUser.status = (int)reader["statusCode"] == 0 ? AccountStatus.Suspended : AccountStatus.Active; return fetchedUser; } public static void Save(User user) { // Code to save User's internal structure to database // ... } } In this example, we have an object that represents a User with a Name and an AccountStatus. We don't want to allow the Status to be set directly, perhaps because we want to check that the change is a valid status transition, so we don't have a setter. Fortunately, the mapping code in the GetById and Save static methods have full access to the object's name and status fields. The second option is to have a second class that is responsible for the mapping. This has the advantage of seperating out the different concerns of business logic and persistence which can allow your design to be more testable and flexible. The challenge with this method is how to expose the name and status fields to the external class. Some options are: 1. Use reflection (which has no qualms about digging deep into your object's private parts) 2. Provide specially-named, public setters (e.g. prefix them with the word 'Private') and hope no one uses them accidentally 3. If your language suports it, make the setters internal but grant your data mapper module access. E.g. use the InternalsVisibleToAttribute in .NET 2.0 onwards or friend functions in C++ For more information, I'd recommend Martin Fowler's classic book 'Patterns of Enterprise Architecture' However, as a word of warning, before going down the path of writing your own mappers I'd strongly recommend looking at using a 3rd-party object relational mapper (ORM) tool such as nHibernate or Microsoft's Entity Framework. I've worked on four different projects where, for various reasons, we wrote our own mapper and it is very easy to waste a lot of time maintaining and extending the mapper instead of writing code that provides end user value. I've used nHibernate on one project so far and, although it has quite a steep learning curve initially, the investment you put in early on pays off considerably. A: This is a classic problem - separating your domain model from your database model. There are several ways to attack it, it really depends on the size of your project in my opinion. You could use the repository pattern as others have said. If you are using .net or java you could use NHibernate or Hibernate. What I do is use Test Driven Development so I write my UI and Model layers first and the Data layer is mocked, so the UI and model is build around domain specific objects, then later I map these object to what ever technology I'm using the the Data Layer. Is a very bad idea to let the database determine the design of your app, write the app first and think about the data later. ps the title of the question is a little mis-leading A: @Ice^^Heat: What do you mean by that the data tier should not be aware of the business logic tier? How would you fill an business object with data? The UI asks the ServiceClass in the business tier for a service, namely getting a list of objects filtered by an object with the needed parameter data. Then the ServiceClass creates an instance of one of the repository classes in the data tier, and calls the GetList(ParameterType filters). Then the data tier accesses the database, pulls up the data, and maps it to the common format defined in the "domain" assembly. The BL has no more work to do with this data, so it outputs it to the UI. Then the UI wants to edit Item X. It sends the item (or business object) to the service in the Business Tier. The business tier validates the object, and if it is OK, it sends it to the data tier for storage. The UI knows the service in the business tier which again knows about the data tier. The UI is responsible for mapping the users data input to and from the objects, and the data tier is responsible for mapping the data in the db to and from the objects. The Business tier stays purely business. :) A: I always create a separate assembly that contains: * *A lot of small Interfaces (think ICreateRepository, IReadRepository, IReadListRepsitory.. the list goes on and most of them relies heavily on generics) *A lot of concrete Interfaces, like an IPersonRepository, that inherits from IReadRepository, you get the point.. Anything you cannot describe with just the smaller interfaces, you put into the concrete interface. As long as you use the IPersonRepository to declare your object, you get a clean, consistent interface to work with. But the kicker is, you can also make a class that takes f.x. a ICreateRepository in its constructor, so the code will end up being very easy to do some really funky stuff with. There are also interfaces for the Services in the business tier here. *At last i stick all the domain objects into the extra assembly, just to make the code base itself a bit cleaner and more loosely coupled. These objects dont have any logic, they are just a common way to describe the data for all 3+ layers. Btw. Why would you define methods in the business logic tier to accommodate the data tier? The data tier should have no reason to even know there is a business tier.. A: It could be a solution, as it would not erode the interface. I guess you could have a class like this: public class BusinessObjectRecord : BusinessObject { } A: What do you mean by that the data tier should not be aware of the business logic tier? How would you fill an business object with data? I often do this: namespace Data { public class BusinessObjectDataManager { public void SaveObject(BusinessObject object) { // Exec stored procedure { } } A: So the problem is that the business layer needs to expose more functionality to the data layer, and adding this functionality means exposing too much to the UI layer? If I'm understanding your problem correctly, it sounds like you're trying to satisfy too much with a single interface, and that's just causing it to become cluttered. Why not have two interfaces into the business layer? One would be a simple, safe interface for the UI layer. The other would be a lower-level interface for the data layer. You can apply this two-interface approach to any objects which need to be passed to both the UI and the data layers, too. public class BusinessLayer : ISimpleBusiness {} public class Some3LayerObject : ISimpleSome3LayerObject {} A: You may want to split your interfaces into two types, namely: * *View interfaces -- which are interfaces that specify your interactions with your UI, and *Data interfaces -- which are interfaces that will allow you to specify interactions with your data It is possible to inherit and implement both set of interfaces such that: public class BusinessObject : IView, IData This way, in your data layer you only need to see the interface implementation of IData, while in your UI you only need to see the interface implementation of IView. Another strategy you might want to use is to compose your objects in the UI or Data layers such that they are merely consumed by these layers, e.g., public class BusinessObject : DomainObject public class ViewManager<T> where T : DomainObject public class DataManager<T> where T : DomainObject This in turn allows your business object to remain ignorant of both the UI/View layer and the data layer. A: I'm going to continue my habit of going against the grain and say that you should question why you are building all these horribly complex object layers. I think many developers think of the database as a simple persistence layer for their objects, and are only concerned with the CRUD operations that those objects need. Too much effort is being put into the "impedence mismatch" between object and relational models. Here's an idea: stop trying. Write stored procedures to encapsulate your data. Use results sets, DataSet, DataTable, SqlCommand (or the java/php/whatever equivalent) as needed from code to interact with the database. You don't need those objects. An excellent example is embedding a SqlDataSource into a .ASPX page. You shouldn't try to hide your data from anyone. Developers need to understand exactly how and when they are interacting with the physical data store. Object-relational mappers are the devil. Stop using them. Building enterprise applications is often an exercise in managing complexity. You have to keep things as simple as possible, or you will have an absolutely un-maintainable system. If you are willing to allow some coupling (which is inherent in any application anyway), you can do away with both your business logic layer and your data access layer (replacing them with stored procedures), and you won't need any of those interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/9240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How print Flex components in FireFox3? Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX. They print fine in IE7, even IE6. We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it. We've found a potential workaround, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough). Anyone know a workaround? A: Using the ACPrintManager I was able to get firefox 3 to print perfectly! The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null. private function initPrint():void { //if we don't have a stage, wait until the next frame and try again if ( stage == null ) { callLater(initPrint); return; } PrintManager.init(stage); var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight); data.draw(myDataGrid); PrintManager.setPrintableContent(data); } A: Thanks. A load of callLater-s added to our custom chart code seems to have done it.
{ "language": "en", "url": "https://stackoverflow.com/questions/9256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to find untracked files in a Perforce tree? (analogue of svn status) Anybody have a script or alias to find untracked (really: unadded) files in a Perforce tree? EDIT: I updated the accepted answer on this one since it looks like P4V added support for this in the January 2009 release. A: EDIT: Please use p4 status now. There is no need for jumping through hoops anymore. See @ColonelPanic's answer. In the Jan 2009 version of P4V, you can right-click on any folder in your workspace tree and click "reconcile offline work..." This will do a little processing then bring up a split-tree view of files that are not checked out but have differences from the depot version, or not checked in at all. There may even be a few other categories it brings up. You can right-click on files in this view and check them out, add them, or even revert them. It's a very handy tool that's saved my ass a few times. EDIT: ah the question asked about scripts specifically, but I'll leave this answer here just in case. A: 2021-07-16: THIS ANSWER MAY BE OBSOLETE. I am reasonably sure that it was accurate in 2016, for whatever version of Perforce I was using them (which was not necessarily the most current). But it seems that this problem or design limitation has been remedied in subsequent releases of Perforce. I do not know what the stack overflow etiquette for this is -- should this answer be removed? 2016 ANSWER I feel impelled to add an answer, since the accepted answer, and some of the others, have what I think is a significant problem: they do not understand the difference between a read-only query command, and a command that makes changes. I don't expect any credit for this answer, but I hope that it will help others avoid wasting time and making mistakes by following the accepted but IMHO incorrect answer. ---+ BRIEF Probably the most convenient way to find all untracked files in a perforce workspace is p4 reconcile -na. -a says "give me files that are not in the repository, i.e. that should be added". -n says "make no changes" - i.e. a dry-run. (Although the messages may say "opened for add", mentally you must interpret that as "would be opened for add if not -n") Probably the most convenient way to find all local changes made while offline - not just files that might need to be added, but also files that might need to be deleted, or which have been changed without being opened for editing via p4 edit, is p4 reconcile -n. Several answers provided scripts, often involving p4 fstat. While I have not verified all of those scripts, I often use similar scripts to make up for the deficiencies of perforce commands such as p4 reconcile -n - e.g. often I find that I want local paths rather than Perforce depot paths or workspace paths. ---+ WARNING p4 status is NOT the counterpart to the status commands on other version control systems. p4 status is NOT a read-only query. p4 status actually finds the same sort of changes that p4 reconcile does, and adds them to the repository. p4 status does not seem to have a -n dry-run option like p4 reconcile does. If you do p4 status, look at the files and think "Oh, I don't need those", then you will have to p4 revert them if you want to continue editing in the same workspace. Or else the changes that p4 status added to your changeset will be checked in the next time. There seems to be little or no reason to use p4 status rather than p4 reconcile -n, except for some details of local workspace vs depot pathname. I can only imagine that whoever chose 'status' for a non-read-only command had limited command of the English language and other version control tools. ---+ P4V GUI In the GUI p4v, the reconcile command finds local changes that may need to be added, deleted, or opened for editing. Fortunately it does not add them to a changelist by default; but you still may want to be careful to close the reconcile window after inspecting it, if you don't want to commit the changes. A: On linux, or if you have gnu-tools installed on windows: find . -type f -print0 | xargs -0 p4 fstat >/dev/null This will show an error message for every unaccounted file. If you want to capture that output: find . -type f -print0 | xargs -0 p4 fstat >/dev/null 2>mylogfile A: Alternatively from P4Win, use the ""Local Files not in Depot" option on the left hand view panel. I don't use P4V much, but I think the equivalent is to select "Hide Local Workspace Files" in the filter dropdown of the Workspace view tab.p4 help fstat In P4V 2015.1 you'll find these options under the filter button like this: A: I use the following in my tool that backs up any files in the workspace that differ from the repository (for Windows). It handles some odd cases that Perforce doesn't like much, like embedded blanks, stars, percents, and hashmarks: dir /S /B /A-D | sed -e "s/%/%25/g" -e "s/@/%40/g" -e "s/#/%23/g" -e "s/\*/%2A/g" | p4 -x- have 1>NUL: "dir /S /B /A-D" lists all files at or below this folder (/S) in "bare" format (/B) excluding directories (/A-D). The "sed" changes dangerous characters to their "%xx" form (a la HTML), and the "p4 have" command checks this list ("-x-") against the server discarding anything about files it actually locates in the repository ("1>NUL:"). The result is a bunch of lines like: Z:\No_Backup\Workspaces\full\depot\Projects\Archerfish\Portal\Main\admin\html\images\nav\navxx_background.gif - file(s) not on client. Et voilà! A: Quick 'n Dirty: In p4v right-click on the folder in question and add all files underneath it to a new changelist. The changelist will now contain all files which are not currently part of the depot. A: Under Unix: find -type f ! -name '*~' -print0| xargs -0 p4 fstat 2>&1|awk '/no such file/{print $1}' This will print out a list of files that are not added in your client or the Perforce depot. I've used ! -name '*~' to exclude files ending with ~. A: Ahh, one of the Perforce classics :) Yes, it really sucks that there is STILL no easy way for this built into the default commands. The easiest way is to run a command to find all files under your clients root, and then attempt to add them to the depot. You'll end up with a changelist of all new files and existing files are ignored. E.g dir /s /b /A-D | p4 -x - add (use 'find . -type f -print' from a nix command line). If you want a physical list (in the console or file) then you can pipe on the results of a diff (or add if you also want them in a changelist). If you're running this within P4Win you can use $r to substitute the client root of the current workspace. A: Is there an analogue of svn status or git status? Yes, BUT. As of Perforce version 2012.1, there's the command p4 status and in P4V 'reconcile offline work'. However, they're both very slow. To exclude irrelevant files you'll need to write a p4ignore.txt file per https://stackoverflow.com/a/13126496/284795 A: The following commands produce status-like output, but none is quite equivalent to svn status or git status, providing a one-line summary of the status of each file: * *p4 status *p4 opened *p4 diff -ds A: I don't have enough reputation points to comment, but Ross' solution also lists files that are open for add. You probably do not want to use his answer to clean your workspace. The following uses p4 fstat (thanks Mark Harrison) instead of p4 have, and lists the files that aren't in the depot and aren't open for add. dir /S /B /A-D | sed -e "s/%/%25/g" -e "s/@/%40/g" -e "s/#/%23/g" -e "s/\*/%2A/g" | p4 -x- fstat 2>&1 | sed -n -e "s/ - no such file[(]s[)]\.$//gp" ===Jac A: Fast method, but little orthodox. If the codebase doesn't add new files / change view too often, you could create a local 'git' repository out of your checkout. From a clean perforce sync, git init, add and commit all files locally. Git status is fast and will show files not previously committed. A: The p4 fstat command lets you test if a file exists in the workspace, combine with find to locate files to check as in the following Perl example: // throw the output of p4 fstat to a 'output file' // find: // -type f :- only look at files, // -print0 :- terminate strings with \0s to support filenames with spaces // xargs: // Groups its input into command lines, // -0 :- read input strings terminated with \0s // p4: // fstat :- fetch workspace stat on files my $status=system "(find . -type f -print0 | xargs -0 p4 fstat > /dev/null) >& $outputFile"; // read output file open F1, $outputFile or die "$!\n"; // iterate over all the lines in F1 while (<F1>) { // remove trailing whitespace chomp $_; // grep lines which has 'no such file' or 'not in client' if($_ =~ m/no such file/ || $_ =~ m/not in client/){ // Remove the content after '-' $_=~ s/-\s.*//g; // below line is optional. Check ur output file for more clarity. $_=~ s/^.\///g; print "$_\n"; } } close F1; Or you can use p4 reconcile -n -m ... If it is 'opened for delete' then it has been removed from the workspace. Note that the above command is running in preview mode (-n). A: I needed something that would work in either Linux, Mac or Windows. So I wrote a Python script for it. The basic idea is to iterate through files and execute p4 fstat on each. (of course ignoring dependencies and tmp folders) You can find it here: https://gist.github.com/givanse/8c69f55f8243733702cf7bcb0e9290a9 A: This command can give you a list of files that needs to be added, edited or removed: p4 status -aed ... you can use them separately too p4 status -a ... p4 status -e ... p4 status -d ... A: In P4V, under the "View" menu item choose "Files in Folder" which brings up a new tab in the right pane. To the far right of the tabs there is a little icon that brings up a window called "Files in Folder" with 2 icons. Select the left icon that looks like a funnel and you will see several options. Choose "Show items not in Depot" and all the files in the folder will show up. Then just right-click on the file you want to add and choose "Mark for Add...". You can verify it is there in the "Pending" tab. Just submit as normal (Ctrl+S).
{ "language": "en", "url": "https://stackoverflow.com/questions/9272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "93" }
Q: Using Parameters in MS Reporting Services (SQL Server 2008) against an ODBC data source I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the @parmName I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible? I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server. A: It sounds like you'll need to treat the SQL Statement as an expression. For example: ="Select col1, col2 from table 1 Where col3 = " & Parameters!Param1.Value If the where clause is a string you would need to do the following: ="Select col1, col2 from table 1 Where col3 = '" & Parameters!Param1.Value & "'" Important: Do not use line breaks in your SQL expression. If you do you will get an error. Holla back if you need any more assistance. A: Doesn't ODBC use the old "?" syntax for parameters? Try this: select col1, col2 from table1 where col3 = ? The order of your parameters becomes important then, but it's less vulnerable to SQL injection than simply appending the parameter value. A: Encountered same problem trying to query an access database via ODBC. My original query: SELECT A.1 FROM A WHERE A.1 = @parameter resulted in error. Altered to: SELECT A.1 FROM A WHERE A.1 = ?. You then have to map the query parameter with your report parameter. A: I am a bit confused about this question, if you are looking for simple parameter usage then the notation is :*paramName* , however if you want to structurally change the WHERE clause (as you might in sql+ using ?) then you should really be using custom code within the report to define a function that returns the required sql for the query. Unfortunately, when using custom code, parameters cannot be referenced directly in the generated query but have to have there values concatenated into the resultant String, thus introducing the potential for SQL injection.
{ "language": "en", "url": "https://stackoverflow.com/questions/9275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Keep Remote Directory Up-to-date I absolutely love the Keep Remote Directory Up-to-date feature in Winscp. Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can theoretically be accomplished using changedfiles or rsync, but I've always found the tutorials for both tools to be lacking and/or contradictory. I basically just need a tool that works in OSX or Linux and keeps a remote directory in sync (mirrored) with a local directory while I make changes to the local directory. Update Looking through the solutions, I see a couple which solve the general problem of keeping a remote directory in sync with a local directory manually. I know that I can set a cron task to run rsync every minute, and this should be fairly close to real time. This is not the exact solution I was looking for as winscp does this and more: it detects file changes in a directory (while I work on them) and then automatically pushes the changes to the remote server. I know this is not the best solution (no code repository), but it allows me to very quickly test code on a server while I develop it. Does anyone know how to combine rsync with any other commands to get this functionality? A: What you want to do for linux remote access is use 'sshfs' - the SSH File System. # sshfs username@host:path/to/directory local_dir Then treat it like an network mount, which it is... A bit more detail, like how to set it up so you can do this as a regular user, on my blog If you want the asynchronous behavior of winSCP, you'll want to use rsync combined with something that executes it periodically. The cron solution above works, but may be overkill for the winscp use case. The following command will execute rsync every 5 seconds to push content to the remote host. You can adjust the sleep time as needed to reduce server load. # while true; do rsync -avrz localdir user@host:path; sleep 5; done If you have a very large directory structure and need to reduce the overhead of the polling, you can use 'find': # touch -d 01/01/1970 last; while true; do if [ "`find localdir -newer last -print -quit`" ]; then touch last; rsync -avrz localdir user@host:path; else echo -ne .; fi; sleep 5; done And I said cron may be overkill? But at least this is all just done from the command line, and can be stopped via a ctrl-C. kb A: lsyncd seems to be the perfect solution. it combines inotify (kernel builtin function which watches for file changes in a directory trees) and rsync (cross platform file-syncing-tool). lsyncd -rsyncssh /home remotehost.org backup-home/ Quote from github: Lsyncd watches a local directory trees event monitor interface (inotify or fsevents). It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes. By default this is rsync. Lsyncd is thus a light-weight live mirror solution that is comparatively easy to install not requiring new filesystems or blockdevices and does not hamper local filesystem performance. A: To detect changed files, you could try fam (file alteration monitor) or inotify. The latter is linux-specific, fam has a bsd port which might work on OS X. Both have userspace tools that could be used in a script together with rsync. A: I have the same issue. I loved winscp "keep remote directory up to date" command. However, in my quest to rid myself of Windows, I lost winscp. I did write a script that uses fileschanged and rsync to do something similar much closer to real time. How to use: * *Make sure you have fileschanged installed *Save this script in /usr/local/bin/livesync or somewhere reachable in your $PATH and make it executable *Use Nautilus to connect to the remote host (sftp or ftp) *Run this script by doing livesync SOURCE DEST *The DEST directory will be in /home/[username]/.gvfs/[path to ftp scp or whatever] A Couple downsides: * *It is slower than winscp (my guess is because it goes through Nautilus and has to detect changes through rsync as well) *You have to manually create the destination directory if it doesn't already exist. So if you're adding a directory, it won't detect and create the directory on the DEST side. *Probably more that I haven't noticed yet *Also, do not attempt to synchronize a SRC directory named "rsyncThis". That will probably not be good :) #!/bin/sh upload_files() { if [ "$HOMEDIR" = "." ] then HOMEDIR=`pwd` fi while read input do SYNCFILE=${input#$HOMEDIR} echo -n "Sync File: $SYNCFILE..." rsync -Cvz --temp-dir="$REMOTEDIR" "$HOMEDIR/$SYNCFILE" "$REMOTEDIR/$SYNCFILE" > /dev/null echo "Done." done } help() { echo "Live rsync copy from one directory to another. This will overwrite the existing files on DEST." echo "Usage: $0 SOURCE DEST" } case "$1" in rsyncThis) HOMEDIR=$2 REMOTEDIR=$3 echo "HOMEDIR=$HOMEDIR" echo "REMOTEDIR=$REMOTEDIR" upload_files ;; help) help ;; *) if [ -n "$1" ] && [ -n "$2" ] then fileschanged -r "$1" | "$0" rsyncThis "$1" "$2" else help fi ;; esac A: You could always use version control, like SVN, so all you have to do is have the server run svn up on a folder every night. This runs into security issues if you are sharing your files publicly, but it works. If you are using Linux though, learn to use rsync. It's really not that difficult as you can test every command with -n. Go through the man page, the basic format you will want is rsync [OPTION...] SRC... [USER@]HOST:DEST the command I run from my school server to my home backup machine is this rsync -avi --delete ~ me@homeserv:~/School/ >> BackupLog.txt This takes all of the files in my home directory (~) and uses rsync's archive mode (-a), verbosly (-v), lists all of the changes made (-i), while deleting any files that don't exist anymore (--delete) and puts the in the Folder /home/me/School/ on my remote server. All of the information it prints out (what was copied, what was deleted, etc.) is also appended to the file BackupLog.txt I know that's a whirlwind tour of rsync, but I hope it helps. A: The rsync solutions are really good, especially if you're only pushing changes one way. Another great tool is unison -- it attempts to syncronize changes in both directions. Read more at the Unison homepage. A: Great question I have searched answer for hours ! I have tested lsyncd and the problem is that the default delay is far too long and no example command line give the -delay option. Other problem is that by default rsync ask password each time ! Solution with lsyncd : lsyncd --nodaemon -rsyncssh local_dir remote_user@remote_host remote_dir -delay .2 other way is to use inotify-wait in a script : while inotifywait -r -e modify,create,delete local_dir ; do # if you need you can add wait here rsync -avz local_dir remote_user@remote_host:remote_dir done For this second solution you will have to install inotify-tools package To suppress the need to enter password at each change, simply use ssh-keygen : https://superuser.com/a/555800/510714 A: How "real-time" do you want the syncing? I would still lean toward rsync since you know it is going to be fully supported on both platforms (Windows, too, with cygwin) and you can run it via a cron job. I have a super-simple bash file that I run on my system (this does not remove old files): #!/bin/sh rsync -avrz --progress --exclude-from .rsync_exclude_remote . remote_login@remote_computer:remote_dir # options # -a archive # -v verbose # -r recursive # -z compress Your best bet is to set it up and try it out. The -n (--dry-run) option is your friend! Keep in mind that rsync (at least in cygwin) does not support unicode file names (as of 16 Aug 2008). A: It seems like perhaps you're solving the wrong problem. If you're trying to edit files on a remote computer then you might try using something like the ftp plugin for jedit. http://plugins.jedit.org/plugins/?FTP This ensures that you have only one version of the file so it can't ever be out of sync. A: Building off of icco's suggestion of SVN, I'd actually suggest that if you are using subversion or similar for source control (and if you aren't, you should probably start) you can keep the production environment up to date by putting the command to update the repository into the post-commit hook. There are a lot of variables in how you'd want to do that, but what I've seen work is have the development or live site be a working copy and then have the post-commit use an ssh key with a forced command to log into the remote site and trigger an svn up on the working copy. Alternatively in the post-commit hook you could trigger an svn export on the remote machine, or a local (to the svn repository) svn export and then an rsync to the remote machine. I would be worried about things that detect changes and push them, and I'd even be worried about things that ran every minute, just because of race conditions. How do you know it's not going to transfer the file at the very same instant it's being written to? Stumble across that once or twice and you'll lose all of the time-saving advantage you had by constantly rsyncing or similar. A: Will DropBox (http://www.getdropbox.com/) do what you want? A: I used to have the same setup under Windows as you, that is a local filetree (versioned) and a test environment on a remote server, which I kept mirrored in realtime with WinSCP. When I switched to Mac I had to do quite some digging before I was happy, but finally ended up using: * *SmartSVN as my subversion client *Sublime Text 2 as my editor (already used it on Windows) *SFTP-plugin to ST2 which handles the uploading on save (sorry, can't post more than 2 links) I can really recommend this setup, hope it helps! A: User watcher.py and rsync to automate this. Read the following step by step instructions here: http://kushellig.de/linux-file-auto-sync-directories/ A: I have been using WinSCP on Wine for a few years now and it works fine for the syncing operations you mention. Here are some instructions I posted to Github on how to setup via wine: WinSCP_On_Wine Just be aware that WinSCP is not being actively tested on wine so there may be some quirky issues. however, I use it daily on Ubuntu 20.04 for all my devops and have never lost a file and rarely experience any of such quirks. A: You can also use Fetch as an SFTP client, and then edit files directly on the server from within that. There are also SSHFS (mount an ssh folder as a Volume) options. This is in line with what stimms said - are you sure you want stuff kept in sync, or just want to edit files on the server? OS X has it's own file notifications system - this is what Spotlight is based upon. I haven't heard of any program that uses this to then keep things in sync, but it's certainly conceivable. I personally use RCS for this type of thing:- whilst it's got a manual aspect, it's unlikely I want to push something to even the test server from my dev machine without testing it first. And if I am working on a development server, then I use one of the options given above. A: Well, I had the same kind of problem and it is possible using these together: rsync, SSH Passwordless Login, Watchdog (a Python sync utility) and Terminal Notifier (an OS X notification utility made with Ruby. Not needed, but helps to know when the sync has finished). * *I created the key to Passwordless Login using this tutorial from Dreamhost wiki: http://cl.ly/MIw5 1.1. When you finish, test if everything is ok… if you can't Passwordless Login, maybe you have to try afp mount. Dreamhost (where my site is) does not allow afp mount, but allows Passwordless Login. In terminal, type: ssh username@host.com You should login without passwords being asked :P *I installed the Terminal Notifier from the Github page: http://cl.ly/MJ5x 2.1. I used the Gem installer command. In Terminal, type: gem install terminal-notifier 2.3. Test if the notification works.In Terminal, type: terminal-notifier -message "Starting sync" *Create a sh script to test the rsync + notification. Save it anywhere you like, with the name you like. In this example, I'll call it ~/Scripts/sync.sh I used the ".sh extension, but I don't know if its needed. #!/bin/bash terminal-notifier -message "Starting sync" rsync -azP ~/Sites/folder/ user@host.com:site_folder/ terminal-notifier -message "Sync has finished" 3.1. Remember to give execution permission to this sh script. In Terminal, type: sudo chmod 777 ~/Scripts/sync.sh 3.2. Run the script and verify if the messages are displayed correctly and the rsync actually sync your local folder with the remote folder. *Finally, I downloaded and installed Watchdog from the Github page: http://cl.ly/MJfb 4.1. First, I installed the libyaml dependency using Brew (there are lot's of help how to install Brew - like an "aptitude" for OS X). In Terminal, type: brew install libyaml 4.2. Then, I used the "easy_install command". Go the folder of Watchdog, and type in Terminal: easy_install watchdog *Now, everything is installed! Go the folder you want to be synced, change this code to your needs, and type in Terminal: watchmedo shell-command --patterns="*.php;*.txt;*.js;*.css" \ --recursive \ --command='~/Scripts/Sync.sh' \ . It has to be EXACTLY this way, with the slashes and line breaks, so you'll have to copy these lines to a text editor, change the script, paste in terminal and press return. I tried without the line breaks, and it doesn't work! In my Mac, I always get an error, but it doesn't seem to affect anything: /Library/Python/2.7/site-packages/argh-0.22.0-py2.7.egg/argh/completion.py:84: UserWarning: Bash completion not available. Install argcomplete. Now, made some changes in a file inside the folder, and watch the magic! A: I'm using this little Ruby-Script: #!/usr/bin/env ruby #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Rsyncs 2Folders # # watchAndSync by Mike Mitterer, 2014 <http://www.MikeMitterer.at> # with credit to Brett Terpstra <http://brettterpstra.com> # and Carlo Zottmann <https://github.com/carlo/haml-sass-file-watcher> # Found link on: http://brettterpstra.com/2011/03/07/watch-for-file-changes-and-refresh-your-browser-automatically/ # trap("SIGINT") { exit } if ARGV.length < 2 puts "Usage: #{$0} watch_folder sync_folder" puts "Example: #{$0} web keepInSync" exit end dev_extension = 'dev' filetypes = ['css','html','htm','less','js', 'dart'] watch_folder = ARGV[0] sync_folder = ARGV[1] puts "Watching #{watch_folder} and subfolders for changes in project files..." puts "Syncing with #{sync_folder}..." while true do files = [] filetypes.each {|type| files += Dir.glob( File.join( watch_folder, "**", "*.#{type}" ) ) } new_hash = files.collect {|f| [ f, File.stat(f).mtime.to_i ] } hash ||= new_hash diff_hash = new_hash - hash unless diff_hash.empty? hash = new_hash diff_hash.each do |df| puts "Detected change in #{df[0]}, syncing..." system("rsync -avzh #{watch_folder} #{sync_folder}") end end sleep 1 end Adapt it for your needs! A: If you are developing python on remote server, Pycharm may be a good choice to you. You can synchronize your remote files with your local files utilizing pycharm remote development feature. The guide link as: https://www.jetbrains.com/help/pycharm/creating-a-remote-server-configuration.html
{ "language": "en", "url": "https://stackoverflow.com/questions/9279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Removing elements with Array.map in JavaScript I would like to filter an array of items by using the map() function. Here is a code snippet: var filteredItems = items.map(function(item) { if( ...some condition... ) { return item; } }); The problem is that filtered out items still uses space in the array and I would like to completely wipe them out. Any idea? EDIT: Thanks, I forgot about filter(), what I wanted is actually a filter() then a map(). EDIT2: Thanks for pointing that map() and filter() are not implemented in all browsers, although my specific code was not intended to run in a browser. A: Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend checking that out if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations. That said, **The tl;dr is this: To accomplish what you're asking for (filtering and mapping within one function call), you would use Array.reduce()**. However, the more readable and (less importantly) usually significantly faster2 approach is to just use filter and map chained together: [1,2,3].filter(num => num > 2).map(num => num * 2) What follows is a description of how Array.reduce() works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression. You give reduce an argument that is a (usually anonymous) function. That anonymous function takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is the value that will be passed along between function calls, often referred to as the memo. Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for 'memo' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then 'memo' in the first anonymous function call will by default be the first iteratee, and the 'iteratee' argument will actually be the second value in the array) In our case, we'll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process. Finally, we'll return our 'array in progress' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call. This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript. For a more complete explanation, refer to MDN docs (or to my post referenced at the beginning of this answer). Basic example of a Reduce call: let array = [1,2,3]; const initialMemo = []; array = array.reduce((memo, iteratee) => { // if condition is our filter if (iteratee > 1) { // what happens inside the filter is the map memo.push(iteratee * 2); } // this return value will be passed in as the 'memo' argument // to the next call of this function, and this function will have // every element passed into it at some point. return memo; }, initialMemo) console.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)] more succinct version: [1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, []) Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as 'memo' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the 'memo' argument to the next function. Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example: [7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val) // ^this would return the largest number in the list. An example of how to write your own reduce function (this often helps understanding functions like these, I find): test_arr = []; // we accept an anonymous function, and an optional 'initial memo' value. test_arr.my_reducer = function(reduceFunc, initialMemo) { // if we did not pass in a second argument, then our first memo value // will be whatever is in index zero. (Otherwise, it will // be that second argument.) const initialMemoIsIndexZero = arguments.length < 2; // here we use that logic to set the memo value accordingly. let memo = initialMemoIsIndexZero ? this[0] : initialMemo; // here we use that same boolean to decide whether the first // value we pass in as iteratee is either the first or second // element const initialIteratee = initialMemoIsIndexZero ? 1 : 0; for (var i = initialIteratee; i < this.length; i++) { // memo is either the argument passed in above, or the // first item in the list. initialIteratee is either the // first item in the list, or the second item in the list. memo = reduceFunc(memo, this[i]); // or, more technically complete, give access to base array // and index to the reducer as well: // memo = reduceFunc(memo, this[i], i, this); } // after we've compressed the array into a single value, // we return it. return memo; } The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it. A: Array Filter method var arr = [1, 2, 3] // ES5 syntax arr = arr.filter(function(item){ return item != 3 }) // ES2015 syntax arr = arr.filter(item => item != 3) console.log( arr ) A: That's not what map does. You really want Array.filter. Or if you really want to remove the elements from the original list, you're going to need to do it imperatively with a for loop. A: You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering. eg. var filteredItems = items.filter(function(item) { return ...some condition...; }); [Edit: Of course you could always do sourceArray.filter(...).map(...) to both filter and mutate] A: You must note however that the Array.filter is not supported in all browser so, you must to prototyped: //This prototype is provided by the Mozilla foundation and //is distributed under the MIT license. //http://www.ibiblio.org/pub/Linux/LICENSES/mit.license if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } And doing so, you can prototype any method you may need. A: TLDR: Use map (returning undefined when needed) and then filter. First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function flatMap but then renamed it to compactMap. For example, if we don't have a compactMap function, we might end up with computation defined twice: let array = [1, 2, 3, 4, 5, 6, 7, 8]; let mapped = array .filter(x => { let computation = x / 2 + 1; let isIncluded = computation % 2 === 0; return isIncluded; }) .map(x => { let computation = x / 2 + 1; return `${x} is included because ${computation} is even` }) // Output: [2 is included because 2 is even, 6 is included because 4 is even] Thus compactMap would be useful to reduce duplicate code. A really simple way to do something similar to compactMap is to: * *Map on real values or undefined. *Filter out all the undefined values. This of course relies on you never needing to return undefined values as part of your original map function. Example: let array = [1, 2, 3, 4, 5, 6, 7, 8]; let mapped = array .map(x => { let computation = x / 2 + 1; let isIncluded = computation % 2 === 0; if (isIncluded) { return `${x} is included because ${computation} is even` } else { return undefined } }) .filter(x => typeof x !== "undefined") A: following statement cleans object using map function. var arraytoclean = [{v:65, toberemoved:"gronf"}, {v:12, toberemoved:null}, {v:4}]; arraytoclean.map((x,i)=>x.toberemoved=undefined); console.dir(arraytoclean); A: I just wrote array intersection that correctly handles also duplicates https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0 // array intersection that correctly handles also duplicates const intersection = (a1, a2) => { const cnt = new Map(); a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1); return a1.filter(el => el in cnt && 0 < cnt[el]--); }; const l = console.log; l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ] l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ] l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ] l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ] A: First you can use map and with chaining you can use filter state.map(item => { if(item.id === action.item.id){ return { id : action.item.id, name : item.name, price: item.price, quantity : item.quantity-1 } }else{ return item; } }).filter(item => { if(item.quantity <= 0){ return false; }else{ return true; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/9289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: onClick doesn't fire with only one input when pressing enter I'm having trouble with events in Internet Explorer 7. When I have a form with two or more input[type=text] and I press enter, the events occurs in this order: * *submit button (onClick) *form (onSubmit) Sample code: <form onSubmit="{alert('form::onSubmit'); return false;}"> <input type="text"> <input type="text"> <input type="submit" onClick="{alert('button::onClick');}"> </form> If I have only one input[type=text] and I press enter the submit button onClick event doesn't fire. Sample code: <form onSubmit="{alert('form::onSubmit'); return false;}"> <input type="text"> <input type="submit" onClick="{alert('button::onClick');}"> </form> A: The button's onclick should (I think) only fire if the button is actually clicked (or when the focus is on it and the user clicks enter), unless you've added logic to change that. Is the addition of the extra textbox possibly changing the tab order of your elements (perhaps making the button the default control in that case)? A: From the dawn of browsers, a single input field in a form would submit on enter with or without a submit button. This was to make it simpler for people to search a site from a single search field. If you need to execute some javascript in a form, it is safer practice to use the onsubmit of the form (and return false to stop submission) rather than executing script in the onClick of the submit button. If you need to execute javascript from a button, use type="button" instead of type="submit" - hope this clarified what I meant A: If you want code to run when the user presses enter, just use the onSubmit handler. If you want code to run when the user presses the button, and not when the user presses enter, use a button other than type="submit". A: Interestingly, if you click on the screen (remove the focus from the textbox) on second example with only one textbox, the event onClick fires... So it's not an expected behaviour since it only occurs when you have just one textbox and you have the focus on the textbox. I'm afraid you've found a bug on the browser and you'll have to find a workaround, or avoid using the onClick event in that case. I use the onSubmit event for validations because it's a "safer" event that is more likely to work on different browsers and situations. A: Out of curiosity, are you using a DOCTYPE, and if so, which one? I'm not saying incompatabilities with the DOCTYPE are the issue, but quirks mode is something to rule out before trying anything else. A: You might want to include a dummy hidden input element to recreate the situation where you had two input elements... that way, you'll get both of the events fired <FORM onSubmit="{alert('form::onSubmit'); return false;}"> <INPUT TYPE="text"> <input type="hidden" name="dummy"> <INPUT TYPE="submit" onClick="{alert('buttom::onClick');}"> </FORM> IE has a lot of confusing fixes that needs to be done for improving compatibility of our code
{ "language": "en", "url": "https://stackoverflow.com/questions/9301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you retrieve selected text using Regex in C#? How do you retrieve selected text using Regex in C#? I am looking for C# code that is equivalent to this Perl code: $indexVal = 0; if($string =~ /Index: (\d*)/){$indexVal = $1;} A: int indexVal = 0; Regex re = new Regex(@"Index: (\d*)") Match m = re.Match(s) if(m.Success) indexVal = int.TryParse(m.Groups[1].toString()); I might have the group number wrong, but you should be able to figure it out from here. A: I think Patrick nailed this one -- my only suggestion is to remember that named regex groups exist, too, so you don't have to use array index numbers. Regex.Match(s, @"Index (?<num>\d*)").Groups["num"].Value I find the regex is a bit more readable this way as well, though opinions vary... A: You'll want to utilize the matched groups, so something like... Regex MagicRegex = new Regex(RegexExpressionString); Match RegexMatch; string CapturedResults; RegexMatch = MagicRegex.Match(SourceDataString); CapturedResults = RegexMatch.Groups[1].Value; A: That would be int indexVal = 0; Regex re = new Regex(@"Index: (\d*)"); Match m = re.Match(s); if (m.Success) indexVal = m.Groups[1].Index; You can also name you group (here I've also skipped compilation of the regexp) int indexVal = 0; Match m2 = Regex.Match(s, @"Index: (?<myIndex>\d*)"); if (m2.Success) indexVal = m2.Groups["myIndex"].Index; A: int indexVal = 0; Regex re = new Regex.Match(s, @"(<?=Index: )(\d*)"); if(re.Success) { indexVal = Convert.ToInt32(re.Value); }
{ "language": "en", "url": "https://stackoverflow.com/questions/9303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: C# 3.0 auto-properties — useful or not? Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language. I am used to create my properties in C# using a private and a public field: private string title; public string Title { get { return title; } set { title = value; } } Now, with .NET 3.0, we got auto-properties: public string Title { get; set; } I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic. In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway. I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code. So, what am I missing here? Why would anyone actually want to use auto-properties? A: Auto-properties are as much a black magic as anything else in C#. Once you think about it in terms of compiling down to IL rather than it being expanded to a normal C# property first it's a lot less black magic than a lot of other language constructs. A: Yes, it does just save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal. You can set different scopes: public string PropertyName { get; private set; } So that the property can only be changed inside the class. This isn't really immutable as you can still access the private setter through reflection. As of C#6 you can also create true readonly properties - i.e. immutable properties that cannot be changed outside of the constructor: public string PropertyName { get; } public MyClass() { this.PropertyName = "whatever"; } At compile time that will become: readonly string pName; public string PropertyName { get { return this.pName; } } public MyClass() { this.pName = "whatever"; } In immutable classes with a lot of members this saves a lot of excess code. A: I use auto-properties all the time. Before C#3 I couldn't be bothered with all the typing and just used public variables instead. The only thing I miss is being able to do this: public string Name = "DefaultName"; You have to shift the defaults into your constructors with properties. tedious :-( A: I think any construct that is intuitive AND reduces the lines of code is a big plus. Those kinds of features are what makes languages like Ruby so powerful (that and dynamic features, which also help reduce excess code). Ruby has had this all along as: attr_accessor :my_property attr_reader :my_getter attr_writer :my_setter A: The three big downsides to using fields instead of properties are: * *You can't databind to a field whereas you can to a property *If you start off using a field, you can't later (easily) change them to a property *There are some attributes that you can add to a property that you can't add to a field A: I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, there's no problem to convert them to normal properties later on. As you said you could use fields, and if you wanted to add logic to them later you'd convert them to properties. But this might present problems with any use of reflection (and possibly elsewhere?). Also the properties allow you to set different access levels for the getter and setter which you can't do with a field. I guess it's the same as the var keyword. A matter of personal preference. A: From Bjarne Stroustrup, creator of C++: I particularly dislike classes with a lot of get and set functions. That is often an indication that it shouldn't have been a class in the first place. It's just a data structure. And if it really is a data structure, make it a data structure. And you know what? He's right. How often are you simply wrapping private fields in a get and set, without actually doing anything within the get/set, simply because it's the "object oriented" thing to do. This is Microsoft's solution to the problem; they're basically public fields that you can bind to. A: The only problem I have with them is that they don't go far enough. The same release of the compiler that added automatic properties, added partial methods. Why they didnt put the two together is beyond me. A simple "partial On<PropertyName>Changed" would have made these things really really useful. A: It's simple, it's short and if you want to create a real implementation inside the property's body somewhere down the line, it won't break your type's external interface. As simple as that. A: One thing nobody seems to have mentioned is how auto-properties are unfortunately not useful for immutable objects (usually immutable structs). Because for that you really should do: private readonly string title; public string Title { get { return this.title; } } (where the field is initialized in the constructor via a passed parameter, and then is read only.) So this has advantages over a simple get/private set autoproperty. A: We use them all the time in Stack Overflow. You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great. A: I always create properties instead of public fields because you can use properties in an interface definition, you can't use public fields in an interface definition. A: One thing to note here is that, to my understanding, this is just syntactic sugar on the C# 3.0 end, meaning that the IL generated by the compiler is the same. I agree about avoiding black magic, but all the same, fewer lines for the same thing is usually a good thing. A: In my opinion, you should always use auto-properties instead of public fields. That said, here's a compromise: Start off with an internal field using the naming convention you'd use for a property. When you first either * *need access to the field from outside its assembly, or *need to attach logic to a getter/setter Do this: * *rename the field *make it private *add a public property Your client code won't need to change. Someday, though, your system will grow and you'll decompose it into separate assemblies and multiple solutions. When that happens, any exposed fields will come back to haunt you because, as Jeff mentioned, changing a public field to a public property is a breaking API change. A: I use CodeRush, it's faster than auto-properties. To do this: private string title; public string Title { get { return title; } set { title = value; } } Requires eight keystrokes total. A: @Domenic : I don't get it.. can't you do this with auto-properties?: public string Title { get; } or public string Title { get; private set; } Is this what you are referring to? A: My biggest gripe with auto-properties is that they are designed to save time but I often find I have to expand them into full blown properties later. What VS2008 is missing is an Explode Auto-Property refactor. The fact we have an encapsulate field refactor makes the way I work quicker to just use public fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/9304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "157" }
Q: "Could not find type" error loading a form in the Windows Forms Designer I have a .NET 2.0 windows forms app, which makes heavy use of the ListView control. I've subclassed the ListView class into a templated SortableListView<T> class, so it can be a bit smarter about how it displays things, and sort itself. Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008. The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors: * *Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built. There is no stack trace or error line information available for this error * *The variable 'listViewImages' is either undeclared or was never assigned. At MyApp.Main.Designer.cs Line:XYZ Column:1 Call stack: at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement) The line of code in question is where it is actually added to the form, and is this.imagesTab.Controls.Add( this.listViewImages ); listViewImages is declared as private MyApp.Controls.SortableListView<Image> listViewImages; and is instantiated in the InitializeComponent method as follows: this.listViewImages = new MyApp.Controls.SortableListView<Image>(); As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the SortableListView class out to a seperate assembly so it can be compiled seperately, but this makes no difference. I have no idea where to go from here. Any help would be appreciated! A: when you added the listview, did you add it to the toolbox and then add it to the form? No, I just edited Main.Designer.cs and changed it from System.Windows.Forms.ListView to MyApp.Controls.SortableListView<Image> Suspecting it might have been due to the generics led me to actually finding a solution. For each class that I need to make a SortableListView for, I defined a 'stub class' like this class ImagesListView : SortableListView<Image> { } Then made the Main.Designer.cs file refer to these stub classes instead of the SortableListView. It now works, hooray! Thankfully I am able to do this because all my types are known up front, and I'm only using the SortableListView as a method of reducing duplicate code. A: I had this problem too, related to merging massive SVN changes (with conflicts) in the *.Designer.cs file. The solution was to just open up the design view graphically, edit a control (move it to the left then right) and resave the design. The *.Designer.cs file magically changed, and the warning went away on the next compilation. To be clear, you need to fix all of the code merge problems first. This is just a work around to force VS to reload them. A: I've had a problem like this (tho not the same) in the past where my control was in a different namespace to my form even tho it was in the same project. To fix it I had to add a using My.Other.Namespace; to the top of the designer generated code file. The annoying thing was it kept getting blown away when the designer regenerated the page. A: It happened to me because of x86 / x64 architecture. Since Visual Studio (the development tool itself) has no x64 version, it's not possible to load x64 control into GUI designer. The best approach for this might be tuning GUI under x86, and compile it for x64 when necessary. A: The assembly that contains MyApp.Controls.SortableListView isn't installed in the GAC by any chance is it? A: when you added the listview, did you add it to the toolbox and then add it to the form? A: Perhaps you forgot to add that: /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Release all resources used. /// </summary> /// <param name="disposing">true if managed resources should be removed otherwise; false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { // ... this.components = new System.ComponentModel.Container(); // Not necessarily, if You do not use // ... } A: I have had the same problem. After removing some of my own controls of the *.Designer.cs-File the problem was solved. After going back to the original code the problem still was solved. So it seems to be a problem with the Visual Sudio cache. At the moment I cannot reproduce this problem. If you have the problem try to emtpy the folder C:\Users\YOURNAME\AppData\Local\Microsoft\VisualStudio\VERSION\Designer\ShadowCache Did it work? A: I had something similar - a user control was referring to a remote serice (which I couldn't guarantee being available at design time). This post on MSDN suggested that I add if (this.DesignMode) return; to the Load function of the control, or in my case to the point before the WCF client was initialised. That did the trick. So private readonly Client _client = new Client(); becomes private Client _client; public new void Load() { if(DesignMode) return; _client = new Client(); } A: I had the same issue. In my case this issue was due to resource initialization. I moved the following code from InitializeComponent method to ctor(After calling InitializeComponent). After that this issue was resolved: this->resources = (gcnew System::ComponentModel::ComponentResourceManager(XXX::typeid)); A: In my case the problem was the folder's name of my project! Why I think this: I use SVN and in the 'trunk\SGIMovel' works perfectly. But in a branch folder named as 'OS#125\SGIMovel' I can't open the designer for a form that uses a custom control and works in the trunk folder. Just get off the # and works nice.
{ "language": "en", "url": "https://stackoverflow.com/questions/9314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }