Check connection to database in thread - database

how to check connection to database while login form is showing to user before show all tools on the login form ?
In an application, I plan to arrange the following steps:
1-Login form without any special tools except a label and background image (similar to a Splash form).
2. Behind the login form (preferably inside a thread) is the connection to the server, and the user see a label with this text: try to connect to database...
3. If a connection is established (flag == right), a series of tools will be displayed for login user.
4. If the connection to the server is not established (flag == false), a series of other tools will be displayed to user for addressing the server.
I hope I could clearly make it.
using System;
using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;
using System.Reflection;
public partial class LoginForm : Form
{
public LoginForm()
{
this.DoubleBuffered = true;
InitializeComponent();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(CheckConnection));
t.Start();
System.Threading.Thread.Sleep(5000);
t.Abort();
}
bool flag;
private void CheckConnection()
{
using (System.Data.SqlClient.SqlConnection connection =
new System.Data.SqlClient.SqlConnection
(connectionString))
{
try
{
connection.Open();
connection.Close();
flag = true;
}
catch
{
flag = false;
}
}
}
private void SplashScreenForm_Load(object sender, EventArgs e)
{
if (flag)
{
//Do somethings to login user
}
else
{
//Do something to create connection to database
}
}
The problem with this code is that the thread starts running before the form is displayed, and the program initially starts with a delay and immediately all the tool is displayed. Thanks for giving friends guidance.

I used Backgroundworker controller to solve this problem. It works very excellent.
Refer to https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.8

Related

Element not found. How to test sequence of steps in multi-page WPF app with winappdriver?

I have a WPF application that features several pages. Navigation takes place after selecting some of the buttons. I am able to start the testing session successfully and to find elements in the main window. However, when clicking the "OK" button that should trigger navigation to another page, the app does not navigate and the test case fails to find UI elements in the next page. I have tried ImplicitWait and Thread.Sleep but the elements still cannot be found. It seems like the app does not navigate at all when the button is clicked.
Any ideas on how to tackle this issue? Below is what I have accomplished so far:
namespace TestDAAC
{
[TestClass]
public class UnitTests
{
protected const string WINAPPDRIVER_URL = "http://127.0.0.1:4723";
private const string DAAC_APP_ID = #"C:\Users\Admin\Desktop\VC PROJECTS\daac\DAAC\bin\x64\Release\DAAC5.exe";
protected static WindowsDriver<WindowsElement> daacSession;
[ClassInitialize]
public static void Setup(TestContext context)
{
if (daacSession == null)
{
var appiumOptions = new AppiumOptions();
appiumOptions.AddAdditionalCapability("app", DAAC_APP_ID);
appiumOptions.AddAdditionalCapability("deviceName", "WindowsPC");
daacSession = new WindowsDriver<WindowsElement>(new Uri(WINAPPDRIVER_URL), appiumOptions);
}
}
[TestMethod]
public void SequenceOfSteps()
{
daacSession.FindElementByName("OK").Click();
Thread.Sleep(5000);
// daacSession.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
daacSession.FindElementByName("New Imaging Session").Click();
}
}
}
I was able to find the reason why my test cases were not working. WinAppDriver is compatible only with Windows 10 Home or Pro. My target device runs on Windows Enterprise.

Accessing document elements when using Windows.Forms.WebBrowser

I'm new to automating webpage access, so forgive what is probably a remedial question. I'm using C#/Windows.Forms in a console app. I need to programmatically enter the value of an input on a webpage that I cannot modify and that is running javascript. I have successfully opened the page (triggering WebBrowser.DocumentCompleted). I set browser emulation mode to IE11 (in registry), so scripts run without errors. When DocumentCompleted() triggers, I am unable to access the document elements without first viewing the document content via MessageBox.Show(), which is clearly not acceptable for my unattended app.
What do I need to do so that my document elements are accessbile in an unattended session (so I can remove MessageBox.Show() from the code below)? Details below. Thank you.
The input HTML is:
<input class="input-class" on-keyup="handleKeyPress($key)" type="password">
My DocumentCompleted event handler is:
private static void LoginPageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = ((WebBrowser)sender);
var document = wb.Document;
// I'm trying to eliminate these 3 lines
var documentAsIHtmlDocument = (mshtml.IHTMLDocument)document.DomDocument;
var content = documentAsIHtmlDocument.documentElement.innerHTML;
MessageBox.Show(content);
String classname = null;
foreach (HtmlElement input in document.GetElementsByTagName("input"))
{
classname = input.GetAttribute("className");
if (classname == "input-class")
{
input.SetAttribute("value", password);
break;
}
}
}
The problem for me was that the page I'm accessing is being created by javascript. Even though documentComplete event was firing, the page was still not completely rendered. I have successfully processed the first page by waiting for the document elements to be available and if not available, doing Application.DoEvents(); in a loop until they are, so I know now that I'm on the right track.
This SO Question helped me: c# WebBrowser- How can I wait for javascript to finish running that runs when the document has finished loading?
Note that checking for DocumentComplete does not accurately indicate the availability of the document elements on a page generated by javascript. I needed to keep checking for the elements and running Application.DoEvents() until they became available (after the javascript generated them).
If the problem comes from the creation of a STAThread, necessary to instantiate the underlying Activex component of WebBrowser control, this is
a modified version of Hans Passant's code as shown in the SO Question you linked.
Tested in a Console project.
class Program
{
static void Main(string[] args)
{
NavigateURI(new Uri("[SomeUri]", UriKind.Absolute), "SomePassword");
Console.ReadLine();
}
private static string SomePassword = "SomePassword";
private static void NavigateURI(Uri url)
{
Thread thread = new Thread(() => {
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate(url);
Application.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
protected static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = ((WebBrowser)sender);
if (browser.Url == e.Url)
{
while (browser.ReadyState != WebBrowserReadyState.Complete)
{ Application.DoEvents(); }
HtmlDocument Doc = browser.Document;
if (Doc != null)
{
foreach (HtmlElement input in Doc.GetElementsByTagName("input"))
{
if (input.GetAttribute("type") == "password")
{
input.InnerText = SomePassword;
//Or
//input.SetAttribute("value", SomePassword);
break;
}
}
}
Application.ExitThread();
}
}
}

Fetching all Microsoft Active Directory users in Domino Xpages NamePicker via java Agent

I'm working with LDAP Microsoft Active Directory and Domino server and quite new with this.
we've successfully fetched all Microsoft Active Directory users in Domino via java Agent and have printed all the user names in java debug console. For that referred this http://lotus-blogs.blogspot.in/2009/08/ldap-programming-using-domino-java-step.html link.
Now, i want to get all users in Domino Xpages NamePicker, so is this possible to get all users in Xpages NamePicker via java Agent?
As per we see that in Xpages NamePicker, we are able to fetch the Domino Users with the help of java beans.
Any kind of suggestion will be really Appreciated.
My java Agent is like following-
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
LDAPQuery.ldapconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
}
AND
import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
public class LDAPQuery {
public static void ldapconnect(){
String isFound="0";
try {
System.out.println("inside try 1");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "PROVIDER_URL");
env.put(Context.SECURITY_PRINCIPAL, "UserName");
env.put(Context.SECURITY_CREDENTIALS, "password");
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Specify the ids of the attributes to return
String[] attrIDs = {"cn","mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectCategory=person)(mail=*abc.com))";
System.out.println("filter defined");
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("", filter,ctls);
System.out.println("get the answer!");
try {
System.out.println("inside try2");
while (answer.hasMore())
{
SearchResult sr = (SearchResult)answer.next();
System.out.println("<<" + sr.getName()+">>");
Attributes attrs = sr.getAttributes();
//System.out.println(sr.getName().matches("/^[0-9]/"));
System.out.println(attrs.get("cn").get());
System.out.println(attrs.get("mail").get());
isFound="1";
}
if ( isFound=="1") {
System.out.println("User found in Active Directory!");
} else {
System.out.println("Opps ! User not found in Active Directory!");
}
answer.close();
}catch(PartialResultException e) {
System.out.println("catch 2");
e.printStackTrace();
}
// Close the context when we're done
ctx.close();
} catch (Exception e) {
System.out.println("catch 1");
e.printStackTrace();
}
}
public LDAPQuery() {
// Don't think I'm doing anything here
}
}
OK, got it.
Any particular reason why you are utilizing an Agent as opposed to using a true bean? Calling an agent everytime someone opens the name picker in my opinion is far from being effective.
Apart from that I don't see a way how the results from your agent could directly be passed into the name picker.
Third: looking at your ldap filter I'm sure that your code will return hundreds or even thousands of names. Using a standard ExtLib NamePicker is no fun for your users, believe me: the list of names displayed per dialog page is way too limited. But that may be a different story.
Sticking to the namePicker approach there are several ways how you could achieve what you appear to accomplish:
refactor your java agent into a javaBean then feed the result to the control
consider going for a directory syncing tool like IBM TDI; thus your AD data can be pushed into a Domino directory of your choice, and then from within your application you can utilize standard name lookup features

Animated GIF while database connects in WPF

I am working on an application that connects to Database as soon as it opens. Sometimes, it takes about 10-15 seconds before the database file gets connected and until then, no controls are loaded, it just loads a blank window and the cursor shows working. I tried using this library to use an animated GIF but it is not loading it before trying DB connection. I am using SQL Server Express and connecting to an mdf file. I tried placing code to display the <image/> before the SqlConnection and SqlDataAdapter Objects but even that didn't help. Any suggestions would be appreciated. Thanks in advance.
Do all the loading processes on a different thread,
Best way to do this is to use a BackgroundWorker
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Initialize
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork +=
new DoWorkEventHandler(bw_DoWork);
Usage
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 10));
}
}
}

WPF + PRISM - Cannot 'LoadModule' in separate thread

I have a WPF application in PRISM architecture.
I have a 'Login View' that is shown in the 'Main Region' when the app loads.
When the user presses 'Login' - I connect to a WCF service, authenticate the user, and get a list of roles for that user from the service.
Then - according to the user's roles - I load different modules, using the 'Module Manager'.
Problem is - I want all the work after the 'Login' button is pressed to be done in a separate thread, because it might take time to connect to the service etc, and I don't want the UI to be frozen.
But - if I put the code to 'connect, authenticate, get roles, load modules' in a separate thread - I get an exception when I call '_moduleManager.LoadModule' that says:
The calling thread must be STA, because many UI components require this.
How can I solve this ?
I have tried different solutions.
I have tried to set the new thread's 'Apartment State = STA' and it didn't help.
I thought about saving the 'Dispatcher' object in the constructor of the View-Model, and then do 'dispatcher.Invoke' when I call 'LoadModule', but that is bad design (View-Model should not use Dispatcher, and also it is bad for testing).
Any ideas how I can solve this ??
Only the 'LoadModule' gives me grief, all the other stuff works fine.
.
[Update] - Added Code Sample :
[Export]
public class LoginViewModel : NotificationObject
{
[ImportingConstructor]
public LoginViewModel(IRegionManager regionManager, IModuleManager moduleManager)
{
this.LoginCommand = new DelegateCommand(LoginExecute, LoginCanExecute);
this._regionManager = regionManager;
this._moduleManager = moduleManager;
}
private void LoginExecute()
{
IsBusy = true; // Set this to 'true' so controls go disabled
LoginStatus = ""; // Clear the 'login status' string
Thread loginThread = new Thread(new ThreadStart(LoginWork));
loginThread.SetApartmentState(ApartmentState.STA);
loginThread.Start();
}
private void LoginWork()
{
ParamsToGetRoles param = new ParamsToGetRoles
{
Username = Username,
InputtedPassword = Password
};
try
{
// Connect to the secure service, and request the user's roles
_clientSecure = new AuthenticationServiceClient("WSHttpBinding_MyService");
_clientSecure.ClientCredentials.UserName.UserName = param.Username;
_clientSecure.ClientCredentials.UserName.Password = param.InputtedPassword;
_clientSecure.ChannelFactory.Faulted += new EventHandler(ChannelFactory_Faulted);
var local = _clientSecure.ChannelFactory.CreateChannel();
_clientSecure.GetRolesCompleted += new EventHandler<GetRolesCompletedEventArgs>(clientSecure_GetRolesCompleted);
_clientSecure.GetRolesAsync(param);
}
catch (Exception ex)
{
Console.WriteLine("Exception : " + ex.Message.ToString());
}
}
void clientSecure_GetRolesCompleted(object sender, GetRolesCompletedEventArgs e)
{
if (e.Error == null)
{
_clientSecure.Close();
LoginSuccess(e.Result.UserRoles);
}
else
{
LoginFailure("Unable to authenticate");
}
_clientSecure = null;
}
private void LoginSuccess(List<UserTypeEnum> rolesOfAuthenticatedUser)
{
LoginStatus = "Success";
if (rolesOfAuthenticatedUser.Contains(UserTypeEnum.Administrator))
{
// This is what throws the exception !
// This is called by the 'EndInvoke' of the 'GetRoles' operation,
// Which was called in the 'LoginWork' function which was run on a separate thread !
_moduleManager.LoadModule(WellKnownModuleNames.ModuleAdmin);
}
NavigateToMainMenu();
this.IsBusy = false;
}
}
You should attach the debugger and inspect the threads window with a breakpoint set at clientSecure_GetRolesCompleted. I'm pretty sure it is not being called from the loginThread: while LoginWork does run in the loginThread, it then adds an eventhandler to the completion event of an async operation. Async = runs in yet another thread.
So what probably happens:
LoginExecute executes in the UI thread
starts a seperate thread B to run LoginWork
calls GetRolesAsync so start a thread C (which is not STA) to get the roles
thread C eventually calls 'clientSecure_GetRolesCompleted', not thread B
So, you do not need a seperate thread for LoginWork since the actual work is already done as an async operation. To get around the loading issue, either try to make the 'get roles' thread STA, or better, use a dispatcher so LoginSuccess gets invoked on the UI thread.

Resources