how to place images into sql server 2005 [duplicate] - sql-server-2005

This question already has answers here:
How to save an image from SQL Server to a file using SQL [closed]
(4 answers)
Closed 8 years ago.
I have written the following code to place the image path into sql server 2005 but its not working is their any alternate way to place images into sql server from clientside application.
example.html
<form id="addresslistingform" name="addresslistingform">
<fieldset id="fieldset1">
<legend>Address for listing</legend> Zipcode:<br />
<input size="30" type="text" id="zipcode" /><br />
Street No:<br />
<input size="30" type="text" id="addstreetno" class="number" name=
"streetno" /><br />
Street Name:<br />
<input size="30" type="text" id="addstreetname" class="required" name=
"streetname" /><br />
Upload a couple of pictures:<br />
<input size="30" type="file" id="addpicture" /><br />
</fieldset><input id="Addresslisting" type="image" src="images/Submit.png" align=
"left" />
</form>
example.js
$("#Addresslisting").click(function () {
var zipcode = ($("#addzipcode").val());
var streetno = ($("#addstreetno").val());
var streetname = ($("#addstreetname").val());
var image = ($("#addpicture").val());
var submitaddress = "{\"zipcode\":\"" + zipcode + "\",\"streetnumber\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"streetname\":\"" + streetname + "\",\"Imagelocation\":\"" + image + "\"}";
$.ajax({
type: "POST",
url: "/exampleproject/Afterlogin.asmx/addresslisting",
data: submitaddress,
contentType: "application/json; charset=utf-8",
success: ajaxSucceed,
dataType: "json",
failure: ajaxFailed
});
});
asmx webservices file
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool addresslisting(string zipcode, string streetnumber, string streetname, string Imagelocation)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "";
con.Open();
SqlCommand sqlcom = new SqlCommand();//declaring a new command
sqlcom.CommandText = "insert into Address_Listing(Zip_Code,Street_Number,Street_Name,Image_Location) values ('" + zipcode + "','" + streetnumber + "','" + streetname + "', '" + Imagelocation + "')"; //query for inserting data into contact table
sqlcom.Connection = con;//connecting to database
try
{
int success = sqlcom.ExecuteNonQuery();
con.Close();
if (success > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
con.Close();
return false;
}

I do not recommend storing images in SQL server, what you really should do is store the path to the image on your server in the SQL server.
Also p.campbell wasn't very helpful but very correct. Your database is going to get hacked with the code you currently have. You need to use SQL Parameters to prevent malicious SQL code from being injected.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx

Related

MVC4 Ajax.BeginForm routeValues converted to Type Name in HTML

I'm using Ajax.BeginForm in a MVC 4 Razor View.
#model EditViewDefinition
#{
RouteValueDictionary postParams = new RouteValueDictionary();
postParams.Add("entityUid", Model.EntityUid);
postParams.Add("entityId", ViewBag.entityId);
postParams.Add("viewUid", Model.UID);
string viewContainerId = "viewcontent_" + Model.UID.ToString().ToLower() + "_" + ViewBag.entityId.ToString();
}
then
using (Ajax.BeginForm("Edit", postParams, new AjaxOptions() { HttpMethod = "Post", OnSuccess = "submitSuccess('" + viewContainerId + "')" }))
{
...
}
Now when I check the resulting HTML in the browser, I get:
<form id="form0"
action="/View/Edit?Count=3&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D"
method="post"
data-ajax-success="submitSuccess('viewcontent_fb1a8d4c-fd30-4da4-b11c-bff99f3bb74f_1')"
data-ajax-method="Post"
data-ajax="true">
...
</form>
Why am I getting System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object in the action attribute instead of action="/View/Edit?entityUid=uid&entityId=1&viewUid=uid?
Thanks to Stephen Muecke's comment. I used var postParams = new { entityUid = Model.EntityUid, entityId = ViewBag.entityId, viewUid = Model.UID }; which worked.
Many Thanks Stephen.

SQL to search the entire table for a string

<!doctype html>
<html>
<title>Search</title>
<script type="text/javascript">
function query() {
var adVarWChar = 202;
var adParamInput = 1;
var pad = "C:\\Users\\azi!z\\Desktop\\Project\\Test.accdb";
var cn = new ActiveXObject("ADODB.Connection");
var strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pad;
cn.Open(strConn);
var cm = new ActiveXObject("ADODB.Command");
cm.ActiveConnection = cn;
cm.CommandText = "SELECT * FROM ImportFromExcel WHERE Module LIKE ? OR TestCase LIKE ? OR Openedby LIKE ? OR Status LIKE ?";
//cm.CommandText = "SELECT * FROM ImportFromExcel where TestCase LIKE ?";
cm.Parameters.Append(cm.CreateParameter(
"?",
adVarWChar,
adParamInput,
255,
"%" + document.getElementById("searchTerm").value + "%"));
var rs = cm.Execute(); // returns ADODB.Recordset object
if (rs.EOF) {
document.write("<p>No data found.</p>");
} else {
while (!rs.EOF) {
document.write("<p>" + rs.fields(0).value + ", ");
document.write(rs.fields(1).value + ", ");
document.write(rs.fields(2).value + ", ");
document.write(rs.fields(3).value + ", ");
document.write(rs.fields(4).value + ", ");
document.write(rs.fields(5).value + ", ");
document.write(rs.fields(6).value + ", ");
document.write(rs.fields(7).value + ", ");
document.write(rs.fields(8).value + ", ");
document.write(rs.fields(9).value + ", ");
document.write(rs.fields(10).value + ", ");
document.write(rs.fields(11).value + ", ");
document.write(rs.fields(12).value + ", ");
document.write(rs.fields(13).value + ", ");
document.write(rs.fields(14).value + ", ");
document.write(rs.fields(15).value + ".</p>");
var row = row.parentNode.rows[ ++idx ];
document.write(rs.fields(1).value + ".</p>");
rs.MoveNext();
}
}
rs.Close();
cn.Close();
}
</script>
</head>
<body>
<form method="get" name="SearchEngine" target="_blank">
<p style="text-align: center;"><span style="font-family:times new roman,times,serif;"><span style="font-size: 36px;"><strong>EA Search Engine</strong></span></span></p>
<p style="text-align: center;"> </p>
<p style="text-align: center;"><input maxlength="300" id="searchTerm" name="KeywordSearch" size="100" type="text" value="Enter Your Keyword Here" /></p>
<p style="text-align: center;"> </p>
<p style="text-align: center;"><input name="Search" type="button" value="Search" onclick="query();" /></p>
</form>
</body>
</html>
Please help me modify the SELECT statement in such a way that it covers the entire table (Not just the "TestCase" column) for ?.
Tried with changing the SELECT query to "SELECT * FROM ImportFromExcel WHERE col1 LIKE ? OR col2 LIKE ? OR col3 LIKE ?; ...", but it's not working.
If you want to search string in all columns of your table
you can concatenate all columns values and search value in the new column. For example
SELECT * FROM ImportFromExcel
WHERE Module
& column1
& column2
& column3 like '*substring*'

formData.append() not working - checked in Chrome,Mozilla, IE

Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.

Autocomplete issue in Yii

I'm using this
auto-complete plugin with my new project. It's working fine. See image
But I want to populate these fields when I select the result.
Here is my code:
var as = $("#query" + x + "").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
});
IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('id','description','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$data = array();
foreach ($items as $c) {
$suggestions[] = $c->description;
$data[] = $c->id;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'query' => 'q',
'suggestions' => $suggestions,
'data' => $data
)
);
exit;
}
grid jquery
jQuery("#addrow").click(function() {
jQuery(".item-row:last").after('<tr class="item-row">\n\
<td>\n\
<span id="delete' + x + '" style="cursor: pointer" class="icon-remove"></span>\n\
</td>\n\
<td class="item-code"><input autocomplete="off" name="code[]" id="code' + x + '" type="text" class="input-code"/></td>\n\
<td class="item-description"><input autocomplete="off" name="q" id="query' + x + '" type="text" class="input-description"/></td>\n\
<td class="item-unit"><input readonly autocomplete="off" name="unit[]" id="unit' + x + '" type="text" class="input-unit"/></td>\n\
<td class="item-qty"><input name="qty[]" autocomplete="off" value="0" id="qty' + x + '" type="text" class="input-qty"/></td>\n\
<td class="item-rate"><input readonly name="rate[]" autocomplete="off" value="125.25" id="rate' + x + '" type="text" class="input-rate"/></td>\n\
<td class="item-discount"><input name="discount[]" autocomplete="off" value="0.00" id="discount' + x + '" type="text" class="input-discount"/></td>\n\
<td class="item-total"><input name="total[]" readonly autocomplete="off" value="0.00" id="total' + x + '" type="text" class="input-amount"/></td>\n\
</tr>');
controller is already there
I have done it like this...
IN JQUERY....
var as = $("#query").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
onSelect: function(suggestion) {
var row = $(this).closest('tr');
row.find('.input-code').val(suggestion.id).attr('readonly', 'readonly');
row.find('.input-description').attr('readonly', 'readonly');
row.find('.input-unit').val(suggestion.unit).attr('readonly', 'readonly');
row.find('.input-rate').val(suggestion.rate).attr('readonly', 'readonly');
row.find('.input-qty').focus();
}
});
AND THEN IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('description', 'id','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$x=0;
foreach ($items as $c) {
$suggestions[$x]['value'] = $c->description;
$suggestions[$x]['id'] = $c->id;
$suggestions[$x]['rate'] = $c->rate;
$suggestions[$x]['unit'] = $c->unit;
$x++;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'suggestions' => $suggestions,
)
);
exit;
}
thats it...!
Sample code as shown below
$('#yourautoCompleteId').change(function(){
var selecteddata=$(this).val();
$.ajax({
url: "'.$this->createUrl('Controller/yourMethod').'",
data: {
//special:specialisation,
data :selecteddata,
},
type:"GET",//you can also use POST method
dataType:"html",//you can also specify for the result for json or xml
success:function(response){
//write the logic to get the response data as u need and set it to the fields
$("#dataId").val("SetHere");
$('#quantityId').val("setHere");
},
error:function(){
//TODO: Display in the poll tr ifself on error
alert("Failed request data from ajax page");
}
});
})
get the data in the controller using post and query with this data and send the result as u need and set to the fields as shown in the sample

Banking API queried by Javascript

I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).