Wednesday, February 1, 2017

What's New in C# 6.0

The 6.0 release of C# contained many features that improve productivity for developers. Features in this release include:             


1.     Read-only Auto-properties:      
è You can create read-only auto-properties that can be set only in constructors.
è You can write initialization expressions to set the initial value of an auto-property.
è You can author one-line methods using lambda expressions.
4.     using static:
è You can import all the methods of a single class into the current namespace.
è You can concisely and safely access members of an object while still checking for null with the null conditional operator.
è You can write string formatting expressions using inline expressions instead of positional arguments.
7.     Exception filters:
è You can catch expressions based on properties of the exception or other program state.
8.     nameof Expressions:
è You can let the compiler generate string representations of symbols.
è You can use await expressions in locations that previously disallowed them.
è You can author initialization expressions for associative containers as well as sequence containers.
è Collection initializers can rely on accessible extension methods, in addition to member methods.
  è Some constructs that previously generated ambiguous method calls now resolve correctly.            


Explaination:                   

Auto-Property Initializers:

C# 6.0 came with a new concept of initializing class properties inline rather than initializing them within the type's constructor. Another handy technique is, if you want to make the setter of a property private to block users from setting value in the property by an instance, you can just declare a getter only property. For example:

Before C# 6

using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee = new Employee();

            WriteLine("Name: " + 
            employee.Name + "\nSalary: " + employee.Salary);

            ReadKey();
        }
        public class Employee
        {
            public string Name { get; set; } 
            public decimal Salary { get; set; }
            public Employee()
            {
             /* Initializing property through constructor */
             Name = "Sammy Jenkins";
                Salary = 10000; 
            }
        }
    }
}

In C# 6.0

using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee = new Employee();

            WriteLine("Name: " + 
            employee.Name + "\nSalary: " + employee.Salary);

            ReadKey();
        }
        public class Employee
        {
         /* Getter only property with inline initialization */
            public string Name { get; } = "Sammy Jenkins"
            
            /* Property with inline initialization */
            public decimal Salary { get; set; } = 10000; 
        }
    } 
}


Dictionary Initializers:

C# 6.0 changed the way you can initialize Dictionary. Previously on C# 5, you would have to initialize the Dictionary with this type of syntax, {"Key", "Value"}. Now in C# 6, you can just place the key between two curly brackets ["Key"] and then set the value of the key ["Key"] = "value"; , just like you set the value for other types of variable. This new syntax is friendlier than before.

Before C# 6

using System.Collections.Generic;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            Dictionary<string, string=""> 
            alien = new Dictionary<string, string="">()
            {
                {"Name", "Fizzy"},
                {"Planet", "Kepler-452b"}
            };

            foreach (KeyValuePair<string, string=""> keyValuePair in alien)
            {
                WriteLine(keyValuePair.Key + ": " + 
                keyValuePair.Value + "\n");
            }

            ReadLine();
        }
    }   
}

In C# 6.0

using System.Collections.Generic;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
         /* The new and friendly syntax */ 
            Dictionary<string, string=""> alien = new Dictionary<string, string="">()
            {
                ["Name"] = "Fizzy",
                ["Planet"] = "Kepler-452b"
            };

            foreach (KeyValuePair<string, string=""> keyValuePair in alien)
            {
                WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "\n");
            }

            ReadLine();
        }
    }   
}

Expression Bodied Function & Property:

You can now write functions and computed properties like lamda expressions to save extra headache of defining function and property statement block. Just use the lambda operator => and then start writing your code that goes into your function/property body. Here is a simple example:
using static System.Console;

namespace NewInCSharp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            double x = 1.618;
            double y = 3.142;

            WriteLine(AddNumbers(x, y));
            ReadLine();
        }

  /* Expression bodied function */
        private static double AddNumbers(double x, double y) => x + y;
    }
}
For expression bodied property:
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            Person person = new Person();
            WriteLine("I'm " + person.FullName);
            ReadLine();
        }

        public class Person
        {
            public string FirstName { get; } = "Fiyaz";
            public string LastName { get; } = "Hasan";
            
            /* Expression bodied computed property */
            public string FullName => FirstName + " " + LastName;
        }
    }
}

Static Types as using:

So, we are all quite familiar with this notion of accessing static class members using the qualification first. It is not required now. Importing static using can save the day. For example, before C# 6.0, we had to access ReadKey(), WriteLine() methods of the Console class by explicitly defining the static class qualifier.
using System;

namespace NewInCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            MySelf.WhoAmI();
            Console.ReadKey();
        }
    }

    static class MySelf
    {
        public static void WhoAmI()
        {
            Console.WriteLine("I'm Fizz!");
        }
    }
}
In C# 6.0, we can get rid of the qualifiers just by importing the static types in the namespace like below:
using static System.Console;
using static NewInCSharp.MySelf; /* Magic happens here */

namespace NewInCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            WhoAmI();
            ReadKey();
        }
    }

    static class MySelf
    {
        public static void WhoAmI()
        {
            WriteLine("I'm Fizz!");
        }
    }
}
  


Null Conditional Operator & Null Propagation:

Again, we have this new notion of null conditional operator where you can remove declaring a conditional branch to check to see if an instance of an object is null or not with this new ?. ?? null conditional operator syntax. The ?. is used to check if an instance is null or not, if it's not null then execute the code after ?. but if it is not, then execute code after ??. Check out the example below:

Before C# 6.0

using System;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            SuperHero hero = new SuperHero();
            if (hero.SuperPower == String.Empty)
            {
                hero = null;
            }
   
            /* old syntax of checking if an instance is null or not */
            WriteLine(hero != null ? hero.SuperPower : "You aint a super hero.");

            ReadLine();
        }
    }

    public class SuperHero
    {
        public string SuperPower { get; set; } = "";
    }
}

In C# 6.0

using System;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            SuperHero hero = new SuperHero();
            if (hero.SuperPower == String.Empty)
            {
                hero = null;
            }

   /* New null conditional operator */
            WriteLine(hero?.SuperPower ?? "You aint a super hero.");

            ReadLine();
        }
    }

    public class SuperHero
    {
        public string SuperPower { get; set; } = "";
    }
}
Again checking a list instance if it is null or not and then accessing its index is also somewhat similar.
using System;
using System.Collections.Generic;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            List<superhero> superHeroes = null;
            SuperHero hero = new SuperHero();

            if (hero.SuperPower != String.Empty)
            {
                superHeroes = new List<superhero>();
                superHeroes.Add(hero);
            }

            WriteLine(superHeroes?[0].SuperPower ?? "There is no such thing as super heros.");
            ReadLine();
        }
    }

    public class SuperHero
    {
        public string SuperPower { get; set; } = "";
    }
}
What if you want to invoke an event/delegate after checking if the handler function is null or not? Well, the null checking syntax would be like in the example below. It is also known as null propagation.

Before C# 6.0

using System;
using System.Collections.Generic;
using System.ComponentModel;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            Movie movie = new Movie();
            movie.Title = "The Shawshank Redemption";
            movie.Rating = 9.3;
            WriteLine("Title: "+ movie.Title + "\nRating: " + movie.Rating);
            ReadLine();
        }
    }

    public class Movie : INotifyPropertyChanged
    {
        public string Title { get; set; }
        public double Rating { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            
            /* Old syntax of checking if a handler is null or not */
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

In C# 6.0


using System;
using System.Collections.Generic;
using System.ComponentModel;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            Movie movie = new Movie();
            movie.Title = "The Shawshank Redemption";
            movie.Rating = 9.3;
            WriteLine("Title: "+ movie.Title + "\nRating: " + movie.Rating);
            ReadLine();
        }
    }

    public class Movie : INotifyPropertyChanged
    {
        public string Title { get; set; }
        public double Rating { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            
            /* Null propagation syntax */
            handler?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}



String Interpolation:

You can now forget using placeholders in strings to replace them with real values. C# 6 has a new feature called string interpolation using which you can now directly write your arguments instead of referring them with placeholders inside a string. You can also do whatever you would have done previously with String.Format() function.

Before C# 6.0

using System;
using System.Collections.Generic;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            string name = "Murphy Cooper";
            string planet = "Cooper Station";

            WriteLine("{0} is actually named after {1}", planet, name);

            ReadLine();
        }
    }   
}

After C# 6.0

using System;
using System.Collections.Generic;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            string name = "Murphy Cooper";
            string planet = "Cooper Station";
            
   /* Magic happens here */
            WriteLine($"{planet} is actually named after {name}");

            ReadLine();
        }
    }   
}
Again, these are a few string formatting examples which I missed in the video. [Check the video link at the bottom of the article.]

string name = "Sammy Jenkins";
double salary = 1000;

WriteLine($"{name}'s monthly salary is {salary:C2}"); 
WriteLine($"Man! This {name} is kind of a 
{(salary >= 1000 ? "rich guy" : "poor guy")}");

/*Output: 
 Sammy Jenkins's monthly salary is $1000.00
 Man! This Sammy Jenkins is kind of a rich guy
*/
                           


Exception Filtering:

Exception filtering is nothing but some condition attached to the catch block. Execution of the catch block depends on this condition. Let me give you a simple example.
In C# 5, we would have done something like the code given below to show users appropriate messages depending on the randomly generated http status codes.
using System;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            Random random = new Random();
            var randomExceptions = random.Next(400, 405);
            WriteLine("Generated exception: " + randomExceptions);
            Write("Exception type: ");

            try
            {
                throw new Exception(randomExceptions.ToString());
            }
            catch (Exception ex)
            {
                if(ex.Message.Equals("400"))
                    Write("Bad Request");
                else if (ex.Message.Equals("401"))
                    Write("Unauthorized");
                else if (ex.Message.Equals("402"))
                    Write("Payment Required");
                else if (ex.Message.Equals("403"))
                    Write("Forbidden");
                else if (ex.Message.Equals("404"))
                    Write("Not Found");
            }

            ReadLine();
        }
    }
}
Here, I'm randomly generating an exception code randomExceptions. Inside the catch block, I'm showing the appropriate error message respective to the exception code.
Now you can achieve the same thing using exception filtering but the syntax is a bit different. Rather than entering the catch block and checking to see which condition met our exception, we can now decide if we even want to enter the specific catch block. Here is the code:
using System;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {           
            Random random = new Random();
            var randomExceptions = random.Next(400, 405);
            WriteLine("Generated exception: " + randomExceptions);
            Write("Exception type: ");

            try
            {
                throw new Exception(randomExceptions.ToString());
            }
            catch (Exception ex) when (ex.Message.Equals("400"))
            {
                Write("Bad Request");
                ReadLine();
            }
            catch (Exception ex) when (ex.Message.Equals("401"))
            {
                Write("Unauthorized");
                ReadLine();
            }
            catch (Exception ex) when (ex.Message.Equals("402"))
            {
                Write("Payment Required");
                ReadLine();
            }
            catch (Exception ex) when (ex.Message.Equals("403"))
            {
                Write("Forbidden");
                ReadLine();
            }
            catch (Exception ex) when (ex.Message.Equals("404"))
            {
                Write("Not Found");
                ReadLine();
            }
        }
    }
}
So, what's the main difference between these two. Well when you enter a catch block, the current execution state is lost. So, the actual cause of the exception is really hard to find. But in the exception filtering, we stay where we should be staying, i.e., current execution state. This means the stack stays unharmed.
So, exception filtering is good, right? Well there is a catch! Since in the exception filtering, entering a catch block depends on the filter applied on the catch, making a silly mistake can change the whole meaning of the exception. This may actually happen cause the filtering depends on a boolean result and this boolean result can be sent from any code block, making the exception have a different meaning. For example:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
       private static void Main(string[] args)
        {
            Task.Factory.StartNew(GetWeather);
            ReadLine();
        }

        private static async void GetWeather()
        {
            string customErrorMessage;
            HttpClient client = new HttpClient();

            try
            {
                HttpResponseMessage httpResponseMessage = 
                await client.GetAsync
                ("http://api.openweathemap.org/data/2.5/weather?q=NewYorK");
                WriteLine(httpResponseMessage);
            }
            catch (Exception ex) when 
            (DoASillyMistake(ex.Message, out customErrorMessage))
            {
                WriteLine(customErrorMessage);
            }
        }

        private static bool DoASillyMistake
        (string exceptionMessage, out string customErrorMessage)
        {
            if (exceptionMessage.Equals
            ("An error occurred while sending the request."))
            {
                customErrorMessage = "Unauthorized.";
                return true;
            }
            else
            {
                customErrorMessage = "Bad Gateway.";
                return true;
            }
        }
    }
}
This is a silly example I must say, but let's assume that if a request to a weather service fails, it's because of two reasons, one the service is not up and running [Bad Request] and the second is a user needs to be authorized before accessing the service [Unauthorized]. So, in my code, I know for sure that the HttpClient will throw an error message like below if it's a Bad Request.
"An error occurred while sending the request."
Again for any other error messages, let's assume it's an Unauthorized request. If you look carefully at the DoASillyMistake(string exceptionMessage, out string customErrorMessage) function, you will see I really did a silly mistake. I've shown the user that they are 'Unauthorized' to access the service while the message should be 'Bad Request' since the service url is not valid [there is a letter is missing in the url; 'r' to complete the word weather]. Now the funny and bit irritating part is that the user will now start looking for a registration process to get access to the service. But sadly, we all know that is not the case. The funnier part is even if he registered himself, from now he will get a 'Bad Request'. So, you must be careful when using exception filtering.
But even this side effect can sometimes come in handy. For example, you can attach a filter function which logs error messages and returns false so that the log contains an appropriate exception and also the execution cursor doesn't end up in the catch block. Here is a good example from that I found in this open source .NET git repo documentation, New Language Features in C# 6.
private static bool Log(Exception e) { /* log it */ ; return false; }
....
try { .... } catch (Exception e) when (Log(e)) {}              

nameof expression:

Next one is the nameof expression. In enterprise level applications, lines of code run like a mad horse. So there is no means of avoiding exception handling where it is necessary. Showing a specific type name with an error message can be a quick way to find the code block where the exception just occurred. But we should also consider refactoring issues. We cannot just simply append a hard coded type name string with an error message and show it to the user because the type name can be changed anytime while refactoring but hard coded string won't change accordingly. So C# 6.0 introduced this concept of nameof expression. A simple example would be like this:

Before C# 6

using System;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                CallSomething();
            }
            catch (Exception exception)
            {
                WriteLine(exception.Message);
            }

            ReadKey();
        }

        private static void CallSomething()
        {
            int? x = null;

            if (x == null)
            {
                throw new Exception("x is null");
                
             /* x is the type name. What if someone changes the 
             type name from x to i? The exception below would be inappropriate. */
            }
        }
    }
}
class Program
{
    private static void Main(string[] args)
    {
        try
        {
            CallSomething();
        }
        catch (Exception exception)
        {
            WriteLine(exception.Message);
        }

        ReadKey();
    }

    private static void CallSomething()
    {
        int? x = null;

        if (x == null)
        {
         
            
            throw new Exception("x is null");
        }
    }
}

In C# 6.0

using System;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                CallSomething();
            }
            catch (Exception exception)
            {
                WriteLine(exception.Message);
            }

            ReadKey();
        }

        private static void CallSomething()
        {
            int? number = null;

            if (number == null)
            {
                throw new Exception(nameof(number) + " is null");
            }
        }
    }
}


Await in catch/finally Block:

I think many of you were waiting for this feature in C# where you can write asynchronous code inside catch and finally block. Well, now you can do that.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using static System.Console;

namespace NewInCSharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            Task.Factory.StartNew(() => GetWeather());
            ReadKey();
        }

        private async static Task GetWeather()
        {
            HttpClient client = new HttpClient();
            try
            {
                var result = await client.GetStringAsync
                ("http://api.openweathermap.org/data/2.5/weather?q=Dhaka,bd");
                WriteLine(result);
            }
            catch (Exception exception)
            {
                try
                {
                 /* If the first request throws an exception, 
                 this request will be executed. 
                        Both are asynchronous request to a weather service*/
                    
                    var result = await client.GetStringAsync
                    ("http://api.openweathermap.org/data/2.5/weather?q=NewYork,us");

                    WriteLine(result);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}

Refferences:
https://www.codeproject.com/Tips/1023426/Whats-New-in-Csharp

What's New Features in C# 5.0

*** C# Evolution Matrix ***
Microsoft just published a new version of C# : 5.0 beta with CLR version 4.5 (Visual Studio 11 beta).
In order to get a big picture of the whole evolution of C# language, I summarized all the key features
into a C# Evolution Matrix for your reference as below diagram shows:



In C# version 5.0, there are two key features: Async Programming and Caller Information.
1. Async Feature
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.
Old methodology:
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:
http://msdn.microsoft.com/zh-cn/library/system.net.httpwebrequest.begingetresponse(v=vs.80).aspx. But it
will takes us a lot effort to realize it.
New Logic:

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.
2.Caller Information
Caller Information can help us in tracing, debugging and creating diagnose tools. It will help us
to avoid duplicate codes which are generally invoked in many methods for same purpose, such
as logging and tracing.
We could get the below information of caller method :

Old Logic:

Below example are a common practice prior to the new feature of Caller Information:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace
ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
InsertLog(“Main”);
MethodB();
Console.ReadLine();
}
static void MethodA()
{
InsertLog(“MethodA”);
MethodB();
}
static void MethodB()
{ }
static void
InsertLog(string methodName)
{
Console.WriteLine(“{0} called method B at {1}”, methodName,
DateTime.Now);
}
}
}
New Logic:
In both Main and MethodA methods, method InsertLog is invoked for logging. Now we can change the
codes to be as per below lines:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace
ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
//InsertLog(“Main”);
MethodB();
Console.ReadLine();
}
static void MethodA()
{
//InsertLog(“MethodA”);
MethodB();
}
static void MethodB(
[CallerMemberName] string memberName = “”,
[CallerFilePath] string sourceFilePath = “”,
[CallerLineNumber] int sourceLineNumber = 0)
{
InsertLog(memberName);
}
static void
InsertLog(string methodName)
{
Console.WriteLine(“{0} called method B at {1}”, methodName,
DateTime.Now);
}
}
}

New Feature:
Binding Operators:

Binding Operators may be C# 5.0. The support for Binding on .NET objects is awesome. I came to know this from Chris on his post where he speaks how Binding operators looked like long ago. The Delphi assignment operator := is now being used for this purpose. :=: would be used for two way binding. Thus:
comboBox1.Text :=: textBox1.Text; 
means there would be two way binding between the properties so that when ComboBox1.Text changes its Text, it will automatically change the value of Textbox1.Text. Binding is actually not a new thing to the system. In WPF, we already have Binding in place, but for that we need the properties to have implemented from INotifyPropertyChanged. So it is not in the language, the WPF objects are doing this internally by handling the PropertyChanged event on the object. But if that is included as an operator, it would be a cool feature to add on.

Summary:
The new features in C# 5.0 will help us to code more easily and improve the productivity. 

References:
https://blogs.msdn.microsoft.com/mvpawardprogram/2012/03/26/an-introduction-to-new-features-in-c-5-0/

Wednesday, December 28, 2016

How to Compare Two Dates using JQuery.

How to Compare Two Dates using JQuery ?


function compareTwoDates(Date1, Date2) {
    var D1 = Date1.split(".");
    var bool = false;
    D1 = new Date(D1.pop(), D1.pop() - 1, D1.pop());
    var D2 = Date2.split(".");
    D2 = new Date(D2.pop(), D2.pop() - 1, D2.pop());
    if (D1 >= D2)
        bool = true;
    return bool;
}

How to get Current Date and Increment and Decrement date using JQuery

How to get Current Date using JQuery ?

 function getCurrentDate() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    today = dd + '.' + mm + '.' + yyyy;
    return today;
}


Increment Date:
This function will give increment date by no. of days

Ex: current date 02.02.2017 increment by 2 days date will be 04.02.2017.

inputs are: incrementVal= 2 , and dateParam= 02.02.2017

function incrementDate(incrementVal, dateParam) {
    if (!isEmptyString(dateParam)) {
        var D1 = dateParam.split(".");
        dateParam = new Date(D1.pop(), D1.pop() - 1, D1.pop());
        dateParam.setDate(dateParam.getDate() + parseInt(incrementVal));

        var decrementedDate = ddmmyyyyFormat(dateParam);
        return decrementedDate;
    }

}

Result:
output:  04.02.2017.

Decrement Date:


This function will give decrement date by no. of days

Ex: current date 02.02.2017 decrement by 2 days date will be 31.01.2017.

inputs are: incrementVal= 2 , and dateParam= 02.02.2017

function decrementDate(decrementVal, dateParam) {
    if (!isEmptyString(dateParam)) {
        var D1 = dateParam.split(".");
        dateParam = new Date(D1.pop(), D1.pop() - 1, D1.pop());
        dateParam.setDate(dateParam.getDate() - parseInt(decrementVal));

        var decrementedDate = ddmmyyyyFormat(dateParam);
        return decrementedDate;
    }
}

Result:
output:  31.01.2017.

Format the Date: custom date format

This function will format the date as 02.02.2017.
inputs: date =current date.

function ddmmyyyyFormat(date) {
    var dateFromString = (('' + date.getDate()).length < 2 ? '0' : '') + date.getDate() + '.' +
        (('' + (date.getMonth() + 1)).length < 2 ? '0' : '') + (date.getMonth() + 1) + '.' +
         date.getFullYear();
    return dateFromString;
}

output:02.02.2017.


Sunday, October 23, 2016

How To Send emails from C# Application using SMTP Server.

             

                MailMessage mail = new MailMessage();
                SmtpClient smtpclient = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("k.vijaykumar0436@gmail.com");
                mail.To.Add("vijaynow2@gmail.com");
                mail.Subject = "Test Mail";
                mail.Body = mailBody;
                smtpclient.Port = 587;
                smtpclient.Credentials = new
                System.Net.NetworkCredential("k.vijaykumar0436@gmail.com", "password");
                smtpclient.EnableSsl = true;

                smtpclient.Send(mail);
                Console.Write("succussfullyy......");

Tuesday, February 16, 2016

Important links for .net

http://myview.rahulnivi.net/getting-started-angular-js/

Config-less Hosting

Hi guys,
In this section, we will look at Config-Less Hosting.
WCF does not require config file. It only requires endpoint information. It does not matter which medium it is coming from. You can provide all these information from the code itself. You can get all mandatory information from some source say xml file or database to construct the endpoint. I will give the demo by simply hardcoding the same. Let us go to console hosting. Nevertheless, before making any change in code, let me just comment the config section for WCF in APP.config file. Below is the snippet in the finished state.
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using MovieLib.Contracts;
using MovieLib.Services;
namespace ConsoleHostApplication
{
class Program
{
static void Main(string[] args)
{
ServiceHost hostMovieManager = new ServiceHost(typeof(MovieManager));
string address = "net.tcp://localhost:8010/MovieService";
Binding binding = new NetTcpBinding();
Type contract = typeof (IMovieService);
hostMovieManager.AddServiceEndpoint(contract, binding, address);
hostMovieManager.Open();
Console.WriteLine("Service Launched,Press Enter to Exit!");
Console.ReadLine();
hostMovieManager.Close();
}
}
}
Let me explain the code a bit. As you can see, I have provided endpoint procedurally. One point to note here is that all of these binding classes inherit from common base class binding. Here, I have created an instance of NetTcpBinding. Then I instantiated a type of my contract. In the end, add I have added endpoint with AddServiceEndpoint method. With the above code change in place, when I build and run the same, it produced the below output.
105th
Similar thing can be achieved with web host as well. We will delve further in the coming section. Till then, stay tuned and Happy Coding,
Thanks,
Vijay Kumar Kandala.
Happy Coding