Sunday 26 July 2015

Reading emails using c# and POP3

I wanted to write my own automated behaviour after I receive new email and for that I needed to read emails that I get.

I have used OpenPop Nuget package.

Here is my package.config file

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="OpenPop.NET" version="2.0.6.1116" targetFramework="net45" />
</packages> 


Now after installing the package I have needed to add implementation that I took from
https://github.com/foens/hpop/blob/master/OpenPopExamples/Examples.cs to read emails.

Here is my code with configuration.

 // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect("pop.gmail.com", 995, true);

                // Authenticate ourselves towards the server
                client.Authenticate("email@gmail.com", "password");

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    var msg = client.GetMessage(i);
                   Console.WriteLine(msg.Headers.Subject));
                }
            }

Now the issue is that email does not allow me to read the emails.
And the reading fill fail with exception.
If you drill into the exception you will be able to find following link

https://www.google.com/settings/security/lesssecureapps

This will give you configuration option to configure this


Now when I run the code I get my emails through.


Thursday 23 July 2015

Installing underscore into angular and typescipt

I wanted to know how difficult it is to install underscore js library to project using typescript and angular js into my MVC Application

Turns out you need to download and install underscore.js (Read more about underscore)

using nuget search for "underscore.js"
After installation of this nuget package you will find in your packages.config line such as
<package id="underscore.js" version="1.8.2" targetFramework="net451" />

Note: 

This may differ based on version or framework but the important part is <package id="underscore.js"

Now we have installed underscore.
The directory where the package will be installed is /Scripts/

We need to add reference to our view

<script type="text/javascript" src="~/Scripts/underscore.min.js"></script>

So far this is standard way of using javascript.

Now I have created my typescript. I have named it index.ts

Now typescript does need definitions for it to recognise methods that library exposes and this is done in definition files. You can download definitions from Boris Yankov collection shared on github : https://github.com/borisyankov

File that you are looking for is named: underscore.d.ts

Put the file to same location where you have your underscore js file in my case or with all of your definitions.

Insert following path on top of your file.
/// <reference path="../../underscore.d.ts" />

Why is underscore path: "../../underscore.d.ts"?

it is because of my typescript lives in "/Scripts/App/Index/index.ts" which needs to go two directories up.

After this all we can go to your typescipt file and start using underscore in typescript





Sunday 28 June 2015

Parse date from yyyy-MM-dd string

Often developer needs to parse formatted string to object.

Here is example I am commonly using:

I have a date time string:

var myString = "2015-06-05"

I need to parse it into DateTime variable 

var myString = "2015-06-05";
var parsedDateTime = DateTime.ParseExact(myString, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);

Monday 30 March 2015

hide input rendered by editorformodel

The problem
We are using following code for login:

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <p>
        <button type="submit">Log In</button>
    </p>
}

The model is defined as:


 public class LogInModel
    {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public string ReturnUrl { get; set; }
    }



So every time the page with the model renders, it will create 3 elements for user to imput data

One for email, second for password and the third for return url.

So how do we hide it?

We hide it using data annotation

 [ScaffoldColumn(false)]



so then our model will become:

    public class LogInModel
    {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        [ScaffoldColumn(false)]
        public string ReturnUrl { get; set; }
    }

Sunday 29 March 2015

While writing my website I have read many blog posts how to do this the best way.

Couple targets I had in mind

  • Create bundle that will create smaller file to download
  • Almost everyone is using cdn, unless they are living behind firewall
  • And if cdn fails, provide file from local source

Key points:
  • Bundling is simply getting multiple files under one.
  • Minification is making files smaller
In my example I have java script files.

To render the bundle i need script in my page such as

 @Scripts.Render("~/bundles/jquery")

How to create a bundle


In your ASP.NET application you will have to find file: BundleConfig.cs
inside you will be able to find default setup, which might not be used in your template. 

     bundles.Add(new ScriptBundle("~/bundles/jquery")
                .Include("~/Scripts/jquery-{version}.js")); 

You might need to enable optimizations with code

 BundleTable.EnableOptimizations = true;
in order to see the efect on your page once run it.
   

Now to CDN


  1. content delivery network (CDN) is a system of distributed servers (network) that deliver webpages and other Web content to a user based on the geographic locations of the user, the origin of the webpage and a content delivery server.

Is supposed to offload some of the traffic, but what if I cannot access it?

We can create backup configuration, so I a case that cdn is unreachable we do not get down with our application.

How to achieve it?
First we need to tell bundle configuration that we are going to use cdn
  bundles.UseCdn = true;
And then we need to provide code with cdn first
  bundles.Add(new ScriptBundle("~/bundles/jquery", "https://code.jquery.com/jquery-{version}.min.js")
                .Include("~/Scripts/jquery-{version}.min.js"));
Notice the include after the path to cdn. This defacto says if you cannot get the file from here look to this alternative location

Example of the code is here:

One of many sources:
http://www.asp.net/mvc/overview/performance/bundling-and-minification
www.stackoverflow.com

Tuesday 24 March 2015

xmlDoc.SelectSingleNode keeps same value in foreach loop


I have had an issue when looping through xml child nodes.

where using selector in loop kept same value.

xmlDoc.SelectSingleNode 

Example
var listOfNodes = xmlDoc.SelectSingleNode("//elementSelector");

foreach (XmlNode node in listOfNodes)
{
            var myValue = node.SelectSingleNode(@"//elementSelector").InnerText
}

myValue for each iteration returns same value even though the node changes


Solution is to add '.'

currentVenue.SelectSingleNode(@".//venueName").InnerText;


Now why this is:

The '.' in selector means to select the current node.
Without it, searching starts from the document root, not current element.

Difference between throw ex vs throw


Just had a 5 min before my VS finish building solution


Examples 

try {
DivByZero();
} catch (Exception ex){
throw;
}

try {
DivByZero();
} catch (Exception ex){
throw ex;
}



The difference is:

"throw ex"
  Resets the stack trace (so your errors would appear to originate from location where the code is throwing ex)
"throw"
 Keeps the original stack trace would be preserved.