I am new to ExtJS,i used in asp.net,C# in VS2008.. i simply added comboBox control with static data in aspx page,
but i need to know how to bind the value from sql DB , can any one provide any sample application which explains, how to get the value from the control and bind to the controls
Thanks in advance
Create a generic HTTP handler, for example our agency list uses this code:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
context.Response.ContentEncoding = Encoding.UTF8;
// Get User ID
int user_id;
try {
user_id = int.Parse(context.Session["user_id"].ToString());
} catch {
WriteErrorObject(context,"Could not find required user in the session.");
return;
}
// Get Query
string query;
try {
query = context.Request.QueryString["query"];
if (String.IsNullOrEmpty(query)) throw new Exception();
} catch {
query = "";
}
// Get Revision
int revision;
try {
revision = int.Parse(ConfigurationManager.AppSettings["reportingRevision"]);
} catch {
revision = -1;
}
// Check for our connection string
try {
if (ConfigurationManager.ConnectionStrings["reportInstance"] == null) throw new Exception();
} catch {
WriteErrorObject(context,"Cannot find the database connection string.");
return;
}
// Get our connection string
string connectionstring = ConfigurationManager.ConnectionStrings["reportInstance"].ConnectionString;
// Create our sproc caller
StoredProc proc;
try {
proc = new StoredProc("usp_rep2_agency_list",connectionstring,30);
} catch (Exception ex) {
WriteErrorObject(context,"There was an exception creating the stored procedure caller: " + ex.Message);
return;
}
// Set up sproc
if (revision != -1) proc.AddParameter("#revision",revision,SqlDbType.Int);
proc.AddParameter("#user_id",user_id,SqlDbType.Int);
if (query != null && query.Length > 0) proc.AddParameter("#query",query,SqlDbType.NVarChar);
// Execute sproc
DataSet results;
try {
results = (DataSet)proc.Execute(StoredProc.ExecuteTypes.ReturnDataset);
} catch (Exception ex) {
WriteErrorObject(context,"There was an exception calling the stored procedure: " + ex.Message);
return;
}
// Check we have results
if (results == null) {
WriteErrorObject(context,"There was no dataset returned from the stored procedure.");
return;
}
// Check we have a table
if (results.Tables.Count < 1) {
WriteErrorObject(context,"There was no tables found in the returned dataset from the stored procedure.");
return;
}
// Get the table
DataTable table = results.Tables[0];
// Begin JSON
StringWriter writer = new StringWriter();
JsonWriter json = new JsonWriter(writer);
json.WriteStartObject();
json.WritePropertyName("success");
json.WriteValue(true);
json.WritePropertyName("count");
json.WriteValue(table.Rows.Count);
json.WritePropertyName("list");
json.WriteStartArray();
// Process table rows
for (int i = 0; i < table.Rows.Count; i++) {
// Get row
DataRow row = table.Rows[i];
// ID
if (row["agency_id"] == null || row["agency_id"] == DBNull.Value) {
WriteErrorObject(context,"There was an error processing the agency id value from row " + i.ToString() + ".");
return;
}
int agency_id;
if (!int.TryParse(row["agency_id"].ToString(),out agency_id)) {
WriteErrorObject(context,"Could not parse the agency id value from row " + i.ToString() + ".");
return;
}
// Name
if (row["agency_name"] == null || row["agency_name"] == DBNull.Value) {
WriteErrorObject(context,"There was an error processing the agency name value from row " + i.ToString() + ".");
return;
}
string agency_name = row["agency_name"].ToString();
// Write out JSON for this row
json.WriteStartObject();
json.WritePropertyName("agency_id");
json.WriteValue(agency_id);
json.WritePropertyName("agency_name");
json.WriteValue(agency_name);
json.WritePropertyName("icon");
json.WriteValue("iq-reporting-dropdowns-agency");
json.WriteEndObject();
}
// End JSON
json.WriteEndArray();
json.WriteEndObject();
string text = writer.GetStringBuilder().ToString();
context.Response.Write(text);
context.Response.Flush();
}
In Ext we then do:
this.ddlAgency = new Ext.form.ComboBox({
fieldLabel: "Agency",
mode: "remote",
triggerAction: "all",
forceSelection: true,
displayField: "agency_name",
valueField: "agency_id",
iconField: "icon",
typeAhead: true,
minChars: 1,
allowBlank: false,
anchor: "100%",
emptyText: "Select an Agency...",
store: new Ext.data.Store({
autoLoad: false,
proxy: new Ext.data.HttpProxy({
method: "GET",
url: "whatever.ashx"
}),
reader: new Ext.data.JsonReader(
{root: "list", totalProperty: "count"},
[{name: "agency_id", type: "int"},{name: "agency_name", type: "string"},{name: "icon", type: "string"}]
),
baseParams: {
action: "agencylist",
level: 1
}
})
});
Note, we use the 'Json.NET' library to handle JSON output and a custom class, 'StoredProc' to do the database interaction. You also won't have the WriteErrorObject() method that simply serializes out an error, but you get the idea.
Related
I have this call which calls a action in the controller and expects a true or false in the object named data.
$("#btnReview").click(function () {
var data = {
'id': '1',
'recordID': selectedInspectionId, 'RoleRemarks': $("#CNGInspectionReport_RoleRemarks").val()
};
$.post('/CNGInspectionReport/ChangeStatus', data, function (data) {
if (data == false) {
alert('Something went wrong');
}
else {
alert('Record reviewed successfully. Kindly review the further records, if any.');
}
});
});
and
public ActionResult ChangeStatus(int id, int recordID, string RoleRemarks, string Role = "") // Later, this should be converted to an object instead of parameters
{
try
{
using (UnitOfWork uwork = new UnitOfWork())
{
CNGInspectionReportDAL = new CNGInspectionReportDAL();
User user = (User)Session["User"];
CNGInspectionReport CNGInspectionReport = uwork.CNGInspectionReportRepository.GetByID(recordID);
CNGInspectionReport.CNGInspectionReportID = recordID;
bool statusCrossOffice = false;
if (id == 1) //Reviewed
{
if(user.Office.Trim() != CNGInspectionReport.StationName.Trim())
{
return Json(new { data = statusCrossOffice, message = "Sorry, this record belongs to another office/station and can only be reviewed by the user of the same station/office" });
}
CNGInspectionReport.RoleRemarks = RoleRemarks;
CNGInspectionReport.CheckedBy = user.UserID;
CNGInspectionReport.CheckedByName = user.UserName;
CNGInspectionReport.Status = (byte)id;
CNGInspectionReport.ReviewDate = DateTime.Now;
}
return Json(new { data = status, message = "Success" });
}
}
catch (Exception ex)
{
ViewBag.Error = ex.Message;
return Json(new { data = false, message = ex.Message });
}
}
but the problem is that it still goes to the else block when returns to the Ajax call. Why? I have clearly returned Fase in data but still it goes to the else part which is NOT FALSE.
You should evaluate your data property of the returned object
if (data.data == false) {
alert('Something went wrong');
}
This is because the data returned value is an object and not a boolean. You can check the value yourself line this:
$.post('/CNGInspectionReport/ChangeStatus', data, function (data) {
alert(JSON.stringify(data));
// etc
I am using Kendo grid and I have stopped the grid from saving duplicate values as follows in create method:
var results = new List<ProviderTypeMasterViewModel>();
try
{
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Start");
foreach (var ProviderTypeMaster in ProviderTypeMasterList)
{
TblProviderTypeMaster ptm = new ProviderTypeMasterViewModel().ToModel(ProviderTypeMaster);
var provd = _context.TblProviderTypeMasters.Where(p => p.ProviderTypeName == ProviderTypeMaster.ProviderTypeName).ToList();
if (provd != null && provd.Count() == 0)
{
if (ProviderTypeMasterList != null && ModelState.IsValid)
{
string userID = GetUserID();
providerTypeMasterService.SaveProviderTypeMaster(ProviderTypeMaster, userID);
}
}
else
{
duplicate = true;
//Session["ErrMsg"] = "Already Exists";
//return RedirectToAction("ProviderType_Read", "ProviderTypeMasters");
}
}
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Complete");
}
catch (Exception e)
{
_logger.LogError("ProviderTypeMastersController ProviderType_Create Failed - " + e.Message);
}
return Json(results.ToDataSourceResult(request, ModelState));
And in the read method I have displayed the error message to the user as follows
try
{
if (duplicate == true)
{
TempData["ErroMsg"] = "Already Exists";
}
_logger.LogInformation("In ProviderTypeMastersController ProviderType_Read");
return Json(providerTypeMasterService.ListProviderTypeMaster().ToDataSourceResult(request));
}
catch (Exception e)
{
_logger.LogError("ProviderTypeMastersController ProviderType_Read Failed - " + e.Message);
}
return View();
The duplication process has stopped. But I am unable to show the error message to the user. Can anyone let me know what I should do where I have gone wrong. I have tried using ViewBag,ViewData,TempData.
This is my View
<div>
if (TempData["ErroMsg"] != null)
{
<p>#TempData["ErroMsg"].ToString()</p>
}
you can use DataBinding() and DataBound() function of kendo grid...these functions call in client side after Read method on server side..for example you can set a field and decision with this field
Might be lock is not working as I expected. Should I use mutes in this case?
Error occurred in following code. On prod it chocked my email server.
Error mail content:
The message is:
Index was outside the bounds of the array.
The Stack trace is:
at System.Collections.Generic.List`1.Add(T item)
at TT.SharedServices.Auditor.Audit.AddAudit(AuditEventType pEvType, Severity pSeverity, Int32 pClientId, String pSessionId, String pDetail, String pClientIp, String pEndUserIp)
The Inner Exception is:
The Request parameters are : sessionID : df58b273-c399-4692-8c14-7400b219769e Details : TimeTaken for LoadAgency:13 ms
private void AddAudit(AuditEventType pEvType, Severity pSeverity, int pClientId, string pSessionId, string pDetail,
string pClientIp, string pEndUserIp)
{
// TO DO: also add Time
Trace.TraceInformation("Audit.Add entered : ");
try
{
if (pSeverity == Severity.High || Convert.ToBoolean(ConfigurationSystem.SharedApiConfig[pSeverity.ToString().ToLower()])) // chk option in config for adding audit
{
if (string.IsNullOrEmpty(pDetail))
{
throw new ArgumentException("Detail should have a value", "pDetail");
}
// adding data
var paramList = new DbParameter[8];
paramList[0] = DataAccess.ParameterFactory.Create("#eventType", DbType.Int16, pEvType);
paramList[1] = DataAccess.ParameterFactory.Create("#severity", DbType.Int16, pSeverity);
paramList[2] = DataAccess.ParameterFactory.Create("#clientId", DbType.String, pClientId);
paramList[3] = DataAccess.ParameterFactory.Create("#detail", DbType.String, pDetail);
if (string.IsNullOrEmpty(pClientIp))
paramList[4] = DataAccess.ParameterFactory.Create("#clientIP", DbType.String, DBNull.Value);
else
paramList[4] = DataAccess.ParameterFactory.Create("#clientIP", DbType.String, pClientIp);
if (string.IsNullOrEmpty(pEndUserIp))
paramList[5] = DataAccess.ParameterFactory.Create("#endUserIP", DbType.String, DBNull.Value);
else
paramList[5] = DataAccess.ParameterFactory.Create("#endUserIP", DbType.String, pEndUserIp);
if (string.IsNullOrEmpty(pSessionId))
paramList[6] = DataAccess.ParameterFactory.Create("#sessionId", DbType.String,
new Guid().ToString());
else
paramList[6] = DataAccess.ParameterFactory.Create("#sessionId", DbType.String, pSessionId);
paramList[7] = DataAccess.ParameterFactory.Create("#eventTime", DbType.DateTime, DateTime.Now);
if (IsBulkAuditSharedApi)
{
_auditQueueData.Add(paramList);
if (_auditQueueData.Count > MaxCountSharedApi)
{
AuditThreadData threadData = new AuditThreadData();
lock (_auditQueueData)
{
threadData.Audit = new List<DbParameter[]>();
threadData.Audit = _auditQueueData;
_auditQueueData = new List<DbParameter[]>();
}
Thread callAuditPush = new Thread(AuditPushThread);
callAuditPush.Start(threadData);
}
}
else
{
int rowsAffected = DataAccess.ExecuteNonQuery(SpNames.IAPI_AddAudit, paramList);
Trace.TraceInformation("Audit.Add : Adding Audit data. rowsAffected = " + rowsAffected);
}
Trace.TraceInformation("Audit.Add exit : ");
}
}
catch (Exception exception)
{
string auditText = "The message is :" + exception.Message + "<br/> The Stack trace is :" + exception.StackTrace;
auditText += "<br/> The Inner Exception is:" + exception.InnerException;
auditText += "<br/> The Request parameters are : \n sessionID : " + pSessionId + "\n Details : " + pDetail;
Email.Email.SendingErrorEmail("Exception in Adding Audit in IAPI :", auditText, true, Email.Email.EmailSeverity.Error);
}
}
struct AuditThreadData
{
internal List<DbParameter[]> Audit;
}
#region Private Static Methods
/// <summary>
/// This method will Audit the data(in Bulk) in DB
/// </summary>
/// <param name="objData"></param>
private void AuditPushThread(object objData)
{
try
{
var data = (AuditThreadData)objData;
if (data.Audit != null && data.Audit.Count > 0)
{
foreach (var paramList in data.Audit)
{
if (DataAccess != null) DataAccess.ExecuteNonQuery(SpNames.IAPI_AddAudit, paramList);
}
}
}
catch (Exception ex)
{
// catch block for precaution.
try
{
var log = new EventLog {Source = "Application"};
log.WriteEntry("Bulk audit add failed:" + ex.Message + ex.InnerException, EventLogEntryType.Error, 2344);
}
catch
{
// to handle system security crash while writing log
}
}
}
You call _auditQueueData.Add(paramList); outside of the lock. Try to put it inside.
Also you lock to the List itself, while ICollections (like List) have a SyncRoot property which exists for this very purpose. This property might be used by other parts of the framework like the UI. You need to explicitly cast your List to ICollection to access this property.
I am running a loop in C# that reads a file and make updates to the MySQL database with MySQL ODBC 5.1 driver in a Windows 8 64-bit environment.
The operations is simple
Count +1
See if file exists
Load XML file(XDocument)
Fetch data from XDocument
Open ODBCConnection
Run a couple of Stored Procedures against the MySQL database to store data
Close ODBCConnection
The problem is that after a while it will hang on for example a OdbcCommand.ExecuteNonQuery. It is not always the same SP that it will hang on?
This is a real problem, I need to loop 60 000 files but it only last around 1000 at a time.
Edit 1:
The problem seemse to accure here hever time :
public bool addPublisherToGame(int inPublisherId, int inGameId)
{
string sqlStr;
OdbcCommand commandObj;
try
{
sqlStr = "INSERT INTO games_publisher_binder (gameId, publisherId) VALUE(?,?)";
commandObj = new OdbcCommand(sqlStr, mainConnection);
commandObj.Parameters.Add("#gameId", OdbcType.Int).Value = inGameId;
commandObj.Parameters.Add("#publisherId", OdbcType.Int).Value = inPublisherId;
if (Convert.ToInt32(executeNonQuery(commandObj)) > 0)
return true;
else
return false;
}
catch (Exception ex)
{
throw (loggErrorMessage(this.ToString(), "addPublisherToGame", ex, -1, "", ""));
}
finally
{
}
}
protected object executeNonQuery(OdbcCommand inCommandObj)
{
try
{
//FileStream file = new FileStream("d:\\test.txt", FileMode.Append, FileAccess.Write);
//System.IO.StreamWriter stream = new System.IO.StreamWriter(file);
//stream.WriteLine(DateTime.Now.ToString() + " - " + inCommandObj.CommandText);
//stream.Close();
//file.Close();
//mainConnection.Open();
return inCommandObj.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (ex);
}
}
I can see that the in parameters is correct
The open and close of the connection is done in a top method for ever loop (with finally).
Edit 2:
This is the method that will extract the information and save to database :
public Boolean addBoardgameToDatabase(XElement boardgame, GameFactory gameFactory)
{
int incomingGameId = -1;
XElement tmpElement;
string primaryName = string.Empty;
List<string> names = new List<string>();
GameStorage externalGameStorage;
int retry = 3;
try
{
if (boardgame.FirstAttribute != null &&
boardgame.FirstAttribute.Value != null)
{
while (retry > -1)
{
try
{
incomingGameId = int.Parse(boardgame.FirstAttribute.Value);
#region Find primary name
tmpElement = boardgame.Elements("name").Where(c => c.Attribute("primary") != null).FirstOrDefault(a => a.Attribute("primary").Value.Equals("true"));
if (tmpElement != null)
primaryName = tmpElement.Value;
else
return false;
#endregion
externalGameStorage = new GameStorage(incomingGameId,
primaryName,
string.Empty,
getDateTime("1/1/" + boardgame.Element("yearpublished").Value),
getInteger(boardgame.Element("minplayers").Value),
getInteger(boardgame.Element("maxplayers").Value),
boardgame.Element("playingtime").Value,
0, 0, false);
gameFactory.updateGame(externalGameStorage);
gameFactory.updateGameGrade(incomingGameId);
gameFactory.removeDesignersFromGame(externalGameStorage.id);
foreach (XElement designer in boardgame.Elements("boardgamedesigner"))
{
gameFactory.updateDesigner(int.Parse(designer.FirstAttribute.Value), designer.Value);
gameFactory.addDesignerToGame(int.Parse(designer.FirstAttribute.Value), externalGameStorage.id);
}
gameFactory.removePublishersFromGame(externalGameStorage.id);
foreach (XElement publisher in boardgame.Elements("boardgamepublisher"))
{
gameFactory.updatePublisher(int.Parse(publisher.FirstAttribute.Value), publisher.Value, string.Empty);
gameFactory.addPublisherToGame(int.Parse(publisher.FirstAttribute.Value), externalGameStorage.id);
}
foreach (XElement element in boardgame.Elements("name").Where(c => c.Attribute("primary") == null))
names.Add(element.Value);
gameFactory.removeGameNames(incomingGameId);
foreach (string name in names)
if (name != null && name.Length > 0)
gameFactory.addGameName(incomingGameId, name);
return true;
}
catch (Exception)
{
retry--;
if (retry < 0)
return false;
}
}
}
return false;
}
catch (Exception ex)
{
throw (new Exception(this.ToString() + ".addBoardgameToDatabase : " + ex.Message, ex));
}
}
And then we got one step higher, the method that will trigger addBoardgameToDatabase :
private void StartThreadToHandleXmlFile(int gameId)
{
FileInfo fileInfo;
XDocument xmlDoc;
Boolean gameAdded = false;
GameFactory gameFactory = new GameFactory();
try
{
fileInfo = new FileInfo(_directory + "\\" + gameId.ToString() + ".xml");
if (fileInfo.Exists)
{
xmlDoc = XDocument.Load(fileInfo.FullName);
if (addBoardgameToDatabase(xmlDoc.Element("boardgames").Element("boardgame"), gameFactory))
{
gameAdded = true;
fileInfo.Delete();
}
else
return;
}
if (!gameAdded)
{
gameFactory.InactivateGame(gameId);
fileInfo.Delete();
}
}
catch (Exception)
{ throw; }
finally
{
if(gameFactory != null)
gameFactory.CloseConnection();
}
}
And then finally the top level :
public void UpdateGames(string directory)
{
DirectoryInfo dirInfo;
FileInfo fileInfo;
Thread thread;
int gameIdToStartOn = 1;
dirInfo = new DirectoryInfo(directory);
if(dirInfo.Exists)
{
_directory = directory;
fileInfo = dirInfo.GetFiles("*.xml").OrderBy(c=> int.Parse(c.Name.Replace(".xml",""))).FirstOrDefault();
gameIdToStartOn = int.Parse(fileInfo.Name.Replace(".xml", ""));
for (int gameId = gameIdToStartOn; gameId < 500000; gameId++)
{
try
{ StartThreadToHandleXmlFile(gameId); }
catch(Exception){}
}
}
}
Use SQL connection pooling by adding "Pooling=true" to your connectionstring.
Make sure you properly close the connection AND the file.
You can create one large query and execute it only once, I think it is a lot faster then 60.000 loose queries!
Can you show a bit of your code?
I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).
My code:
private void updateCustomer()
{
MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");
MySqlCommand command = new MySqlCommand(#"mySelectCommand", connection);
DataTable customerTbl = new DataTable();
MySqlDataReader reader;
try
{
connection.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
customerTbl.Load(reader);
}
reader.Close();
}
catch (Exception ex)
{
_out.error("Could not connect to mySql database");
}
finally
{
connection.Close();
}
foreach (DataRow row in customerTbl.Rows)
{
// Declare the customer variables
string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
string ChildOf = row["Child of"].ToString();
// Create the customer object
Customer customer = new Customer();
customer.entityId = customerID;
if (ChildOf != "")
{
RecordRef parentRef = new RecordRef();
try
{
parentRef.internalId = searchCustomer(ChildOf);
}
catch
{
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
_out.error(customerID + " was not updated. Error: invalid format Parent string");
}
finally
{
parentRef.typeSpecified = false;
customer.parent = parentRef;
}
}
// Invoke update() operation
WriteResponse response = _service.update(customer);
// Process the response
if (response.status.isSuccess)
{
}
else
{
_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
}
}
}
You need to remove the row in the catch block, and change the foreach loop to a backwards for loop to handle the removals.
I realized that I want to log the other failed fields as well. Maybe it's an inefficient way but I did something like:
bool findParent = true;
if (ChildOf != "")
{
try
{
RecordRef parentRef = new RecordRef();
parentRef.internalId = searchCustomer(ChildOf);
parentRef.typeSpecified = false;
customer.parent = parentRef;
}
catch
{
findParent = false;
_out.error(customerID + " was not inserted. Error: invalid format Parent string");
}
}
And then an if statement before trying to insert:
if (findPartner == true && findParent == true)
{
response = _service.add(customer);
// Process the response
if (response.status.isSuccess)
{
}
else
{
_out.error(customerID + " was not inserted. Error: " + getStatusDetails(response.status));
}
}
else
{
//_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
}
Use the row.HasError property.