The type or namespace GlobalVar could not be found - asp.net

Please dear this is my code and everything is fine but the GlobalVar is not being declared any suggestions.
[WebMethod(MessageName = "OpenAccount", Description = "This method is to add new account")]
[System.Xml.Serialization.XmlInclude(typeof(ContactResult))]
public ContactResult openaccount(String FullName, String Phone)
{
ContactResult cr = new ContactResult();
**GlobalVar var = new GlobalVar();**
try
{
using (SqlConnection openconn = new SqlConnection(var.connectionstring))
{
string save = "INSERT into AndroidContact (AndroidContactName,AndroidContactPhone) VALUES ('" + FullName + "' ,'" + Phone + "')";
using (SqlCommand query = new SqlCommand(save))
{
query.Connection = openconn;
query.Parameters.Add("#AndroidContactName", SqlDbType.NVarChar, 50).Value = FullName;
query.Parameters.Add("#AndroidContactPhone", SqlDbType.NVarChar, 50).Value = Phone;
openconn.Open();
query.ExecuteNonQuery();
openconn.Close();
}
}
cr.ErrorID = 0;
cr.ErrorMessage = "Contact Added";
return cr;
}
catch (Exception ex){
cr.ErrorID = 1;
cr.ErrorMessage = ex.Message;
return cr;
}
}
}
}

Thanks, but i fixed mine like that :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod(MessageName = "OpenAccount", Description = "This method is to add new account")]
[System.Xml.Serialization.XmlInclude(typeof(ContactResult))]
public ContactResult openaccount(String FullName, String Phone)
{
ContactResult cr = new ContactResult();
SqlConnection Connection = new SqlConnection();
try
{
Connection.ConnectionString = ConfigurationManager.ConnectionStrings["webConnectionString"].ToString();
Connection.Open();
SqlCommand save = new SqlCommand ("INSERT into AndroidContact (AndroidContactName,AndroidContactPhone) VALUES ('" + FullName + "' ,'" + Phone + "')",Connection);
save.ExecuteNonQuery();
cr.ErrorID = 0;
cr.ErrorMessage = "Contact Added";
return cr;
}
catch (Exception ex)
{
cr.ErrorID = 1;
cr.ErrorMessage = ex.Message;
return cr;
}
}
}

Related

Getting error "Database is locked" when I trye to save data i SQLITE DB

I have following class that connects to database but when I trye to call the method that saves data I get error "Database is locked". Could some one please help me to find the problem?
class Data
{
private SQLiteConnection con;
private void ConnectoDB()
{
String PathDB = Directory.GetCurrentDirectory();
PathDB += "\\SQLiteDB_MEDFit.db";
string cs = #"URI=file:" + PathDB;
string stm = "SELECT SQLITE_VERSION()";
con = new SQLiteConnection(cs);
con.Open();
var cmd = new SQLiteCommand(stm, con);
string version = cmd.ExecuteScalar().ToString();
}
public Boolean SaveToDatabase(string name, string number)
{
bool result = false;
try
{
ConnectoDB();
con.Execute("insert into People(name, number) values ('" + name+ "', '" + number+ "')");
con.Close();
result = true;
MessageBox.Show("Saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
}
The code that calls the "SaveToDatabase()"
string name = textBox1.Text();
string number = textBox2.Text();
Data connect = new Data();
connect.SavetoDB(name, number);

jQuery Bootgrid sorting, pagination and search functionality not working

I have a jQuery bootgrid implemented into my ASP.Net application which is filled using a Generic Handler.
I fill the bootgrid using the Generic Handler as follows:
$(function () {
var grid = $("#grid").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
},
url: "/MyHandler.ashx",
rowCount: [10, 50, 75, 100, 200, -1]
});
}
Here's MyHandler.ashx code:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
context.Response.Write(GetData());
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData()
{
var result = string.Empty;
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
var sNumRows = dt.Rows.Count.ToString();
var sDT = JsonConvert.SerializeObject(dt);
result = "{ \"current\": 1, \"rowCount\": 10, \"rows\": " + sDT + ", \"total\": " + sNumRows + " }";
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
THF.Models.SQLConnectionManager.CloseConn(con);
}
return result;
}
}
Basically all the important functionality of my bootgrid that worked before I implemented it the ajax way doesn't work anymore. Specifically the ordering, searching and pagination functionality aren't working at all without any errors.
As far as I know from a bit of research. This is because every time a search phrase is made, or a header is clicked (for ordering) etc. The bootgrid performs an ajax call.
Any idea on how to fix the functionality here?
After much work I ended up getting it working and this is the final code result:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
var current = context.Request.Params["current"];
var rowCount = context.Request.Params["rowCount"];
var orderById = context.Request.Params["sort[Id]"];
var orderByName = context.Request.Params["sort[Name]"];
var searchPhrase = context.Request.Params["searchPhrase"];
var orderBy = "Id";
var orderFrom = "ASC";
if (orderById != null)
{
orderBy = "Id";
orderFrom = orderById;
}
else if (orderByName != null)
{
orderBy = "Name";
orderFrom = orderByName;
}
context.Response.Write(GetData(current, rowCount, orderBy, orderFrom, searchPhrase));
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData(string current, string rowCount, string orderBy, string orderFrom, string searchPhrase)
{
var result = string.Empty;
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if (!"Id".Equals(orderBy, StringComparison.OrdinalIgnoreCase)
&& !"Name".Equals(orderBy, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderBy is not a valid value");
if (!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if (!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase
ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
command.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase + "%"));
command.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
connection.Close();
}
}
var total = string.Empty;
string sSQLTotal = #"SELECT COUNT(*)
FROM dbo.Log
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQLTotal, connection))
{
command.Parameters.Add(new SqlParameter("searchPhrase", "%" + searchPhrase + "%"));
connection.Open();
command.CommandTimeout = 0;
total = command.ExecuteScalar().ToString();
connection.Close();
}
}
var rows = JsonConvert.SerializeObject(dt);
return result = "{ \"current\": " + current + ", \"rowCount\": " + rowCount + ", \"rows\": " + rows + ", \"total\": " + total + " }";
}
}

set a constant(same) time stamp for multiple data base rows

I'm creating an asp.net mvc4 application, that can write data into database tables from excel sheets(using sqlbulkcopy column mapping). when we select excel sheet and submit, it is writing data into database.
Now I want to set file uploaded time as timestamp for each data rows when it write data into database table.
Code:
namespace AFFEMS2_HEC.Controllers
{
public class ExcelController : Controller
{
//
// GET: /Excel/
public ActionResult Index()
{
return View();
}
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(HttpPostedFileBase FileUpload1)
{
//Upload and save the file
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string excelPath = Path.Combine(HttpContext.Server.MapPath("~/Content/"), Path.GetFileName(FileUpload1.FileName));
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
string sheet2 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[4] {
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("Email",typeof(string)),
new DataColumn("Mobile", typeof(int)) });
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
using (OleDbDataAdapter oda = new OleDbDataAdapter(query, excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con,
SqlBulkCopyOptions.CheckConstraints|
SqlBulkCopyOptions.FireTriggers|
SqlBulkCopyOptions.KeepNulls|
SqlBulkCopyOptions.TableLock|
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
con.Open();
try
{
// Write from the source to the destination
sqlBulkCopy.WriteToServer(dtExcelData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
return View();
}
}
}
Just create another column as "TimeStamp_Inserted" but it type should be datetime or
nvarchar
and try to replace following code snippet
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"'"+DateTime.Now.ToString() +"'"+" as TimeStamp_Inserted"+
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
sqlbulkcopy column mapping try to change like this
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
sqlBulkCopy.ColumnMappings.Add("TimeStamp_Inserted", "TimeStamp");
con.Open();
just try it

Excel Upload in asp.net

I am uploading excel in asp.net. but one column not read .
protected void btnUpload_Click(object sender, EventArgs e)
{
SqlConnection myconn = new SqlConnection(sqlConnectionString);
if (FileUpload1.HasFile)
{
string paramExcelSheetName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.Equals(Server.MapPath("~/UploadExcel/" + paramExcelSheetName));
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = string.Concat(Server.MapPath("~/UploadExcel/" + FileUpload1.FileName));
if (File.Exists(path))
{
File.Delete(path);
}
if (strFileType.Trim() == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Persist Security Info=False;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
FileUpload1.SaveAs(path);
OleDbConnection conn = new OleDbConnection(excelConnectionString);
query = "SELECT * FROM [Sheet1$] ";
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader oledbdr = cmd.ExecuteReader();
#region readline by line
if (oledbdr.HasRows)
{
while (oledbdr.Read())
{
if (!oledbdr.IsDBNull(0))
{
if (!oledbdr.IsDBNull(0))
{
sr =Convert.ToInt32( oledbdr["SrNo"].ToString());
}
else
{
}
if (!oledbdr.IsDBNull(0))
{
certificate = oledbdr["CertificateNo"].ToString();
}
else
{
}
if (!oledbdr.IsDBNull(0))
{
cr = oledbdr["CR"].ToString();
}
else
{
}
//if (!oledbdr.IsDBNull(0))
//{
// cr = oledbdr["Pass"].ToString();
//}
//else
//{
//}
#region
SqlCommand myCommand = new SqlCommand("INSERT INTO test1 (SrNo,CertificateNo,CR) VALUES('" + sr + "','" +certificate+ "','" + cr + "')", myconn);
try
{
myconn.Open();
myCommand.ExecuteNonQuery();
myconn.Close();
}
catch (Exception ex)
{
myconn.Close();
}
#endregion
}
}
}
#endregion
conn.Close();
}
}
one column certificate not read certificate value like 737737373737/En2
try this code.
query = "SELECT SrNo,CertificateNo,CR FROM [Sheet1$] ";
FileUpload1.SaveAs(Server.MapPath("~/uploadmedicine/") + FileUpload1.FileName);
if (FileUpload1.PostedFile != null)
{
string path = FileUpload1.PostedFile.FileName;
string connectString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/uploadmedicine/") + FileUpload1.FileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("SELECT SrNo,CertificateNo,CR from [Sheet1$]", conn);
}

ASP.NET C# - Redirect After Inserted Record

I perform and insert new record, this code below works for for inserting. After that, I want to redirect to another page using window.parent.location with the ID (ProposalID) that I used in the insert.
private void ExecuteInsert(string ProposedID, string CreatedBy, string Note)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_ProposedNote (ProposedID, Note, CreatedBy)
VALUES "
+ " (#ProposedID, #Note, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ProposedID", SqlDbType.Int, 10);
param[1] = new SqlParameter("#Note", SqlDbType.VarChar, 2000);
param[2] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = ProposedID;
param[1].Value = Note;
param[2].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
}
}
This is where I and to redirect to another page + RecordID
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
Please help. Thanks in advance.
You probably want
Response.Redirect(string.format("~/ProposalItemView.aspx?ProposedID={0}", ProposedID), true);

Resources