Dailycode.info

Short solution for short problems

ASP.NET: app_offline.htm takes your site offline

When deploying to a site, you want to show a nice message like, working on the site untill 12 PM or something.
You can do this several ways, one way is to add to the deploy script a drop of the file app_offline.htm into the root of your site. This will send all incoming request to this file. 
When the deploy is finished, simply remove it again!

IIS: What triggers recycle of a website in IIS?

A colleague and me where thinking about this, because we were copying files to the root directory of the web site. But no worries, this doesn't trigger a recycle. What does trigger a recycle?


Trigger Immediate Recycle

  • Web.config changes
  • Machine.config changes
  • Global.asax changes
  • Bin directory changes
  • App_Code changes

Tech: My Techorama 2015 review

1.           ASP.NET 5

1.           ASP.NET 5

A session on the new ASP.NET 5. A lot of overlapping information. New features of visual studio 2015. This session also confirms that WEB API is the way to go in the future.

Here is a summary of the foundational improvements:

  • New light-weight and modular HTTP request pipeline
  • Ability to host on IIS or self-host in your own process
    • Showed in the session, you can host is from command line on USB stick.
  • Built on .NET Core, which supports true side-by-side app versioning
  • Ships entirely as NuGet packages
    • Not part of the System.Web.dll anymore.
  • Integrated support for creating and using NuGet packages
  • Single aligned web stack for Web UI and Web APIs
  • Cloud-ready environment-based configuration
  • Built-in support for dependency injection
  • New tooling that simplifies modern Web development
  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
  • Open source and community focused

 

2.           The internet of your things (Iot)

Mainly about Azure and the capabilities to host applications on Azure. Interesting was the table storage. You can create a table service where different types of data can be stored in 1 table. It’s a no SQL datastore. This is ideal for storing structured non relational data.

Link to this:

https://azure.microsoft.com/en-gb/documentation/articles/storage-dotnet-how-to-use-tables/

 

3.           How to live longer and happier with Visual Studio 2015

This session was about the new features of Visual Studio 2015.

You can see that a lot of resharper functionality is now default in VS 2015.

Also integration with a BOWER, Gulp and Grunt are used very frequenly. For packages like AngularJS, bower is better than NuGet.

http://www.dotnetcurry.com/visualstudio/1096/using-grunt-gulp-bower-visual-studio-2013-2015

 

 

4.           EF7, Who are You and What Have You Done With My ORM?

Julie Lerman who gave the session is an expert on EF. She wrote books and gives trainings about it. Her conclusion in regard with the silver bullet key note is that the best way to go for the future is:

-       Keep using EF 6.0 in existing projects.

-       Start using EF 7.0 in new projects.

EF7 is a complete makeover of the entity framework. Since the start of EF they continued on the same code base. For EF7 they restarted completely from the beginning, to make it more light weight and also to tackle some challenges that were not possible to take with the old code base.

 

5.           "Write once, run anywhere”: Can AngularJS & Cordova do it?

This was definitely my favorite session. Christian Weyer explained in 1 hour and 30 min the complete lifecycle of a modern app that has 1 code base but can be published in any device!

 

He is co-owner of thinktecture that tackle very large implementations using .Net back-end, HTML5 and Javascript to code once, deploy anywhere.

 

Their code base is EF --> .Net WEB API --> AngularJS.

Using Cordova they can deploy the code to native iOS, Android and Windows Phone.

Then the AngularJS is also available in any browser and can even be build to native Apps for Windows and Mac OS.

 

6.           "It's alive!": Real-time applications with ASP.NET SignalR and AngularJS

Again a great session by Christian Weyer. SignalR is definitely something to look into. Very brief it’s a way to let the server communicate to the clients. E.g. when some data is updated and the clients need to refresh without the user having to click on a refresh button.

More info:

http://signalr.net/

 

7.           HTML 5 Security

This session was mainly about CORS and ways that javascript could inject bad code. If setup the code in the correct way, you could prevent this.

 

8.           Aurelia Deep Dive

This session was about an alternative to AngularJS. Another javascript framework. The demo were not impressive, some failed. I do not believe in Aurelia, since the community behind it is not comparable with AngularJS.

 

9.           Domain Driven Design for the Database Driven-Mind

Another view on application architecture. This looks promising, but at the moment not feasible because lack of knowledge and high impact on development. Also we are in a process of change that first need to be advanced.

 

10.        The Engaging User Experience & the Natural User Interface

Key note about user experience. Not very interesting. Talking a lot about xbox Kinect and face recognition.

 

11.        Chrome developer tools

Here is a good summery made by one of the attendees:

The Console tab

It’s probably safe to assume that you all know and use the Console Tab of Google Chrome to write your debug statements and evaluate JavaScript expressions. Most of the time we do that by using “console.log” statement which writes your logging messages to the console. If you are using a lot of those “console.log” statements in your code then things can quickly get messy and it will become difficult to work through your logs to find the one line you actually need.

To organize your statements you can use “console.groupCollapsed” and “console.groupEnd”. These functions will create a collapsable group in the log window so you can find your debug lines faster.


If you want to measure how fast your code is executing you can use “console.time” and “console.timeEnd”. This can also prove quite handy when you want to benchmark certain functions.


Device Emulation

The Device Emulator enables you to test out your website on several devices (phones, tablets, computers…) and on different network speeds (4G, 3G, GPRS…). This makes it very easy to test out your responsive design. The emulator even supports touch events!

You can enable/disable it by toggling the device icon Chrome Dev Tools - Mobile Iconin your Dev Tools.


The Network tab

The Network tab is used to monitor the performance of your application and helps you identify slow loading resources. It includes detailed timing data, HTTP request and response headers, cookies…

A very useful feature of the Network tab is that you can download its contents to a .HAR file. This could help us debug the “unreproducible bugs” reported by a QA Engineer. If he’s doing his tests with the Network tab opened he can just send the failed requests to a developer to investigate. All he has to do is right-click the network table and select “Save as HAR with Content”. This will download a .HAR-file that can be read using a tool called Chrome HAR Viewer.

Quick tips

Inline editing

To enable inline editing just open up the console and type “document.body.contentEditable = true” and press ENTER. You can now modify any text on your page by just typing into the browser window. If you have to build a multilingual application you can use this to easily test what would happen if the text in your title or menu items would be translated (and thus be longer or shorter than intended by the designer).

Blackbox scripting

You all know that you can debug javascript code by adding breakpoints to your code in the “sources tab”. Very often this tab includes a lot of scripts that you don’t care about (external libraries etc.). You can prevent the debugger from breaking in those scripts by “blackboxing” them. Just right-click on the file and select “Blackbox Script”. You can stop blackboxing a script by right-clicking the same file and selecting “stop blackboxing”.

Styling log statements

You can add CSS styling to your “console.log” statements. This can prove useful if you want something to stand out if it occurs.


Conclusion

Please note that this blogpost is just a high level overview of useful and time saving features that were presented by Shay Friedman (@ironshay) at Techorama. The Google Chrome dev tools contain a lot more functionality than what can be covered here. If you are curious to learn more or want to read on about the topics covered in this post you can visit https://developer.chrome.com/devtools.

 

12.        Decomposing AngularJS

This was an interesting session that gave a deeper view of how the AngularJS binding works. He actually created a fresh JavaScript Framework from scratch (using code blocks and copy paste) that bound model to the view.

 

13.        EF7 demo demo demo

This was a replacing session were Julie showed EF 7 in combination with ASP.NET 5 in action.


HTTP Error 500.19 - Internal Server Error

After getting a latest version of the source files of my web project I got this error:

HTTP Error 500.19 - Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid.

The solution was to set the application pool to network identity and provide this user read access to the files of my web site.


JSON & EF: Error Self referencing loop detected for type System.data.entity occurs .

I got this error when I started to add the navigation properties to the entities. Because a master detail relation has got 2 kinds of navigation properties. The master gets the collection of childs and the child gets the master where it belongs to. JSON serialization will end up in a circular loop, since it serializes the child, then tries to serialize the parent, but this has a collection of child etc.

You can solve this many ways.

- If you do not need the parent navigation property, you can remove it. 

- You could set an attribute to the property: [JsonIgnore] [IgnoreDataMember]. The problem here is when you use the generated classes, the next time you generate it will be removed.

- Set lazy loading on your context to false: db.Configuration.LazyLoadingEnabled = false;

In my case I chose the first one, since the parent did not need to know about it's children.  


.Net: Ajax UpdatePanel causes DevExpress Controls to lose style after post

In my web application, I had a dev express gridview with a detail grid view. It was not so nice to see the form post backing after every click in the master grid, so I decided to use the ajax update panel.

The grid looks like this:

But after the first click the form looked like this:

The problem was apparently devexpress tries to edit the header of the page adding the style sheets links, so adding the runat="server" to your page header fixes this problem. In my case I had to add this to the master page and remove some <% tags in the header.

 <head runat="server">


.Net Web API and querystrings

 

Creating a web api is very easy and powerfull. If you want to use querystrings, its not done with the ols Request.Querystrings, but rather like this:

publicIEnumerable<GALV_ACCOUNT> GetAllAccounts()

{

    var q = Request.GetQueryNameValuePairs().Where(nv => nv.Key =="q").Select(nv => nv.Value).FirstOrDefault();

    if (q != null && q != string.Empty)

    {

        var result = accounts.Where(a=>a.Name.ToLower().StartsWith(q.ToLower()));

        return result;

    }

    else

    {

        thrownewException("Please specify a search query");

    }

}

Then you can call the method like this:

http://myserver/Accounts?q=p

 


Serialized SOAP has some records empty and set to reference another.

Since I have a .Net back end WCF service and a front end iOS consumer, I have tackled several new challenges and learned a lot of what SOAP is all about. The next strange thing I encountered and it took me an hour or 2 to find out the solution was:

On my iOS client I suddenly got 15 records, where 7 of then were just empty records. I could not find the reason, on the server SQL all records were there and all records were filled in and unique. Then I took a closer look to the incoming SOAP message and found out that there were 7 records that looked like this:

<a:GP_MES_SetOrderPosReadyHistory xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Ref="i1"/>

So no contents only an empty xml tag with at the end z:Ref="i1". Soon I discovered that it was referencing a record that was found earlier in the XML with the same keys. So strange, because the rest of the item was different. At this website I found out that settings the IsReference property on the data contract creates this behavior. So one thing you could do is to set it to false. In my case the data contracts were generated by self tracking entities. So I discovered that I had to adjust the key fields of the entities. In my case it was on a view and the key fields were not unique for each records. So I added an extra field to the key fields and now it works perfect.


Drop tables procedure for .Net and MS SQL

I wrote a simple procedure that will drop tables in a database that have a certain prefix. 

First I initiate the process layer:

MESCockpitProcessLayer.DirectDataAccess pl = new MESCockpitProcessLayer.DirectDataAccess();

Then I will fill a dataset with the following statement:

//This script will get all tables with the selected prefix and generates a drop statement. I load it in a dataset, each drop statement

//is a row

string DropTableString = "SELECT 'DROP TABLE ' + TABLE_NAME + ' ' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'GP_MES%'";

DataSet ds = pl.GetDataSet(new StringBuilder(DropTableString), serverName, DBName, DBUserName, DBUserPWD);

Next I simply go over each row in the dataset table and execute the statement:

if (ds != null)

{

    foreach (DataRow table in ds.Tables[0].Rows)

    {

        //Drop the table using the generated script

        pl.ExecuteQueryDirect(new StringBuilder(table[0].ToString()), serverName, DBName, DBUserName, DBUserPWD);

    }

}


The generated statement look like this:

DROP TABLE EventLog 

The data class that gets the data and executes the SQL statements is just the very simplest using the Data.SqlClient:

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace MESCockpitDataLayer.SqlClient

{

    publicclassMESDataAccess

    {

        publicstaticint ExecuteNonQuery(StringBuilder sb, string connectionString)

        {

            SqlConnection conn = null;

            SqlCommand executeCommand = null;

            //SqlTransaction MyTrans = null;

            try

            {

                conn = newSqlConnection(connectionString);

                conn.Open();

 

                executeCommand = newSqlCommand(sb.ToString(), conn);

                return executeCommand.ExecuteNonQuery();

            }

            catch (Exception er)

            {

                //Handle exception.

                throw er;

            }

        }

 

        publicstaticobject ExecuteScalar(StringBuilder sb, string connectionString)

        {

            SqlConnection conn = null;

            SqlCommand executeCommand = null;

            //SqlTransaction MyTrans = null;

            try

            {

                conn = newSqlConnection(connectionString);

                conn.Open();

 

                executeCommand = newSqlCommand(sb.ToString(), conn);

                return executeCommand.ExecuteScalar();

            }

            catch (Exception er)

            {

                //Handle exception.

                throw er;

            }

        }

 

        publicstaticDataSet GetDataSet(StringBuilder sb, string connectionString)

        {

            SqlConnection conn = null;

            SqlCommand executeCommand = null;

            SqlDataAdapter MyDataAdapter = null;

            DataSet returnDS = newDataSet();

            try

            {

                MyDataAdapter = newSqlDataAdapter();

               

                conn = newSqlConnection(connectionString);

                conn.Open();

 

                executeCommand = newSqlCommand(sb.ToString(), conn);

                MyDataAdapter.SelectCommand = executeCommand;

               

                MyDataAdapter.Fill(returnDS);

                return returnDS;

            }

            catch (Exception er)

            {

                //Handle exception.

                throw er;

            }

        }

    }

}

 


Translate your ASP.Net page

A really simple and quick solution is the one we use here for some websites that need to be multi langual and where the tranlations are loaded in the database.

All pages that need translation inherit from a custom Page control. In this control we browse iterative through the page's child controls. We check for certain types of controls and the take the delivered text and tranlate it. The text provided on the controls will be the ID that is used to get the translation from the database. I use a "_" before the text if it needs to be translated, just to keep it flexible.

Here the code of the custom page object:

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using DevExpress.Web.ASPxGridView;

using GalvaSFIMobile.GlobalFunctions;



namespace My.Controls

{

    public class MyPage : Page

    {

        protected override void OnPreRender(EventArgs e)

        {

            //TranslateControls

            TranslateControls(this);

            base.OnPreRender(e);

        }



        private void TranslateControls(Control cont)

        {

            foreach (Control c in cont.Controls)

            {

                //Check if the control is a text control.

                if (c.GetType() == typeof(Label))

                {

                    //translate label

                    if (((Label)c).Text.StartsWith("_"))

                    {

                        ((Label)c).Text = Globalfunctions.GetTranslation(((Label)c).Text);

                    }

                }

                else if (c.GetType() == typeof(DevExpress.Web.ASPxEditors.ASPxLabel))

                {

                    //translate button

                    if (((DevExpress.Web.ASPxEditors.ASPxLabel)c).Text.StartsWith("_"))

                    {

                        ((DevExpress.Web.ASPxEditors.ASPxLabel)c).Text = Globalfunctions.GetTranslation(((DevExpress.Web.ASPxEditors.ASPxLabel)c).Text);

                    }

                }

                else if (c.GetType() == typeof(DevExpress.Web.ASPxEditors.ASPxButton))

                {

                    //translate button

                    if (((DevExpress.Web.ASPxEditors.ASPxButton)c).Text.StartsWith("_"))

                    {

                        ((DevExpress.Web.ASPxEditors.ASPxButton)c).Text = Globalfunctions.GetTranslation(((DevExpress.Web.ASPxEditors.ASPxButton)c).Text);

                    }

                }

                else if (c.GetType() == typeof(Button))

                {

                    //translate button

                    if (((Button)c).Text.StartsWith("_"))

                    {

                        ((Button)c).Text = Globalfunctions.GetTranslation(((Button)c).Text);

                    }

                }

                else if (c.GetType() == typeof(RadioButtonList))

                {

                   //translate listitem

                   

                    foreach (ListItem a in  ((RadioButtonList )c).Items )

                    {

                        if (((ListItem)a).Text.StartsWith("_"))

                        {

                            ((ListItem)a).Text = Globalfunctions.GetTranslation(((ListItem)a).Text);

                        }

                    }

                }

                else if (c.GetType() == typeof(RequiredFieldValidator))

                {

                    if (((RequiredFieldValidator)c).ErrorMessage.StartsWith("_"))

                    {

                        ((RequiredFieldValidator)c).ErrorMessage = Globalfunctions.GetTranslation(((RequiredFieldValidator)c).ErrorMessage);

                    }

                }

                else if (c.GetType() == typeof(ValidationSummary))

                {

                    if (((ValidationSummary)c).HeaderText.StartsWith("_"))

                    {

                        ((ValidationSummary)c).HeaderText = Globalfunctions.GetTranslation(((ValidationSummary)c).HeaderText);

                    }

                }

                else if (c.GetType() == typeof(RegularExpressionValidator))

                {

                    if (((RegularExpressionValidator)c).ErrorMessage.StartsWith("_"))

                    {

                        ((RegularExpressionValidator)c).ErrorMessage = Globalfunctions.GetTranslation(((RegularExpressionValidator)c).ErrorMessage);

                    }

                }

                else if (c.GetType() == typeof(ASPxGridView))

                {

                    foreach(GridViewColumn col in ((ASPxGridView)c).Columns)

                    {

                        if (col.Caption.StartsWith("Grid."))

                        {

                            col.Caption = Globalfunctions.GetTranslation(col.Caption);

                        }

                    }

                }

                if (c.HasControls())

                {

                    TranslateControls(c);

                }

            }

        }

    }

}

The Globalfunctions.GetTranslation(string trans); function simply gets the translation from the database. Make sure that you cache your translations! Because else the translation of the page will result in a delay. I use the entity framework in combination with the singleton pattern to cache the translation entities. Its working very good.