Skip to main content

Posts

Send email to specific location using SmtpClient

 Many times, we need to send email notifications in our application. However, during the local development stage, we may not have access to SMTP server, therefore the email function would throw errors. The easiest way to solve this problem is to use the built-in function provided by SmtpClient in C# to save the email to specified folder location. using (var smtp = new SmtpClient(_host, _port)) {     using (var message = new MailMessage())     {         message.Subject = "this is a test";         message.Body = "<p>Test email body</p>";         message.IsBodyHtml = true;         message.To.Add(new MailAddress("tester@test.com", "tester"));         message.From = new MailAddress("tester1@test.com", tester1); #if DEBUG         smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;         const string em...
Recent posts
Mock Entity Framework FindAsync() method In entity framework, FindAsync() method has signature of:         public virtual ValueTask<TEntity> FindAsync([CanBeNullAttribute] params object[] keyValues); Assume we have a method in DB repository that looks for brand information by brand ID:            public async Task<Brand> GetBrandbyIdAsync(int brandId)         {             var brand = await _context.Brands.FindAsync(brandId).ConfigureAwait(false);             return brand;         } In order to make this method work, we need to mock the FindAsync call inside the method:             var dbSetMock =  CreateDbSetMock(brands );             dbSetMock.Setup(m => m.FindAsync(It.IsAny<object[]>())).Returns((object[] r) =>           ...

FormsAuthentication.Encrypt returns null

There are several reason that the FormsAuthentication.Encrypt() returns null:              FormsAuthenticationTicket  ticket = new  FormsAuthenticationTicket (                         1, // version                         identity.Name, // Name                          DateTime .Now, // issue date,                          DateTime .Now.AddDays(1), // expiration date, created above                          false , // persistent or not                         jsSerializer.Serialize(identity) // User data             );     ...

Disable html5 mode in angular for individual link

In Angular, if we enable the html5 mode,    all href's on the page w ill try to use the html5mode and use the route provider to determine which view should be loaded. In reality, we may need to enable html5 mode on the page but for certain links we want the browser to navigate to the link directly. In HTML5 mode, there are three situations in which the A tag is not rewritten: from the  angular docs Links that contain a  target  attribute. Example:  <a href="/ext/link?a=b" target="_self">link</a> Absolute links that point to a different domain  Example: <a href="http://angularjs.org/">link</a> Links starting with '/' that lead to a different base path when  base  is defined  Example: <a href="/not-my-base/link">link</a>

nlog in netcore does not output Trace, Debug and Information log

When using nlog in .netcore application, I found out a very strange thing: When using VisualStudio to debug the application, the nlog works perfect. I set the minloglevel in nlog.config to Debug: <rules> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <!--All logs, including from Microsoft--> <!--<logger name="*" minlevel="Warn" writeTo="console" /> --> <logger name="*" minlevel="Debug" writeTo="applog" /> </rules> However, when deployed to server, the log only shows level equals or greater than Warning. I have also set the minlevel in program.cs file and it is still output Trace, Debug and Information log: .ConfigureLogging((host, builder) => { host.HostingEnvironment.ConfigureNLog("nlog.config"); builder.Set...

HttpClient BaseAddress

When using HttpClient class in .NET, I found out when assigning the BaseAddress to HttpClient, the BaseAddress must end with "/". Otherwise it would get 404 error when calling the get or post method. using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("Setting"); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { ilog.Error(string.Format("GetGlobalSetting error - StatusCode: {0}; ReasonPhrase: {1} ", response.StatusCode.ToString(), response.ReasonPhrase??"")); throw new Exception(string.Format("Error getting Global settings - StatusCode: {0}; ReasonPhrase: {1}", response.StatusCode.ToString(), response.ReasonPhrase ?? ...

Create aspnet core 2.0 Identity entity framework Sql Server database schema

When running aspnet core 2.0 identity application, I have encountered the error "invalid object AspNetUsers", which means the database table is not created. In order to create database schema required by aspnet core 2.o identity framework, following these steps: 1. In your project, create data context related to identity: public class UserDbContext : IdentityDbContext < IdentityUser > { public UserDbContext (DbContextOptions< UserDbContext > options) : base (options) { } protected override void OnModelCreating( ModelBuilder builder) { base .OnModelCreating(builder); } } 2. In Startup.cs file, configure the Identity store and UserDbContext entity framework: var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value; var issuer = Configuration.GetSection("JWTSettings:Issuer").Value; var audience = Configuration.GetSection("JWTSet...