It's checking only firs row in table. help someone :) C# winForm - c#-5.0

SqlConnection con = new SqlConnection(#"Data Source=(local)\SQLEXPRESS; Integrated Security= SSPI;" + "Initial Catalog = CarRent_vaxo;");
con.Open();
string strSQL = "select * from AccesList";
SqlCommand myCommand = new SqlCommand(strSQL, con);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
myDataReader.Read();
{
if (usertextBox.Text == myDataReader["User"].ToString() && paswordTextBox.Text == myDataReader["Password"].ToString())
{
this.Hide();
ResultForm rf = new ResultForm();
rf.Show();
}
else if (usertextBox.Text == "" || paswordTextBox.Text == "")
{
Notificarion2.Text = "PLEASE FILL THE BOXES !!!";
}
else
{
Notificarion2.Text = "WRONG USER OR PASSWORD !!!";
usertextBox.Text = "";
paswordTextBox.Text = "";
}
}
}

You should read from SqlDataReader in a while loop as
while (myDataReader.Read())
{
//your code goes here
}
myDataReader.Close();
http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx

Related

How to simplify multiple if else statement using Java

I've use-case where I've to validate two inputs and return success/failed in responses.
Please find my code below, I feel I'm using too many if-else statements - how can we simplify this?
I've to check given string is null or not, then check if matches the pattern - then return success or failure based on below given conditions:
public class Main {
public static void main(String[] args) {
// Scenario 1: -> Return Success
String input1 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
String input2 = "bearer kiIkdqAplMNbeieW3dJKidAkdmElsEpsles";
// Scenario 2: -> Return Success
//String input1 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
//String input2 = null;
// Scenario 3: -> Return Failed
//String input1 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
//String input2 = "bearer ";
// Scenario 4: -> Return Failed
//String input1 = null;
//String input2 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
String result = validate(input1, input2);
System.out.println("result: " +result);
}
private static String validate(String input1, String input2) {
Pattern pattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+)=*$", Pattern.CASE_INSENSITIVE);
String status ="failed";
if (input1 != null && input2 != null) {
if (StringUtils.startsWithIgnoreCase(input1, "bearer")
&& StringUtils.startsWithIgnoreCase(input2, "bearer")) {
if (!pattern.matcher(input1).matches() || !pattern.matcher(input2).matches()) {
System.out.println("Pattern not match");
// throw exception here
}
status = "success";
}
} else if (input1 != null) {
if (StringUtils.startsWithIgnoreCase(input1, "bearer")) {
if (!pattern.matcher(input1).matches()) {
System.out.println("Pattern not match");
// throw exception here
}
status = "success";
}
}
return status;
}
}
You can group the ifs related to the same input
if (input1 != null) {
if (StringUtils.startsWithIgnoreCase(input1, "bearer")) {
// INTO
if (input1 != null && StringUtils.startsWithIgnoreCase(input1, "bearer")) {
And include the tests about input2 inside the if for input1
Final code
private static String validate(String input1, String input2) {
Pattern pattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+)=*$", Pattern.CASE_INSENSITIVE);
String status = "failed";
if (input1 != null && StringUtils.startsWithIgnoreCase(input1, "bearer")) {
if ((input2 != null && StringUtils.startsWithIgnoreCase(input2, "bearer") && !pattern.matcher(input2).matches())
|| !pattern.matcher(input1).matches()) {
System.out.println("Pattern not match");
// throw exception here
} else {
status = "success";
}
}
return status;
}

This program is automatically exiting after finishing any one action, why?

My program is exiting after giving one command every time and I am unable to find a logical reason why. I have checked all my loops and if-statements for exit codes but was not able to located any.
the program includes many classes and functions, but here is main:
int main()
{
int local_location = 0;
vector<string>Inventory = { "", "", "" };
unordered_set<string> excl = { "in", "on", "the", "with" };
string word;
array<string, 2> command;
size_t n = 0;
command.at(1) = "";
command.at(0) = "";
while (n < command.size() && cin >> word) {
auto search = excl.find(word);
if (search == excl.end())
command.at(n++) = word;
}
if (command.at(0) == "look") {
look(command.at(1), local_location, Inventory);
}
else if (command.at(0) == "get") {
look(command.at(1), local_location, Inventory);
}
else if (command.at(0) == "drop") {
look(command.at(1), local_location, Inventory);
}
else if (command.at(0) == "bag") {
bag(Inventory);
}
else if (command.at(0) == "go") {
look(command.at(1), local_location, Inventory);
}
}
Loop over standard input and reset the condition on n after processing the command.
while(cin>>word)
{
auto search = excl.find(word);
if (search == excl.end())
command.at(n++) = word;
if (n== command.size())
{
// process the command
// reset n=0
}
}

Creating SO via Webservice says customerID does not exist

Hello I have created a routine to connect two Systems: XXXXWIN10 that is a local system with Acumatica. XXXWIN10 system have to send information about sales order to Acumatica. I'm using screen webservice in order to create a Sales Order. When I execute to test my code, each time I receive that customerID could not be empty but I'm sending all the information and also the customer exist. Do you see something wrong in my code:
using System;
using System.Net.Security;
using System.Net;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Conexionspa.apitest;
using System.Globalization;
namespace Conexionspa
{
class Program
{
static void Main(string[] args)
{
string CVECLI = "";
string CVEORDEN = "";
string FEC_ORDEN = "";
string DESCUENTO = "";
string CVESERVI = "";
string CANTIDAD = "";
decimal QTY = 0;
string PIEZAS = "";
string CAPA_REQ = "";
string CAPA_OBT = "";
string KILOS = "";
string TIPO_ACERO = "";
string RECIPIENTE = "";
string DUREZA_OBT = "";
string FEC_PROMES = "";
string PRECIOME = "";
decimal PRECIO = 0;
string IMPORTE = "";
string PORPIEZA = "";
string MONEDA = "";
string TIPOCAMBIO = "";
string PLANTA = "";
string conexion = #"Data Source = XXXXWIN10,2433; Initial Catalog = SYSXXXX; User ID = sa; Password = XXXYYYZZZ";
string queryString = "SELECT CVECLI, CVEORDEN, FEC_ORDEN, DESCUENTO, CVESERVI, CANTIDAD, PIEZAS, CAPA_REQ, CAPA_OBT, KILOS, TIPO_ACERO, RECIPIENTE, DUREZA_OBT, FEC_PROMES, PRECIOME, IMPORTE, PORPIEZA, MONEDA, TIPOCAMBIO, PLANTA FROM [Ordenes de Trabajo] WHERE STATUS = 2";
SqlConnection conection = new SqlConnection(conexion);
try
{
conection.Open();
SqlDataReader leeordenes = null;
SqlCommand Command = new SqlCommand(queryString, conection);
leeordenes = Command.ExecuteReader();
while (leeordenes.Read())
{
CVECLI = leeordenes["CVECLI"].ToString();
CVEORDEN = leeordenes["CVEORDEN"].ToString();
FEC_ORDEN = leeordenes["FEC_ORDEN"].ToString();
DateTime FECORDEN = DateTime.Parse(FEC_ORDEN);
DESCUENTO = leeordenes["DESCUENTO"].ToString();
CVESERVI = leeordenes["CVESERVI"].ToString();
CANTIDAD = leeordenes["CANTIDAD"].ToString();
decimal.TryParse(CANTIDAD, out QTY);
PIEZAS = leeordenes["PIEZAS"].ToString();
CAPA_REQ = leeordenes["CAPA_REQ"].ToString();
CAPA_OBT = leeordenes["CAPA_OBT"].ToString();
KILOS = leeordenes["KILOS"].ToString();
TIPO_ACERO = leeordenes["TIPO_ACERO"].ToString();
RECIPIENTE = leeordenes["RECIPIENTE"].ToString();
DUREZA_OBT = leeordenes["DUREZA_OBT"].ToString();
FEC_PROMES = leeordenes["FEC_PROMES"].ToString();
DateTime FECPROMES = DateTime.Parse(FEC_PROMES);
PRECIOME = leeordenes["PRECIOME"].ToString();
decimal.TryParse(PRECIOME, out PRECIO);
IMPORTE = leeordenes["IMPORTE"].ToString();
PORPIEZA = leeordenes["PORPIEZA"].ToString();
MONEDA = leeordenes["MONEDA"].ToString();
TIPOCAMBIO = leeordenes["TIPOCAMBIO"].ToString();
PLANTA = leeordenes["PLANTA"].ToString();
apitest.Screen context = new apitest.Screen();
context.CookieContainer = new CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "http://localhost/XXXYYY/Soap/APITEST.asmx";
try
{
LoginResult result = context.Login("Admin#XXXYYY:P000", "AdminXXX");
}
catch(Exception ep)
{
Console.WriteLine("Error en las credenciales" + ep.Message );
}
try
{
SO301000Content SO301000 = context.SO301000GetSchema();
context.SO301000Clear();
SO301000Content[] SO301000result = context.SO301000Submit
(
new Command[]
{
new Value { Value = "SO", LinkedCommand = SO301000.OrderSummary.OrderType },
new Value { Value = "TADEO", LinkedCommand = SO301000.OrderSummary.Customer },
new Value { Value = "0000007", LinkedCommand = SO301000.OrderSummary.OrderNbr },
new Value { Value = CVEORDEN, LinkedCommand = SO301000.OrderSummary.ExternalReference },
new Value { Value = FEC_ORDEN, LinkedCommand = SO301000.OrderSummary.Date },
new Value { Value = CVESERVI, LinkedCommand = SO301000.DocumentDetails.InventoryID },
new Value { Value = CANTIDAD, LinkedCommand = SO301000.DocumentDetails.Quantity },
new Value { Value = PIEZAS, LinkedCommand = SO301000.OrderSummary.Description },
new Value { Value = CAPA_REQ + " " + CAPA_OBT + " " + KILOS + " " + TIPO_ACERO + " " + RECIPIENTE + " " + DUREZA_OBT, LinkedCommand = SO301000.DocumentDetails.LineDescription },
new Value { Value = FEC_ORDEN, LinkedCommand = SO301000.OrderSummary.RequestedOn },
new Value { Value = PRECIOME, LinkedCommand = SO301000.DocumentDetails.UnitPrice, Commit = true },
new Value { Value = "NA", LinkedCommand = SO301000.DocumentDetails.UOM },
new Value { Value = "USD", LinkedCommand = SO301000.OrderSummary.Currency },
new Value { Value = "AP3", LinkedCommand = SO301000.DocumentDetails.Warehouse },
SO301000.Actions.Save,
}
);
Console.WriteLine("Orden registrada");
Thread.Sleep(9000);
}
catch(Exception ex)
{
Console.WriteLine("Error al insertar O.T en Acumatica: " + ex.Message);
Thread.Sleep(5000);
}
}
}
catch (Exception mensaje)
{
Console.WriteLine("Error en las credenciales del SPA รณ Acumatica Web Service: " + mensaje);
Thread.Sleep(5000);
}
}
}
}
As far as I know, you should first set Order Type and Order Number, and only then all the other fields, i.e.
new Command[]
{
new Value { Value = "SO", LinkedCommand = SO301000.OrderSummary.OrderType },
new Value { Value = "0000007", LinkedCommand = SO301000.OrderSummary.OrderNbr },
new Value { Value = "TADEO", LinkedCommand = SO301000.OrderSummary.Customer },
//rest of fields
SO301000.Actions.Save,
}

How to fix this "if" statement?

The problem is that when the answer is null, it should show as "lollie or flavour did not enter", but it is not working.
var lollie;
var flavour;
lollie = prompt("Please enter type of lollie", "");
if (lollie != null) {
document.writeln("<p>lollie);
} else {
document.writeln(lollie = "lollie was not entered");
}
flavour = prompt("Please enter flavour", "");
if (flavour != null) {
document.writeln("<p> flavour <p>");
} else {
document.writeln(flavour = "You did not enter flavour");
}
You need to use && (logical AND) instead of || (logical OR):
var firstname;
var lastname;
var height;
firstname = prompt("Please enter first name of player 1", "");
if (firstname != null && firstname != "") {
document.writeln("<td>" + firstname + "</td>");
} else {
document.writeln(firstname = "First name not supplied");
}
lastname = prompt("Please enter Last name of player 1", "");
if (lastname != null && lastname != "") {
document.writeln("<td>" + lastname + "</td>");
} else {
document.writeln(lastname = "Last name not supplied");
}
height = prompt("Please enter height of player 1", "");
if (height != null && height != "") {
document.writeln("<td>" + height + "</td>");
} else {
document.writeln(height = "Height not supplied");
}
You'll also need to work a bit on your HTML markup, but I guess that is a Work In Progress.
Delete
firstname != ""
Only write this in if statement:
if(firstname !=null)
use && in your condition. and make sure you trim those variables.

Webmatrix - including int's in my search page

i have built a fully working search page for my WebMatrix property site. To summarize, it checks the query string, and if any of the defined values are present, it adds it to a list so it can iterate through them.
The problem, as you will see, if that it currently adds everything to the list as a string. This causes problems when i need to use the value as an INT (PropertyType and NumBedrooms should be int's). is there a way i can use both strings and int's in this scenario? can i add ints AND strings to the same list?
here's the code:
var db = Database.Open("StayInFlorida");
var proptype = db.Query("SELECT * FROM Property_Type");
IEnumerable<dynamic> queryResults;
//Search Variables
string searchTerm = "";
string resortID = "";
string propertyType = "";
string numBedrooms = "";
List<string> argList = new List<string>();
//Paging Variables
var pageSize = 6;
var totalPages = 0;
var count = 0;
var page = UrlData[0].IsInt() ? UrlData[0].AsInt() : 1;
var offset = (page -1) * pageSize;
//Request querystrings from URL
if (!String.IsNullOrWhiteSpace(Request.QueryString["searchTerm"]))
{
searchTerm = Request.QueryString["searchTerm"];
}
if (!String.IsNullOrWhiteSpace(Request.QueryString["resortID"]))
{
resortID = Request.QueryString["resortID"];
}
if (!String.IsNullOrWhiteSpace(Request.QueryString["propertyType"]))
{
propertyType = Request.QueryString["propertyType"];
}
if (!String.IsNullOrWhiteSpace(Request.QueryString["numBedrooms"]))
{
numBedrooms = Request.QueryString["numBedrooms"];
}
int numOfArguments = 0;
string selectQueryString = "SELECT * FROM Property_Info ";
if (searchTerm != "")
{
argList.Add(searchTerm);
selectQueryString += "WHERE FullDescription LIKE '%' + #0 + '%' OR BriefDescription LIKE '%' + #0 + '%' ";
numOfArguments++; //increment numOfArguments by 1
}
if (resortID != "")
{
argList.Add(resortID);
if (numOfArguments == 0)
{
selectQueryString += "WHERE ResortID = #0 ";
}
else
{
selectQueryString += "AND ResortID = #" + numOfArguments + " ";
}
numOfArguments++;
}
if (propertyType != "")
{
argList.Add(propertyType);
if (numOfArguments == 0)
{
selectQueryString += "WHERE PropertyTypeID = #0 ";
}
else
{
selectQueryString += "AND PropertyTypeID = #" + numOfArguments + " ";
}
numOfArguments++;
}
if (numBedrooms != "")
{
argList.Add(numBedrooms);
if (numOfArguments == 0)
{
selectQueryString += "WHERE NumBedrooms = #0 ";
}
else
{
selectQueryString += "AND NumBedrooms = #" + numOfArguments + " ";
}
numOfArguments++;
}
selectQueryString += "ORDER BY CreatedDate DESC";
string[] argArray = argList.ToArray();
queryResults = db.Query(selectQueryString, argArray);
count = queryResults.Count();
totalPages = count/pageSize;
if(count % pageSize > 0){
totalPages += 1;
}
Edited code after Polynomial's suggestion:
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Search Page";
var db = Database.Open("StayInFlorida");
var proptype = db.Query("SELECT * FROM Property_Type");
//Paging Variables
var pageSize = 6;
var totalPages = 0;
var count = 0;
var page = UrlData[0].IsInt() ? UrlData[0].AsInt() : 1;
var offset = (page -1) * pageSize;
IEnumerable<dynamic> queryResults;
//Request querystrings from URL
string selectQueryString = "SELECT * FROM Property_Info WHERE 0 = 0 AND NumBedrooms = #0 AND NumBathrooms = #1 ";
selectQueryString += "ORDER BY CreatedDate DESC";
queryResults = db.Query(selectQueryString, Request.QueryString["NumBedrooms"], Request.QueryString["NumBathrooms"]);
count = queryResults.Count();
totalPages = count/pageSize;
if(count % pageSize > 0){
totalPages += 1;
}
}
Well, there are lots of ways around the problem, I'm thinking the easiest one that doesn't involve not using named ordinal parameterization would be to use fixed ordinals for each search criteria and just not use the ones you don't need in the SQL statement. Your code is very long so I don't really want to try and rewrite the whole thing here, but basically if your db.Query() call has all of the potential arguments passed as parameters like this:
queryResults = db.Query(selectQueryString, Request.QueryString["searchTerm"], Request.QueryString["resortId"]).AsInt(), Request.QueryString["propertyType"].AsInt() /* etc etc */);
Then your ordinals are always the same number. searchTerm is always #0, resortId is always #1 etc, etc. You then don't need the array at all and just need to build up an appropriate SQL statement for what the user specified, for example some WHERE clauses that would all fit with the code above could be:
"WHERE ResortID = #1"
"WHERE PropertyType = #2"
"WHERE ResortID = #1 AND PropertyType = #2"
"WHERE Name = #0"
"WHERE Name = #0 AND ResortID = #1 AND PropertyType = #2"
In the case of the clauses that only use one or two of the parameters, the others are just ignored and hopefully everything will work as you intend.
Edit to show code:
// Basic beginning of the select statement
string selectQueryString = "SELECT * FROM Property_Info WHERE 0 = 0 ";
// Check to see if the user specified bedrooms, if they did add to the select statement
if (Request.QueryString["NumBedrooms"].AsInt() > 0)
{
selectQueryString += "AND NumBedrooms = #0 ";
}
// Same for the number of bathrooms
if (Request.QueryString["NumBathrooms"].AsInt() > 0)
{
selectQueryString += "AND NumBathrooms = #1 ";
}
// ** Add more criteria to your select list here by checking for valid values and concatenating your string **
// Finally add the order by on the end
selectQueryString += "ORDER BY CreatedDate DESC";
// Execute the statement
queryResults = db.Query(selectQueryString, Request.QueryString["NumBedrooms"].AsInt(), Request.QueryString["NumBathrooms"].AsInt());
This should give you a very flexible and expandable search criteria system that is happy with zero, one or many criteria.