Insert values in database at some intervals from a visual c++ program/project - database

I want to create a visual c++ program that automatically inserts some random values and the current system datetime in the database at particular intervals. I would be using the srand() function for this. I am not sure how to do this. I was able to achieve this using the winForm projects and scheduling it to run every 30 mins using Task Scheduler but the issue is that every time an empty form pops up and until and unless i close it the values are not entered. What i need is that all these happen on their own and the window should not pop up as its empty. Is winform the right way to achieve this and if not then what kinf of project should i choose. Maybe timers, threads...Please shed some light as i am relatively new to this.
Regards
PS: Here's the code
String^ constring = L"datasource=localhost;port=3306;username=root;password=root";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
MySqlCommand^ cmdDataBase = gcnew MySqlCommand("INSERT INTO `data`.`test` (`datetime`,`temp`,`pressure`) VALUES ('"+dt+"','"+rand_temp+"','"+rand_pressure+"');",conDataBase); MySqlDataReader^ myReader;
try{
conDataBase->Open();
myReader = cmdDataBase->ExecuteReader();
//MessageBox::Show("Data Inserted");
while(myReader->Read()){
}
}catch(Exception^ex){
MessageBox::Show(ex->Message);
}
Application::Exit();
The above code is inside my formload method

Use a console application project instead of a winforms project

You should put the code in the "Main" method and not in the constructor of your Form. You do not Need a Form at all...
Also I do not recommend using a console application, because this will popup a Console-Window...

please share your code for deeper insight.
the program is writing to the DB the values, but the DB won't be updated(A.K.A committed) until you'll close the connection/do manual commit. again share your code please. i would advise not to use winforms if you don't need a form. you can use a variety of different ways to achieve DB update. for example, you can use sleep so the thread will work once in a while(depends on how much u gave him on the sleep method).
in anyway, give us more information so we can help you
edited
after the cmdDataBase->ExecuteReader(); use the MySQLConnection.commit() in order to commit the transaction. take all your code to the main function rather then in the creation of the form. it doesn't seems you need a form at all, right?
use the Sleep method to wait for some time if you need(read here) for more information or search google.
anything more?

Related

Runnig N times the simulation in anylogic

In my anylogic Project, I want to terminate my execution and run the simulation for N times. in each of the simulation I store my output in an excel file which depends on the run count.
Instead of stopping and running by my click, I want to do it automatically. How can I do that?
I try to use an event and write by while loop (myparm<=N) and in loop I wrote getEngine().run, but it didn't work!
if it is possible please help me.
Thanks
Below is an overview of a methodology of how you can do it using the existing simulation framework used by AnyLogic
You need to make use of the simulation setup in order to run multiple runs of the model and save the output. My suggested setup will be the following:
Have a button on your Simulation Experiment page (The first page you see when running the model) that you will use to start off the multiple model runs. In here you set the engine to not run in real time mode by using
getEngine().setRealTimeMode(false);
you might also want to set the initial seed and some other model parameters that you might also want to change and perhaps save after model execution. When you have setup the model the way you want use run() to start running the model.
Now under the Simulation Experiment setup page under the 'Java actions' section you need to specify what the model must do after it finished running the model. In the 'After simulation run' section write some code to save the data from the model into your Excel files. To access variables and objects from the model use root, e.g.
saveSomeData(root.myDataset);
where saveSomeData is a function on the Simulation page to save my data set found on the model, called myDataset, to an Excel file. It would be great to also save the seed and the specific parameters, if you changed any, to the Excel file for future reference.
Once you have saved the data output from the model you can specify a new seed and perhaps change parameters again and then call the run() again to run the model for another iteration. When the model has finished running it will again call the 'After simulation run' code here, so do put a stop condition otherwise it will just continue running one iteration after the other. You can access the number of model runs by using
getEngine().getRunCount()
Also, your model needs to have some stop condition, otherwise once it starts running it will never stop. You can specify this in the Simulation Experiment page under the 'Model time' section or programatically in your model using
finishSimulation();
In order to run the model cyclically, please use the following code in the Action field of a timeout triggered event or On destroy field of the top-level agent:
new Thread(){
public void run(){
// stops the model
getExperiment().stop();
try {
// delay
this.sleep(1000);
} catch(Exception e) {};
// runs it again
((Simulation) getExperiment()).button.action();
}
}.start();
The model results should be written to the Excel file before executing this code.
As Jaco-Ben suggested, you can specify getEngine().getRunCount() as condition of restarting the Simulation experiment.

How to detect an unfinished awaiting process before Window closure?

Having spent the last several days converting a working frontend application for a database with Async/Await, I fear I have worked myself into a corner. Being new to all this, I have a very simple question.
What happens to an "awaiting" process when the computer is suspended? Additionally, can a process that is "awaiting" be detected in a generic fashion so that the user can be warned that "the process is not finished" prior to Window closure? (The application has many Create and Update processes to manage the database backend).
TIA
Instead of
await DoAsync();
you could do something like
task = DoAsync();
await task;
and when closing your application, you might want to check somewhere else
if(task.Status == TaskStatus.Running)
...
this would make sense for long running operations. Have a look at the Task Class, though.

Random Popups While Automating the Webpage

I was attending an interview and he gave me the following scenarios . If I could get an hint as I could not answer the questions.
Assume that there is an application and popups keep coming up all the time. These are not times, its just random. You never know when they are going to come. How to deal with it?
Assume that the script you wrote is fine. But due to network issues the objects in the page are really slow to load or the page itself is taking long time. How do you deal with such a scenario?
Assume that I have 5-6 pages in the application. In all the pages we have certain text fields. In page 1 and Page 5 there is an object which is a text box. I see that what ever whatever identification method (css, xpath, id etc) you take, the values are same. That is duplicates. How do you deal with this scenario?
What is the basic purpose of "data provider" annotation in TestNG. In genral, what is the purpose of testng annotations?
Thanks.
Assume that the script you wrote is fine. But due to network issues the objects in the page are really slow to load or the page itself is taking long time.
How do you deal with such a scenario. In such situation, You should Wait property of Selenium. Implicit Wait or Explicit wait.
Implicit Wait -- Used for setting Timeout for Webpage loading
Driverobject.manage().timeouts().PageLoadtimeOut(units,TimeUnit.SECONDS);
Explicit Wait-- Used for setting Timeout for particular
Webelement FirefoxDriver f = new FirefoxDriver();
WebDriverWait ww = new WebDriverWait(f,Units);
ww.until(ExpectedConditions.CONDITION);
For second question, Anubhav has answered it.
For third, even if elements are same for the page1 and page5, they can be differentiated. First, switch to page to, whose text field you want to interact with, and then interact with that text field.
For forth, dataprovider is an annotation in TestNG using which you can do data driven testing and using TestNG annotations, you can manage test execution flow of your tests. For more details of dataprovider and TestNG annotation, please go here
For third, If you open 5-6 the pages in different tabs of single browser you will get such a duplication problem. That time only one page is visible to the end user. So we can differentiate that element by visibility and can interact with that element using webdriver
List<WebElement> el=driver.findElements(By.xpath("xpath of that text element"));//you can use other than xpath too to identify the elements
for(int i=0;i<el.size();i++)
{
if(el.get(i).isDisplayed())
el.get(i).sendKeys("text you want to send");//any other action you want to perform
break;
}

Can i recreate a CompositionContainer?

i have a wpf application with login window before displaying the mainwindow.
i use mef to load all modules/parts. before the mainwindow start i check the user login data against the parts which i display then. the parts a Shared and NonShared.
[ImportMany]
private IEnumerable<Lazy<IComponent, IComponentMetadata>> _components;
[ImportMany("Resourcen", typeof(ResourceDictionary))]
private IEnumerable<ResourceDictionary> _importResourcen;
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory));
_mefcontainer = new CompositionContainer(catalog);
_mefcontainer.ComposeParts(somepartwithaSharedExport, this);
this all works fine. but now i tried the "relogin".
_mefcontainer.Dispose();
_mefcontainer = null;
//here the stuff that works from above
first i thought it works, but it seems that the parts i create the first time still exist in memory and i have no chance to "kill" them. so i got OutOfMemory Exception when i relogin enough times.
that why i use this approach now
System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
App.ShutDown();
i dont feel happy with this.
is there a way to cleanup the Compositioncontainer and create a new one?
You could try to call _mefcontainer.RemovePart(somepartwithaSharedExport). More details here: http://mef.codeplex.com/wikipage?title=Parts%20Lifetime
For the non-shared part you can call CompositionContainer.ReleaseExport:
_mefcontainer.ReleaseExport(nonSharedExport);
For more info have a try the sample code from this answer.
As far as I know, the shared parts cannot be released without disposing the container. If you go with that path, then you will also have to make sure that no references to these objects are kept to allow for the GC to collect them. The documentation reference from mrtig's answer provides a lot of useful details concerning the lifetime of parts and you should probably study it along with the answer by weshaggard to a similar question. It also explains what happens to disposable parts.

"The calling thread must be STA, because many UI components require this." Error in WPF?

I am creating a xps document as below.
Assembly assembly = Assembly.GetExecutingAssembly();
//read embedded xpsDocument file
Stream helpStream = assembly.GetManifestResourceStream(resourceNameOfContext);
if (helpStream != null)
{
Package package = Package.Open(helpStream);
string inMemoryPackageName = "memorystream://" + topicName + ".xps";
Uri packageUri = new Uri(inMemoryPackageName);
//Add package to PackageStore
PackageStore.AddPackage(packageUri, package);
docXps = new XpsDocument(package, CompressionOption.Maximum, inMemoryPackageName);
}
return docXps;
When i am trying to get docXps.GetFixedDocumentSequence();
I am getting the above error. Can anyone help?
Thanks,
Your problem has nothing to do with the code surrounding the creation or use of the XPS document. It has everything to do with what thread you are running under.
You will receive the The calling thread must be STA, because many UI components require this error whenever any of the following are attempted on a MTA thread:
You construct any object derived from FrameworkElement (including Controls and Panels)
You construct any object derived from BitmapEffect
You construct any object derived from TextComposition
You construct any object derived from HwndSource
You access the current InputManager
You access the primary KeyboardDevice, StylusDevice, or TabletDevice
You attempt to change the focus on a FrameworkContentElement
You provide mouse, keyboard or IME input to any control that accepts text input
You make WPF content visible or update its layout
You manipulate the visual tree in such a way as to cause a re-evaluation for rendering
Several other changes, mostly having to do with display and input
For example, I received this error last year when I tried to deserialize some XAML that contained <Button> and other WPF objects from within a WCF service. The problem was simple to solve: I just switch to a STA thread to do the processing.
Obviously most work with XPS documents will trigger one or more of the above conditions. In your case I suspect that GetFixedDocumentSequence ends up using TextComposition or one of its subclasses.
No doubt the my solution of switching to a STA thread will also work for you, but first you need to figure out how your code that works with XpsDocuments is getting executed run from a MTA thread. Normally any code from from the GUI (eg a button press) is automatically run in a STA thread.
Is it possible that your code that manipulates XPS Documents may be being executed without a GUI? From a user-created thread? From a WCF service or a web service? From an ASPX page? Track that down and you'll probably find your solution.
If that doesn't work, let us know the details of the path through which GetFixedDocumentSequence is called, so we can diagnose it. The directly surrounding code isn't nearly as important as the call stack and how it is originally being invoked. If it is hard to explain you probably should add a call stack to prevent misunderstandings and help us diagnose the problem further, or tell you how to start a STA thread in your particular situation.
Is your code trying to access the xps doc from a background thread? If this is the case, you'll want to use the dispatcher. Info on that here.
If this doesn't help, could you post the code where you're actually calling GetFixedDocumentSequence()?

Resources