I'm trying to automate a website, and I have the following piece of code to change the value of a dropdown (select):
private bool ChangeElementSelection(mshtml.IHTMLDocument3 document, string id, string value)
{
var el = document.getElementById(id);
if (el != null)
{
log.Write("Setting HTML element " + id + " value to " + value + " (by ID)");
el.setAttribute("value", value);
var el3 = (el as IHTMLElement3);
el3.FireEvent("onchange");
return true;
}
log.Write("Could not find HTML element " + id + " (by ID)");
return false;
}
The website I am visiting uses JQuery to catch the "change" event for the select element. It does not expect any parameters. Yet the script is not triggered. Why ?
Related
I'm trying to extract the values of a SharePoint list to use with Revit to update the status parameters of some elements and after many tries I can connect and get the values if I know the keys for the dictionary inside every ListItem, but there are many problems with this approach.
The first one is the need to know the keys, sometimes the key is changed because of encoding, It would be more productive for me to get all the list values at one time. I tried to use a GetDataTable like some tutorials, but it appears that this don't work with the client.
The second is sometimes I can't get the value of the List but a description of the value, like "Microsoft.SharePoint.Client.FieldLookupValue".
Can someone help me with this issue? Bellow is the code I'm using.
using Microsoft.SharePoint.Client;
using System;
using System.Security;
namespace ConsoleTESTES
{
class Program
{
static void Main(string[] args)
{
string username = "USERNAME";
string siteURL = "SITEURL";
SecureString password = GetPassword();
GetAllWebProperties(siteURL, username, password);
}
public static void GetAllWebProperties(string siteURL, string username, SecureString password)
{
using (var context = new ClientContext(siteURL))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
// Assume the web has a list named "Announcements".
//List lista = context.Web.Lists.GetByTitle("Lista teste");
List lista = context.Web.Lists.GetByTitle("LIST");
// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"
// so that it grabs all list items, regardless of the folder they are in.
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = lista.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
context.Load(items);
context.ExecuteQuery();
//GET VALUES FROM LISTITEM
foreach (ListItem listItem in items)
{
Console.WriteLine(listItem["Setor"] + " " + "|" + " "
+ listItem["LocalServico"] + " " + "|" + " "
+ listItem["Equipe"] + " " + "|" + " "
+ listItem["Confeccao"]);
}
Console.ReadLine();
}
}
public static SecureString GetPassword()
{
ConsoleKeyInfo info;
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey();
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
}
You could get the values from the fields collection, but be warned that some special types of fields might require special treatment for the values and that you might not need to get all the values from the server (you can probably reduce your payload):
var items = lista.GetItems(query);
var fields = list.Fields;
var fieldsToIgnore = new[] { "ContentType", "Attachments" };
context.Load(items);
context.Load(fields);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
foreach (Field field in fields)
{
if (!fieldsToIgnore.Contains(fld.InternalName))
Console.WriteLine(item[field.InternalName]);
}
}
There are some fields that might not be loaded by default of that you might not need, so I have included the fieldsToIgnore to make your test easier.
After some search I found this solution to my FieldLookUpTable, to avoid errors if the item is null I added a if statement, but I could access the value with (listItem["Setor"] as FieldLookupValue).LookupValue. Here my messy code to check if is a LookupValue and get the value. Now I need to implement Pedro's solution to get all the values without the need to write everyone.
String setor = "";
String localServico = "";
String confeccao = "";
if (listItem["Setor"] != null && listItem["Setor"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
setor = (listItem["Setor"] as FieldLookupValue).LookupValue;
}
else if (listItem["Setor"] != null && listItem["Setor"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
setor = listItem["Setor"].ToString();
}
if (listItem["LocalServico"] != null && listItem["LocalServico"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
localServico = (listItem["LocalServico"] as FieldLookupValue).LookupValue;
}
else if (listItem["LocalServico"] != null && listItem["LocalServico"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
localServico = listItem["LocalServico"].ToString();
}
if (listItem["Confeccao"] != null && listItem["Confeccao"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
confeccao = (listItem["Confeccao"] as FieldLookupValue).LookupValue;
}
else if (listItem["Confeccao"] != null && listItem["Confeccao"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
confeccao = listItem["Confeccao"].ToString();
}
Console.WriteLine(setor + " " + "|" + " "
+ localServico + " " + "|" + " "
+ confeccao);
Calling Thickbox popup from Parent Page ServiceTicket.aspx like this :
function OpenCustomerView(companyID, accountID) {
var e = document.getElementById('<%= txtAccountID.ClientID %>');
var custId = e.value;
**var url = "CustomerSearch.aspx?custid=" + custId + "&TB_iframe=true&width=1200&height=800";**
**tb_show("Customer Search", url);**
}
And on Child Popup Window CustomerSearch.aspx i m using this code to close the popup and sending values back to parent :
function CloseDialog(tanksize,companyID, accountID, address, serviceContract, cod, divisionId) {
**var url = 'ServiceTicket.aspx?CompanyID=' + companyID + '&AccountID=' + accountID + '&Address=' + address.replace('#', '%23') + '&TankSize=' + tanksize + '&divisionId=' + divisionId;**
}
in above line var url='ServiceTicket.aspx?CompanyID=' this is how i m passing values to parent window.
Handling values on Parent Page with C# Code behind
if (Request.QueryString["companyID"] != null && Request.QueryString["companyID"] != "")
{
short companyID = Convert.ToInt16(Request.QueryString["companyID"]);
}
So I need help in closing this child popup from function CloseDialog and passing values to parent by that var url used in the closedialog function.Please guide me or share your code...
Not sure if this will work or not as it was a way long back I did something like this for similar issue. Just give try and see if works out else notify here will update again.
function CloseDialog(tanksize,companyID, accountID, address, serviceContract, cod, divisionId) {
tb_remove();
var url = 'ServiceTicket.aspx?CompanyID=' + companyID + '&AccountID=' + accountID + '&Address=' + address.replace('#', '%23') + '&TankSize=' + tanksize + '&divisionId=' + divisionId;
window.parent.location.href = url;
}
I am fairly new to C# and I have written several functioning programs, but all of them have been single thread applications. This is my first multi-threaded application and I am struggling to resolve this "Cross-thread operation not valid: Control 'cbLogType' accessed from a thread other than the one it was created on" error. My application searches Windows Event viewer for a user defined Event ID in a user defined Event Log Source(cbLogType). I am using a backgroundworker process to do all the work and I am using the worker.reportprogress to update a label, however, I receive the above error when debugging. I have tried several Invoke methods, but none seem to resolve my error. I have also tried removing the combobox and setting the Log Source directly in the code, which works to an extent, but still fails. I have included my code and any help would be greatly appreciated. I suspect that I might not be using the Invoke method correctly. Thanks in advance!
CODE:
private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
{
if (File.Exists(#"C:\Events.log"))
MessageBox.Show("File 'Events.log' already exists. All new data will be appended to the log file!", "Warning!");
string message = string.Empty;
string eventID = (tbEventID.Text);
string text;
EventLog eLog = new EventLog();
Invoke((MethodInvoker)delegate() { text = cbLogType.Text; });
eLog.Source = (this.cbLogType.Text); // I am receiving the error here
eLog.MachineName = ".";
int EventID = 0;
string strValue = string.Empty;
strValue = tbEventID.Text.Trim();
//string message = string.Empty;
EventID = Convert.ToInt32(strValue); // Convert string to integer
foreach (EventLogEntry entry in eLog.Entries)
{
int entryCount = 1;
if (cbDateFilter.Checked == true)
{
if (entry.TimeWritten > dtPicker1.Value && entry.TimeWritten < dtPicker2.Value)
if (entry.InstanceId == EventID)
message = "Event entry matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
using (StreamWriter writer = new StreamWriter(#"C:\Events.log", true))
writer.WriteLine("EventID: " + entry.InstanceId +
"\r\nDate Created: " + entry.TimeWritten +
"\r\nEntry Type: " + entry.EntryType +
"\r\nMachinename: " + entry.MachineName +
"\r\n" +
"\r\nMessage: " + entry.Message +
"\r\n");
if (entry.InstanceId != EventID)
message = "No event ids matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
}
else
{
if (cbDateFilter.Checked == false)
{
if (entry.InstanceId == EventID)
using (StreamWriter writer = new StreamWriter(#"C:\Events.log", true))
writer.WriteLine("EventID: " + entry.InstanceId +
"\r\nDate Created: " + entry.TimeWritten +
"\r\nEntry Type: " + entry.EntryType +
"\r\nMachinename: " + entry.MachineName +
"\r\n" +
"\r\nMessage: " + entry.Message +
"\r\n");
else if (entry.InstanceId != EventID)
message = "No event ids matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
}
bgWorker1.ReportProgress((entryCount) * 10, message);
entryCount++;
}
}
}
}
private void bgWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStat.Text = e.UserState.ToString();
}
You're accessing cbLogType in a non-UI thread.
Change to
eLog.Source = text;
So I have a dropdown context box, which I use to select which item I am going to be working with.
Now everything seems to be working on all browsers except Safari. I have a type function that works fine in safari if you focus on the box and type the name in and hit enter. However my issue is with the mouse click. If I select an item from the dropdown and click it, the postback doesn't work until I hit enter on the keyboard.
Here is my .ascx.cs file
...
if (cboContext.Visible)
{
string postBackFunction = "function contextPostback() {\n"
+ "var newValue = document.getElementById(\"" + cboContext.ClientID + "\").value;\n"
+ "if (newValue != " + cboContext.SelectedValue + ") " + Page.ClientScript.GetPostBackEventReference(cboContext, "") + ";\n}";
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "contextPostback", postBackFunction, true);
if (Request.UserAgent.ToLower().IndexOf("chrome") > -1)
{
cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onclick", "contextPostback();");
}
else if (Request.UserAgent.ToLower().IndexOf("safari") > -1)
{
cboContext.Attributes.Add("onclick", "contextPostback();");
cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onkeyup", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
}
else
{
cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onclick", "contextPostback();");
}
}
Here is the typeAhead() function
function typeAhead(e, nextFocus) {
//don't trap Ctrl+keys
if ((window.event && !window.event.ctrlKey) || (e && !e.ctrlKey)) {
// timer for current event
var now = new Date();
....
if (inputBuffer.accumString == "" || now - inputBuffer.last < inputBuffer.delay) {
//check for browsers
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
// make shortcut event object reference
var evt = e || window.event;
// get reference to the select element
var selectElem = evt.target || evt.srcElement;
// get typed character ASCII value
var charCode = evt.keyCode || evt.which;
// get the actual character, converted to uppercase
var newChar = "";
// get reference to the actual form selection list
// added cross browser fix to enable the context switcher to work properly
if (is_chrome) {
var selection = document.getElementById("ctl00_ContextSwitch1_cboContext").selectedIndex;
}
else {
var selection = document.getElementById(nextFocus);
}
....
Now I have a section in the typeAhead for the chrome browser, but everything I try for safari doesn't seem to allow me to use the mouse click to select an item.
Any help would be appreciated.
simple fix. safari recognizes onchange so once I added that, it worked fine.
I'm using the local database functionality in Chrome and Safari and what I do when I want to save this to a remote database is to create a hidden textfield and then using JSON to stringify each row. In the code behind I then parse each JSON object and insert it into the list. What I want to do now is to delete these rows from the local database. I have a JavaScript function called deletePatient:
function deletePatient(patientID) {
MaRDB.transaction(
function (transaction) {
transaction.executeSql("DELETE FROM Patients WHERE id = " + patientID + ";");
}
);
}
I then call this function from the code behind if the insert was successfull
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete", "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");
However, it only deletes the patient with the lowest ID (the first JSON object). When I step through the code it goes back to that code for each ID but only deletes one. If I try with an alert it also only shows one ID even though it iterates through the code N number of times. I guess it's some kind of conflict with postback and executing a JavaScript function here but is it possible to solve?
protected void btnSave_Click(object sender, EventArgs e)
{
bool successfullySent = false;
SharePointConnection();
int count = Convert.ToInt32(txtRows.Text);
for (int i = 0; i <= count; i++)
{
string p = String.Format("{0}", Request.Form["hiddenField" + i]).ToString();
JObject o = JObject.Parse(p);
id = (int)o["id"];
string name = (string)o["name"];
string address = (string)o["address"];
string city = (string)o["city"];
string state = (string)o["state"];
string zip = (string)o["zip"];
string country = (string)o["country"];
string phone = (string)o["phone"];
StringBuilder sb_method = new StringBuilder();
sb_method.Append("<Method ID='1' Cmd='New'>");
sb_method.Append("<Field Name='Title'>" + name + "</Field>");
sb_method.Append("<Field Name='Address'>" + address + "</Field>");
sb_method.Append("<Field Name='City'>" + city + "</Field>");
sb_method.Append("<Field Name='State'>" + state + "</Field>");
sb_method.Append("<Field Name='ZIP'>" + zip + "</Field>");
sb_method.Append("<Field Name='Country'>" + country + "</Field>");
sb_method.Append("<Field Name='Phone'>" + phone + "</Field>");
sb_method.Append("</Method>");
XmlDocument x_doc = new XmlDocument();
XmlElement xe_batch = x_doc.CreateElement("Batch");
xe_batch.SetAttribute("OnError", "Continue");
xe_batch.InnerXml = sb_method.ToString();
try
{
//updating the list
XmlNode xn_return = listsObj.UpdateListItems(ConfigurationManager.AppSettings["SaveToSPList"].ToString(), xe_batch);
if (xn_return.InnerText == "0x00000000")
{
successfullySent = true;
}
else
{
successfullySent = false;
}
}
catch
{
successfullySent = false;
}
if (successfullySent)
{
divSuccessfulMessage.Visible = true;
lblSuccessfulMessage.Text = "Report Successfully Saved";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete", "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");
}
else
{
divErrorMessage.Visible = true;
lblErrorMessage.Text = "Failed to Save, Please Try Again";
}
}
}
Thanks in advance.
I'm assuming you're calling the RegisterClientScriptBlock multiple times? In that case, the second parameter of your RegisterClientScriptBlock is the unique key of the script you're trying to inject. Since its always the same, in effect you're basically 'overwriting' each previous script with the latest one.
Try it again, and make sure your key is unique every time you call the RegisterClientScriptBlock (for example, append a counter to it?).
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete" + counter.ToString(), "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");