I'm having some trouble in my C# program.
After adding 9 items, the programs bugs, when im trying to add the 10th item, it only shows blank spaces.
private void btnConfirmar_Click(object sender, EventArgs e)
{
int NumeroUtente;
if (string.IsNullOrEmpty(txtNomeUtente.Text) || string.IsNullOrEmpty(txtTelefoneUtente.Text) || string.IsNullOrEmpty(txtEmailUtente.Text) || string.IsNullOrEmpty(cbbPulseira.Text))
{
MessageBox.Show("Não podem existir campos vazios!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
// Utentes na Fila de Atendimento
if (ListasFilas.FilaAtendimento.Count == 0)
MessageBox.Show("Erro: Não existem utentes na fila!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
// Utente repetido
if (txtNumeroUtente.Enabled == true && LV_Repetido(Convert.ToInt32(txtNumeroUtente.Text)) == true)
MessageBox.Show("Erro: Utente repetido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
{
// Cria novo utente
if (NovoUtente == true)
{
// Nº Utente
NumeroUtente = Atribui_Num_Utente();
// Adiciona à ListaUtentes
ListasFilas.ListaUtentes.Add(new Utente(NumeroUtente, txtNomeUtente.Text, Convert.ToInt32(txtTelefoneUtente.Text), txtEmailUtente.Text));
//switch (cbbPulseira.Text)
//{
// case "Verde": ListasFilas.FilaAtVerde.Enqueue(NumeroUtente); break;
// case "Amarela": ListasFilas.FilaAtAmarelo.Enqueue(NumeroUtente); break;
// case "Vermelha": ListasFilas.FilaAtVermelho.Enqueue(NumeroUtente); break;
// case "Roxa": ListasFilas.FilaAtRoxo.Enqueue(NumeroUtente); break;
//}
// Atribui número
//NumeroUtente = Atribui_Num_Utente();
}
// Utente existente
else
{
NumeroUtente = Convert.ToInt32(txtNumeroUtente.Text);
}
// Bug encontrado
if(lblSenha.Text == "10")
MessageBox.Show("Bug: Quando chega à senha 10 não mostra os campos na listview!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// Adiciona à listview
int cntItems = lvUtentes.Items.Count;
lvUtentes.Items.Add(lblSenha.Text); // Senha
lvUtentes.Items[cntItems].SubItems.Add(NumeroUtente.ToString()); // Nº
lvUtentes.Items[cntItems].SubItems.Add(txtNomeUtente.Text); // Nome
lvUtentes.Items[cntItems].SubItems.Add(cbbPulseira.Text); // Fila Cor
// Adiciona à Fila Cores
switch (cbbPulseira.Text)
{
case "Verde": ListasFilas.FilaAtVerde.Enqueue(NumeroUtente); break;
case "Amarela": ListasFilas.FilaAtAmarelo.Enqueue(NumeroUtente); break;
case "Vermelha": ListasFilas.FilaAtVermelho.Enqueue(NumeroUtente); break;
case "Roxa": ListasFilas.FilaAtRoxo.Enqueue(NumeroUtente); break;
}
// Próxima senha
lblSenha.Text = (Convert.ToInt32(lblSenha.Text) + 1).ToString();
ListasFilas.FilaAtendimento.Dequeue(); // Retira o próximo utente da fila
Im not seeing where is the problem, when i try to debug, watching it code by code it works, but when add's to the listview, i just got blank spaces.
Thank you.
EDIT: After some tests i figured out that it bugs when:
lblSenha.text passes from 9 to 10.
lblSenha.text passes from 99 to 100.
When lblsenha.text starts at 10 doesnt bug until 99.
Related
I am trying to localize standard identity error messages. I have seen several discussions about this topic. I did manage to create a project and use my own translations and failed on translating standard identity error messages. I decided to create a new project to focus on identity errors. The constructor MultilanguageIdentityErrorDescriber is getting called and returns expected value. When I go to https://localhost:7067/Identity/Account/Register and type "test" into email field standard error "The Email field is not a valid e-mail address." is shown. I appreciate when somebody can guide me into the right directions or send me some links. After a few hours I have decided to ask you guys here. Thanks!
Program.cs
using Localizer.Data;
using Localizer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddErrorDescriber<MultilanguageIdentityErrorDescriber>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
MultilanguageIdentityErrorDescriber.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Localization;
public class MultilanguageIdentityErrorDescriber : IdentityErrorDescriber
{
private readonly IStringLocalizer<SharedResource> _localizer;
public MultilanguageIdentityErrorDescriber(IStringLocalizer<SharedResource> localizer)
{
_localizer = localizer;
// ckecking identityError.Description which returns expected value
var identityError = new IdentityError();
identityError = this.InvalidEmail("email#email.com");
}
public override IdentityError DuplicateEmail(string email)
{
return new IdentityError()
{
Code = nameof(DuplicateEmail),
Description = string.Format(_localizer["Email {0} is already taken."], email)
};
}
public override IdentityError DuplicateUserName(string userName)
{
return new IdentityError()
{
Code = nameof(DuplicateEmail),
Description = string.Format(_localizer["Email {0} is already taken."], userName)
};
}
public override IdentityError InvalidEmail(string email)
{
return new IdentityError
{
Code = nameof(InvalidEmail),
Description = string.Format(_localizer["Email '{email}' is invalid."], email)
};
}
}
I have the same problem in my project and I also couldn't find a way to translate the Identity error messages, so I made a workaround that didn't look pretty but it solve my problem, I made a Class with a method that checks the error code and sets a custom messagem, so I can not only translate but also define my own error messages. I did it to translate to Brazilian portuguese,
here is the code:
public class TranslateIdentityErrors
{
public string TranslateErrorMessage(string codeError)
{
string message = string.Empty;
switch (codeError)
{
case "DefaultError":
message = "Um erro desconhecido ocorreu.";
break;
case "ConcurrencyFailure":
message = "Falha de concorrência otimista, o objeto foi modificado.";
break;
case "InvalidToken":
message = "Token inválido.";
break;
case "LoginAlreadyAssociated":
message = "Já existe um usuário com este login.";
break;
case "InvalidUserName":
message = $"Este login é inválido, um login deve conter apenas letras ou dígitos.";
break;
case "InvalidEmail":
message = "E-mail inválido.";
break;
case "DuplicateUserName":
message = "Este login já está sendo utilizado.";
break;
case "DuplicateEmail":
message = $"Este email já está sendo utilizado.";
break;
case "InvalidRoleName":
message = "Esta permissão é inválida.";
break;
case "DuplicateRoleName":
message = "Esta permissão já está sendo Utilizada";
break;
case "UserAlreadyInRole":
message = "Usuário já possui esta permissão.";
break;
case "UserNotInRole":
message = "Usuário não tem esta permissão.";
break;
case "UserLockoutNotEnabled":
message = "Lockout não está habilitado para este usuário.";
break;
case "UserAlreadyHasPassword":
message = "Usuário já possui uma senha definida.";
break;
case "PasswordMismatch":
message = "Senha incorreta.";
break;
case "PasswordTooShort":
message = "Senha muito curta.";
break;
case "PasswordRequiresNonAlphanumeric":
message = "Senhas devem conter ao menos um caracter não alfanumérico.";
break;
case "PasswordRequiresDigit":
message = "Senhas devem conter ao menos um digito ('0'-'9').";
break;
case "PasswordRequiresLower":
message = "Senhas devem conter ao menos um caracter em caixa baixa ('a'-'z').";
break;
case "PasswordRequiresUpper":
message = "Senhas devem conter ao menos um caracter em caixa alta ('A'-'Z').";
break;
default:
message = "Um erro desconhecido ocorreu.";
break;
}
return message;
}
}
}
To use this method i go to where the error messages are passed to modelstate and change the code from this:
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
to this:
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
TranslateIdentityErrors translateErrors = new();
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, translateErrors.TranslateErrorMessage(error.Code));
}
return Page();
}
I have a button with open a scan (as a modal). When I scan a QRCode i have a display alert with 2 buttons. When I click on "no" I want to return on my scan and not in my page (listPeoplePage).
So I have a button ScanClicked (when I open the scan)
private async Task BtnScanClicked(object sender, EventArgs e)
{
// Ouverture de la page de scan
scanPage = DependencyService.Get<IScanPage>(); // new ZXingScannerPage();
if (scanPage.scannerPage.IsScanning)
return;
scanPage.scannerPage.IsScanning = true;
if (scanPage.scannerPage.Parent == null)
{
// On affiche la page
await Navigation.PushModalAsync(scanPage.scannerPage); //.PushAsync(scanPage.scannerPage);
}
// Le check des résultats
scanPage.scannerPage.OnScanResult += (result) =>
{
// Pour éviter de le faire tant que le client n'a pas validé
if (scanPage.scannerPage.IsScanning == false)
return;
// On stoppe le scan
scanPage.scannerPage.IsScanning = false;
// On retire la page et on montre le résultat
Device.BeginInvokeOnMainThread(async () =>
{
// On essaye de récupérer le code IdA09 si il existe et on appelle le WS
string paramA09 = getParameterByName(result.Text, "IdA09");
if (!string.IsNullOrEmpty(paramA09))
{
//await DisplayAlert("Scanned barcode", paramA09, "OK");
await SendPresenceAck(paramA09,sender,e); //, this.idPrestation);
}
else
{
// Message d'erreur
await this.DisplayAlert("Attention", "Erreur de la validation d'un invité par QR Code.", "Cancel");
}
await Navigation.PopModalAsync(); //.PopAsync();
});
};
}
And there is a method SendPresenceAck when I have scan a QrCode
private async Task SendPresenceAck(string paramA09, object sender, EventArgs e) //, int? idPrestation)
{
int idParticipant;
if (!int.TryParse(paramA09, out idParticipant))
{
//await this.ShowAlert("Attention", "Problème de lecture du QR Code.");
await this.DisplayAlert("Attention", "Problème de lecture du QR Code.", "Yes","No");
return;
}
// On appelle le WS pour signifier la présence
// On passe par validateService
// On prépare la validation de la présence
var validateService = new ValidatePresenceService(this.Token);
// On ajoute la ligne à valider
var validate = validateService.AddNewPresence(idParticipant, this.idPrestation, true);
// On déclenche l'envoi au WS (si besoin)
if (validate != null)
{
// On envoie uniquement en cas de connexion
if (!Global.GetSettingsBool(TypeSettings.IsHorsConnexion))
{
//await validateService.SendAll();
// Attention : si participant déjà enregistré : erreur 403
try
{
await validateService.Send(await validate);
await this.DisplayAlert("OK", "Le billet est validé.", "OK");
}
catch (WebException ex)
{
HttpWebResponse objresponse = ex.Response as HttpWebResponse;
if (objresponse.StatusCode == HttpStatusCode.Forbidden)
{
// 403 : le participant a déjà été enregistré aujourd'hui
// Message d'erreur
await this.DisplayAlert("Attention", "Le billet a déjà été enregistré, le numéro du billet a déjà été scanné auparavant.", "Yes", "No");
return;
}
else if (objresponse.StatusCode == HttpStatusCode.NotFound)
{
// 404 : billet non valide
var alert = await this.DisplayAlert("Attention", "Le billet n'est pas valide.", "Yes","No");
if (alert==true)
return;
else
{
}
}
else if (objresponse.StatusCode == HttpStatusCode.Unauthorized)
{
// 401 : impossible d'identifier le numéro du billet
var alert = await this.DisplayAlert("Attention", "Impossible d'identifier le numéro du billet, veuillez vérifier les informations de celui ci.", "Yes", "No");
if (alert==true)
return;
else
{
Debug.WriteLine(alert);
}
}
}
catch (Exception exception)
{
// Erreur
await this.DisplayAlert("Attention", exception.Message, "Yes", "No");
return;
}
}
else
{
// Hors connexion : on vérifie juste si l'utilisateur n'est pas déjà présent dans la table SQL
// Attention : si pas de prestation : on a le droit d'enregistrer plusieurs fois la présence
// Si il y a une prestation, en revanche, on doit vérifier qu'il n'est pas déjà inscrit
if (validate.Result.IdPrestation.HasValue &&
validateService.IsInscriptionAlreadyRecorded(await validate))
{
// Déjà trouvé : message d'erreur
await this.DisplayAlert("Attention", "Le participant a déjà été enregistré.", "Yes", "No");
return;
}
}
}
else
{
// Pb à l'insertion des données ??
}
//return;
await BtnScanClicked(sender, e);
}
So I want, on my scan to click on a button to return on a scan for scan an other QrCode. A sort of a button "do you want scan an other time?"
Edit: For the moment the only important message is `"await this.DisplayAlert("Attention", "Problème de lecture du QR Code.", "Yes","No");
In English ("Alert", Problem to read QR Code." "Yes", "No");
I try to call again at the end of the SendPresenceAck function but it doesn't work.
For the moment if you answer "yes" or "no" it do nothing. I want to return on scan if you answer "yes" and return to the page if you answer "no".
Might need to see more code, but you are always popping your scanner page at the end of the OnScanResult by calling:
await Navigation.PopModalAsync();
at the end of the OnScanResult method, so no matter what you do in SendPresenceAck when you return from that method, you are popping the modal scanner page.
The non-english (french?) text makes it hard for me to know which alert is asking if the user wants to scan another code, but regardless no matter what they respond, the page will be popped.
Oh, wait, it looks like you have some recursion going on? i.e. BtnScanClicked calls SendPresenceAck and SendPresenceAck calls BtnScanClicked at the end... I'd have to dig though all of your logic to see if this may be an issue, but again that is hard because of the non-english language makes it hard for me to follow code flow after user responses to the multiple alerts.
I tried to check some similar post about this, but I didn't find a proper solution to this, I have the following code
if(dgvOC.Rows.Count == 0)
{
dgvOC.Rows.Add(txtProd.Text, numCant.Value, txtTipo.Text, precioGuardado, precioGuardado * (int)numCant.Value);
}
for (int i = 0; i <= dgvOC.Rows.Count; i++)
{
if (txtProd.Text == dgvOC.Rows[i].Cells[0].Value.ToString())
{
MessageBox.Show("Usted ya ha agregado un producto con el mismo nombre" +
", modifique la cantidad o borre el producto para agregarlo" +
" de nuevo.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtProd.Clear();
txtTipo.Clear();
numCant.Value = 0;
return;
}
dgvOC.Rows.Add(txtProd.Text, numCant.Value, txtTipo.Text, precioGuardado, precioGuardado * (int)numCant.Value);
}
First If is at the start I don't need to compare it to nothing because there is nothing to compare it with so I just add it (My DGV has "AddingRows" property to false)
I use the for to run on all the DGV, then in the 2nd If what I would like to do is compare the textbox to each row that is in the DGV and if it matches a MessageBox will pop out saying that you've added a product with the same name, then it clears some TextBoxes and a numericupdown, then it returns and if it doesn't match the row adds
...my problem is, using this code the first insert into the DGV works fine, but at the second it displays the warning (even if I add a name that doesn't match with the product) and in the 3rd one it adds a row in blank
Thanks for the help
Try something like this
Create a method to verify content of datagridview and if there are rows in.
// Call this in your event.
If(NoRowOrNoDuplicate())
{
dgvOC.Rows.Add(txtProd.Text, numCant.Value, txtTipo.Text, precioGuardado, precioGuardado * (int)numCant.Value);
}
//The method be like
private bool NoRowOrNoDuplicate()
{
// Add condition s here
for (int i = 0; i <= dgvOC.Rows.Count; i++)
{
if (txtProd.Text == dgvOC.Rows[i].Cells[0].Value.ToString())
{
MessageBox.Show("Usted ya ha agregado un producto con el mismo nombre" +
", modifique la cantidad o borre el producto para agregarlo" +
" de nuevo.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtProd.Clear();
txtTipo.Clear();
numCant.Value = 0;
return false;
}
}
Return true;
}
I've a list which each index saves a patient with his id, name, age, (...); I'm currently using this code when searching for one:
foreach (Paciente patient in pacientes)
{
if (patient.id == Convert.ToInt32(txtIDP.Text))
{
txtNomeP.Text = patient.nome;
txtIdadeP.Text = Convert.ToString(patient.idade);
txtMoradaP.Text = patient.morada;
txtContatoP.Text = patient.contato;
txtEmailP.Text = patient.email;
break;
}
else
{
txtNome.Clear();
txtIdade.Clear();
txtMorada.Clear();
txtNumero.Clear();
txtEmail.Clear();
MessageBox.Show(
"Não existe nenhum paciente com esse ID!",
"Error!",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
But I know this is not correct because it will search on the list if it exists and it will automatically show the MessageBox that the id couldn't be found before finding an id. And of course, it will show the error the n times of the array lenght. How can I fix this? Thank you.
Use LINQ like this:
Paciente patient = pacientes.FirstOrDefault(x => x.id == Convert.ToInt32(txtIDP.Text));
if (patient == null)
{
txtNome.Clear();
txtIdade.Clear();
txtMorada.Clear();
txtNumero.Clear();
txtEmail.Clear();
MessageBox.Show("Não existe nenhum paciente com esse ID!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
txtNomeP.Text = patient.nome;
txtIdadeP.Text = Convert.ToString(patient.idade);
txtMoradaP.Text = patient.morada;
txtContatoP.Text = patient.contato;
txtEmailP.Text = patient.email;
}
You can do like this
var found = false;
foreach (Paciente patient in pacientes)
{
if (patient.id == Convert.ToInt32(txtIDP.Text))
{
txtNomeP.Text = patient.nome;
txtIdadeP.Text = Convert.ToString(patient.idade);
txtMoradaP.Text = patient.morada;
txtContatoP.Text = patient.contato;
txtEmailP.Text = patient.email;
found = true;
break;
}
}
if (!found)
{
txtNome.Clear();
txtIdade.Clear();
txtMorada.Clear();
txtNumero.Clear();
txtEmail.Clear();
MessageBox.Show("Não existe nenhum paciente com esse ID!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I have a windows form where a user will be able to download all currency rates for selected date period. I have this now:
for (DateTime d = fromDatePicker.Value.Date; d <= toDatePicker.Value.Date; d.AddDays(1))
{
if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
return;
string url = "http://cbar.az/currencies/" + d.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) + ".xml";
XmlDocument doc = new XmlDocument();
doc.Load(url);
//other stuff
}
URL format is like this depending on the date: http://cbar.az/currencies/15.07.2015.xml And for example if I select two week period, it gets rates for two days, then skips two days and etc. throwing an error not even reaching the end of the period:
remote server returned an error (503) server unavailable
I could guess that this is kind of server side protection against multiple client requests but do not know how to solve this problem.
It does not throw an error if I select period of 2 or 3 days. But here it also may not get rates for all dates as well.
I would appreciate your help. Thank you.
Here is my whole code:
for (DateTime d = fromDatePicker.Value.Date; d <= toDatePicker.Value.Date; d.AddDays(1))
{
if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
continue;
string url = "http://cbar.az/currencies/" + d.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) + ".xml";
#region read rates for the date to the DataTable
XmlDocument doc = new XmlDocument();
doc.Load(url);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//ValCurs/ValType");
DataTable tempRates = new DataTable();
foreach (XmlNode node in nodes)
{
if (node.Attributes["Type"].Value == "Xarici valyutalar")
{
//create temp table and load new rates
tempRates.Clear();
tempRates.Columns.Add("Code");
tempRates.Columns.Add("Nominal");
tempRates.Columns.Add("Name");
tempRates.Columns.Add("Value");
foreach (XmlNode currency in node.ChildNodes)
{
DataRow dr = tempRates.NewRow();
dr["Code"] = currency.Attributes["Code"].Value;
foreach (XmlNode currencyDetailsNode in currency.ChildNodes)
{
dr[currencyDetailsNode.Name] = currencyDetailsNode.InnerText;
}
tempRates.Rows.Add(dr);
}
}
}
#endregion
DAL dal = new DAL();
dal.ClearCurrentRates(d);
//insert new values
foreach (DataRow currencyRow in StaticValues.dataSet.Tables["Currencies"].Rows)
{
if (currencyRow["Code"].ToString() == "AZN")
{
#region Insert the row for AZN
try
{
SqlParameter[] pars = new SqlParameter[3];
pars[0] = new SqlParameter("#Date", SqlDbType.Date);
pars[0].Value = d.ToShortDateString();
pars[1] = new SqlParameter("#CurrencyID", SqlDbType.Int);
pars[1].Value = currencyRow["ID"].ToString();
pars[2] = new SqlParameter("#Rate", SqlDbType.Decimal);
pars[2].Value = 1.0000;
dal.InsertData("CurrencyRates", pars);
}
catch (Exception ex)
{
StaticValues.WriteEventLogXML(ex, this.Text);
switch (StaticValues.user.Language)
{
case "English":
MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "Russian":
MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "Azeri":
MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
default:
break;
}
}
#endregion
continue;
}
foreach (DataRow tempRow in tempRates.Rows)
{
if (tempRow["Code"].ToString() == currencyRow["Code"].ToString())
{
#region Insert the row
try
{
SqlParameter[] pars = new SqlParameter[3];
pars[0] = new SqlParameter("#Date", SqlDbType.Date);
pars[0].Value = d.ToShortDateString();
pars[1] = new SqlParameter("#CurrencyID", SqlDbType.Int);
pars[1].Value = currencyRow["ID"].ToString();
pars[2] = new SqlParameter("#Rate", SqlDbType.Decimal);
pars[2].Value = decimal.Parse(tempRow["Value"].ToString());
dal.InsertData("CurrencyRates", pars);
break;
}
catch (Exception ex)
{
StaticValues.WriteEventLogXML(ex, this.Text);
switch (StaticValues.user.Language)
{
case "English":
MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "Russian":
MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "Azeri":
MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
default:
break;
}
break;
}
#endregion
}
}
}
d = d.AddDays(1);
Thread.Sleep(1000);
}
Your stuff is completely wrong.
method AddDays(x) don't update your "d" variable, so construction of
for (DateTime d = fromDatePicker.Value.Date; d <= toDatePicker.Value.Date; d.AddDays(1))
produces endless loop
2.
if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
return;
exits the loop completely.
it seems, that the remote server has a some kind of performance problem with many requests at a short time. It can be solved by some pause between requests (for example: Thread.Sleep(2000) - two seconds pause)
So, your code would look like this:
for (DateTime d = fromDatePicker.Value.Date; d <= toDatePicker.Value.Date; d = d.AddDays(1))
{
if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
continue;
string url = "http://cbar.az/currencies/" + d.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) + ".xml";
XmlDocument doc = new XmlDocument();
doc.Load(url);
Thread.Sleep(2000);
}