c# console app as service - service

Just a simple consloe app that I want to have running as a service at all times, don't have the VB template.
So far I have:
given highestAvailable permission in the manifest, and bound the manifest in properties
right clicked on exe compatibility and selected "run as admin"
opened security settings so "everyone", administrators, services, system, network services, local services and some users all have permission for full access.
successfully added to service list with this code, code is run from separate solution form, also running with manifest and as admin:
private static void cmd_PROMPT(string cmd)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = #"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.Verb = "runas";
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
cmdStartInfo.Arguments = "/user:Administrator ";
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine(cmd);
MessageBox.Show(">>" + cmd);
//cmdProcess.WaitForExit();
}
private void button3_Click(object sender, EventArgs e)
{
string s;
string prgmName = "#QU#Service";
string prgmPath = "c:\\#QU#\\aquaService.exe";
string prgmMode = "auto";
s = "sc create " + prgmName + " binpath= " + prgmPath + " DisplayName= \"" + prgmName + "\" start= " + prgmMode;
cmd_PROMPT(s);
}
The app has made it in to the service list in control panel but it is "stopped"... when I click ...action... start service, it tries but fails with error:1053 did not start in timely fashion.
When I use CMD instruction it changes to "starting" in the service list, but then goes right back to stop:
prgmName = "#QU#Service";
prgmPath = "c:\\#QU#\\aquaService.exe";
prgmMode = "auto";
s = "sc start " + prgmName;
cmd_PROMPT(s);

ty Noodles, with your clue I was able to get this code working:
private void button3_Click(object sender, EventArgs e)
{
string s;
string prgmName = "#QU#Service";
string prgmPath = "c:\\#QU#\\aquaService.exe";
string prgmMode = "auto";
string _subKey = "Parameters";
string keyName = "Application";
RegistryKey _baseRegistryKey;
s = "C:\\#QU#\\instsrv.exe " + prgmName + " C:\\#QU#\\srvany.exe";
cmd_PROMPT(s);
s = "sc config " + prgmName + " start=auto "; // boot
cmd_PROMPT(s);
try
{
_baseRegistryKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services", true);
var sk1 = _baseRegistryKey.CreateSubKey(prgmName);
_baseRegistryKey = sk1; sk1 = _baseRegistryKey.CreateSubKey(_subKey);
if (sk1 != null) { sk1.SetValue(keyName.ToUpper(), prgmPath, RegistryValueKind.String); }
}
catch (Exception ee)
{
MessageBox.Show(" " + ee, "Administrator");
}
Thread.Sleep(5000);
prgmName = "#QU#Service";
prgmPath = "c:\\#QU#\\aquaService.exe";
prgmMode = "auto";
s = "sc start " + prgmName;
cmd_PROMPT(s);
}

Related

android display arraylist items in dialog

I am having an arraylist fetching name and status of a person. Arraylist is storing the status and name. Its displaying one name at a time. How can I be able to display multiple names at once in alert dialog?
private ArrayList getunfiledRogspDoctorList() {
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_DOCTOR + " WHERE " + Queryclass.DOCTOR_ROGSP_STATUS + " == " + 0 + " AND " + Queryclass.DOCTOR_DATE_ID + " = '" + selectionID + "'";
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
rogspname = gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_CONTACTNAME));
unfiledrogspDoctorList.add(gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_ROGSP_STATUS)) + rogspname);
}while (gspCu.moveToNext());
}
gspCu.close();
sd.close();
System.out.println("unfiledrogspDoctorList "+unfiledrogspDoctorList);
return unfiledrogspDoctorList;
}
From the code, you are having an ArrayList of your target display String in unfiledrogspDoctorList:
// Suggest to also define the type of your returning ArrayList
private ArrayList<String> getunfiledRogspDoctorList() {
// Define a local ArrayList
ArrayList<String> unfiledrogspDoctorList = new ArrayList<>();
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_DOCTOR + " WHERE " + Queryclass.DOCTOR_ROGSP_STATUS + " == " + 0 + " AND " + Queryclass.DOCTOR_DATE_ID + " = '" + selectionID + "'";
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
rogspname = gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_CONTACTNAME));
unfiledrogspDoctorList.add(gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_ROGSP_STATUS)) + rogspname);
}while (gspCu.moveToNext());
}
gspCu.close();
sd.close();
System.out.println("unfiledrogspDoctorList "+unfiledrogspDoctorList);
return unfiledrogspDoctorList;
}
You can consider to convert your ArrayList of String into just a String.
private String concat(ArrayList<String> unfiledrogspDoctorList) {
StringBuilder sb = new StringBuilder();
for (String item : unfiledrogspDoctorList) {
sb.append(item);
sb.append(","); // Or change into other separate you would like to display
}
sb.setLength(Math.max(0, sb.length() - 1)); // Remove the appending character
return sb.toString();
}
Then you can make use of an AlertDialog to display that concatenated String.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage(concat(getunfiledRogspDoctorList()))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do anything upon pressing OK button
}
);
AlertDialog alert = builder.create();
alert.show();
You could use :-
SELECT group_concat(name) FROM ....
or to place each on a line you could change the default comma separator to a line feed using
SELECT group_concat(name,'\n') FROM ....
.... representing the rest of the SQL in the question
See https://www.sqlite.org/lang_aggfunc.html#group_concat
note that the GROUP as no GROUP BY clause is provided is a single group (and therefore output row) made up of ALL extracted rows.

apache beam: accessing metrics during pipeline processing

Using the WordCount.java example to test metrics. The PrintMetricsFn function (see below) prints the metrics correctly once the pipeline is finished, but fails when called while the pipeline is processing. DirectRunner and FlinkRunner both throw exceptions (null input), while SparkRunner prints only the header line (similar to "* Metric Values *").
private static void PrintMetricsFn(final MetricsFilter inputFilter) {
final MetricResults metrics = result.metrics();
final MetricQueryResults returns = metrics.queryMetrics(inputFilter);
final Iterable<MetricResult<Long>> counters = returns.getCounters();
System.out.println("*** Metric Values ***");
for(final MetricResult<Long> s: counters){
System.out.println(s.getName().getNamespace() + ":" +
s.getName().getName() + ":" + s.getStep() + ": count=" +
s.getAttempted()) ;
}
final Iterable<MetricResult<DistributionResult>> dist = returns.getDistributions();
for (final MetricResult<DistributionResult> d: dist) {
System.out.println(d.getName().getNamespace() + ":" +
d.getName().getName() + ":" + d.getStep() + ": sum=" +
d.getAttempted().getSum() + ", count=" +
d.getAttempted().getCount() + ", min=" +
d.getAttempted().getMin() + ", max=" +
d.getAttempted().getMax() + ", mean=" +
d.getAttempted().getMean());
}
final Iterable<MetricResult<GaugeResult>> gauge = returns.getGauges();
for (final MetricResult<GaugeResult> g: gauge) {
System.out.println(g.getName().getNamespace() + ":" +
g.getName().getName() + ":" + g.getStep() + ": gauge=" +
g.getAttempted().getValue());
}
return;
}
Here are the declarations for the external variables:
private static PipelineResult result;
private static MetricQueryResults returns;
private static MetricsFilter mFilter;
And here's where the mFilter and result variables are set:
mFilter = MetricsFilter.builder()
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "emptyLines"))
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "lineLenDistro"))
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "maxLineLen"))
.build();
result = p.run();
Finally, here's the function that calls PrintMetricsFN without success:
#ProcessElement
public void processElement(#Element final String element, final OutputReceiver<String> receiver) {
lineLen = element.length();
lineLenDist.update(lineLen);
if (element.trim().isEmpty()) {
emptyLines.inc();
}
if (lineLen > localMax) {
localMax = lineLen;
maxLineLen.set(localMax);
}
if((lineCnt++ % 10) == 0) {
PrintMetricsFn(mFilter);
}
// Split the line into words.
final String[] words = element.split(ExampleUtils.TOKENIZER_PATTERN, -1);
// Output each word encountered into the output PCollection.
for (final String word : words) {
if (!word.isEmpty()) {
receiver.output(word);
}
}
}
And for completeness, here's the error I get from DirectRunner:
Caused by: java.lang.NullPointerException
at org.apache.beam.examples.WordCount.PrintMetricsFn(WordCount.java:158)
at org.apache.beam.examples.WordCount.access$1(WordCount.java:157)
at org.apache.beam.examples.WordCount$ExtractWordsFn.processElement(WordCount.java:132)

On Maintaining Unique Scope between server and client. Still it reflect same data on sync with another client as i syn with first one. Why?

I have create Scope different between each client and one server in scope_info table in DB. Once i sync with first client on filter condition it work correct but on changing filter condition with another client still it sync same data as i get previously. My code as given below :
Here Value is Unique Identity of Client.
Code:
ArrayList UnSyncTable = new ArrayList();
SqlConnection clientConn = new SqlConnection(ClientString);
SqlConnection serverConn = new SqlConnection(ServerString);
for (int i = 0; i < ClientDs.Tables[0].Rows.Count; i++)
{
#region Start Sync
//////////////////////////////////////////////////////////////////////////////////
if (serverConn.State == ConnectionState.Closed)
{
serverConn.Open();
}
if (clientConn.State == ConnectionState.Closed)
{
clientConn.Open();
}
try
{
#region Step1 for ServerSide
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(ClientDs.Tables[0].Rows[i][0].ToString() + "_SyncScope" + Value);
DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(ClientDs.Tables[0].Rows[i][0].ToString(), serverConn);
scopeDesc.Tables.Add(tableDesc);
SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc);
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
#region Filter Condition
if (DBFilteredTables.Contains(ClientDs.Tables[0].Rows[i][0].ToString()))
{
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
serverProvision.Tables[ClientDs.Tables[0].Rows[i][0].ToString()].AddFilterColumn(AttributeName);
serverProvision.Tables[ClientDs.Tables[0].Rows[i][0].ToString()].FilterClause = "[side].[" + AttributeName + "] =" + Value;
}
#endregion
// start the provisioning process
serverProvision.Apply();
#endregion
}
catch
{
}
try
{
#region Step2 for ClientSide
DbSyncScopeDescription scopeDesc1 = SqlSyncDescriptionBuilder.GetDescriptionForScope(ClientDs.Tables[0].Rows[i][0].ToString() + "_SyncScope" + Value, serverConn);
SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc1);
clientProvision.Apply();
#endregion
}
catch
{
}
try
{
#region Step3
SyncOrchestrator syncOrchestrator = new SyncOrchestrator();
syncOrchestrator.LocalProvider = new SqlSyncProvider(ClientDs.Tables[0].Rows[i][0].ToString() + "_SyncScope" + Value, clientConn);
syncOrchestrator.RemoteProvider = new SqlSyncProvider(ClientDs.Tables[0].Rows[i][0].ToString() + "_SyncScope" + Value, serverConn);
if (SyncCondition == 1)
syncOrchestrator.Direction = SyncDirectionOrder.Download;
else if (SyncCondition == 2)
syncOrchestrator.Direction = SyncDirectionOrder.DownloadAndUpload;
else if (SyncCondition == 3)
syncOrchestrator.Direction = SyncDirectionOrder.Upload;
else if (SyncCondition == 4)
syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;
((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);
SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();
//print statistics
string Msg = "Start Time : " + syncStats.SyncStartTime + "\n";
Msg += "Table Name : " + ClientDs.Tables[0].Rows[i][0].ToString() + "\n";
Msg += "Total Changes Uploaded : " + syncStats.UploadChangesTotal + "\n";
Msg += "Total Changes Downloaded : " + syncStats.DownloadChangesTotal + "\n";
Msg += "Complete Time : " + syncStats.SyncEndTime + "\n";
#endregion
}
catch
{
UnSyncTable.Add(ClientDs.Tables[0].Rows[i][0].ToString());
}
#endregion
}

Nokia Forms not showing text

I only wish Nokia documentation was more helpful. Its search on developer documentation totally sucks.
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
this.helloScreen = helloScreen;
getLocationThread.start();
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
String helloText = new String("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
super.append(helloText);
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
do you mean not showing from this command?:
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
It's not showing to phone screen. Instead it will show on console (IDE / debugging).
to showing text on Form.. you need to use somethings like:
form.addComponent(new Label("hi...");
hope it helps.

In what order C# execute sqlstatement?

I have two table related by foreign and primary key constraint.The Visit_Number in Patient table must exist in the Visit table.In my code in define create two instance of my connection string such that i can use one instance to insert record:VisitNumber in Visit table first and then the other instance to insert record in the patient table,with the believe that the cord runs from top to bottom.But this was n't the case. i still get foreign key constraint errror:
Error Number:547
Error MessageThe INSERT statement conflicted with the FOREIGN KEY constraint "Patient_Vist_FK".
The conflict occurred in database "TestDB", table "dbo.Visit", column 'Visit_Number'.
The statement has been terminated.On line Number: 1
meaning the code is running as i expected. Please do you have a better approach and why isn't mine working
code:
protected void btn_save_Click(object sender, EventArgs e)
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
SqlConnection con2 = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
SqlCommand cmd = new SqlCommand(insert_statement, con);
SqlCommand cmd2 = new SqlCommand(insert_stament2, con2);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
try
{
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script language=javascript>alert('Record Sucessfully Inserted!');</script>");
//Success_Message.Text = "Record inserted";
txtpatientNum.Text = String.Empty;
txtfirstName.Text = String.Empty;
txtlastname.Text = String.Empty;
txtVistNumber.Text = String.Empty;
DropDownList1.Text = String.Empty;
val_age.Text = String.Empty;
}
}
}
catch (SqlException ex)
{
{
VisitError_Message.Text = "Error Number:" + ex.Number.ToString() + " Error Message" + ex.Message + "On line Number" + ": " + ex.LineNumber;
}
}
catch (NullReferenceException nullexception)
{
VisitError_Message.Text = "Error Occurred, Error Type:" + nullexception.GetType().ToString() + "Error Message:" + nullexception.Message;
}
catch (DllNotFoundException dllexception)
{
VisitError_Message.Text = dllexception.GetType().ToString() + dllexception.Message;
}
finally
{
con.Close();
}
}
you not excuting you cmd2, you must execute the insert Visit_Number in cmd2 then excute your cmd, you can test this code
using (con2)
{
con2.Open();
cmd2.ExecuteNonQuery();
}
then you can excute your cmd
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
}
and you can do the work with the same connexion if you want
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
using(con)
{
con.open;
SqlCommand cmd2 = new SqlCommand(insert_stament2, con);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd2.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(insert_statement, con);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.ExecuteNonQuery();
}