Data Refresh not happening till program re launch - c#

I have class which I am implementing the proptery changed event but for some reason my listview will not update the data until I close the app and re launch it.
public BindingList<SalesOrders> GetSalesOrders()
{
BindingList<SalesOrders> _salesOrdersList = new BindingList<SalesOrders>();
try
{
string sageDsn = ConfigurationManager.AppSettings["SageDSN"];
string sageUsername = ConfigurationManager.AppSettings["SageUsername"];
string sagePassword = ConfigurationManager.AppSettings["SagePassword"];
//using (var connection = new OdbcConnection("DSN=SageLine50v24;Uid=Manager;Pwd=;"))
using (var connection = new OdbcConnection(String.Format("DSN={0};Uid={1};Pwd={2};", sageDsn, sageUsername, sagePassword)))
{
connection.Open();
//string sql = string.Format(getInvoiceSql, customerCode, DateTime.Today.AddMonths(-1).ToString("yyyy-MM-dd"));
string fromD = dtpFrom.Value.ToString("yyyy-MM-dd");
string toD = dtpTo.Value.ToString("yyyy-MM-dd");
String SQL = string.Format("SELECT 'ORDER_NUMBER', 'ORDER_OR_QUOTE', 'ANALYSIS_1','ACCOUNT_REF','ORDER_DATE','NAME', 'COURIER_NUMBER','COURIER_NAME','CUST_TEL_NUMBER' ,'DESPATCH_DATE','ACCOUNT_REF', 'DEL_NAME', 'DEL_ADDRESS_1', 'DEL_ADDRESS_2', 'DEL_ADDRESS_3', 'DEL_ADDRESS_4', 'DEL_ADDRESS_5', 'INVOICE_NUMBER','INVOICE_NUMBER_NUMERIC', 'CONTACT_NAME','CONSIGNMENT', 'NOTES_1', 'ITEMS_NET' ,'ITEMS_GROSS','QUOTE_STATUS' FROM SALES_ORDER WHERE ORDER_DATE >='{0}' and ORDER_DATE <='{1}'", fromD, toD);
using (var command = new OdbcCommand(SQL, connection))
{
backgroundWorker1.ReportProgress(15);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
backgroundWorker1.ReportProgress(35);
counter++;
var salesOrders = new SalesOrders();
if ((reader["ORDER_NUMBER"] != ""))
{
string orderNumber = Convert.ToString(reader["ORDER_NUMBER"]);
salesOrders.ACCOUNT_REF = Convert.ToString(reader["ACCOUNT_REF"]);
salesOrders.RecordIdentifier = "SHN";
salesOrders.ShipmmentId = Convert.ToString(reader["ORDER_NUMBER"]);
salesOrders.OrderDate = Convert.ToDateTime(reader["ORDER_DATE"]);
salesOrders.OrderNumber = Convert.ToString(reader["ORDER_NUMBER"]);
salesOrders.Company = "hackett";
salesOrders.Carrier = Convert.ToString(reader["COURIER_NUMBER"]);
salesOrders.CarrierService = Convert.ToString(reader["COURIER_NAME"]);
salesOrders.CustomerName = Convert.ToString(reader["NAME"]);
salesOrders.ShipToAddress1 = Convert.ToString(reader["DEL_ADDRESS_1"]);
salesOrders.ShipToAddress2 = Convert.ToString(reader["DEL_ADDRESS_2"]);
salesOrders.ShipToAddress3 = Convert.ToString(reader["DEL_ADDRESS_3"]);
salesOrders.ShipToAddress4 = Convert.ToString(reader["DEL_ADDRESS_4"]);
salesOrders.ShipToAddress5 = Convert.ToString(reader["DEL_ADDRESS_5"]);
salesOrders.ShiptoAttention = Convert.ToString(reader["DEL_NAME"]);
salesOrders.ShiptoPhoneNo = Convert.ToString(reader["CUST_TEL_NUMBER"]);
salesOrders.Country = Convert.ToString(reader["ANALYSIS_1"]);
salesOrders.ShiptoEmail = "";
salesOrders.MakeAddressDefault = "Y";
salesOrders.ExporteDateTime = GetExportedDate(orderNumber);
bool isProcessed = hasbeenProcessed(orderNumber);
if (isProcessed == true)
salesOrders.Exported = true;
_salesOrdersList.Add(salesOrders);
}
backgroundWorker1.ReportProgress(80);
}
}
}
}
backgroundWorker1.ReportProgress(100);
}
catch (Exception ex)
{
}
return _salesOrdersList;
}
}
backgroundWorker1.ReportProgress(100);
}
catch (Exception ex)
{
}
return _salesOrdersList;
}
In my background worker i am creating the list here
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var listOrders = new List<SalesOrders>();
listOrders = GetSalesOrders().OrderByDescending(o => o.OrderDate).ToList();
var listBindingOrders = new BindingList<SalesOrders>(listOrders);
SalesOrders = listBindingOrders;
}
This is my constructor which I am binding the above.
public BindingList<SalesOrders> SalesOrders = new BindingList<BusinessObjects.SalesOrders>();
Here is my class as to which I am using the notifcation changed proprerty on the exported flag which is being changed but it only updates when I close the application.
public class SalesOrders : INotifyPropertyChanged
{
public bool selected { get; set; }
public string ORDER_OR_QUOTE { get; set; }
public string OrderNumber { get; set; }
public string ACCOUNT_REF { get; set; }
public string RecordIdentifier { get; set; }
public DateTime OrderDate { get; set; }
public string ShipmmentId { get; set; }
public string Company { get; set; }
public string Carrier { get; set; }
public string CarrierService { get; set; }
public string Customer { get; set; }
public string CustomerName { get; set; }
public string ShiptoName { get; set; }
public string ShipToAddress1 { get; set; }
public string ShipToAddress2 { get; set; }
public string ShipToAddress3 { get; set; }
public string ShipToAddress4 { get; set; }
public string ShipToAddress5 { get; set;
}
public string ShiptoAttention { get; set; }
public string ShiptoPhoneNo { get; set; }
public string ShiptoEmail { get; set; }
public string County { get; set; }
public string MakeAddressDefault { get; set; }
public string Address
{
get
{
var sb = new StringBuilder();
sb.Append(ShipToAddress1);
sb.Append(ShipToAddress2);
sb.Append(ShipToAddress3);
return sb.ToString();
}
}
private bool ExportedValue = false;
public bool Exported
{
get { return this.ExportedValue; }
set
{
if (value != this.ExportedValue)
{
this.ExportedValue = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// The cons
public DateTime ExporteDateTime { get; set; }
public String Country { get; set; }
}
I thought it would be important to show my binding event here.
// <summary>
/// Bind the list view to the sales order collection
/// </summary>
/// <param name="_salesOrders"></param>
private void BindListView(BindingList<SalesOrders> _salesOrders)
{
invoiceListView.Items.Clear();
foreach (SalesOrders _pur in _salesOrders)
{
invoiceListView.Items.Add(CreateListViewItem(_pur));
}
foreach (ListViewItem lvw in invoiceListView.Items)
{
Boolean hasExported = Convert.ToBoolean(lvw.SubItems[8].Text);
if (hasExported == true)
{
lvw.BackColor = Color.Wheat;
}
}
}
I hope someone can help me out this is driving me nuts at the minute everything else is working but data refresh.

Have you made sure that you have a BindingList that is associated with your ListView using listView1.ItemsSource = bindingList, and then sticking to modifying the actual BindingList instead of the ListView? (Eg. not using listView1.Items.Add, but simply adding to the listViews binding collection)

Have you tried to use the .refresh() method everytime

Related

Link Column In Datagridview C#

How can I set PDF and Word column to link column(Please see the photo below)?
The code to get data from the database:
public IQueryable<Document> GetAllDocuments()
{
//Somethings
}
public List<DocumentForIndexViewModel> GetAllDocumentsForIndexViewModel()
{
List<Document> documents = GetAllDocuments().ToList();
var documentsForIndexViewModel = new List<DocumentForIndexViewModel>();
foreach (var document in documents)
{
var documentForIndexViewModel = new DocumentForIndexViewModel
{
Id = document.Id,
PDFFileName = document.PDFFiles.Last().PDFFileName,
WordFileName = document.WordFiles.Last().WordFileName,
IsDelete = document.Deletes.Last().IsDelete,
CreateDate = document.ActivityTimes.First().Time.ToShamsi(),
DocName = document.DocumentNames.Last().Name,
Producer = document.ProducerNames.Last().Name,
Approver = document.Approvers.Last().Name,
Type = document.Type.Name,
};
EditNumber editNumber = document.EditNumbers.LastOrDefault();
if (editNumber != null)
{
documentForIndexViewModel.LastEditNumber = editNumber.Number;
}
EditDate editDate = document.EditDates.LastOrDefault();
if (editDate != null)
{
documentForIndexViewModel.LastEditDate = editDate.Date.ToShamsi();
}
Review review = document.Reviews.LastOrDefault();
if (review != null)
{
documentForIndexViewModel.LastReviewDate = review.ReviewDate.ToShamsi();
}
documentsForIndexViewModel.Add(documentForIndexViewModel);
}
return documentsForIndexViewModel;
}
DocumentForIndexViewModel:
public class DocumentForIndexViewModel
{
public int Id { get; set; }
[DisplayName("نام سند")]
public string DocName { get; set; }
[DisplayName("نوع")]
public string Type { get; set; }
[DisplayName("فرمت")]
public string Format { get; set; }
[DisplayName("تاریخ ساخت")]
public string CreateDate { get; set; }
[DisplayName("آخرین شماره ویرایش")]
public int? LastEditNumber { get; set; }
[DisplayName("آخرین تاریخ ویرایش")]
public string? LastEditDate { get; set; }
[DisplayName("آخرین بازبینی")]
public string? LastReviewDate { get; set; }
[DisplayName("PDF")]
public string PDFFileName { get; set; }
[DisplayName("تهیه کننده")]
public string Producer { get; set; }
[DisplayName("تصویب کننده")]
public string Approver { get; set; }
[DisplayName("امحا")]
public bool IsDelete { get; set; }
[DisplayName("Word")]
public string WordFileName { get; set; }
}
the code to get data from GetAllDocumentsForIndexViewModel() method in index form:
private void IndexForm_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
MyDataGridView.DataSource = null;
using (UnitOfWork db = new UnitOfWork())
{
var documents = db.DocumentRepository.GetAllDocumentsForIndexViewModel();
MyDataGridView.DataSource = documents;
MyDataGridView.Columns[0].Visible = false;
MyDataGridView.Columns["LastEditDate"].Width = 170;
MyDataGridView.Columns["LastEditNumber"].Width = 170;
}
}
Thankyou

using jsonData as a key value to send mixed data in asp: Does not update the database with the values

After trying to mix a fileupload and json data in postman i finally found a method where it is possible to send them both in the same request. Therefore, I have moved my json data to a Key in Postman, so that it becomes possible to send files as well using form-data (Picture below).
Within the value I have JSON data as following:
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"DamageDate":"2021-05-03",
"DamageKilometerreading":"213",
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":"1223",
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
The empty {} just contains more service types. Now when I send the request in Postman i get a 200 OK and when i debug i can see the following (sorry if the picture is blurry):
¨
However, my database does not get updated with these values. Here's the class for inserting data into the tables:
public async Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData)
{
bool CreateRequest = true;
int requestID = 0;
int claimID = 0;
//bool country = true;
//First Create the Request
foreach (Service item in model.Service)
{
//First Create the Request
if (CreateRequest)
{
var parameters = new DynamicParameters();
parameters.Add("WorkshopEmail", model.WorkshopEmail);
parameters.Add("WorkshopContactperson", model.WorkshopContactperson);
parameters.Add("WorkshopCellphone", model.WorkshopCellphone);
parameters.Add("DamageDate", model.DamageDate);
parameters.Add("LatestServiceDate", model.LatestServiceDate);
parameters.Add("LatestServiceKilometer", model.LatestServiceKilometer);
parameters.Add("DamageKilometerreading", model.DamageKilometerreading);
parameters.Add("CurrentKilometerreading", model.CurrentKilometerreading);
parameters.Add("CarOwnerDescription", model.CarOwnerDescription);
parameters.Add("WorkshopDiagnos", model.WorkshopDiagnos);
parameters.Add("AmountIncVat", model.AmountIncVat);
try
{
var requestIDenum = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[Request]
(WorkshopEmail,WorkshopContactperson,WorkshopCellphone,DamageDate,LatestServiceDate,
LatestServiceKilometer,DamageKilometerreading,CurrentKilometerreading,
CarOwnerDescription,WorkshopDiagnos,AmountIncVat)
VALUES
(#WorkshopEmail,#WorkshopContactperson,#WorkshopCellphone,#DamageDate,#LatestServiceDate,
#LatestServiceKilometer,#DamageKilometerreading,#CurrentKilometerreading,
#CarOwnerDescription,#WorkshopDiagnos,#AmountIncVat);SELECT SCOPE_IDENTITY();",parameters);
requestID = requestIDenum.First();
CreateRequest = false;
}
catch(Exception ex)
{
int hej = 0;
}
}
if (item.fileuploadresults != null)
{
foreach (FileUploadResult f in item.fileuploadresults)
{
var parameters = new DynamicParameters();
parameters.Add("file", f.filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
int FileMessageID = filemessage.First();
await _sqlconnection.QueryAsync<int>($#"INSERT INTO[dbo].[ClaimCrossOptionalFile]
(ClaimID,FileID)
VALUES
({claimID},{FileMessageID});");
}
}
return true;
//return list;
}
Controller:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
// if (!ModelState.IsValid)
// {
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
try
{
//await _request.AddRequest(request);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Interface:
Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData);
Sidenote: This is part of the code, as i've tried to keep it short, so perhaps some } or something is missing here, but there's no problem. If i should add the whole code i could perhaps send it in a link or something similar, as it would be a lot to upload here.
However, I do not now how to proceed with this issue at the moment. I've not worked with form-data much before, at least not with passing json as a value. Perhaps there's something I'm missing/have to do in the controller with the json data? I've tried looking for solutions but I've gotten stuck here. The only issue is that the database does not get updated.
Update, the model:
public class Work
{
//base for claim
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
public string id { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string quantity { get; set; } = "";
//service
public int rentreasonId { get; set; } = -1;
public int rentservicecartypeId { get; set; } = -1;
//tyres
public int tireserviceId { get; set; } = -1;
public IList<TireType> tireTypes { get; set; }
public IList<Labour> labours { get; set; }
public DateTime DateFrom{ get; set; } = DateTime.Parse("1753-01-01");
public DateTime DateTo { get; set; } = DateTime.Parse("1753-01-01");
//Insurance
public string totalAmount { get; set; }
public string requestInsuranceVatID { get; set; }
public string vat { get; set; } = "0.0";
public string totalExclVat { get; set; }="0.0";
public string totalIncVat { get; set; }="0.0";
}
public class Labour
{
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
}
public class TireType
{
public string quantity { get; set; } = "";
public string brand { get; set; } = "";
public string model { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string price { get; set; } = "";
public string tireTypeId { get; set; } = "";
public string widthID { get; set; } = "";
public string heightID { get; set; } = "";
public string diameterID { get; set; } = "";
}
public class Request
{
public string WorkshopEmail { get; set; } = "";
public string WorkshopContactperson { get; set; } = "";
public string WorkshopCellphone { get; set; } = "";
public int AmountIncVat { get; set; } = 0;
#region Claim
public DateTime DamageDate { get; set; } = DateTime.Parse("1753-01-01");
public DateTime LatestServiceDate { get; set; } = DateTime.Parse("1753-01-01");
public int LatestServiceKilometer { get; set; } = 0;
public int DamageKilometerreading { get; set; } = 0;
public int CurrentKilometerreading { get; set; } = 0;
public string CarOwnerDescription { get; set; } = "";
public string WorkshopDiagnos { get; set; } = "";
//public string OptionalMessage { get; set; } = "";
#endregion
public IList<Service> Service { get; set; }
}
public class TireTread
{
public string tireserviceId { get; set; } = "";
public string leftfront { get; set; } = "";
public string rightfront { get; set; } = "";
public string leftrear { get; set; } = "";
public string rightrear { get; set; } = "";
public string added1 { get; set; } = "";
public string added2 { get; set; } = "";
public string added3 { get; set; } = "";
public string added4 { get; set; } = "";
public string added5 { get; set; } = "";
}
public class TireMessage
{
public int tireserviceId { get; set; }
public string message { get; set; }
}
public class Service
{
// [JsonProperty("ServiceId")]
public string RequestTypeId { get; set; } = "";
public string CategoryId { get; set; } = "-1";
public string OptionalMessage { get; set; } = "";
public IList<Work> works { get; set; }
public IList<TireTread> treads { get; set; }
public IList<TireMessage> TireMessages { get; set; }
//filuppladdning
public IList<FileUploadResult> fileuploadresults { get; set; }
}
//filuppladdning
public class FileUploadResult
{
//public IFormFile files { get; set; }
public string filename { get; set; }
}
Firstly,the json format does not match the model structure.You need to pass json like this(Pay attention to DamageKilometerreading and LatestServiceKilometer,the type of them are int,so don't use ""):
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"DamageDate":"2021-05-03",
"DamageKilometerreading":213,
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":1223,
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
Then try to add public string service { get; set; }="" inService model.
I found a solution, in case anyone else comes across this problem. I needed to modify the controller and add this code:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
await _request.AddRequest(request, file, jsonData);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Basically adding request (that I deserialize in the begining of the method), and adding the file, and jsonData in an await request, solved the problem. As for the fileuploading, I needed to modify that method as well, to get the filename into the database:
if (file != null)
{
foreach (IFormFile f in file)
{
string filename = Path.GetFileName(f.FileName);
var parameters = new DynamicParameters();
parameters.Add("file", filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO
[dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
}
}
Changing these to made it possible to send a request containg both the json key value, and multiple files, in the same request.

SQLite Xamarin/C# inserting data

I am developing an application. I have connected my project to SQLIte, now I am trying to add an advert, which I am failing to do.
my SQLInterface
public interface ISQLiteInterface
{
SQLiteConnection GetSQLiteConnection();
}
my Droid SQL
public class SQLiteDb : ISQLiteInterface
{
public SQLiteDb()
{
}
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "Mydatabase.db";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(dbpath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
}
}
my model
public class AdLogEntry
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string SellerName { get; set; }
public string Name { get; set; }
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
public string Image { get; set; }
public string Video { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public string LoadedDate { get; set; }
public string Location { get; set; }
public int Age { get; set; }
}
public class Picture
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] Image { get; set; }
}
public class Video
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] ImageVideo { get; set; }
}
}
this is my task
private async void NextStep_Clicked(object sender, EventArgs e)
{
await SaveAdLog();
}
private async Task SaveAdLog()
{
if (string.IsNullOrWhiteSpace(NameEntry.Text) || (string.IsNullOrWhiteSpace(PriceEntry.Text) || (string.IsNullOrWhiteSpace(LocationEntry.Text))))
{
await DisplayAlert("error", "fill all entries", "OK");
}
else {
var adLogEntry = new AdLogEntry
{
Location = LocationEntry.Text,
Price = PriceEntry.Text,
Name = NameEntry.Text,
};
var result = _adService.CreateAddLogEntry(adLogEntry); //ok
if (result == null)
{
await DisplayAlert("Gratulace", "", "OK");
App.Current.MainPage = new AppShell();
}
};
}
this is my advertservice
class AdService
{
private SQLiteConnection _conn;
public AdService()
{
_conn = DependencyService.Get<Helpers.ISQLiteInterface>().GetSQLiteConnection();
_conn.CreateTable<AdLogEntry>();
}
public string CreateAddLogEntry(AdLogEntry adLogEntry)
{
var detail = _conn.Table<AdLogEntry>();
var d1 = detail.Connection.Insert(adLogEntry);
return "Thank you";
}
}
}
Once I press the button nothing happens. When I try to debug it i get 'Object reference not set to an instance of an object.'
Edit.
This app is supposed to be something like LetItGo so all values should be able to repeat
I have ISQLite interface implemented.
According to your error message, I can not see where you instantiate a new instance of the AdService class.
So please try to add the following code before you call _adService.CreateAddLogEntry() method.
_adService = new AdService();
i think SQLite can't process this properties in your model
List< Picture > and
List< Video >
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
I suggest that you change the property to string and serialize the data before saving

Large object on ViewState

I am storing object of a class on a ViewState. It has 3 string variables. But when ever one string gets larger (more than 400 chars) Pagination stops working.
I have tried so many things but no luck.
So I need to think of another Session Management method?
public class Productx
{
public bool check { get; set; } // ForMultiProduct Page - Selected or not
public string imagePathSmall { get; set; }
public string imagePathLarge { get; set; }
public int Id { get; set; }
public int RatingCount { get; set; }
public string SetName { get; set; }
public string Description { get; set; }
public string KeyWords { get; set; }
public int FavourCount { get; set; }
}
public List<Productx> ArticleList
{
get
{
if (this.ViewState["ArticleList"] != null)
{
return (List<Productx>)(this.ViewState["ArticleList"]);
}
return new List<Productx>();
}
set { this.ViewState["ArticleList"] = value; }
}
List<Productx> al = new List<Productx>();
foreach (DataRow dr in tblProducts.Rows)
{
Productx a = new Productx();
a.check = false;
a.Id = Convert.ToInt32(dr["ID"].ToString());
a.RatingCount = Convert.ToInt32(dr["RATING_COUNT_BY_CAT"].ToString());
string s = dr["KEY_WORDS"].ToString();
a.KeyWords = s;
a.FavourCount = Convert.ToInt32(dr["FAVORITE_COUNT"].ToString());
al.Add(a);
}
if (al.Count > 0) ArticleList = al;

Trying to save xml class to file and my password encryption is not saving

I have the following class that I am using to save my settings:
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
using SSSBackup.MiscClasses;
namespace SSSBackup
{
public class MySettings
{
public string FileList { set; get; }
public bool EmailForFailures { set; get; }
public string EmailAddress { set; get; }
public string OutputDirectory { set; get; }
public string OutputFile { set; get; }
public decimal NumberOfBackupsToKeep { set; get; }
public bool RetainDirectoryStructure { set; get; }
// ftp1 settings
public bool Ftp1Enabled { set; get; }
public string Ftp1Server { set; get; }
public int Ftp1Port { set; get; }
public string Ftp1Username { set; get; }
public string Ftp1RemoteDirectory { set; get; }
private string _ftp1Password;
public string Ftp1Password
{
set
{
if (string.IsNullOrEmpty(value))
{
_ftp1Password = string.Empty;
}
else
{
_ftp1Password = EncryptString.Encrypt(value, "29dk23lh2");
}
}
get
{
return string.IsNullOrEmpty(_ftp1Password) ? string.Empty : EncryptString.Decrypt(_ftp1Password, "29dk23lh2");
}
}
// ftp2 settings
public bool Ftp2Enabled { set; get; }
public string Ftp2Server { set; get; }
public int Ftp2Port { set; get; }
public string Ftp2Username { set; get; }
public string Ftp2RemoteDirectory { set; get; }
private string _ftp2Password;
public string Ftp2Password
{
set
{
if (string.IsNullOrEmpty(value))
{
_ftp2Password = string.Empty;
}
else
{
_ftp2Password = EncryptString.Encrypt(value, "29dk23lh2");
}
}
get
{
if(string.IsNullOrEmpty(_ftp2Password))
{
return string.Empty;
}
return EncryptString.Decrypt(_ftp2Password, "29dk23lh2");
}
}
private static string _settingsFile;
public static XmlSerializer xs;
static MySettings()
{
_settingsFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "sssbackup.xml");
xs = new XmlSerializer(typeof(MySettings));
}
public void SaveToFile()
{
using (var sw = new StreamWriter(_settingsFile))
{
xs.Serialize(sw, this);
}
}
public MySettings ReadFromFile()
{
if (!File.Exists(_settingsFile))
{
FileList = string.Empty;
EmailForFailures = true;
EmailAddress = "replace#this.com";
OutputFile = #"c:\path\to\your\zip";
OutputFile = "ZipFile.zip";
NumberOfBackupsToKeep = 14;
RetainDirectoryStructure = true;
SaveToFile();
}
using (var sr = new StreamReader(_settingsFile))
{
return xs.Deserialize(sr) as MySettings;
}
}
}
}
The save seems to be working well except when I call SaveToFile(), the password is not encrypted. I have put debug points on the property and the conversion is happening, but it is not making it to the file.
Any suggestions?
Serializer calls getter of your property, so it gets decrypted value of the password (#har07)
Change:
get
{
return string.IsNullOrEmpty(_ftp1Password) ? string.Empty : EncryptString.Decrypt(_ftp1Password, "29dk23lh2");
}
To:
get
{
return string.IsNullOrEmpty(_ftp1Password) ? string.Empty : _ftp1Password;
}
and whenever you need this pass in program, call:
string pass = EncryptString.Decrypt(Ftp1Password, "29dk23lh2");
Do the same for Ftp2Password.
You should save the key for en/decrypt as a constant variable (or one other way) that you can refer to it in your en/decypt function, that way it is easier to maintain and avoid mistake.

Categories