Sql/c# Error: Cannot insert explicit value for identity column when IDENTITY_INSERT is set to off - sql

I have a web application which is giving me the following exception:
InnerException {"Cannot insert
explicit value for identity column in
table 'Cover' when IDENTITY_INSERT is
set to OFF."} System.Exception
{System.Data.SqlClient.SqlException}
I'm trying to insert into a database which looks like the following:
dbo.File
FileID int PK
Title nvarchar(50)
ISBN nvarchar(50)
UploadDate datetime
UserName nvarchar(50)
dbo.Cover
CoverID int PK
CoverFileContent varbinary(max)
CoverMimeType nvarchar(50)
CoverFileName nvarchar(50)
FileID int FK
dbo.Cover
CoverID int PK
CoverFileContent varbinary(max)
CoverMimeType nvarchar(50)
CoverFileName nvarchar(50)
FileID int FK
In this database the File table has a one to many relationship with both the Cover, and the Pdf table. In my application, the user first enters a description of the file, and this updates the file table, then they upload a picture associated with the file which updates the Cover table, and then they upload a PDF file (I have not got this far yet).
Right now, my MVC c# code looks like the following:
FileController
//
//GET: /File/CreateFile
public ActionResult CreateFile()
{
File file = new File();
return View(file);
}
//
//POST: /File/CreateFile
[HttpPost]
public ActionResult CreateFile(FormCollection formvalues)
{
File file = new File();
if (TryUpdateModel(file))
{
filerepository.AddFileData(file);
filerepository.Save();
return RedirectToAction("CreateCover", "Cover", new { id = file.FileID });
}
return View(file);
}
Cover Controller
//
//GET: /File/CreateCover
public ActionResult CreateCover(int id)
{
Cover cover = new Cover();
cover.FileID = id;
return View(cover);
}
//
//POST: /File/CreateCover
[HttpPost]
public ActionResult CreateCover(Cover cover)
{
cover.CoverMimeType = Request.Files["CoverUpload"].ContentType;
Stream fileStream = Request.Files["CoverUpload"].InputStream;
cover.CoverFileName = Path.GetFileName(Request.Files["CoverUpload"].FileName);
int fileLength = Request.Files["CoverUpload"].ContentLength;
cover.CoverFileContent = new byte[fileLength];
fileStream.Read(cover.CoverFileContent, 0, fileLength);
cover.FileID = int.Parse(Request.Form["FileID"]);
filerepository.AddCoverData(cover);
filerepository.Save();
return View(cover);
//return View("CreatePdf", "Pdf", new { id = cover.FileID });
}
CreateCover View
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SampleApp.Models.Cover>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
CreateCover
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<h2>CreateCover</h2>
<% using (Html.BeginForm("CreateCover", "Cover", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<%: Html.HiddenFor(model => model.FileID) %>
<asp:Label ID="Label2" runat="server" Text="Please Select your eBook Cover" /><br />
<input type="file" name="CoverUpload" /><br />
<input type="submit" name="submit" id="Submit" value="Upload" />
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
I was able to upload a cover once, however ever since then I've been getting this error. I noticed that in my table I had forgotten to set the PK column as IDENTITY (1, 1), however I changed this and am still getting the error.
I also don't know if it's worth mentioning, but in my database for the one image I was able to upload, the binary content in the database is pretty much "0x00000...."...This seems wrong? :)
Any help or advice would be appreciated, thanks!

Solved this issue for anyone else who is having the same problem. Simply refreshed the model in Visual Studio and it seems to have done the trick.

Related

Unable to add records into database due to output.inserted id error

Hi everyone I have this code to try to add a record to my rider table in the database but when i run the code the following error occurs , may I know how do I fix this error?:
System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into
column 'RiderID', table 'bikestop.dbo.Rider'; column does not allow
nulls. INSERT fails.'
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace bikestop
{
public partial class bikestop_Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public int addRider()
{
string strConn = ConfigurationManager.ConnectionStrings
["BikeStop_DBString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"Insert INTO Rider (Name,RiderUsername,Password) " +
"OUTPUT INSERTED.RiderID " +
"VALUES (#Name,#RiderUsername,#Password)", conn);
cmd.Parameters.AddWithValue("#Name", txt_Name.Text);
cmd.Parameters.AddWithValue("#RiderUsername", txt_RiderUsername.Text);
cmd.Parameters.AddWithValue("#Password", txt_RiderPw.Text);
conn.Open();
int id = (int)cmd.ExecuteScalar();
conn.Close();
return id;
}
protected void btn_Register_Click(object sender, EventArgs e)
{
addRider();
}
}
}
Here is the code for the aspx file for the above code:
<%# Page Title="" Language="C#" MasterPageFile="~/bikestop_LoggedOut.Master" AutoEventWireup="true" CodeBehind="bikestop_Register.aspx.cs" Inherits="bikestop.bikestop_Register" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.auto-style1 {
width: 195px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<table class="w-100">
<tr>
<td class="auto-style1">Name</td>
<td>
<asp:TextBox ID="txt_Name" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">Username</td>
<td>
<asp:TextBox ID="txt_RiderUsername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">Password</td>
<td>
<asp:TextBox ID="txt_RiderPw" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td>
<asp:Button ID="btn_Register" runat="server" Text="Register" OnClick="btn_Register_Click" />
</td>
</tr>
</table>
</asp:Content>
Edit : Here is how the rider table looks :
and here is the code used to create it :
CREATE TABLE Rider(
RiderID int NOT NULL,
Name varchar(10) NOT NULL,
RiderUsername varchar(250) NOT NULL,
Password varchar(250) NOT NULL,
Primary Key (RiderID)
)
You are not inserting ID or you don't have auto-increment (so SQL cannot know which value to insert in your ID).
You can create your table like this:
CREATE TABLE Rider (
RiderID int NOT NULL PRIMARY KEY IDENTITY(1,1),
Name varchar(10) NOT NULL,
RiderUsername varchar(250) NOT NULL,
Password varchar(250) NOT NULL
)
and you will have auto-increment on ID column.
If you already have data, you cannot alter column to user identity(1,1), but you have a couple of options:
- Create a new table with identity(1,1) and drop the existing table
- Create a new column with identity(1,1) and drop the existing column
Note: You'll need to handle relations, but this is the cleanest way. I would probably go with second option.
More information about IDENTITY(1,1) on THIS LINK

In Webcenter Sites how to retrieve values of Page attributes using Template code

<assetset:getattributevalues name="sachin" attribute="Date_SV" listvarname="date_sv" typename="Content_Att" />
the above is normally the code to get value of Flex attribute when writing a template code. In fact typename is used for specifying Flex Attribute type.
What is the code for Page attribute? Secondly, what should the "typename" value be to get the value of Page attribute?
Here is an example of use to get a page attribute "article" :
<%
Session ses = SessionFactory.getSession();
AssetDataManager mgr =(AssetDataManager) ses.getManager( AssetDataManager.class.getName() );
AssetId id = new AssetIdImpl( "Page",new Long(ics.GetVar("cid")));
List attrNames = new ArrayList();
attrNames.add( "articles" );
AssetData data = mgr.readAttributes( id, attrNames );
AttributeData articlesData = data.getAttributeData( "articles" );
List<AssetId> relatedArticles = null ;
if (articlesData != null) {
relatedArticles=(List<AssetId>) articlesData.getData();
}
%>
However I don't recommend you to use this method if you are using WCS 12g : it is better to use controllers. The new philosophy is to read all your asset in your groovy controller and then use JSTL to render the values of your asset in your JSP.
Here are some code for the groovy controller :
public Map readAsset(String type, String name) {
Map assetMap = newAssetReader()
.forAssetName(type, name)
.selectAll(true)
.selectImmediateOnlyParents(true)
.includeLinks(true)
.includeLinksForBlobs(true)
.read();
}
Map myPage = readAsset("Page","Home")
models.put("homePage",myPage)
And here is the code in your JSP :
<%# taglib prefix="cs" uri="futuretense_cs/ftcs1_0.tld"%>
<%# taglib prefix="ics" uri="futuretense_cs/ics.tld"%>
<%# taglib prefix="fragment" uri="futuretense_cs/fragment.tld"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<cs:ftcs>
Here is the full page asset : ${homePage} <br/>
Here is just the page name : ${homePage.name} <br/>
</cs:ftcs>
Enjoy the ease of use ...
<assetset:getattributevalues name="sachin" attribute="Date_SV" listvarname="date_sv" typename="PageAttribute"
The typename should be "PageAttribute" without any spaces in between.

Retrieving information from a database

I am currently facing a dilemma within the project I am currently completing. I have a database where two tables are linked through foreign keys which are of data type int.
What I am trying to do is retrieve a value from tblProductColour and using the INNER JOIN function add the information to the other table which is tblProducts.
Here is the controller code,
public ActionResult Index()
{
var db = WebMatrix.Data.Database.Open("Database");
if (Session["AdministrationTeam"] != null)
{
View = "ViewAllProducts";
}
else
{
return RedirectToAction("Login", "Home");
}
return View(View, odb.tblproducts.SqlQuery("SELECT * FROM tblproducts t INNER JOIN tblProductColour ot ON t.ID = ot.ProductColour"));
}
The getters and setters that are stored within the model itself are as shown below,
public int? ProductColour {get;set;}
Here is the code I am using in my View to retrieve the information from the model,
#foreach (var item in Model) {
<div class="col-lg-3 col-md-6 col-sm-6 ">
<img src="#item.ProductImagePath" alt="Image Should Show Here" style="margin:auto auto; background-color:#fff;" width="100%" height="20%"/>
<p>Product Id: #Html.DisplayFor(modelItem => item.Id) </p>
<p> Product Name: #Html.DisplayFor(modelItem => item.ProductName)</p>
<p>Supplier: #Html.DisplayFor(modelItem => item.ProductSupplier) </p>
<p>Colour: #Html.DisplayFor(modelIteem => item.ProductColour) </p>
<p>Product Quantity: #Html.DisplayFor(modelItem => item.ProductQuantity)</p>
<p> Product Description: #Html.DisplayFor(modelItem => item.ProductDescription)</p>
</div>
When retrieving the information, I am faced with this error shown below,
Conversion failed when converting the varchar value 'Red' to data type int.
Here are the entities,
tblproducts
tblProductColour
If anyone has any solutions to how I can display the information it would be appreciated.
You're joining the wrong items
"SELECT * FROM tblproducts t INNER JOIN tblProductColour ot ON t.ID = ot.ProductColour"
should be
"SELECT * FROM tblproducts t INNER JOIN tblProductColour ot ON t.ProductColour = ot.ID"
You then need to change
#Html.DisplayFor(modelIteem => item.ProductColour)
in your view to (assuming the correct reference name for the table is tblProductColours) to
#Html.DisplayFor(modelIteem => item.tblProductColours.ProductColour)
- or
#Html.DisplayFor(modelIteem => item.ProductColours.ProductColour) -
may also work - just depends on how it is referenced, hopefully autocomplete will help you out.

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

How to get file tmp_name using JInput

I'm a bit stuck with this. I have this bit of code which manages to get the filename of my file:
class AControllerA extends JControllerForm
{
function save()
{
//Upload file
jimport('joomla.filesystem.file');
$jinput = JFactory::getApplication()->input;
$store_form = $jinput->get('jform', null, 'array');
$file = $store_form['img_url'];
echo $file;
}
}
*The file field has a name of jform[img_url];
However I cannot seem to get the 'tmp_name' for the file. Anyone know what I'm missing out? I'm a bit confused as to how jinput works...jrequest worked quite easily. Thanks!
models/forms/a.xml
<form enctype="multipart/form-data">
<fieldset>
<field
name="img_url"
type="file"
label=""
description=""
size="40"
class="inputbox"
default=""
/>
</fieldset>
</form>
How about like this:
$files = $input->files->get('jform', null);
$filename = $files['img_url']['tmp_name'];
echo $filename;
Check out documentation for Retrieving file data using JInput
Supposing you are using JForm and the file input type, then you can access the file using this:
$files = $jinput->files->get('jform');
$file = $files['img_url']['tmp_name']
Also make sure your form has the enctype="multipart/form-data" set, otherwise it will not work.
In your model you should have sth like this
public function getForm($data = array(), $loadData = false)
{
/**
* Get the Form
*/
$form = $this->loadForm('com_mycomponent.mycomponent', 'mycomponent',
array('control' => false, 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
Note that $loaddata and 'control' is set to false, when 'control' is false you can get file parameters as according to the name specified in your xml i.e the output form is like:
<input name="name in xml file" type="file" />
If 'control' => 'jform'
<input name="jform[name in xml file]" type="file" />
$loaddata= false means you dont need to fetch any data from the database to the form.
in your view.html.php you should have sth like this
public function display($tpl = null)
{
$this->formData = $this->get('Form');
$this->addToolbar();
parent::display($tpl);
}
Lets suppose I'll receive the requested file in "upload" method of "mycomponent" controller then it should have sth like this:
class MycomponentControllerMycomponent extends JControllerAdmin
{
public function upload()
{
//Retrieve file details from uploaded file, sent from upload form
$file = JFactory::getApplication()->input->files->get('name in xml
**$tmp_name** = $file['tmp_name'];
}
}
$tmp_name is Your required name