.NET 2015: C# 6

C# in its 6th version received its major change in the language engine “the compiler” along with many other little improvements in the language features

The new compiler “Roslyn”

C#/VB teams were working for years on the new compiler Roslyn, and here is why

What is wrong with the old compiler?
  • The old compiler is some sort of black box compilation without easy way to access the source code which makes live code analysis very difficult
  • Visual Studio provides build-time static code analysis only
  • Visual Studio popular extensions such as ReSharper uses its own compiler to provide live source code analysis and fixes
  • it is too difficult for developers to write code analyzers and fixers
Roslyn to the rescue
  • Roslyn is rewritten in C#, and open sourced on GitHub.com
  • It provides an API for developers to access its internals and services
  • It becomes too much easier to develop extensions for Visual Studio using the new compiler’s APIs such as Alive and SonarLint Visual Studio extensions
  • It enables building live code analyzers and fixers which do analysis on the code by reading from the buffer, and find patterns and suggest refactoring as you go
  • Developers can use Roslyn public API to ship analyzers and fixers along with their libraries to show guidance on how their library should be used
  • Visual Studio 2015 uses Roslyn API in order to bring productivity features while coding in C# and VB

Language Improvements

The driving philosophy in the development of C# 6 was to build many small improvements almost syntactical to make every day code easier and lesser. In previous versions C# introduced some big language features such as LINQ and Dynamic Capabilities 

Below are the 2 features I liked most. For the full list of C# 6 new features read C# 6 new features article on Roslyn Wiki

Null Conditional Operator

This code

var managerName = (employee != null 
                   && employee.Department != null 
                   && employee.Department.Manager != null) 
                   ? employee.Department.Manager.Name : null;

In C# 6 it can be

var managerName = employee?.Department?.Manager?.Name;
String Interpolation

This code

var firstName = "First";
var lastName = "Last";
var fullName = string.Format("Full name is {0} {1}", firstName, lastName);

In C# 6 it can be

fullName = $"Full name is {firstName} {lastName}";

If you prefer videos over reading you can watch What’s New in C# 6

.NET 2015: Free Developer Tools

In this post I am going to mention some free development tools and services offered by Microsoft which help .NET developers to set up their development environment from IDE to Version Control to Work Planning to Build and finally deployment

Visual Studio Community

  • Free full-featured IDE with support for all different kinds of applications supported by the enterprise version of Visual Studio 2015
  • Visual Studio Community supports all extensions (aka. plugins) including non-Microsoft extensions. Extensions can be found in Visual Studio Gallery.
  • It can be used by Individual developers or team of 1-5 developers to develop commercial software.
  • It can be downloaded from here
  • I recommend to use Web Essentials 2015 extension for its features for web development

Visual Studio Code

  • Free, cross-platform and lightweight code editor which can be used to develop ASP.NET 5 and Web applications on Windows, Linux and Mac OSX
  • It can be download from here
  • Visual Studio Code built on Electron  which enables development of cross platform desktop applications using web technologies

Team Foundation Server Express (TFS)

  • TFS Express is ALM tool with features such as Version control, and Plan and track your projects’ work using agile tools
  • It can be installed on the developer’s machine
  • Free for individuals and teams of five members or less
  • It can be downloaded from here

Visual Studio Online (VSO)

  • Visual Studio Online is the cloud/online version of Team Foundation Server
  • Free for up to 5 users
  • TFS & VSO have three access levels (Stakeholder, basic, and Advanced)
  • Stakeholder users are free of charge with no limit, although they can add/modify work items and view dashboards

Microsoft Azure

  • Azure is a cloud based Platform as a Service (PAAS) with services such as applications, databases, virtual machines and more
  • Developers can host up to 10 web, mobile, and API applications for free

SQL Server Express

Finally, If you are looking for free training on Microsoft and Web Technologies, have a look at Microsoft Virtual Academy and Channel9

Hopefully, this post helps developers to get started quickly with .NET Platform

In the coming post, I will talk about some new changes in C# I found interesting and cool

 

.NET 2015: The Platform and The Openness

The world of .NET Platform has witnessed a lot of changes and enhancements in its 2015 version which span a wide variety of  areas.

This post is the first in a series where I am going to write about what I found important for every .NET web developer to know about .NET 2015.

First off, as a .NET developer since version 2, I really appreciate that Microsoft .NET Team has embraced principles such as free tools, open source, cross platform, and incorporating non-Microsoft stuff.

The following list of short notes is a summary of the major changes in the platform, at least as I understand it so far :), so please don’t hesitate to write a comment if there is something wrong or missing

  • .NET 2015 released with 2 different editions of the framework, the full .NET Framework with version 4.6 which is the normal upgrade of the previous 4.5 version, the second is what so-called .NET Core 5 which is a lightweight, modular, and cross-platform run-time
  • With .NET Framework 4.6, developers can build all kinds of applications from web to mobile to desktop with full access to everything .NET platform offers
  • .NET Core enables currently running ASP.NET and console applications on other operation systems such as Mac and Linux with the ability to be ported to more platforms by Microsoft and the community in future
  • .NET Core runs on the .NET Framework, .NET Core and Mono
  • .NET Core is growing over time as more libraries and functionalities are being ported from .NET Framework
  • All of the .NET Core libraries are distributed as NuGet.org packages
  • ASP.NET 5 is built on top of .NET Core and runs on the full framework
  • ASP.NET 5 is modular, optimized for the cloud and cross-platform (runs on Windows, OS X, and Linux), and can be deployed as a self-contained package which doesn’t depend on the full system-wide framework
  • ASP.NET 5 comes with MVC 6, C# only (No Visual Basic), and No Web Forms
  • ASP.NET 5 comes with its built-in Dependency Injection
  • MVC 6 is a unified programming model of MVC, Web API, and Web pages
  • ASP.NET Web Forms 4.6 and MVC 5 are supported only in the full framework
  • C# and VB got a new compiler “Roslyn” which is completely rewritten in C#
  • Roslyn compiler is open sourced on GitHub where C# developers can explore and contribute to the project
  • Visual Studio Code is a lightweight IDE developed by Microsoft to support developing ASP.NET 5 Web Apps on Mac and Linux as well as Windows along with other technologies such as NodeJS
  • The Garbage Collector got a significant performance update

Some links for further reading:

What’s New in the .NET Framework

Announcing .NET 2015 Preview: A New Era for .NET

Introducing ASP.NET 5

Top 10 Changes in ASP.NET 5 and MVC 6

in the next post I will talk about the free developer tools offered by Microsoft

Customizing file upload element by using associated label workaround

Today I got a defect to fix which is “File Upload functionality is not working  when using IE9”. Oh IE9 again!!.

I just wanted to show a nice and consistent UI for file input element and as there is no standard way to customize it with my own text and look, I used a button to trigger the file input’s click event and made file input hidden by setting its height and width to zero as you can see at the below code sample:

<a href="#" onclick="showFileUpload()">Click to choose file</a>

<input type="file" id="fileUpload" style="height:0; width:0;"/>
<script>
    var showFileUpload = function() {
        document.getElementById("fileUpload").click();
    };
</script>

Also here is jsFiddle

That is working in every browser but not in IE9. After some investigation I found that “Access is denied” exception is raised by IE9 when calling file input’s click from JavaScript!!

Why this happens? It is bug in IE9 as it should only prevent developer’s code from changing the content of the file input (which file to upload should be chosen through browse dialog by the user) and that seems a nice security feature but not preventing invoking other functions like click.

The issue as follows IE9 catches file input’s click invocations in JavaScript code as security breach!!

I tried to find out another workaround to get the same result. I ended up using associated label for file input in order to fire its click event and show the files browse dialog.

That is enabled because of the default behavior of labels and their associated controls. If the user clicks on a label its control’s click event will be fired. Seems nice? yes it is. It did the trick for me :)

Here is the code for using a label to customize file input:

<label for="fileUpload">Click to choose file</label>
<input type="file" id="fileUpload" style="height:0; width:0;"/>

jsFiddle is here

ASP.NET AJAX Control Toolkit HTMLEditorExtender issue when in modal popup in IE 7

Over again, supporting IE7 is a nightmare. Today I have been assigned to a defect says “When user enters long text and words in text editor in modal popup using IE7, the whole page/window horizontal scroll bar appeared and get wider as the user typing”.

I used AJAX Control Toolkit HTMLEditorExtender to provide simple formatting options when user enters text information. It is working as expected in IE8 & IE9, but in IE7 when HTMLEditorExtender used with Multiline TextBox in modal popup, it behaves in a weird way as described above.

I fixed this issue by using the below style to override the HTMLEditorExtender default style.

.ajax__html_editor_extender_texteditor
{
 word-wrap: break-word !important;
 height: 60px !important;
}
.ajax__html_editor_extender_container
{
 overflow: auto !important;
 height: 100px !important;
}

Note: !important and Height are not a must to fix this issue, but I used !important to enforce the style if other styles are there and Height to hide the scroll vertical bar until the text gets bigger than the input box.

Page.MaintainScrollPositionOnPostBack issue in IE 7 when nested GridViews used

As the page’s content becomes bigger and bigger like the one I am working on currently, specific features are more critical than others. In such case we may need to apply performance and user experience techniques such as content lazy loading, partial content updating, and maintain page’s scroll position cross requests, and more …

I am concerned here about the last one – Maintain Scroll Position. fortunately, ASP.NET Page.MaintainScrollPositionOnPostBack when set to true, the required JavaScript code will be generated to do the job. and that’s just works great for most if not all browsers including Internet Explorer 7.

However, I faced a weird issue when firing any post-back request in nested GridViews (GridView in another GridView) in UpdatePanel using IE 7 only, the scroll position reset to zero and Page.MaintainScrollPositionOnPostBack simply stop to do the magic!

After investigation and debugging, I got to know where is the problem to fix but not the root cause behind this behavior. Is it IE 7 problem or the generated JS code missed a behavior that IE 7 still using?.

The decision was not to use Page.MaintainScrollPositionOnPostBack, and write my own solution. I ended up with the below script in which written using jQuery and jquery.cookie.js plugin.

The cookie is used to store the value of window’s scrollTop every time the scroll position changed via jQuery window.scroll event. And then set window’s scrollTop back to the stored value in the cookie when both a new AJAX request initialized or ended.

I did not test the below code enough, so please don’t hesitate to put your comments

 
    <script src="Scripts/jquery.cookie.js"></script>
    <script type="text/javascript">

        var scrollTopValue;
        var scrollPositionCookie = "scrollTopValue";
        $.cookie(scrollPositionCookie, $(window).scrollTop(), { expires: 10 });

        $(document).ready(function () {

            var smgr = Sys.WebForms.PageRequestManager.getInstance();

            smgr.add_initializeRequest(function () {

                scrollTopValue = $(window).scrollTop();
                if (scrollTopValue == 0) {

                    scrollTopValue = $.cookie(scrollPositionCookie);
                    $(window).scrollTop(scrollTopValue);
                }
                else {
                    $.cookie(scrollPositionCookie, scrollTopValue);
                }
            });

            smgr.add_endRequest(
                function () {

                    if (scrollTopValue == 0) scrollTopValue = $.cookie(scrollPositionCookie);
                    $(window).scrollTop(scrollTopValue);
                }
            );


            $(window).scroll(function () {

                scrollTopValue = $(window).scrollTop();
                if (scrollTopValue != 0) {
                    $.cookie(scrollPositionCookie, scrollTopValue);
                }
            });


        });

    </script>

Hide export format in RDLC/SSRS Report Viewer control

I recently needed to hide or disable PDF format in Export Formats dropdown list displayed in SSRS ReportViewer’s toolbar in Local Report mode.

Unfortunately, ReportViewer control has no method or property to manage specific format’s visibility and this is true also for the recently released Report Viewer 10.

We can use Report Viewer’s property ShowExportControls to hide the export formats dropdown list but not a specific format such as PDF.

In Local Report mode, there are 2 export formats (Excel and PDF) and more Rendering Extensions for Server Report mode are available.

We have the option to hide export formats control and implement our own list. this article might help on this.

Finally, I ended up with adding new extension method SetExportFormatVisibility to ReportViewer control which uses private Reflection to disable/enable export formats.

This method is inspired by Stephen Songer’s blog post Disable/Enable export format in SSRS and ASP.NET.

The code consists of two parts, one is ReportViewerExtensions class which has SetExportFormatVisibility extension method and the second is ReportViewerExportFormat Enum to specify available export formats.

public static class ReportViewerExtensions
 {
 public static void SetExportFormatVisibility(this ReportViewer viewer, ReportViewerExportFormat format, bool isVisible)
 {

 string formatName = format.ToString();

 const System.Reflection.BindingFlags Flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;
 System.Reflection.FieldInfo m_previewService = viewer.LocalReport.GetType().GetField("m_previewService", Flags);

 System.Reflection.MethodInfo ListRenderingExtensions = m_previewService.FieldType.GetMethod("ListRenderingExtensions", Flags);
 object previewServiceInstance = m_previewService.GetValue(viewer.LocalReport);

 IList extensions = (IList)ListRenderingExtensions.Invoke(previewServiceInstance, null);
 System.Reflection.PropertyInfo name = extensions[0].GetType().GetProperty("Name", Flags);

 //object extension = null;
 foreach (var ext in extensions)
 {

 if ((string.Compare(name.GetValue(ext, null).ToString(), formatName, true) == 0))
 {
 System.Reflection.FieldInfo m_isVisible = ext.GetType().GetField("m_isVisible", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

 System.Reflection.FieldInfo m_isExposedExternally = ext.GetType().GetField("m_isExposedExternally", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
 m_isVisible.SetValue(ext, isVisible);
 m_isExposedExternally.SetValue(ext, isVisible);

 break;
 }

 }
 }

 }

 public enum ReportViewerExportFormat
 {
 Excel,
 PDF
 }

Simple to use..

 ReportViewer1.SetExportFormatVisibility(ReportViewerExportFormat.PDF, false);