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

Define multiple Angular apps in MVC layout and content page

Here is the situation I encountered: I have a MVC application, in layout.cshtml file, I have a header logo and footer logo and I want the logos to be dynamic based on the client information passed in. Here is my layout page: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>For your security - Mercer.MFA.SharedUI</title> <base href="~/" /> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /> <link rel="stylesheet" href="~/css/magic-check.css" /> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> <div class="container"> <header ng-app=" headerApp " ng-controller=" headerCtrl "> <div class="row"> <div class="col-md-6 header_left...

MVC Render Partial View to HTML inside controller

We know that we can use @Html.Partial("PartialViewName") to render partial view in view. However, sometimes we need to render the partial view to HTML inside the controller. For example, I have a ChoiceResultsPartial which displays the choices that user has made. I also want to send the results to the email address the user provides. The best way to achieve this is to use the same way as @Html.Partial() to get the HTML and send the HTML as email body. In order to achieve this, we can use following code:         public string RenderViewToString( string viewName, object model, TempDataDictionary tempData)         {             if ( string .IsNullOrEmpty(viewName))                 viewName = this .ControllerContext.RouteData.GetRequiredString( "action" );             var viewData = new ViewDataDictionary(model);     ...

Secure cookie in load balancer environment

To secure cookie in an environment without load balancer, simply add or configure httpCookie element in web.config file under <system.web> <httpCookies requireSSL="true" httpOnlyCookies="true"/> For form authentication cookie, simply add requireSSL="true" in <forms> element <forms name="authCookie" loginUrl="login.aspx" timeout="20" requireSSL="true"  />  However, if there are load balancer exist and the certificate is deployed on load balancer, the actual web site is only http, configuring as above will not work. In order for it to work, you have to keep the httpCookie configuration the same as above, but change the requreSSL attribute in <forms> element to false. In addition, in your code that creates the authentication cookie, make sure not set the "Secured" property (You can not set it to true nor false).

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

When I try to connect to a remote WCF service which uses basicHttpBinding and transport security, I got this error message. It turns out that the reason of the error is the root certificate that issues the certificate for the WCF site is not in the calling machines "Trusted Root Certification Authority" store. By obtaining the root public certificate and import it into calling machines "Trusted Root Certification Authority" store, the problem solved. It is easy to obtain root public certificate using just the browser. Take Chrome as an example: Open Chrome and type the secured URL into the address bar, for example, https://www.google.ca/ In the browser address bar, click the lock icon in front the address. In the pop-up window, click the "Details" link after the sentence "Your connection to this site is private" Click the "View Certificate" button on the right panel In the "Certificate" dialog window, click "...

MVC partial view not getting new model value after postback

It takes me quite a long time to figure out what the issue is and how to fix it. Here is a example to explain the problem. Say you have a view which include a partial view called "RandomNumber", which takes a RandomNumberModel object as model. Each time the page refresh or post back, the RandomNumberModel object will generate a new random number. public class RandomNumberModel { public static int Generate() { return new Random().Next(); } } Partial View: @model RandomNumberMode <p>         @Html.TextBoxFor(m => RandomNumber.new { autocomplete = "off" }) </p> It turns out after the postback, the values of all the inputs binding using HtmlHelper class are from ModelState instead of from Model. The value changes in model will not be shown in the rendered view. The solution for this is easy: 1. Using the plain html tag for data display instead of using Html helper <input type="text" name="RandomNumber" id="Ran...

.NET - CryptographicException 'Keyset does not exist'

When you use the certificate to do signing and encryption, you may encounter this exception: CryptographicException 'Keyset does not exist' One possibility of this error is that the caller has not read permission of the private certificate using. By granting the read permission to the private certificate, the problem is solved. Following these steps to grant read permission to private certificate: In Windows -> Run, type mmc to open Microsoft Management Console In MMC, click File -> Add/Remove Snap-in... Choose "Certificates", then click "Add"  In the popup window, choose "Computer account" and then click "Next" Choose "Local computer" and click "Finish" to close popup window Click "OK" to close "Add or Remove Snap-ins" dialog. Go to "Personal"  certificates store on the left navigation Found the certificate on the right panel and right click it and choose "All T...

Manage IIS 7 remotely using PowerShell and AppCmd

We can use  Windows PowerShell remoting features  to manage IIS 7 websites remotely.  Currently, remoting is supported on Windows Vista with Service Pack 1 or later, Windows 7, Windows Server 2008, and Windows Server 2008 Release 2.  Start Windows PowerShell as an administrator by right-clicking the Windows PowerShell shortcut and selecting Run As Administrator .  Enable PowerShell Remoting with Enable-PSRemoting -Force Starting a Remote Session using:  Enter-PSSession -ComputerName <COMPUTER> -Credential <USER> Now the PowerShell connected to the remote server. Any commands issued with work against the remote server. We can use the Appcmd.exe command line tool to manage remote server just as what we do locally. For example, to add an application pool: c:\windows\system32\inetsrv\appcmd add apppool /name:"Contoso" /managedPipelineMode:Integrated /managedRuntimeVersion:"v4.0" /enable32BitAppOnWin64:true To change application p...

Packing, Packaging and Indirect materials treatment in various free trades

Definition of Packing, Packaging and Indirect Material Packaging materials and containers  means materials and containers in which a good is packaged for retail sale Packing materials and containers  means materials and containers that are used to protect a good during transportation, but does not include packaging materials and containers; Indirect material   means a good used in the production, testing or inspection of a good but not physically incorporated into the good, or a good used in the maintenance of buildings or the operation of equipment associated with the production of a good, and includes a)       fuel and energy, b)       tools, dies and moulds, c)        spare parts and materials used in the maintenance of equipment and buildings, d)       lubricants, greases, compounding materials and other materials used in production or used to operate ...

log4net file appender file location

In log4net, we can use the FileAppender to log information into text files. There are two ways to specify the file: 1. Specify the file name in absolutely path. For example: <log4net> <appender name = "FileAppender" type = "log4net.Appender.FileAppender" > <file value = "c:\logs\log-file.txt" /> <appendToFile value = "true" /> <lockingModel type = "log4net.Appender.FileAppender+MinimalLock" /> <layout type = "log4net.Layout.PatternLayout" > <conversionPattern value = "%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> </log4net> Obviously, the file will be created in c:\logs\log-file.txt 2. Specify the file name in relative path. For example: <log4net> <appender name = "FileAppender" type = "log4net.Appender.FileAppender" ...

ComponentSpace SAML message expired issue

When I used ComponentSpace SAML2 API to process the SAML message, I got the messsage expired error. The code I used to check if the message is expired or not is: if (!samlAssertion.Conditions.IsWithinTimePeriod()) {     // Message expired } It seems the IsWithinTimePeriod() function uses the local time to compare with NotBefore and NotOnOrAfter attributes in the SAML message. Since SAML message uses UTC time for all the datetime related attributes, the  IsWithinTimePeriod() function often returns false because of the big difference between local time and UTC time. In order to check if the message is expired or not, we cannot use the IsWithinTimePeriod() function. I used following code to check the exipiration: if (!(DateTime.Now.ToUniversalTime() > samlAssertion.Conditions.NotBefore && DateTime.Now.ToUniversalTime() < samlAssertion.Conditions.NotOnOrAfter)) {      // Message expired }

X509Certificate2: The system cannot find the file specified.

When I use the new X509Certificate2(fileName, password, X509KeyStorageFlags.DefaultKeySet) to create certificate from certificate file containing private key in my web application, I got following error message: System . Security . Cryptography . CryptographicException : The system cannot find the file specified . at System . Security . Cryptography . CryptographicException . ThrowCryptogaphicException ( Int32 hr ) at System . Security . Cryptography . X509Certificates . X509Utils . _LoadCertFromBlob ( Byte [] rawData , IntPtr password , UInt32 dwFlags , Boolean persistKeySet , SafeCertContextHandle & pCertCtx ) at System . Security . Cryptography . X509Certificates . X509Certificate . LoadCertificateFromBlob ( Byte [] rawData , Object password , X509KeyStorageFlags keyStorageFlags ) at System . Security . Cryptography . X509Certificates . X509Certificate2 .. ctor ( Byte [] rawData , String password , X509KeyStorageFlags keyStorageFlags ) In orde...

Post dictionary parameters or IEnumerable parameters to MVC controller

I found a very good artical about how to pass the dictionary or IEnumerable<T> parameters to MVC controller . http://www.hanselman.com/blog/ ASPNETWireFormatForModelBindingToArraysListsCollectionsDicti onaries.aspx So if your action requires array of objects, say Person: public ActionResult ProcessAction(Person[] people) Then your MVC view HTML should look like: < input type = "text" name = "people[0].FirstName" value = "George" /> < input type = "text" name = "people[0].LastName" value = "Washington" /> < input type = "text" name = "people[1].FirstName" value = "Abraham" /> < input type = "text" name = "people[1].LastName" value = "Lincoln" /> < input type = "text" name = "people[3].FirstName" value = "Thomas" /> < input type = "text" name = ...