Thursday, 27 November 2014

C# code to download a file from a website URL

Hi All,
Yesterday one of my colleagues was having issue with downloading a file from URL using c# for one of the projects. This is a general requirement for many projects and thought it would be helpful if I post here.

using System;
using System.IO;
using System.Net;
using System.Text;

namespace FileDownloadSample
{
    class Program
    {
        static void Main(string[] args)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com/yourfile.pdf");

            request.Method = "GET";

            var encoding = new UTF8Encoding();

            request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-gb,en;q=0.5");
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");

            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0";

            var resp = (HttpWebResponse)request.GetResponse();

           

            using (var stream = File.Create("TargetFileName.pdf"))
                resp.GetResponseStream().CopyTo(stream);


        }
    }
}

Thursday, 14 August 2014

How to Replace characters at specified position and line in UNIX


sed -n -e 24p -e 24q | cut -c27-34
sed -n '24p;24q' | cut -c27-34
The -n option means 'do not print lines by default'; the 24p means print line 24; the 24q means quit after processing line 24. You could leave that out, in which case sed would continue processing the input, effectively ignoring it.

Thursday, 7 August 2014

DoEvents in WPF

Below is the equivalent of Doevents in WPF

public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
}


If you want to do it in a WPF UserControl Library or CustomControl Library then you can do as below:

controlname.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));


Tuesday, 1 July 2014

C#.Net - Handling special characters in XML strings

Because XML syntax uses some characters for tags and attributes it is not possible to directly use those characters inside XML tags or attribute values.
To include special characters inside XML files you must use the numeric character reference instead of that character. The numeric character reference must be UTF-8 because the supported encoding for XML files is defined in the prolog as encoding="UTF-8" and should not be changed.
The numeric character reference uses the format:

&#nn;  decimal form
&#xhh; hexadecimal form
We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent [1]. 
1
2
//Usage
srtXML = SecurityElement.Escape(strXML);
Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)
I have used the HttpUtility classes UrlEncode and UrlDecode methods to handle cross-site scripting attacks and this also helped me to get rid of the XmlException – “Data at the root level is invalid”.
The following table shows the invalid XML characters and their respective replacements.

CodeNameDisplayed as
	Horizontal tabnon-printing

Line feednon-printing

Carriage Returnnon-printing
 Spacenon-printing
!Exclamation mark!
"Quotation mark"
#Number sign#
$Dollar sign$
%Percent sign%
&Ampersand&
'Apostrophe'
(Left parenthesis(
)Right parenthesis)
*Asterisk*
+Plus sign+
,Comma,
-Hyphen-
.Period.
/Slash/
:Colon:
&#59;Semi-colon;
&#60;Less than<
&#61;Equals sign=
&#62;Greater than>
&#63;Question mark?
&#64;At@
&#91;Left square bracket[
&#92;Bbackslash\
&#93;Right square bracket]
&#94;Caret^
&#95;Underscore_
&#96;Acute accent`
&#123;Left curly brace{
&#124;Vertical bar|
&#125;Right curly brace}
&#126;Tilde~

Reference:
1. MSDN


Thursday, 13 February 2014

New Features in C#.Net 5.0

Here are some of the C#.NET 5.0 New Features -

1. Key Features Matrix: Microsoft has published a new version of C# 5.0 beta with CLR version 4.5.

Key Features introduced in C# .Net 5.0

C# 5.0 introduces mainly two key features: Async Programming and Caller Information.

2. Asynchronous functions (Async and Await): Using Async and Await, you can use resources in the .NET Framework, to create an asynchronous method as easily as you create a synchronous method.

Asynchronous methods are the methods that you define using async and await.

Click on this http://codejunction.blogspot.in/2014/02/new-features-added-in-c-50.html to know more about async and await.

3. Caller Information: Caller Information attributes provide the information about the caller to a method. You can obtain the file path of the source code, the line number in the source code, and the member name of the caller. Caller Information helps us in tracing, debugging, and creating diagnostic tools.

CallerFilePathAttribute - Full path of the source file that contains the caller. This is the file path used at compile time.

CallerLineNumberAttribute - Line number in the source file on which the method is called.

CallerMemberNameAttribute - Method or property name of the caller.

4. Windows Runtime Support: C# and .NET now have deep integration with the Windows Runtime. C# project can compiled into a WinMD file and then referenced from a HTML/JavaScript project. WinRT’s flavor of COM uses the same metadata format used by the Common Language Runtime. This information is stored in WINMD files that show the structure, though not the implementation, of all the public classes. Windows Runtime returns an HRESULT instead of throwing an exception. For well-known HRESULT values, the corresponding exception is thrown, otherwise a COMException is used.

Read this article for more information on C# and Visual Basic on the WinRT API.

5. Compiler APIs: This feature is supposed to come after C# 5.0 – the APIs will expose whatever knowledge the compiler has about the code to the IDE and the developers, through Syntax Tree APIs, Symbol APIs, Binding and Flow analysis APIs and Emit APIs.

References:

http://msdn.microsoft.com/en-us/library/hh156499.aspx

http://www.infoq.com/news/2011/09/net-v5.0

Wednesday, 12 February 2014

Entity Framework result set not correct

This is a common problem that most of the people run into. You create an entity model to your view or table. Create a domain service and the client side code. In the client side code you put the filter and you run expecting to get some data but you end up getting one or few rows. I ran into the same problem yesterday. When I ran the program I got just the first row of the expected result.
The problem in my case, when I created the model from my table, I made some changes to attributes, removed bunch of columns, while doing it, i removed the unique key that identified the rows. It seems that if Entity Framework can not uniquely identify the rows, it does not return all the rows. To fix it, all I had to do is, go back to the model, make the fields that uniquely identify the rows, recompile and that’s it.
So if you run into any situation where the rows are not coming properly, this may be one of the culprit.

Introduction to .NET Framework 4.5.1

Introduction
This article is a brief introduction to .NET Framework 4.5.1. This framework was released with Visual Studio 2013 Preview. There are new characteristics in this framework and those are the following:
  • Windows Store Apps
  • CLR Improvements
  • Multi-core JIT improvements
  • LOH Compaction
  • ASP.NET Scaffolding
  • NuGet 2.6
Windows Store Apps
Windows Store Apps are designed for specific form factors to look better in the Windows Operating System. There is a subset available for building Windows Store apps in Visual Basic and Visual C# and that subset is called .NET for Windows Store Apps.
CLR Improvements
The following new features and improvements have been added to the Common Language Runtime (CLR) and to .NET Framework 4.5.1:
  • When you compile any app that targets the framework 4.5.1, binding redirects may be added in the app configuration file if your application or its components reference multiple versions of the same assembly. You can enable this feature for the apps that target the older version of .NET Framework.
  • Better performance of the server is always needed. So now, you have the ability to collect diagnostic information to improve the performance.
  • Performance is also improved in the startup of the application. 
  • Better experience of Exception Handling for Windows Store Applications.
  • Now you can return a value in the debugger. When you debug the application the Auto window displays the return type and value information for methods.
  • Managed Profile Guided Optimization Tool for optimize Windows Store Apps and Desktop apps also.
Multi-core JIT improvements
This feature was previously launched in .Net Framework 4.5. Microsoft extended this feature to work better in ASP.NET. Multi-core JIT has been extended to support dynamically loaded assemblies that exists in Assembly.LoadFrom. Multi-core JIT is enabled automatically for ASP.NET applications. The performance of ASP.NET is improved in .NET Framework 4.5.1 Preview with the Multi-core JIT improvements.
LOH Compaction
In the .Net Framework 4.5, Large Object Heap Fragmentation is released for the better use of free blocks. LOH Fragmentation is the enhancement of Garbage Collector. With the release of .NET Framework 4.5.1 Preview, the next logical step is taken by Microsoft which is LOH Compaction. You can now instruct the Garbage Collector to compact the LOH, either as a part of natural GC or forced GC. LOH Compaction is the solution of the issue but it is expensive and should only be used after significant performance analysis. The developer can't use this in the application every 5 minutes. If an application does not have the LOH Fragmentation issue then they do not want to use the LOH Compaction. It totally depends on them.   
ASP.NET Scaffolding
ASP.NET Scaffolding is a code generation framework for ASP.NET Web Applications. The Visual Studio 2013 Preview has pre-installed code generators for MVC, Web Forms and Web API Projects. Using ASP.NET Scaffolding the amount of time is reduced to develop standard data operations in the Web Development Projects. There are some following prerequisites for the ASP.NET Scaffolding:
  • Visual Studio 2013 Preview
  • Web Developer Tools
  • ASP.NET Web Framework and Tools
NuGet 2.6
With the release of Visual Studio 2013 Preview, NuGet released the 2.6 version. If you do not know what NuGet is then here is some information. When you use to install the NuGet package, it copies the library files and automatically updates projects that includes references, config file and so on. Microsoft also published a list for NuGet Packages that is helpful to discover the releases of NuGet packages. NuGet 2.6 released in Visual Studio 2013 Preview provides better support for the applications that directly depends on multiple versions of a single NuGet package. This support is only available for Desktop apps, not for Windows Store Apps or Windows Phone Apps.












Monday, 10 February 2014

New features in VB.NET 11 (.NET 4.5)

Unlike the release of VB.NET with .NET 4.0, the next release of VB.NET doesn’t have the anything like as many new features, which is almost certainly because the language is really maturing and a lot more parity has been achieved between C# and VB.NET.

Async

The big new feature for both languages is the introduction of the await/async keywords. I won’t go into detail here because they are covered in lots of other places (including the VB.NET team blog).

Yield

One if the freebees we get because of the Async feature is the Yield keyword. This has been a feature of C# for a long time, and although not massively useful, when you do need it, it can save you a lot of time. Let look at an example.

Imagine you have a function that takes an array of integers and returns an IEnumerable(Of Integer) containing the even numbers in that array (I know – completely contrived demo). The easiest way to do it would be to build a list and then return it once it is complete, for example:

Function GetEvens(numbers As Integer()) As IEnumberable(Of Integer) 
  Dim evenNumbers As New List(Of Integer)
  For Each number in numbers
    If number Mod 2 = 0 Then
      evenNumbers.Add(number)
    End If
  Next
  Return evenNumbers
End Function

With the Yield keyword we no longer need the List to hold the results, we can return them (yield them) as we find them, making our function look like this:

Function GetEvens(numbers As Integer()) As IEnumberable(Of Integer)
  For Each number in numbers
    If number Mod 2 = 0 Then
      Yield number
    End If
  Next
End Function

Global

The Global keyword has existed for a while to allow you to be explicit about which namespace you want. For example, assume you have this namespace in your project:

Namespace Acme.System.IO

If you have Imported the Acme namespace this line becomes ambiguous:

Dim dataFile As System.IO.File

The global keyword allows us to be explicit:

Dim dataFile As Global.System.IO.File

In the next version of VB.NET we will also be able to use the Global keyword in namespace declarations (for exactly the same purpose). Kind of minor, but useful when you need it.

Friday, 7 February 2014

Five Great .NET Framework 4.5 Features

Hi All,

You may want to check “Five Great .Nrt Framework 4.5 Features” by  Shivprasad Koirala on codeproject site.

www.codeproject.com/Articles/599756/Five-Great-NET-Framework-4-5-Features

Tuesday, 4 February 2014

Thoughts on Unit Testing

Yesterday I had a great conversation with one of my friend about few things one of them was Unit testing. He is a big proponent of Unit Testing. Good unit testing (see I did not write more unit testing) could  help identify and resolve the bugs in the code very early. This also helps code maintenance. I use unit testing where ever and when ever possible. I will not sit and break my head over how will I do unit test when I develop form over data patterns. On the flip side when you develop a program that involves some kind of logic that manipulate data then for sure you need to identify the components and test it.
This was one of my friend example, why would we need unit testing, lets assume _a and _b are variable and instead of doing if (_a == _b) if you would do it, if (_a = _b) then you have problem. If you would write an unit test for it, you will catch it early enough. On the side note, this condition will not even compile in C#, because compiler will complain, it can not convert integer to bool implicitly. Anyway, you got the point.
One very import point I want to make is how many unit test you write? Write enough to do good code coverage. If you have a method which takes bunch of parameters and you are asserting against some values, in older version of NUnit, you would write individual methods for each assertion. With latest version of NUnit you can write the single test and decorate it with all the assertion saves lots of code duplication. It also make code maintenance easy. So please check out latest version of NUnit.
If you are lazy or do not want to do unit test yet you need to do please your boss, here is a short cut, use Microsoft PEX. In this, you point a method and PEX will create all the possible scenario test cases with all possible input parameters.
Now that I am doing more and more Silver Light + RIA, I need to do more reading on how I can test the code good. Any of you are using testing for these platform, drop me a mail.