How to replace plain URLs with links? (C# and Javascript)

Idea: In Suppo project we want to replace URLs in chat conversations by HTML links. Yes the first thing was to use google to find some recommendations or regular expressions BUT: On stackoverflow in article http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links is written:

“First off, rolling your own regexp to parse URLs is a terrible idea. You must imagine this is a common enough problem that someone has written, debugged and tested a library for it, according to the RFCs. URIs are complex  … and there is multiple recommended libraries in Javascript (expect similar libraries in C#) like linkifyjs, anchorme.js, autolinker.js … OK so where is the problem?

The problem for me is that all of this libraries are huge … >30KB minified.

Why?

Because we are developing livechat window (Suppo) which is attached to every page of our clients and +30KB of javascript code is not acceptable when our solution has 63KB at all (included the core of jQuery library)

So what next?

Back to beginning and compose simple regular expression (is not so important to work on every URLs … suffice many of them)

C#:

public static string Linkify(this string text)
{
    // www|http|https|ftp|news|file
    text = Regex.Replace(
        text,
        @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])",
        "<a href=\"$1\" target=\"_blank\">$1</a>",
        RegexOptions.IgnoreCase)
        .Replace("href=\"www", "href=\"http://www");

    // mailto
    text = Regex.Replace(
        text,
        @"(([a-zA-Z0-9_\-\.])+@[a-zA-Z\ ]+?(\.[a-zA-Z]{2,6})+)",
        "<a href=\"mailto:$1\">$1</a>",
        RegexOptions.IgnoreCase);

    return text;
}

Javascript:

// www|http|https|ftp|news|file
text = text.replace(
    /((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/gim,
    '<a href="$1" target="_blank">$1</a>');

// mailto
text = text.replace(
    /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim,
    '<a href="mailto:$1">$1</a>');

It’s simple: first part of code find www|http|https|ftp|news|file and replace it by <a href=”http(s):// and second part find email address and replace it by <a href=”mailto::.
That is all and it's less than 1KB of code.

How to view LINQ Generated SQL statements?

It’s multiple options how we can view generated SQL from LINQ to SQL or Entity framework. My favorite is by SQL Server profiler. BUT sometimes I need something quicker. And here is the option how to look directly at the DB (SQL Server) to the last executed query:

SELECT TOP 5 
	deqs.last_execution_time AS [Time], 
	dest.text AS [Query]
FROM 
	sys.dm_exec_query_stats AS deqs
	CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE 
	dest.text like '%vw_Visitor%'
ORDER BY 
	deqs.last_execution_time DESC

Only one note: Beneficial can by the WHERE condition … I suppose that the query looking under particular Table or View or SP so I can help to SQL server by adding WHERE condition like dest.text like '%vw_Visitor%' = By this I said something like : hey server, give me only query where is mentioned something related with particular View called vw_Visitor.  

Background image to HTML and/or BODY element

Keep in mind that height of <html> and <body> element are not same. Body element is inside of <html> element, so in some cases are important to specify background (image or color) for particular element in different way. This is example how:

CSS2:

html {
    background: url(background1.png) center center no-repeat;
}

body {
    background: url(background2.png) center center no-repeat;
}

CSS3:

body {
    background: url(background2.png) center center no-repeat, 
		url(background1.png) center center no-repeat;
}

Specification says : The background of the root element becomes the background of the canvas and its background painting area extends to cover the entire canvas, although any images are sized and positioned relative to the root element as if they were painted for that element alone. (In other words, the background positioning area is determined as for the root element.) If the root's ‘background-color’ value is ‘transparent’, the canvas's background color is UA dependent. The root element does not paint this background again, i.e., the used value of its background is transparent.

For documents whose root element is an HTML HTML element or an XHTML html element: if the computed value of ‘background-image’ on the root element is ‘none’ and its ‘background-color’ is ‘transparent’, user agents must instead propagate the computed values of the background properties from that element's first HTML BODY or XHTML body child element. The used values of that BODY element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

Error 404 for .axd files (WebResource.axd & ScriptResource.axd)

If you’ve got a similar error as on following image:

ScriptResource.axd error 404

that your script resources related with components like UpdatePanel or ScriptManager are not working correctly, think about routing. It may by caused by many other reasons as wrote on similar blog post across the web e.g. wrong version of related System.Web.Extensions.dll or wrong IIS configuration or incorrect handlers defined in web.config. BUT when you are working in hybrid ASP.NET application where are .aspx + .chtml pages together (old Web Forms and new MVC) the problem will probably be routing.

Check and correct your RouteConfig.cs as on following image:

Ignore .axd Resources in RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
{
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
	
	// Default MVC routing
    routes.MapRoute(
       name: "D1",
       url: "{controller}/{action}/{id}",
       defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
    );
}

 

Enjoy!

InsertOnSubmit throwing NullReferenceException

Be careful when you are using your own constructor in partial classes on entities generated for LINQ to SQL (Data context entities). When you create your own constructor is really important to call the default constructor in it. Example :

Default contructor on LINQ to SQL entities in partial class


Why? Because is important to execute the default generated constructor while execution of your program. This constructor contains some Initialization under your entity:

Generated contructor of LINQ to SQL object
Otherwise you will getting following error:

[NullReferenceException: Object reference not set to an instance of an object.]
   System.Data.Linq.Mapping.EntitySetDefSourceAccessor`2.GetValue(T instance) +18
   System.Data.Linq.Mapping.MetaAccessor`2.GetBoxedValue(Object instance) +56
   System.Data.Linq.StandardTrackedObject.HasDeferredLoader(MetaDataMember deferredMember) +128
   System.Data.Linq.StandardTrackedObject.get_HasDeferredLoaders() +130
   System.Data.Linq.StandardChangeTracker.Track(MetaType mt, Object obj, Dictionary`2 visited, Boolean recurse, Int32 level) +269
   System.Data.Linq.StandardChangeTracker.Track(Object obj, Boolean recurse) +113
   System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity) +383

Suppo.biz – testovacia prevádza spustená

Doménu Suppo.biz už nejaký ten mesiac máme obsadenú, no len pred pár týždňami sme spustili testovaciu prevádzku pre vybraných zákazníkov na subdoménach ako: turingion.suppo.biz, fincentrum.suppo.biz … no až teraz sme updatli stránku turingion.com, konkrétne časť o produkte eShop, kde už LiveChat nie je ako plánovaná novinka (vo vývoji), ale je plne funkčný a pripravený pre nových zákazníkov v balíčku Business. Samozrejmosťou je doplnenie tejto funkcionality všetkym existujúcim zákazníkom, ktorý o tento skvelý nástroj budú mať záujem. Jeden ScreenShot z aplikácie:

image

Pomodoro Technique in Turingion

http://www.legalproductivity.com/wp-content/uploads/2010/08/pomodoro_timer.jpg 

What is the pomodoro timer?
The Pomodoro timer is a well-known productivity interval that has been shown to improve your productivity. It gives you a prescribed interval of 25 minutes of work followed by a 5-minute break. After 4 work intervals, there is a 15-minute break.

Why?
In these days we are experimenting with this technique, because the interrupt by customer mails, requirements on multiple projects, interaction with colleagues and other disturbances are beyond the normal bounds. We need to reorganize our work (working day) and it seems that this is one of the possibilities.

App
We are google-ing/ finding the best app for our need, but sometimes is the best to create the own one. Here is our solution … is really simple, no settings. Every interval starts every half an hour (e.g. 7:00, 7:30, 8:00, 8:30…). It contains only activate/deactivate button and task bar notification by synthetic voice (hint: library System.Speech).

ASP.NET- Simple localization with free tool (Zeta Resource Editor)

When we are writing every application (software), we are localizing the resources. Every text information writing to the .resx files as follows :

Text resources in .resx filesCommonly we are using 2 languages (English as default and Slovak as optional, because Slovak is our motherly language). So in this case we need 2 resource files for as follows:

Two resource files

And what was the issue? The issue is effectiveness of translating from one language to another. This issue is in visual studio little bit complicated, because you need to synchronize every keys from one file to another. And for this purpose we are using cool tool called Zeta resource editor. Look at the following picture:
Zeta resource editor in action

Zeta resource editor provide you edit values for particular key very confortable on one screen (on one line). And the best feature is the finding of missing keys. You can easily add new value for particular missing key.
Zeta resource editor - missing keys

Is really useful in situations, when your resource files are not sync. and some keys missing in both files.

ASP.NET MVC - the value set on the field does not correspond to the value in the Model - what’s wrong?

While developing our brand new LiveChat called ”Suppo.biz”, I noticed interesting behaviour, what I never noticed before. In the functions like @Html.EditorFor, @Html.TextBoxFor … or @Html.TextArea, @Html.TextBox … When you do AJAX “postback” of your form like this:

			@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "FormAjaxContainer" }))
			{
				@Html.AntiForgeryToken()
				
				<div id="FormAjaxContainer">

					<div class="form-group">
						@Html.LabelFor(model => model.WidgetThemeColor, htmlAttributes: new { @class = "control-label col-md-2" })
						<div class="col-md-10">
							@Html.ValidationMessageFor(model => model.WidgetThemeColor, "", new { @class = "text-danger" })
							<div class="input-group BGColorPicker">
								<span class="input-group-addon"><i></i></span>
								@Html.EditorFor(model => model.WidgetThemeColor, new { htmlAttributes = new { @class = "form-control" } })
							</div>
						</div>
					</div>

				</div>
			}

with value “A” on property WidgetThemeColor and on the server you change the value to value “B” you still see on the input field the value “A”. Its caused by interesting behaviour of the helper function of all controls like @Html.EditorFor, @Html.TextBox …
They first use the value of the POST request and after that the value in the model. This means that even if you modify the value of the model in your controller action if there is the same variable in the POST request your modification will be ignored and the POSTed value will be used. When you want to apply your new value from controller, you need to do this:
 
ModelState.Clear();

Or for particular property by this statement :
ModelState.Remove("WidgetThemeColor");

And the POSTed value will be ignored while rendering of the View or PartialView.

Microsoft SQL Server - Import wizard fails with incomprehensible message

Many times the confused/unknown error has a simple resolution. I tried to import big .csv file with simple GEO information to database. The columns were “IP Address“, “Country Code”, “Region”, “City”. When I open the file all columns look simple with length less then 50 characters. And that was the problem. I tried to import this file by following wizard:

MsSQL Server - Import Data Wizard

And when you specifying the source, look at the “Advanced” section and increase the length of your columns (string columns)

MsSQL Server - Import Data Wizard - Csv file as Source

MsSQL Server - Import Data Wizard - Csv file as Source

Otherwise, when the length of your columns will be short you see en error similar as on this screen (but this is error about wrong encoding Smiech):

MsSQL Server - Import Data Wizard - Error view

Text version of error:

Validating (Error)
Messages
Error 0xc02020f4: Data Flow Task 1: The column "IPFrom" cannot be processed because more than one code page (65001 and 1250) are specified for it.
 (SQL Server Import and Export Wizard)
 
Error 0xc02020f4: Data Flow Task 1: The column "IPTo" cannot be processed because more than one code page (65001 and 1250) are specified for it.
 (SQL Server Import and Export Wizard)
 
Error 0xc02020f4: Data Flow Task 1: The column "Code" cannot be processed because more than one code page (65001 and 1250) are specified for it.
 (SQL Server Import and Export Wizard)
 
Error 0xc02020f4: Data Flow Task 1: The column "Region" cannot be processed because more than one code page (65001 and 1250) are specified for it.
 (SQL Server Import and Export Wizard)
 
Error 0xc02020f4: Data Flow Task 1: The column "City" cannot be processed because more than one code page (65001 and 1250) are specified for it.
 (SQL Server Import and Export Wizard)
 
Error 0xc004706b: Data Flow Task 1: "Destination - dbip-cityT" failed validation and returned validation status "VS_ISBROKEN".
 (SQL Server Import and Export Wizard)
 
Error 0xc004700c: Data Flow Task 1: One or more component failed validation.
 (SQL Server Import and Export Wizard)
 
Error 0xc0024107: Data Flow Task 1: There were errors during task validation.
 (SQL Server Import and Export Wizard)
 

And when I optimized the length … the interesting thing was, that problematic column was the most unlikely - the “Code”. Code which is in 99% with 2 characters Diabol