If you use Redux in your Angular web application (likely it is an NgRedux from Angular Redux) and develop unit tests for components that depend on the Redux store sometimes it's easier to mock the Redux store rather than deal with incorrect values that it may supply in a test scenario. If this sounds like your situation, read on.
Sponsored
Friday, December 18, 2020
Angular: Mock NgRedux for Unit Testing
Friday, November 27, 2020
.NET Core OData: How to Construct a DateTime Filter
Friday, November 6, 2020
Best Practices of Working with Date in JavaScript/TypeScript
Date is a built-in type in JavaScript/TypeScript (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) and provides most of the basic needs for manipulating with Date and Time values in the code. Being one of the most well-defined and often used basic types of the language it still generates a lot of confusion, questions and erroneously working code among a wide developers' community. Let's try and figure out some of the best practices that should be applied to the JavaScript/TypeScript code when dealing with the Date type.
Friday, October 30, 2015
Using Google Tag Manager to deploy Azure Application Insights client-side monitoring
| If your web application is hosted on Microsoft Azure and you are using Application Insights for monitoring you'll have to add a piece of JavaScript on web pages to collect client-side statistics like page load time, JavaScript errors, users and sessions analytics, etc. The script can be found on Azure portal when Application Insights is enabled for a web application. |
Tuesday, July 12, 2011
Using jQuery to Consume ASP.NET MVC JSON Services
Since the inception of ASP.NET Web Services have been an important part of any professional web developer's tool set. Starting .NET 3.5 Web Services became even more useful as it became possible to call Web Services asynchronously from a browser using JavaScript and ASP.NET AJAX.
However for the last two years the alternative ASP.NET MVC framework has been drawing more and more attention from the development community due to its good implementation of the MVC design pattern and adherence to web standards and bleeding edge web technologies.
For many experienced ASP.NET developers accustomed to Web Services especially accompanied with ASP.NET AJAX framework a natural question occurs: how to implement similar approach with ASP.NET MVC framework and its natural JavaScript companion jQuery?
Sunday, May 1, 2011
Fix for Bing Maps not working in Firefox 4+
Apparently that problem exists for Firefox 5 also and perhaps will apply for the future versions too. So the solution below should be considered a best practice for using Bing Maps 6.x with Firefox 4+.
Recently I've upgraded from Firefox 3.6 to Firefox 4 and while doing regression testing I've notice that apparently Bing Maps has some issues in Firefox 4. In particular I saw a JavaScript error that said "p_elSource.attachEvent is not a function":
The problem at this point looks like this:
- the error happens in Bing's JavaScript itself; and
- it only happens in Firefox 4 browser. Other browsers like IE 8 & 9, Chrome, Safari, Opera and Firefox 3.6 don't produce that problem.
What's that condition? I looked at the difference between Firefox browser and the other browsers. When in Firefox Bing Maps dynamically loads another JavaScript file atlascompat.js. Apparently that file is required since it contains a definition for the attachEvent function that caused an error and must be loaded first before the main Bing Maps script. So that's the condition I've been looking for! Now the picture got clearer:
- the error happens in Bing's JavaScript itself; and
- it only happens in Firefox 4 browser. Other browsers like IE 8 & 9, Chrome, Safari, Opera and Firefox 3.6 don't produce that problem;
- it happens when the atlascompat.js is not present on a page at the moment when the main Bing Maps script is being loaded.
The solution is simple: since the Bing Maps itself cannot load the atlascompat.js reliably I need to help it and just add a reference to the atlascompat.js script on my page before a reference to the main Bing Maps script. This can be easily accomplished with a few line of code like below:
if ((Page.Request.Browser.Browser.IndexOf("Firefox") >= 0) && (Page.Request.Browser.MajorVersion >= 4))
{
// add script reference on a page
// use technique that is suitable for your application
}Notice that the browser version is more or equal 4 to cover the future versions of Firefox too (for version 5 this solution is confirmed). In my case I've added the code above into a GetScriptReferences method of an IScriptControl that was responsible for rendering the Bing Maps on a page.
Friday, May 7, 2010
How to set programmatically a value of a watermarked TextBox via JavaScript - Update
Ajax Control Toolkit changes
One of the most significant changes in the recent Ajax Control Toolkit release that affected everything is renaming namespaces and control names. Most of the JavaScript classes in the ACT has been moved into Sys.Extended.UI and some of them renamed.Correspondingly the AjaxControlToolkitTextboxWrapper class that is crucial for the technique described in this article is now called Sys.Extended.UI.TextBoxWrapper and this is a breaking change. Most if its methods haven't been renamed and this is a good news however the new way of using the wrapper has been introduced.
Below are the code examples demonstrating how to write the code correctly with the new version of the ACT.
First we need to acquire an instance of the Sys.Extended.UI.TextBoxWrapper class for our textbox control and this is the newly introduced technique compared to the previous version of the ACT:
// get the instance of a textbox element
var textBox = $get(textBoxId);
// use the get_Wrapper static method of the TextBoxWrapper class to get the instance of the wrapper for the textbox
var wrapper = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(textBox);
In the code above first I assume that the ACT is present so I don't have to check that Sys.Extended.UI namespace is defined. Secondly the code above is safe even if the textbox is not watermarked: the get_Wrapper static method will always return the instance of the TextBoxWrapper; the new instance will be created if the textbox is not watermarked.
Now we can set or get a value of the textbox using the instance of the TextBoxWrapper:
// get the textbox value
var oldValue = wrapper.get_Value();
// set the textbox value
wrapper.set_Value(newVlaue);
Conclusion
In a nutshell there are two major changes introduced in the new ACT release that affect the coding technique described here: the name of the textbox wrapper class has been changed; and now it's not required to check whether the textbox is watermarked to use the technique above.Wednesday, May 5, 2010
Leveraging Visual Studio JavaScript IntelliSense.
One of the most useful features of the Visual Studio 2008 and Visual Studio 2010 is JavaScript IntelliSense that allows developers write JavaScript code faster, with fewer errors and reduce learning time of some JavaScript frameworks. Many developers already enjoy its power when code JavaScript with Microsoft ASP.NET Ajax framework and jQuery. However many developers are still not familiar with that tool and even less developers realize that it can also be used with their own code.
Sunday, November 29, 2009
Automatically compress embedded JavaScript resources with Microsoft Ajax Minifier
The question however is how to use it. Microsoft Ajax Minifier package does include a set of documentation that explains how to use the tool and even discusses a couple of usage scenarios. Unfortunately the way I wanted to use the Minifier is not covered in the documentation and for some reason I haven't found useful information on the Internet too so I've decided to do some research and share my findings with the community.
So how would I like to use the Minifier? Here are the requirements:
- I want to automatically compress embedded JavaScript resources in any project of my web application solution.
- I want the compressed JavaScripts have the original names so I don't have to change the references in HTML mark-up.
- I want the compression to be done only when I switch to the Release mode in Visual Studio. When I am in the Debug mode I want all the JavaScript files to be uncompressed for easier debugging.
- I want compressed JavaScript files never overrides the original JavaScript files and I don't want to keep the compressed JavaScripts so whenever I modify my JavaScript code the compressed resources are always up-to-date.
I believe that the requirements above describe one of the most common web application solution configuration so if there is a way to achieve them it would be very useful.
Can I achieve the requirements above with the Microsoft Ajax Minifier? The answer is yes. The solution is kind of obvious: since the Microsoft Ajax Minifier includes an MSBuild task I just need to modify a project file where I have embedded JavaScript resources that I need to be compressed to include the Microsoft Ajax Minifier build task. It does not sound complicated and below is the solution which is simple indeed. Just include the following XML in your project file right before the closing </Project> tag (in most cases):
<!-- Minify all JavaScript files that were embedded as resources -->
<Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
<PropertyGroup>
<ResGenDependsOn>
MinifyJavaScript;
$(ResGenDependsOn)
</ResGenDependsOn>
</PropertyGroup>
<Target Name="MinifyJavaScript" Condition=" '$(ConfigurationName)'=='Release' ">
<Copy SourceFiles="@(EmbeddedResource)" DestinationFolder="$(IntermediateOutputPath)" Condition="'%(Extension)'=='.js'">
<Output TaskParameter="DestinationFiles" ItemName="EmbeddedJavaScriptResource" />
</Copy>
<AjaxMin SourceFiles="@(EmbeddedJavaScriptResource)" SourceExtensionPattern="\.js$" TargetExtension=".js" />
<ItemGroup>
<EmbeddedResource Remove="@(EmbeddedResource)" Condition="'%(Extension)'=='.js'" />
<EmbeddedResource Include="@(EmbeddedJavaScriptResource)" />
<FileWrites Include="@(EmbeddedJavaScriptResource)" />
</ItemGroup>
</Target>
What this script does is when the solution configuration is 'Release' it finds all the project embedded resource files with the extension '.js' and creates their compressed versions with the same names in the intermediate output folder where they are picked from later by the build process.
A few tips
As you may have noticed the Microsoft Ajax Minifier MSBuild task is referenced from the default folder where it was copied to by the installer. If you want to reference it from a different location, for example if you have a shared development environment and want to have similar setting for everyone, just copy two files ajaxmin.dll and ajaxmintask.dll to another location and include the <UsingTask> tag (below) instead of the <Import> tag in the script above:
<UsingTask TaskName="AjaxMin" AssemblyFile="$(MSBuildProjectDirectory)\..\Build\AjaxMinTask.dll" />
The presented script performs so called 'Normal Crunching' (see the Ajax Minifier documentation) of the JavaScript code which already does a pretty good job that is good enough in most of the cases: compression rate is over 50%. If you would like to turn on the 'Hypercrunching' mode (see the Ajax Minifier documentation) you only need to modify one line of the script to include the 'LocalRenaming' option of the Ajax Minifier:
<AjaxMin SourceFiles="@(EmbeddedJavaScriptResource)" SourceExtensionPattern="\.js$" TargetExtension=".js" LocalRenaming="CrunchAll" />
And the last note is: don't use the default Hypercrunching mode or RemoveUnneededCode option with the ASP.NET AJAX Framework as it does not work properly with it.
Monday, June 22, 2009
How to set programmatically a value of a watermarked TextBox via JavaScript
$get(textBoxId).value = someText;
then the value displayed in the TextBox on the page will change to the set value but the watermarked look will still be present and other AJAX Control Toolkit TextBox extenders (like a Calendar extender, for instance) will not recognize the new value.
This happens because the TextBoxWatermark extender can not recognize and intercept your JavaScript operation since it's designed to serve user interactions. However there is a correct way of programmatic access to the TextBox's value. We modify the code above like that:
var textBox = $get(textBoxId);
if (textBox.AjaxControlToolkitTextBoxWrapper) {
textBox.AjaxControlToolkitTextBoxWrapper.set_Value(someText);
}
else {
textBox.value = someText;
}
The explanation is that most of the TextBox extenders from the AJAX Control Toolkit including a TextBoxWatermark extender use a special proxy class AjaxControlToolkitTextBoxWrapper to manipulate with the input elements. The proxy adds a special property AjaxControlToolkitTextBoxWrapper to the input element that contains a reference to itself allowing to access the value of the input element correctly. Similarly, if you need to get a value of a watermarked TextBox you do it like this:
var textBox = $get(textBoxId), text;
if (textBox.AjaxControlToolkitTextBoxWrapper) {
text = textBox.AjaxControlToolkitTextBoxWrapper.get_Value();
}
else {
text = textBox.value;
}
Tuesday, June 2, 2009
New version of ASP.NET AJAX Control Toolkit released
The new release of ASP.NET AJAX Control Toolkit is available for download. Bertrand Le Roy has written a very informative post about it.
What I particularly like in this new release is that the Color Picker extender is now included in the Ajax Control Toolkit. Hooray!
Along with the new Toolkit release there come a whole bunch of new tutorials and videos. Among them there are this particularly nice tutorial about the Color Picker extender and another excellent video tutorial by Joe Stagner. Thank you folks for such a great job!
What that means for the Color Picker Extender users is that they don't have to download it separately from Codeplex anymore because it is included in the Ajax Control Toolkit. For those who cannot yet switch to the new version of ACT the original Color Picker Extender control will continue to be available on Codeplex. During the next few days I will prepare and upload a new release synced up with the Ajax Control Toolkit.
It is very educating to read people's opinions about the new release of ACT in response to blog posts and on Codeplex. In general, the responses are positive, but occasionally there are some complaints, mostly about little things.
I would like to remind everybody that Ajax Control Toolkit is a completely community-based initiative (with, of course, the initial kick-off help from Microsoft) and people who work on it take time out of their personal calendars so let's be more tolerant and if you've come across something really bad please use the Issue Tracker.
As I mentioned before, I specifically was interested in reading responses about the ColorPicker. Interestingly, all the complaints were about its look and feel, not about functionality. I admit that the UI it provides is rather simplistic but here is my question back: why don't you all take some time and come up with feedbacks and suggestions on what can be improved?
Since the ColorPicker was publicly available on CodePlex it's been downloaded more then 2000 times (and I don't count downloads of ACT source code) and only a few people suggested something about improving it. I take it as everybody has been satisfied.
Now that the CPE is a part of the ACT and has a bit more visibility I suggest that people who have suggestions or concerns please don't hesitate to speak up.
Wednesday, May 27, 2009
Survey: Ajax usage among .NET developers
The survey:
http://www.zoomerang.com/Survey/?p=WEB22973CYKW2H
Wednesday, March 11, 2009
Using ColorPickerExtender Client-side Events
Subscribing to the colorSelectionChanged event
You can subscribe to the event either via JavaScript code or ASP.NET mark-up:
var cpe = $find("ColorPickerExtender1");
cpe.add_colorSelectionChanged(changeColor);
Here $find is a standard function of the ASP.NET AJAX Framework that returns an instance of the AJAX component by BehaviourID; ColorPickerExtender1 is a BehaviourID of the ColorPickerExtender component and changeColor is your JavaScript function that will be called when the event occurs.
<ajaxToolkit:ColorPickerExtender ID="defaultCPE" runat="server"
TargetControlID="Color1"
BehaviorID="ColorPicker1"
OnClientColorSelectionChanged="changeColor"
/>
Make sure that the changeColor JavaScript function exists on the page otherwise you'll see a JavaScript error "changeColor is undefined". You may define a changeColor function like this:
function changeColor(sender) {
sender.get_element().style.color = "#" + sender.get_selectedColor();
}
When your function is called after a user picked a color (i.e. clicked a mouse on the color palette) a sender argument will point to the instance of the ColorPickerExtender component that you can use inside your function. For instance, call a method get_element() to retrieve a reference to an input DOM element which the extender is attached to or use a get_selectedColor() method to retrieve a hexadecimal color code that the user selected. When assigning the color value to a DOM element style don't forget to prepend it with a '#' character.
Thursday, January 29, 2009
ASP.NET AJAX Compatibility Patch for Safari 3.x and Google Chrome
Sys.Browser.WebKit = {};
if( navigator.userAgent.indexOf('WebKit/') > -1 ) {
Sys.Browser.agent = Sys.Browser.WebKit;
Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
Sys.Browser.name = 'WebKit';
}
That is all the code you need. To apply this code to your web application you will need to create a JavaScript file, let's say webkit.js and reference it in your application using standard ScriptManager server control. You can reference the fix as a file using this syntax:
<asp:ScriptManager ID="sm" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Scripts/webkit.js" />
</Scripts>
</asp:ScriptManager>
or embed it into an assembly (my preferred way) and reference it from the assembly as an embedded resource:
<asp:ScriptManager ID="sm" runat="server">
<Scripts>
<asp:ScriptReference Assembly="Scripts" Name="Scripts.webkit.js" />
</Scripts>
</asp:ScriptManager>
Note that when you reference the fix from an assembly don't forget to add an assembly default namespace to the file name in the Nameattribute.
In conclusion, according to my tests the fix eliminated problems with UpdatePanel, AjaxControlToolkitand Virtual Earth map control.Wednesday, October 1, 2008
More About Color Picker ASP.NET AJAX Extender
I have published an article on Code Project about the Color Picker ASP.NET AJAX Extender. Please read it there.
Friday, September 26, 2008
Color Picker ASP.NET AJAX extender control
I was looking for a client-side color picker control and found it extremely difficult to find something that would satisfy to my requirements. I have found plenty of pure JavaScript controls written with various levels of proficiency and there was even one ASP.NET color-picker control that I almost liked but still my major requirement was not satisfied: I was looking for AJAX .NET Extender control - easy to use and based on a solid and proven platform.
So, I have researched what other color picker controls do and decided to write the one myself that I would base on Microsoft AJAX .NET platform. After some considerations I've decided to go even further and build an AJAX Control Toolkit Extender control.
As an example I took an AJAX Control Toolkit Calendar extender and in my Color Picker extender control I also internally used another AJAX Control Toolkit control: Popup extender.
Now, what are the advantages of implementing a client control as an ASP.NET AJAX extender?
- You use ASP.NET page mark-up to render the control content to the browser.
- No need to manually inject JavaScript, HTML and other resources.
- You develop JavaScript code in a standalone file leveraging ASP.NET AJAX framework and Visual Studio intellisense abilities.
- JavaScript per se is very well structured, easy to read and debug.
- Many of the hassles of JavaScript client coding such as cross-browser compatibility, event handling, asynchronous calls are taken care of by ASP.NET AJAX framework.
So, I have spent a few days coding the control and finally it's out there. I have created a Codeplex project for it so if you are interested just go there and download the control and a Demo Web site.
Now, just a few more words about the extender. First, this is how it looks:
Second, it's extremely easy to use. The extender attaches to an ASP.NET TextBox server control and to an optional button that can open a popup window and an element that samples a selected color in the background. User selects a color by clicking on a colored area. Below is a code example of using an extender on an ASP.NET page.
<asp:TextBox ID="TextBox1" runat="server"
Columns="7" MaxLength="7"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/Images/icon_colorpicker.gif" />
<cdt:ColorPickerExtender ID="cpe" runat="server"
TargetControlID="TextBox1"
SampleControlID="ImageButton1"
PopupButtonID="ImageButton1" />
Feel free to download the extender from the Codeplex, try it and post any comments or suggestions on the Codeplex project page.
Update 2020
Recently, I've visited the old and now archived CodePlex page for the ColorPickerExtender (https://archive.codeplex.com/?p=cpe) and found out that back in the day Microsoft had included that control on the official ASP.NET site (https://docs.microsoft.com/en-us/aspnet/web-forms/overview/ajax-control-toolkit/colorpicker/using-the-colorpicker-control-extender-cs). What a nice thing! Encouraged by this finding I've decided to resurrect the CPE and port it over to Angular, which is currently my favourite client-side framework. I will be introducing a new project on Git some time at the end of 2020, so stay sharp!
Monday, September 15, 2008
Working with VEColor class of VirtualEarth SDK
If you ever wanted to set a color for a custom VEShape object of type polyline or polygon than you must be familiar with the VEColor class that is used to represent a color in VirtualEarth SDK.
I am sure there are reasons behind of the design of the VEColor class, but for those who are used to a standard Web color representation in a form of 6-digit hexadecimal number it's kind of weird to provide 3 integer number in order to construct a color.
So I was in a search for some convenient ways of converting between VEColor and standard Web color and first place I looked through was of course the VirtualEarth Map control because I thought that the VE developers themselves would need a way to perform the same exercise. No surprise there is a couple of non-documented VE objects to support such conversion technique.
Here is a code example of using those objects:
// Create a convertor class
var converter = new VEHexStringToColor();
// Converter returns an instance of a VEColor class
// Transparency value is always set to 1.0
var veColor = converter.Convert("aabbcc");
// Adjust transparency value
veColor.A = 0.7;
// Convert VEColor to a string with a leading '#'
var webColor = VEColorToHexString(veColor);alert(webColor);
Both objects are available on the page after you reference a VE Map control v6.1. Of course there is no guarantee of any support of those objects in any future versions of the VE Map control so use it at your own risk and have fun.
Tuesday, June 17, 2008
Scalable CSS for Ajax Control Toolkit Tabs
If you use Tabs control from AJAX Control Toolkit library you may have noticed that the default CSS definition provided with the control does not display properly when you increase font size on a page, that is the default CSS is not scalable.
Since Tabs allows you to override CSS it's quite easy to fix a problem. Just grab a correct CSS file with the set of images and assign a CssClass property a new class name:
<ajaxToolkit:TabContainer runat="server" CssClass="myTabs" ...>
Now it looks more appropriate:
Thursday, May 22, 2008
ToolkitScriptManager and Web Deployment Project
If you use AJAX Control Toolkit in your project you probably use
ToolkitScriptManager from the Toolkit instead of standard ASP.NET ScriptManager class. Now if you want to deploy your web application using Web Deployment Project (WDP) for VS2008 then you will find out very quickly that your AJAX enabled application features don't work. The reason for that is there is a JavaScript error on a page saying that the root JavaScript object for AJAX Control Toolkit is not defined on the page and all the subsequent scripts relying on that object have failed. I am not reproducing the exact message here because it may vary in different situations.Background
You have tested your web application many times in your Dev environments and everything worked just fine. So what you've changed is you used a Web Deployment Project to build and deploy your web application and you presumably wanted to take advantage of a famous precompile and merge feature of the WDP.
Explanation
Now the problem is that the missing JavaScript on the page is rendered by a
ToolkitScriptManager object that generate a link to a JavaScript code using a ScriptResource handler which is in its turn supposed to retrieve the code embedded into assembly. Because WDP changes the names and locations of the assemblies ToolitScriptManager was unable to resolve the assembly name and could not generate the link so your page does not have that JavaScript reference any more.Workaround
Use standard ASP.NET
ScriptManager instead of ToolkitScriptManager and everything will work again.What's next?
I am in a process of investigating whether a
ToolkitScriptManager brings any advantages comparing to a new ScriptManager 3.5 in terms of more efficient HTML rendering and will post here my findings as soon as possible.Also if you are interested in employing a ToolkitScriptManager together with the Web Deployment Project I invite you to vote for this bug on Codeplex.






