Thursday, August 14, 2014
Generic Collection
When to Use Generic Collections
.NET Framework 4.5 Other Versions .NET Framework 4 .NET Framework 3.0 Silverlight .NET Framework 3.5 .NET Framework 2.0 4 out of 5 rated this helpful - Rate this topic
Using generic collections is generally recommended, because you gain the immediate benefit of type safety without having to derive from a base collection type and implement type-specific members. Generic collection types also generally perform better than the corresponding nongeneric collection types (and better than types that are derived from nongeneric base collection types) when the collection elements are value types, because with generics there is no need to box the elements.
For programs that target the .NET Framework 4 or later, you should use the generic collection classes in the System.Collections.Concurrent namespace when multiple threads might be adding or removing items from the collection concurrently.
The following generic types correspond to existing collection types:
•List is the generic class that corresponds to ArrayList.
•Dictionary and ConcurrentDictionary are the generic classes that correspond to Hashtable.
•Collection is the generic class that corresponds to CollectionBase. Collection can be used as a base class, but unlike CollectionBase, it is not abstract. This makes it much easier to use.
•ReadOnlyCollection is the generic class that corresponds to ReadOnlyCollectionBase. ReadOnlyCollection is not abstract, and has a constructor that makes it easy to expose an existing List as a read-only collection.
•The Queue, ConcurrentQueue, Stack, ConcurrentStack, and SortedList generic classes correspond to the respective nongeneric classes with the same names.
Additional Types
--------------------------------------------------------------------------------
Several generic collection types do not have nongeneric counterparts. They include the following:
•LinkedList is a general-purpose linked list that provides O(1) insertion and removal operations.
•SortedDictionary is a sorted dictionary with O(log n) insertion and retrieval operations, which makes it a useful alternative to SortedList.
•KeyedCollection is a hybrid between a list and a dictionary, which provides a way to store objects that contain their own keys.
•BlockingCollection implements a collection class with bounding and blocking functionality.
•ConcurrentBag provides fast insertion and removal of unordered elements.
LINQ to Objects
--------------------------------------------------------------------------------
The LINQ to Objects feature enables you to use LINQ queries to access in-memory objects as long as the object type implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface. LINQ queries provide a common pattern for accessing data; are typically more concise and readable than standard foreach loops; and provide filtering, ordering and grouping capabilities. LINQ queries can also improve performance. For more information, see LINQ to Objects and Parallel LINQ (PLINQ).
Additional Functionality
--------------------------------------------------------------------------------
Some of the generic types have functionality that is not found in the nongeneric collection types. For example, the List class, which corresponds to the nongeneric ArrayList class, has a number of methods that accept generic delegates, such as the Predicate delegate that allows you to specify methods for searching the list, the Action delegate that represents methods that act on each element of the list, and the Converter delegate that lets you define conversions between types.
The List class allows you to specify your own IComparer generic interface implementations for sorting and searching the list. The SortedDictionary and SortedList classes also have this capability. In addition, these classes let you specify comparers when the collection is created. In similar fashion, the Dictionary and KeyedCollection classes let you specify your own equality comparers.
Singleton
This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. Please see the patterns & practices guidance for the most current information.
Version 1.0.1
GotDotNet community for collaboration on this pattern
Complete List of patterns & practices
Context
You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.
Implementation Strategy
Even though Singleton is a comparatively simple pattern, there are various tradeoffs and options, depending upon the implementation. The following is a series of implementation strategies with a discussion of their strengths and weaknesses.
Singleton
The following implementation of the Singleton design pattern follows the solution presented in Design Patterns: Elements of Reusable Object-Oriented Software [Gamma95] but modifies it to take advantage of language features available in C#, such as properties:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
This implementation has two main advantages:
•Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.
•The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.
The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:
if (instance == null)
Various approaches solve this problem. One approach is to use an idiom referred to as Double-Check Locking [Lea99]. However, C# in combination with the common language runtime provides a static initialization approach, which circumvents these issues without requiring the developer to explicitly code for thread safety.
Static Initialization
One of the reasons Design Patterns [Gamma95] avoided static initialization is because the C++ specification left some ambiguity around the initialization order of static variables. Fortunately, the .NET Framework resolves this ambiguity through its handling of variable initialization:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
In this strategy, the instance is created the first time any member of the class is referenced. The common language runtime takes care of the variable initialization. The class is marked sealed to prevent derivation, which could add instances. For a discussion of the pros and cons of marking a class sealed, see [Sells03]. In addition, the variable is marked readonly, which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.
This implementation is similar to the preceding example, except that it relies on the common language runtime to initialize the variable. It still addresses the two basic problems that the Singleton pattern is trying to solve: global access and instantiation control. The public static property provides a global access point to the instance. Also, because the constructor is private, the Singleton class cannot be instantiated outside of the class itself; therefore, the variable refers to the only instance that can exist in the system.
Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instance property. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton.
The only potential downside of this approach is that you have less control over the mechanics of the instantiation. In the Design Patterns form, you were able to use a nondefault constructor or perform other tasks before the instantiation. Because the .NET Framework performs the initialization in this solution, you do not have these options. In most cases, static initialization is the preferred approach for implementing a Singleton in .NET.
Multithreaded Singleton
Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution. Cases do exist, however, in which you cannot rely on the common language runtime to ensure thread safety, as in the Static Initialization example. In such cases, you must use specific language capabilities to ensure that only one instance of the object is created in the presence of multiple threads. One of the more common solutions is to use the Double-Check Locking [Lea99] idiom to keep separate threads from creating new instances of the singleton at the same time.
Note: The common language runtime resolves issues related to using Double-Check Locking that are common in other environments. For more information about these issues, see "The 'Double-Checked Locking Is Broken' Declaration," on the University of Maryland, Department of Computer Science Web site, at http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.
The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.
This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.
Monday, July 7, 2014
UI Testing using TestStack.White
https://github.com/TestStack/White
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading;
using TestStack.White;using TestStack.White.Factory;using TestStack.White.UIItems.Finders;
namespace AnotherTestStackApplication{
class Program{#region varaibles
private static TestStack.White.Application _application;
private static TestStack.White.UIItems.WindowItems.Window _mainWindow;
private static TestStack.White.UIItems.ListBoxItems.ListBox _listbox;
private static TestStack.White.UIItems.Button _btnok;
private static List<TestStack.White.UIItems.WindowItems.Window> _allWindows;
static StringBuilder _totalControls= new StringBuilder();
#endregionstatic void Main(string[] args){
try{
_totalControls = new StringBuilder();
//launching ApplicationlaunchApp();
//Reading from main PanelloadingReadingMain();
}
catch (Exception ex){
}
}
static void launchApp(){
try{
// string ExeSourceFPFile = @"E:\TPL\TPL\2014.06.01\Flow and Listed Pricer - Unity\bin\Debug\Unity.exe";//find Exe application, right now in same place-- we need to figure out how to do, may be copy this exe same location_application = Application.Launch("Unity.exe");_mainWindow = _application.GetWindow(
SearchCriteria.ByText("FlowPricer"), InitializeOption.NoCache);
//Get list box of all region_listbox = (TestStack.White.UIItems.ListBoxItems.ListBox)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[1];
// Select Europe_listbox.Select(2);//Select Europe//Get button_btnok = (TestStack.White.UIItems.Button)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[5];_btnok.Click();
//Put wait for 3 sec// Thread.Sleep(1000);
//popup AddIns Region Override._mainWindow = _application.GetWindow(SearchCriteria.ByText("AddIns Region Override"), InitializeOption.NoCache);_listbox = (TestStack.White.UIItems.ListBoxItems.
ListBox)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[1];_listbox.Select(2);
//Select Europe//Put wait for 3 secThread.Sleep(2000);
//Get button_btnok = (TestStack.White.UIItems.Button)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[5];_btnok.Click();
}
catch (Exception ex){
}
}
static void loadingReadingMain(){
try{
//_mainWindow = _application.GetWindow(SearchCriteria.ByText("Unified Trading Desktop (EU)"), InitializeOption.NoCache);// Find Menu//var test = ((TestStack.White.UIItems.UIItemContainer)(_application));
//Loading All controls from Main Windows_allWindows=_application.GetWindows();
StringBuilder sb = new StringBuilder();
foreach (var allWindow in _allWindows){
foreach (var uiItem in allWindow.Items){
if (uiItem is TestStack.White.UIItems.UIItem){
TestStack.White.UIItems.
UIItem _uiItem = uiItem as TestStack.White.UIItems.UIItem;_totalControls.Append(GetAllControl(_uiItem));
}
//if (uiItem is TestStack.White.UIItems.Image)//{// // sb.Append(((TestStack.White.UIItems.Image)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Thumb)//{// sb.Append(((TestStack.White.UIItems.Thumb)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.WindowStripControls.MenuBar)//{// sb.Append(((TestStack.White.UIItems.WindowStripControls.MenuBar)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.WPFLabel)//{// sb.Append(((TestStack.White.UIItems.WPFLabel)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Custom.CustomUIItem)//{// sb.Append(((TestStack.White.UIItems.Custom.CustomUIItem)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Button)//{// sb.Append(((TestStack.White.UIItems.Button)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.WindowStripControls.WPFStatusBar)//{// sb.Append(((TestStack.White.UIItems.WindowStripControls.WPFStatusBar)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Panel)//{// var result1 = uiItem as TestStack.White.UIItems.Panel;// foreach (var childitem in result1.Items)// {// sb.Append(childitem.Name.ToString());// }// sb.Append(((TestStack.White.UIItems.Panel)uiItem).Name.ToString());//}}
}
string result = _totalControls.ToString();}
catch (Exception ex){
}
}
private string getName(TestStack.White.UIItems.UIItemContainer uiItem){
if (uiItem is TestStack.White.UIItems.Panel){
var panel = uiItem as TestStack.White.UIItems.Panel;
if (panel.Items.Count > 0){
foreach (var UIItem in panel.Items){
}
}
}
return "";}
private static StringBuilder GetAllControl(TestStack.White.UIItems.UIItem uiItem){
StringBuilder sbResult = new StringBuilder();
Type nodeType = uiItem.GetType();
switch (uiItem.GetType().Name){
case "Panel":
var panel = uiItem as TestStack.White.UIItems.Panel;
if (panel != null) foreach (TestStack.White.UIItems.UIItemContainer panelItem in panel.Items) sbResult.Append(GetAllControl(panelItem));
break;
case "Image":
var ImguiItem = uiItem as TestStack.White.UIItems.Image;sbResult.Append(ImguiItem.Name.ToString());
break;
case "Thumb":
var ThumbuiItem = uiItem as TestStack.White.UIItems.Thumb;sbResult.Append(ThumbuiItem.Name.ToString());
break;
case "WindowStripControls.MenuBar":
var MnuuiItem = uiItem as TestStack.White.UIItems.WindowStripControls.MenuBar;sbResult.Append(MnuuiItem.Name.ToString());
break;
case "WPFLabel":
var WPFLabeluiItem = uiItem as TestStack.White.UIItems.WPFLabel;sbResult.Append(WPFLabeluiItem.Name.ToString());
break;
case "TestStack.White.UIItems.Custom.CustomUIItem":
var CustomuiItem = uiItem as TestStack.White.UIItems.Custom.CustomUIItem;sbResult.Append(CustomuiItem.Name.ToString());
break;
case "TestStack.White.UIItems.WindowStripControls.WPFStatusBar":
var statusuiItem = uiItem as TestStack.White.UIItems.WindowStripControls.WPFStatusBar;sbResult.Append(statusuiItem.Name.ToString());
break;
}
return sbResult;}
private void GetAllControl(TestStack.White.UIItems.UIItemCollection uiItem){
foreach (TestStack.White.UIItems.UIItemContainer uicontainers in uiItem){
StringBuilder test = new StringBuilder();test.Append(GetAllControl(uicontainers));
}
}
}
}
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading;
using TestStack.White;using TestStack.White.Factory;using TestStack.White.UIItems.Finders;
namespace AnotherTestStackApplication{
class Program{#region varaibles
private static TestStack.White.Application _application;
private static TestStack.White.UIItems.WindowItems.Window _mainWindow;
private static TestStack.White.UIItems.ListBoxItems.ListBox _listbox;
private static TestStack.White.UIItems.Button _btnok;
private static List<TestStack.White.UIItems.WindowItems.Window> _allWindows;
static StringBuilder _totalControls= new StringBuilder();
#endregionstatic void Main(string[] args){
try{
_totalControls = new StringBuilder();
//launching ApplicationlaunchApp();
//Reading from main PanelloadingReadingMain();
}
catch (Exception ex){
}
}
static void launchApp(){
try{
// string ExeSourceFPFile = @"E:\TPL\TPL\2014.06.01\Flow and Listed Pricer - Unity\bin\Debug\Unity.exe";//find Exe application, right now in same place-- we need to figure out how to do, may be copy this exe same location_application = Application.Launch("Unity.exe");_mainWindow = _application.GetWindow(
SearchCriteria.ByText("FlowPricer"), InitializeOption.NoCache);
//Get list box of all region_listbox = (TestStack.White.UIItems.ListBoxItems.ListBox)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[1];
// Select Europe_listbox.Select(2);//Select Europe//Get button_btnok = (TestStack.White.UIItems.Button)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[5];_btnok.Click();
//Put wait for 3 sec// Thread.Sleep(1000);
//popup AddIns Region Override._mainWindow = _application.GetWindow(SearchCriteria.ByText("AddIns Region Override"), InitializeOption.NoCache);_listbox = (TestStack.White.UIItems.ListBoxItems.
ListBox)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[1];_listbox.Select(2);
//Select Europe//Put wait for 3 secThread.Sleep(2000);
//Get button_btnok = (TestStack.White.UIItems.Button)((TestStack.White.UIItems.UIItemContainer)(_mainWindow)).Items[5];_btnok.Click();
}
catch (Exception ex){
}
}
static void loadingReadingMain(){
try{
//_mainWindow = _application.GetWindow(SearchCriteria.ByText("Unified Trading Desktop (EU)"), InitializeOption.NoCache);// Find Menu//var test = ((TestStack.White.UIItems.UIItemContainer)(_application));
//Loading All controls from Main Windows_allWindows=_application.GetWindows();
StringBuilder sb = new StringBuilder();
foreach (var allWindow in _allWindows){
foreach (var uiItem in allWindow.Items){
if (uiItem is TestStack.White.UIItems.UIItem){
TestStack.White.UIItems.
UIItem _uiItem = uiItem as TestStack.White.UIItems.UIItem;_totalControls.Append(GetAllControl(_uiItem));
}
//if (uiItem is TestStack.White.UIItems.Image)//{// // sb.Append(((TestStack.White.UIItems.Image)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Thumb)//{// sb.Append(((TestStack.White.UIItems.Thumb)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.WindowStripControls.MenuBar)//{// sb.Append(((TestStack.White.UIItems.WindowStripControls.MenuBar)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.WPFLabel)//{// sb.Append(((TestStack.White.UIItems.WPFLabel)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Custom.CustomUIItem)//{// sb.Append(((TestStack.White.UIItems.Custom.CustomUIItem)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Button)//{// sb.Append(((TestStack.White.UIItems.Button)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.WindowStripControls.WPFStatusBar)//{// sb.Append(((TestStack.White.UIItems.WindowStripControls.WPFStatusBar)uiItem).Name.ToString());//}//if (uiItem is TestStack.White.UIItems.Panel)//{// var result1 = uiItem as TestStack.White.UIItems.Panel;// foreach (var childitem in result1.Items)// {// sb.Append(childitem.Name.ToString());// }// sb.Append(((TestStack.White.UIItems.Panel)uiItem).Name.ToString());//}}
}
string result = _totalControls.ToString();}
catch (Exception ex){
}
}
private string getName(TestStack.White.UIItems.UIItemContainer uiItem){
if (uiItem is TestStack.White.UIItems.Panel){
var panel = uiItem as TestStack.White.UIItems.Panel;
if (panel.Items.Count > 0){
foreach (var UIItem in panel.Items){
}
}
}
return "";}
private static StringBuilder GetAllControl(TestStack.White.UIItems.UIItem uiItem){
StringBuilder sbResult = new StringBuilder();
Type nodeType = uiItem.GetType();
switch (uiItem.GetType().Name){
case "Panel":
var panel = uiItem as TestStack.White.UIItems.Panel;
if (panel != null) foreach (TestStack.White.UIItems.UIItemContainer panelItem in panel.Items) sbResult.Append(GetAllControl(panelItem));
break;
case "Image":
var ImguiItem = uiItem as TestStack.White.UIItems.Image;sbResult.Append(ImguiItem.Name.ToString());
break;
case "Thumb":
var ThumbuiItem = uiItem as TestStack.White.UIItems.Thumb;sbResult.Append(ThumbuiItem.Name.ToString());
break;
case "WindowStripControls.MenuBar":
var MnuuiItem = uiItem as TestStack.White.UIItems.WindowStripControls.MenuBar;sbResult.Append(MnuuiItem.Name.ToString());
break;
case "WPFLabel":
var WPFLabeluiItem = uiItem as TestStack.White.UIItems.WPFLabel;sbResult.Append(WPFLabeluiItem.Name.ToString());
break;
case "TestStack.White.UIItems.Custom.CustomUIItem":
var CustomuiItem = uiItem as TestStack.White.UIItems.Custom.CustomUIItem;sbResult.Append(CustomuiItem.Name.ToString());
break;
case "TestStack.White.UIItems.WindowStripControls.WPFStatusBar":
var statusuiItem = uiItem as TestStack.White.UIItems.WindowStripControls.WPFStatusBar;sbResult.Append(statusuiItem.Name.ToString());
break;
}
return sbResult;}
private void GetAllControl(TestStack.White.UIItems.UIItemCollection uiItem){
foreach (TestStack.White.UIItems.UIItemContainer uicontainers in uiItem){
StringBuilder test = new StringBuilder();test.Append(GetAllControl(uicontainers));
}
}
}
}
Subscribe to:
Posts (Atom)