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.



Friday, 13 December 2013

Top 10 New Features in SQL 2012

 

Top 10 New Features in SQL 2012

Our new SQL 2012 just released. I get asked all the time why should I upgrade to the latest. There are 100’s of reasons with this one, I tried to pick the best 10. More info here: http://social.technet.microsoft.com/wiki/contents/articles/3783.what-s-new-in-sql-server-2012.aspx

1) AlwaysOn SQL Server Failover Cluster Instances

  • Multi-subnet failover clusters: A SQL Server multi-subnet failover cluster is a configuration where each failover cluster node is connected to a different subnet or different set of subnets. These subnets can be in the same location or in geographically dispersed sites. Clustering across geographically dispersed sites is sometimes referred to as Stretch clusters. As there is no shared storage that all the nodes can access, data should be replicated between the data storage on the multiple subnets. With data replication, there is more than one copy of the data available. Therefore, a multi-subnet failover cluster provides a disaster recovery solution in addition to high availability. For more information, see SQL Server Multi-Subnet Clustering.
  • Flexible failover policy for cluster health detection: In a SQL Server failover cluster instance, only one node can own the cluster resource group at a given time. The client requests are served through this node for that failover cluster instance. In the case of a failure, the group ownership is moved to another node in the failover cluster. This process is called failover. The improved failure detection introduced in SQL Server 2012, and addition of failure condition level property allows you to configure a more flexible failover policy. For more information, see Failover Policy for Failover Cluster Instances.
  • Indirect checkpoints: The indirect checkpoints feature provides a database-specific alternative to automatic checkpoints, which are configured by a server property. Indirect checkpoints implements a new checkpointing algorithm for the Database Engine. This algorithm provides a more accurate guarantee of database recovery time in the event of a crash or a failover than is provided by automatic checkpoints. To ensure that database recovery does not exceed allowable downtime for a given database, you can specify the maximum allowable downtime for that database.

2) Windows PowerShell


Starting with SQL Server 2012, Windows PowerShell is no longer installed by SQL Server Setup. Windows PowerShell 2.0 is a pre-requisite for installing SQL Server 2012. If PowerShell 2.0 is not installed or enabled on your computer, you can enable it by following the instructions on the Windows Management Framework page. For more information about SQL Server PowerShell, see SQL Server PowerShell.

SQL Server 2012 now uses the new Windows PowerShell 2.0 feature called modules for loading the SQL Server components into a PowerShell environment. Users import the sqlps module into PowerShell, and the module then loads the SQL Server snap-ins. For more information, see Run Windows PowerShell from SQL Server Management Studio.

The sqlps Utility is no longer a PowerShell 1.0 mini-shell; it now starts PowerShell 2.0 and imports the sqlps module. This improves SQL Server interoperability by making it easier for PowerShell scripts to also load the snap-ins for other products. The sqlps utility is also added to the list of deprecated features starting in SQL Server 2012.

The SQL Server PowerShell provider includes two new cmdlets: backup-sqldatabase and restore-sqldatabase. For more information, use the get-help cmdlet after loading in the sqlps module.

3) Data-tier Applications

  • The data-tier application (DAC) upgrade has been changed to an in-place process that alters the existing database to match the schema defined in the new version of the DAC. This replaces the side-by-side upgrade process, which created a new database with the new schema definitions. The Upgrade a Data-Tier Application wizard has been updated to perform an in-place upgrade. The Upgrade method of the DacStore type is now deprecated, and replaced with a new IncrementalUpgrade method. Upgrades are also supported for DACs deployed to SQL Azure. For more information, see Upgrade a Data-tier Application.
  • In addition to just extracting a schema definition as a new DAC package file, you can now export both the schema definition and data from a database as a DAC export file. You can then import the file to create a new database with the same schema and data. For more information, see Export a Data-tier Application and Import a BACPAC File to Create a New User Database.
  • Data-tier applications now support many more objects than in SQL Server 2008 R2. For more information, see DAC Support For SQL Server Objects and Versions.
  • Technorati Tags:

4) Server Modes for Analysis Services Instances: Multidimensional, Tabular, and SharePoint

This release adds a server mode concept to an Analysis Services installation. An instance is always installed in one of three modes that determines the memory management and storage engines used to query and process data. Server modes include Multidimensional and Data Mining, SharePoint, and Tabular. For more information, see Determine the Server Mode of an Analysis Services Instance

5) Integration Services Performance


Reduced Memory Usage by the Merge and Merge Join Transformations

Microsoft has made the Integration Services Merge and Merge Join transformations more robust and reliable. This is achieved by reducing the risk that these components will consume excessive memory when the multiple inputs produce data at uneven rates. This improvement helps packages that use the Merge or Merge Join transformations to use memory more efficiently.

Microsoft has also provided new properties and methods for developers of custom data flow components to implement a similar solution in their own components. This improvement makes it more feasible to develop a robust custom data flow component that supports multiple inputs. For more information, see Developing Data Flow Components with Multiple Inputs.

6) Answering the Need with (DQS) Data Quality Services


Data quality is not defined in absolute terms. It depends upon whether data is appropriate for the purpose for which it is intended. DQS identifies potentially incorrect data, and provides you with an assessment of the likelihood that the data is in fact incorrect. DQS provides you with a semantic understanding of the data so you can decide its appropriateness. DQS enables you to resolve issues involving incompleteness, lack of conformity, inconsistency, inaccuracy, invalidity, and data duplication.

DQS provides the following features to resolve data quality issues.

  • Data Cleansing: the modification, removal, or enrichment of data that is incorrect or incomplete, using both computer-assisted and interactive processes. For more information, see Data Cleansing.
  • Matching: the identification of semantic duplicates in a rules-based process that enables you to determine what constitutes a match and perform de-duplication. For more information, see Data Matching.
  • Reference Data Services: verification of the quality of your data using the services of a reference data provider. You can use reference data services from Windows Azure Marketplace DataMarket to easily cleanse, validate, match, and enrich data. For more information, see Reference Data Services in DQS.
  • Profiling: the analysis of a data source to provide insight into the quality of the data at every stage in the knowledge discovery, domain management, matching, and data cleansing processes. Profiling is a powerful tool in a DQS data quality solution. You can create a data quality solution in which profiling is just as important as knowledge management, matching, or data cleansing. For more information, see Data Profiling and Notifications in DQS.
  • Monitoring: the tracking and determination of the state of data quality activities. Monitoring enables you to verify that your data quality solution is doing what it was designed to do. For more information, see DQS Administration.
  • Knowledge Base: Data Quality Services is a knowledge-driven solution that analyzes data based upon knowledge that you build with DQS. This enables you to create data quality processes that continually enhances the knowledge about your data and in so doing, continually improves the quality of your data.

7) Replication Support for AlwaysOn Availability Groups


Replication supports the following features on Availability groups:

  • A publication database can be part of an availability group. The publisher instances must share a common distributor. Transaction, merge, and snapshot replication are supported.

In an AlwaysOn Availability Group an AlwaysOn secondary cannot be a publisher. Republishing is not supported when replication is combined with AlwaysOn.

Peer-To-Peer (P2P), bi-directional, reciprocal transactional publications, and Oracle Publishing are not supported.

  • A database that is enabled for Change Data Capture (CDC) can be part of an availability group.
  • A database enabled for Change Tracking (CT) can be part of an availability group.

Four new stored procedures provide replication support for AlwaysOn.

For more information about replication with AlwaysOn, see Configure Replication for AlwaysOn Availability Groups (SQL Server), Maintaining an AlwaysOn Publication Database (SQL Server), and Replication, Change Tracking, Change Data Capture, and AlwaysOn Availability Groups (SQL Server).

8) Power View


Power View, a feature of SQL Server 2012 Reporting Services Add-in for Microsoft SharePoint Server 2010 Enterprise Edition, is an interactive data exploration, visualization, and presentation experience. It provides drag-and-drop ad hoc reporting for business users such as data analysts, business decision makers, and information workers. Power View reports are in a new file format, RDLX.

Power View expands on the self-service BI capabilities delivered with PowerPivot for Excel and PowerPivot for SharePoint by enabling customers to visualize and interact with modeled data in a meaningful way, using interactive visualizations, animations, and smart querying. It is a browser-based Silverlight application launched from within SharePoint Server 2010 that enables users to present and share insights with others in their organization through interactive presentations.

Based on Tabular Models

With Power View, customers start from an SQL Server 2012 Analysis Services (SSAS) tabular model to build their reports. Tabular models use metadata to present an underlying data source to end users, with predefined relationships and behaviors, in terms they understand. For more information about tabular models, see What's New (Analysis Services) and Tabular Modeling (SSAS Tabular).

Coexists with Report Builder

Power View does not replace Report Builder, the report authoring tool for richly designed operational reports. Power View addresses the need for Web-based, ad hoc reporting. It co-exists with the latest version of Report Builder, which also ships in SQL Server 2012.

For more information, see the following:

Use Excel to Manage Master Data

You can now manage your master data in the Master Data Services Add-in for Excel. You can use this add-in to load a filtered set of data from your Master Data Services database, work with the data in Excel, and then publish the data back to the database. If you are an administrator, you can also use the add-in to create new entities and attributes. It is easy to share shortcut query files, which contain information about the server, the model, version, entity, and any applied filters. You can send the shortcut query file to another user via Microsoft Outlook. You can refresh data in the Excel worksheet with data from the server, refreshing either the entire Excel worksheet or a contiguous selection of MDS-managed cells in the worksheet. For more information, see Master Data Services Add-in for Microsoft Excel.

Match Data before Loading

Before adding more data to MDS, you can now confirm that you are not adding duplicate records. The MDS Add-in for Excel uses SQL Server Data Quality Services (DQS) to compare two sources of data: the data from MDS and the data from another system or spreadsheet. DQS provides suggestions for updating your data, along with the percent of confidence that the changes are correct. For more information, see Data Quality Matching in the MDS Add-in for Excel.

Load Data into MDS Using Entity-Based Staging

Loading data into MDS has become easier. You can now load all members and attribute values for an entity at one time. Previously you had to load members and attributes in separate batches. See Importing Data (Master Data Services).

10)SQL Server Install

  • Server Core Installation: Starting with SQL Server 2012, we can install SQL Server on Windows Server 2008 R2 Server Core SP1. For more information, see Install SQL Server 2012 on Server Core.
  • SQL Server Data Tools (Formerly called Business Intelligence Development Studio): Starting with SQL Server 2012, you can install SQL Server Data Tools (SSDT) which provides an IDE for building solutions for the Business Intelligence components: Analysis Services, Reporting Services, and Integration Services.

SSDT also includes “Database Projects”, which provides an integrated environment for database developers to carry out all their database design work for any SQL Server platform (both on and off premise) within Visual Studio. Database developers can use the enhanced Server Object Explorer in Visual Studio to easily create or edit database objects and data, or execute queries.

  • SQL Server multi-subnet clustering: You can now configure a SQL Server failover cluster using clustered nodes on different subnets. For more information, see SQL Server Multi-Subnet Clustering.
  • SMB file share is a supported storage option: System databases (Master, Model, MSDB, and TempDB), and Database Engine user databases can be installed on a file share on an SMB file server. This applies to both SQL Server stand-alone and SQL Server failover cluster installations. For more information, see Install SQL Server with SMB fileshare as a storage option.

Thursday, 31 October 2013

New features added in C# 5.0

C# most recent version 5.0 was released on August 15, 2012 with .NET Framework 4.5 and Visual Studio 2012.

There are two main features in C# 5.0 - Async Programming and Caller Information. Let's understand both these features in details as given below.

Async Feature (Asynchronous Methods)

C# 5.0 Async feature introduces two keywords async and await which allows you to write asynchronous code more easily and intuitively like as synchronous code. Before C# 5.0, for writing an asynchronous code, you need to define callbacks (also known as continuations) to capture what happens after an asynchronous process finishes. This makes your code and other routine task such exception handling complicated.

Both the keywords are used in a combination of each other. Hence, an await operator is applied to a one or more than one expressions of an async method. An async method returns a Task or Task<TResult> that represents the ongoing work of the method. The task contains information that the caller of the asynchronous method can use, such as the status of the task, its unique ID, and the method's result.

  1. public async Task<IEnumerable<Product>> GetProductList()

  2. {

  3. HttpClient client = new HttpClient();

  4. Uri address = new Uri("http://dotnet-tricks.com/");

  5. client.BaseAddress = address;

  6.  
  7. HttpResponseMessage response = await client.GetAsync("myservice/product/ProductList");

  8.  
  9. if (response.IsSuccessStatusCode)

  10. {

  11. var list = await response.Content.ReadAsAsync<IEnumerable<Product>>();

  12. return list;

  13. }

  14. else

  15. {

  16. return null;

  17. }

  18. }


Caller Information (Caller info attributes)


Caller Information can help you in tracing, debugging and creating diagnose tools. It will help you to avoid duplicate codes which are generally invoked in many methods for same purpose, such as logging and tracing.

You could get the following information of caller method:



  1. CallerFilePathAttribute


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



  2. CallerLineNumberAttribute


    Line number in the source file at which the method is called.



  3. CallerMemberNameAttribute


    Method or property name of the caller.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Example
  8. {
  9. static void Main(string[] args)
  10. {
  11. Console.WriteLine("Main method Start");
  12. InsertLog("Main");
  13. MyMethodB();
  14. MyMethodA();
  15. Console.WriteLine("Main method End!");
  16. Console.ReadLine(); // hold on result
  17. }
  18.  
  19. static void MyMethodA()
  20. {
  21. InsertLog("MyMethodA");
  22. MyMethodB();
  23. }
  24.  
  25. static void MyMethodB()
  26. {
  27. // some code here.
  28. }
  29.  
  30. static void InsertLog(string method)
  31. {
  32. Console.WriteLine("{0} called MyMethodB at {1}", method,
  33. DateTime.Now);
  34. }
  35. }
  36. /* Output:
  37. Main method Start
  38. Main called MyMethodB at 11/17/2013 11:12:24 PM
  39. MyMethodA called MyMethodB at 11/17/2013 11:12:24 PM
  40. Main method End!
  41. */

In both Main and MyMethodA, method InsertLog is invoked for logging. Now we can change the above code as follows.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Example
  8. {
  9. static void Main(string[] args)
  10. {
  11. Console.WriteLine("Main method Start");
  12. MyMethodB();
  13. MyMethodA();
  14. Console.WriteLine("Main method End!");
  15. Console.ReadLine();
  16. }
  17.  
  18. static void MyMethodA()
  19. {
  20. MyMethodB();
  21. }
  22.  
  23. static void MyMethodB([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
  24. {
  25. InsertLog(memberName);
  26. }
  27.  
  28. static void InsertLog(string method)
  29. {
  30. Console.WriteLine("{0} called MyMethodB at {1}", method, DateTime.Now);
  31. }
  32. }
  33.  
  34. /*Output:
  35. Main method Start
  36. Main called MyMethodB at 11/17/2013 10:30:11 PM
  37. MyMethodA called MyMethodB at 11/17/2013 10:30:11 PM
  38. Main method End!
  39. */


Hope you like these new features of C# 5.0.

Saturday, 24 August 2013

How to change the root password for MySQL in XAMPP?

By default, when you install XAMPP in your windows machine, the root password for the MySQL is set to empty. But this is not recommended, as the MySQL database without a password will be accessible to everyone. To avoid this, a proper/secure password must be set to the user root. To do it in XAMPP, there are two ways.

Method 1: reset XAMPP MySQL root password through web interface:

After you started your XAMPP server, go to the browser and type the URL http://localhost/security/ (incase you've modified XAMPP server port, you need to include that port number also in previous URL). The security page will be shown where you can change the root password for MySQL. This will update the phpMyAdmin config also.

Method 2: reset XAMPP MySQL root password through SQL update:


  1. Start the Apache Server and MySQL instances from the XAMPP control panel.
  2. After the server started, open any web browser and give http://localhost:8090/phpmyadmin/ (if you are running XAMPP on 8090 port). This will open the phpMyAdmin interface. Using this interface we can manager the MySQL server from the web browser.
  3. In the phpMyAdmin window, select SQL tab from the right panel. This will open the SQL tab where we can run the SQL queries.
  4. Now type the following query in the textarea and click Go
    UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; FLUSH PRIVILEGES;
  5. Now you will see a message saying that the query has been executed successfully.
  6. If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.
  7. Open the file [XAMPP Installation Path] / phpmyadmin / config.inc.php in your favorite text editor.
  8. Search for the string $cfg\['Servers'\]\[$i\]['password'] = ''; and change it to like this, $cfg\['Servers'\]\[$i\]['password'] = 'password'; Here the 'password' is what we set to the root user using the SQL query.
  9. Now all set to go. Save the config.inc.php file and restart the XAMPP server. 

Thursday, 18 July 2013

.Net c# parallel yield

yield is a very useful keyword in C# that allows you to create dynamic enumerators of stuffs without having to fill in a List<T> of things you want to return first. The generated code builds a state machine that will go forward, step by step, whenever the caller calls MoveNext on the IEnumerable it gets back (usually using foreach).


static void Main(string[] args)
{
    var input = new[] { "A", "B", "C" };
 
    Console.WriteLine(String.Join("\n", Process(input)));
}
 
static IEnumerable<string> Process(IEnumerable<string> input)
{
    if (input == null)
        throw new ArgumentNullException("input");
 
    foreach (var item in input)
    {
        yield return "Process " + item;
    }
}
 
// Output :
// Process A
// Process B
// Process C
 
The second really useful thing is Parallel.ForEach. Whenever you have to process loads of independent data that are CPU hungry you can launch the process in parallel and have it scheduled for you by the .NET runtime.

static void Main(string[] args)
{
    var input = new[] { "A", "B", "C" };
 
    Stopwatch w = new Stopwatch();
    w.Start();
    Process(input);
    w.Stop();
 
    Console.WriteLine("{0}s ", w.Elapsed.TotalSeconds);
}
 
static void Process(IEnumerable<string> input)
{
    if (input == null)
        throw new ArgumentNullException("input");
 
    Parallel.ForEach(input, item =>
        {
            // Something long
            Thread.Sleep(1000);
        });
}
 
// Output :
// ~ 1s although we had 3 stuffs that each took 1s
 
What if we could write that?

 
static void Main(string[] args)
{
    var input = new[] { "A", "B", "C" };
 
    Stopwatch w = new Stopwatch();
    w.Start();
    var result = Process(input);
    w.Stop();
 
    Console.WriteLine("{0}s ", w.Elapsed.TotalSeconds);
    Console.WriteLine(String.Join("\n", result));
}
 
static IEnumerable<string> Process(IEnumerable<string> input)
{
    if (input == null)
        throw new ArgumentNullException("input");
 
    Parallel.ForEach(input, item =>
        {
            // Something long
            Thread.Sleep(1000);
             
            // >>>> THE POWER !!
            yield return "Process " + item;
        });
}
 
But no we can’t because “The yield statement cannot be used inside an anonymous method or lambda expression“.
You obviously can’t mix those two pieces of magic together. In fact, if we could this would produce some of the weirdest bugs ever if something went wrong. But maybe we can’t build something that looks like it, for the sake of doing it?

static void Main(string[] args)
{
    var input = new[] { "A", "B", "C" };
 
    Stopwatch w = new Stopwatch();
    w.Start();
    var result = Process(input);
 
    Trace.WriteLine(String.Format("{0}s before enumerating", w.Elapsed.TotalSeconds));
    Trace.WriteLine(String.Format(String.Join("\n", result)));
    Trace.WriteLine(String.Format("{0}s after enumerating", w.Elapsed.TotalSeconds));
}
 
static IEnumerable<string> Process(IEnumerable<string> input)
{
    if (input == null)
        throw new ArgumentNullException("input");
 
    var workQueue = new ConcurrentQueue<string>();
    Exception workException = null;
    var completed = false;
 
    // This task will run on its side in another thread
    Task.Run(() =>
    {
        try
        {
            Parallel.ForEach(input, item =>
                {
                    // Something long
                    Thread.Sleep(1000);
 
                    // Push our results here
                    workQueue.Enqueue("Process " + item);
                });
        }
        catch (Exception ex)
        {
            // We don't want a crash to be lost in another thread
            // so we have to bring it back somehow on the main thread
            workException = ex;
        }
 
        completed = true;
    });
 
    // Not the most elegant, but it's just for fun so ...
    while (!completed)
    {
        string item;
        if (workQueue.TryDequeue(out item))
            yield return item;
        else
            Thread.Sleep(1); // remember, just for fun
    }
 
    // We don't want to lose the last items
    string finalItem;
    while (workQueue.TryDequeue(out finalItem))
        yield return finalItem;
 
    // Buble the exception if there's one
    if (workException != null)
    {
        throw new Exception("Error while doing stuffs", workException);
    }
}
Output:
0.00039s before enumerating
Process B
Process A
Process C
1.0398348s after enumerating
Notice than we did have an “yield behavior” as the processing was not executed on the call to Process, and how the whole process took 1s where it has 3 items that each took 1s. We also don’t have a reliable order anymore, it could have been any combination of B, A and C.