Incorrect syntax near the keyword 'to' in c# database backup - c#-3.0

string sql = "BACKUP DATABASE" + comboBox1.SelectedText.ToString() +
" to disk = '" + textBox1.Text.ToString() + "'\'" +
comboBox1.SelectedText+"'.bak";

try
{
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Anjum-Dar\Documents\Visual Studio 2012\managerecord\managerecord\recordemanage.mdf;Integrated Security=True");
con.Open();
string sql = "BACKUP DATABASE" + comboBox1.SelectedText.ToString() + " to disk = '" + textBox1.Text.ToString() + "'\'" + comboBox1.SelectedText + "'.bak";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Successfully ");
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}

Related

Sql anywhere 12 connection string

I am trying to connect sql anywhere12 database to my .net project but while connecting to the database i am facing an error
"{"Invalid connection string. Error parsing connection parameter string\r\nParameter name: connectionString"}"
while running this code.
private void btncon_Click(object sender, EventArgs e)
{
string connetionString = null;
SAConnection connection;
SACommand command;
string sqla = null;
// connetionString = "Data Source=SQL Anywhere 12 Demo;Initial Catalog=Demo2;User ID=dba;Password=sql";
connetionString = "Driver={SQL Anywhere 12};ENG=demo12;UID=dba;PWD=sql;DBN=sql;LINKS=TCPIP(HOST=localhost)";
sqla = "INSERT INTO student(Rollnumber,Name) values('" + textBox1.Text + "','" + textBox2.Text + "')";
connection = new SAConnection(connetionString);
try
{
connection.Open();
command = new SACommand(sqla, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show(" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
actually i have no much knowledge about the sql anywhere 12 connection string please help me to solve this error

c# console app as 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);
}

#AspectJ pointcut for execute methods of a package that contains keyword service

I'm trying to intercept all classes that contains a specific word in their package name... something as below:
#Pointcut("execution(* *..service..*.*(..))")
I have all the classes in the packages to intercept:
com.domain.model.user.service.save(User user);
com.domain.model.user.service.impl.save(XPTO xpto);
com.domain.model.foo.service.HelloWorld.getMessage(Foo foo);
In short, i would like to intercept all the methods in the classes that belong to the
package *service*
I am trying to get this working from past many days.
Try this. Perhaps you have to exclude your aspect classes to avoid endless loops. This example catch all methods with com..login..* in package
#Aspect
#SuppressAjWarnings({ "adviceDidNotMatch" })
public class AllMethodsAspect {
private static Map<String, Long> beforeTimestamps = new HashMap<>();
#Pointcut("!within(aspects..*)"
+ " && (!execution(* org..* (..)) && !within(org..*) && !call(* org..* (..)) )"
+ " && (!execution(* java..* (..)) && !within(java..*) && !call(* java..* (..)) )"
+ " && (!execution(* javax..* (..)) && !within(javax..*) && !call(* javax..* (..)) )"
+ " && (!execution(* sun..* (..)) && !within(sun..*) && !call(* sun..* (..)) )"
+ " && execution(* com..login..*(..))")
public void methodCall() {
}
#Before("methodCall()")
public void before(JoinPoint joinPoint) {
beforeMethodCall(joinPoint);
}
#AfterReturning(pointcut = "methodCall()", returning = "returnObject")
public void after(JoinPoint joinPoint, Object returnObject) {
afterMethodCall(joinPoint, returnObject);
}
#AfterThrowing(pointcut = "methodCall()", throwing = "throwable")
public void throwing(JoinPoint joinPoint, Throwable throwable) {
afterThrowingMethodCall(joinPoint, throwable);
}
void beforeMethodCall(JoinPoint joinPoint) {
try {
long start = System.currentTimeMillis();
beforeTimestamps.put(joinPoint.toString() + " - " + Thread.currentThread().getName(), Long.valueOf(start));
LOG.info(".before " + joinPoint);
} catch (Exception e) {
LOG.error(".before Exception " + e);
}
}
void afterMethodCall(JoinPoint joinPoint, Object returnObject) {
afterMethodCall(joinPoint, returnObject, 0);
}
void afterMethodCall(JoinPoint joinPoint, Object returnObject, int depth) {
try {
long start = beforeTimestamps.get(joinPoint.toString() + " - " + Thread.currentThread().getName()).longValue();
beforeTimestamps.remove(joinPoint.toString() + " - " + Thread.currentThread().getName());
long duration = System.currentTimeMillis() - start;
Signature signature = joinPoint.getSignature();
if (signature instanceof MethodSignature) {
Class<?> returnType = ((MethodSignature) signature).getReturnType();
LOG.info(".after " + joinPoint + " " + duration + "ms" + (void.class == returnType ? "" : " [" + returnObject + "]"));
} else if (signature instanceof ConstructorSignature) {
LOG.info(".after " + joinPoint + " " + duration + "ms Constructor");
} else if (signature instanceof FieldSignature) {
LOG.info(".after " + joinPoint + " " + duration + "ms Field");
} else {
LOG.info(".after " + joinPoint + " " + duration + "ms unknown");
}
} catch (Exception e) {
LOG.error(".after Exception " + e);
}
}
void afterThrowingMethodCall(JoinPoint joinPoint, Throwable throwable) {
try {
Long startAsLong = beforeTimestamps.get(joinPoint.toString() + " - " + Thread.currentThread().getName());
long start = startAsLong == null ? 0 : startAsLong.longValue();
beforeTimestamps.remove(joinPoint.toString() + " - " + Thread.currentThread().getName());
long duration = System.currentTimeMillis() - start;
LOG.info(".fail " + joinPoint.toString() + " " + duration + " ms - " + throwable.getMessage());
} catch (NullPointerException e) {
LOG.info(".fail NullPointerException " + "unknown - " + throwable.getMessage());
}
}
static final class LOG {
static void info(String loggingData) {
System.err.println(new Date() + " " + loggingData);
}
static void error(String loggingData) {
System.err.println(new Date() + " " + loggingData);
}
}
}
I think you can capture what you need with a pointcut like this:
before(): execution(* *(..)) &&
(within(*..service..*.*) || within(service..*.*) || within(*..service.*)) {}
The three within clauses capture the three alternatives:
within(*..service..*.*): 'service' is somewhere in the package name but not at the start or end
within(service..*.*): 'service' is at the start of the package name (maybe this can't happen in your scenario)
within(*..service.*)): 'service' is at the end of the package name
If you need to capture serviceFoo variants you could add further wildcards around service (I think): within(*..*service*.*)
You should use a pointcut expression like this:
within(your.base.package..service..*)
restrict to at least your base package (typically this is not an issue)
match 'service' keyword in your package name at any level
for example, this will match those classes :
your.base.package.service.ServiceClass
your.base.package.service.customer.ServiceClass
your.base.package.internal.service.ServiceClass
your.base.package.internal.service.customer.ServiceClass

GWT upload error FileNotFoundException

I'm uploading the files on the server like this: I create folder on the server and then I put all my uploading files in this folder
#Override
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
int cont = 0;
userNumber = request.getParameter("userNumber");
File f = new File(ConfAppServer.getRealContextPath() + "/edoc/"
+ userNumber);
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
cont++;
try {
String extension = item.getName().substring(
item.getName().length() - 3);
File file = null;
file = new File(ConfAppServer.getRealContextPath()
+ "/edoc/"
+ userNumber
+ System.getProperty("file.separator")
+ item.getName().substring(0,
item.getName().length() - 4) + "."
+ extension);
item.write(file);
receivedFiles.put(item.getFieldName(), file);
receivedContentTypes.put(item.getFieldName(),
item.getContentType());
response += "<file-" + cont + "-field>"
+ item.getFieldName() + "</file-" + cont
+ "-field>\n";
response += "<file-" + cont + "-name>" + item.getName()
+ "</file-" + cont + "-name>\n";
response += "<file-" + cont + "-size>" + item.getSize()
+ "</file-" + cont + "-size>\n";
response += "<file-" + cont + "-type>"
+ item.getContentType() + "</file-" + cont
+ "type>\n";
} catch (Exception e) {
throw new UploadActionException(e);
}
}
}
removeSessionFileItems(request);
return "<response>\n" + response + "</response>\n";
}
It works ver well on my colleague computer, but on my computer I get an error
There is an error in file name. Help me please fix my problem. Thanks.
As you can see the file name is not displaying correcly. So the problem is the encoding of the Request/Response. You need to add a filter servlet. Here is a tutorial.

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();
}