I have an automation project in C# that works with Microsoft Excel using WinAppDriver Release Candidate 1.2.
I have a case where I am attempting to get the number of rows that have been populated on a sheet with the code below.
public string GetLastCellBelowStartRange(string sheetName, string startRange)
{
var sheet = FindSheet(sheetName);
var nameBox = this.GetNameBox();
nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");
this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");
var endCellRange = nameBox.GetAttribute("LegacyIAccessible.Value");
return endCellRange;
}
The code successfully goes to the last cell in the workbook and nameBox is known as well as the excel driver (i.e. this.excel).
I cannot determine how to get the contents of the current cell which Inspect shows in both Value.Value and LegacyIAccessible.Value.
Does anybody know of a way to do this?
public string GetLastCellBelowStartRange(string sheetName, string startRange)
{
var sheet = FindSheet(sheetName);
var nameBox = this.GetNameBox();
nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");
this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");
string endCellRange = nameBox.GetAttribute("Value.Value").ToString();
return endCellRange;
}
Related
I have the following table :
CREATE TABLE DI_Simulation
(
[city] nvarchar(255),
[profession] nvarchar(255)
);
I load the data from an URL with a Script task where I created a class Simulation and added two string attributes. I then deserialize the downloaded JSON data and create output rows.
I specify that the output columns city and profession are of type DT_WSTR but the following characters [é,à,è,...] are always replaced...
I tried different collations on both columns but no changes were seen. I also tried forcing UTF8 conversion on the Script Task but that also didn't work.
Any suggestions ?
EDIT: I should also mention that I have other tables where the insertion is made correctly, but this one especially has this issue, which I'm thinking the Script Task has something to do with it.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
// Convert json string to .net object using the old school JavaScriptSerializer class
string Uri = "https://....";
JavaScriptSerializer serialize = new JavaScriptSerializer
{
MaxJsonLength = Int32.MaxValue,
};
var simulation = serialize.Deserialize<Simulation[]>(DownloadJson(Uri));
EDIT 2:
WebClient client = new WebClient();
Stream stream = client.OpenRead(Url);
StreamReader streamreader = new StreamReader(stream, System.Text.Encoding.GetEncoding(1252));
var ags = streamreader.ReadToEnd();
/*System.IO.File.WriteAllText(#"C:\Users\hhamdani\Desktop\Data Integration Objetcs\simulation_data.json",
ags,
System.Text.Encoding.GetEncoding(1252));*/
var simulation = serialize.Deserialize<Simulation[]>(ags);
Instead of downloading with DownloadJson, I used streamreader to get the Json Data from the URL and forced the Encoding, when I save the data on a txt file it's good, but on the Database it's the same issue.
Works fine from a script source component based on my reproduction
Setup
Table creation
A trivial table with two columns
CREATE TABLE dbo.[SO_71842511] (
[TestCase] int,
[SomeText] nvarchar(50)
)
SCR Do Unicode
Proof that we can inject unicode characters into the data flow task from a script source.
Define the Script Task as a Source. Add 2 columns to the output, one int, one DT_WSTR
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void CreateNewOutputRows()
{
Output0Buffer.AddRow();
Output0Buffer.SomeText = "e e plain";
Output0Buffer.TestCase = 0;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "é e forward";
Output0Buffer.TestCase = 1;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "à a back";
Output0Buffer.TestCase = 2;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "è e backward";
Output0Buffer.TestCase = 3;
}
}
Results
WebClient client = new WebClient();
Stream stream = client.OpenRead(Url);
StreamReader streamreader = new StreamReader(stream, System.Text.Encoding.UTF8);
var ags = streamreader.ReadToEnd();
This did the job for me.
Thanks #billinkc
Consider a text file stored in an online location that looks like this:
;aiu;
[MyEditor45]
Name = MyEditor 4.5
URL = http://www.myeditor.com/download/myeditor.msi
Size = 3023788
Description = This is the latest version of MyEditor
Feature = Support for other file types
Feature1 = Support for different encodings
BugFix = Fix bug with file open
BugFix1 = Fix crash when opening large files
BugFix2 = Fix bug with search in file feature
FilePath = %ProgramFiles%\MyEditor\MyEditor.exe
Version = 4.5
Which details information about a possible update to an application which a user could download. I want to load this into a stream reader, parse it and then build up a list of Features, BugFixes etc to display to the end user in a wpf list box.
I have the following piece of code that essentially gets my text file (first extracting its location from a local ini file and loads it into a streamReader. This at least works although I know that there is no error checking at present, I just want to establish the most efficient way to parse this first. One of these files is unlikely to ever exceed more than about 250 - 400 lines of text.
Dim UpdateUrl As String = GetUrl()
Dim client As New WebClient()
Using myStreamReader As New StreamReader(client.OpenRead($"{UpdateUrl}"))
While Not myStreamReader.EndOfStream
Dim line As String = myStreamReader.ReadLine
If line.Contains("=") Then
Dim p As String() = line.Split(New Char() {"="c})
If p(0).Contains("BugFix") Then
MessageBox.Show($" {p(1)}")
End If
End If
End While
End Using
Specifically I'm looking To collate the information about Features, BugFixes and Enhancements. Whilst I could construct what would in effect be a rather messy if statement I feel sure that there must be a more efficient way to do this , possibly involving linq. I'd welcome any suggestions.
I have added the wpf tag on the off chance that someone reading this with more experience of displaying information in wpf listboxes than I have might just spot a way to effectively define the info I'm after in such a way that it could then be easily displayed in a wpf list box in three sections (Features, Enhancements and BugFixes).
Dom, Here is an answer in C#. I will try to convert it to VB.Net momentarily. First, since the file is small, read all of it into a list of strings. Then select the strings that contain an "=" and parse them into data items that can be used. This code will return a set of data items that you can then display as you like. If you have LinqPad, you can test thecode below, or I have the code here: dotnetfiddle
Here is the VB.Net version: VB.Net dotnetfiddle
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Program
Public Sub Main()
Dim fileContent As List(Of String) = GetFileContent()
Dim dataItems = fileContent.Where(Function(c) c.Contains("=")).[Select](Function(c) GetDataItem(c))
dataItems.Dump()
End Sub
Public Function GetFileContent() As List(Of String)
Dim contentList As New List(Of String)()
contentList.Add("sb.app; aiu;")
contentList.Add("")
contentList.Add("[MyEditor45]")
contentList.Add("Name = MyEditor 4.5")
contentList.Add("URL = http://www.myeditor.com/download/myeditor.msi")
contentList.Add("Size = 3023788")
contentList.Add("Description = This is the latest version of MyEditor")
contentList.Add("Feature = Support for other file types")
contentList.Add("Feature1 = Support for different encodings")
contentList.Add("BugFix = Fix bug with file open")
contentList.Add("BugFix1 = Fix crash when opening large files")
contentList.Add("BugFix2 = Fix bug with search in file feature")
contentList.Add("FilePath = % ProgramFiles %\MyEditor\MyEditor.exe")
contentList.Add("Version = 4.5")
Return contentList
End Function
Public Function GetDataItem(value As String) As DataItem
Dim parts = value.Split("=", 2, StringSplitOptions.None)
Dim dataItem = New DataItem()
dataItem.DataType = parts(0).Trim()
dataItem.Data = parts(1).Trim()
Return dataItem
End Function
End Class
Public Class DataItem
Public DataType As String
Public Data As String
End Class
Or, in C#:
void Main()
{
List<string> fileContent = GetFileContent();
var dataItems = fileContent.Where(c => c.Contains("="))
.Select(c => GetDataItem(c));
dataItems.Dump();
}
public List<string> GetFileContent()
{
List<string> contentList = new List<string>();
contentList.Add("sb.app; aiu;");
contentList.Add("");
contentList.Add("[MyEditor45]");
contentList.Add("Name = MyEditor 4.5");
contentList.Add("URL = http://www.myeditor.com/download/myeditor.msi");
contentList.Add("Size = 3023788");
contentList.Add("Description = This is the latest version of MyEditor");
contentList.Add("Feature = Support for other file types");
contentList.Add("Feature1 = Support for different encodings");
contentList.Add("BugFix = Fix bug with file open");
contentList.Add("BugFix1 = Fix crash when opening large files");
contentList.Add("BugFix2 = Fix bug with search in file feature");
contentList.Add("FilePath = % ProgramFiles %\\MyEditor\\MyEditor.exe");
contentList.Add("Version = 4.5");
return contentList;
}
public DataItem GetDataItem(string value)
{
var parts = value.Split('=');
var dataItem = new DataItem()
{
DataType = parts[0],
Data = parts[1]
};
return dataItem;
}
public class DataItem
{
public string DataType;
public string Data;
}
The given answer only focuses on the first part, converting the data to a structure that can be shaped for display. But I think you main question is how to do the actual shaping.
I used a somewhat different way to collect the file data, using Microsoft.VisualBasic.FileIO.TextFieldParser because I think that makes coding just al little bit easier:
Iterator Function GetTwoItemLines(fileName As String, delimiter As String) _
As IEnumerable(Of Tuple(Of String, String))
Using tfp = New TextFieldParser(fileName)
tfp.TextFieldType = FieldType.Delimited
tfp.Delimiters = {delimiter}
tfp.HasFieldsEnclosedInQuotes = False
tfp.TrimWhiteSpace = False
While Not tfp.EndOfData
Dim arr = tfp.ReadFields()
If arr.Length >= 2 Then
Yield Tuple.Create(arr(0).Trim(), String.Join(delimiter, arr.Skip(1)).Trim())
End If
End While
End Using
End Function
Effectively the same thing happens as in your code, but taking into account Andrew's keen caution about data loss: a line is split by = characters, but the second field of a line consists of all parts after the first part with the delimiter re-inserted: String.Join(delimiter, arr.Skip(1)).Trim().
You can use this function as follows:
Dim fileContent = GetTwoItemLines(file, "=")
For display, I think the best approach (most efficient in terms of lines of code) is to group the lines by their first items, removing the numeric part at the end:
Dim grouping = fileContent.GroupBy(Function(c) c.Item1.TrimEnd("0123456789".ToCharArray())) _
.Where(Function(k) k.Key = "Feature" OrElse k.Key = "BugFix" OrElse k.Key = "Enhancement")
Here's a Linqpad dump (in which I took the liberty to change one item a bit to demonstrate the correct dealing with multiple = characters:
You could do it with Regular Expressions:
Imports System.Text.RegularExpressions
Private Function InfoReader(ByVal sourceText As String) As List(Of Dictionary(Of String, String()))
'1) make array of fragments for each product info
Dim products = Regex.Split(sourceText, "(?=\[\s*\w+\s*])")
'2) declare variables needed ahead
Dim productProperties As Dictionary(Of String, String)
Dim propertyNames As String()
Dim productGroupedProperties As Dictionary(Of String, String())
Dim result As New List(Of Dictionary(Of String, String()))
'2) iterate along fragments
For Each product In products
'3) work only in significant fragments ([Product]...)
If Regex.IsMatch(product, "\A\[\s*\w+\s*]") Then
'4) make array of property lines and extract dictionary of property/description
productProperties = Regex.Split(product, "(?=^\w+\s*=)", RegexOptions.Multiline).Where(
Function(s) s.Contains("="c)
).ToDictionary(
Function(s) Regex.Match(s, "^\w+(?=\s*=)").Value,
Function(s) Regex.Match(s, "(?<==\s+).*(?=\s+)").Value)
'5) extract distinct property names, ignoring numbered repetitions
propertyNames = productProperties.Keys.Select(Function(s) s.TrimEnd("0123456789".ToCharArray)).Distinct.ToArray
'6) make dictionary of distinctProperty/Array(Of String){description, description1, ...}
productGroupedProperties = propertyNames.ToDictionary(
Function(s) s,
Function(s) productProperties.Where(
Function(kvp) kvp.Key.StartsWith(s)
).Select(
Function(kvp) kvp.Value).ToArray)
'7) enlist dictionary to result
result.Add(productGroupedProperties)
End If
Next
Return result
End Function
I'm looking to see if the SQL Database behind TFS2015 (or any version of TFS, in this case 2015 or 2010) stores the full file path for a file. There is information that we include in the Project folder (namely the version number) and while I realize there are better ways to track this information, we have a lot of legacy data that only has the version stored within this path. I want to pull the data into Crystal Reports to strip off the information and then use it.
You want to get a list of folders in TFS Source Control, instead of querying in database, we recommend to achieve it programmatically. The blog below and the sample code associated with it will do what you want:
http://blogs.microsoft.co.il/blogs/shair/archive/2009/02/26/tfs-api-part-16-mapping-source-control-using-versioncontrolserver.aspx
Also, check the code snippet in this case, which should help you:
ICommonStructureService structureService = (ICommonStructureService)Tfscollection.GetService(typeof(ICommonStructureService));
ProjectInfo[] projects = structureService.ListAllProjects();
//combo_projects.ItemsSource = projects;
////Create VersionControlServer object from TFS
//sourceControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
RecursionType recursion = RecursionType.OneLevel;
Item[] items = null;
string path = "$/" + projects[0].Name;//"$/TescoPOC/FetchStoryfromTFS";
ItemSet itemSet = versionControl.GetItems(path, recursion);
items = itemSet.Items;
//Dictionary<string, int> FolderListName = new Dictionary<string, int>();
List<string> FolderListName = new List<string>();
foreach (Item keyItem in items)
{
char[] charSeparators = new char[] { '/' };
//Using split to isolated the Project Name and the File Name
string[] ss = keyItem.ServerItem.Split(charSeparators, StringSplitOptions.None);
if (keyItem != items[0])
{
string filename = keyItem.ServerItem.Replace(path + "/", string.Empty);
if (filename != "BuildProcessTemplates")
{
FolderListName.Add(filename);
//if (FolderListName.ContainsKey(filename))
// FolderListName[filename] = FolderListName[filename] + 1;
//else
// FolderListName.Add(filename, 1);
}
}
}
I am using SMS caster to send sms.It has an option to Import csv files.
Now I want to dynamically create csv file of CellNo column of Person table from Visual Studio 2010 connected SQL Server 2008.So that I click on a button and it creates a csv file which I can then access from my software SMSCaster to send sms.
The solutions available are either manual-based or if some query is provided it requires Microsoft OLEDB.....so is there any simple query to convert queryresult into .csv file?
Try this :
Namespace : System.IO;
var _lines = new List<string>();
for(int _i=0;i<gridview1.rows.count;_i++)
{
string[] _mobileNos = gridView1.rows[_i].cells[mobilecolumn index in gridview].text;
var header = string.Join(",", _mobileNos);
_lines.Add(header);
}
File.WriteAllLines("FileName.csv",_lines);
Here is the solution that worked:
public void gridtoCSVFILE()
{
string ing;
List<string> lines = new List<string>();
for (int i = 0; i < gvStudCellNo.Rows.Count; i++)
{
ing = gvStudCellNo.Rows[i].Cells[0].Value.ToString();
lines.Add(ing);
File.WriteAllLines("StudentsCellNo.csv", lines);
}
}
//it will create csv file in your bin folder...also it automatically replaces each new file with the old one
Even though I set the parameters in the code, I keep getting that a parameter must be set error. I have run profiler to see what is being passed to SSRS, and profiler indicates that parameters = null. Yet all of them are set in code. Anyone have any ideas? The code is as follows:
string strReportPath;
Microsoft.Reporting.WinForms.ReportParameter prmFranchiseOID;
Microsoft.Reporting.WinForms.ReportParameter prmSchoolOID;
Microsoft.Reporting.WinForms.ReportParameter prmRoomOID;
Microsoft.Reporting.WinForms.ReportParameter prmOrderDate;
Microsoft.Reporting.WinForms.ReportParameter prmLanguage;
Microsoft.Reporting.WinForms.ReportParameter prmContrast;
List<Microsoft.Reporting.WinForms.ReportParameter> prms = new List<ReportParameter>();
byte[] pdf = null;
try
{
prmFranchiseOID = new Microsoft.Reporting.WinForms.ReportParameter("FranchiseOID", "8D126AA2-2E5C-4B2B-8D19-167027F8C7D8");
prmSchoolOID = new Microsoft.Reporting.WinForms.ReportParameter("SchoolOID", "96FEE335-0CB9-413A-9DDC-78F8C67770C4");
prmRoomOID = new Microsoft.Reporting.WinForms.ReportParameter("RoomOID", "null");
prmOrderDate = new Microsoft.Reporting.WinForms.ReportParameter("OrderDate", DateTime.Now.AddDays(1).Date.ToString());
prmLanguage = new Microsoft.Reporting.WinForms.ReportParameter("Language", "en-CA");
prmContrast = new Microsoft.Reporting.WinForms.ReportParameter("Contrast", "true");
prms.Add(prmFranchiseOID);
prms.Add(prmSchoolOID);
prms.Add(prmRoomOID);
prms.Add(prmOrderDate);
prms.Add(prmLanguage);
prms.Add(prmContrast);
// Note: For Account Holder users, their specified report folder is "/LunchLady/User".
strReportPath = "/LunchLady/Franchise/" + urlReportName;
try
{
rvReport.ServerReport.ReportServerUrl = new System.Uri("https://testsql.thelunchlady.ca/ReportServer");
rvReport.ServerReport.ReportPath = strReportPath;
rvReport.ServerReport.SetParameters(prms);
string ReportType = "PDF";
pdf = rvReport.ServerReport.Render(ReportType);
Thanks
Having done extensive programming on the SSRS controls in ASP.NET, one thing that I've found which may or may not be relevant for WinForms is that each SSRS parameter is actually a collection in itself (due to parameters being able to be multi-select).
So what worked for us is that the collection (prms in your case) was of type
List<IEnumerable<ReportViewer.ReportParameter>> prms
Also when adding parameters using the SetParameters function we added them one at a time:
for (int i = 0; i < prms.Count; i++)
{
rvReport.ServerReport.SetParameters(prms[i]);
}
Again, this is what worked for us in ASP.NET, could be something for you to try.