Search Results

Search found 61 results on 3 pages for 'stathread'.

Page 1/3 | 1 2 3  | Next Page >

  • How to run unit tests in STAThread mode?

    - by Peter
    I would like to test an app that uses the Clipboard (WindowsForms) and I need the Clipboard in my Unittests also. In order to use it, it should run in STA mode, but since the NUnit Testfixture does not have a main method, I don't know where/how to annotate it... Thanks!

    Read the article

  • STAThread and Process output capture in c#

    - by alex
    Hi: This is a strange problem I encountered. I have an window application written in c# to do testing. It has a MDI parent form that is hosting a few children forms. One of the forms launch test cripts by creating processes and capture the scripts output to a text box. Another form open serial port and monitoring the status of the device I am working on(like a shell). If I ran both of them together, the output of the script seems only appear in the text box after the test is done. However, If I don't open the serial port form, the output of the script is captured in real time. Does anyone knows what's causing the problem? I notice the onDataReceived even handler for serial port form has a [STAThread] header to it. Will this cause the serial port thread having higher priority than other processes? Thanks in advance.

    Read the article

  • Using delegates in C# (Part 2)

    - by rajbk
    Part 1 of this post can be read here. We are now about to see the different syntaxes for invoking a delegate and some c# syntactic sugar which allows you to code faster. We have the following console application. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Operation op1 = new Operation(Division); 9: double result = op1.Invoke(10, 5); 10: 11: Console.WriteLine(result); 12: Console.ReadLine(); 13: } 14: 15: static double Division(double x, double y) { 16: return x / y; 17: } 18: } Line 1 defines a delegate type called Operation with input parameters (double x, double y) and a return type of double. On Line 8, we create an instance of this delegate and set the target to be a static method called Division (Line 15) On Line 9, we invoke the delegate (one entry in the invocation list). The program outputs 5 when run. The language provides shortcuts for creating a delegate and invoking it (see line 9 and 11). Line 9 is a syntactical shortcut for creating an instance of the Delegate. The C# compiler will infer on its own what the delegate type is and produces intermediate language that creates a new instance of that delegate. Line 11 uses a a syntactical shortcut for invoking the delegate by removing the Invoke method. The compiler sees the line and generates intermediate language which invokes the delegate. When this code is compiled, the generated IL will look exactly like the IL of the compiled code above. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //shortcut constructor syntax 9: Operation op1 = Division; 10: //shortcut invoke syntax 11: double result = op1(10, 2); 12: 13: Console.WriteLine(result); 14: Console.ReadLine(); 15: } 16: 17: static double Division(double x, double y) { 18: return x / y; 19: } 20: } C# 2.0 introduced Anonymous Methods. Anonymous methods avoid the need to create a separate method that contains the same signature as the delegate type. Instead you write the method body in-line. There is an interesting fact about Anonymous methods and closures which won’t be covered here. Use your favorite search engine ;-)We rewrite our code to use anonymous methods (see line 9): 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //Anonymous method 9: Operation op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } We could rewrite our delegate to be of a generic type like so (see line 2 and line 9). You will see why soon. 1: //Generic delegate 2: public delegate T Operation<T>(T x, T y); 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: Operation<double> op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } The .NET 3.5 framework introduced a whole set of predefined delegates for us including public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); Our code can be modified to use this delegate instead of the one we declared. Our delegate declaration has been removed and line 7 has been changed to use the Func delegate type. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //Func is a delegate defined in the .NET 3.5 framework 7: Func<double, double, double> op1 = delegate (double x, double y) { 8: return x / y; 9: }; 10: double result = op1(10, 2); 11: 12: Console.WriteLine(result); 13: Console.ReadLine(); 14: } 15: 16: static double Division(double x, double y) { 17: return x / y; 18: } 19: } .NET 3.5 also introduced lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. We change our code to use lambda expressions. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //lambda expression 7: Func<double, double, double> op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } C# 3.0 introduced the keyword var (implicitly typed local variable) where the type of the variable is inferred based on the type of the associated initializer expression. We can rewrite our code to use var as shown below (line 7).  The implicitly typed local variable op1 is inferred to be a delegate of type Func<double, double, double> at compile time. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //implicitly typed local variable 7: var op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } You have seen how we can write code in fewer lines by using a combination of the Func delegate type, implicitly typed local variables and lambda expressions.

    Read the article

  • How LINQ to Object statements work

    - by rajbk
    This post goes into detail as to now LINQ statements work when querying a collection of objects. This topic assumes you have an understanding of how generics, delegates, implicitly typed variables, lambda expressions, object/collection initializers, extension methods and the yield statement work. I would also recommend you read my previous two posts: Using Delegates in C# Part 1 Using Delegates in C# Part 2 We will start by writing some methods to filter a collection of data. Assume we have an Employee class like so: 1: public class Employee { 2: public int ID { get; set;} 3: public string FirstName { get; set;} 4: public string LastName {get; set;} 5: public string Country { get; set; } 6: } and a collection of employees like so: 1: var employees = new List<Employee> { 2: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 3: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 4: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 5: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }, 6: }; Filtering We wish to  find all employees that have an even ID. We could start off by writing a method that takes in a list of employees and returns a filtered list of employees with an even ID. 1: static List<Employee> GetEmployeesWithEvenID(List<Employee> employees) { 2: var filteredEmployees = new List<Employee>(); 3: foreach (Employee emp in employees) { 4: if (emp.ID % 2 == 0) { 5: filteredEmployees.Add(emp); 6: } 7: } 8: return filteredEmployees; 9: } The method can be rewritten to return an IEnumerable<Employee> using the yield return keyword. 1: static IEnumerable<Employee> GetEmployeesWithEvenID(IEnumerable<Employee> employees) { 2: foreach (Employee emp in employees) { 3: if (emp.ID % 2 == 0) { 4: yield return emp; 5: } 6: } 7: } We put these together in a console application. 1: using System; 2: using System.Collections.Generic; 3: //No System.Linq 4:  5: public class Program 6: { 7: [STAThread] 8: static void Main(string[] args) 9: { 10: var employees = new List<Employee> { 11: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 12: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 13: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 14: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }, 15: }; 16: var filteredEmployees = GetEmployeesWithEvenID(employees); 17:  18: foreach (Employee emp in filteredEmployees) { 19: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 20: emp.ID, emp.FirstName, emp.LastName, emp.Country); 21: } 22:  23: Console.ReadLine(); 24: } 25: 26: static IEnumerable<Employee> GetEmployeesWithEvenID(IEnumerable<Employee> employees) { 27: foreach (Employee emp in employees) { 28: if (emp.ID % 2 == 0) { 29: yield return emp; 30: } 31: } 32: } 33: } 34:  35: public class Employee { 36: public int ID { get; set;} 37: public string FirstName { get; set;} 38: public string LastName {get; set;} 39: public string Country { get; set; } 40: } Output: ID 2 First_Name Jim Last_Name Ashlock Country UK ID 4 First_Name Jill Last_Name Anderson Country AUS Our filtering method is too specific. Let us change it so that it is capable of doing different types of filtering and lets give our method the name Where ;-) We will add another parameter to our Where method. This additional parameter will be a delegate with the following declaration. public delegate bool Filter(Employee emp); The idea is that the delegate parameter in our Where method will point to a method that contains the logic to do our filtering thereby freeing our Where method from any dependency. The method is shown below: 1: static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) { 2: foreach (Employee emp in employees) { 3: if (filter(emp)) { 4: yield return emp; 5: } 6: } 7: } Making the change to our app, we create a new instance of the Filter delegate on line 14 with a target set to the method EmployeeHasEvenId. Running the code will produce the same output. 1: public delegate bool Filter(Employee emp); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: var employees = new List<Employee> { 9: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 10: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 11: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 12: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 13: }; 14: var filterDelegate = new Filter(EmployeeHasEvenId); 15: var filteredEmployees = Where(employees, filterDelegate); 16:  17: foreach (Employee emp in filteredEmployees) { 18: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 19: emp.ID, emp.FirstName, emp.LastName, emp.Country); 20: } 21: Console.ReadLine(); 22: } 23: 24: static bool EmployeeHasEvenId(Employee emp) { 25: return emp.ID % 2 == 0; 26: } 27: 28: static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) { 29: foreach (Employee emp in employees) { 30: if (filter(emp)) { 31: yield return emp; 32: } 33: } 34: } 35: } 36:  37: public class Employee { 38: public int ID { get; set;} 39: public string FirstName { get; set;} 40: public string LastName {get; set;} 41: public string Country { get; set; } 42: } Lets use lambda expressions to inline the contents of the EmployeeHasEvenId method in place of the method. The next code snippet shows this change (see line 15).  For brevity, the Employee class declaration has been skipped. 1: public delegate bool Filter(Employee emp); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: var employees = new List<Employee> { 9: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 10: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 11: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 12: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 13: }; 14: var filterDelegate = new Filter(EmployeeHasEvenId); 15: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 16:  17: foreach (Employee emp in filteredEmployees) { 18: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 19: emp.ID, emp.FirstName, emp.LastName, emp.Country); 20: } 21: Console.ReadLine(); 22: } 23: 24: static bool EmployeeHasEvenId(Employee emp) { 25: return emp.ID % 2 == 0; 26: } 27: 28: static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) { 29: foreach (Employee emp in employees) { 30: if (filter(emp)) { 31: yield return emp; 32: } 33: } 34: } 35: } 36:  The output displays the same two employees.  Our Where method is too restricted since it works with a collection of Employees only. Lets change it so that it works with any IEnumerable<T>. In addition, you may recall from my previous post,  that .NET 3.5 comes with a lot of predefined delegates including public delegate TResult Func<T, TResult>(T arg); We will get rid of our Filter delegate and use the one above instead. We apply these two changes to our code. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: var employees = new List<Employee> { 7: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 8: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 9: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 10: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 11: }; 12:  13: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 14:  15: foreach (Employee emp in filteredEmployees) { 16: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 17: emp.ID, emp.FirstName, emp.LastName, emp.Country); 18: } 19: Console.ReadLine(); 20: } 21: 22: static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) { 23: foreach (var x in source) { 24: if (filter(x)) { 25: yield return x; 26: } 27: } 28: } 29: } We have successfully implemented a way to filter any IEnumerable<T> based on a  filter criteria. Projection Now lets enumerate on the items in the IEnumerable<Employee> we got from the Where method and copy them into a new IEnumerable<EmployeeFormatted>. The EmployeeFormatted class will only have a FullName and ID property. 1: public class EmployeeFormatted { 2: public int ID { get; set; } 3: public string FullName {get; set;} 4: } We could “project” our existing IEnumerable<Employee> into a new collection of IEnumerable<EmployeeFormatted> with the help of a new method. We will call this method Select ;-) 1: static IEnumerable<EmployeeFormatted> Select(IEnumerable<Employee> employees) { 2: foreach (var emp in employees) { 3: yield return new EmployeeFormatted { 4: ID = emp.ID, 5: FullName = emp.LastName + ", " + emp.FirstName 6: }; 7: } 8: } The changes are applied to our app. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: var employees = new List<Employee> { 7: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 8: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 9: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 10: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 11: }; 12:  13: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 14: var formattedEmployees = Select(filteredEmployees); 15:  16: foreach (EmployeeFormatted emp in formattedEmployees) { 17: Console.WriteLine("ID {0} Full_Name {1}", 18: emp.ID, emp.FullName); 19: } 20: Console.ReadLine(); 21: } 22:  23: static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) { 24: foreach (var x in source) { 25: if (filter(x)) { 26: yield return x; 27: } 28: } 29: } 30: 31: static IEnumerable<EmployeeFormatted> Select(IEnumerable<Employee> employees) { 32: foreach (var emp in employees) { 33: yield return new EmployeeFormatted { 34: ID = emp.ID, 35: FullName = emp.LastName + ", " + emp.FirstName 36: }; 37: } 38: } 39: } 40:  41: public class Employee { 42: public int ID { get; set;} 43: public string FirstName { get; set;} 44: public string LastName {get; set;} 45: public string Country { get; set; } 46: } 47:  48: public class EmployeeFormatted { 49: public int ID { get; set; } 50: public string FullName {get; set;} 51: } Output: ID 2 Full_Name Ashlock, Jim ID 4 Full_Name Anderson, Jill We have successfully selected employees who have an even ID and then shaped our data with the help of the Select method so that the final result is an IEnumerable<EmployeeFormatted>.  Lets make our Select method more generic so that the user is given the freedom to shape what the output would look like. We can do this, like before, with lambda expressions. Our Select method is changed to accept a delegate as shown below. TSource will be the type of data that comes in and TResult will be the type the user chooses (shape of data) as returned from the selector delegate. 1:  2: static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector) { 3: foreach (var x in source) { 4: yield return selector(x); 5: } 6: } We see the new changes to our app. On line 15, we use lambda expression to specify the shape of the data. In this case the shape will be of type EmployeeFormatted. 1:  2: public class Program 3: { 4: [STAThread] 5: static void Main(string[] args) 6: { 7: var employees = new List<Employee> { 8: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 9: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 10: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 11: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 12: }; 13:  14: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 15: var formattedEmployees = Select(filteredEmployees, (emp) => 16: new EmployeeFormatted { 17: ID = emp.ID, 18: FullName = emp.LastName + ", " + emp.FirstName 19: }); 20:  21: foreach (EmployeeFormatted emp in formattedEmployees) { 22: Console.WriteLine("ID {0} Full_Name {1}", 23: emp.ID, emp.FullName); 24: } 25: Console.ReadLine(); 26: } 27: 28: static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) { 29: foreach (var x in source) { 30: if (filter(x)) { 31: yield return x; 32: } 33: } 34: } 35: 36: static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector) { 37: foreach (var x in source) { 38: yield return selector(x); 39: } 40: } 41: } The code outputs the same result as before. On line 14 we filter our data and on line 15 we project our data. What if we wanted to be more expressive and concise? We could combine both line 14 and 15 into one line as shown below. Assuming you had to perform several operations like this on our collection, you would end up with some very unreadable code! 1: var formattedEmployees = Select(Where(employees, emp => emp.ID % 2 == 0), (emp) => 2: new EmployeeFormatted { 3: ID = emp.ID, 4: FullName = emp.LastName + ", " + emp.FirstName 5: }); A cleaner way to write this would be to give the appearance that the Select and Where methods were part of the IEnumerable<T>. This is exactly what extension methods give us. Extension methods have to be defined in a static class. Let us make the Select and Where extension methods on IEnumerable<T> 1: public static class MyExtensionMethods { 2: static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) { 3: foreach (var x in source) { 4: if (filter(x)) { 5: yield return x; 6: } 7: } 8: } 9: 10: static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { 11: foreach (var x in source) { 12: yield return selector(x); 13: } 14: } 15: } The creation of the extension method makes the syntax much cleaner as shown below. We can write as many extension methods as we want and keep on chaining them using this technique. 1: var formattedEmployees = employees 2: .Where(emp => emp.ID % 2 == 0) 3: .Select (emp => new EmployeeFormatted { ID = emp.ID, FullName = emp.LastName + ", " + emp.FirstName }); Making these changes and running our code produces the same result. 1: using System; 2: using System.Collections.Generic; 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: var employees = new List<Employee> { 10: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 11: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 12: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 13: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 14: }; 15:  16: var formattedEmployees = employees 17: .Where(emp => emp.ID % 2 == 0) 18: .Select (emp => 19: new EmployeeFormatted { 20: ID = emp.ID, 21: FullName = emp.LastName + ", " + emp.FirstName 22: } 23: ); 24:  25: foreach (EmployeeFormatted emp in formattedEmployees) { 26: Console.WriteLine("ID {0} Full_Name {1}", 27: emp.ID, emp.FullName); 28: } 29: Console.ReadLine(); 30: } 31: } 32:  33: public static class MyExtensionMethods { 34: static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) { 35: foreach (var x in source) { 36: if (filter(x)) { 37: yield return x; 38: } 39: } 40: } 41: 42: static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { 43: foreach (var x in source) { 44: yield return selector(x); 45: } 46: } 47: } 48:  49: public class Employee { 50: public int ID { get; set;} 51: public string FirstName { get; set;} 52: public string LastName {get; set;} 53: public string Country { get; set; } 54: } 55:  56: public class EmployeeFormatted { 57: public int ID { get; set; } 58: public string FullName {get; set;} 59: } Let’s change our code to return a collection of anonymous types and get rid of the EmployeeFormatted type. We see that the code produces the same output. 1: using System; 2: using System.Collections.Generic; 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: var employees = new List<Employee> { 10: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 11: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 12: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 13: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 14: }; 15:  16: var formattedEmployees = employees 17: .Where(emp => emp.ID % 2 == 0) 18: .Select (emp => 19: new { 20: ID = emp.ID, 21: FullName = emp.LastName + ", " + emp.FirstName 22: } 23: ); 24:  25: foreach (var emp in formattedEmployees) { 26: Console.WriteLine("ID {0} Full_Name {1}", 27: emp.ID, emp.FullName); 28: } 29: Console.ReadLine(); 30: } 31: } 32:  33: public static class MyExtensionMethods { 34: public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) { 35: foreach (var x in source) { 36: if (filter(x)) { 37: yield return x; 38: } 39: } 40: } 41: 42: public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { 43: foreach (var x in source) { 44: yield return selector(x); 45: } 46: } 47: } 48:  49: public class Employee { 50: public int ID { get; set;} 51: public string FirstName { get; set;} 52: public string LastName {get; set;} 53: public string Country { get; set; } 54: } To be more expressive, C# allows us to write our extension method calls as a query expression. Line 16 can be rewritten a query expression like so: 1: var formattedEmployees = from emp in employees 2: where emp.ID % 2 == 0 3: select new { 4: ID = emp.ID, 5: FullName = emp.LastName + ", " + emp.FirstName 6: }; When the compiler encounters an expression like the above, it simply rewrites it as calls to our extension methods.  So far we have been using our extension methods. The System.Linq namespace contains several extension methods for objects that implement the IEnumerable<T>. You can see a listing of these methods in the Enumerable class in the System.Linq namespace. Let’s get rid of our extension methods (which I purposefully wrote to be of the same signature as the ones in the Enumerable class) and use the ones provided in the Enumerable class. Our final code is shown below: 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; //Added 4:  5: public class Program 6: { 7: [STAThread] 8: static void Main(string[] args) 9: { 10: var employees = new List<Employee> { 11: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 12: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 13: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 14: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 15: }; 16:  17: var formattedEmployees = from emp in employees 18: where emp.ID % 2 == 0 19: select new { 20: ID = emp.ID, 21: FullName = emp.LastName + ", " + emp.FirstName 22: }; 23:  24: foreach (var emp in formattedEmployees) { 25: Console.WriteLine("ID {0} Full_Name {1}", 26: emp.ID, emp.FullName); 27: } 28: Console.ReadLine(); 29: } 30: } 31:  32: public class Employee { 33: public int ID { get; set;} 34: public string FirstName { get; set;} 35: public string LastName {get; set;} 36: public string Country { get; set; } 37: } 38:  39: public class EmployeeFormatted { 40: public int ID { get; set; } 41: public string FullName {get; set;} 42: } This post has shown you a basic overview of LINQ to Objects work by showning you how an expression is converted to a sequence of calls to extension methods when working directly with objects. It gets more interesting when working with LINQ to SQL where an expression tree is constructed – an in memory data representation of the expression. The C# compiler compiles these expressions into code that builds an expression tree at runtime. The provider can then traverse the expression tree and generate the appropriate SQL query. You can read more about expression trees in this MSDN article.

    Read the article

  • webbrowser control on form2 vb windows application

    - by user228058
    Hi, I have a vb windows application with 2 forms, where form2 is called from form1 using form2.showdialog() I added a web browser control to form2, and I'm getting the following error at the point where form2 is called: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. I tried: 1) adding STAThread() to the form_load() 2) I added a module to my application, and created a sub main(), with the STAThread attribute applied to it 3) I marked the sub startup() with STAThread() And none of this helped. Any tips on how to get around this issue? Thanks, rcpg

    Read the article

  • SharpDX: best practice for multiple RenderForms?

    - by Rob Jellinghaus
    I have an XNA app, but I really need to add multiple render windows, which XNA doesn't do. I'm looking at SharpDX (both for multi-window support and for DX11 / Metro / many other reasons). I decided to hack up the SharpDX DX11 MultiCubeTexture sample to see if I could make it work. My changes are pretty trivial. The original sample had: [STAThread] private static void Main() { var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample"); ... I changed this to: struct RenderFormWithActions { internal readonly RenderForm Form; // should just be Action but it's not in System namespace?! internal readonly Action RenderAction; internal readonly Action DisposeAction; internal RenderFormWithActions(RenderForm form, Action renderAction, Action disposeAction) { Form = form; RenderAction = renderAction; DisposeAction = disposeAction; } } [STAThread] private static void Main() { // hackity hack new Thread(new ThreadStart(() = { RenderFormWithActions form1 = CreateRenderForm(); RenderLoop.Run(form1.Form, () = form1.RenderAction(0)); form1.DisposeAction(0); })).Start(); new Thread(new ThreadStart(() = { RenderFormWithActions form2 = CreateRenderForm(); RenderLoop.Run(form2.Form, () = form2.RenderAction(0)); form2.DisposeAction(0); })).Start(); } private static RenderFormWithActions CreateRenderForm() { var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample"); ... Basically, I split out all the Main() code into a separate method which creates a RenderForm and two delegates (a render delegate, and a dispose delegate), and bundles them all together into a struct. I call this method twice, each time from a separate, new thread. Then I just have one RenderLoop on each new thread. I was thinking this wouldn't work because of the [STAThread] declaration -- I thought I would need to create the RenderForm on the main (STA) thread, and run only a single RenderLoop on that thread. Fortunately, it seems I was wrong. This works quite well -- if you drag one of the forms around, it stops rendering while being dragged, but starts again when you drop it; and the other form keeps chugging away. My questions are pretty basic: Is this a reasonable approach, or is there some lurking threading issue that might make trouble? My code simply duplicates all the setup code -- it makes a duplicate SwapChain, Device, Texture2D, vertex buffer, everything. I don't have a problem with this level of duplication -- my app is not intensive enough to suffer resource issues -- but nonetheless, is there a better practice? Is there any good reference for which DirectX structures can safely be shared, and which can't? It appears that RenderLoop.Run calls the render delegate in a tight loop. Is there any standard way to limit the frame rate of RenderLoop.Run, if you don't want a 400FPS app eating 100% of your CPU? Should I just Thread.Sleep(30) in the render delegate? (I asked on the sharpdx.org forums as well, but Alexandre is on vacation for two weeks, and my sister wants me to do a performance with my app at her wedding in three and a half weeks, so I'm mighty incented here! http://robjsoftware.org for details of what I'm building....)

    Read the article

  • How to make a file load in my program when a user double clicks an associated file.

    - by Edward Boyle
    I assume in this article that file extension association has been setup by the installer. I may address file extension association at a later date, but for the purpose of this article, I address what sometimes eludes new C# programmers. This is sometimes confusing because you just don’t think about it — you have to access a file that you rarely access when making Windows forms applications, “Program.cs” static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } There are so many ways to skin this cat, so you get to see how I skinned my last cat. static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 mainf = new Form1(); if (args.Length > 0) { try { if (System.IO.File.Exists(args[0])) { mainf.LoadFile= args[0]; } } catch { MessageBox.Show("Could not open file.", "Could not open file.", MessageBoxButtons.OK, MessageBoxIcon.Information); } } Application.Run(mainf); } } It may be easy to miss, but don’t forget to add the string array for the command line arguments: static void Main(string[] args) this is not a part of the default program.cs You will notice the mainf.LoadFile property. In the main form of my program I have a property for public string LoadFile ... and the field private string loadFile = String.Empty; in the forms load event I check the value of this field. private void Form1_Load(object sender, EventArgs e) { if(loadFile != String.Empty){ // The only way this field is NOT String.empty is if we set it in // static void Main() of program.cs // LOAD it however it is needed OpenFile, SetDatabase, whatever you use. } }

    Read the article

  • Using Delegates in C# (Part 1)

    - by rajbk
    This post provides a very basic introduction of delegates in C#. Part 2 of this post can be read here. A delegate is a class that is derived from System.Delegate.  It contains a list of one or more methods called an invocation list. When a delegate instance is “invoked” with the arguments as defined in the signature of the delegate, each of the methods in the invocation list gets invoked with the arguments. The code below shows example with static and instance methods respectively: Static Methods 1: using System; 2: using System.Linq; 3: using System.Collections.Generic; 4: 5: public delegate void SayName(string name); 6: 7: public class Program 8: { 9: [STAThread] 10: static void Main(string[] args) 11: { 12: SayName englishDelegate = new SayName(SayNameInEnglish); 13: SayName frenchDelegate = new SayName(SayNameInFrench); 14: SayName combinedDelegate =(SayName)Delegate.Combine(englishDelegate, frenchDelegate); 15: 16: combinedDelegate.Invoke("Tom"); 17: Console.ReadLine(); 18: } 19: 20: static void SayNameInFrench(string name) { 21: Console.WriteLine("J'ai m'appelle " + name); 22: } 23: 24: static void SayNameInEnglish(string name) { 25: Console.WriteLine("My name is " + name); 26: } 27: } We have declared a delegate of type SayName with return type of void and taking an input parameter of name of type string. On line 12, we create a new instance of this delegate which refers to a static method - SayNameInEnglish.  SayNameInEnglish has the same return type and parameter list as the delegate declaration.  Once a delegate is instantiated, the instance will always refer to the same target. Delegates are immutable. On line 13, we create a new instance of the delegate but point to a different static method. As you may recall, a delegate instance encapsulates an invocation list. You create an invocation list by combining delegates using the Delegate.Combine method (there is an easier syntax as you will see later). When two non null delegate instances are combined, their invocation lists get combined to form a new invocation list. This is done in line 14.  On line 16, we invoke the delegate with the Invoke method and pass in the required string parameter. Since the delegate has an invocation list with two entries, each of the method in the invocation list is invoked. If an unhandled exception occurs during the invocation of one of these methods, the exception gets bubbled up to the line where the invocation was made (line 16). If a delegate is null and you try to invoke it, you will get a System.NullReferenceException. We see the following output when the method is run: My name is TomJ'ai m'apelle Tom Instance Methods The code below outputs the same results as before. The only difference here is we are creating delegates that point to a target object (an instance of Translator) and instance methods which have the same signature as the delegate type. The target object can never be null. We also use the short cut syntax += to combine the delegates instead of Delegate.Combine. 1: public delegate void SayName(string name); 2: 3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Translator translator = new Translator(); 9: SayName combinedDelegate = new SayName(translator.SayNameInEnglish); 10: combinedDelegate += new SayName(translator.SayNameInFrench); 11:  12: combinedDelegate.Invoke("Tom"); 13: Console.ReadLine(); 14: } 15: } 16: 17: public class Translator { 18: public void SayNameInFrench(string name) { 19: Console.WriteLine("J'ai m'appelle " + name); 20: } 21: 22: public void SayNameInEnglish(string name) { 23: Console.WriteLine("My name is " + name); 24: } 25: } A delegate can be removed from a combination of delegates by using the –= operator. Removing a delegate from an empty list or removing a delegate that does not exist in a non empty list will not result in an exception. Delegates are invoked synchronously using the Invoke method. We can also invoke them asynchronously using the BeginInvoke and EndInvoke methods which are compiler generated.

    Read the article

  • Run the Windows .net Application in System Tray on System Startup

    - by Rajneesh Verma
    Hi, Today i have created a .net windows application which has following key points. 1. Run only one instance of the project: to achieve this i have change the code of Program.cs as: Code Snippet static class Program { /// <summary> /// The main entry point for the application. /// </summary> [ STAThread ] static void Main() { bool instanceCountOne = false ; using ( Mutex mtex = new Mutex ( true , "MyRunningApp" , out instanceCountOne)) { if (instanceCountOne) { Application ...(read more)

    Read the article

  • Exception handling problem in release mode

    - by lama-power
    I have application with this code: Module Startup <STAThread()> _ Public Sub Main() Try Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) InitApp() Dim login As New LoginForm() Dim main As New MainForm() Application.Run(login) If login.DialogResult = DialogResult.OK Then ActUser = login.LoggedUser main.ShowDialog() End If DisposeApp() Catch ex As Exception ErrMsg(ex, "Error!", ErrorLogger.ErrMsgType.CriticalError) End End Try End Sub End Module in debug mode everithing is OK. But in release mode when somewhere in application exception occurs my global catch in Main method doesn`t catch exception. What is the problem please?

    Read the article

  • Debug checklists/Helpers with Visual Studio/.NET

    - by hmm
    I have STAThread process which when called from my process simply bombs with no exceptions and almost nothing in the call stack. If I click Cntrl+Alt+E, I get an exceptions window, how can I use it in this situation, seems like some exception is not being caught here. Also what other debugging aids can I use here in Visual Studio 2010?

    Read the article

  • What are the limitations of a STA thread in compare to MTA threads ?

    - by Xaqron
    If we make a thread STA like this: Thread.SetApartmentState(STA); then it cannot run code marked with [MTAThread] attribute. We have seen [STAThread] in windows and console applications but I have never seen code with [MTAThread] attribute and don't know which .NET libraries use this attribute. My question is what are the limitations of a thread with apartment state set to STA, in compare to threads with MTA apartment state (natural .NET threads) ?

    Read the article

  • How to set User Tile image Windows Server 2012?

    - by moontear
    I found this nice article of how to add a user tile image via code: http://joco.name/2010/12/06/i-discovered-the-new-windows-user-tile-api/ This is also explained in depth here: http://msitpros.com/?p=1036 I have problems with doing this in Windows Server 2012. Whenever I run the code: using System; using System.Runtime.InteropServices; namespace FejesJoco { class Program { [DllImport("shell32.dll", EntryPoint = "#262", CharSet = CharSet.Unicode, PreserveSig = false)] public static extern void SetUserTile(string username, int whatever, string picpath); [STAThread] static void Main(string[] args) { SetUserTile(args[0], 0, args[1]); } } } I get an exception: Error HRESULT E_FAIL has been returned from a call to a COM component. Can anyone get this to work and add a user tile image via code?

    Read the article

  • Serializing WPF DataTemplates and {Binding Expressions} (from PowerShell?)

    - by Jaykul
    Ok, here's the deal: I have code that works in C#, but when I call it from PowerShell, it fails. I can't quite figure it out, but it's something specific to PowerShell. Here's the relevant code calling the library (assuming you've added a reference ahead of time) from C#: public class Test { [STAThread] public static void Main() { Console.WriteLine( PoshWpf.XamlHelper.RoundTripXaml( "<TextBlock Text=\"{Binding FullName}\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>" ) ); } } Compiled into an executable, that works fine ... but if you call that method from PowerShell, it returns with no {Binding FullName} for the Text! add-type -path .\PoshWpf.dll [PoshWpf.Test]::Main() I've pasted below the entire code for the library, all wrapped up in a PowerShell Add-Type call so you can just compile it by pasting it into PowerShell (you can leave off the first and last lines if you want to paste it into a new console app in Visual Studio. To output (from PowerShell 2) as an executable, just change the -OutputType parameter to ConsoleApplication and the -OutputAssembly to PoshWpf.exe (or something). Thus, you can see that running the SAME CODE from the executable gives you the correct output. But running the two lines as above or manually calling [PoshWpf.XamlHelper]::RoundTripXaml or [PoshWpf.XamlHelper]::ConvertToXaml from PowerShell just doesn't seem to work at all ... HELP?! Add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace PoshWpf { public class Test { [STAThread] public static void Main() { Console.WriteLine( PoshWpf.XamlHelper.RoundTripXaml( "<TextBlock Text=\"{Binding FullName}\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>" ) ); } } public class BindingTypeDescriptionProvider : TypeDescriptionProvider { private static readonly TypeDescriptionProvider _DEFAULT_TYPE_PROVIDER = TypeDescriptor.GetProvider(typeof(Binding)); public BindingTypeDescriptionProvider() : base(_DEFAULT_TYPE_PROVIDER) { } public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance); return instance == null ? defaultDescriptor : new BindingCustomTypeDescriptor(defaultDescriptor); } } public class BindingCustomTypeDescriptor : CustomTypeDescriptor { public BindingCustomTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) { } public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptor pd; var pdc = new PropertyDescriptorCollection(base.GetProperties(attributes).Cast<PropertyDescriptor>().ToArray()); if ((pd = pdc.Find("Source", false)) != null) { pdc.Add(TypeDescriptor.CreateProperty(typeof(Binding), pd, new Attribute[] { new DefaultValueAttribute("null") })); pdc.Remove(pd); } return pdc; } } public class BindingConverter : ExpressionConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType == typeof(MarkupExtension)) ? true : false; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(MarkupExtension)) { var bindingExpression = value as BindingExpression; if (bindingExpression == null) throw new Exception(); return bindingExpression.ParentBinding; } return base.ConvertTo(context, culture, value, destinationType); } } public static class XamlHelper { static XamlHelper() { // this is absolutely vital: TypeDescriptor.AddProvider(new BindingTypeDescriptionProvider(), typeof(Binding)); TypeDescriptor.AddAttributes(typeof(BindingExpression), new Attribute[] { new TypeConverterAttribute(typeof(BindingConverter)) }); } public static string RoundTripXaml(string xaml) { return XamlWriter.Save(XamlReader.Parse(xaml)); } public static string ConvertToXaml(object wpf) { return XamlWriter.Save(wpf); } } } "@ -language CSharpVersion3 -reference PresentationCore, PresentationFramework, WindowsBase -OutputType Library -OutputAssembly PoshWpf.dll Again, you can get an executable by just altering the last line like so: "@ -language CSharpVersion3 -reference PresentationCore, PresentationFramework, WindowsBase -OutputType ConsoleApplication -OutputAssembly PoshWpf.exe

    Read the article

  • OpenFileDialog.AutoUpgradeEnabled doesn't work under 7?

    - by Digiku
    If I specify OpenFileDialog.AutoUpgradeEnabled = true, my program still shows the old XP-style dialog. Any idea why this would happen? This is after I enable theming in Main() [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Primary()); } and this is my dialog code: private void OpenProgramFile() { OpenFileDialog programFileDialog = new OpenFileDialog(); programFileDialog.Filter = "Program files (*.exe;*.lnk)|*.exe|All files (*.*)|*.*"; programFileDialog.FilterIndex = 0; programFileDialog.Title = "Select program file"; programFileDialog.AutoUpgradeEnabled = true; programFileDialog.ShowHelp = true; DialogResult fileResult = programFileDialog.ShowDialog(); if (fileResult != DialogResult.OK) return false; programFileDialog.Dispose(); } So why would AutoUpgradeEnabled not work on 7?

    Read the article

  • OpenFileDialog.AutoUpgradeEnabled doesn't work under Vista or 7?

    - by Digiku
    If I specify OpenFileDialog.AutoUpgradeEnabled = true, my program still shows the old XP-style dialog. Any idea why this would happen? This is after I enable theming in Main() [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Primary()); } and this is my dialog code: private void OpenProgramFile() { OpenFileDialog programFileDialog = new OpenFileDialog(); programFileDialog.Filter = "Program files (*.exe;*.lnk)|*.exe|All files (*.*)|*.*"; programFileDialog.FilterIndex = 0; programFileDialog.Title = "Select program file"; programFileDialog.AutoUpgradeEnabled = true; programFileDialog.ShowHelp = true; DialogResult fileResult = programFileDialog.ShowDialog(); if (fileResult != DialogResult.OK) return false; programFileDialog.Dispose(); } So why would AutoUpgradeEnabled not work?

    Read the article

  • Trouble with using ActiveX control in .net windows application

    - by alex dee
    C#, visual studio 2005 I have several 3rd party activeX control. I need to use them in my .net windows application. These controls are graphical. I created a wrapper with aximp.exe for them. But it seems that something wrong. When I call some methods of wrapped activeX control == targetinvocativeexception occured. Or visual studio writes "you are attempting to write or read protected memory". I know that something wrong. But what is exactly wrong - i don't know. I find out about method CreateControl() or STAthread attribute. but it doesn't help me. What is the common problem and common solution for my type of problem ? These activex control from big and trusted company, other developers work with them.

    Read the article

  • Simple Windows.Forms binding is failing using framework 4.0.

    - by jyoung
    This works under the .net framework 3.5 client. This fails under the .net framework 4.0 client. Was I doing something that was illegal under 3.5 but just happened to work, or is this a bug? Note that in my project 'PropInt' does not raise change events so using ctx[obj1.PropObj2, "PropInt"] is not an option. public class Obj1 { public Obj2 PropObj2 { get; set; } public Obj1() { PropObj2 = new Obj2(); } } public class Obj2 { public int PropInt { get; set; } } static class Program { [STAThread] static void Main() { var ctx = new BindingContext(); var obj1 = new Obj1(); var x1 = ctx[obj1, "PropObj2.PropInt"]; } }

    Read the article

  • XAML resources aren't loaded when calling from different project

    - by svick
    I have a WPF project with some styles in XAML in Application.Resources. This works perfectly fine. But when I open a window from this project from another one (this one is a console application), the resources from XAML aren't loaded. When I first tried it, I got a XamlParseException on StaticResource calls in XAML, so I changed it to DynamicResource and now the style just doesn't get loaded. How do I fix this? The code I use: [STAThread] static void Main() { App app = new App(); MyWindow wnd = new MyWindow (); wnd.Show(); app.Run(); }

    Read the article

  • ThreadStateException when using QueueUserWorkItem in a Timer

    - by Tim
    Hi all, I have a ThreadStateException in my winforms application. Step to reproduce : Create simple winforms app Add a button In click event, do : timer1.Interval = 1000; timer1.Tick += timer1_Tick; timer1.Start(); void timer1_Tick(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(delegate { StringCollection paths = new StringCollection { @"c:\my.txt", @"c:\my.png" }; Clipboard.SetFileDropList(paths); }); } The exception tells me : Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. But the main has already the [STAThread] attribute. How to solve it ? Thanks in advance for any help

    Read the article

  • F# WPF Form &ndash; the basics

    - by MarkPearl
    I was listening to Dot Net Rocks show #560 about F# and during the podcast Richard Campbell brought up a good point with regards to F# and a GUI. In essence what I understood his point to be was that until one could write an end to end application in F#, it would be a hard sell to developers to take it on. In part I agree with him, while I am beginning to really enjoy learning F#, I can’t but help feel that I would be a lot further into the language if I could do my Windows Forms like I do in C# or VB.NET for the simple reason that in “playing” applications I spend the majority of the time in the UI layer… So I have been keeping my eye out for some examples of creating a WPF form in a F# project and came across Tim’s F# Twitter Stream Sample, which had exactly this…. of course he actually had a bit more than a basic form… but it was enough for me to scrap the insides and glean what I needed. So today I am going to make just the very basic WPF form with all the goodness of a XAML window. Getting Started First thing we need to do is create a new solution with a blank F# application project – I have made mine called FSharpWPF. Once you have the project created you will need to change the project type from a Console Application to a Windows Application. You do this by right clicking on the project file and going to its properties… Once that is done you will need to add the appropriate references. You do this by right clicking on the References in the Solution Explorer and clicking “Add Reference'”. You should add the appropriate .Net references below for WPF & XAMl to work. Once these references are added you then need to add your XAML file to the project. You can do this by adding a new item to the project of type xml and simply changing the file extension from xml to xaml. Once the xaml file has been added to the project you will need to add valid window XAML. Example of a very basic xaml file is shown below… <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="F# WPF WPF Form" Height="350" Width="525"> <Grid> </Grid> </Window> Once your xaml file is done… you need to set the build action of the xaml file from “None” to “Resource” as depicted in the picture below. If you do not set this you will get an IOException error when running the completed project with a message along the lines of “Cannot locate resource ‘window.xaml’ You then need to tie everything up by putting the correct F# code in the Program.fs to load the xaml window. In the Program.fs put the following code… module Program open System open System.Collections.ObjectModel open System.IO open System.Windows open System.Windows.Controls open System.Windows.Markup [<STAThread>] [<EntryPoint>] let main(_) = let w = Application.LoadComponent(new System.Uri("/FSharpWPF;component/Window.xaml", System.UriKind.Relative)) :?> Window (new Application()).Run(w) Once all this is done you should be able to build and run your project. What you have done is created a WPF based window inside a FSharp project. It should look something like below…   Nothing to exciting, but sufficient to illustrate the very basic WPF form in F#. Hopefully in future posts I will build on this to expose button events etc.

    Read the article

  • Friend Assemblies in C#

    - by Tim Long
    I'm trying to create some 'friend assemblies' using the [InternalsVisibleTo()] attribute, but I can't seem to get it working. I've followed Microsoft's instructions for creating signed friend assemblies and I can't see where I'm going wrong. So I'll detail my steps here and hopefully someone can spot my deliberate mistake...? Create a strong name key and extract the public key, thus: sn -k StrongNameKey sn -p public.pk sn -tp public.pk Add the strong name key to each project and enable signing. Create a project called Internals and a class with an internal property: namespace Internals { internal class ClassWithInternals { internal string Message { get; set; } public ClassWithInternals(string m) { Message = m; } } } Create another project called TestInternalsVisibleTo: namespace TestInternalsVisibleTo { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var c = new Internals.ClassWithInternals("Test"); Console.WriteLine(c.Message); } } } Edit the AssemblyInfo.cs file for the Internals project, and add teh necessary attribute: [assembly: AssemblyTitle("AssemblyWithInternals")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Internals")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("41c590dc-f555-48bc-8a94-10c0e7adfd9b")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("TestInternalsVisibleTo PublicKey=002400000480000094000000060200000024000052534131000400000100010087953126637ab27cb375fa917c35b23502c2994bb860cc2582d39912b73740d6b56912c169e4a702bedb471a859a33acbc8b79e1f103667e5075ad17dffda58988ceaf764613bd56fc8f909f43a1b177172bc4143c96cf987274873626abb650550977dcad1bb9bfa255056bb8d0a2ec5d35d6f8cb0a6065ec0639550c2334b9")] And finally... build! I get the following errors: error CS0122: 'Internals.ClassWithInternals' is inaccessible due to its protection level error CS1729: 'Internals.ClassWithInternals' does not contain a constructor that takes 1 arguments error CS1061: 'Internals.ClassWithInternals' does not contain a definition for 'Message' and no extension method 'Message' accepting a first argument of type 'Internals.ClassWithInternals' could be found (are you missing a using directive or an assembly reference?) Basically, it's as if I had not used the InternalsVisibleTo attrbute. Now, I'm not going to fall into the trap of blaming the tools, so what's up here? Anyone?

    Read the article

  • AppDomain.CurrentDomain.UnhandledException doesn't always fire up

    - by Simon T.
    I encountered an exception in our application that isn't handled at all. I really don't know what to look for to debug this problem since the application close immediately when this peculiar exception is thrown (even running from VS). The exception handling is setup that way: [STAThread] [LoaderOptimizationAttribute(LoaderOptimization.MultiDomainHost)] static void Main() { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ApplicationExit += new EventHandler(ApplicationExitHandler); Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); ... The thread from which the exception is thrown is started that way: Thread executerThread = new Thread(new ThreadStart(modele.Exporter)); executerThread.SetApartmentState(ApartmentState.STA); executerThread.Start(); Now, every unhandled exception thrown from that thread fire up our UnhandledExceptionHandler except the one I have problems with. Even if I catch the problematic exception and throw it again, the application closes silently. None of the 3 handlers (ApplicationExit, ThreadException, UnhandledException) get fired (breakpoints not hit). There is nothing so exceptional in that exception (see details here: http://pastebin.com/fCnDRRiJ).

    Read the article

  • #indent "off" in F#

    - by anta40
    I just started learning F#, and tried a code from the wiki: I prefer tabs to spaces, so I change the code a bit into this: #indent "off" open System open System.Windows.Forms let form = new Form(Visible=true, TopMost=true, Text="Welcome to F#") let label = let temp = new Label() let x = 3 + (4 * 5) temp.Text <- sprintf "x = %d" x temp form.Controls.Add(label) [<STAThread>] Application.Run(form) The output is: Microsoft (R) F# 2.0 Compiler build 4.0.30319.1 Copyright (c) Microsoft Corporation. All Rights Reserved. fstest2.fs(1,1): warning FS0062: This construct is for ML compatibility. Conside r using a file with extension '.ml' or '.mli' instead. You can disable this warn ing by using '--mlcompatibility' or '--nowarn:62'. fstest2.fs(9,2): error FS0010: Unexpected keyword 'let' or 'use' in expression. Expected 'in' or other token. fstest2.fs(13,1): error FS0597: Successive arguments should be separated by spac es or tupled, and arguments involving function or method applications should be parenthesized fstest2.fs(9,14): error FS0374: Invalid expression on left of assignment fstest2.fs(16,1): error FS0010: Unexpected identifier in definition Guess the error is somewhere in the let label block, but couldn't figure it out.

    Read the article

  • Passing data to a non-static listBox, by calling function from another class

    - by Andrew A
    I have a simple forms program that I have been fighting with for a while now. I simply want to be able to call a method from a different class file (when a certain step is triggered in the code in that class file) in order to insert a string in the listBox. Here is my main method, pretty standard: class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } Here is the function which resides in my MainForm.cs file, which I can call just fine from that class file (via 'TextToBox(myString);'): public partial class MainForm : Form { ... // Function to output results to main Listbox window public void TextToBox(string aString) { // Place messages in Main Display list box window this.listBox1.Items.Insert(0, aString); } ... } But my problem is when I am in another class and I want to call 'TextToBox(myString);'. If I create another object reference of the MainForm, the code compiles fine but nothing will show up in the listBox. How do I do this? I cannot simply make TextToBox() static. I know I must create the object reference but I can't figure out how to reference the ORIGINAL MainForm, the one that was created in the Main method. Thanks in advance...

    Read the article

1 2 3  | Next Page >