Wednesday, December 7, 2016

Append TimeStamp to a File Name C#

DateTime.Now.ToString("yyyyMMddHHmmssfff")
string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}",DateTime.Now);
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
With Extension Method
Usage:
string result = "myfile.txt".AppendTimeStamp();
//test20160604234625642.txt
public static class MyExtensions
{
    public static string AppendTimeStamp(this string fileName)
    {
        return string.Concat(
            Path.GetFileNameWithoutExtension(fileName),
            DateTime.Now.ToString("yyyyMMddHHmmssfff"),
            Path.GetExtension(fileName)
            );
    }
}

Monday, July 25, 2016

FREE Technical Microsoft eBooks


Microsoft Director of Sales Excellence - Eric Ligman Giving Away MILLIONS of FREE Microsoft eBooks again! Including: Windows 10, Office 365, Office 2016, Power BI, Azure, Windows 8.1, Office 2013, SharePoint 2016, SharePoint 2013, Dynamics CRM, PowerShell, Exchange Server, System Center, Cloud, SQL Server and more


Link 1

Link2






Built-In Logging In .NET Core

Introduction
For an application, logging is very important to keep track of that application and keep it error-free. In .NET Core, we don't need any third party logging; instead, we can use built-in logging whenever we want. This is very efficient in terms of code and performance.
Let’s start.
Create a new .NET Core application and name it.



 Step 1: Go to Package mManager View-->Other Windows--> Package manager Console  -->
 Install-Package Microsoft.Extensions.Logging



Add Logging

Once  the extension's installed, we can add logging by adding ILogger<T> (custom logging) or ILoggerFactory. If we want to use ILoggerFactory, then we must create it using CreateLogger, to use logging add logging services under ConfigureServices. Moreover, we can use built-in logging with the other loggings (like Nlog) with very minimal code. 
  1. services.AddLogging();  
Startup.cs 
  1. public class Startup  
  2.     {  
  3.         public Startup(IHostingEnvironment env)  
  4.         {  
  5.             var builder = new ConfigurationBuilder()  
  6.                 .SetBasePath(env.ContentRootPath)  
  7.                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  8.                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)  
  9.                 .AddEnvironmentVariables();  
  10.             Configuration = builder.Build();  
  11.         }  
  12.   
  13.         public IConfigurationRoot Configuration { get; }  
  14.   
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         public void ConfigureServices(IServiceCollection services)  
  17.         {  
  18.             // Add framework services.  
  19.             services.AddMvc();  
  20.             services.AddLogging();  
  21.         }  
  22.   
  23.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  24.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  25.         {  
  26.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  27.             loggerFactory.AddDebug();  
  28.   
  29.             if (env.IsDevelopment())  
  30.             {  
  31.                 app.UseDeveloperExceptionPage();  
  32.                 app.UseBrowserLink();  
  33.             }  
  34.             else  
  35.             {  
  36.                 app.UseExceptionHandler("/Home/Error");  
  37.             }  
  38.   
  39.             app.UseStaticFiles();  
  40.   
  41.             app.UseMvc(routes =>  
  42.             {  
  43.                 routes.MapRoute(  
  44.                     name: "default",  
  45.                     template: "{controller=Home}/{action=Index}/{id?}");  
  46.             });  
  47.         }  
  48.     }  
ILoggerFactory: We can use  ILoggerFactory. For this, we must use CreateLogger. 
  1. _logger = Mylogger.CreateLogger(typeof(HomeController));  
HomeController.cs 
  1. public class HomeController : Controller  
  2.     {  
  3.         private ILogger _logger;  
  4.   
  5.         public HomeController(ILoggerFactory Mylogger)  
  6.         {  
  7.             _logger = Mylogger.CreateLogger(typeof(HomeController));  
  8.         }  
  9.   
  10.         public IActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.   
  15.         public IActionResult About()  
  16.         {  
  17.             try  
  18.             {  
  19.                 ViewData["Message"] = "Your application description page.";  
  20.                 _logger.LogInformation("About Page has been Accessed");  
  21.                 return View();  
  22.             }  
  23.             catch (System.Exception ex)  
  24.             {  
  25.                 _logger.LogError("About: " + ex.Message);  
  26.                 throw;  
  27.             }  
  28.         }  
  29.   
  30.         public IActionResult Contact()  
  31.         {  
  32.             try  
  33.             {  
  34.                 ViewData["Message"] = "Your contact page.";  
  35.                 _logger.LogInformation("Contact Page has been Accessed");  
  36.                 return View();  
  37.             }  
  38.             catch (System.Exception ex)  
  39.             {  
  40.                 _logger.LogError("Contact: " + ex.Message);  
  41.                 throw;  
  42.             }  
  43.         }  
  44.   
  45.         public IActionResult Error()  
  46.         {  
  47.             return View();  
  48.         }  
  49.     }  
Run and Test



LogLevel: We can add logging level by adding the level we want in appsettings.json.
  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Application failure or crashes                   
Summary
We can use built-in logging frameworks and separate our application from logger implementation so that we can use the same framework later for other logging providers.

Visual Studio Dev Essentials for Developers



Greetings,
                 You can get everything you need to build an application in all platforms.




Visual Studio - Microsoft Developer Tools

Everything you need to build and deploy your app on any platform – for FREE
Read this on visualstudio.com >

Friday, July 22, 2016

The server response was: 5.5.1 authentication required in Gmail

Introduction 
          Today i came  across an forum post saying  cant able to send a mail to his domain that he purchased but able to send mail to gmail to gmail.The actual is gmail wants the clients to be secure even throw we set EnableSsl = true;
simply it wont work.
       
           To fix the issue add the RemoteCertificateValidationCallback then it will work fine.
  1. public class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             string senderID = "xxx@gmail.com";  
  6.             string senderPassword = "xxxx";  
  7.             RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;  
  8.             string body = "Test";  
  9.             try  
  10.             {  
  11.                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);  
  12.                 ServicePointManager.Expect100Continue = true;  
  13.                 MailMessage mail = new MailMessage();  
  14.                 mail.To.Add("danish.habib@plan-international.org");  
  15.                 mail.From = new MailAddress(senderID);  
  16.                 mail.Subject = "My Test Email!";  
  17.                 mail.Body = body;  
  18.                 mail.IsBodyHtml = true;  
  19.                 SmtpClient smtp = new SmtpClient();  
  20.                 smtp.Host = "smtp.gmail.com";  
  21.                 smtp.Credentials = new System.Net.NetworkCredential(senderID, senderPassword);  
  22.                 smtp.Port = 587;  
  23.                 smtp.EnableSsl = true;  
  24.                 smtp.Send(mail);  
  25.                 Console.WriteLine("Email Sent Successfully");  
  26.             }  
  27.             catch (Exception ex)  
  28.             {  
  29.                 Console.WriteLine(ex.Message);  
  30.             }  
  31.             finally  
  32.             {  
  33.                 ServicePointManager.ServerCertificateValidationCallback = orgCallback;  
  34.             }  
  35.         }  
  36.   
  37.         private static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)  
  38.         {  
  39.             return true;  
  40.         }  
  41.     }