1120 error by adding a var in Flex 3 - apache-flex

On the adobe website was this code:
var conn:SQLConnection = new SQLConnection();
var dbFile:File = File.applicationStorageDirectory.resolvePath("DBSample.db");
try
{
conn.open(dbFile);
trace("the database was created successfully");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
on the line of
conn.open(dbFile);
there is an errorcode: 1120, Access of undefined property
Can anyone help? I just started with flex.
#aftee:
Here is the whole mx:Script, it stays also between CDATA
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.errors.SQLError;
import flash.filesystem.File;
var conn:SQLConnection = new SQLConnection();
var dbFile:File = File.applicationStorageDirectory.resolvePath("DBSample.db");
try
{
conn.open(dbFile);
trace("the database was created successfully");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
var createStmt:SQLStatement = new SQLStatement();
createStmt.sqlConnection = conn;
var sql:String =
"CREATE TABLE IF NOT EXISTS employees (" +
" empId INTEGER PRIMARY KEY AUTOINCREMENT, " +
" firstName TEXT, " +
" lastName TEXT, " +
" salary NUMERIC CHECK (salary > 0)" +
")";
createStmt.text = sql;
createStmt.addEventListener(SQLEvent.RESULT, createResult);
createStmt.addEventListener(SQLErrorEvent.ERROR, createError);
createStmt.execute();
function createResult(event:SQLEvent):void
{
trace("Table created");
}
function createError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}

add to the mx:application tag this option: creationComplete="init()"
and put your code to this function
private function init():void {
var conn:SQLConnection = new SQLConnection();
var dbFile:File = File.applicationStorageDirectory.resolvePath("DBSample.db");
conn.open(dbFile);
...
}

Related

Increase data insert performance

We have created a code that loops in to CosmosDb records and inserts values to Sql db. But in the process, the data insertion perfomance is very slow. please help with suggestions, here is the code. This process is taking more than 4 hours for inserting a data of 4000 rows.
namespace PushNotificationUserInsert
{
class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
#region Variables
var endpoint = ConfigurationManager.AppSettings["DocDbEndpoint"];
var masterKey = ConfigurationManager.AppSettings["DocDbMasterKey"];
var connetionString = ConfigurationManager.AppSettings["SQL_connetionString"].ToString();
// var useremail = "\"\"";
string path = #"xxxx.txt";
string[] useremails = File.ReadAllLines(path);
List<string> It = useremails.ToList();
var newIt = It.Distinct().ToList();
var channel = "\"msteam\"";
var cnn = new SqlConnection(connetionString);
var cnnInsert = new SqlConnection(connetionString);
string query = null;
cnn.Open();
foreach (var email in newIt)
{
query = "SELECT * FROM c where c.document.bot_js.mail = \"" + email + "\" AND CONTAINS(c.id," + channel + ", true)";
dynamic responses = "";
JSONModel.Rootobject records = null;
string conversationId = "";
//string email = "";
#endregion
#region Reading data from SQL
// cnn.Open();
SqlDataReader dataReader;
String Output = "";
SqlCommand command = new SqlCommand(#"SELECT [ConversatonReferenceJson] FROM [dbo].[ConversationReferences] where emailid like ''", cnn);
//command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = dataReader.GetValue(0).ToString();
records = JsonConvert.DeserializeObject<JSONModel.Rootobject>(Output);
}
dataReader.Close();
dataReader.Dispose();
#endregion
string[] readText = File.ReadAllLines(path);
//List<string> It = readText.ToList();
//var newIt = It.Distinct().ToList();
//foreach (string email in newIt)
//{
Console.WriteLine(email);
try
{
#region reading data from Consmos DB
using (var client = new DocumentClient(new Uri(endpoint), masterKey))
{
responses = client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri("Cosmosdbname", "cosmosdbtablebame"), query).ToList();
}
#endregion
#region Looping throught each cosmos DB records and insert value in SQL
foreach (var response in responses)
{
conversationId = response.id.Remove(0, 26);
records.conversation.id = conversationId;
cnnInsert.Open();
SqlCommand commInsert = new SqlCommand("INSERT INTO [ConversationReferences] VALUES " +
"(#ChannelId, #UserId, #ConverJson, #ID, #EmailID)", cnnInsert);
commInsert.Parameters.AddWithValue("#ChannelId", "xxxx");
commInsert.Parameters.AddWithValue("#UserId", "tobedeleted");
commInsert.Parameters.AddWithValue("#ConverJson", JsonConvert.SerializeObject(records));
commInsert.Parameters.AddWithValue("#ID", "tobedeleted");
commInsert.Parameters.AddWithValue("#EmailID", email);
commInsert.ExecuteNonQuery();
cnnInsert.Close();
Console.WriteLine("records updated for " + email);
}
#endregion
}
catch (Exception ex)
{
cnnInsert.Close();
throw;
}
finally
{ cnnInsert.Close(); }
Console.ReadKey();
}
}).Wait();
}
}

How to send data using Json and get in asp.net services

I am php developer and recently switched to asp, I want to send data to web services and get there but I am unable to come up with a solution.
In php if you want to access data for back-end process purpose we simply use
.Serialize(); method,
for example:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
and in Jscript function we will serialize the form, e.g:
var data = $("#loginForm").serialize();
and in process side I can call it by inputs name, But in asp.net I am unable to do the same, I might be missing something or does asp.net do not support such approach at all? I do not know please programmers help me out.
You should use Id property and use stingify() method instead of serialization.
HTML
<input class="form-control" Id="UserEmail" placeholder="Email" type="email" required=""/>
JS
function YesFunction() {
var email= $("#UserEmail").val();
var d= [];
d.push(email);
var jsndta = JSON.stringify({ d: d});
$.ajax({
type: "POST",
url: "wbservices/SearchSchoolInfoAndInventory.asmx/Searchschoolbesicinfo",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
table.html(msg);
} else {
}
}); //1st out loop ends here...
},
error: function (jqXHR, textStatus, errorThrown) {
// $("#responseMovDetails").html(jqXHR + textStatus + errorThrown);
alert("error while loading Purchases Head" + jqXHR + textStatus + errorThrown);
}
});
}
Now create a class and create two public variables and call both variables by creating class object in web service class.
public class RequestResponse
{
public bool status { get; set; }
public string msg { get; set; }
}
[WebMethod]
public List<RequestResponse>ActivatePBudget(List<string> d)
{
RequestResponse r = new RequestResponse();
List<RequestResponse> list = new List<RequestResponse>();
string Email= d[0].ToString();
//establish connection. I have established connection in separate class.
DbCon dbcon = new DbCon();
string constr = dbcon.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string CheckEmail = "select * from Table_Name where Email= #m";
SqlCommand getcmd= new SqlCommand(CheckEmail,con);
getcmd.Parameters.AddWithValue("#m", Email);
SqlDataReader reader=getbhidcmd.ExecuteReader();
if(reader.Read())
{
r.status = true;
r.msg = "Valid User Or Redirect user to another page";
list.Add(r);
reader.Close();
}
else
{
reader.Close();
r.status = false;
r.msg = "Invalid Email";
list.Add(r);
}
}
catch (Exception ex)
{
r.status = false;
r.msg = "Invalid Email" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}
HTML+JS+ WEB-SERVICE
JS:
<script type="text/javascript">
function getProject() {
var data = "";
var strUser = "<%=nowUser%>";
$.ajax({
type: 'post',
url: '<%=AppRoot%>main/BackWebservice.asmx/LoadProjects',
async: true,
dataType: 'json',
data: { strAdmin: strUser },
success: function (result) {
var json = eval(result); //数组
var optionstring = "";
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].Name;
var idnumber = json[index].ID;
optionstring += "<option value=\"" + idnumber + "\" >" + name + "</option>";
});
$("#userProject").html("<option value=\"" + 0 + "\"'>所有项目</option> " + optionstring);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
</script>
WEB-SERVICE
[WebMethod]
public void LoadProjects(string strAdmin)
{
List<Project> mProjects = new List<Project>();
string stuJsonString = "";
bool bManager = false;
using (SqlConnection connection1 = new SqlConnection(Cfg.SqlServer))
{
connection1.Open();
string mstrsql1 = "SELECT * FROM ShuiUser where 账号='" + strAdmin + "'";
using (SqlCommand CMD1 = new SqlCommand(mstrsql1, connection1))
{
SqlDataReader DR1 = CMD1.ExecuteReader();
while (DR1.Read())
{
if (DR1["管理"].ToString() == "1")
{
bManager = true;
}
}
DR1.Close();
}
connection1.Close();
}
using (SqlConnection connection2 = new SqlConnection(Cfg.SqlServer))
{
connection2.Open();
string mstrsql2 = "";
if (bManager)
{
mstrsql2 = "select * from ShuiProject";
}
else
{
mstrsql2 = "select a.* from ShuiProject a,ShuiUser b where a.[编号]=b.[项目] AND b.[账号]='" + strAdmin + "' ";
}
using (SqlCommand CMD2 = new SqlCommand(mstrsql2, connection2))
{
SqlDataReader DR2 = CMD2.ExecuteReader();
while (DR2.Read())
{
Project mProject = new Project();
mProject.ID = Convert.ToInt16(DR2["编号"]);
mProject.Name = DR2["名称"].ToString();
mProjects.Add(mProject);
}
DR2.Close();
}
connection2.Close();
}
stuJsonString = JsonConvert.SerializeObject(mProjects);
//主要是下面的两句 The most important two sentences
Context.Response.Write(stuJsonString);
Context.Response.End();
}
ASPX:
<form runat=”server” id="loginForm">
<asp:Textbox runat=”server” cssClass="form-control" id="UserEmail" placeholder="Email" TextMode=”email” required=""/>
</form>
On Codebehind(.cs):
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
I have assumed that you are working on webforms.
you must used jsonp in asp
$.ajax({
url: 'you path',
datatype: 'jsonp',
data: {....}
});

SQLite data should be displayed on view after clicking on tab (view) in tabbedNavigatorApplication (Flex mobile/Flash Builder)

I had created an android app (Employee Directory) in flash builder with SQLite database connection and having 4 tabs (view). I Just want that when I click on the Admin tab the Employee details from the database should be loaded. Below is my code.
EmployeeDirectory.mxml
<s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<fx:Style>
s|ActionBar
{
chromeColor: #D3D3D3;
}
s|ActionBar #titleDisplay
{
color: #161616;
fontSize: 20;
fontWeight: normal;
fontFamily: "Microsoft Sans Serif";
}
s|TabbedViewNavigator #tabBar
{
chromeColor: #D3D3D3;
color: #161616;
fontFamily: "Microsoft Sans Serif";
iconPlacement:top;
}
</fx:Style>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function button1_clickHandler(event:MouseEvent):void {
// Switch to the first section in the application.
tabbedNavigator.selectedIndex = 0;
// Switch to the first view in the section.
ViewNavigator(tabbedNavigator.selectedNavigator).popToFirstView();
}
protected function BackBtn_clickHandler(event:MouseEvent):void {
// Switch to the first view in the section.
ViewNavigator(tabbedNavigator.selectedNavigator).popView();
}
]]>
</fx:Script>
<s:navigators>
<s:ViewNavigator label="Home" width="100%" height="100%"
firstView="views.HomeView" icon="#Embed('assets/Home1.png')">
</s:ViewNavigator>
<s:ViewNavigator label="Admin" width="100%" height="100%"
firstView="views.AdminView" icon="#Embed('assets/admin.png')">
<s:navigationContent>
<s:Button icon="#Embed('assets/home.png')"
click="button1_clickHandler(event)"/>
<s:Button icon="#Embed('assets/back2.png')"
click="BackBtn_clickHandler(event)"/>
</s:navigationContent>
</s:ViewNavigator>
<s:ViewNavigator label="Consultants" width="100%" height="100%"
firstView="views.ConsultantsView" icon="#Embed('assets/doctor.jpg')">
<s:navigationContent>
<s:Button icon="#Embed('assets/home.png')"
click="button1_clickHandler(event)"/>
</s:navigationContent>
</s:ViewNavigator>
<s:ViewNavigator label="Extn." width="100%" height="100%"
firstView="views.ExtnView" icon="#Embed('assets/ext.png')">
<s:navigationContent>
<s:Button icon="#Embed('assets/home.png')"
click="button1_clickHandler(event)"/>
<s:Button label="Back"
click="BackBtn_clickHandler(event)"/>
</s:navigationContent>
</s:ViewNavigator>
</s:navigators>
<fx:Declarations>
</fx:Declarations>
</s:TabbedViewNavigatorApplication>
AdminView
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="Admin" xmlns:dao="dao.*">
<fx:Declarations>
<dao:EmployeeDAO id="srv"/>
</fx:Declarations>
<s:titleContent>
<s:TextInput id="key" width="100%"/>
</s:titleContent>
<s:actionContent>
<s:Button icon="#Embed('assets/search.png')"
click="data=srv.findByName(key.text)"/>
</s:actionContent>
<s:List id="list" top="0" bottom="0" left="0" right="0"
dataProvider="{data}"
change="navigator.pushView(Employeedetails, list.selectedItem)">
<s:itemRenderer>
<fx:Component>
<s:IconItemRenderer
label="{data.firstName} {data.lastName}"
messageField="title"/>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:View>
EmployeeDAO
package dao
{
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import mx.collections.ArrayCollection;
public class EmployeeDAO
{
public function getItem(id:int):Employee
{
var sql:String = "SELECT id, firstName, lastName, title, department,
city, email, officePhone, cellPhone, managerId, picture FROM employee WHERE
id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = id;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result && result.length == 1)
return processRow(result[0]);
else
return null;
}
public function findByManager(managerId:int):ArrayCollection
{
var sql:String = "SELECT * FROM employee WHERE managerId=? ORDER BY
lastName, firstName";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = managerId;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
var list:ArrayCollection = new ArrayCollection();
for (var i:int=0; i<result.length; i++)
{
list.addItem(processRow(result[i]));
}
return list;
}
else
{
return null;
}
}
public function findByName(searchKey:String):ArrayCollection
{
var sql:String = "SELECT * FROM employee WHERE firstName || ' ' ||
lastName || ' ' || department LIKE ? and managerId in ('1','2') ORDER BY id,
managerId, firstName, lastName";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = "%" + searchKey + "%";
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
var list:ArrayCollection = new ArrayCollection();
for (var i:int=0; i<result.length; i++)
{
list.addItem(processRow(result[i]));
}
return list;
}
else
{
return null;
}
}
public function create(employee:Employee):void
{
trace(employee.firstName);
if (employee.manager) trace(employee.manager.id);
var sql:String =
"INSERT INTO employee (id, firstName, lastName, title,
department, managerId, city, officePhone, cellPhone, email, picture) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?)";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = employee.id;
stmt.parameters[1] = employee.firstName;
stmt.parameters[2] = employee.lastName;
stmt.parameters[3] = employee.title;
stmt.parameters[4] = employee.department;
stmt.parameters[5] = employee.manager ? employee.manager.id : null;
stmt.parameters[6] = employee.city;
stmt.parameters[7] = employee.officePhone;
stmt.parameters[8] = employee.cellPhone;
stmt.parameters[9] = employee.email;
stmt.parameters[10] = employee.picture;
stmt.execute();
employee.loaded = true;
}
protected function processRow(o:Object):Employee
{
var employee:Employee = new Employee();
employee.id = o.id;
employee.firstName = o.firstName == null ? "" : o.firstName;
employee.lastName = o.lastName == null ? "" : o.lastName;
employee.title = o.title == null ? "" : o.title;
employee.department = o.department == null ? "" : o.department;
employee.city = o.city == null ? "" : o.city;
employee.email = o.email == null ? "" : o.email;
employee.officePhone = o.officePhone == null ? "" : o.officePhone;
employee.cellPhone = o.cellPhone == null ? "" : o.cellPhone;
employee.picture = o.picture;
if (o.managerId != null)
{
var manager:Employee = new Employee();
manager.id = o.managerId;
employee.manager = manager;
}
employee.loaded = true;
return employee;
}
public static var _sqlConnection:SQLConnection;
public function get sqlConnection():SQLConnection
{
if (_sqlConnection) return _sqlConnection;
var file:File =
File.applicationDirectory.resolvePath("assets/Employee.db");
var fileExists:Boolean = file.exists;
_sqlConnection = new SQLConnection();
_sqlConnection.open(file);
if (!fileExists)
{
createDatabase();
populateDatabase();
}
return _sqlConnection;
}
protected function createDatabase():void
{
var sql:String =
"CREATE TABLE IF NOT EXISTS employee ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"firstName VARCHAR(50), " +
"lastName VARCHAR(50), " +
"title VARCHAR(50), " +
"department VARCHAR(50), " +
"managerId INTEGER, " +
"city VARCHAR(50), " +
"officePhone VARCHAR(30), " +
"cellPhone VARCHAR(30), " +
"email VARCHAR(30), " +
"picture VARCHAR(200))";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
}
protected function populateDatabase():void
{
var file:File =
File.applicationDirectory.resolvePath("assets/employees.xml");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
var employeeDAO:EmployeeDAO = new EmployeeDAO();
for each (var emp:XML in xml.employee)
{
var employee:Employee = new Employee();
employee.id = emp.id;
employee.firstName = emp.firstName;
employee.lastName = emp.lastName;
employee.title = emp.title;
employee.department = emp.department;
employee.city = emp.city;
employee.officePhone = emp.officePhone;
employee.cellPhone = emp.cellPhone;
employee.email = emp.email;
employee.picture = emp.picture;
if (emp.managerId>0)
{
employee.manager = new Employee();
employee.manager.id = emp.managerId;
}
employeeDAO.create(employee);
}
}
}
}
The below is my screen
this is the home screen and after clicking on admin tab the data should be
displayed. Currently the data is displayed after clicking on search button in
admin view
[After clicking on admin tab from home screen][2]
The data should be displayed like this

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 + " }";
}
}

Check If Value Exists in DB

I am trying to check if value exists in DB and trying to 'out' it to a var.
and cannot get it to turn into a 1...
here is my code to check.
if(!sqlUtil.Check_Person_Exists(txt_FirstName.Text.Trim(),txt_Surname.Text.Trim()))
{
// Insert
// ======
sqlUtil.Insert_person(obj);
// Redirect
// ========
Response.Redirect("Default.aspx");
}
else
{
txt_FirstName.BackColor = Color.FromName(ConfigurationManager.AppSettings["ErrorColour"]);
txt_Surname.BackColor = Color.FromName(ConfigurationManager.AppSettings["ErrorColour"]);
lbl_message.Text = " * '" + txt_FirstName.Text + " " + txt_Surname.Text +
"' already Exists!";
}
Here is the Check Method.
public Boolean Check_Person_Exists(String Fname, String Lname)
{
// Init()
// ======
SqlConnection conn = null;
SqlDataReader rdr = null;
SqlCommand cmd = null;
var iPerson = 0;
var bPerson = false;
try
{
// Config
// -------
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
conn.Open();
cmd = new SqlCommand("[sp_Check_Person_Exists]", conn);
cmd.CommandType = CommandType.StoredProcedure;
// Param(s)?
// ---------
cmd.Parameters.Add("#s_FirstName", SqlDbType.NVarChar, 50).Value = Fname;
cmd.Parameters.Add("#s_Surname", SqlDbType.NVarChar, 50).Value = Lname;
// Execute
// -------
rdr = cmd.ExecuteReader();
// Row(s)?
// -------
if (rdr.HasRows)
{
// Read
// ----
while (rdr.Read())
{
// Something there?
// ----------------
if (rdr["FirstName"].ToString() !=string.Empty)
{
// Valid?
// ------
Int32.TryParse(rdr["FirstName"].ToString(), out iPerson);
if(iPerson > 0)
{
// Exists
// ------
bPerson = true;
}
}
}
}
// Clean up / close down
// ---------------------
cmd.Dispose();
rdr.Dispose();
rdr.Close();
conn.Dispose();
conn.Close();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
// Clean up / close down
// ---------------------
if (cmd != null)
{
cmd.Dispose();
}
if ((rdr != null) && (!rdr.IsClosed))
{
rdr.Close();
}
if ((conn != null) && (conn.State != ConnectionState.Closed))
{
conn.Dispose();
conn.Close();
}
}
// Return
// ======
return bPerson;
}
}
On the // Valid?
Check i am trying to out to the iPerson and this is where it fails and won't populate the iPerson.
Here is my Stored Procedure.
ALTER PROCEDURE [dbo].[sp_Check_Person_Exists]
#s_FirstName nvarchar(50),
#s_Surname nvarchar(50)
AS
BEGIN
SELECT FirstName, Surname
FROM tbl_person
WHERE (FirstName = #s_FirstName) AND (Surname = #s_Surname)
END
I am assigning my variables and all this works ok but just wont populate the iPerson..
You're trying to parse the person's FirstName into an Int32? You'll have to query the ID and parse that into the iPerson.

Resources