Tuesday, 30 April 2019

Win/Control

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Automation;
using System.Windows.Forms;

namespace CoreWinLibraries
{
    public abstract class Control
    {
        public Control()
        {

        }

        private void SetValue(AutomationElement element, string value)
        {



        }
        private string GetValue(AutomationElement element)
        {
            string result = string.Empty;
            return result;
        }
        private void Click(AutomationElement element)
        {

        }
        //public bool Exists(AutomationElement element)
        //{
        //   bool result =  Exists(aeParent,aeChild);
        //  return result;
        //}

        public static AutomationElement FindElement(AutomationElement aeParent, string locator)
        {
            AutomationElement aeChild = null;
            string searchType = locator.Split(':')[0];
            string sPropertyValue = locator.Split(':')[1];
            switch (searchType)
            {
                case "Id":
                    {
                        aeChild = Wait.UntilResponsive(aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, sPropertyValue)),TimeSpan.FromSeconds(10));
                        //aeChild = aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, sPropertyValue));
                    }
                    break;
                case "Name":
                    {
                       aeChild =  Wait.UntilResponsive(aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, sPropertyValue)),TimeSpan.FromSeconds(10));
                       
                       //aeChild = aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, sPropertyValue));
                    }
                    break;
                case "ClassName":
                    {
                        aeChild = Wait.UntilResponsive(aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, sPropertyValue)),TimeSpan.FromSeconds(10));
                       
                        //aeChild = aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, sPropertyValue));
                    }
                    break;
                case "ControlType":
                    {
                        aeChild = Wait.UntilResponsive(aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, sPropertyValue)),TimeSpan.FromSeconds(10));
                       
                        //aeChild = aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, sPropertyValue));
                    }
                    break;
                case "LocalizedControlType":
                    {
                        System.Threading.Thread.Sleep(500);
                        aeChild = Wait.UntilResponsive(aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, sPropertyValue)), TimeSpan.FromSeconds(30));

                        //aeChild = aeParent.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, sPropertyValue));
                    }
                    break;
                default:
                    break;
            }
            return aeChild;

        }

        private static AutomationElement GetChildren(AutomationElement parent, string sAutomationElementValue)
        {
            if (parent == null)
            {
                throw new ArgumentException();
            }
            AutomationElementCollection collection = parent.FindAll(TreeScope.Children, Condition.TrueCondition);
            if (collection != null)
            {
                //Cast AutomationElementCollection into
                //AutomationElement List
                List<AutomationElement> aeList = new List<AutomationElement>(collection.Cast<AutomationElement>());
                AutomationElement aeSelected = aeList.FirstOrDefault(i => i.Current.Name.Contains(sAutomationElementValue));
                if (aeSelected != null)
                {
                    return aeSelected;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                // some error occured
                return null;
            }
        }

        /// <summary>
        /// Retrieves the top-level window that contains the specified UI Automation element.
        /// </summary>
        /// <param name="element">The contained element.</param>
        /// <returns>The containing top-level window element.</returns>
        private AutomationElement GetTopLevelWindow(AutomationElement element)
        {
            TreeWalker walker = TreeWalker.ControlViewWalker;
            AutomationElement elementParent;
            AutomationElement node = element;
            do
            {
                elementParent = walker.GetParent(node);
                if (elementParent == AutomationElement.RootElement)
                {
                    break;
                }

                node = elementParent;
            }
            while (true);
            return node;
        }

        /// <summary>
        /// Walks the UI Automation tree and adds the control type of each enabled control
        /// element it finds to a TreeView.
        /// </summary>
        /// <param name="rootElement">The root of the search on this iteration.</param>
        /// <param name="treeNode">The node in the TreeView for this iteration.</param>
        /// <remarks>
        /// This is a recursive function that maps out the structure of the subtree beginning at the
        /// UI Automation element passed in as rootElement on the first call. This could be, for example,
        /// an application window.
        /// CAUTION: Do not pass in AutomationElement.RootElement. Attempting to map out the entire subtree of
        /// the desktop could take a very long time and even lead to a stack overflow.
        /// </remarks>
        private void WalkEnabledElements(AutomationElement rootElement, TreeNode treeNode)
        {
            Condition condition1 = new PropertyCondition(AutomationElement.IsControlElementProperty, true);
            Condition condition2 = new PropertyCondition(AutomationElement.IsEnabledProperty, true);
            TreeWalker walker = new TreeWalker(new AndCondition(condition1, condition2));
            AutomationElement elementNode = walker.GetFirstChild(rootElement);
            while (elementNode != null)
            {
                TreeNode childTreeNode = treeNode.Nodes.Add(elementNode.Current.ControlType.LocalizedControlType);
                WalkEnabledElements(elementNode, childTreeNode);
                elementNode = walker.GetNextSibling(elementNode);
            }
        }

         /// <summary>
        ///
        /// </summary>
        /// <param name="aeTargetted"></param>
        /// <returns></returns>
        public static AutomationPattern[] GetSupportedPattern(AutomationElement aeTargetted)
        {
            List<AutomationPattern> lAutomationPattern = new List<AutomationPattern>();
            return aeTargetted.GetSupportedPatterns();

        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="aeTargetted"></param>
        /// <returns></returns>
        public static AutomationProperty[] GetSupportedProperties(AutomationElement aeTargetted)
        {
            List<AutomationProperty> lAutomationPattern = new List<AutomationProperty>();
            return aeTargetted.GetSupportedProperties();
           
        }
    }

}

Thursday, 1 November 2012

Code Coverage Analysis

Code Coverage Analysis:
Steps to get code coverage of a module:
1.Instrument the web service binary that you want coverage on: VsInstr.exe /coverage myWebService.dll. The tool executables can be found at \Program Files (x86)\Microsoft Visual Studio 9.0\Team Tools\Performance Tools. So first you need to go to this directory on cmd line to run the command.
For e.g. VsInstr.exe /coverage C:\build\Test10_150\Release\Test.dll
2. Start the monitor for collecting coverage data:
VSPerfCmd.exe /start:coverage /output:C:\CoverageData\150.coverage /cs /user:vkumar.
4.Verify the monitor has started: VSPerfCmd.exe /status:
If you will get an output similar to below message, then the coverage monitor has started:

Microsoft (R) VSPerf Command Version 9.0.30729 x86
Copyright (C) Microsoft Corp. All rights reserved.
Process and Thread Status
============================================================
Output File Name : C:\CoverageData\150.coverage
Collection mode : COVERAGE
Maximum Processes : 64
Maximum Threads : 256
Number of Buffers : 258
Size of Buffers : 65536
============================================================
Maximum Number of Processes : 64
Number of Active Processes : 0
Global Start/Stop Count : 1
Global Suspend/Resume Count : 0
============================================================
Users with access rights to monitor:
UserName (SID)
Test\vkumar(S-1-5-21-1462854013-198636-2508-34309)
NT AUTHORITY\SYSTEM (S-1-5-18)
5. Run the scenario or test cases that will exercise the Windows Service.
Stop the Windows Service and Shutdown the monitor: VSPerfCmd.exe /shutdown. The code coverage data should be saved at C:\CoverageData\150.Coverage. Do not move the .pdb files of the instrumented EXE or DLL. Otherwise, C:\CoverageData\150.Coverage will fail to load.

Error Handling and Logging


ClassLibrary Project:    Error Handling

using System;
using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace ErrorHandling{

public class ErrorHandlingCls{
string _ModuleName,_PageURL,_EventName;
public string ModuleName {

get{
return _ModuleName;}

set{
_ModuleName =
value;}
}

public string PageURL{

get{
return _PageURL;}

set{
_PageURL =
value;}
}

public string EventName{

get{
return _EventName;}

set{
_EventName =
value;}
}

/// <summary>/// This method is for preapare the error massage on base of Exception Object/// </summary>/// <param name="serviceException"></param>/// <returns></returns>public static string CreateErrorMessage(Exception serviceException){

StringBuilder messageBuilder = new StringBuilder();
try{
messageBuilder.Append(
"The Exception is:-"); messageBuilder.Append(
"Exception :: " + serviceException.ToString());
if (serviceException.InnerException != null){
messageBuilder.Append(
"InnerException :: " + serviceException.InnerException.ToString());}

return messageBuilder.ToString();}

catch{
messageBuilder.Append(
"Exception:: Unknown Exception.");
return messageBuilder.ToString();}
}

/// <summary>/// This method is for writting the Log file with message parameter/// </summary>/// <param name="message"></param>public static void LogFileWrite(ErrorHandlingCls objErr, string message){

FileStream fileStream = null;
StreamWriter streamWriter = null;
try{
string logFilePath = "c:\\LogError\\";logFilePath = logFilePath +
"ProgramLog" + "-" + DateTime.Today.ToString("yyyyMMdd") + "." + "txt";
if (logFilePath.Equals("")) return;#region Create the Log file directory if it does not exists
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo = new FileInfo(logFilePath);logDirInfo =
new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();#endregion Create the Log file directory if it does not exists
if (!logFileInfo.Exists){
fileStream = logFileInfo.Create();
}

else{
fileStream =
new FileStream(logFilePath, FileMode.Append);}
streamWriter =
new StreamWriter(fileStream);streamWriter.WriteLine(message);
}

finally{
if (streamWriter != null) streamWriter.Close();
if (fileStream != null) fileStream.Close();}
}

/// <summary>/// This method is for writting the Log file with message parameter/// </summary>/// <param name="message"></param>public static void LogFileWrite(string message){

FileStream fileStream = null;
StreamWriter streamWriter = null;
try{
string logFilePath = "c:\\LogError\\"; logFilePath = logFilePath +
"ProgramLog" + "-" + DateTime.Today.ToString("yyyyMMdd") + "." + "txt";
if (logFilePath.Equals("")) return;#region Create the Log file directory if it does not exists
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo = new FileInfo(logFilePath);logDirInfo =
new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();#endregion Create the Log file directory if it does not exists
if (!logFileInfo.Exists){
fileStream = logFileInfo.Create();
}

else{
fileStream =
new FileStream(logFilePath, FileMode.Append);}
streamWriter =
new StreamWriter(fileStream);streamWriter.WriteLine(message);
}

finally{
if (streamWriter != null) streamWriter.Close();
if (fileStream != null) fileStream.Close();}

}
}
 
}
Default.aspx.cs
using ErrorHandling;
using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace ClientAopp{

public partial class _Default : System.Web.UI.Page{
ErrorHandlingCls objError=new ErrorHandlingCls();

private void Page_Load(object sender, System.EventArgs e){

SqlDataReader objDataReader = null;
SqlConnection myConnection = null;
try{
string sql = "server=192.168.0.1;uid=username;pwd=mypass;database=mydb";myConnection =
new SqlConnection(sql);
SqlCommand myLogin = new SqlCommand("MyStoredProcedure", myConnection);myLogin.CommandType =
CommandType.StoredProcedure;
SqlParameter myParm1 = myLogin.Parameters.Add("@Id", SqlDbType.Int);myParm1.Value = 1;
myConnection.Open();
objDataReader = myLogin.ExecuteReader(
CommandBehavior.CloseConnection);}

catch (SqlException sqlex) // Catch SQL error message{
objError.ModuleName =
"ABC";objError.PageURL =
"Default.aspx";objError.EventName =
"PageLoad";
ErrorHandlingCls.LogFileWrite(objError,ErrorHandlingCls.CreateErrorMessage(sqlex));}

catch (Exception ex) // Catch other exception message{
ErrorHandlingCls.LogFileWrite(objError, ErrorHandlingCls.CreateErrorMessage(ex));}

finally //Close DB objects{
if (objDataReader != null) objDataReader.Close();
if (myConnection != null) myConnection.Close();}
}
}
}