Generating Unique Token in C# | Generating Unique Token that Expires after 24 Hours in C# | C# Tutorial

,
There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.
To create a unique token:
string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
Basic example of creating a unique token containing a time stamp:
byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());
To decode the token to get the creation time:
byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
  // too old
}
Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.

New Features in C# 6.0 Visual Studio 2013 | C# 6.0 Video Tutorial | C# 6.0 Tutorial

,
This video tutorial explains you about new features on C# 6.0 visual studio 2013. From this video tutorial, you will understand what is improvised in C# 6.0 visual studio 2013 and the new features in C# 6.0 visual studio 2013. Features introduced in C# 6.0 visual studio 2013 includes Null-Conditional Operator, Auto-Property Initializers, Nameof Expressions, Primary Constructors, Expression Bodied Functions and Properties.

Now let us get into the details of new features in C# 6.0 visual studio 2013 in this video tutorial.


Webinar on What's New in C# 6.0

Diagnosing Error: validation failed for one or more entities. see 'entityvalidationerrors' property for more details | Entity Framework Programmer Guide

,
Sometimes in entity framework code first approach, you could have come across an issue "validation failed for one or more entities. see 'entityvalidationerrors' property for more details" while you commit your changes db using SaveChanges() method.

In such cases, you can make use of the below C# code snippet to get through the root cause of the error.

try
{
    context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

How a Foreign Key is Represented in LINQ ? | Foreign Key in LINQ Join | LINQ Interview Question | LINQ Programmer Guide

, ,

In LINQ you do not have to use join as often as you do in SQL because foreign keys in LINQ are represented in the object model as properties that hold a collection of items. For example, a Customer object contains a collection of Order objects. Rather than performing a join, you access the orders by using dot notation:
from order in Customer.Orders...
Join operations create associations between sequences that are not explicitly modeled in the data sources. For example you can perform a join to find all the customers and distributors who have the same location. In LINQ the join clause always works against object collections instead of database tables directly.

var innerJoinQuery =
    from cust in customers
    join dist in distributors on cust.City equals dist.City
    select new { CustomerName = cust.Name, DistributorName = dist.Name };

Sending Email with Attachment in C# | SMTP Email with Attachment in C# | Send Files using Google SMTP Server in C# | C# Programmer Guide

In the previous article, we have seen how to send Email using SMTP in C#. In this article, let us see how to send an email with attachment using SMTP protocol in C#.

This example uses Gmail SMPT server for sending a mail with attachment in C#. The below code snippet shows how to add an attachment to the mail object.

  System.Net.Mail.Attachment attachment;
  attachment = new System.Net.Mail.Attachment("your attachment file");
  mail.Attachments.Add(attachment);

The Complete Source Code for sending an attachment in email using C#

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add("to_address");
                mail.Subject = "Test Mail - 1";
                mail.Body = "mail with attachment";

                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment("your attachment file");
                mail.Attachments.Add(attachment);

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Sending Email from C# | SMTP Email in C# | Using Google SMTP Server in C# | C# Programmer Guide | C# Tutorial

We can send data or receive data over Internet in C# using two namespaces, System.Net and System.Net.Sockets. Let us use SMTP protocol in C# to send email from C# application.

SMTP stands for Simple Mail Transfer Protocol . In C#, using System.Net.Mail namespace for sending email, We can instantiate SmtpClient class and assign the Host and Port . The default port for using SMTP is 25,

The C# code snippet shows how to send an email from a Gmail address using SMTP server. The Gmail SMTP server name is smtp.gmail.com and the port used to send mail is 587. We pass the email credential using NetworkCredential for password based authentication.


  SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
  SmtpServer.Port = 587;
  SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add("to_address");
                mail.Subject = "Test Mail";
                mail.Body = "This is for testing SMTP mail from GMAIL";

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

What is tuple in c#? | New features in C# 5.0 | ASP.NET C# Interview Question | ASP.NET Programmer Guide

, ,
Tuple

Tuples allow you to group related values without the need of a class. It’s more flexible than the KeyValuePair because it can store up to 8 values. A nice thing about Tuples is also the fact that they take on the aggregate equality of the values of the items they hold. Meaning that a Tuple<int, int> with values 1 and 2 equals any other Tuple<int, int> with 1 and 2 as values when you call Equals to compare them, plus they both return the same GetHashCode value.


Here’s a small example of how you can instantiate a Tuple using declarative notation and type inference:

// Create one using the constructor
var tupleOne = new Tuple<int, string, double>(3, "John", 2.13);

// Or using type inference
var tupleTwo = Tuple.Create(3, "John", 2.13);


If you’re thinking of using this for more than 3 items, consider using a class instead because you’re code will end up messy.

What is Named and Optional Arguments in C#? | New features in C# 5.0 | ASP.NET C# Interview Question | ASP.NET Programmer Guide

, ,
Named and Optional Arguments

Named and optional arguments allows a lot of calling options (with defaults) but without the need of littering your code with overloads. Named Parameters allow you to specify  your parameters in any order and omit any parameters with defaults as long as everything without a default value is specified.


Here’s an example of a method with named arguments:

public void ShowNamedArguments()
{
    ShowValue(message: "Hello");
    ShowValue(message: "Hello", newLine: false);
}

public void ShowValue(bool newLine = true, string message = "Default", string extraFooter = "")
{
    Debug.Write(message);
    if (newLine) Debug.Write(Environment.NewLine);
    if (!string.IsNullOrEmpty(extraFooter)) Debug.Write(extraFooter);
}
 

New features in C# 5.0 | What is Parallel.ForEach and the Task Parallel Library | ASP.NET C# Interview Question | ASP.NET Programmer Guide

,
Parallel.ForEach and the Task Parallel Library

The Task Parallel Library or TPL is a collection of classes designed to make multi-threading and parallel coding a lot easier and safer now that we have multi-core processors widely available.
One of the feature in the TPL is the Parallel.ForEach which will let you parallelize your loop if order of execution is not important. It will let you parallelize your work in no time without the need of starting up and handling threads on your own.


public void ParallelForEach()
{
    var testList = new List<string> { "One", "Two", "Three", "Four", "Five" };
    System.Threading.Tasks.Parallel.ForEach(testList, item => Console.WriteLine(item));
}

New features in C# 4.5 and C# 5.0 | ASP.NET C# Interview Question | C# Programmer Guide

,
BigInteger

The is a new DLL called System.Numerics that holds 2 public types. One of these types is the BigInteger struct. If you ever feel the need for some scientific programming you can resort to this struct. BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.


BigInteger bigIntFromDouble = new BigInteger(156487.4645);
Console.WriteLine(bigIntFromDouble);

BigInteger bigIntFromInt64 = new BigInteger(465789487421);
Console.WriteLine(bigIntFromInt64);

When to use IEnumerable, ICollection, IList and List? | Scenarions for IEnumerable, ICollection, IList and List | C# Interview Question | C# Programmer Guide

,
The below diagram clearly defines the difference between IEnumerable, ICollection, IList and List by listing the methods available in each of them.

Scenarions for IEnumerable, ICollection, IList

The following table provides various scenarios to use IEnumerable, ICollection, IList and List and it will help you to decide which type you should use.
InterfaceScenario
IEnumerable, IEnumerable<T>The only thing you want is to iterate over the elements in a collection. You only need read-only access to that collection.
ICollection, ICollection<T>You want to modify the collection or you care about its size.
IList, IList<T>You want to modify the collection and you care about the ordering and / or positioning of the elements in the collection.
List, List<T>Since in object oriented design you want to depend on abstractions instead of implementations, you should never have a member of your own implementations with the concrete type List/List.

Removing All Namespaces from XML Using C# Linq | Linq Programmer Guide

,
Below is the simple C# linq code snippet that strips namespaces from an XML string.

public static string RemoveAllNamespaces(string xmlDocument)
{
    var xml = XElement.Parse(xmlDocument);
    xml.Descendants().Select(o => o.Name = o.Name.LocalName).ToArray();
    return xml.ToString();
}

Async Feature in C# 5.0 with Example Code | C# Tutorial | C# Programmer Guide

Two new key words are used for Async feature: async modifier and await operator. Method marked
with async modifier is called async method. This new feature will help us a lot in async programming.
For example, in the programming of Winform, the UI thread will be blocked while we use HttpWebRequest synchronously request any resource in the Internet. From the perspective of user experience, we cannot interact with the form before the request is done.

private void btnTest_Click(object sender, EventArgs e)
{
    var request = WebRequest.Create(txtUrl.Text.Trim());
    var content=new MemoryStream();
    using (var response = request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
             responseStream.CopyTo(content);

}

}

txtResult.Text = content.Length.ToString();

}


In the above example, after we clicked the Test button, we cannot not make any change to the form
before the txtResult textbox shows the result.

In the past, we can also use BeginGetResponse method to send async request as this sample in MSDN
shows: 

But it will takes us a lot effort to realize it. Now, we can simply use below code to do request asynchronously :

private async void btnTest_Click(object sender, EventArgs e)
{
   var request = WebRequest.Create(txtUrl.Text.Trim());
   var content = new MemoryStream();

   Task<WebResponse> responseTask = request.GetResponseAsync();

   using (var response = await responseTask)
   {
      using (var
      responseStream = response.GetResponseStream())
      {
         Task copyTask = responseStream.CopyToAsync(content);

         //await operator to supends the excution of the method until the task is completed. In the meantime, the           control is returned the UI thread.

         await copyTask;
      }
   }
   txtResult.Text = content.Length.ToString();
}

The await operator is applied to the returned task. The await operator suspends execution of the method until the task is completed. Meanwhile, control is returned to the caller of the suspended method.

Parallel Programming Architecture in the .NET Framework 4 | .Net Programmer Guide

,
The following illustration provides a high-level overview of the parallel programming architecture in the .NET Framework 4.
.NET Parallel Programming Architecture

C# Features By Version | C# Interview Question | C# Tutorial | C# Programmer Guide

,
C# evolution started with visual studio 2002. Below diagram summarizes all the key features
into a C# Evolution Matrix for your reference:

What Is A Predicate Delegate? | Predicate Delegate In C# Tutorial | C# Guide

A predicate delegate is a delegate with the following signature:
  • Return type - bool
  • Argument type - generic
So, a predicate delegate is a delegate which points to a boolean function that returns true or false and takes a generic type as an argument. A predicate delegate thus is a delegate which is capable of taking any custom type as an argument. This makes it quite useful because what we get as a result is a generic delegate. The bool function that it points to has logic to evaluate any condition and return true/false accordingly.

What's New In Microsoft Enterprise Library 6 Release | C# Tutorial And Tips

,
This major release of Enterprise Library contains many compelling new features and updates that will make developers and IT professionals more productive. Two new application blocks are:
  • Semantic Logging Application Block.
  • Transient Fault Handling Application Block (this application block was previously a part of the Enterprise Library Integration Pack for Windows Azure; in this release it has been generalized and updated to the latest technologies).
Other major new features include:
  • New programmatic configuration that doesn’t require a container.
  • AsynchronousTraceListenerWrapper for the Logging Application Block, which enables existing listeners to write messages asynchronously.
  • JSON formatter for the Logging Application Block.
The new Unity Application Block includes many improvements:
  • Registration by convention.
  • Support for NetCore (Windows Store apps).
  • Resolving objects of type Lazy<T>.
  • The Unity assembly is now Security Transparent.
  • Support for ASP.NET MVC and ASP.NET Web API.
Note, this release of Enterprise Library retired the following application blocks:
  • Caching Application Block
  • Cryptography Application Block
  • Security Application Block

Why To Use Microsoft Enterprise Library | Main Goal Of Enterprise Library | C# Tutorial And Tips

Microsoft Enterprise Library is intended for use by developers who build complex, enterprise-level applications. Enterprise Library is used when building applications that typically will be deployed widely and must interoperate with other applications and systems. In addition, they generally have strict security, reliability, and performance requirements. The goals of Enterprise Library are the following:
  • Consistency. All Enterprise Library application blocks feature consistent design patterns and implementation approaches.
  • Extensibility. All application blocks include defined extensibility points that allow developers to customize the behavior of the application blocks by adding their own code.
  • Ease of use. Enterprise Library offers numerous usability improvements, including a configuration tool, powerful programmatic configuration support, intuitive interfaces, a simpler installation procedure that allows you to select only those application blocks you require, and clear documentation, samples, and hands-on labs.
  • Integration. Enterprise Library application blocks are designed to work well together or individually.

Components In Microsoft Enterprise Library 6 | C# Tutorial And Tips

,
Microsoft Enterprise Library consists of reusable software components that are designed to assist developers with common enterprise development challenges. It includes a collection of functional application blocks addressing specific cross-cutting concerns such as data access, logging, or validation; and wiring blocks, Unity and the Interception/Policy Injection Application Block, designed to help implement more loosely coupled, testable, and maintainable software systems.
Different applications have different requirements, and you will find that not every application block is useful in every application that you build. Before using an application block, you should have a good understanding of your application requirements and of the scenarios that the application block is designed to address.
Microsoft Enterprise Library 6 contains the following application blocks:
  • Data Access Application Block. Developers can use this application block to incorporate standard database functionality in their applications, including both synchronous and asynchronous data access and returning data in a range of formats.
  • Exception Handling Application Block. Developers and policy makers can use this application block to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging Application Block. Developers can use this application block to include logging functionality for a wide range of logging targets in their applications. This release adds asynchronous logging capabilities.
  • Policy Injection Application Block. Powered by the Interception mechanism built into Unity, this application block can be used to implement interception policies to streamline the implementation of common features, such as logging, caching, exception handling, and validation, across a system.
  • Semantic Logging Application Block. This application block provides a set of destinations (sinks) to persist application events published using a subclass of the EventSource class from the System.Diagnostics.Tracing namespace. Sinks include Windows Azure table storage, SQL Server databases, and flat files with several formats and rolling capabilities. Developers can extend the block by creating custom formatters and sinks. For those sinks that can store structured data, the block preserves the full structure of the event payload in order to facilitate analyzing or processing the logged data. Events can be persisted in-process or collected and persisted out-of-process in a separate service.
  • Transient Fault Handling Application Block. This application block makes on-premises or cloud applications more resilient to transient failures by providing intelligent retry logic mechanisms.
  • Unity Application Block. Developers can use this application block as a lightweight and extensible dependency injection container with support for constructor, property, and method call injection, as well as instance and type interception. This release adds support for Windows Store apps as well as the registration by convention feature to ease the task of configuring Unity.
  • Validation Application Block. Developers can use this application block to create validation rules for business objects that can be used across different layers of their applications.
Enterprise Library also includes a set of core functions for declarative configuration support.

Scenarios To Implement Microsoft Enterprise Library | C# Tutorial And Tips

,
Microsoft released new version of Microsoft Enterprise Library 6. Microsoft Enterprise Library is a collection of application blocks designed to assist developers with common enterprise development challenges. Application blocks are a type of guidance, provided as source code that can be used "as is," extended, or modified by developers for use in their development projects.
Microsoft Enterprise Library can be useful in a variety of situations:

  • Enterprise Library provides sufficient functionality to support many common cross-cutting scenarios that enterprise-level applications must address.
  • Enterprise Library can serve as the basis for a custom library. You can take advantage of the extensibility points incorporated in each application block and extend the application block by adding new providers. You can also modify the source code for the existing application blocks to incorporate new functionality, and even add new application blocks to Enterprise Library. You can either develop extensions for existing application blocks and new application blocks yourself, or you can use extensions and application blocks developed by others.
  • Enterprise Library is designed so that its application blocks can function independently of each other. You need to add only the application blocks that your application will use.
  • Enterprise Library includes the source code and the unit tests for all application blocks. This means you can explore the implementations, modify the application blocks to merge into your existing library, or you can use parts of the Enterprise Library source code in other application blocks or applications that you build.
  • Enterprise Library includes documentation, a reference implementation, and source code. Enterprise Library embodies many design patterns, and demonstrates good architectural and coding techniques. You can use the library as a tool for learning architectural, design, and proven coding practices.