The code below its working very well but when i make new user and check in MS Sql i can find the new user that i enter it but without the image name and also cant store the image in the project file, please any help
public partial class Registration : System.Web.UI.Page
{
string sc = ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString.ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(sc);
cn.Open();
SqlCommand cmd = new SqlCommand();
string sqlstatment= "INSERT INTO [dbo].[UserInfo]"+
" ([UID]"+
" ,[FN] "+
" ,[LN]" +
",[Password] "+
" ,[RePass] "+
" ,[Email] "+
" ,[CountID] "+
" ,[State] "+
" ,[City] "+
" , [Post] " +
" ,[Img]) values (#UID,#FN,#LN,#Password,#RePass,#Email,#CountID,#State,#City,#Post,#Img)";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
cmd.Connection = cn;
cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#UID", UsrNme.Text);
cmd.Parameters.AddWithValue("#FN", fnbox.Text);
cmd.Parameters.AddWithValue("#LN", lnamebox.Text);
cmd.Parameters.AddWithValue("#Password", passtxtbx1.Text);
cmd.Parameters.AddWithValue("#RePass", passtxtbx2.Text);
cmd.Parameters.AddWithValue("#Email", emailbox.Text);
cmd.Parameters.AddWithValue("#CountID", DDLCOUNTRY.Text);
cmd.Parameters.AddWithValue("#State", DDLSTATE.Text);
cmd.Parameters.AddWithValue("#City", citytxtbox.Text);
cmd.Parameters.AddWithValue("#Post",postbox.Text);
cmd.Parameters.AddWithValue("#Img", FileUpload1.FileName);
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
{
FileUpload1.SaveAs(Server.MapPath("~/images/users/" + FileUpload1.FileName));
}
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
}
Related
I am new to ASP NET MVC
I need Populate a drop down list from values obtained from a database table using MySql database and view model, after checking if the current user is application enabled, using ASP NET MVC.
This is the tutorial
My code below return
Error: returns void, a return keyword must not be followed by an object expression
On this line
return items;
Any help really appreciated.
Controller
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
List<SelectListItem> items = new List<SelectListItem>();
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "' ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
connection.Close();
}
}
return items;
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
Update
I have tried with this code.
I have error
Error CS0103 The name 'cCountry' does not exist in the current context
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
TempData["Dates"] = PopulateDates();
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
private static List<SelectListItem> PopulateDates()
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "'; ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
You are not passing cCountry value to populateDates.That's why you are getting this error. You can do something like below to get drop down populated. However it is not good idea to write Business Logic directly in controller. You should move it to model or Business layer.
private static List<SelectListItem> PopulateDates(string country)
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM dotable_countries WHERE cCountry = #country";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("#country",country);
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
and while calling this method in Action pass country value to it like below
TempData["Dates"] = PopulateDates(cCountry);
I have a form in my MVC 5 Webb App, a very simple form for "contact us":
-Name
-Email
-Subject
-Message (body)
I have to check the strings that the user input.
How can I check it in .NET ?
Update:
As Darin suggested, a Parameterizing Queries will take care of that, but I have a problem with implementation it with my architecture design of my web application:
I have a Ado Helper Class:
public class AdoHelper
{
static string connectionString = ConfigurationManager.ConnectionStrings["SQL_DB"].ConnectionString;
public static DataTable ExecuteDataTable(string query)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand command = new SqlCommand(query, con);
SqlDataAdapter tableAdapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
tableAdapter.Fill(dt);
return dt;
}
}
public static void ExecuteNonQuery(string query)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand command = new SqlCommand(query, con);
command.ExecuteNonQuery();
}
}
public static object ExecuteScalar(string query)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand command = new SqlCommand(query, con);
return command.ExecuteScalar();
}
}
}
And I have Data Queries Class: ( I display here only the relevant function to this question)
public class DataQueries
{
public static void InsertContactForm(ContactForm form)
{
try
{
string query = "INSERT INTO ContactForm (Name, Email, Subject, Message, Reply) VALUES ( '" + form.Name + "','" + form.Email + "','" + form.Subject + "','" + form.Message + "','" + form.Reply + "')";
AdoHelper.ExecuteNonQuery(query);
}
catch (Exception ex)
{
throw ex;
}
}
}
When I want to insert data to my DB I call to a Data Queries function that communicate with the Ado Helper Class.
So the query pass to Ado Helper function as string well formed and ready to go, this creates a problem because I cant use parameters in the Ado Helper class (where I have SQL command instance).
Are there any workaround to this problem ?
Thanks.
Looks like your AdoHelper class is currently vulnerable to SQL injection. In order to avoid that you need to use parametrized queries. So I would start by refactoring this AdoHelper class so that it suits better those needs:
public class AdoHelper
{
private static string connectionString = ConfigurationManager.ConnectionStrings["SQL_DB"].ConnectionString;
public static int ExecuteNonQuery(string query, IDictionary<string, object> parameters)
{
using (var con = new SqlConnection(connectionString))
using (var command = con.CreateCommand())
{
con.Open();
command.CommandText = query;
foreach (var p in parameters)
{
command.Parameters.AddWithValue(p.Key, p.Value);
}
return command.ExecuteNonQuery();
}
}
}
and then you could call this method in order to perform the INSERT statement:
AdoHelper.ExecuteNonQuery(
"INSERT INTO ContactForm (Name, Email, Subject, Message, Reply) VALUES (#Name, #Email, #Subject, #Message, #Reply)",
new Dictionary<string, object>
{
{ "#Name", "form.Name" },
{ "#Email", "form.Email" },
{ "#Subject", "form.Subject" },
{ "#Message", "form.Message" },
{ "#Reply", "form.Reply" }
}
);
What you need is parametrized queries. In the cmd object in ADO.NET, for example, there is a straight forward to do that:
using (var cmd = new SqlCommand())
{
// Add the input parameter and set its properties.
using (var parameter = new SqlParameter())
{
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
cmd.Parameters.Add(parameter);
// Now you can execute query
}
}
http://msdn.microsoft.com/en-us/library/yy6y35y8%28v=vs.110%29.aspx
Many thanks to Jonathan Peppers for the advice on how to refresh a tableview.
Update: Here is a link to my solution: https://github.com/Videlia/Veggies.git. Also, I have discovered that once I have added 5 items in landscape view, or about 7 or 8 in portrait view, the list starts to display the top items over again, instead of continuing down the list. However, if I select a row, it selects the value that should have been displayed.
My tableview is now working perfectly if I add or edit a row (both of which require that I go to another screen and then return to this one). For some reason, the delete operation, which is executed on the same screen, does not reload the data.
Here is my updated code:
View Controller
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace TableViewTest
{
public partial class vc_ManageVeggies : UIViewController
{
public vc_ManageVeggies () : base ("vc_ManageVeggies", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// connect table to source.
VeggieTableSource source = new VeggieTableSource ();
Console.WriteLine ("\n vc_ManageVeggies.ViewDidLoad: " + Veggies.CountVeggies ().ToString () + " veggies found! :-)");
if (Veggies.CountVeggies () > 0) {
this.tblVeggies.Source = source;
}
btnNewVeggie.TouchUpInside += delegate {
Veggies.SelectedVeggie = string.Empty;
vc_VeggieAddEdit newScreen = new vc_VeggieAddEdit ();
try {
this.NavigationController.PushViewController (newScreen, false);
} catch (Exception ex) {
Console.WriteLine ("btnNewVeggie error: " + ex.ToString ());
}
};
btnEditVeggie.TouchUpInside += delegate {
if (Veggies.SelectedVeggie == string.Empty) {
UIAlertView alert = new UIAlertView ("Oops!", "Please select a veggie to edit.", null, "OK");
alert.Show ();
} else {
vc_VeggieAddEdit newScreen = new vc_VeggieAddEdit ();
this.NavigationController.PushViewController (newScreen, false);
}
};
btnDeleteVeggie.TouchUpInside += delegate {
Veggies.DeleteVeggie (Veggies.SelectedVeggie);
// update VeggieNames list and reload tableview data.
//Veggies.RefreshVeggieList ();
Veggies.VeggieNames.Remove (Veggies.SelectedVeggie);
tblVeggies.ReloadData ();
};
btnDone.TouchUpInside += delegate {
vc_MainMenu newScreen = new vc_MainMenu ();
NavigationController.PushViewController (newScreen, false);
};
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
public void RefreshVeggieTable ()
{
}
}
}
Table Source
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Collections.Generic;
namespace TableViewTest
{
public class VeggieTableSource: UITableViewSource
{
//List<string> veggieNames;
public VeggieTableSource ()
{
Veggies.GetVeggieNames ();
}
#region implemented abstract members of MonoTouch.UIKit.UITableViewSource
public override int RowsInSection (UITableView tableview, int section)
{
//return veggieNames.Count;
return Veggies.VeggieNames.Count;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell ("cell");
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, "cell");
var text = string.Format ("{0}", Veggies.VeggieNames [indexPath.Row]);
cell.TextLabel.Text = text;
}
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
Veggies.SelectedVeggie = Veggies.VeggieNames [indexPath.Row].ToString ();
}
#endregion
}
}
Veggie Class
using System;
using System.Collections.Generic;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MyDataLayer;
namespace TableViewTest
{
public static class Veggies
{
public static List<string> VeggieNames;
public static string SelectedVeggie;
public static int NumberOfVeggies;
public static int CountVeggies ()
{
NumberOfVeggies = DataLayer.CountRecords ("tVeggies");
return NumberOfVeggies;
}
public static List<string> GetVeggieNames ()
{
//VeggieName ntext, Description ntext, Yummy int
string sql = "Select VeggieName from tVeggies ORDER BY VeggieName";
VeggieNames = DataLayer.GetStringList (sql);
Console.WriteLine ("\n GetVeggieNames: " + VeggieNames.ToString ());
return VeggieNames;
}
public static void CreateVeggie (string veggieName, int yummy, string description)
{
// 1. Declare variables and set initial values
DataLayer dataLayer = new DataLayer ();
DataField[] dataFields;
DataField NameField = new DataField ();
DataField YummyField = new DataField ();
DataField DescriptionField = new DataField ();
string sql = string.Empty;
// unselect any other players because the new player will also become the selected player.
MyDataLayer.DataLayer.ExecuteNonQuery (sql);
//3. Create data field objects for each field to be created.
NameField.FieldName = "VeggieName";
NameField.FieldType = "string";
NameField.FieldValue = '"' + veggieName + '"';
YummyField.FieldName = "Yummy";
YummyField.FieldType = "int";
YummyField.FieldValue = yummy.ToString ();
DescriptionField.FieldName = "Description";
DescriptionField.FieldType = "string";
DescriptionField.FieldValue = '"' + description + '"';
dataFields = new DataField[] { NameField, YummyField, DescriptionField };
// Insert Record into database.
dataLayer.InsertRecord ("tVeggies", dataFields);
RefreshVeggieList ();
}
public static void DeleteVeggie (string veggieName)
{
string sql = "DELETE FROM tVeggies WHERE VeggieName = '" + veggieName + "'";
try {
DataLayer.ExecuteNonQuery (sql);
} catch (Exception ex) {
Console.WriteLine ("Player.Delete error: " + ex.ToString ());
}
RefreshVeggieList ();
}
public static void UpdateVeggie (string veggieName, int yummy, string description)
{
// create variables and set initial values
//DataLayer dataLayer = new DataLayer ();
string sql = "UPDATE tVeggies SET VeggieName = '" + veggieName + "', yummy = " + yummy.ToString () + ", description = '" + description + "' where VeggieName = '" + Veggies.SelectedVeggie + "'";
//string response = string.Empty; //this will hold a response such as "success" or the error message.
Console.WriteLine ("Veggie.UpdateVeggie sql statement: " + sql);
try {
DataLayer.ExecuteNonQuery (sql);
Console.WriteLine ("PVeggie.UpdateVeggie: veggie updated successfully.");
} catch (Exception ex) {
Console.WriteLine ("Veggie.UpdateVeggie: " + ex.ToString ());
}
RefreshVeggieList ();
}
// Update list of Veggie names
// the TableView on the ManageVeggies view controller needs the VeggieList to be updated whenever veggie records are changed.
//so the tableview will refresh properly.
public static void RefreshVeggieList ()
{
string sql = "Select VeggieName from tVeggies ORDER BY VeggieName";
VeggieNames = DataLayer.GetStringList (sql);
}
}
}
Data Layer
using System;
using System.IO;
using Mono.Data.Sqlite;
using System.Data;
using System.Collections.Generic;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace MyDataLayer
{
// DataField class is used to create data for each data field in a table to be created, updated, or deleted.
public class DataField
{
public string FieldName { get; set; }
public string FieldValue { get; set; }
public string FieldType { get; set; }
}
public class DataLayer
{
//declare variables used by all DataLayer methods;
private static string dbFileName = "myFunDatabase.db3";
//private string dbFileAndPath = string.Empty;
private static SqliteConnection connection;
public DataLayer ()
{
}
public static int CountRecords (string tableName)
{
int count = 0;
string sql = "SELECT count(*) FROM " + tableName;
count = DataLayer.ExecuteScalar_Int16 (sql);
Console.WriteLine ("\n DataLayer.CountRecords: " + count.ToString () + "records found in the datatable.");
return count;
}
public static void ExecuteNonQuery (string sql)
{
SqliteCommand sqlCommand = new SqliteCommand ();
try {
// create and open connection
connection = GetConnection ();
using (connection) {
connection.Open ();
Console.WriteLine ("\n DataLayer.ExecuteNonQuery: connection opened. Connection state is " + connection.State);
// create and execute command
sqlCommand.CommandText = sql;
sqlCommand.Connection = connection;
sqlCommand.ExecuteNonQuery ();
connection.Close ();
Console.WriteLine ("\n DataLayer.ExecuteNonQuery: Connection was closed. Connection state is " + connection.State);
}
connection.Close ();
Console.WriteLine ("DataLayer.ExecuteNonQuery: NonQuery Executed: " + sql);
} catch (Exception ex) {
Console.WriteLine ("\n >>> DataLayer.ExecuteNonQuery Exception: " + ex.ToString ());
Console.WriteLine ("\n >>> SQL statement: " + sql);
}
}
public static Int16 ExecuteScalar_Int16 (string sql)
{
int result = 0;
SqliteCommand sqlCommand = new SqliteCommand ();
try {
//connection = new SqliteConnection (string.Format ("Data Source = {0};", dbFileName));
connection = GetConnection ();
connection.Open ();
sqlCommand.CommandText = sql;
sqlCommand.Connection = connection;
result = Convert.ToInt16 (sqlCommand.ExecuteScalar ());
connection.Close ();
} catch (Exception ex) {
Console.WriteLine ("\n >>>DataLayer.ExecuteScalar_Int Exception: " + ex.ToString ());
}
return Convert.ToInt16 (result);
}
public static string ExecuteScalar_String (string sql)
{
string result = string.Empty;
SqliteCommand sqlCommand = new SqliteCommand ();
try {
//connection = new SqliteConnection (string.Format ("Data Source = {0};", dbFileName));
connection = GetConnection ();
connection.Open ();
sqlCommand.CommandText = sql;
sqlCommand.Connection = connection;
result = Convert.ToString (sqlCommand.ExecuteScalar ());
connection.Close ();
} catch (Exception ex) {
Console.WriteLine ("\n >>>DataLayer.ExecuteScalar_Int Exception: " + ex.ToString ());
}
return result;
}
public void CreateDatabaseFolder ()
{
}
//public string InsertRecord(string tableName, string variableNames, string variableTypes, string variableValues)
public string InsertRecord (string tableName, DataField[] dataFields)
{
string sql = string.Empty;
string fieldNameList = string.Empty;
string fieldValueList = string.Empty;
string response = string.Empty;
SqliteCommand sqlCommand = new SqliteCommand ();
connection = GetConnection ();
try {
connection.Open ();
// Begin transaction for multiple updates (improves efficiency)
sqlCommand = new SqliteCommand ("BEGIN", connection);
sqlCommand.ExecuteNonQuery ();
// begin individual inserts. I will nest this later to accommodate batch updates.l
sql = "INSERT INTO " + tableName + " (";
sqlCommand = new SqliteCommand ();
sqlCommand.Connection = connection;
foreach (DataField dataField in dataFields) {
fieldNameList += dataField.FieldName + ", ";
fieldValueList += dataField.FieldValue + ", ";
sqlCommand.Parameters.AddWithValue ("#" + dataField.FieldName, dataField.FieldValue);
}
// remove extra commas at the end of the lists, and append to the sql statement
sql += fieldNameList.Substring (0, fieldNameList.Length - 2);
sql += ") VALUES (";
sql += fieldValueList.Substring (0, fieldValueList.Length - 2);
sql += ")";
Console.WriteLine (sql);
// load and run sql insert statement.
sqlCommand.CommandText = sql;
sqlCommand.ExecuteNonQuery ();
sqlCommand = new SqliteCommand ("END", connection);
sqlCommand.ExecuteNonQuery ();
connection.Close ();
response = "Success";
} catch (Exception ex) {
response = ">>> DataLayer.InsertRecord Error: " + ex.ToString ();
}
// End batch commmand and close connection to the database.
Console.WriteLine ("\n DataLayer.InsertRecord Response to be returned: " + response);
return response;
}
public static List<string> GetStringList (string sql)
{
SqliteDataReader dataReader;
SqliteCommand sqlCommand = new SqliteCommand ();
List<string> values = new List<string> ();
int i = 0; //used to increment through records.
int count = 0;
connection = GetConnection ();
try {
using (connection) {
connection.Open ();
Console.WriteLine ("\n DataLayer.GetStringList: sql statement: " + sql);
sqlCommand.CommandText = sql;
sqlCommand.Connection = connection;
dataReader = sqlCommand.ExecuteReader ();
if (dataReader.HasRows) {
Console.WriteLine ("\n DataLayer.GetStringList: dataReader has" + " rows. ");
while (dataReader.Read ()) {
values.Add (dataReader [0].ToString ());
Console.WriteLine ("\n DataLayer.GetStringList: value added to list: " + dataReader [0].ToString ());
i++;
}
count = i + 1;
Console.WriteLine ("\n DataLayer.GetStringList: dataReader has" + count + " rows. ");
Console.WriteLine ("\n DataLayer.GetStringList: successfully populated value string array from data reader");
connection.Close ();
}
}
} catch (Exception ex) {
Console.WriteLine ("\n >>> DataLayer.GetStringList error: " + ex.ToString ());
}
return values;
}
public void GetSchema ()
{
}
public static void DeleteDatabase ()
{
// Declare variables
var path = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string db; // full name and path of database file.
// set initial values;
path = Path.Combine (path, "..", "Library");
db = Path.Combine (path, dbFileName);
bool databaseExists = File.Exists (db);
Console.WriteLine ("\n DataLayer.GetConnection: Getting ready to create database if it does not exist.");
if (databaseExists) {
try {
File.Delete (db);
Console.WriteLine ("\n DataLayer.DeleteDatabase: database deleted: " + dbFileName);
} catch (Exception ex) {
Console.WriteLine ("\n >>> DataLayer.DeleteDatabase: Unable to delete database: " + dbFileName);
Console.WriteLine ("\n >>> DataLayer.DeleteDatabase: Cause of error: " + ex.ToString ());
}
}
}
static SqliteConnection GetConnection ()
{
// Declare variables
var path = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string db; // full name and path of database file.
var conn = new SqliteConnection ();
// set initial values;
path = Path.Combine (path, "..", "Library");
db = Path.Combine (path, dbFileName);
bool databaseExists = File.Exists (db);
Console.WriteLine ("\n DataLayer.GetConnection: Getting ready to create database if it does not exist.");
if (!databaseExists) {
CreateDatabase (db);
}
conn = new SqliteConnection ("\n Data Source=" + db);
return conn;
}
static void CreateDatabase (string db)
{
// Declare variables
var conn = new SqliteConnection ();
// set initial values;
bool databaseExists = File.Exists (db);
Console.WriteLine ("\n DataLayer.GetConnection: Getting ready to create database if it does not exist.");
if (!databaseExists) {
try {
SqliteConnection.CreateFile (db);
Console.WriteLine ("\n DataLayer.GetConnection: Database created successfully.");
} catch (Exception ex) {
Console.WriteLine ("\n >>> DataLayer.GetConnection: Error creating database: " + ex.ToString ());
}
if (!File.Exists (db)) {
Console.WriteLine ("\n >>> DataLayer.GetConnection: Database NOT created.");
}
conn = new SqliteConnection ("Data Source=" + db);
var commands = new[] {
"CREATE TABLE tVeggies (VeggieName ntext, Description ntext, Yummy int)",
"INSERT INTO tVeggies (VeggieName, Description, Yummy) VALUES ('Carrots', 'An orange root', 0)",
"INSERT INTO tVeggies (VeggieName, Description, Yummy) VALUES ('Spinach', 'Green leafy veggie', 1)",
"INSERT INTO tVeggies (VeggieName, Description, Yummy) VALUES ('Onion', 'Round with layers', 1)",
};
foreach (var cmd in commands) {
using (var c = conn.CreateCommand()) {
c.CommandText = cmd;
//c.CommandType = CommandType.Text; //this code does not work.
conn.Open ();
c.ExecuteNonQuery ();
conn.Close ();
Console.WriteLine ("\n DataLayer.GetConnection: command executed: " + cmd.ToString ());
}
}
}
}
public static System.Data.DataTable GetData (string sql)
{
// declare variables and set initial values
SqliteCommand command = new SqliteCommand ();
System.Data.DataTable dataTable = new System.Data.DataTable ();
SqliteDataAdapter adapter = new SqliteDataAdapter ();
System.Data.DataRow iRow;
//open connection and retrieve desired data.
try {
connection = GetConnection ();
using (connection) {
Console.WriteLine ("\n DataLayer.GetData: sql statement: " + sql);
command.CommandText = sql;
command.Connection = connection;
adapter = new SqliteDataAdapter (command);
connection.Open ();
adapter.Fill (dataTable);
// check to see if we got some data.
Console.WriteLine ("\n DataLayer.GetData: retrieved dataTable with " + dataTable.Rows.Count.ToString () + " rows.");
for (int i = 0; i< dataTable.Rows.Count; i++) {
iRow = dataTable.Rows [i];
}
Console.WriteLine ("\n DataLayer.GetData: successfully populated data table");
connection.Close ();
}
} catch (Exception ex) {
Console.WriteLine ("\n >>> error: " + ex.ToString ());
}
return dataTable;
}
}
}
Looking at your code, what is visible on your screen should be directly correlated to your list of veggieNames.
So to remove, replace, or add an item:
Perform this operation on the List<string>
call tblVeggies.ReloadData()
You don't have to create new table source or anything, which is likely what is messing you up. I would recommend creating the table source in ViewDidLoad.
If you want to get really fancy, an optimization you can do is call tblVeggies.ReloadRows on a specific row, but I would get it working in general first.
I have had a couple of questions on this issue. However, now I have redone my code and almost all of it is working. The only issue is after the for is submitted it is not checking the model state, because even when the form is successful it displays there is an error. Here is my code.
[HttpPost]
public ActionResult ContactForm(ContactModel emailModel)
{
MailMessage oMail = new MailMessage();
oMail.From = new MailAddress("no-reply#hovdenoil.com", "Web Contact Form");
oMail.To.Add("email#hovdenoil.com");
oMail.Subject = emailModel.Subject;
string body = "Name: " + emailModel.Name + "\n"
+ "Email: " + emailModel.Email + "\n"
+ "Phone: " + emailModel.Phone + "\n\n"
+ "Company: " + emailModel.Company + "\n"
+ "Website: " + emailModel.Website + "\n"
+ emailModel.Message;
oMail.Body = body;
SmtpClient client = new SmtpClient("smtpout.secureserver.net");
client.Credentials = new NetworkCredential("username", "password");
client.Send(oMail);
string message = "There are a few errors";
if (ModelState.IsValid)
{
message = "Thanks! We'll get back to you soon.";
ModelState.Clear();
}
if (Request.IsAjaxRequest())
{
return new JsonResult { ContentEncoding = Encoding.UTF8, Data = new { success = true, message = message } };
}
TempData["Message"] = message;
return View();
}
My bad. I put the If(ModelState.IsValid) too early. Hear is my final code which worked.
[HttpPost]
public ActionResult ContactForm(ContactModel emailModel)
{
string message = "There are a few errors";
if (ModelState.IsValid)
{
MailMessage oMail = new MailMessage();
oMail.From = new MailAddress("no-reply#hovdenoil.com", "Web Contact Form");
oMail.To.Add("email#hovdenoil.com");
oMail.Subject = emailModel.Subject;
string body = "Name: " + emailModel.Name + "\n"
+ "Email: " + emailModel.Email + "\n"
+ "Phone: " + emailModel.Phone + "\n\n"
+ "Company: " + emailModel.Company + "\n"
+ "Website: " + emailModel.Website + "\n"
+ emailModel.Message;
oMail.Body = body;
SmtpClient client = new SmtpClient("smtpout.secureserver.net");
client.Credentials = new NetworkCredential("username", "password");
client.Send(oMail);
message = "Thanks! We'll get back to you soon.";
ModelState.Clear();
}
if (Request.IsAjaxRequest())
{
return new JsonResult { ContentEncoding = Encoding.UTF8, Data = new { success = true, message = message } };
}
TempData["Message"] = message;
return View();
}
I have a table called Links.
two stored Procedures called sp_InsertLinks, sp_GetLinks.
I have simple webpart which takes two parameters and adds it the SQL Table call Links.
In The first Interface it displays the list of values from the database and a Button to ADD List.
When I click on the Link it displays next interface, where I can add txtbox for Link Name and Txtbox for Link URL.
And When I submit this The page is loading in the sequence of events of normal sharepoint lifecycle.
And I am unable to add the new links into the page because the button click method never gets fired.
Could any one have a look at this please?
The Code is :
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Text ;
using System.Data ;
using System.Data.SqlClient;
using System.Drawing;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace ContextMenuOptionsUsingJQuery
{
[Guid("7a3a52d4-9ad6-44b2-b96f-852da1a95371")]
public class ContextMenuOptionsUsingJQuery : System.Web.UI.WebControls.WebParts.WebPart
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string Con_string = string.Empty;
Button btnAddLink;
Button btnAddNewLink;
StringBuilder outputDisplay;
TextBox txtLink;
TextBox txtLinkUrl;
Label lblDisplay = new Label();
public ContextMenuOptionsUsingJQuery()
{
}
protected override void CreateChildControls()
{
try
{
// Getting the Connection
ConnectionMethod();
// Calling the Appropraite Method or stored Procedures
RefreshData();
// Adding a New Link though the button
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
//New item
Controls.Add(btnAddLink);
}
catch (Exception e)
{
Label l = new Label();
l.Text = e.StackTrace;
Controls.Add(l);
}
}
// Button Add Link
private void btn_AddLink(Object sender, EventArgs e)
{
Controls.Clear();
btnAddNewLink = new Button();
txtLink = new TextBox();
txtLinkUrl = new TextBox();
Controls.Add(txtLink);
Controls.Add(txtLinkUrl);
btnAddNewLink.Text = "ADD NEW Link";
btnAddNewLink.Click += new EventHandler(btnAddNewLink_Click);
Controls.Add(btnAddNewLink);
}
private void btnAddNewLink_Click(Object sender, EventArgs e)
{
int i;
try
{
ConnectionMethod();
cmd.CommandText = "sp_InsertLinks";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramLinkName = new SqlParameter("#LinkName", SqlDbType.VarChar, 50);
SqlParameter paramLinkUrl = new SqlParameter("#LinkUrl", SqlDbType.VarChar, 50);
paramLinkName.Direction = ParameterDirection.Input;
paramLinkUrl.Direction = ParameterDirection.Input;
paramLinkName.Value = txtLink.Text.ToString();
paramLinkUrl.Value = txtLinkUrl.Text.ToString();
cmd.Parameters.Add(paramLinkUrl);
cmd.Parameters.Add(paramLinkName);
i = cmd.ExecuteNonQuery();
con.Close();
ConnectionMethod();
RefreshData();
}
catch (Exception exp)
{
Label l = new Label();
l.Text = exp.StackTrace;
Controls.Add(l);
}
finally
{
con.Close();
}
}
private void RefreshData()
{
cmd.CommandText = "sp_GetLinks";
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
outputDisplay = new System.Text.StringBuilder();
outputDisplay.AppendLine("<br/>");
// Fetching the Data from the Datareader object
while (dr.Read())
{
outputDisplay.AppendLine("" + dr[1] + "" + "<br/><br/>");
}
con.Close();
outputDisplay.AppendLine("<br/> <br/>");
lblDisplay.Text = outputDisplay.ToString();
Controls.Add(lblDisplay);
}
// Method to get the Connection
public void ConnectionMethod()
{
con = new SqlConnection();
cmd = new SqlCommand();
Con_string = "Data Source=servername;Initial Catalog=HariVMTest;Integrated Security=True";
con.ConnectionString = Con_string;
con.Open();
cmd.Connection = con;
}
}
}
Thank you
Hari
I would nearly always recommend creating all your controls in CreateChildControls()
Then you should use the Visible property to show and hide the controls as needed.
The code would then look something like this:
public class ContextMenuOptionsUsingJQuery : System.Web.UI.WebControls.WebParts.WebPart {
Button btnAddLink;
Button btnAddNewLink;
protected override void CreateChildControls() {
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
Controls.Add(btnAddLink);
btnAddNewLink.Text = "ADD NEW Link";
btnAddNewLink.Click += new EventHandler(btnAddNewLink_Click);
btnAddNewLink.Visible = false;
Controls.Add(btnAddNewLink);
}
private void btn_AddLink(Object sender, EventArgs e) {
btnAddLink.Visible = false;
}
private void btnAddNewLink_Click(Object sender, EventArgs e) {
}
}
If you do it this way, your events will more often than not, fire correctly.
i think you need to just add :
// Adding a New Link though the button
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
before connectionmethod in createchildcontrol()
hope this works.