SQL statement check for concatenated value and return statement if not found - sql

I am trying to search a two column table with a CustomerID and a ServID. The primary key is the combination of both. I want the query to search if the combination is there. If it is return something I can use in c# to cancel the input or if it is not found have it insert the record. This is as far as I have made it after hours of searching.
IF (SELECT * FROM Cus_Ser WHERE customerID=inputnumber AND ServID=inputnumber) IS NULL
PRINT 'Already Exists'
ELSE
INSERT INTO Cus_Ser(CustomerID,ServID) VALUES(inputnumber, inputnumber)
Here is the code
#using WebMatrix.Data
#{
var CustomerID = Request.QueryString["CustomerID"];
var ServID = 0;
var db = Database.Open("Azure");
var selectedData = db.Query("SELECT * FROM Customer INNER JOIN Cus_Ser ON Customer.customerID=Cus_Ser.customerID INNER JOIN Service ON Cus_Ser.ServID=Service.ServID WHERE customer.CustomerID =" + CustomerID);
var grid = new WebGrid(source: selectedData);
var selectedData2 = db.Query("SELECT * FROM Service");
var grid2 = new WebGrid(source: selectedData2);
if (IsPost)
{ if (int.TryParse(Request.Form["ServID"], out int numbertest))
{
ServID = Int32.Parse(Request.Form["ServID"]);
var dbCommandSearch = "SELECT * FROM Cus_Ser WHERE customerID=" + CustomerID + " AND ServID=" + ServID;
//search = db.QuerySingle(dbCommandSearch);
//if ((CustomerID, "ServID") != search
db = Database.Open("Azure");
var insertCommand = "INSERT INTO cus_ser (customerID,ServID)VALUES(" + CustomerID + ", " + ServID + ")";
db.Execute(insertCommand);
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
//else
//{
//Validation.AddFormError("Entered Value is Not a Service Numberr");
//}
else
{
Validation.AddFormError("Entered Value is NOT a Service Number");
}
} }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add Service</title>
<style>
.validation-summary-errors {
border: 2px dashed red;
color: red;
font-weight: bold;
margin: 12px;
}
</style>
</head>
<body>
<form method="post">
<fieldset>
<legend>Input Service To Add</legend>
<p>
<label for="ServID">Service ID:</label>
<input type="text" name="ServID" value="#ServID" />
</p>
<input type="hidden" name="CustomerID" value="#CustomerID" />
<p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p>
</fieldset>
</form>
<p>Return to customer listing</p>

Multiple Inline SQL Statements
Your sample code seems to be very close. The QuerySingle method will return null if no matches are found. Thus you can check for a null value before issuing the insert statement, with something like:
ServID = Int32.Parse(Request.Form["ServID"]);
var dbCommandSearch = "SELECT * FROM Cus_Ser WHERE customerID=" + CustomerID + " AND ServID=" + ServID;
search = db.QuerySingle(dbCommandSearch);
if (search == null) { // record does not already exist
var insertCommand = "INSERT INTO cus_ser (customerID,ServID)VALUES(" + CustomerID + ", " + ServID + ")";
db.Execute(insertCommand);
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
else
{
Validation.AddFormError("Entered Value is Not a Service Numberr");
}
Single SQL Statement
You can combine this all into one big SQL statement, something like:
var sql = #"IF EXISTS (SELECT 1 FROM Cus_Ser WHERE customerID=#0 AND ServID=#1)
SELECT 0 as [Inserted];
ELSE
BEGIN
INSERT INTO Cus_Ser(CustomerID,ServID) VALUES(#0, #1)
SELECT 1 as [Inserted];
END";
You can execute this as a parameterized query, which is much safer* than the code you have:
var response = db.QuerySingle(sql, CustomerID, ServID); // passing the input value as a parameter
if (response.Inserted == 1) {
// WebMatrix might convert to a bool, in which you would want `response.Inserted == true` instead
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
else
{
Validation.AddFormError("Entered Value is Not a Service Numberr");
}
As I am not deeply familiar with WebMatrix, I am not 100% sure about this code. Hopefully it sets you in the right direction.
A word of warning: your original code is vulnerable to something called a SQL injection attack. Most programmers start out making that mistake; I know that I did. In summary: that inputnumber parameter could have a SQL statement in it instead of a number. If someone crafts that SQL Statement just right, then they could cause a lot of damage. For an entry-level programming assignment it is not something to worry about in detail. But as you progress in coding, you will need to learn how to use parameterized queries in order to guard against SQL injection. A few useful references:
SQL Injection
Introduction to Working with a Database in ASP.NET Web Pages (Razor) Sites

Related

SQL how to select data in terms of weeks

Is it in any way possible to select data from the database in spans of weeks?
I use cshtml (not MVC) and webmatrix if that makes any difference.
var dbQueryAllVariants = "SELECT * FROM Test WHERE exercise = " + exercise + " AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
So right now I'm using this, I put in a start date (ex. 2016-11-01) and end date (ex. 2016-11-30) (yyyy-mm-dd cuz north europe). This displays all the data in the database between those dates but since all rows in the database only have a day as date, the result to be viewed would be in day form, I'd like if it can do weeks, in this case, from first to last november as an example would be aprox 4 weeks, is this possible? Also, the data in the database is int values so I would like to be able to add those up to display a total of the week that gets displayed if that makes sense.
For example.
column 1 column 2 column 3
5 . . . . 6 . . 2016-11-13
8 . . . . 10 . . 2016-11-15
6 . . . . 3 . . 2016-11-17
So as of right now it would display 3 days with a sum of 11 for day 1, 18 for day 2 and 9 for day 3, but while displayed in terms of weeks it would be 11+18+9=38, as for an example. This might not even be possible to begin with but I'd like to know how to do this if possible!
If this isn't a possible solution, is there a way to like select all the data in day form, put it in a array or whatever, and from there send it grouped as a weekly total based on the weeks of the year (ex. november contains week 44-48) something like that? What I'm trying to say is that if the end result is what I want, it doesn't matter how its done.
#{
//Calls for my website layout.
Layout = "~/_SiteLayout.cshtml";
//Browser title of the specific page.
Page.Title = "TEST";
//Opens database.
var db = Database.Open("SmallBakery");
//Variables.
var exercise = Request.Form["Exercise"];
var fromDate = Request.Form["fromDate"];
var toDate = Request.Form["toDate"];
var exerVariName = "";
var exerVariNameS = "";
var exerVariNameB = "";
var exerVariNameD = "";
//Defaults to show data between these
//dates if user dont choose any dates.
var noStartDate = "1970-01/01";
var noEndDate = "2099-12/31";
//If user does not choose eiter/any start/end date
//this will end up showing all results possible.
if (fromDate == "") {
fromDate = noStartDate;
}
if (toDate == "") {
toDate = noEndDate;
}
//Takes exerVariName from different dropdowns
//depending on which exercise is selected due to
//the fact that only one dropdown is visible at any time.
if (exercise == "1") {
exerVariName = Request.Form["exerVariNameS"];
} else if (exercise == "2") {
exerVariName = Request.Form["exerVariNameB"];
} else {
exerVariName = Request.Form["exerVariNameD"];
}
//Gets exercise variants to the dropdown menu.
var getSVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 1 ORDER BY exerVariName";
var getBVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 2 ORDER BY exerVariName";
var getDVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 3 ORDER BY exerVariName";
var getData = "SELECT * FROM Test";
//Gets the date.
var getDate = "SELECT date FROM Test";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<!-- Form for posting. -->
<form method="post" action="">
<!-- Radio buttons to select which data to show. -->
<div>
<label>Squat</label>
<input type="radio" name="Exercise" id="hej1" value="1" />
</div>
<div>
<label>Benchpress</label>
<input type="radio" name="Exercise" id="hej2" value="2" />
</div>
<div>
<label>Deadlift</label>
<input type="radio" name="Exercise" id="hej3" value="3" />
</div>
<div>
<!-- Dropdown menu with squat-variant-names. -->
<select id="exerVariNameS" name="exerVariNameS">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getSVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
<!-- Dropdown menu with bench-variant-names. -->
<select id="exerVariNameB" name="exerVariNameB">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getBVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
<!-- Dropdown menu with deadlift-variant-names. -->
<select id="exerVariNameD" name="exerVariNameD">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getDVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
</div>
<div>
<!-- Date calendar. -->
<input placeholder="From date..." type="text" class="datepicker" name="fromDate" value="#fromDate">
</div>
<div>
<!-- Date calendar. -->
<input placeholder="To date..." type="text" class="datepicker" name="toDate" value="#toDate">
</div>
<!-- The submit button. -->
<input type="submit" value="Show" class="submit" />
</form>
<!-- Displays database value on submit click based on choosen radiobutton from form-post above. -->
#if (IsPost) {
//When I select ALL in the dropdown it runs
//this line because there is no filter for 'exerVariName'.
// var dbQueryAllVariants = "SELECT * FROM Test WHERE exercise = " + exercise + " AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
//When I select a specific exercise variation.
var dbQuerySingleVariant = "SELECT * FROM Test WHERE exercise = " + exercise + " AND exerVariName = '" + exerVariName + "' AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
//This is what the problem is....
var dbQueryAllVariants = "SELECT DATEPART(week, date) AS weekNumber, sum(kg)+sum(sett) AS grandTotalPerWeek FROM Test WHERE Exercise = " + exercise + " AND DATEPART(week, date) BETWEEN DATEPART(week, " + fromDate + ") AND DATEPART(week, " + toDate + ") GROUP BY DATEPART(week, date)";
var dbQuery = "";
//If dropdown = select all, it does, else, it show the one I pick.
if (exerVariName == "all") {
dbQuery = dbQueryAllVariants;
} else {
dbQuery = dbQuerySingleVariant;
}
//Foreach to write out all the data from db.
var sumTotalWeight = 0;
foreach (var get in db.Query(dbQuery)) {
<a>Weight: </a>
<a>#get.Kg kg</a>
<a> Sets: </a>
<a>#get.Sett</a>
<a> Reps: </a>
<a>#get.Rep</a>
<a> Total reps: </a>#(get.Sett * get.Rep)
<a> #get.date</a>
var totalWeight = #get.Kg * #get.Sett * #get.Rep;
sumTotalWeight += totalWeight;
<a> #totalWeight</a>
<br>
}
#sumTotalWeight
}
</body>
From your comments one may conclude you are using the MSSQL Server Compact Edition.
If that's correct then you could use the DATEPART function to extract the week of the year for each date, and then group by week and sum all results for each.
Something like this:
SELECT
sum(column1)+sum(column2) AS grandTotalPerWeek
FROM Test
WHERE Exercise = {Exercise}
AND DATEPART(week, date) = {weekNumber}
Where {Exercise} and {weekNumber} are the variables to be substituted.
Or like this, if you need to request multiple weeks at once:
SELECT
DATEPART(week, date) AS weekNumber,
sum(column1)+sum(column2) AS grandTotalPerWeek
FROM Test
WHERE Exercise = {Exercise}
AND DATEPART(week, date) IN ({listOfWeekNumbers})
GROUP BY DATEPART(week, date)
Where {Exercise} and {listOfWeekNumbers} are the variables to be substituted.
In either case, when we talk about week numbers we talk about integer values. 1 means the first week of the year, 2 the second week, ...
Example: Get the values for January
SELECT
DATEPART(week, date) AS weekNumber,
sum(kg)+sum(sett) AS grandTotalPerWeek
FROM Test
WHERE Exercise = 1
AND DATEPART(week, date) IN (1,2,3,4)
GROUP BY DATEPART(week, date)
So, to use this SQL you need to translate dates into week numbers. If you only have dateFrom and dateTo then you can try something like this:
SELECT
DATEPART(week, date) AS weekNumber,
sum(kg)+sum(sett) AS grandTotalPerWeek
FROM Test
WHERE Exercise = 1
AND DATEPART(week, date) BETWEEN DATEPART(week, {dateFrom}) AND DATEPART(week, {dateTo})
GROUP BY DATEPART(week, date)
DATEPART documentation on MSDN.

Product autocomplete input on module (Prestashop)

I'm developing a prestashop module that has to make lists of existing products.
For the configuration panel of the module, using renderForm() and getContent(), I'm trying to replicate the "accesories" capability, where you start writing some info of a product on an input, and it shows the products that are a match. When selecting that product, it gets added on a list. Like this:
This a screenshot of Catalog / Products / Associations tab.
I'm trying with PS 1.6.0.14 and PS1.6.1.0RC3. How would I replicate this functionality to get lists of products on a module configuration panel?
I tried looking here Prestashop AdminProductsController.php but I don't really understand where half of that info is coming from.
There is an autocomplete plugin in prestashop you got to use that for this. Its in js->jquery->plugins you got to add this plugin into your module to make it work.
I think that to achieve that functionality, the renderForm() function won't be enough since you have to bind some javascript and some custom html.
The process of writing a fully functional module is a bit long but by taking the accessories functionality as a starting point it wont be so hard and you will always have a reference on "how-to-do-it".
I would go with this:
1) first create your
getContent()
function to be able to show the custom template and the product associated by your module so we will have something along:
public function getContent(){
//post process part to save the associations
if(Tools::isSubmit('saveMyAssociations'){
... //we will see it later
}
$my_associations = MyModule::getAssociationsLight($this->context->language->id,Tools::getValue('id_product')); //function that will retrieve the array of all the product associated on my module table.
$this->context->smarty->assign(array(
'my_associations' => $my_associations,
'product_id' => (int)Tools::getValue('id_product')
));
return $this->display(__FILE__, 'views/templates/admin/admintemplate.tpl'); //custome template to create the autocomplete
}
//our little function to get the already saved list, for each product we will retrieve id, name and reference with a join on the product/product_lang tables.
public static function getAssociationsLight($id_lang, $id_product, Context $context = null)
{
if (!$context)
$context = Context::getContext();
$sql = 'SELECT p.`id_product`, p.`reference`, pl.`name`
FROM `'._DB_PREFIX_.'my_associations`
LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.`id_product`= `id_product_2`)
'.Shop::addSqlAssociation('product', 'p').'
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (
p.`id_product` = pl.`id_product`
AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').'
)
WHERE `id_product_1` = '.(int)$id_product;
return Db::getInstance()->executeS($sql);
}
2) create a template that will be able to show the automplete and the list.
Here we will loop trough the saved associations to create our autocomplete list, and we will do it with some hidden field to keep track of the ids/name and also a visible list were we will have a delete button for each row.
<input type="hidden" name="inputMyAssociations" id="inputMyAssociations" value="{foreach from=$my_associations item=accessory}{$accessory.id_product}-{/foreach}" />
<input type="hidden" name="nameMyAssociations" id="nameMyAssociations" value="{foreach from=$my_associations item=accessory}{$accessory.name|escape:'html':'UTF-8'}¤{/foreach}" />
<div id="ajax_choose_product_association">
<div class="input-group">
<input type="text" id="product_autocomplete_input_association" name="product_autocomplete_input_association" />
<span class="input-group-addon"><i class="icon-search"></i></span>
</div>
</div>
<div id="divMyAssociations">
{foreach from=$my_associations item=accessory}
<div class="form-control-static">
<button type="button" class="btn btn-default delAssociation" name="{$accessory.id_product}">
<i class="icon-remove text-danger"></i>
</button>
{$accessory.name|escape:'html':'UTF-8'}{if !empty($accessory.reference)}{$accessory.reference}{/if}
</div>
{/foreach}
</div>
<input type="submit" name="submitMyAssociations" id="submitMyAssociations" value="Send"/>
<input type="hidden" name="productId" id="productId" value="{$product_id|escape:'html'}"/>
3) Now we can add the javascript to bind an autocomplete on the main input and perform all the logic for each action
$(document).ready(function(){
//our function wrapper.
var initMyAssociationsAutocomplete = function (){
//initialize the autocomplete that will point to the default ajax_products_list page (it returns the products by id+name)
$('#product_autocomplete_input_association')
.autocomplete('ajax_products_list.php', {
minChars: 1,
autoFill: true,
max:20,
matchContains: true,
mustMatch:true,
scroll:false,
cacheLength:0,
formatItem: function(item) {
return item[1]+' - '+item[0];
}
}).result(addAssociation);
//as an option we will add a function to exclude a product if it's already in the list
$('#product_autocomplete_input_association').setOptions({
extraParams: {
excludeIds : getAssociationsIds()
}
});
};
//function to exclude a product if it exists in the list
var getAssociationsIds = function()
{
if ($('#inputMyAssociations').val() === undefined)
return '';
return $('#inputMyAssociations').val().replace(/\-/g,',');
}
//function to add a new association, adds it in the hidden input and also as a visible div, with a button to delete the association any time.
var addAssociation = function(event, data, formatted)
{
if (data == null)
return false;
var productId = data[1];
var productName = data[0];
var $divAccessories = $('#divCrossSellers');
var $inputAccessories = $('#inputMyAssociations');
var $nameAccessories = $('#nameMyAssociations');
/* delete product from select + add product line to the div, input_name, input_ids elements */
$divAccessories.html($divAccessories.html() + '<div class="form-control-static"><button type="button" class="delAssociation btn btn-default" name="' + productId + '"><i class="icon-remove text-danger"></i></button> '+ productName +'</div>');
$nameAccessories.val($nameAccessories.val() + productName + '¤');
$inputAccessories.val($inputAccessories.val() + productId + '-');
$('#product_autocomplete_input_association').val('');
$('#product_autocomplete_input_association').setOptions({
extraParams: {excludeIds : getAssociationsIds()}
});
};
//the function to delete an associations, delete it from both the hidden inputs and the visible div list.
var delAssociations = function(id)
{
var div = getE('divMyAssociations');
var input = getE('inputMyAssociations');
var name = getE('nameMyAssociations');
// Cut hidden fields in array
var inputCut = input.value.split('-');
var nameCut = name.value.split('¤');
if (inputCut.length != nameCut.length)
return alert('Bad size');
// Reset all hidden fields
input.value = '';
name.value = '';
div.innerHTML = '';
for (i in inputCut)
{
// If empty, error, next
if (!inputCut[i] || !nameCut[i])
continue ;
// Add to hidden fields no selected products OR add to select field selected product
if (inputCut[i] != id)
{
input.value += inputCut[i] + '-';
name.value += nameCut[i] + '¤';
div.innerHTML += '<div class="form-control-static"><button type="button" class="delAssociation btn btn-default" name="' + inputCut[i] +'"><i class="icon-remove text-danger"></i></button> ' + nameCut[i] + '</div>';
}
else
$('#selectAssociation').append('<option selected="selected" value="' + inputCut[i] + '-' + nameCut[i] + '">' + inputCut[i] + ' - ' + nameCut[i] + '</option>');
}
$('#product_autocomplete_input_association').setOptions({
extraParams: {excludeIds : getAssociationsIds()}
});
};
//finally initialize the function we have written above and create all the binds.
initMyAssociationsAutocomplete();
//live delegation of the deletion button to our delete function, this will allow us to delete also any element added after the dom creation with the ajax autocomplete.
$('#divMyAssociations').delegate('.delAssociation', 'click', function(){
delAssociations($(this).attr('name'));
});
});
4) now you just need to save the associations made by your module autocomplete, and i suggest to perform it by first deleting any association made on a given product and then saving all of them. so you don't have to care about inserting or updating an entry
public function getContent(){
//post process part
if(Tools::isSubmit('saveMyAssociations'){
$product_id = (int)Tools::getValue('productId');
// see the function below, a simple query to delete all the associations on a product
$this->deleteMyAssociations($product_id);
if ($associations = Tools::getValue('inputMyAssociations'))
{
$associations_id = array_unique(explode('-', $associations));
if (count($associations_id))
{
array_pop($associations_id);
//insert all the association we have made.
$this->changeMyAssociations($associations_id, $product_id);
}
}
}
}
protected function deleteMyAssociations($product_id){
return Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'my_associations` WHERE `id_product_1` = '.(int)$product_id);
}
protected function changeMyAssociations($associations_id, $product_id){
foreach ($associations_id as $id_product_2)
Db::getInstance()->insert('my_associations', array(
'id_product_1' => (int)$product_id,
'id_product_2' => (int)$id_product_2
));
}
I hope it can help you to go through all of this.

ASP.NET Razor split record and increase by one

in my code I'm trying to display in a text box the record that follows the last one of my database. For example, if my last record is A560 I want to display A561. To achieve this I know I have to split the record and then manipulate it, but I haven't had any luck. Here is what the database looks like:
Point_ID Project No. Project Manager Comments
A558 1304 Oscar Duran Found destroyed
A559 1304 Oscar Duran Helicopter access
A560 1356 Julio Bravo Airport parking lot
This is my code so far:
#{
Layout = "~/_Layout.cshtml";
var db = Database.Open("ControlPoints");
var SelectCommand = "SELECT * FROM( SELECT TOP 5 * FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC )AS BaseData Order BY Point_ID ASC";
var SearchTerm = "";
if(!Request.QueryString["SearchCP"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE Point_ID = #0";
SearchTerm = Request.QueryString["SearchCP"];
}
if(!Request.QueryString["SearchProject"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE [Project Used on] LIKE #0";
SearchTerm = "%" + Request["SearchProject"] + "%";
}
var SelectData = db.Query(SelectCommand, SearchTerm);
var grid = new WebGrid(source: SelectData, rowsPerPage: 10);
}
#{
Validation.RequireField("Point_ID", " Required");
Validation.RequireField("ProjectNo", " Required");
Validation.RequireField("ProjectManager", " Required");
var Point_ID = "";
var ProjectNo = "";
var ProjectManager = "";
if(IsPost && Validation.IsValid() ){
Point_ID = Request.Form["Point_ID"];
ProjectNo = Request.Form["ProjectNo"];
ProjectManager = Request.Form["ProjectManager"];
db = Database.Open("ControlPoints");
var InsertCommand = "INSERT INTO AllControlMergedND ([Point_ID], [Project No.], [Project Manager]) VALUES(#0, #1, #2)";
db.Execute(InsertCommand, Point_ID, ProjectNo, ProjectManager);
}
var SelectLastCP = "SELECT TOP 1 Point_ID FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC";
var SelectData2 = db.QuerySingle(SelectLastCP);
var SuggestedPoint_ID = SelectData2.Point_ID;
}
<h2>Airborne Imaging Control Points Database</h2><br/><br/>
<form method="get">
<fieldset>
<legend>Search Criteria</legend>
<div>
<p><label for="SearchCP">Control Point ID:</label>
<input type="text" name="SearchCP" value="#Request.QueryString["SearchCP"]" />
<input type="submit" value="Search"/></p>
</div>
<div>
<p><label for="SearchProject">Project:</label>
<input type="text" name="SearchProject" value="#Request.QueryString["SearchProject"]" />
<input type="Submit" value="Search" /></p>
</div>
</fieldset>
</form>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Point_ID"),
grid.Column("Project No."),
grid.Column("Project Used on"),
grid.Column("WGS84 Lat"),
grid.Column("WGS84 Long"),
grid.Column("Ellips_Ht"),
grid.Column("Project Manager"),
grid.Column("Comments")
)
)
<br/><br/>
</div>
<form method="post">
<fieldset>
<legend>Create Control Point(s)</legend>
<p><label for="Point_ID">Point ID:</label>
<input type="text" name="Point_ID" value="#SuggestedPoint_ID" />
#Html.ValidationMessage("Point_ID")</p>
<p><label for="ProjectNo">Project No:</label>
<input type="text" name="ProjectNo" value="#Request.Form["ProjectNo"]" />
#Html.ValidationMessage("ProjectNo")</p>
<p><label for="ProjectManager">Project Manager:</label>
<input type="text" name="ProjectManager" value="#Request.Form["ProjectManager"]" />
#Html.ValidationMessage("ProjectManager")</p>
<p><input type="submit" name="ButtonConfirm" value="Confirm" /></p>
</fieldset>
</form>
As you can see, all I am able to do is to display the last record of my database in the text box, which in this case would be A560. The variable 'SuggestedPoint_ID' is holding that record. I have tried converting the data type, but had no success. Any help would be greatly appreciated.
Update:
What I need is to do the following. Split A560 in two parts 'A' and '560'. Then increment '560' by one to obtain '561' and finally attach 'A' again to '561' in order to obtain the next increment 'A561'.
If you are trying to convert "A560" to int for example then it won't work because you don't have a valid number. A needs to be removed.
var SuggestedPoint_ID = SelectData2.Point_ID.Replace("A", "");
This is not my recommended way to do it as A could be anything such as AA or B or ZZZZ. My point is that you need to describe what you need to get a better solution to your problem.
UPDATE
var source = "A560";
var lhs = source.Substring(0, 1);
var tmp = source.Replace(lhs, "");
int rhs;
if(int.TryParse(tmp, out rhs))
{
rhs++;
}
var result = string.Format("{0}{1}", lhs, rhs);

pass an ID with hyperlik but cant get this ID value from a fk in one table when i click in insert

Something strange happened in my codes, actually I have a hyperlink that pass ID value in a query string to second page.in second page i have 2 sql datasource that both these sql datasources should get this id value and pass it to a filter parameter to show sth in datalist.
so in another word I have a first page that has an hyperlink read ID value from a datasource and pass it to second page.its like below:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/forumpage.aspx?ID="+Eval("ID")%>'><%#Eval("title")%> </asp:HyperLink>
then in second page i have one sql datasource with a query like this ...where ID=#id and get this id in query string from db.it work great . but i have problem with second sql datasource in second page it has a query sth like below:...forms.question_id=#id
then in sql reference both to query string as ID that get by first page in hyperlink.
but when i click in insert button show me error with fk.
error:Error:The INSERT statement conflicted with the FOREIGN KEY
constraint "FK_forumreply_forumquestions". The conflict occurred in
database "forum", table "dbo.forumquestions", column 'ID'. The
statement has been terminated.
my tables
(question(ID,user_id(fk),Cat_id(fk),title,bodytext)
(reply(ID,userr_id(fk),questionn_id(fk),titlereply,bodytestreply);
When by hand in cb i gave a number in questionn_id like 1 it show me successful but when it want read from a filter by datasource this field face with problem.
plzzzz help i really need skip from this part.and cause i am new i guess I cant understand the logic way clearly.
<asp:SqlDataSource ID="sdsreply" runat="server"
ConnectionString="<%$ ConnectionStrings:forumConnectionString %>"
SelectCommand="SELECT forumreply.ID, forumreply.userr_id, forumreply.questionn_id, forumreply.bodytextreply, forumreply.datetimereply, forumquestions.ID AS Expr1, forumusers.ID AS Expr2, forumusers.username FROM forumquestions INNER JOIN forumreply ON forumquestions.ID = forumreply.questionn_id INNER JOIN forumusers ON forumquestions.user_id = forumusers.ID AND forumreply.userr_id = forumusers.ID where forumreply.questionn_id=#questionn_id">
<SelectParameters>
<asp:QueryStringParameter Name="questionn_id" QueryStringField="ID" />
</SelectParameters>
</asp:SqlDataSource>
it is cb for second page in insert button:
{
if (Session["userid"] != null)
{
lblreply.Text = Session["userid"].ToString();
}
else
{
Session["userid"]=null;
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
lblshow.Text = string.Empty;
string d = HttpContext.Current.User.Identity.Name;
lblshow.Text =d + "عزیز خوش آمدید." ;
foreach (DataListItem item in DataList2.Items)
{
Label questionn_idLabel = (Label)item.FindControl("questionn_idLabel");
Label userr_idLabel = (Label)item.FindControl("userr_idLabel");
lbltest.Text = string.Empty;
lbltest.Text = questionn_idLabel.Text;
lblreply.Text = string.Empty;
lblreply.Text = userr_idLabel.Text;
}
}
else
{
lblshow.Text = "اگر بار اول هست که می خواهید پاسخ دهید لطفا ابتدا ثبت نام و سپس لاگین فرمائید.";
}
}
{
if(HttpContext.Current.User.Identity.IsAuthenticated)
{
if (Page.IsValid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["forumConnectionString"].ConnectionString);
try
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into forumreply (userr_id,questionn_id,bodytextreply,datetimereply)values(#userr_id,#questionn_id,#bodytextreply,#datetimereply)", con);
cmd.Parameters.AddWithValue("userr_id",lblreply.Text);
cmd.Parameters.AddWithValue("questionn_id",lbltest.Text);
cmd.Parameters.AddWithValue("bodytextreply",txtbody.Text);
cmd.Parameters.AddWithValue("datetimereply",DateTime.Now );
cmd.ExecuteNonQuery();
}
catch (Exception exp)
{
Response.Write("<b>Error:</b>");
Response.Write(exp.Message);
}
finally
{
con.Close();
}
lblmsg.Text = "پیام شما با موفقیت ثبت گردید.thx";
lblshow.Visible = false;
//lbltxt.Text = txtbody.Text;
txtbody.Text = string.Empty;
}
}
else
{
lblmsg.Text = string.Empty;
Session["rem"] = Request.UrlReferrer.AbsoluteUri;
Response.Redirect("~/login.aspx");
}
}

How do I send an additional parameter to a function?

I have this code which displays text from a Web SQL database:
<span contenteditable="true"
onkeyup="updateRecord('+item['id']+', this)">' + item['product'] + '</span>
When I edit the text it calls the updateRecord function and updates the value.
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET product = ? WHERE id = ?",
[textEl.innerHTML, id], null, onError);
});
}
I have several of these values I'm trying to work with though. So I would like to specify the column. The above code works if I set the column to product in the function, in the following code I'm trying to send an additional parameter to the function but it's not working. What am I doing wrong here?
<span contenteditable="true"
onkeyup="updateRecord('+item['id']+', 'product', this)">'+ item['product'] + '</span>
function updateRecord(id, column, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET ? = ? WHERE id = ?",
[column, textEl.innerHTML, id], null, onError);
});
}
Same with any full-bodied DBMS, you cannot parameterize the column names, only values.
So you need to do it like this
<span contenteditable="true"
onkeyup="updateRecord('+item['id']+', 'product', this)">'+ item['product'] + '</span>
function updateRecord(id, column, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET " + column + " = ? WHERE id = ?",
[column, textEl.innerHTML, id], null, onError);
});
}