Ales Rosina's blog

shelastyle.net
Subscribe

jQuery Project Template for Visual Studio

jQuery Summit 2009

Recently I wanted to create a few websites, more precisely, AJAX websites with a lot of animation and calling (external) web services. So basically, I needed HTML page with included jQuery library and support for IntelliSense and that’s it. No ASP.NET or any other server side stuff, like data access, MVC etc.
Since I wanted to reuse this project template, I did my own Visual Studio template – jQuery Project. Creating template is very simple, if you’re interested here is a very well written article about it by Rick Strahl.

In this template you have one HTML file with jQuery script tag included and MyScript.js file with a little trick on top to enable IntelliSense in external javascript file:

/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js"/>


We are referencing to Microsoft’s host servers, so we decrease latency, increase parallelism and creates better caching. Read more on that subject in this great article on Encosia.

That’s all what you need to develop with jQuery in Visual Studio. Download this template here.

Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | No Comments | Tags: ,
03
marec
2010

jQuery vs. ScriptManager in ASP.NET

2.22 - Learning

There are a lot of discussions around web, why using one and why not the other one. My reason was pretty simple: I wanted a lot of cool UI effects, that are already part of jQuery. At first I thought, OK, no problem, I’ll just include both of them on my site. But … there are some cases, where jQuery and ScriptManager just don’t get along and why including two different libraries with the same functionalities?

So I did run a very simple test – wrote the same functionality for both cases. Since the test is very simple, it’s hard to make any conclusions, but the jQuery version was more than half size than ScriptManager version. The problem is, that for jQuery version you need to write more code by hand, but sometimes that’s good, because you have more control over what’s going on.

Let’s take a look at both cases (download code here) – ScriptManager is very simple, just drag on website ScriptManager, UpdatePanel with one Button and Label and UpdateProgress with one label. On Button_click event just change text in Label, and you’re done. No big deal, your AJAX enabled site is done!

jQuery version is on the other hand a little bit more tricky, so let’s go step by step. First, add new html site and let’s add a jquery script reference:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

It’s recommended to include jQuery from Google servers, for 3 major reasons: decreased latency, increased parallelism, and better caching. Why, read here. Anyway, now we need to manually add a few divs, spans and a button. Like this:

<div id="UpdatePanel1"> 
<input type="button" name="Button1" value="Button" id="Button1" /> 
<span id="Label1">Label</span> 
</div> 
<div id="UpdateProgress1" style="display:none;">loading.....</div> 


Names are the same as in first example. OK, so here comes the tricky part – how the hell can we create server side code? Easy, with web services. So create new WebService1.asmx file and create new method Test().

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public string Test()
    {
        return "testing testing.";
    }
}
Let’s stop here for a moment - [System.Web.Script.Services.ScriptService] signature is very important, since this will tell service, that it’s supposed to return JSON and not XML. With [WebMethod] we expose method to web service. What about client side? Simple, just use jQuery’s .ajax() method like this:
$(document).ready(function () {
    $("#Button1").click(function () {
        $("#UpdateProgress1").show();
        $.ajax({
            type: "POST",
            url: "WebService1.asmx/Test",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $("#Label1").html(msg.d);
                $("#UpdateProgress1").hide();
            }
        });
    });
});

So when we click on button, first let’s show “loading” sign and than call web service. When the service returns result, success function will be triggered. This is where we show up result in a <span> and hide loading bar.

jquery
scriptmanager

As you can see, it’s a little bit more work than normal, but you will gain a lot – even in this simple example was the jQuery version (upper picture) more than twice smaller than ScriptManager version (lower picture). Not to mention, that you’ll get much nicer code and a very popular JavaScript library with a lot of other useful functions, like manipulating with elements, CSS properties and much more.

If you have a small project, where you don’t care about size, use ScriptManager, since it’s much faster to develop with. But if you need some cool effects and better performance, than use jQuery.

You can download source code for those two examples here.

Have any thoughts? Leave a comment!
Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | 1 Comment | Tags: , ,
24
februar
2010

Windows Phone 7 and developers

winphone7 Today Microsoft reviled their new OS for phones called Windows 7 phone at Mobile World Congress in Barcelona. There was a lot of rumors about it, how it will look like, what features will it have, when it’s available and so on. After this press conference, there are even more questions raised, at least for me. Let me just summarize a few key points of this new OS:

You can watch keynote (or newsroom) here, read a lot about it on Gizmodo, see a lot of pictures (and live coverage) on Engadget or see what are people twitting about it.
But that’s about it. No words about developer’s platform, any other third party applications etc. So, what can we developers expect? Where will we develop? How? So here are some basic information what I think will happen:

Let me just conclude with my though, that this was really necessary, since WM platform was already dying and Microsoft really needed to drastic move to survive on mobile platform. So decision to remove old apps support is one of the best, it is very similar to Palm’s move to WebOS from their old platform. And there will sooner or later be emulator for old applications, I’m pretty sure about that.
Disturbing is the rumor, that there will be no bypass from Marketplace, which can lead to another Apple AppStore like ridiculous rejections of completely legit applications. We will see about that.

I think Microsoft is back alive in mobile world. It’s a little bit early to compare it with competitors (Android, iPhone, Maemo, Palm), but it will surly be a bigger player than Palm. And for us, developers, that is a good thing.

Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | No Comments | Tags:
15
februar
2010

WebKit vs. IE browser control in C#

Recently I needed to include a web browser control (in Windows Forms project), so the logical choice would be WebControl, which is actually only .NET wrapper around Internet Explorer’s ActiveX control.

Well, I wanted to try some other engines, like WebKit (which is core of Apple Safari, Google Chrome, Adobe AIR, etc.), since IE engine (called Trident) scores on Acid3 very low (13 out of 100) and WebKit engine scores almost perfect (99 out of 100). For most cases this is not important, since most of web pages are done with optimizations for all browsers, but sometimes it is.

So for this test I’ve created very simple application, where you can compare those two rendering engines (you can download this app here, if you’re not interested in code).

I have run this app on a different sites and found out, that WebKit renders pages faster, if there is a lot of JavaScript behind, where simple plain HTML pages is rendered faster by Internet Explorer engine. So based on that, you have to decide which control to use in your application.

acid3 
For WebKit implementation I’ve used WebKit.NET, which is using Cairo derivate of WebKit (how to build it on your own, read here) and already includes binaries, so all you need to do, is to include WebKitBrowser in your toolbox in Visual Studio (right click on Toolbox > Choose items > .NET Framework Components > Browse… and select WebKitBrowser.dll from previously downloaded zip file) and drag it into your Form. Using this component is basically the same as using WebBrowser control, so you start navigation with

webBrowser1.Navigate(textBox1.Text);


and do something when document is loaded on event:

private void webBrowser1_DocumentCompleted(
object sender, WebBrowserDocumentCompletedEventArgs e) { //... }
And that’s it, you just created a very simple web browser.

You can download project (with source code) here, so you can play with code or if you want only app, download it here.
Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | 3 Comments | Tags: , , ,
07
februar
2010

Stop using IE6, please!

I was just checking statistics for my site and I was shocked by one particular information: nearly 8% of visitors are still using Internet Explorer 6. This graph represents only users of Internet Explorer, so the biggest part (66.63%) is the latest version of IE, which was expected.

browsers

And why was I shocked? Well, I’m writing about latest technologies, about programming, about web … so I thought, that visitors are mostly “geeks” like myself, who always wants the newest technologies, especially if the new one is better and much easier to use. And specially for us programmers is easier to develop stuff.

So I stumbled upon this particular website, called ie6update.com. It’s meant for us, developers, to somehow “force” users of sites to upgrade their old browser. In fact, if you go to this website with IE6, you can see it in action. What it does, it shows IE’s Information bar, with a little help of Java Script, with notice to upgrade your browser. I think it’s cool way of notifying users, but still not forcing them to switch, if they are really (I mean really, really, really) used to that old piece of software.

Join the “fight” and add this to your site, you and million of other developers will appreciate it :)

Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | No Comments | Tags: ,
05
februar
2010

Using Flickr in .NET applications

Wordmark of Flickr

Currently I’m working on a cool project, where I need to show some nice photos, just for visual effects. And the first thing I thought, where could I get cool photos? Easy, somewhere on the internet, right? Well, that can be tricky, since finding images on web is not that simple, there are license problems, images can be in poor quality, etc.
Since I’m also using Flickr for my own photos, it was obvious to choose this database. And it’s supposed to be the largest (public) database of images, photographs and even world famous artist are posting images on Flickr. OK, so we need to somehow access this database with our code. Sure, we can parse HTML, but that would be pretty stupid, since Flickr has great APIs exposed into the wild.

Flick APIs are exposed in various formats (JSON, SOAP, REST, etc.) but using that service in .NET applications means a little bit more hacking, if you want to do it by yourself. But there is one library, called FlickrNET, which was developed by Sam Judson. So I’ve used this library, which is super easy to use.

And as today is very popular for web services, you need to acquire API key, which you can get here for free.

For my case, I need to access just one random photo from Flickr Explore, since there are pretty cool photos from public photo stream. The only “hack” that I needed to do is to check, if there is a large image. In Flikcr, you (as author) can set to which sizes of photos others can access and if you upload smaller image than the “large” – which is defined by 1024 pixels width – Flickr will not create bigger image. So when requesting images, we need to take that into account – and here’s the code to do that:

FlickrNet.Flickr f = new FlickrNet.Flickr("your_api_key");
FlickrNet.Photos photos = 
f.InterestingnessGetList(FlickrNet.PhotoSearchExtras.All, 100, 1); bool stop = false; int stop2 = 0; FlickrNet.Photo photo = null; while (!stop) { Random r = new Random((int)DateTime.Now.Ticks); photo = photos.PhotoCollection[r.Next(0, 99)]; FlickrNet.Size[] size = f.PhotosGetSizes(photo.PhotoId).SizeCollection; if (size.Length == 5 || stop2 == 100) if (size[4].Label.ToLower() == "large") stop = true; stop2++; } pictureBox1.ImageUrl = photo.LargeUrl;

So what we are doing here is just get a list of 100 popular images, and then checking for the first picture, that has large format. We will get a URL pointing to that image in photo.LargeUrl property and since this is a ASP.NET application, that is enough. For Windows applications, you would need to do a simple WebRequest for getting the image and than showing it as Bitmap in picture box.
That’s it! Very simple and extremely useful for creating cool UIs. Leave a comment, if you have any question.

Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | No Comments | Tags: , ,
23
januar
2010

Locating Windows Mobile phone without GPS

Mobile phone and the Japanese 2

We all know apps like Google Maps Mobile, Microsoft’s Bing equivalent, Nokia Maps, etc. In every app you have option to locate yourself, even if you don’t have GPS or it’s turned off. The only thing you need is quite good signal and access to Internet.
Obvious question is: how is it done? Since I was playing a little bit with Windows Mobile, I’ll show you how to create simple app, which will show your current location. OK, not your exact location, but location of the closest Cell ID, which is in cities quite accurate (on few 100 meters).

This app is capable of showing Cell ID info, “transforming” it into latitude and longitude, finding the closest address and showing map of your location. To achieve this, I have used a few services, that are out there:

Everything is very well documented, so we just need to put everything together.

The first step is very easy – just download RIL.cs from Dale’s blog and include it into your Windows Mobile project. For showing up the Cell info, you just need to modify this function rilResultCallback in RIL.cs, because original function is lacking MNC (Mobile Network Code) data, so we will add this (bolded):

public static void rilResultCallback(uint dwCode,
                                     IntPtr hrCmdID,
                                     IntPtr lpData,
                                     uint cbData,
                                     uint dwParam)
{
    //....
    celltowerinfo = rilCellTowerInfo.dwCellID + "-" +
                    rilCellTowerInfo.dwLocationAreaCode + "-" +
                    rilCellTowerInfo.dwMobileNetworkCode + "-" +
                    rilCellTowerInfo.dwMobileCountryCode;

    //...
}

Before we will pass this data to Mobile Location service, we need to register ourselves for API key. It’s simple, just fill in the form and you’ll get API key. So, next thing is to pass Cell ID info into this web service. We have option of choosing JSON or XML version, and I have chosen JSON version (with no obvious reason), so I needed to somehow parse JSON into more usable form. For doing that, I used code, found in this blog post. Remember, we are on mobile device, so using very light libraries is essential, since those devices are still not so powerful. Also notice, to put your API key instead of “yourkey” string into web service url.

string cellInfoFull = RIL.GetCellTowerInfo();
string[] cellInfo = cellInfoFull.Split(new char[] { '-' });
cellInfo[0] = Convert.ToInt64(cellInfo[0]).ToString("X");
cellInfo[1] = Convert.ToInt64(cellInfo[1]).ToString("X");
WebRequest oRequest = WebRequest.Create(
String.Format("http://cellid.labs.ericsson.net/json/lookup
?cellid={0}&mnc={2}&mcc={3}&lac={1}&key=yourkey"
,cellInfo)); WebResponse oResponse = oRequest.GetResponse(); StreamReader oReader = new StreamReader(oResponse.GetResponseStream()); string sContent = oReader.ReadToEnd(); Hashtable h = (Hashtable)JsonParser.JSON.JsonDecode(sContent); string latlong = ((Hashtable)h["position"])["latitude"].ToString() +
"," + ((Hashtable)h["position"])["longitude"].ToString();

We could finish here, but let me just add a little map into our application. For doing that, we need another API key, this time from Microsoft – find it here. Again, very easy, just filling in form and you’re done.
For usage and very cool example (with all steps how to use this service) follow this link on MSDN, so I will not explain in detail how to use it. We will just copy two functions into our project (after we have added two web services – GeocodeService and ImageryService) - ReverseGeocodePoint(string locationString) and GetImagery(string locationString). The first function is ready to use:
textBox2.Text = latlong + "\n" + ReverseGeocodePoint(latlong);
pictureBox1.Image = GetImageFromUrl(GetImagery(latlong));
What we’ve done here is to “convert” latitude and longitude into actual closest address.
For the second we have to add function for downloading image from given URL, which is pretty straight forward:

private Bitmap GetImageFromUrl(string url)
{
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
    myRequest.Method = "GET";
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
    System.Drawing.Bitmap bmp = 
new System.Drawing.Bitmap(myResponse.GetResponseStream()); return bmp; }
So that’s it! Now you need to create cool UI and a little bit of try-catch stuff :)

Sure, this method will not work all around the world and is not accurate, so you need to do extensive testing, if you have plans to implement that kind of solution into your application.
What you can do to improve this method is to implement so called triangulation – basic idea is, that (especially) in urban areas, there are multiple cells, that covers each other. By tracking movements of your phone you can locate it much more accurate. I will finish here, since that would be completely out of scope, so leave a comment if you have any questions!
Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | No Comments | Tags: , , ,
16
januar
2010

Translations in .NET Applications

{{ca|La pedra de Rosetta resolgué un problema ...

In developing applications we all came to the point, when it would be nice, to have some kind of translations, let it be user interface translations, maybe some user input data, that needs to be instantly translated, etc. There are millions of use cases how we could create better user experience with a “simple” translations. But this can become very complicated, if we need to translate some text on the fly and can even be very expensive to translate static text in application into, let’s say, 50 different languages.
But today’s machine translations are getting better and better, with a lot of interesting techniques on how to translate text. I will not go deep into that subject, since it’s too complex for just one blog post :)

There are a lot of free services for translations, some are good, some totally suck. The most famous (and probably the best free one) is Google Translate tool, which also allows developers to use it programmatically. The second one is by Microsoft, called Microsoft Translator (or Bing Translator). Big difference between Google and Bing is number of supported languages – Google have 51 languages, Bing has only 22. But for .NET developers, Bing is much easier to implement. So we are going to see, how to implement those two services into simple Console application.

Both have very good written documentation (Google’s documentation and Bing’s one), the only problem is, that Google’s service is made only for AJAX apps. With that in mind, we must know, that means parsing JSON in .NET. Luckily, we have a lot of parsers already written. I have chosen open source library called LitJSON. When we import this library into project, it’s very easy to use it. But for customizing it to Google Translate, we need to do some hacks, which is very well written in this blog post by Dan Matthews, so I’ll do just a quick overview. The most important line of code is

WebRequest oRequest = WebRequest.Create(
"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q="
+ HttpUtility.UrlEncode(userInput) + "&langpair=%7Cen");

We have defined here, where is Google Translator located with all necessary attributes. Attribute langpair=sl|en defines from and to which language should service translate text (in this example, from Slovenian to English). If you leave the first language empty, than Google will try to detect the correct language. You should note here, that longer the text is, we have better chance of correct language detection. As I said, for more details check Dan’s blog post.

Now let’s take a look at Microsoft solution. As expected, they have a “true” SOAP service, which means, that you can implement this service with two clicks in Visual Studio. There is only one more step, before you can start using this service, registration of your application. Just go to this address and log in with your LiveID, fill in the form and you will get API ID. When you’re done with that, add a service reference – in Solution Explorer inside Visual Studio, right-click on References folder, and choose Add Service Reference, paste this http://api.microsofttranslator.com/V1/SOAP.svc URL inside box and press Go. Just name the namespace LiveTranslator for example, and you’re ready to use in it in code. Here is example code:

Console.Write("Input text to translate: ");
string userInput = Console.ReadLine();
//create web request to Microsoft Translator LiveTranslator.LanguageServiceClient cl =
new ConsoleApplication2.LiveTranslator.LanguageServiceClient(); //just for checking, let's write out, which language did service detect
//note: instead of myApiId you shoud write in your api id
string detectedLang = cl.Detect("myApiID", userInput); Console.WriteLine("Detected language: " + detectedLang); //write out transaltion Console.WriteLine(cl.Translate("myApiId", userInput, "", "en"));
That’s it! As we can see, code for Bing translator is much more clean, but we could also write a small wrapper for Google Translate, if we need to do a lot of translations inside our app.

You can also download example application on my SkyDrive. Any questions? Just leave a comment!
Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | 2 Comments |
09
januar
2010

My new business cards

A month ago I have created brand new business cards, first truly mine. I was thinking about design, which would be similar to my webpage, simple to recognize and easy to read, but still with just a little bit of custom touch. First I was thinking about ordering them through moo.com service, but I couldn’t create cards, that would be cool enough. So I just downloaded their jpg file, which shows format sizes for standard business cards. After a few hours of designing and drawing, I came up with this:


vizitka_preview



I was satisfied, so I went to search for a good (and cheap) print service. I could still use moo.com (which is very popular, by the way) for prints, but I decided to find some local printing office, since delivery would be faster. And after couple of days, I got a pack of about 100 cards. They even put some extra in the pack! So the final result was pretty cool, and here’s the photo of cards dropped on my laptop:


vizitka_small 

So what do you think about this design? Leave a comment!



Bookmark and Share
author: Aleš Rosina | 3 Comments | Tags: ,
07
januar
2010

BlogEngine with simple gallery

thumbnail‎

Are you a user of BlogEngine.NET? If you don’t know that engine yet, it’s quite cool engine written in ASP.NET for obvious purpose, blogs.
I love this engine, because it is very well written, so it’s a piece of cake to extend it for your own needs. There are lots of themes, extensions and projects based on this engine.
I’m using this engine for various sites, and recently I had to implement a gallery. What I did, was very simple solution, I created one folder called gallery, where various galleries are stored - every gallery is it’s own folder. And in every gallery, there is a subfolder called thumbs, where thumbnails of pictures are stored. But you don’t need to bother with that, since I also did admin part for uploading images. But let’s take a look step by step how to implement this gallery into your blog:

As I said, it’s very easy solution, so for customizing it, you will need to dig into some code. So for all of you, let me explain a little bit of code and what have I done.
First of all, this code is in code-behind for site.master in my theme:

protected string GetGalleryMenu()
{
    string result = "";
    foreach (string item in Directory.GetDirectories(MapPath("/gallery/")))
    {
        DirectoryInfo di = new DirectoryInfo(item);
        if (this.Request.Url.Query.ToLower().Contains(
Uri.EscapeUriString(di.Name.ToLower()))) result += "<option value=\"/gallery.aspx?gal=" +
di.Name + "\" selected>" + di.Name + "</option>\n"; else result += "<option value=\"/gallery.aspx?gal=" +
di.Name + "\">" + di.Name + "</option>\n"; } return result; }

It’s just looping through gallery folder and creating dropdown menu for all the galleries. In aspx page, you call that function simply by inserting one line of code,where you would like to have this menu:

<select OnChange="location.href=this.options[this.selectedIndex].value" 
style="width:220px;" name="menu"> <option value="#">[gallery]</option> <option value="#">--------------------------------</option> <%= GetGalleryMenu() %> </select>


Another piece of code is gallery.aspx, where I list all the images, that are inside selected folder:

protected string GenerateGallery(string path)
{
    string fullPath = "/gallery/" + path;
    string result = "";
    foreach (string item in System.IO.Directory.GetFiles(MapPath(fullPath),"*.jpg"))
    {
        FileInfo fi = new FileInfo(item);

        result += "<a href=\"" + fullPath + "/" + fi.Name + 
"\" rel=\"lightbox[becooldontwaste]\"><img src=\"" +
fullPath + "/thumbs/" + fi.Name + "\" alt=\"Slika\"></a>\n"; } return result; }


And that’s it, what is needed to view galleries. Simple, right?

Now let’s take a look at admin part. This one is a little bit trickier, but as I said, BlogEngine is very well written, so what I need to do is just added one line in Web.sitemap and before that created file in admin/Pages called Gallery.aspx.

<siteMapNode url="~/admin/Pages/Gallery.aspx" title="Gallery"  
description="" roles="administrators, editors"/>

It’s pretty straight forward, in roles you define who can access this part of admin module and in url you define path to admin page for gallery “module”.
Last thing is to see how did I manage to upload files to server and store them on system. The idea was, that before storing to server, I need to resize it and create two different copies – thumbnail and big picture. Before resizing, there is also a check, if the uploaded file is image or not. Obviously, I don’t want users to upload anything else than image.
The most important function is

protected void btnAddNewImg_Click(object sender, EventArgs e)

where we do all the “magic” of resizing and storing images on server. Change image sizes here in this function.
And if you want different “type” of resizing, you should edit this part of function:

private static Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
    //....
    //if (nPercentH < nPercentW)
    //    nPercent = nPercentH;
    //else
    //    nPercent = nPercentW;

    if (sourceWidth < sourceHeight)
        nPercent = nPercentH;
    else
        nPercent = nPercentW;

    if (size.Width == 0)
        nPercent = nPercentH;

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);
    //.....
}

That’s it, if you have any comments, leave them here! Happy coding!

Oh, and take a look of this gallery in action on this site.

Reblog this post [with Zemanta]


Bookmark and Share
author: Aleš Rosina | 16 Comments | Tags: , , ,
24
december
2009