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
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.
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
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.