Dailycode.info

Short solution for short problems

Passing objects in methods by ref or not....

public void Foo(Image image)
{
    // This change won't be seen by the caller: it's changing the value
    // of the parameter.
    image = Image.FromStream(...);
}

public void Foo(ref Image image)
{
    // This change *will* be seen by the caller: it's changing the value
    // of the parameter, but we're using pass by reference
    image = Image.FromStream(...);
}

public void Foo(Image image)
{
    // This change *will* be seen by the caller: it's changing the data
    // within the object that the parameter value refers to.
    image.RotateFlip(...);
}
Source: Stackoverflow

Write HTML content to file

Not so very hard. The only tricky part is when there are IFrames on the page.

string
html;
using (WebClient client = new WebClient())
{
    client.UseDefaultCredentials = true;
    html = client.DownloadString("http://dailycode.info/dailycardgames/#/home");
    using (FileStream fs = new FileStream(@"d:\temp\files\test" + DateTime.Now.Ticks.ToString() + ".htm", FileMode.OpenOrCreate))
    {
        using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
        {
            w.WriteLine(html);
        }
    }
}

Then I noticed that in my page (not the one from the example above) there were iframes. And they were not loaded. 

So I had to also download the iframes, save them to a file and replace the url of the iframe to the url of the file.

Also I noticed that for example the umlaut ö was not shown correctly, so I had to include the UTF8 encoding in the download as well as in the file writer:

At the end it looked like this:

string html;
using (WebClient client = new WebClient())
{
    client.UseDefaultCredentials = true;
    client.Encoding = Encoding.UTF8;
    html = client.DownloadString("http://dailycode.info/dailycardgames/#/home");
 
    MatchCollection iframes = Regex.Matches(html, "<iframe.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase);
           
    int i = 0;
    foreach (Match m in iframes)
    {
        string url = m.Groups[1].Value;
        string iframe = client.DownloadString("http://dailycode.info/dailycardgames/" + url);
        iframe = iframe.Replace(@"../../images", @"D:\temp\images");
        var iframehtml = @"d:\temp\files\testiframe_"+i+"_" + DateTime.Now.Ticks.ToString() + ".htm";
        using (FileStream fs = new FileStream(iframehtml, FileMode.OpenOrCreate))
        {
            using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
            {
                w.WriteLine(iframe);
            }
        }
 
        html = html.Replace(url, iframehtml);
        i++;
    }
}
           
html = html.Replace(@"../images", @"D:\temp\images");
           
using (FileStream fs = new FileStream(@"d:\temp\files\test" + DateTime.Now.Ticks.ToString() + ".htm", FileMode.OpenOrCreate))
{
    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
    {
        w.WriteLine(html);
    }
}

As you can see I also replace the images location to a offline location. 



Logging: log4net type not resolved error!!!

I got this error when using log4net. Type is not resolved for member 'log4net.Util.PropertiesDictionary,log4net

It only occurred on the development machines. So we were looking for iisexpress problems. Could find a lot of unittest fixes etc, but this was not our problem. It simply crashed whenever we called logging in our web site. the dll's were nicely referenced.

When we used local iss, it works fine.

So at the end I found out that in iisexpress the dll was not always loaded because of multi threading. So the fix was to install the dll into the GAC:

gacutil /i D:\dev\packages\log4net\log4net.dll



Web API call Json object is null

I have a WCF service that call's a Web API 2 service. I serialize the object ot JSON and pass it to the API. But when deployed to the server the incoming object was null. I had a very hard time figuring out what was the problem, the server only teturned this message:

The remote server returned an error: (500) Internal Server Error

The code to call the web API was something like this:

using (var client = new WebClient())

{

    //var employeeJson = new JavaScriptSerializer().Serialize(empBDO);

    var empJson = JsonConvert.SerializeObject(empBDO);

 

    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    empJson.LogMessage(CurrentProject, LoggingMode.Debug, "JSON to send");

 

    try

    {

        var response = client.UploadString(apiUrl, empJson);

    }

    catch (Exception apiex)

    {

        ("PostToAPI.CallAPI error = " + apiex.Message).LogMessage(CurrentProject, LoggingMode.Debug, apiex.StackTrace);

    }

}

If I called the API from an angular app with the same json that was logged, there was no problem. Everything worked. Then I started to add more and more logging and noticed that the incoming object in the API was null if I called it from the server.

At the end I had to add this line of code to the webclient that was calling the API:

    client.Encoding = UTF8Encoding.UTF8;

So the code looked like this:

using (var client = new WebClient())

{

    var empJson = JsonConvert.SerializeObject(empBDO);

    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    client.Encoding = UTF8Encoding.UTF8;

    try

    {

        var response = client.UploadString(apiUrl, empJson);

    }

    catch (Exception apiex)

    {

        ("PostToAPI.CallAPI error = " + apiex.Message).LogMessage(CurrentProject, LoggingMode.Debug, apiex.StackTrace);

    }

}


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.


The message recieved was unexpected or badly formatted.

After settings up a new Azure Server with MSSQL 2014, we couldn't connect to the server.

After some research it appeared to be because .Net 4.5.1 was giving problems. On my machine it was solved by removing the .Net Framework 4.5.1 and installing the .Net Framework 4.5.2. No need to reboot even. On another PC, we had to rebuild the .Net Framework using the regiis tool describer here:



VS 2010/2012 crashes when opening designer.

This can be a really time eating problem. In my case this problem came suddenly, in a class that didn't change for a long time. 

The error looked something like this:

Faulting application name: devenv.exe, version: 10.0.40219.1, time stamp: 0x4d5f2a73

Faulting module name: KERNELBASE.dll, version: 6.1.7601.18409, time stamp: 0x53159a86

Exception code: 0xe0434352

Fault offset: 0x0000c42d

Faulting process id: 0x1898

Faulting application start time: 0x01d00d526a76a093

Faulting application path: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe

Faulting module path: C:\Windows\syswow64\KERNELBASE.dll

Report Id: f6f5bf23-7945-11e4-afad-02004e435049

When you experience this kind of behavior, it could be that an add-in is causing the problem or some update of software. In our case this didn't help.

So at the end we found that is was a problem in the page load of a form, it gets executed when you open the designer. We had some code that went to the database. The strange this is that this worked for years and now suddenly it starts crashing on all development PC's. The solution to this problem is to prevent the code from being run at design time by using the System.ComponentModel.LicenseManager.UsageMode:

Private Sub BaseForm_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Handles Me.Load

    Try

       If System.ComponentModel.LicenseManager.UsageMode = System.ComponentModel.LicenseUsageMode.Runtime Then

          HandleFormDisableButtons()

          Translate()

       End If

    Catch ex As Exception

ExceptionHandling.ShowException(ex)

    End Try

 

End Sub


Using LINQ to concatinate an object property from a list of objects

Just put this in a little demo to make it clear. I created a simple object Person, with ID, FirstName and LastName.

Now I fill a List with 3 persons (later I'll fill it with 20000 to do a performance check):

List<Person> persons = newList<Person>();

{

    newPerson(){ID=0, FirstName="Mark", LastName="Deraeve"},

    newPerson(){ID=1, FirstName="Priscilla", LastName="Lauwerijssen"},

    newPerson(){ID=2, FirstName="Anne-Lisa", LastName="Deraeve"}

};

Instead of looping over the list and concatinating it, like this:

start = DateTime.Now;

foreach (Person p in persons)

{

    sPersons = String.Format("{0},{1}", sPersons, p.FirstName);

}

//remove front ,

Console.WriteLine("With Loop: " + sPersons);

I can also just use 1 line to accomplisch this:

Console.WriteLine("With LINQ: " +string.Join(",", persons.Select(p => p.FirstName)));

Result:

 

Now let's say you do not want all records, this makes it even more easy, just put a Where before the Select and you got it!

Let's only show person named 'Deraeve':

Console.WriteLine("With LINQ: " +string.Join(",", persons.Where(p => p.LastName == "Deraeve").Select(p => p.FirstName)));

Result:

 

Now last, lets try to see performance difference. I'll fill the list with 20000 persons. This is where the power comes in. (The number 188889 or 188890(+1 for the extra comma) is the length of the result string)

 

Amazingly, the LINQ only uses 3 or 4 milliseconds, the old for loop takes 1-3 (There is a difference when using String.Format (slower) or just "string + ','+ "string") seconds. This can really make a big difference in today's apps.

So here the complete code so you can test it yourself:

Code of the console app:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace TestConsoleApp

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            List<Person> persons = newList<Person>();

            /*{

                new Person(){ID=0, FirstName="Mark", LastName="Deraeve"},

                new Person(){ID=1, FirstName="Priscilla", LastName="Lauwerijssen"},

                new Person(){ID=2, FirstName="Anne-Lisa", LastName="Deraeve"}

            };*/

 

            for (int i = 0; i < 20000; i++)

            {

                persons.Add(newPerson() { ID = i, FirstName = string.Format("Name{0}", i), LastName = "Deraeve" });

            }

 

            string sPersons="";

            DateTime start = DateTime.Now;

            TimeSpan ts;

 

            start = DateTime.Now;

            sPersons = string.Join(",", persons.Select(p => p.FirstName));

            ts = DateTime.Now.Subtract(start);

            Console.WriteLine("With LINQ: " + sPersons.Length);

            Console.WriteLine(String.Format("Seconds:{0} Miliseconds{1} ", ts.Seconds, ts.Milliseconds));

            Console.WriteLine("");

 

            sPersons = "";

 

            start = DateTime.Now;

            sPersons = string.Join(",", persons.Where(p => p.LastName == "Deraeve").Select(p => p.FirstName));

            ts = DateTime.Now.Subtract(start);

            Console.WriteLine("With LINQ and Where: " + sPersons.Length);

            Console.WriteLine(String.Format("Seconds:{0} Miliseconds{1} ", ts.Seconds, ts.Milliseconds));

            Console.WriteLine("");

 

            sPersons="";

 

            start = DateTime.Now;

            foreach (Person p in persons)

            {

                sPersons = String.Format("{0},{1}", sPersons, p.FirstName);

            }

            ts = DateTime.Now.Subtract(start);

 

            Console.WriteLine("With for loop: " + sPersons.Length);

            Console.WriteLine(String.Format("Seconds:{0} Miliseconds{1} ",ts.Seconds,ts.Milliseconds));

            Console.WriteLine("");

 

            sPersons = "";

 

            start = DateTime.Now;

            foreach (Person p in persons)

            {

                if (p.LastName == "Deraeve")

                {

                    sPersons = String.Format("{0},{1}", sPersons, p.FirstName);

                }

            }

 

            ts = DateTime.Now.Subtract(start);

 

            Console.WriteLine("With for loop and if: " + sPersons.Length);

            Console.WriteLine(String.Format("Seconds:{0} Miliseconds{1} ", ts.Seconds, ts.Milliseconds));

            Console.WriteLine("");

 

            sPersons = "";

 

            start = DateTime.Now;

            foreach (Person p in persons)

            {

                sPersons = sPersons + ',' + p.FirstName;

            }

            ts = DateTime.Now.Subtract(start);

 

            Console.WriteLine("With for loop without format: " + sPersons.Length);

            Console.WriteLine(String.Format("Seconds:{0} Miliseconds{1} ", ts.Seconds, ts.Milliseconds));

            Console.WriteLine("");

 

            Console.ReadKey();

        }

    }

}

Code of the Person class:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace TestConsoleApp

{

    publicclassPerson

    {

        publicstring FirstName { get; set; }

 

        publicstring LastName { get; set; }

 

        publicint ID { get; set; }

 

    }

}

Things even get better for the Join statement when we add the last name to the result:

sPersons = string.Join(",", persons.Where(p => p.LastName == "Deraeve").Select(p => p.FirstName + ' ' + p.LastName));

VS

foreach (Person p in persons)

{

    sPersons = String.Format("{0},{1} {2}", sPersons, p.FirstName, p.LastName);

}


Result: 



How to get a dataset with variable SQL from the entity framework

When you are working with the EF, you will finally get to the point that you need some joined data from the database that could be based on variable SQL queries. In our case we can define SQL queries in the database that will decide what to show in grids. Since this data is combining several tables from a non relational DB, its not returning entity data. So I found a good way to get a dataset and still use the entity framework connection. So no new connection logic to be instantiated:

 

public DataSet ExecuteStoreQuery(string commandText)

{

    DataSet retVal = new DataSet();

    EntityConnection entityConn = (EntityConnection)MyContext.Connection;

    SqlConnection sqlConn = (SqlConnection)entityConn.StoreConnection;

    SqlCommand cmdReport = new SqlCommand(commandText, sqlConn);

    SqlDataAdapter daReport = new SqlDataAdapter(cmdReport);

    using (cmdReport)

    {

        cmdReport.CommandType = CommandType.Text;

        daReport.Fill(retVal);

    }                  



    return retVal;

}

 

You should only use this for view purposes only!!!