Retrieving images from Database into ArrayList and Displaying it one by one from ArrayList in ASP.NET - asp.net

using following code i store images into ArrayList.
public ArrayList getImagesToArray(string qry)
{
ArrayList arr;
if (myConn.State == System.Data.ConnectionState.Closed)
myConn.Open();
if (myDR != null)
myDR.Close();
myComm = new SqlCommand(qry, myConn);
using (myComm)
{
arr = new ArrayList();
myDR = myComm.ExecuteReader();
while (myDR.Read())
{
arr.Add((byte[])myDR[0]);
}
return arr;
}
}
Now i retreive images to an ArrayList using Following Code
ArrayList arrImgs_Main = Q.getImagesToArray("Select FieldImg from InfoTagQA I INNER JOIN PensionScannedDocs P on p.ScanImageID=i.ScanImageID Where P.PersonalNumber='" + hid_PersonalNo.Value + "'");
Now I display image one by one from arrayList to ImageUrl by clicking Next and Previous button
protected void lnk_BackImage_Click(object sender, EventArgs e)
{
try
{
if (arrImgs_Main.Count > 0)
{
if (i > 0)
{
i--;
img_mainImage.ImageUrl = "data:image;base64," + Convert.ToBase64String((byte[])arrImgs_Main[i]);
lab_TotalRecords.Text = "(" + (i + 1) + "/" + arrImgs_Main.Count + ")";
if (i == 0)
{
lnk_ForwardImage.Visible = true;
lnk_BackImage.Visible = false;
}
}
}
}
catch(Exception ee)
{
ShowErrorMsg(ee.Message);
}
}
**All above code works fine and quick on my local machine, but after deployment on server , it take much time in displaying image one by one from array.
Am i doing doing right in above code or going on wrong way. Please guide me **

Related

Export to CSV not working in mobile handheld device using c#

I am working with Mobile Handheld device application using c#, trying to export datatable to csv file but none of method are working for me,
Plateform Visual Studio 2008 and Smart Device Application.
File.WriteALLText method is not working in smart device application.
private void btnsubmit_Click(object sender, EventArgs e)
{
TextWriter txt = new StreamWriter("logs.txt");
try
{
if (!string.IsNullOrEmpty(txtOutput.Text) && !string.IsNullOrEmpty(txtqty.Text))
{
DataTable dt;
dt = new DataTable();
dt.Columns.Add("Barcode", System.Type.GetType("System.String"));
dt.Columns.Add("Location", System.Type.GetType("System.String"));
dt.Columns.Add("Quantity", System.Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["Barcode"] = txtOutput.Text.Trim();
dr["Location"] = "123";
dr["Quantity"] = txtqty.Text.Trim();
dt.Rows.Add(dr);
StringBuilder data = ConvertDataTableToCsvFile(dt);
SaveData(data, #"Data.csv");
MessageBox.Show("Data exported Success");
}
else
{
MessageBox.Show("Please enter all value");
}
txt.Close();
}
catch (Exception ex)
{
string errmsg = ex.Message.ToString();
MessageBox.Show("error " + errmsg);
}
txt.Close();
}
public StringBuilder ConvertDataTableToCsvFile(DataTable dtData)
{
StringBuilder data = new StringBuilder();
for (int column = 0; column < dtData.Columns.Count; column++)
{
//Making sure that end of the line, shoould not have comma delimiter.
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";"));
else
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";") + ',');
}
data.Append(Environment.NewLine);//New line after appending columns.
for (int row = 0; row < dtData.Rows.Count; row++)
{
for (int column = 0; column < dtData.Columns.Count; column++)
{
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";"));
else
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";") + ',');
}
if (row != dtData.Rows.Count - 1)
data.Append(Environment.NewLine);
}
return data;
}
public void SaveData(StringBuilder data, string filePath)
{
using (StreamWriter objWriter = new StreamWriter(filePath))
{
objWriter.WriteLine(data);
}
}
I've had same issue, years ago when starting with Handheld device with Windows mobile on them. You should add objWriter.Flush() in SaveData:
public void SaveData(StringBuilder data, string filePath)
{
using (StreamWriter objWriter = new StreamWriter(filePath))
{
objWriter.WriteLine(data);
objWriter.Flush();
}
}

Adding a new item in database through combobox

I am having a database and I use it through Entity Framework, I need to update the data by editing the other items in text boxes and grid, that is working fine and below is the code:
In aspx.cs
protected void SaveBtn_Click(object sender, EventArgs e)
{
obj.Address = AppAddress.Text;
obj.City = AppCity.Text;
obj.Email = AppEmail.Text;
obj.Notes = AppComments.Text;
obj.Postal = AppPostal.Text;
obj.AppraiserAppraiserCompanyId = ApprCompCmbx.SelectedIndex;
obj.ProvinceState = Province.SelectedIndex;
apprblobj.GetUpdate(obj);
Response.Write("<script>alert('You have successfully updated the Data');</script>");
}
call in the BL:
public void GetUpdate(Appraiser appObj)
{
obj.UpdateData(appObj);
}
and in the DAL
public void UpdateData(Appraiser apprObj)
{
try
{
var Appsave = context.Appraisers.FirstOrDefault(App => App.AppraiserId == apprObj.AppraiserId);
if (Appsave != null)
{
Appsave.AppraiserName = apprObj.AppraiserName;
Appsave.AppraiserAppraiserCompanyId = apprObj.AppraiserAppraiserCompanyId;
Appsave.Address = apprObj.Address;
Appsave.City = apprObj.City;
Appsave.ProvinceState = apprObj.ProvinceState;
Appsave.Email = apprObj.Email;
Appsave.Postal = apprObj.Postal;
Appsave.Notes = apprObj.Notes;
context.SaveChanges();
}
}
catch (Exception ex)
{
log.Debug("Appraiser : UpdateData: " + ex.Message + " Trace : " + ex.StackTrace);
}
}
Now I wanto to add a new item through the same combobox and on the button click functionality as it is doing all the work like add, update and delete.
Kindly provide me the hint: This I know that addobject(__) will ve used in place of savechanges etc.

if..else statement not working in foreach loop

Else statement not working properly in foreach loop? Here's my code. If something's wrong with my code explanations would be nice.
protected void getdata_Click(object sender, EventArgs e)
{
using (var db2 = new cftzClassDataContext())
{
var username = (from p in db2.cftzAccounts
where p.username.Equals(getdata2.Text)
select p);
foreach (var p in username)
{
if (getdata2.Text == p.username)
{
displayMSG.Text = "Is this correct ";
displayData.Text = p.username;
displayQuestionMark.Text = "?";
}
else
{
displayMSG.Text = "No User Found.";
}
}
}
}
The if statement is entirely redundant, as you have already filtered your list to only include accounts where the username equals getData2.Text. Therefore, your if test will always evaluate to true.
You can rewrite it as this, with the same effect
using (var db2 = new cftzClassDataContext())
{
var username = (from p in db2.cftzAccounts.Take(100)
where p.username.Equals(getdata2.Text)
select p);
foreach (var p in username)
{
displayMSG.Text = "Is this correct ";
displayData.Text = p.username;
displayQuestionMark.Text = "?";
}
}
However, as Hans points out, your loop is unnecessary as well, as all the usernames will be the same. Your code could be as simple as:
using (var db2 = new cftzClassDataContext())
{
var user = db2.cftzAccounts.
FirstOrDefault(account => account.username.Equals(getdata2.Text));
if (user != null)
{
displayMSG.Text = "Is this correct ";
displayData.Text = user.username;
displayQuestionMark.Text = "?";
}
else
{
displayMSG.Text = "No User Found.";
}
}
not sure what you try to achieve, but it looks like you are try to find if user is in database and if so, configure displayMSG object.
cant you do something like
var user=db2.Single(u=> u.username==getdata2.Text);
if no user is found, Singe will throw an exception. If you dont wont that, you can use SingleOrDefault() method
protected void getdata_Click(object sender, EventArgs e)
{
using (var db2 = new cftzClassDataContext())
{
try
{
var user=db2.Single(u=> u.username==getdata2.Text);
displayMSG.Text = "Is this correct ";
displayData.Text = user.username;
displayQuestionMark.Text = "?";
}
catch
{
displayMSG.Text = "No User Found.";
}
}
}

SQLite keep expanding

I'm new to the blackberry development and to this site. right now, i'm working on an app that retrieve data from a json service. In my app I should parse the data into a database and save it in four tables. I already parsed the data and I was successful able to create the database and add the first and the second tables.
The problem that I'm facing right now is, the second table in my data base keep expanding. I checked the database in the sql browser and I discovered that everytime I click on the app icon it adds the 700 rows to the table again.(ex. 700 becomes 1400) .
(only to the second table, the first table works so fine).
Thank you in advance
This is my code:
public void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Managers")) {
add(new LabelField("Managers has been added to the database"));
JSONArray j2 = j.getJSONArray("Managers");
for (intk = 0; k < j2.length(); ++k) {
JSONObject MangersDetails = j2.getJSONObject(k);
if (MangersDetails.has("fName")) {
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(myURI);
Statement st =
d.createStatement
("CREATE TABLE Managers ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.open(myURI);
Statement st =
d.createStatement
("INSERT INTO Managers(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
//Owners method
public voidparseJSONResponceInBB1(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Owners")) {
add(new LabelField("Owners has been added to the database"));
JSONArray j2 = j.getJSONArray("Owners");
for (intk = 0; k < j2.length(); ++k) {
JSONObject OwnersDetails = j2.getJSONObject(k);
if (OwnersDetails.has("fName")) {
try {
Statement st =
d.createStatement
("CREATE TABLE Owners ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
Statement st =
d.createStatement
("INSERT INTO Owners(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
It depends on what your goals are here. If you want to replace the data in the database each time the json query runs, you should add a sqlite command to remove all the existing rows with the newly fetched ones coming in via JSON.
If you just want to keep certain types of records unique, you should add an index to the sqlite table. The 'ID' column is a likely candidate for this. You'll have to do some experiments to make sure a conflict is handled correctly - it may abort the entire transaction. "INSERT OR REPLACE" is useful in that situation.

Object reference not set to an instance of an object

I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.

Resources