Asp.Net Entity Framework textbox to database - sql

New to this.
I have a database, one table "Logins":
FirstName, LastName, Birthdate, Email
I am using VS2015 and I am using Entity Framework 6 and have my database loaded in through there. I have text boxes and I want the data entered in them to insert into the table "Logins" when submit is clicked.
I've been looking online and watching videos an I just seem to be getting more confused. How do I do this?
This is what I have on the back end code (the front just has the textboxes and submit button):
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (LoginData2Entities lg = new LoginData2Entities())
{
DateTime birthdate = DateTime.Parse(tbBirth.Text);
Logins l = new Logins();
l.FirstName = tbFirstName.Text;
l.LastName = tbLastName.Text;
l.Birthdate = birthdate;
l.Email= tbEmail.Text;
lg.SaveChanges();
}
Nothing is saving to the database. How do I fix this?

You are not adding the Login object l with your LoginData2Entities object so there is nothing to save into the database.. add this in your code.
lg.Logins.Add(l);
it will look like this..
using (LoginData2Entities lg = new LoginData2Entities())
{
DateTime birthdate = DateTime.Parse(tbBirth.Text);
Logins l = new Logins();
l.FirstName = tbFirstName.Text;
l.LastName = tbLastName.Text;
l.Birthdate = birthdate;
l.Email= tbEmail.Text;
lg.Logins.Add(l);
lg.SaveChanges();
}

you are not adding the object to database before performing savechanges..
using (LoginData2Entities lg = new LoginData2Entities())
{
DateTime birthdate = DateTime.Parse(tbBirth.Text);
Logins l = new Logins();
l.FirstName = tbFirstName.Text;
l.LastName = tbLastName.Text;
l.Birthdate = birthdate;
l.Email= tbEmail.Text;
lg.Logins.Add(l); //add the object
lg.SaveChanges();
}

Related

SSRS/ASP.NET Setting all required report input parameters but still getting:One or more parameters required to run the report have not been specified

Although this has been asked before, none of the answers provided solve my issue. I AM passing in all of the required report parameters and all have HasValidValue set in the State property of the parameter array of ExecutionInfo. I am using ReportExecution2005.asmx in my ASP.NET web application. There is no GetParameters() call method to ReportExecution2005.ReportExecutionService object.
My report is calling a subreport so the input parameters are identical to the main report and the subreport. There are 4 single value inputs (two integer, two text) and then one Multivalue text input parameter which I supply multiple values for. I have double and tripled checked that the values I'm setting in the Multivalue input parameter match exactly one of the default parameters.
Here is the code that setups up the reports and renders/writes it out to a PDF file:
protected void btnPrintReq_Tests_Click(object sender, EventArgs e)
{
string query = string.Format("SELECT PatientFName, PatientLName, Address1 + ' ' + Address2 AS Address, City, Region AS State, PostalCode, Email, Phone, Gender, DOB, CONVERT(VARCHAR, ClinicID) AS ClinicID FROM Tbl_ShippingDropShip WHERE RequestID = {0}", giRequestID.ToString());
string sClinicID = string.Empty;
try
{
//get the drop ship test order details
SqlDataReader reader = default(SqlDataReader);
reader = o_cSQL.RunSQLReturnDataReader(query);
REService.ReportExecutionService rs_ext = new REService.ReportExecutionService();
rs_ext.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs_ext.Url = ConfigurationManager.AppSettings["ReportExecutionServer"];
List<string> ordereditems = new List<string> { };
ordereditems = GetOrderedItems(); //panels and profiles
int numordereditems = ordereditems.Count;
List<String> comments = new List<String>();
if (cbIce.Checked)
comments.Add("Ice");
if (cbKit.Checked)
comments.Add("Kit");
if (cbSwabs.Checked)
comments.Add("Swabs");
if (cbGoldTop.Checked)
comments.Add("Gold Top");
if (cbNeedlePack.Checked)
comments.Add("Needle Pack");
if (cbButterflyPack.Checked)
comments.Add("Butterfly Pack");
if (comments.Count == 0)
comments.Add("");
byte[] result = null;
string historyID = null;
string devInfo = null;
string encoding;
string mimeType;
string extension;
REService.Warning[] warnings = null;
string[] streamIDs = null;
//define the size of the parameter array to pass into the REService
REService.ParameterValue[] rValues = new REService.ParameterValue[4 + numordereditems];
while (reader.Read())
{
sClinicID = reader["ClinicID"].ToString();
rValues[0] = new REService.ParameterValue();
rValues[0].Name = "ClinicID";
rValues[0].Value = sClinicID;
rValues[1] = new REService.ParameterValue();
rValues[1].Name = "ReqFormID";
rValues[1].Value = giRequestID.ToString();
rValues[2] = new REService.ParameterValue();
rValues[2].Name = "DropShipID";
rValues[2].Value = giDropShipID.ToString();
rValues[3] = new REService.ParameterValue();
rValues[3].Name = "Comments";
rValues[3].Value = string.Join(",",comments.ToArray());
int j = 0;
for (int i = 4; i < rValues.Length; i++)
{
rValues[i] = new REService.ParameterValue();
rValues[i].Name = "PanelsNProfiles";
rValues[i].Label = "Panels and Profiles :";
rValues[i].Value = ordereditems[j++];
}
}
REService.ExecutionInfo res_info = new REService.ExecutionInfo();
res_info = rs_ext.LoadReport("/zReportSandbox/RequisitionDS", historyID);
res_info = rs_ext.SetExecutionParameters(rValues, "en-us");
res_info = rs_ext.GetExecutionInfo();
result = rs_ext.Render("PDF", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
string pdfFile = "Requisition_" + giRequestID.ToString() + "_"+ txtPatientName_Edit.Text + ".pdf";
string sPDFSavePath = ConfigurationManager.AppSettings["Shipping_Requisitions"] + sClinicID;
//add the date pathing
sPDFSavePath = ReportHelper.CreateDateDirectories(sPDFSavePath);
//make sure the file doesn't already exist and if it does, delete it so we create a new one
ReportHelper.checkPDFfilesNDirectory(sPDFSavePath +#"\", pdfFile);
FileStream stream = File.Create(sPDFSavePath + #"\" + pdfFile, result.Length);
stream.Write(result, 0, result.Length);
stream.Close();
}
catch(Exception ex)
{
Common.CommonUtilities.FatalError(sPageName, "btnPrintReq_Tests_Click", query, ex.Message.ToString(), ex.ToString());
}
}
I have noticed that the ExecutionInfo item shows me all parameters in the array of the report, meaning the required INPUT parameters AND the INTERNAL parameters, but also noticed that for the INTERNAL parameters, the default value that was set in the report is satisfied and ExecutionInfo shows them with the State of HasValidValue.
The following list is what I know
the report works on its own, so the Main report that calls the Subreport has no issues creating the PDF
there report when run in SSRS does prompt for the 4 input parameters
I have tried the removal of the report in SSRS and redeployed it because there were many that suggested this somehow fixes issues like this.
I have tried the Insert a table, delete the columns and put subreport in one cell of table trick and still the same error.
It would be nice if the error would state what parameter it sees as not being satisfied, even if there are more than one, then simply listing the first one before erroring out would help a developer work through the issues.
The attached picture shows the values I'm passing in for the multivalue parameters (PanelsNProfiles). I'm also attaching my RDL files for the main report and the Subreport, but had to add a (.txt) file extension to them to be able to upload them.
Here is the error in the SSRS execution log:
library!ReportServer_0-57!5250!03/23/2022-09:06:27:: i INFO: RenderForNewSession('/zReportSandbox/RequisitionDS')
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: , Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: One or more parameters required to run the report have not been specified.;
reportrendering!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: , Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS.;
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: An error has occurred while processing a sub-report. Details: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS. Stack trace:
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.FinalizeErrorMessageAndThrow()
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.RetrieveSubreport()

Unable to create relationships in SSAS 2016 using tabular model programming for compatability level 1200

I am trying to create a simple tool that creates a model from metadata. I am successful in creating tables and columns, but unable to create relationships under model. While trying to add FromTable and ToTable properties to relationship object i was getting an error saying those properties are read-only and cannot be changed.
Below is the sample code that i am using to create relationships.
public void AddRelationshipsToModel()
{
OleDbDataReader reader = null;
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = metadataConnInfo.ConnectionString;
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "select source_parent_table_name,source_parent_column_name, source_child_table_name,source_child_column_name from HX_VIEWS_RMS.BI_TABULAR_RELATIONSHIPS where MODEL_NAME='"+database.Model.Name +"'";
reader = command.ExecuteReader();
while(reader.Read())
{
string _toTable = srcAndTabularTableMap[reader.GetValue(0).ToString().Trim()];
string _toColumn = srcTableAndTabularColMap[reader.GetValue(0).ToString().Trim()][ reader.GetValue(1).ToString().Trim()];
string _fromTable = srcAndTabularTableMap[reader.GetValue(2).ToString().Trim()];
string _fromColumn = srcTableAndTabularColMap[reader.GetValue(2).ToString().Trim()][reader.GetValue(3).ToString().Trim()];
Table fromTable = Database.Model.Tables[_fromTable];
DataColumn fromColumn = (DataColumn)fromTable.Columns[_fromColumn];
Table toTable = Database.Model.Tables[_toTable];
DataColumn toColumn = (DataColumn)fromTable.Columns[_toColumn];
SingleColumnRelationship relationship = new SingleColumnRelationship();
relationship.FromTable = fromTable;
relationship.FromColumn = fromColumn;
relationship.ToTable = toTable;
relationship.ToColumn = toColumn;
//database.Model.Relationships.Add(new SingleColumnRelationship() { FromColumn = fromColumn ,ToColumn =toColumn});
}
connection.Close();
}
catch(Exception ex)
{
logger.Error(ex.Message);
}
}
This blog post is a good walk through.
Try just setting the FromColumn and ToColumn properties not the FromTable and ToTable settings. Optionally you can set them as part of the constructor:
SingleColumnRelationship relationship = new SingleColumnRelationship()
{
FromColumn = fromColumn,
ToColumn = toColumn
};
Tabular object model API has quite a few readonly fields / properties. Basically they are trying to tell you that you are not suppose to edit these fields directly but rather let API fill them for you.
Typical relationship look like this
Server = new Microsoft.AnalysisServices.Tabular.Server();
[...]
Server.Databases["MyDatabaseName"].Model.Relationships.Add(new SingleColumnRelationship
{
Name = "Relationship name",
FromColumn = Server.Databases["MyDatabaseName"].Model.Tables["FromTableName"].Columns["FromColumnName"],
FromCardinality = RelationshipEndCardinality.Many,
ToColumn = Server.Databases["MyDatabaseName"].Model.Tables["ToTableName"].Columns["ToColumnName"],
ToCardinality = RelationshipEndCardinality.One,
CrossFilteringBehavior = CrossFilteringBehavior.BothDirections,
IsActive = false
});
Try to handle with this class - Microsoft.AnalysisServices.Tabular.SingleColumnRelationship

Insert SQL statement is not working after checking against quantities from tables in database

I created a sale table which Insert function does not work properly. It shows the error message
Must declare the scalar variable "#iProductID"
at the statement
using (var sdRead = cmdOrder.ExecuteReader())
I am really stuck here. I also want to know how I can achieve for inserting SaleID with auto-increment without with any input field at the form. Every time I insert a new record, SaleID should be auto-generated and saved in the database.
My code below work like this. I checked available stocks from my Product table. If quantity order is greater than quantity from Product table, show error message.
Otherwise, proceed to inserting order information into Sale table. Any help is appreciated.
private void btnOrder_Click(object sender, EventArgs e)
{
int iQuantityDB;
int iCustomerID = Convert.ToInt32(txtCustomerID.Text);
int iProductID = Convert.ToInt32(txtProductID.Text);
decimal dPrice = Convert.ToDecimal(txtPrice.Text);
int iQuantity = Convert.ToInt32(txtQuantity.Text);
decimal dSubtotal = Convert.ToDecimal(txtSubTotal.Text);
decimal dGST = Convert.ToDecimal(txtGST.Text);
decimal dTotal = Convert.ToDecimal(txtTotal.Text);
string strConnectionString = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB; MultipleActiveResultSets=True;";
using (var sqlconn = new SqlConnection(strConnectionString))
{
sqlconn.Open();
string querySelectQuantity = #"Select Quantity from dbo.JeanProduct WHERE ProductID = #iProductID";
using (var cmdOrder = new SqlCommand(querySelectQuantity, sqlconn))
{
using (var sdRead = cmdOrder.ExecuteReader())
{
sdRead.Read();
iQuantityDB = Convert.ToInt32(sdRead["Quantity"]);
}
}
if (iQuantityDB > iQuantity)
{
string InsertQuery = #"INSERT INTO Sale(CustomerID, ProductID, Price, Quantity, Subtotal, GST, Total)VALUES(#iCustomerID, #iProductID, #dPrice, #iQuantity, #dSubtotal, #dGST, #Total)";
using (var InsertCMD = new SqlCommand(InsertQuery, sqlconn))
{
InsertCMD.Connection = sqlconn;
InsertCMD.Parameters.AddWithValue("#iCustomerID", iCustomerID);
InsertCMD.Parameters.AddWithValue("#iProdcutID", iProductID);
InsertCMD.Parameters.AddWithValue("#dPrice", dPrice);
InsertCMD.Parameters.AddWithValue("#iQuantity", iQuantity);
InsertCMD.Parameters.AddWithValue("#dSubtotal", dSubtotal);
InsertCMD.Parameters.AddWithValue("#dGST", dGST);
InsertCMD.Parameters.AddWithValue("#dTotal", dTotal);
InsertCMD.ExecuteNonQuery();
LoadDataonTable();
}
}
else
{
MessageBox.Show("no more stock");
}
sqlconn.Close();
}
}
At the line using (var sdRead = cmdOrder.ExecuteReader()) your SQL SELECT query is using a parameter - WHERE ProductID = #iProductID - but this hasn't been set. Hence the error message Must declare the scalar variable "#iProductID"
Just add cmdOrder.Parameters.AddWithValue("#iProductID", iProductID) between defining the SQL and executing it, and that should clear that problem.
Moving on to the next one - you're using AddWithValue("#dTotal" but it's #Total in the SQL :)

how to update a column in force.com explorer

SELECT Name, ProfileId, Id, Username FROM User this is the select query to retrive data in Force.com explorer
Now I wan't to update a column how can I do this? update key word it self not working here please give the solution for this.
thanks in advance
In Salesforce you not write to update query same as in SQL.
Please use update method to update column of an object.
More information and sample please read following documents.
https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_update.htm
I found Solution it's working fine now, If any one haveing doubts ask me for Create,Update,Get functionalities
private void UpdateProfileId(string Id)
{
SforceService sfs = new SforceService();
var login = sfs.login(ConfigurationManager.AppSettings["username"],ConfigurationManager.AppSettings["password"]);
sfs.Url = login.serverUrl;
sfs.SessionHeaderValue = new SessionHeader();
sfs.SessionHeaderValue.sessionId = login.sessionId;
var userinfo = login.userInfo;
QueryResult qr = null;
sfs.QueryOptionsValue = new salesforce.QueryOptions();
User[] UpdateUser = new User[1];
User objuser = new User();
objuser.Id = Id;
objuser.ProfileId = "00e90000001CcTnAAK";
UpdateUser[0] = objuser;
try
{
SaveResult[] saveResults = sfs.update(UpdateUser);
foreach (SaveResult saveResult in saveResults)
{
if (saveResult.success)
{
Console.WriteLine("Successfully updated Account ID: " +saveResult.id);
}
}
}
}

C# Sql Data not saving

I have a few tables in a c# application I'm currently working on and for 4/5 of the tables everything saves perfectly fine no issues. For the 5th table everything seems good until I reload the program again (without modifying the code or working with a seperate install so that the data doesn't go away) The 4/5 tables are fine but the 5th doesn't have any records in it after it has been restarted (but it did the last time it was running). Below is some code excerpts. I have tried a few different solutions online including creating a string to run the sql commands on the database manually and creating the row directly as opposed to the below implementation which uses a generic data row.
//From main window
private void newInvoice_Click(object sender, EventArgs e)
{
PosDatabaseDataSet.InvoicesRow newInvoice = posDatabaseDataSet1.Invoices.NewInvoicesRow();
Invoices iForm = new Invoices(newInvoice, posDatabaseDataSet1, true);
}
//Invoices Table save [Works] (from Invoices.cs)
private void saveInvoice_Click(object sender, EventArgs e)
{
iRecord.Date = Convert.ToDateTime(this.dateField.Text);
iRecord.InvoiceNo = Convert.ToInt32(this.invoiceNumField.Text);
iRecord.Subtotal = (float) Convert.ToDouble(this.subtotalField.Text);
iRecord.Tax1 = (float)Convert.ToDouble(this.hstField.Text);
iRecord.Total = (float)Convert.ToDouble(this.totalField.Text);
iRecord.BillTo = this.billToField.Text;
invoicesBindingSource.EndEdit();
if (newRecord)
{
dSet.Invoices.Rows.Add(iRecord);
invoicesTableAdapter.Adapter.Update(dSet.Invoices);
}
else
{
string connString = Properties.Settings.Default.PosDatabaseConnectionString;
string queryString = "UPDATE dbo.Invoices set ";
queryString += "Date='" + iRecord.Date+"'";
queryString += ", Subtotal=" + iRecord.Subtotal;
queryString += ", Tax1=" + iRecord.Tax1.ToString("N2");
queryString += ", Total=" + iRecord.Total;
queryString += " WHERE InvoiceNo=" + iRecord.InvoiceNo;
using (SqlConnection dbConn = new SqlConnection(connString))
{
SqlCommand command = new SqlCommand(queryString, dbConn);
dbConn.Open();
SqlDataReader r = command.ExecuteReader();
dbConn.Close();
}
}
dSet.Invoices.AcceptChanges();
}
//Invoice Items save [works until restart] (also from Invoices.cs)
private void addLine_Click(object sender, EventArgs e)
{
DataRow iRow = dSet.Tables["InvoiceItems"].NewRow();
iRow["Cost"] = (float)Convert.ToDouble(this.costField.Text);
iRow["Description"] = this.descriptionField.Text;
iRow["InvoiceNo"] = Convert.ToInt32(this.invoiceNumField.Text);
iRow["JobId"] = Convert.ToInt32(this.jobIdField.Text);
iRow["Qty"] = Convert.ToInt32(this.quantityField.Text);
iRow["SalesPerson"] = Convert.ToInt32(this.salesPersonField.Text);
iRow["SKU"] = Convert.ToInt32(this.skuField.Text);
dSet.Tables["InvoiceItems"].Rows.Add(iRow);
invoiceItemsTableAdapter.Adapter.Update(dSet,"InvoiceItems");
PosDatabaseDataSet.InvoiceItemsDataTable dTable = (PosDatabaseDataSet.InvoiceItemsDataTable)dSet.InvoiceItems.Copy();
DataRow[] d = dTable.Select("InvoiceNo=" + invNo.ToString());
invoiceItemsView.DataSource = d;
}
Thanks in advance for any insight.
UPDATE: October 17, 2011. I am still unable to get this working is there any more ideas out there?
you must execute your Sql Command in order to persis the changes you made.
using (SqlConnection dbConn = new SqlConnection(connString))
{
dbConn.Open();
SqlCommand command = new SqlCommand(queryString, dbConn);
command.ExecuteNonQuery();
dbConn.Close();
}
The ExecuteReader method is intended (as the name says) to read the data from a SQL table. You need to use a different method as you can see above.
We need some more info first, you haven't shown the case where your code fails.
Common mistakes on this kind of code is calling DataSet.AcceptChanges() before actually committing the changes to the database.
Second is a conflict between databound data through the binding source vs edits to the dataset directly.
Lets see the appropriate code and we can try and help.
Set a breakpoint after teh call to invoiceItemsTableAdapter and check the InvoiceItems table for the row you have added. Release the breakpoint and then close your app. Check the database again. I would say that another table may be forcibly overwriting the invoice item table.