How do I programmatically close an InfoPath form in C#? - c#

Is it possible to close an InfoPath form programmatically? I know that it can be configured as a form rule / action but I want to close the form via code.

Use the ApplicationClass.XDocuments.Close method and pass it your document object:
using System;
using Microsoft.Office.Interop.InfoPath;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var app = new ApplicationClass();
var uri = #".\form1.xml";
var doc = app.XDocuments.Open(uri, 0);
app.XDocuments.Close(doc);
}
}
}

Related

MultiThreading Variables C# -- Selenium

I am trying to automate the test for one of my websites using Selenium on C#. The website prompts the user for login credentials. It can only be done through multi threading.
I execute one thread to open the page in a special FireFox profile and another thread in parallel to simulate the press of ENTER.
The problem is the if I don't use multi threading, the code stops at opening the page as the website is not completely opened.
The driver is initiated in the first thread created. However it has to be used in the main method.
How can I pass an object created in a method (executed by a thread) in the main function?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
using System.Threading;
using System.IO;
using OpenQA.Selenium.Interactions;
using System.Windows.Forms;
namespace CRMTest1WithSelenium
{
class Program
{
public static IWebDriver OpenPage()
{
IWebDriver driver = null;
string path = #"C:\Users\ntouma\AppData\Roaming\Mozilla\Firefox\Profiles\nuxgc36b.CRMTester";
FirefoxProfile ffprofile = new FirefoxProfile(path);
driver = new FirefoxDriver(ffprofile);
driver.Navigate().GoToUrl("http://www.example.com");
return driver;
}
public static void pressEnter()
{
Thread.Sleep(6000);
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
static void Main(string[] args)
{
IWebDriver driver2 = null;
driver2 = OpenPage();
// Thread driverCreation = new Thread(OpenPage);
// driverCreation.Start();
Thread login = new Thread(pressEnter);
login.Start();
Thread.Sleep(2000);
driver2.Manage().Window.Maximize();
IWebElement sales = driver2.FindElement(By.XPath("/html/body/div[4]/d"));
sales.Click();
IWebElement leads = driver2.FindElement(By.XPath("/html/body//div/div/ul/li[3]/span/span[2]/span/span[1]/span/a[1]"));
leads.Click();
Thread.Sleep(5000);
}
}
}
Well i don't understand your problem in 100%...
But i can suggest two solutions:
1) Use a static member that your login functions will use inside it.
2) Send a class(object) to the thread when you create one:
e.g:
var myObj = ...; Thread thread = new Thread(() => pressEnter(myObj)); thread.Start();

Screen Capture in C# using HtmlAgilityPack

Due to the lack of proper documentation, I'm not sure if HtmlAgilityPack supports screen capture in C# after it loads the html contents.
So is there a way I can more or less grab a screenshot using (or along with) HtmlAgilityPack so I can have a visual clue as to what happens every time I do page manipulations?
Here is my working code so far:
using HtmlAgilityPack;
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string urlDemo = "https://htmlagilitypack.codeplex.com/";
HtmlWeb getHtmlWeb = new HtmlWeb();
var doc = getHtmlWeb.Load(urlDemo);
var sentence = doc.DocumentNode.SelectNodes("//p");
int counter = 1;
try
{
foreach (var p in sentence)
{
Console.WriteLine(counter + ". " + p.InnerText);
counter++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
Currently, it scrapes and output all the p of the page in the console but at the same time I want to get a screen grab of the scraped contents but I don't know how and where to begin.
Any help is greatly appreciated. TIA
You can't do this with HTML Agility Pack. Use a different tool such as Selenium WebDriver. Here is how to do it: Take a screenshot with Selenium WebDriver
Could you use Selenium WebDriver instead?
You'll need to add the following NuGet packages to your project first:
Selenium.WebDriver
Selenium.Support
Loading a page and taking a screenshot is then as simple as...
using System;
using System.Drawing.Imaging;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
// Create a web driver that used Firefox
var driver = new FirefoxDriver(
new FirefoxBinary(), new FirefoxProfile(), TimeSpan.FromSeconds(120));
// Load your page
driver.Navigate().GoToUrl("http://google.com");
// Wait until the page has actually loaded
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
wait.Until(d => d.Title.Contains("Google"));
// Take a screenshot, and saves it to a file (you must have full access rights to the save location).
var myDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(myDesktop, "google-screenshot.png"), ImageFormat.Png);
driver.Close();
}
}
}

How to upload a document to SharePoint using WebServices

I have looked through multiple tutorials and asked many questions with NO result . Here it is step by step :
1) I use Microsoft Visual Studio 2012 . I do NOT have SP server installed and cannot use Microsoft.SharePoint.dll . However , I can use Web Service
2) I create a console project and add a WebReference like this
3) Here is my FULL code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication6;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
string srcUrl = #"C:\\xxx\\test.txt";
System.IO.FileStream fStream = System.IO.File.OpenRead(srcUrl);
string fileName = fStream.Name.Substring(3);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
ServiceWebReference.Lists listService = new ServiceWebReference.Lists(); // "Lists" get underlined with a red line ?
listService.ClientCredentials = System.Net.CredentialCache.DefaultCredentials;
try
{
// adding attachment
string result = listService.AddAttachment("testList", "1", fileName, contents);
Console.WriteLine(result);
}
catch (System.Web.Services.Protocols.SoapException e)
{
Console.WriteLine(e.GetBaseException());
Console.WriteLine(e);
}
}
}
}
Am I adding the reference in a right way ? If yes , then why does the ServiceWebReference.Lists listService ... ... ... get underlined in red (does not recognize namespace ) ?
How to make the code work ?
Since Lists.asmx is a SOAP Web service, it could be referenced as described in article: How to: Add a Reference to a Web Service
How to add Lists.asmx SOAP Web service in Visual Studio:
In Solution Explorer, right-click the name of the project that you want to add the service to, and then click Add Service Reference
The Add Service Reference dialog box appears, in the Service Reference Settings dialog box, click Add Web Reference as demonstrated below
Specify service endpoint Url
Visual Studio
Sample code
namespace SPUpload
{
class Program
{
static void Main(string[] args)
{
var attachmentUrl = UploadAttachment(#"c:\temp\usermanual.rtf","Phones","1");
}
private static string UploadAttachment(string filePath, string listName, string listItemId)
{
var listsSvc = new ListsService.Lists();
listsSvc.Credentials = System.Net.CredentialCache.DefaultCredentials;
var fileName = Path.GetFileName(filePath);
var fileContent = File.ReadAllBytes(filePath);
return listsSvc.AddAttachment(listName, listItemId, fileName, fileContent);
}
}
}

Roslyn Run Code in AppDomain

I added Roslyn my project.
Roslyn can run script from string like
using Roslyn.Scripting.CSharp;
namespace RoslynScriptingDemo
{
class Program
{
static void Main(string[] args)
{
var engine = new ScriptEngine();
engine.Execute(#"System.Console.WriteLine(""Hello Roslyn"");");
}
}
}
but I wanna access the controls,properties,variables in the form.
For Example There is a textbox in form.
var engine = new ScriptEngine();
engine.Execute(#" textbox1.Text="SK"; ");
Can I access controls in Roslyn?
You could set up a host object for your script session that has a public property for the controls you want to access.

Twitter and Winform C# app is making me go bald

Ok twitter might be great for social media but for a small app that I am trying to create just for fun has turned into a nightmare. I have searched everywhere and can't find a good explanation on how to use the api.
I am using the TweetSharp api and all I want to do is for user to allow my app and be able to post from the app to their twitter.
My problem comes when the app gives out a pin code for the user to type in...where would the user type it in at? Ok so this is what I have so far..if anyone can help i would be most greatful so I can stop pulling my hair..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TweetSharp;
using System.Configuration;
using Hammock.Authentication.OAuth;
using System.Diagnostics;
namespace testtweet
{
public partial class Form1 : Form
{
//I already have these values not showing here for obvious reasons.
TwitterService service = new TwitterService("ConsumerKey", "ConsumerSecret");
public Form1()
{
InitializeComponent();
// Pass your credentials to the service
// Step 1 - Retrieve an OAuth Request Token
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
Form2 frm = new Form2(uri.ToString());
frm.Show();
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
IEnumerable<TwitterStatus> mentions = service.ListTweetsMentioningMe();
}
}
}
on my Form2
public Form2(string url)
{
InitializeComponent();
webBrowser1.Navigate(url);
}
Here is where I am lost. As you see Step 3 is wating for the pin code..How would I set it in there? I had an idea to write directly in the app.config but
how do I know when it has been generated? Should I make a 3rd form to have the user input the pin code there?
so this is what I've got (add a webbrowser named webBrowser1 in the designer)
public partial class TwitterBrowser : Form
{
public TwitterBrowser()
{
InitializeComponent();
webBrowser1.Navigated += OnNavigate;
}
private void OnNavigate(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.ToString() != #"https://api.twitter.com/oauth/authorize")
return;
if (webBrowser1.Document != null)
{
var regex = new Regex("<code>([0-9]*)</code>", RegexOptions.Multiline);
VerificationCode = regex.Match(webBrowser1.DocumentText).Groups[1].Value;
Close();
}
}
public string VerificationCode { get; private set; }
#region Implementation of ITwitterUserInteraction
public void NavigateTo(Uri uri)
{
webBrowser1.Navigate(uri);
}
#endregion
}
Then use it like this:
var browser = new TwitterBrowser();
browser.NavigateTo(uri);
browser.ShowDialog();
result = browser.VerificationCode;

Categories

Resources