I have an invoice with multiple lines that I want to consolidate into one line. It takes the and iterates through each . It sums each to a variable. After the loop, it should create a new line on the invoice and delete the others.
I keep getting a "TxnLineID: required field is missing" even though I am providing it as "-1" for a new line:
private static void Main(string[] args)
{
// creates the session manager object using QBFC
var querySessionManager = new QBSessionManager();
// want to know if a session has begun so it can be ended it if an error happens
var booSessionBegun = false;
try
{
// open the connection and begin the session with QB
querySessionManager.OpenConnection("", "Test Connection");
querySessionManager.BeginSession("", ENOpenMode.omDontCare);
// if successful then booSessionBegin = True
booSessionBegun = true;
// Get the RequestMsgSet based on the correct QB Version
var queryRequestSet = GetLatestMsgSetRequest(querySessionManager);
// Initialize the message set request object
queryRequestSet.Attributes.OnError = ENRqOnError.roeStop;
// QUERY RECORDS **********************
// appendInvoiceQuery to request set
// only invoices that start with the consulting invoice prefix
// include all of the line items
// only unpaid invoices
var invoiceQ = queryRequestSet.AppendInvoiceQueryRq();
invoiceQ.ORInvoiceQuery.InvoiceFilter.ORRefNumberFilter.RefNumberFilter.MatchCriterion.SetValue(ENMatchCriterion.mcStartsWith);
invoiceQ.ORInvoiceQuery.InvoiceFilter.ORRefNumberFilter.RefNumberFilter.RefNumber.SetValue("ML-11");
invoiceQ.ORInvoiceQuery.InvoiceFilter.PaidStatus.SetValue(ENPaidStatus.psNotPaidOnly);
invoiceQ.IncludeLineItems.SetValue(true);
// DELETE INVOICE ***********************************
// var deleteI = queryRequestSet.AppendTxnDelRq();
// deleteI.TxnDelType.SetValue(ENTxnDelType.tdtInvoice);
// deleteI.TxnID.SetValue("3B57C-1539729221");
// Do the request and get the response message set object
var queryResponseSet = querySessionManager.DoRequests(queryRequestSet);
// Uncomment the following to view and save the request and response XML
var requestXml = queryRequestSet.ToXMLString();
// Console.WriteLine(requestXml);
SaveXML(requestXml, 1);
var responseXml = queryResponseSet.ToXMLString();
// Console.WriteLine(responseXml);
SaveXML(responseXml, 2);
// Get the statuscode of the response to proceed with
var respList = queryResponseSet.ResponseList;
var ourResp = respList.GetAt(0);
var statusCode = ourResp.StatusCode;
// Test what the status code
if (statusCode == 0)
{
// Parse the string into an XDocument object
var xmlDoc = XDocument.Parse(responseXml);
// Set the xmlDoc root
var xmlDocRoot = xmlDoc.Root.Element("QBXMLMsgsRs")
.Element("InvoiceQueryRs")
.Elements("InvoiceRet");
var i = 1;
// Iterate through the elements to get values and do some logic
foreach (var invoiceElement in xmlDocRoot)
{
// Create connection to update
var updateSessionManager = new QBSessionManager();
updateSessionManager.OpenConnection("", "Test Connection");
updateSessionManager.BeginSession("", ENOpenMode.omDontCare);
// Make the request set for updates
var updateRequestSet = GetLatestMsgSetRequest(updateSessionManager);
updateRequestSet.Attributes.OnError = ENRqOnError.roeStop;
// Set the variables required to edit a file
var txnId = (string) invoiceElement.Element("TxnID");
var editSequence = (string) invoiceElement.Element("EditSequence");
var xmlLineItemRoot = invoiceElement.Elements("InvoiceLineRet");
var feeAmount = 0.0f;
foreach (var invoiceLineItemElement in xmlLineItemRoot)
{
if (invoiceLineItemElement.Element("ItemRef").Element("FullName").Value == "Consulting Fees:Consulting")
{
feeAmount = float.Parse(invoiceLineItemElement.Element("Amount").Value) + (float) feeAmount;
}
}
//// UPDATING RECORDS ******************************
//// TxnID and EditSequence required
var invoiceM = updateRequestSet.AppendInvoiceModRq();
invoiceM.TxnID.SetValue(txnId);
invoiceM.EditSequence.SetValue(editSequence);
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.TxnLineID.SetValue("-1");
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.ItemRef.FullName.SetValue("Consulting Fees:Consulting");
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.Amount.SetValue((double)feeAmount);
updateSessionManager.DoRequests(updateRequestSet);
i++;
updateSessionManager.EndSession();
updateSessionManager.CloseConnection();
}
}
// end and disconnect after done
querySessionManager.EndSession();
booSessionBegun = false;
querySessionManager.CloseConnection();
}
catch (Exception e)
{
// if it couldn't connect then display a message saying so and make sure to EndSession/CloseConnection
Console.WriteLine(e.Message.ToString() + "\nStack Trace: \n" + e.StackTrace + "\nExiting the application");
if (booSessionBegun)
{
querySessionManager.EndSession();
querySessionManager.CloseConnection();
}
}
}
Furthermore, I want it to remove the lines from the invoice that were used in the sum. I've read conflicting information on how to do this.
One camp says, don't specify those lines and it will erase them when the updateRequestSet is executed. Another contradicts by saying that not specifying them, it will retain them. Can someone please clear this up. I haven't gotten far enough to test, however.
Oh and here is the entirety of the error:
InvoiceMod
ORInvoiceLineModList:
element(2) - InvoiceLineMod:
TxnLineID: required field is missing
End of InvoiceLineMod
End of ORInvoiceLineModList
End of InvoiceMod
Stack Trace:
at Interop.QBFC13.IQBSessionManager.DoRequests(IMsgSetRequest request)
at ConsolidateInvoiceLineItems.Program.Main(String[] args) in C:\qb\QuickBooks\ConsolidateInvoiceLineItems\ConsolidateInvoiceLineItems\Program.cs:line 226
Exiting the application
Wish I could take credit for this, but actually got help from the Intuit Developers forum.
Need to change the multiple Append() to the following:
var invoiceModLineItems = invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod;
invoiceModLineItems.TxnLineID.SetValue("-1");
invoiceModLineItems.ItemRef.FullName.SetValue("Consulting Fees:Consulting");
invoiceModLineItems.Amount.SetValue((double)feeAmount);
I think I've come across a bug in the CreateFolder command in the Reportingservices2010 SOAP API
The test scenario is I'm trying to create a folder (named Sales Dashboard) in the same Parent folder (lets say Sales) as a report also named Sales Dashboard.
The command completed with the "AlreadyExists" Exception when the folder does not already exist. It looks like the method isn't checking the catalog item type.
Here's my code:
public static void createFolders(string targetURL, string folderName, string parentPath, string description, string visible)
{
//Build Authentication
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = targetURL;
//Declare properties
Property descriptionProp = new Property();
Property visibleProp = new Property();
Property[] props = new Property[2];
descriptionProp.Name = "Description";
descriptionProp.Value = description;
visibleProp.Name = "Visible";
visibleProp.Value = visible;
props[0] = descriptionProp;
props[1] = visibleProp;
try
{
rs.CreateFolder(folderName, parentPath, props);
}
catch(Exception ex)
{
if(ex.Message.Contains("AlreadyExists"))
{
//do nothing?
}
else
{
throw;
}
}
}
I wanted to see if I could contribute a fix but there's no GitHub repo for the C# SSRS stuff. Any thought's on a workaround?
The API is returning the correct error since this is a restriction of Reporting Services in general: items within the same folder must have unique names (regardless of item type).
I try to create a new EPT (project server 2013) using C# CSOM library.
But It has following error occurred.
"PJClientCallableException: EnterpriseProjectTypeInvalidCreatePDPUid"
Couple of article tell to change the "IsCreate=true". But it does not success for me. Here is the code what I have done.
public void CreateEnterpriseProjectType(Guid eptGuid, string eptName, string eptDescription)
{
ProjectContext pwaContext = new ProjectContext(this.PWA_URL);
EnterpriseProjectTypeCreationInformation eptData = new EnterpriseProjectTypeCreationInformation();
eptData.Id = eptGuid;
eptData.Name = eptName;
eptData.Description = eptDescription;
eptData.IsDefault = false;
eptData.IsManaged = true;
eptData.WorkspaceTemplateName = "PROJECTSITE#0";
eptData.ProjectPlanTemplateId = Guid.Empty;
eptData.WorkflowAssociationId = Guid.Empty;
eptData.Order = 4;
List<ProjectDetailPageCreationInformation> projectDetailPages = new
List<ProjectDetailPageCreationInformation>() {
new ProjectDetailPageCreationInformation() {
Id = pwaContext.ProjectDetailPages[1].Id, IsCreate = true }
};
eptData.ProjectDetailPages = projectDetailPages;
pwaContext.Load(pwaContext.EnterpriseProjectTypes);
pwaContext.ExecuteQuery();
EnterpriseProjectType newEpt = pwaContext.EnterpriseProjectTypes.Add(eptData);
pwaContext.EnterpriseProjectTypes.Update();
pwaContext.ExecuteQuery();
}
Can anyone explain the issue or provide the working code part.
I would like to suggest the following:
Define an enterprise project type:
string basicEpt = "Enterprise Project"; // Basic enterprise project type.
int timeoutSeconds = 10; // The maximum wait time for a queue job, in seconds.
And then, when you create the new project, work like this:
ProjectCreationInformation newProj = new ProjectCreationInformation();
newProj.Id = Guid.NewGuid();
newProj.Name = "Project Name";
newProj.Description = "Test creating a project with CSOM";
newProj.Start = DateTime.Today.Date;
// Setting the EPT GUID is optional. If no EPT is specified, Project Server
// uses the default EPT.
newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt);
PublishedProject newPublishedProj = projContext.Projects.Add(newProj);
QueueJob qJob = projContext.Projects.Update();
// Calling Load and ExecuteQuery for the queue job is optional.
// projContext.Load(qJob);
// projContext.ExecuteQuery();
JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds);
When the last line of that piece of code ends, the project must be created and published in order to define tasks or whatever.
I don't know what is happening to your code, seems great.
Hope it helps to you,
After trying out several solutions, I am in desperate need for help.
I tried several approaches, before finally copying and still being stuck with the solution from Getting full contents of a Datagrid using UIAutomation.
Let's talk code, please consider the comments:
// Get Process ID for desired window handle
uint processID = 0;
GetWindowThreadProcessId(hwnd, out processID);
var desktop = AutomationElement.RootElement;
// Find AutomationElement for the App's window
var bw = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ProcessIdProperty, (int)processID));
// Find the DataGridView in question
var datagrid = bw.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "dgvControlProperties"));
// Find all rows from the DataGridView
var loginLines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));
// Badumm Tzzz: loginLines has 0 items, foreach is therefore not executed once
foreach (AutomationElement loginLine in loginLines)
{
var loginLinesDetails = loginLine.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));
for (var i = 0; i < loginLinesDetails.Count; i++)
{
var cacheRequest = new CacheRequest
{
AutomationElementMode = AutomationElementMode.None,
TreeFilter = Automation.RawViewCondition
};
cacheRequest.Add(AutomationElement.NameProperty);
cacheRequest.Add(AutomationElement.AutomationIdProperty);
cacheRequest.Push();
var targetText = loginLinesDetails[i].FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "TextBlock"));
cacheRequest.Pop();
var myString = targetText.Cached.Name;
}
}
I can neither fetch a GridPattern, nor a TablePattern instance from datagrid, both results in an exception:
GridPattern gridPattern = null;
try
{
gridPattern = datagrid.GetCurrentPattern(GridPattern.Pattern) as GridPattern;
}
catch (InvalidOperationException ex)
{
// It fails!
}
TablePattern tablePattern = null;
try
{
tablePattern = datagrid.GetCurrentPattern(TablePattern.Pattern) as TablePattern;
}
catch (InvalidOperationException ex)
{
// It fails!
}
The rows were added to the DataGridView beforehand, like this:
dgvControlProperties.Rows.Add(new object[] { false, "Some Text", "Some other text" });
I am compiling to .Net Framework 4.5. Tried both regular user rights and elevated admin rights for the UI Automation client, both yielded the same results described here.
Why does the DataGridView return 0 rows?
Why can't I get one of the patterns?
Kudos for helping me out!
Update:
James help didn't to the trick for me. The following code tough returns all rows (including the headers):
var rows = dataGrid.FindAll(TreeScope.Children, PropertyCondition.TrueCondition);
Header cells can then be identified by their ControlType of ControlType.Header.
The code that you are copying is flawed. I just tested this scenario with an adaptation of this sample program factoring in your code above, and it works.
The key difference is that the code above is using TreeScope.Children to grab the datagrid element. This option only grabs immediate children of the parent, so if your datagrid is nested it's not going to work. Change it to use TreeScope.Descendants, and it should work as expected.
var datagrid = bw.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "dgvControlProperties"));
Here is a link to how the various Treescope options behave. Also, I don't know how your binding the rows to the grid, but I did it like this in my test scenario and it worked flawlessly.
Hopefully this helps.
public class DataObject
{
public string FieldA { get; set; }
public string FieldB { get; set; }
public string FieldC { get; set; }
}
List<DataObject> items = new List<DataObject>();
items.Add(new DataObject() {FieldA="foobar",FieldB="foobar",FieldC="foobar"});
items.Add(new DataObject() { FieldA = "foobar", FieldB = "foobar", FieldC = "foobar" });
items.Add(new DataObject() { FieldA = "foobar", FieldB = "foobar", FieldC = "foobar" });
dg.ItemsSource = items;
Your code looks fine though this could be a focus issue.
Even though you are getting a reference to these automation element objects you should set focus on them (using the aptly named SetFocus method) before using them.
Try:
var desktop = AutomationElement.RootElement;
desktop.SetFocus();
// Find AutomationElement for the App's window
var bw = desktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ProcessIdProperty, (int)processID));
and if that does not work try explicitly focusing on the dataGrid prior to calling "FindAll" on it i.e.
datagrid.SetFocus()
Why does the DataGridView return 0 rows?
The DataGridViewRows have a ControlType of ControlType.Custom. So I modified the line
// Find all rows from the DataGridView
var loginLines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));
To
var loginLines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));
That gets you all the rows within the DataGridView. But your code has that within the loop.
What pattern is supported by DataGridView (not DataGrid)?
LegacyIAccessiblePattern. Try this-
LegacyIAccessiblePattern legacyPattern = null;
try
{
legacyPattern = datagrid.GetCurrentPattern(LegacyIAccessiblePattern.Pattern) as LegacyIAccessiblePattern;
}
catch (InvalidOperationException ex)
{
// It passes!
}
As I commented on #James answer, there is no support for UIA for DataGridView (again, not DataGrid).
If you search in google with terms: "UI Automation DataGridView" the first result has an incomplete answer. Mike replies with what provider class (Obviously one that extends DataGridView)to create within the source, unfortunately I have no clue as to how to make UIA load that class a provider. If anyone can shed some clues, Phil and I will be extremely pleased!
EDIT
Your DataGridView should implement the interfaces in that link above. Once you do that the ControlType of Row will be ControlType.DataItem instead of ControlType.Custom. You can then use it how you'd use a DataGrid.
EDIT
This is what I ended up doing -
Creating a Custom DataGridView like below. Your datagridview could subclass this too. That will make it support ValuePattern and SelectionItemPattern.
public class CommonDataGridView : System.Windows.Forms.DataGridView,
IRawElementProviderFragmentRoot,
IGridProvider,
ISelectionProvider
{.. }
The complete code can be found # this msdn link.
Once I did that, I played a bit with visualUIVerify source. Here is how I can access the gridview's cell and change the value. Also, make note of the commented code. I didn't need that. It allows you to iterate through rows and cells.
private void _automationElementTree_SelectedNodeChanged(object sender, EventArgs e)
{
//selected currentTestTypeRootNode has been changed so notify change to AutomationTests Control
AutomationElementTreeNode selectedNode = _automationElementTree.SelectedNode;
AutomationElement selectedElement = null;
if (selectedNode != null)
{
selectedElement = selectedNode.AutomationElement;
if (selectedElement.Current.ClassName.Equals("AutomatedDataGrid.CommonDataGridViewCell"))
{
if(selectedElement.Current.Name.Equals("Tej")) //Current Value
{
var valuePattern = selectedElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
valuePattern.SetValue("Jet");
}
//Useful ways to get patterns and values
//System.Windows.Automation.SelectionItemPattern pattern = selectedElement.GetCurrentPattern(System.Windows.Automation.SelectionItemPattern.Pattern) as System.Windows.Automation.SelectionItemPattern;
//var row = pattern.Current.SelectionContainer.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewRow", PropertyConditionFlags.IgnoreCase));
//var cells = row.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewCell", PropertyConditionFlags.IgnoreCase));
//foreach (AutomationElement cell in cells)
//{
// Console.WriteLine("**** Printing Cell Value **** " + cell.Current.Name);
// if(cell.Current.Name.Equals("Tej")) //current name
// {
// var valuePattern = cell.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
// valuePattern.SetValue("Suraj");
// }
//}
//Select Row
//pattern.Select();
//Get All Rows
//var arrayOfRows = pattern.Current.SelectionContainer.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewRow", PropertyConditionFlags.IgnoreCase));
//get cells
//foreach (AutomationElement row in arrayOfRows)
//{
// var cell = row.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewCell", PropertyConditionFlags.IgnoreCase));
// var gridItemPattern = cell.GetCurrentPattern(GridItemPattern.Pattern) as GridItemPattern;
// // Row number.
// Console.WriteLine("**** Printing Row Number **** " + gridItemPattern.Current.Row);
// //Cell Automation ID
// Console.WriteLine("**** Printing Cell AutomationID **** " + cell.Current.AutomationId);
// //Cell Class Name
// Console.WriteLine("**** Printing Cell ClassName **** " + cell.Current.ClassName);
// //Cell Name
// Console.WriteLine("**** Printing Cell AutomationID **** " + cell.Current.Name);
//}
}
}
_automationTests.SelectedElement = selectedElement;
_automationElementPropertyGrid.AutomationElement = selectedElement;
}
Hopefully this helps.
I run into this problem too, after researching, i figured out that you can only access data grid view with LegacyIAccessible. However, .NET does not support this. So, here are the steps:
there are 2 versions of UIA: managed version and unmanaged version (native code). In some cases, the unmanaged version can do what the managed version can't.
=> as said here, using tblimp.exe (go along with Windows SDK) to generate a COM wrapper around the unmanaged UIA API, so we can call from C#.
I have done it here
we can use this to access DataGridView now but with very limited data, you can use Inspect.exe to see.
The code is:
using InteropUIA = interop.UIAutomationCore;
if (senderElement.Current.ControlType.Equals(ControlType.Custom))
{
var automation = new InteropUIA.CUIAutomation();
var element = automation.GetFocusedElement();
var pattern = (InteropUIA.IUIAutomationLegacyIAccessiblePattern)element.GetCurrentPattern(10018);
Logger.Info(string.Format("{0}: {1} - Selected", pattern.CurrentName, pattern.CurrentValue));
}
I have C# using the CRM RetrieveMultiple web service to update Lead entity records. Everything works perfectly 80% of the time.
About 20% of the time, it fails. On failure, here is the SoapException Detail.InnerText property:
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Here is the code that makes the web service call:
local.mycompany.crm.CrmAuthenticationToken token;
local.mycompany.crm.CrmService service;
local.mycompany.crm.lead tourRequestLead = new local.mycompany.crm.lead();
tourRequestLead.emailaddress1 = "xxxxxxx#mycompany.com";
token = new local.mycompany.crm.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "mycompanyCRM";
service = new local.mycompany.crm.CrmService();
service.CrmAuthenticationTokenValue = token;
service.UnsafeAuthenticatedConnectionSharing = true;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.Url = "http://crm.mycompany.local/mscrmservices/2007/crmservice.asmx";
// Create the ColumnSet that indicates the properties to be retrieved.
local.mycompany.crm.ColumnSet cols = new local.mycompany.crm.ColumnSet();
// Set the properties of the ColumnSet.
cols.Attributes = new string[] { "emailaddress1", "new_initialtourrequestlistingid", "description" };
// Create the ConditionExpression.
local.mycompany.crm.ConditionExpression condition = new local.mycompany.crm.ConditionExpression();
// Set the condition for the retrieval to be when the contact's address' city is Sammamish.
condition.AttributeName = "emailaddress1";
condition.Operator = local.mycompany.crm.ConditionOperator.Equal;
condition.Values = new string[] { tourRequestLead.emailaddress1 };
// Create the FilterExpression.
local.mycompany.crm.FilterExpression filter = new local.mycompany.crm.FilterExpression();
// Set the properties of the filter.
filter.FilterOperator = local.mycompany.crm.LogicalOperator.And;
filter.Conditions = new local.mycompany.crm.ConditionExpression[] { condition };
// Create the QueryExpression object.
local.mycompany.crm.QueryExpression query = new local.mycompany.crm.QueryExpression();
// Set the properties of the QueryExpression object.
query.EntityName = local.mycompany.crm.EntityName.lead.ToString();
query.ColumnSet = cols;
query.Criteria = filter;
// Retrieve the leads.
local.mycompany.crm.BusinessEntityCollection retrieveLeads = null;
try
{
retrieveLeads = service.RetrieveMultiple(query);
}
catch (Exception exp)
{
Console.WriteLine("RetrieveMultiple " + exp);
CountError += 1;
}
if ((retrieveLeads != null) && (retrieveLeads.BusinessEntities.Length > 0))
{
try
{
foreach (local.mycompany.crm.lead rlead in retrieveLeads.BusinessEntities)
{
string strNotes = rlead.description;
}
}
catch (Exception exp)
{
Console.WriteLine("Reard " + exp);
CountError += 1;
}
}
I have pretty much ruled out that it is a problem with the VPN or CRM 4.0 itself.,,I have not been able to reproduce the error in a controlled way. Please advise if you have tips, ideas, or solutions!
Thanks
How often are you retrieving the records? Are you also updating them afterwards? Under high volume (and with default IIS/Windows Server settings) I have seen the server run out of available ports, since with every call to the CRM Service (even using the same service object) CRM opens up another port.