My program does not save or load infomation in or from data base - c#-3.0

I created a database and three pages for a register & login form & the third is for a lottery between my usernames .
I don't have any errors but the whole thing is not using the data base,
it does not save or load from database .
This is my register form:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _2 : System.Web.UI.Page
{
protected void btnRegister_Click(object sender, EventArgs e)
{
string strcon = "Data Source=.;uid=sa;pwd=123;database=Login_Register";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("strlogin", con);
com.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", txtUserName.Text.ToString());
SqlParameter p2 = new SqlParameter("email", txtEmail.Text.ToString());
SqlParameter p3 = new SqlParameter("password", txtpassword.Text.ToString());
com.Parameters.Add(p1);
com.Parameters.Add(p2);
com.Parameters.Add(p3);
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
con.Close();
com.ExecuteNonQuery();
}
private SqlDbType ToString(object text)
{
throw new NotImplementedException();
}
}
public class Label4
{
internal static object Text;
internal static bool Visible;
}
public class txtUserName
{
internal static object Text;
internal static bool Visible;
}
public class txtEmail
{
internal static object Text;
internal static bool Visible;
}
public class txtpassword
{
internal static object Text;
internal static bool Visible;
}

Look at your code
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
con.Close();
com.ExecuteNonQuery();
You are opening the connection, closing it and then executing.
it should be:
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
com.ExecuteNonQuery();
con.Close();//close connection after execute.
also it would be a good idea to add try/catch block around it - in case connection cannot be opened

Related

How to write NUnit test for dependency injection service .net core

I have a service class with some injected services. It's dealing with my Azure storage requests. I need to write NUnit tests for that class.
I'm new to NUnit and I'm struggling with making the object of that my AzureService.cs
Below AzureService.cs. I have used some injected services
using System;
using System.Linq;
using System.Threading.Tasks;
using JohnMorris.Plugin.Image.Upload.Azure.Interfaces;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain.Media;
using Nop.Services.Logging;
namespace JohnMorris.Plugin.Image.Upload.Azure.Services
{
public class AzureService : IAzureService
{
#region Constants
private const string THUMB_EXISTS_KEY = "Nop.azure.thumb.exists-{0}";
private const string THUMBS_PATTERN_KEY = "Nop.azure.thumb";
#endregion
#region Fields
private readonly ILogger _logger;
private static CloudBlobContainer _container;
private readonly IStaticCacheManager _cacheManager;
private readonly MediaSettings _mediaSettings;
private readonly NopConfig _config;
#endregion
#region
public AzureService(IStaticCacheManager cacheManager, MediaSettings mediaSettings, NopConfig config, ILogger logger)
{
this._cacheManager = cacheManager;
this._mediaSettings = mediaSettings;
this._config = config;
this._logger = logger;
}
#endregion
#region Utilities
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
public virtual async Task DeleteFileAsync(string prefix)
{
try
{
BlobContinuationToken continuationToken = null;
do
{
var resultSegment = await _container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.All, null, continuationToken, null, null);
await Task.WhenAll(resultSegment.Results.Select(blobItem => ((CloudBlockBlob)blobItem).DeleteAsync()));
//get the continuation token.
continuationToken = resultSegment.ContinuationToken;
}
while (continuationToken != null);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file delete error", e);
}
}
public virtual async Task<bool> CheckFileExistsAsync(string filePath)
{
try
{
var key = string.Format(THUMB_EXISTS_KEY, filePath);
return await _cacheManager.Get(key, async () =>
{
//GetBlockBlobReference doesn't need to be async since it doesn't contact the server yet
var blockBlob = _container.GetBlockBlobReference(filePath);
return await blockBlob.ExistsAsync();
});
}
catch { return false; }
}
public virtual async Task SaveFileAsync(string filePath, string mimeType, byte[] binary)
{
try
{
var blockBlob = _container.GetBlockBlobReference(filePath);
if (!string.IsNullOrEmpty(mimeType))
blockBlob.Properties.ContentType = mimeType;
if (!string.IsNullOrEmpty(_mediaSettings.AzureCacheControlHeader))
blockBlob.Properties.CacheControl = _mediaSettings.AzureCacheControlHeader;
await blockBlob.UploadFromByteArrayAsync(binary, 0, binary.Length);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file upload error", e);
}
}
public virtual byte[] LoadFileFromAzure(string filePath)
{
try
{
var blob = _container.GetBlockBlobReference(filePath);
if (blob.ExistsAsync().GetAwaiter().GetResult())
{
blob.FetchAttributesAsync().GetAwaiter().GetResult();
var bytes = new byte[blob.Properties.Length];
blob.DownloadToByteArrayAsync(bytes, 0).GetAwaiter().GetResult();
return bytes;
}
}
catch (Exception)
{
}
return new byte[0];
}
#endregion
}
}
This is my test class below, I need to create new AzureService(); from my service class. But in my AzureService constructor, I'm injecting some service
using JohnMorris.Plugin.Image.Upload.Azure.Services;
using Nop.Core.Caching;
using Nop.Core.Domain.Media;
using Nop.Services.Tests;
using NUnit.Framework;
namespace JohnMorris.Plugin.Image.Upload.Azure.Test
{
public class AzureServiceTest
{
private AzureService _azureService;
[SetUp]
public void Setup()
{
_azureService = new AzureService( cacheManager, mediaSettings, config, logger);
}
[Test]
public void App_settings_has_azure_connection_details()
{
var url= _azureService.GetAzureStorageUrl();
Assert.IsNotNull(url);
Assert.IsNotEmpty(url);
}
[Test]
public void Check_File_Exists_Async_test(){
//To Do
}
[Test]
public void Save_File_Async_Test()(){
//To Do
}
[Test]
public void Load_File_From_Azure_Test(){
//To Do
}
}
}
Question is, what exactly do you want to test? If you want to test if NopConfig is properly reading values from AppSettings, then you do not have to test AzureService at all.
If you want to test that GetAzureStorageUrl method is working correctly, then you should mock your NopConfig dependency and focus on testing only AzureService methods like this:
using Moq;
using Nop.Core.Configuration;
using NUnit.Framework;
namespace NopTest
{
public class AzureService
{
private readonly NopConfig _config;
public AzureService(NopConfig config)
{
_config = config;
}
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
}
[TestFixture]
public class NopTest
{
[Test]
public void GetStorageUrlTest()
{
Mock<NopConfig> nopConfigMock = new Mock<NopConfig>();
nopConfigMock.Setup(x => x.AzureBlobStorageEndPoint).Returns("https://www.example.com/");
nopConfigMock.Setup(x => x.AzureBlobStorageContainerName).Returns("containername");
AzureService azureService = new AzureService(nopConfigMock.Object);
string azureStorageUrl = azureService.GetAzureStorageUrl();
Assert.AreEqual("https://www.example.com/containername", azureStorageUrl);
}
}
}

Mock DBContext class which uses a stored procedure and SqlAdapter to fetch details using Nunit and Moq

I need to Mock a DBContext class which in turn uses a Stored procedure & SqlAdapter to fetch result using Nunit and Moq . There is Unity Resolver IOC involved which takes care of DI .
---Web API Controller Class----
IEmployee _employee;
public Controller(IEmployee employee)
{
_employee = employee;
}
Route[employeedetails/get]
[HttpPost]
public EmployeeEntity Get(ParameterObject param)
{
return _employee.Get(param);
}
----------------------------------
Employee implements IEmployee :
--- DataAccess Class which implements the interface----
public class Employee : IEmployee
{
public EmployeeContext _repository;
public Employee(EmployeeContext repository)
{
_repository = repository;
}
public EmployeeEntity Get(ParameterObject param)
{
DataSet dataset= new DataSet();
EmployeeEntity response = new EmployeeEntity();
using(SqlConnection connection =
(SqlConnection)_repository.Database.Connection)
{
connection.Open()
SqlCommand command = connection.CreateCommand();
command.CommandText = "spGetEmployee";
command.CommandType = CommandType.StoredProcedure;
-- Add Parameters using param object --
using(SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(dataset);
response = MapReponse(dataset);
}
connection.Close();
}
return response;
}
}
-------------------------------------
--------DBContext class -----------
public partial class EmployeeContext : DbContext
{
public EmployeeContext() : base ("name=EmployeeContext")
{
}
}
So I need to Mock the DB functionality using NUnit and Moq .. My code using Unity resolver . Please help I tried many ways . Nothing si working for me ....

Database.CompatibleWithModel n EF7 ( detecting the need to run migrations)

In EF6 I was able to check whether the database needed upgrading and get an OK from the (power) user
I made use of
dbContext.Database.CompatibleWithModel and db.RunMigrations()
I can't find these methods in EF7. Can I still do this in EF7?
So far I have the following
namespace Console4Migration
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json");
var config = builder.Build();
var connectionString = config.GetConnectionString("ApplicationDatabase");
var optionsBuilder = new DbContextOptionsBuilder<ApiDbContext>();
optionsBuilder.UseSqlServer(connectionString);
var options = new DbContextOptions<ApiDbContext>();
var db = new ApiDbContext(options);
var numUsers = db.Users.Count();
Console.WriteLine("finished opening the database");
}
}
}
and
public class ApiDbContext : IdentityDbContext<ApplicationUser>
{
public ApiDbContext(DbContextOptions<ApiDbContext> options)
: base(options)
{
}
}
public class ApplicationUser : IdentityUser
{
}
I was able to create a partial solution as shown here that detects the need to run migrations and optionally runs them.
However it does not check for whether the model is compatible which I would still like to do.
using System;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MyApi.Entities;
namespace Console4Migration
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json");
var config = builder.Build();
var connectionString = config.GetConnectionString("MyDatabase");
var optionsBuilder = new DbContextOptionsBuilder<ApiDbContext>();
optionsBuilder.UseSqlServer(connectionString);
var options = optionsBuilder.Options;
var db = new ApiDbContext(options);
if (EFFunctions.HasOutstandingMigrations(db))
{
var sb = new StringBuilder();
sb.AppendLine("Upgrades are needed. Enter Y to upgrade");
sb.AppendLine(EFFunctions.GetUpgradesDescription(db));
Console.WriteLine(sb);
var answer = Console.ReadKey();
if (answer.Key != ConsoleKey.Y)
{
Console.WriteLine("No upgrade performed");
Console.ReadKey();
return;
}
db.Database.Migrate();
Console.WriteLine("Migration performed");
Console.ReadKey();
return;
}
Console.WriteLine("There are no migrations outstanding");
Console.ReadKey();
}
}
}
and
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
public static class EFFunctions
{
public static string GetUpgradesDescription(DbContext db)
{
var migrations = db.Database.GetPendingMigrations();
var sb = new StringBuilder();
var enumerable = migrations as string[] ?? migrations.ToArray();
if (!enumerable.Any()) return sb.ToString();
foreach (var migration in enumerable)
{
sb.AppendLine(migration);
}
return sb.ToString();
}
public static bool HasOutstandingMigrations(DbContext db)
{
return GetUpgradesDescription(db).Length == 0;
}
}

Unable to Send email via .Net core 2.0

I wrote the following and was running perfectly. But after updates stops running, I have already setup a mail server I had not any problem.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SportsStore.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Claims;
using System.Threading.Tasks;
namespace SportsStore.Helper
{
public class Email: IEmail
{
private SmtpClient Client;
private string MessageBody, Subject, UserEmail;
private MailAddress MailFrom, MailTo;
private MailMessage Message;
public Email(IServiceProvider service)
{
this.Client = new SmtpClient("localhost");
this.Client.Port = 25;
this.Client.UseDefaultCredentials = false;
this.Client.Credentials = new NetworkCredential("postmaster", "xxxxxxx!");
this.MailFrom = new MailAddress("xxxxx.xxxxx#yandex.com");
this.UserEmail = service.GetRequiredService<IHttpContextAccessor>().HttpContext.User.Identity.Name;
this.MailTo = new MailAddress(UserEmail);
}
public void SetMessageBody(string orderName)
{
MessageBody = String.Format("The order with id {0} has been placed and is ready to ship", orderName);
}
public string GetMessageBody()
{
return MessageBody;
}
public void SetSubject()
{
Subject = "Order Details";
}
public string GetSubject()
{
return Subject;
}
public bool SendMessageAsync()
{
this.Message = new MailMessage(this.MailFrom.ToString(), this.MailTo.ToString(), this.GetSubject(), this.GetMessageBody());
if (this.Client.SendMailAsync(this.Message).IsCompletedSuccessfully)
{
return true;
}
return false;
}
}
}
The Client.SendEmailAsync() now return false.
Any suggestion?Please give a quick answer or I have to jump to nuget packages for a package to install.
The method SendMailAsync is Async in your Send Mail in your application.
What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0

C# - duplicated output for start date in date range iteration

I am trying to make simple app and got stuck. User chooses start date from date picker1 28.01.2015 and end date picker2 29.01.2015 then marks what he/she wants via checkboxes and presses button. The output in console should look similar to this depending on what is marked.
tar zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log`
but instead date picked as start date is returned twice in console and I have no idea what is wrong:
zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log
Code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;
using System.Configuration;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
}
...
private void button1_Click(object sender, EventArgs e)
{
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
GlobalMethods dateIterator = new GlobalMethods();
dateIterator.Iterator();
GlobalVariables.comminit = null;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
GlobalVariables.cLM = true;
}
else if (!checkBox1.Checked)
{
GlobalVariables.cLM = false;
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateStart = dateTimePicker1.Value;
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateEnd = dateTimePicker2.Value;
//string endDate = dateTimePicker2.Value.ToString("yyyyMMdd");
}
}
public static class GlobalVariables
{
// Log variables below
public static Boolean mLM;
public static Boolean cLM;
public static Boolean hLM;
public static Boolean pLM;
public static Boolean prLM;
public static Boolean compressMarked = true;
public static String iterate;
public static String comminit;
public static String pH;
public static String pP;
public static String pC;
public static String ppP;
public static String pM;
// Time variables below
public static DateTime dateStart = DateTime.Now;
public static DateTime dateEnd = DateTime.Now;
}
public class Instructions
{
public static String hLl()
{
if (GlobalVariables.compressMarked)
{
return "tar zxcvf " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;";
}
else { return "wget " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;"; }
}
...
public static String commandsBath()
{
if (GlobalVariables.mLM == true)
{
GlobalVariables.comminit += mLl();
}
if (GlobalVariables.cLM == true)
{
GlobalVariables.comminit += cLl();
}
if (GlobalVariables.hLM == true)
{
GlobalVariables.comminit += hLl();
}
if (GlobalVariables.pLM == true)
{
GlobalVariables.comminit += pLl();
}
if (GlobalVariables.prLM == true)
{
GlobalVariables.comminit += pLlp();
}
return GlobalVariables.comminit;
}
}
public class GlobalMethods
{
public void Iterator()
{
for (DateTime i = GlobalVariables.dateStart; i <= GlobalVariables.dateEnd; i = i.AddDays(1))
{
string iterated = i.ToString("yyyyMMdd");
GlobalVariables.iterate = iterated;
}
}
public void ConfigRead()
{
...
}
public void ConfigWrite()
{
...
}
}
}
Hopefully someone can help.
Never mind, found the solution. Instead of using += and add results of if statements it is better to use String builder like below. This way it works correctly and is more simple.
var sb = new StringBuilder();
if (GlobalVariables.mLM == true) sb.Append(mLl());
if (GlobalVariables.cLM == true) sb.Append(cLl());
...
return GlobalVariables.comminit = sb.ToString();