This is a mirror of official site: http://jasper-net.blogspot.com/

Ubuntu 10.10 on Android, the Slightly Less Difficult Way

| Saturday, April 9, 2011
In case you haven’t noticed, I tend to like doing things the easy way. Our own Portal Admin, Egzthunder1 is no different, preferring the easy way at times. Heck, even everyone’s favorite Azrienoch over at XDA TV just finished covering how rooting the manual way is for snobs. Well, unfortunately there’s no “easy way” to install Ubuntu on Android. However, XDA forum member fire314, has you covered with a slightly less excruciatingly painful way! Jump past the break for more.

Why would you want to do this? Good question!

An ubuntu 10.10 maverick (with LXDE window manager) machine in your pocket. Perfectly usable from the phone itself using a VNC client, this allows you to install any ubuntu software onto your phone and have it with you always. Coupled with the (potential) ability for your phone to be hooked up to a television with TV Out (works with the Nokia TV Out cable available on eBay), and for (supposedly any) HID-compliant bluetooth keyboard and mouse to be linked up to the phone (requires Android 2.2), this really does become a PC in your pocket.
Not convinced that this could actually be doable without too much effort? Well, why not take a look at the instructions:
How to boot:
- Place ubuntu.sh and ubuntu.img in the same directory in your SD storage.
- Enter a terminal and enter ‘su’ to become a superuser (root).
- Navigate to the directory where you placed the files (e.g. “cd /sdcard/external_sd/ubuntu”).
- Execute the script by typing “sh ubuntu.sh”.

Read more: xdadevelopers

Posted via email from Jasper-net

Mono for Android now available. C# and .NET developers rejoice now that you can make apps for Android

|
b_500_274_16777215_0___images_stories_news_mono_mono-for-android.png

It must be developer news day today or something, not that we are complaining. The more tools developers have, the better they can make good games with! Mono for Andorid, now available for general consumption, will allow developers to develop applications and whatever else they want to using technologies like C# and .NET.

MonoTouch is similar to Novell's other product, MonoTouch, which allows iOS developers the same flexibility that Mono for Android is giving to Android developers, allowing them to develop iOS applications using C# and .NET for the iPhone, iPod, iPad. However, using both MonoTouch and Mono for Android side-by-side will allow developers to share code across all platforms from Android to Windows Mobile and iOS which will save time for developers who can then worry less about porting and more about game quality.

Included in Mono for Android:

Core Mono Runtime
Bindings for native Android APIs
Visual Studio 2010 plugin
An SDK containing relevant tools to build, debug and deploy your applications

Read more: Droid games
Read more: Mono-android

Posted via email from Jasper-net

Google Makes Android More Attractive For Google Apps Users With New Remote Capabilities

|
Just another step in Google’s efforts to make Android more appealing to businesses – an update to the Google Apps Device Policy application has added three new features to make your Android device more secure:
  • Remote Location: Any Android 2.2+ device can be located remotely via GPS or by making it ring. The PIN or password can also be remotely reset.
  • Data Encryption: Android 3.0 introduced data encryption, and now Google Apps users have the ability to encrypt this data remotely as long as the App Device Policy is already installed on the device.
  • Google Apps Lookup: An entirely new app, Google Apps Lookup allows Apps users to find contact info for anybody in the Google Apps Global Address List.
These features will all be very helpful for business users, but hopefully we’ll also see them make their way to non-Google Apps users some time in the future.

Read more: Android police

Posted via email from Jasper-net

Control Your PowerPoint Presentations On Open Office With Your Android Device

|
So, lets say that you are in the middle of a conference and have to present some really important work to your team or prospective customers. Your computer is hooked up to a good projector, and you are all dressed up and ready to go. The last thing on your mind is that you will have to be close to your computer in order to get the different slides to show up on the overhead. Well, as you are currently in a bind with no way to run anywhere to get a remote control for this, you are left with no alternative than to pull out your trusty Android to do the job for you. XDA member v XenOn v has made an Android app that will allow you to control Open Office Presentation or PowerPoint software remotely. The app is simple to set up and works wonderfully well, and you will leave everyone’s head spinning as to why you can control your presentation with your phone. There is a .jar file that needs to be installed in your computer for this to work, which means that you also need Java in your computer as a requirement.

Read more: xdadevelopers

Posted via email from Jasper-net

The truth behind Android’s “Remote Wipe” ability

|
My morning started as most of my mornings do, Tablet in hand I trudge around my house making sure my little ones are getting breakfast and readying for school. I flick through all of the news and commentary I may have missed in the last 8 hours, catch a few webcomics, and if I am feeling adventurous I will even check out Twitter. This was one such morning where a flick through twitter revealed more than a few people upset that someone had discovered a “kill switch” in the Thunderbolt source code. Through the Droid Rage, it was pointed out that this bit of code is not exclusive to the Thunderbolt.

You can find the snippet of code that I will be referring to HERE.

package com.android.server;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.RecoverySystem;
import android.util.Log;
import android.util.Slog;
import java.io.IOException;

public class MasterClearReceiver extends BroadcastReceiver
{
  private static final String TAG = "MasterClear";

  public void onReceive(Context paramContext, Intent paramIntent)
  {
    if (paramIntent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
    {
      String str = paramIntent.getStringExtra("from");
      if (!"google.com".equals(str))
        int i = Slog.w("MasterClear", "Ignoring master clear request -- not from trusted server.");
    }
    while (true)
    {
      return;
      try
      {
        int j = Slog.w("MasterClear", "!!! FACTORY RESET !!!");
        RecoverySystem.rebootWipeUserData(paramContext);
        int k = Log.wtf("MasterClear", "Still running after master clear?!");
      }

Read more: Android and me

Posted via email from Jasper-net

requestedExecutionLevel level=requireAdministrator

| Friday, April 8, 2011
כיצד להגדיר את האפליקצייה שלכם שתרוץ עם הרשאות מנהל.
כדי להגדיר זאת תצטרכו להכין קובץ עם סיומת manifest ולכתוב את הקוד הבא
 
<?xml version="1.0" encoding="utf-8" ?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="WebcastController" type="win32"/>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
      <security>
        <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator"/>
        </requestedPrivileges>
      </security>
  </trustInfo>
</assembly>
 

Posted via email from Jasper-net

To box or not to box, that is the question

|
Suppose you have an immutable value type that is also disposable. Perhaps it represents some sort of handle.

struct MyHandle : IDisposable
{
    public MyHandle(int handle) : this() { this.Handle = handle; }
    public int Handle { get; private set; }
    public void Dispose()
    {
        Somehow.Close(this.Handle);
    }
}

You might think hey, you know, I'll decrease my probability of closing the same handle twice by making the struct mutate itself on disposal!

public void Dispose()
{
    if (this.Handle != 0)
      Somehow.Close(this.Handle);
    this.Handle = 0;
}

This should already be raising red flags in your mind. We're mutating a value type, which we know is dangerous because value types are copied by value; you're mutating a variable, and different variables can hold copies of the same value. Mutating one variable does not mutate the others, any more than changing one variable that contains 12 changes every variable in the program that also contains 12. But let's go with it for now.

What does this do?

Posted via email from Jasper-net

Android-x86 Project - Run Android on Your PC

|
android-x86-120.png?attredirects=0

This is a project to port Android open source project to x86 platform, formerly known as "patch hosting for android x86 support". The original plan is to host different patches for android x86 support from open source community. A few months after we created the project, we found out that we could do much more than just hosting patches. So we decide to create our code base to provide support on different x86 platforms, and set up a git server to host it.

This is an open source project licensed under Apache Public License 2.0. If you think we did something great, consider making a donation.

Posted via email from Jasper-net

Deal with Performance in WPF applications

|
Hi friends,

WPF is one of the major changes to the desktop applications in recent times. Most of us is using it in your day to day life programming. Some use for normal desktop or windows based applications while others write programs that run in browsers as Sandboxed application. The major investments of Microsoft on making silverlight to work out of browser enhanced the usage of WPF in a larger extent. But as for any other application, performance is the major issue for your application. Its not how well you structured your application, or how loose couple your UI with other layers, it is often a requirement for any software on how it acts in stressed situations.

One of such performance hits that might appear for your WPF application is over utilization of CPU. In this post, I will cover some of the general performance hiccups with WPF which you might consider unnecessary for your application or may be you want just to identify them for your application. Lets put few of the performance improvement tips for you in this post : 

Try not to be Smarter

WPF architecture is well written to handle performance of your application in smart way. It draws only the portion of the screen which is visible through the window. Hence if you have code which hides an element in WPF window, the Frames which WPF rendering engine draws will not take up those elements.

Hence it is unnecessary to Remove a child element from a Container (even with having a strong reference of the control for future) to improve the application performance, rather it is ok if you just hide the control visually.For instance, Let us suppose you have a TextBox on the screen, now for certain situation if you want to hide the TextBox from the screen, it will not be an issue to hide the Textbox rather than actually removing the TextBox from the Visual Tree.

Basically WPF runs with two threads (not only) which you should know. 

1. UI Thread  : Sometimes called as Dispatcher Thread is actually a Thread that runs all the managed code within it. This thread creates each element of WPF and every control has Thread affinity for the thread. Every control in WPF inheriting from DispatcherObject does holds the reference of this Thread in the form of DispatcherThread property. Hence if you want to run any Non-UI thread to invoke a statement, like if any of your non-ui thread needs to update any WPF element, you should use code like this :

this.Dispatcher.BeginInvoke((Action)delegate()
{
    //Write your Code here
}, DispatcherPriority.ApplicationIdle);

Read more: DOT NET TRICKS

Posted via email from Jasper-net

Lazy Load XAML content from External File and Vice Versa

|
XAML is the most flexible language built ever. More I see XAML, more I know about it. Today while tweaking around with XAML code, I found XAML could be loaded dynamically from any XML string. That means if you have a xaml in a xml file you can probably load the part of the XAML into your ContentControl or to any control element you want and the UI will appear instantly. 
Once you compile a XAML it produces BAML. BAML is in binary format for the XML, so if you can pass a BAML into the UI separately somehow during runtime,you would be seeing the content instantly in the Window. In this post I am going to discuss how easily you could load a Dynamic content of XAML file into a normal WPF ContentControl just like what we do for normal htmls.
What is XamlReader and XamlWriter? 
If you look into the implementation of these classes you could wonder how flexible these are. They are highly capable of parsing the whole content of the file. It uses a XAMLDictionary which holds all the XAML elements that a XAML can see. The Reader parses the Xml content very cautiously to ensure it makes the XAML file to contain no reference of outside. Thus the class is used to Refactor the XAML from outside and hence allows you to put the content anywhere such that everything will be applied on that instantly.
XamlReader exposes methods like Load / Parse which allows you to parse a file content into BAML. Hence each of them returns an binary object which you can put into the Content.

The sample application implements these features to store the Xaml content into an external file and later on it loads the same content from the file to show up the content again.

Read more: Dot net tips

Posted via email from Jasper-net

c# and SQL interview question :- What is the difference between unique key and primary key?

|
Unique key can have nulls
Primary key cannot have nulls.

In a single table we can create multiple unique keys.In a single table we can have only one primary key.
=============================================
Unqiue key creates a non-clustered index by default.Primary Key created a clustered index by default.
================================================
Both unique keys and primary keys can be referenced by foreign key.

Read more: Youtube

Posted via email from Jasper-net

Step by Step to discuss Application Library Caching in Silverlight 4

|
Introduction

Sometime your Silverlight application becomes too larger and creates a bigger XAP file. This causes issue while loading your XAP file for the first time as it increases the loading time for downloading the XAp. So, what will you do in this case? There is one answer: split your application in multiple projects which will create multiple XAPs and then use On Demand downloading feature. 

Absolutely right, but you may sometime include 3rd party assembly references. In such case, storing them in a separate XAP and writing the code for downloading them on demand will be another hectic. So, what's the easy process? In this article we will learn the same. Read to know more and provide your feedback in case you need more information. 

Assembly caching is not a new thing in Silverlight 4. It was present since Silverlight 3. Today I got a chance to look into it and thought to share the same with depth details to you. 

So, what is Application library caching? We all know about the on demand download of XAP. To do this, we need to write code for downloading the external xap files using WebClient. Application Library caching does the similar thing for you very easily. Suppose, if you have a bigger application and used a huge 3rd party libraries, this easy step will help you make a separate zip file with them which can be downloaded on demand without writing any additional code. 

Many people don't know about it and hence let's start describing that here. 

Step 1 - Digging inside XAP:

First of all, we will create a small Silverlight Application project. To do this, open your Visual Studio and create that. 

Read more: Codeproject

Posted via email from Jasper-net

Minimizing Hibernate Schema Complexity

|
In my applications I persist a lot of structured data into the database. Hibernate and other ORMs are great at making this easy to do. One problem is that they tend to map the entire object structure to rigidly structured database fields and tables. Quite often that's just overkill.
STRINGS AS A BLACK BOX DATATYPE

Take strings for instance. A VARCHAR makes perfect sense if you know the string will always be less than, say, 30 characters. Even if your not going to use that string field in a where clause, ever.
But if you won't know the max size the string will be for every instance, or it could be a very large string and you're never going to use it in a search, then your fine using a LOB column to store that string.

Modern ORMs will even read/write the whole string value into/out from the LOB column for you. Or give you the CLOB instance itself for better performance, whichever you prefer.

I've experienced many DBAs that don't like the use of LOB columns. But I've never understood that, as this is exactly the purpose that LOB columns were meant to solve. The storage of arbitrary data in the database, no different than in a file, without any sort of internal random access, indexing, or searching. A Blackbox-column to the database server, if you will.

COMPLICATED OBJECT GRAPHS

Worse is when you have classes with lots of field and subobjects. This can get messy, even if they're just value objects.
The multiple tables, table hierarchies, link tables, and huge column lists that can result, while entirely valuable for some classes, are just overkill for others. Especially when you won't be indexing, searching or retrieving individually, any of those fields/rows/objects.

PERSISTING SERIALIZED CLASSES

ORMs can persist a whole instance into one field. They do so using serialization of some form or another to turn the instance into flat data like a byte array. Then this data can be persisted as a BLOB value.
In the case of Hibernate, its as simple as marking a reference (non primitive) field with @Lob, just as with the strings. But in this case, by default, Hibernate will use the standard java serialization mechanism. Which some would take exception *cough* to.

You can provide your own serialization mechanism of course. I'm not sure how to do this across the board for hibernate. But my solution is just to create a custom hibernate UserType implementation. Then I can mark the fields with this custom UserType, that I want stores as non-entities.

This is surprisingly easy.

XML

For the serialization format, I chose XML. There are a number of good XML serializers for java objects. Some even work well on arbitrary classes, though you shouldn't be putting just any classes in your databases columns.

Posted via email from Jasper-net

ASP.NET HTML Controls

|
I have recently completed to develop the seventh topic in my ongoing ASP.NET course. It focuses on the ASP.NET HTML controls. You can find the community version of this ongoing course available for free at www.abelski.com. The professional version is available at www.xperato.com. You can download the slides and watch the relevant video clips below.

Read more: Life Michael

Posted via email from Jasper-net

ASP.NET Web Controls

|
I have recently completed to develop the eighth topic in my ongoing ASP.NET course. It focuses on the ASP.NET web controls and explains how to use the more complicated ones. You can find the community version of this ongoing course available for free at www.abelski.com. The professional version is available at www.xperato.com. You can download the slides and watch the relevant video clips below.

Read more: Life Michael

Posted via email from Jasper-net

Start Debugging with Windbg

|
Hey folks, I’m a big fan of Windbg. It’s really powerful and you can do much more things than you can do with another other debugger!

In this blog post I’m going to show you different methods to start debugging with windbg.

Start by launching the process with Windbg

This is easy. If you need to debug a simple application and you have the exe path, you can launch it with Windbg either from the command line or from the UI. All you need to do is launching Windbg and clicking “Open Executable” menu item from the File menu. You can then provide executable path and arguments to the process. Once you click Open, your debugging session starts.

Start by attaching the process to Windbg

If you have a process that’s already running, you can use this option to start debugging with Windbg. This option is useful when debugging services or processes that cannot be restarted. To do so, launch the Windbg and select “Attach to a Process” menu item from the File menu. Windbg will display a list of processes that you can select any to attach it to the debugger. Once you click OK, your debugging session starts.

Start by using Gflags

This is a little bit advanced. You can use gflags.exe, a utility tool for processes, to start the process under Windbg. Here is how it works: You write the executable name to the GFLAGS under Image File tab and it displays you a bunch of options. In the below image, I launched the gflags.exe as administrator, switched to Image File tab and wrote notepad.exe as image name. When I clicked the TAB key, it displayed options associated with the notepad executable. The Debugger option should be filled to point to Windbg.exe path in your system.

7510.image_5F00_thumb_5F00_3DB93989.png

Read more: Emre's blog

Posted via email from Jasper-net

Организуем view models в ASP.NET MVC

|
В интернете полно примеров вроде «Делаем вики на ASP.NET MVC за 15 минут». Проблема таких примеров в том, что они используют VideData или ViewBag для передачи данных в View. Для генерации форм используются нетипизированные методы вроде Html.TextBox(). А для получения данных из форм просто параметры к методам контроллера, или хуже того – сами сущности из ORM.

Это может быть прекрасно с точки зрения того, кто в жизни имеет дело только с созданием таких «видео уроков». Но в немного более сложных случаях вы, конечно же, захотите иметь строго типизированные модели, использовать строго типизированные методы вроде Html.TextBoxFor(m=>..), и получать в методе контроллера из формы ровно то, что хотите получить и при этом держать все модели в консистентном виде. 

Итак, правила, если вы хотите разрабатывать в MVC:

Каждому View свой персональный класс ViewModel.
Только View диктует, какие будут свойства у ViewModel. Остальное – проблемы контроллера.
ViewModel – это простой DTO, без логики.
View использует только те данные, которые приходят из ViewModel, ничего больше. Не трогайте Request.IsAuthenticated в ваших View, для этого есть модель.

Может возникнуть вопрос, а как быть с _Layout (мастер страницами) – ведь это тоже View и они тоже хотят свои модели. Вполне резонно – ведь мы помним, что view диктует модель, всё остальное следует потом. Поэтому создайте в приложении класс SharedLayoutViewModel с нужными вашему _Layout.cshtml свойствами, и наследуйте от него ваши модели для остальных View. Пользуйтесь Result-фильтрами чтобы наполнять эту модель в одном месте для всех методов ваших контроллеров. Или переопределите OnResultExecuting в базовом классе ваших контроллеров, и делайте это там.

Read more: Habrahabr.ru

Posted via email from Jasper-net

Microsoft Announces Mobile Management Tool for iPhone, Android & More

|
Believe it or not Microsoft held a conference last week that was devoted completely to device management. Dubbed the Microsoft Management Summit (MMS), Microsoft looked at many ways to manage the variety of devices in your organization. 
They described it as follows on the event web page:
“At MMS 2011, you’ll drill deep into IT management technologies and learn about the latest solutions for Desktop, Datacenter, Device and Cloud management from Microsoft.”
Now, you might expect since it’s Microsoft that this was exclusively devoted to managing Windows devices — whether PCs, tablets or mobile phones — but you would be wrong. In fact, Microsoft announced the Beta of a new monitoring tool that they claim enables you to track iOS devices (both iPhones and iPads). Symbian (that’s Nokia’s OS for now until they switch over Windows Phone 7 next year) and Android.
It also lets you watch your servers and clients (although presumably these are Windows only).
The tool, The System Center Configuration Manager 2012 (SCCM 2012), will supposedly enable IT pros to manage this variety of devices from a central console. According to a post by Mary Jo Foley, Microsoft reporter  extrordinaire, on ZDNet, the new tool has been designed specifically to handle the so-called consumerization of IT, which has lead to the proliferation of a variety of mobile devices across the enterprise.
Microsoft released its second SCCM beta last week. From a monitoring stand-point, this is a big departure for Microsoft which typically confines its monitoring to Windows devices. While Foley suggests this undercuts Microsoft’s claim that Windows tablets are superior to iPads and Android tablets, I think it shows surprising foresight to acknowledge the breadth of the existing market and to provide a way to monitor all of the mobile devices in the organization.

Posted via email from Jasper-net

AES Encrypted Serialization Tutorial

|
Advanced Encryption Standard (AES) also called the Rijndael cipher, based off a combination of the two Belgian author's names Joan Daemen and Vincent Rijmen.  AES was accepted in 2002 to replace DES cipher and quickly became the preferred encryption choice to hide secret data. AES is a symmetric cipher, also known as shared key cipher, which means that it uses one single key for both encryption and decryption. 

In .Net the AES is visible through the System.Security.Cryptography namespace.
I use the RijndaelManaged class in this example to show you how to easily take a object, serialize it to an XML string, encode it to a byte array, and then deserialize it back to a new copy of the original object. 

This example originates from a recent project of mine where I needed to securely store a user object containing sensitive information. This way I can quickly load and save my serialized object to disk and have it encrypted using my secret key.

To show you the different steps, I created a Console App that goes through the different steps:

class Program
    {
        static void Main(string[] args)
        {
            const string SecretKey = "needstobe32bytesneedstobe32bytes"; //need to be 32 bytes for 256 bit encryption

            var oldUser = new User() {Password = "mysecret", Username = "MyName"};
            var str = Serializer.SerializeToString(oldUser); //Serialize User to XML string

            Console.WriteLine("Serialized object: "+str);
            User newUser = Serializer.FromString<User>(str); //Deserialize User from XML string
            Console.WriteLine("****");
            Console.WriteLine("Old user name is: "+oldUser.Username+" and new user name is: "+newUser.Username);
            Console.ReadKey();

            byte[] encryptedOldUser = Security.Encrypt(str, SecretKey); //Encrypt XML string using AES 
            Console.WriteLine("Encrypted old user: "+Encoding.ASCII.GetString(encryptedOldUser));

            Console.WriteLine("****");
            string decryptedOldUser = Security.Decrypt(encryptedOldUser, SecretKey); //Decrypt bytes
            Console.WriteLine("decrypted old user: " + decryptedOldUser);

            User secureUser = Serializer.FromString<User>(decryptedOldUser); //Serialize back to a new User object
            Console.WriteLine("****");
            Console.WriteLine("Old user name is: " + oldUser.Username + " and secure user name is: " + secureUser.Username);
            Console.ReadKey();

        }
    }

Read more: robbanp

Posted via email from Jasper-net

ASP.NET MVC 3.0 Internals

|
ASP.NET MVC 3.0 Internals
בפוסט זה אני רוצה לכתוב על איך עובד ה- ASP.NET MVC 3.0 ואיפה אפשר להרחיב ולשנות את הטכנולוגיה.

אני מחלק את הפוסט לארבעה חלקים:

1. החיבור בין ASP.NET ל- ASP.NET MVC
2. Controller Extensibility
3. Model Extensibility
4. View Extensibility

1. החיבור בין ASP.NET ל- ASP.NET MVC.
ה- MVC חי בתוך ה- ASP.NET וכדי לשנות את סדר הפעולות שקורות ב- ASP.NET הוא משתמש במנגנון ה- Routing שנוסף בדוט-נט 4, הוא רושם אוביקט Route ל- RouteTable.

clip_image002_thumb_7B0D9450.png

ב- Global.asax.cs אנחנו יכולים לראות את הקוד הבא:

routes.MapRoute(
    "Default",                    // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new                           // Parameter defaults
    {
       controller = "Home",
       action     = "Index",
       id         = UrlParameter.Optional
    }
);

המתודה MapRoute היא Extension Method תפקידה ליצור אוביקט Route שמקשר בין ה- "{controller}/{action}/{id}" ל- MvcRouteHandler. אם מסתכלים בתוך הקוד של המתודה MapRoute נמצא את השורות הבאות:

var route = 
     new Route( url , new MvcRouteHandler() )
     {
        Defaults    = new RouteValueDictionary(defaults),
        Constraints = new RouteValueDictionary(constraints),
        DataTokens  = new RouteValueDictionary()
     };

Read more: I Love C#

Posted via email from Jasper-net

Good to meet you Source. And you, Source... And you... Using Source Meet to meet about source [Beta]

|
image%5B3%5D.png?imgmax=800

  • Source code collaboration from anywhere, in real-time
  • Integrated Instant Messaging
  • Virtual project team grouping and collaboration
  • No third-party applications required
  • Full integration into Visual Studio™
  • Based on a secure P2P overlay network, which provides a very high level of security

Read more: Source Meet

Posted via email from Jasper-net

How to create a Visual Studio add-in that launches from the Project window

|
Introduction

Within Visual Studio 2010, there are two main ways to install add-ons that allow you to make modifications to a Visual Studio project. The first way is to use Visual Studio templates. Templates are a great way to duplicate work that you would commonly need to do such as add license information to the top of every class. Another way is to use add-ins. Add-ins typically run from the Visual Studio Tools menu and allows you to run a program to do something. In our case, we were writing a component for our customers that would modify the Windows Azure service config file, and add-ins seemed to be the best way to accomplish this. The main issue with add-ins is that they run from the Tools menu so if you want to be able to make changes to a project of the user's choice, there is no way to do this unless you actually ask the user which project to modify. This would give a very bad user experience. What would be best is if a user could right click on a project to launch the add-in. Surprisingly, we could find very little information on the subject. Luckily, it is quite simple. This tutorial will walk you through the process.

Using the Code

To get started, open Visual Studio 2010 and create a new project and choose Other Project Types | Extensibility | Visual Studio Add-in. Leave the Name as the default name MyAddin1, and press OK.

visual_studio_addin.png

Read more: Codeproject

Posted via email from Jasper-net

SQL SERVER – Fix : Error : The request failed or the service did not respond in timely fashion. Consult the event log or other applicable error logs for details

|
Two days ago, I was participating TechEd India 2011 and I had great time presenting on various subjects. My computer fortunately behaved very well and I consider myself lucky for it. However, very next day today, when I went to office and turned on the machine, it did not start SQL Server. I was bit confused and very quickly checked SQL Server Services. I noticed that services were OFF. I tried to turn on the services but it keep on giving me following error.

Error:

The request failed or the service did not respond in timely fashion. Consult the event log or other applicable error logs for details.

starterror.jpg

Posted via email from Jasper-net

Common problems with Notifications from a View Model

|
In the MVVM (Model, View, ViewModel) pattern in xaml based applications (Windows Phone 7, Silverlight and WPF) there are two different ways a view model will notify the view of changes. If you're unaware of the differences you can end up wondering why your changes aren't being reflected in your view.

The most common is implementing the INotifyPropertyChanged interface, the other is through the INotifyCollectionChanged interface. Most developers really won't use second interface but its useful to know about and how it affects your view model.

When you bind to a property on your view model the binding infrastructure will listen for INotifyPropertyChanged events from your view model for that property.

If the type of the property implements INotifyCollectionChanged (such as ObservableCollection) it will also listen for events off that property.

The distinction is important because a common pattern with developers is implement collection properties as automatic properties. This however limits the way you can interact with the collection such that changes will be reflected in the view.

public class CorrectViewModel : ViewModelBase
{
    public CorrectViewModel()
    {
        Items = new ObservableCollection<Item>();??
    }
 
    public ObservableCollection<Item> Items
    {
        get; set;
    }
 
    public void Add()
    {
        var items = GetItems();
 
        Items.Clear(); // Collection changed raised
 
        foreach(var item in items)
        {
            Items.Add(item); // Collection changed raised
        }
    }
 
    private IEnumerable<Item> GetItems()
    {
        return from i in Enumerable.Range(0, 10)
                select new Item
                {
                    Name = "Item: " + i
                };
    }
}
 
public class IncorrectViewModel : ViewModelBase
{
    public IncorrectViewModel()
    {
        Items = new ObservableCollection<Item>();
    }
 
    public ObservableCollection<Item> Items
    {
        get;
        set;
    }

Posted via email from Jasper-net

5 tips for converting iOS UI to Android

|
Making your app look like it belongs into an Android phone

Many companies are converting their iOS apps to Android nowadays. However, simple one-to-one conversion of the UI might cause problems to the potential users. 

I don't believe that inter-platform consistency between an app's different versions is as important than consistency between apps on a single platform. Not many users use multiple different phones at the same time. This post describes five simple rules how an iOS app can be made to fit into the growing Android app crowd.

1. Use top tabs
Google recommends that tabs in Android apps placed on top part of the UI instead of the very bottom.

tabs.png

Posted via email from Jasper-net

Dropping A Role in SQL server using T-SQL

|
It happens so that when you drop/delete a Database Role in SQL Server Database, the Role members who were assigned to this role wont get de-associated from this Role. No doubt the role will be dropped/deleted but the member will be having this Role still existing in their permission list. So I came up with the below T-SQL which will first de-associate all the role member’s from the role to be dropped and then it will go ahead and drop the role. For Testing Purpose, I have taken Role “db_execute” as the role which needs to be dropped/deleted.

/* De-Associating RoleMember From Role To Be Dropped*/
USE [AdventureWorks]
GO
DECLARE @RoleName sysname
set @RoleName = N'db_execute'
IF  EXISTS (SELECT * FROM dbo.sysusers WHERE name = @RoleName AND issqlrole = 1)
Begin
 
      DECLARE @RoleMemberName sysname
      /* Cursor to Loop in for Each Member have the Role Privilege and Drop RoleMember */
      DECLARE Member_Cursor CURSOR FOR
      select [name]
      from dbo.sysusers
      where uid in (
            select memberuid
            from dbo.sysmembers
            where groupuid in (
                  select uid
                  FROM dbo.sysusers where [name] = @RoleName AND issqlrole = 1))
 
      OPEN Member_Cursor;
 
      FETCH NEXT FROM Member_Cursor
      into @RoleMemberName
 
      WHILE @@FETCH_STATUS = 0
      BEGIN
 
            exec sp_droprolemember @rolename=@RoleName, @membername= @RoleMemberName
 
            FETCH NEXT FROM Member_Cursor
            into @RoleMemberName
      END;

Posted via email from Jasper-net

WPF 4 DataGrid Row Drag and Drop

|
I recently had a discussion with a colleague about the capabilities of WPF for application development. We had discussions on the various new features in WPF including the capabilities of the WPF DataGrid control. The WPF DataGrid control has lots of features for data representations and manipulation. One of the nicest features of the DataGrid, is that we can change the column position using Drag-Drop. When my colleague asked me if the Drag-Drop effect is possible for the DataGridRow too, I was clueless. But this question gave me enough motivation to try my hands on implementing a Drag drop with the DataGridRow. This article demonstrates how to do so.

Step 1: Open VS2010 and create a WPF windows application. Name it as ‘WPF40_DataGrid_Row_Drag_Drop’.

Step 2: To this project, add a new class file and name it as ‘DataAccess.cs’. Write the following code in it:  

wpf-data-access.png

The above class, defines classes for Employee Entity and the EmployeeCollection, to store Employee records.

Step 3: Open MainWindow.Xaml and define an instance for the ‘EmployeeCollection’ class in Windows.Resource. Also define the DataGrid columns and set the AllowDrop property of the DataGrid to ‘true’. This will enable Drag-Drop operations on the DataGrid control.  

wpf-drag-drop.png

Read more: net Curry

Posted via email from Jasper-net

Compound Assignment, Part One

|
When people try to explain the compound assignment operators += –= *= /= %= <<= >>= &= |= ^= to new C# programmers they usually say something like “x += 10; is just a short way of writing x = x + 10;”. Now, though that is undoubtedly true for a local variable x of type int, that’s not the whole story, not by far. There are actually many subtle details to the compound assignment operators that you might not appreciate at first glance.

First off, suppose the expression on the left hand side has a side effect or is expensive to call. You only want it to happen once:

class C 
  private int f;
  private int P { get; set; }
  private static C s = new C();
  private static C M() 
  {  
    Console.WriteLine("Hello");
    return s;
  }
  private struct Evil 
  {
      public int f; // Mutable value type with a public field, evil!
      public int P { get; set; }
  }
  private static Evil[] evil = new Evil[2000];
  private static Evil[] N()
  {
    Console.WriteLine("Badness");
    return evil;
  }

If somewhere inside C you have M().f += 10; then you only want M’s side effect to happen once. This is not the same as M().f = M().f + 10;

What is it the same as then? How about this:

C receiver = M();
receiver.f = receiver.f + 10;

Is that right? It seems to be, but suppose we make it a bit more complicated. Suppose we have N()[123].f += 10; . Is this then

Evil receiver = N()[123];
receiver.f = receiver.f + 10;

Clearly not.  We've made a copy of the contents of variable N()[123] and we are now mutating the variable containing the copy but we need to be mutating the original.

Once more we see how much pure concentrated evil mutable value types are!

To express the real semantics concisely we need a feature that C# does not have, namely, “ref locals”. C# has ref-typed parameters, but not ref-typed locals. When you make a ref-typed parameter essentially you are saying “this parameter is an alias for this variable”:

    void N(ref int x) { x = 10; }
    …
    N(ref M().f);

Posted via email from Jasper-net

WP7: Right alignment bug for item templates with grids

|
If you have done a few templates with some of the content aligned right and other content aligned left in a grid. You have probably bumped into this. It took quite some time to solve. The problem does not exist in WPF or later versions of Silverlight, but since Windows Phone 7 is based on version 3 it’s a bug that can cause some headache. First, a quick view of how it looks. In the picture below, the accent colored label should be aligned right:

rightalign_thumb.png

Read more: Jayway Team Blog

Posted via email from Jasper-net

Mastering in Visual Studio 2010 Debugging

|

Introduction

In the software development life cycle, testing and defect fixing take more time than actually code writing. In general, debugging is a process of finding out defects in the program and fixing them. Defect fixing comes after the debugging, or you can say they are co-related. When you have some defects in your code, first of all you need to identify the root cause of the defect, which is called the debugging. When you have the root cause, you can fix the defect to make the program behavior as expected.

Now how to debug the code? Visual Studio IDE gives us a lot of tools to debug our application. Sometimes debugging activity takes a very long time to identify the root cause. But VS IDE provides a lot of handy tools which help to debug code in a better way. Debugger features include error listing, adding breakpoints, visualize the program flow, control the flow of execution, data tips, watch variables and many more. Many of them are very common for many developers and many are not. In this article, I have discussed all the important features of VS IDE for debugging like Breakpoint, labeling and saving breakpoints, putting conditions and filter on breakpoints, DataTips, Watch windows, Multithreaded debugging, Thread window, overview of parallel debugging and overview of IntelliTrace Debugging. I hope this will be very helpful for beginners to start up with and for becoming an expert on debugging. Please note, targeted Visual Studio version is Visual Studio 2010. Many things are common in older versions, but many features such as Labeling breakpoint, Pinned DataTip, Multithreaded Debugging, Parallel debugging and IntelliTrace are added in VS 2010. Please provide your valuable suggestions and feedback to improve my article.

How to Start?

You can start debugging from the Debug menu of VS IDE. From the Debug Menu, you can select “Start Debugging” or just press F5 to start the program. If you have placed breakpoints in your code, then execution will begin automatically.

Posted via email from Jasper-net

Автоматизация локализации в Silverlight при помощи макросов Visual Studio

|
дравствуйте. Хочу поделиться небольшой наработкой в области автоматизации локализации приложений разработанных с использованием технологии SilverLight. Прочитав этот пост (Локализация в Silverlight), стало ясно, что придется выносить все строковые константы в ресурсные файлы, что нельзя назвать особо интеллектуальной работой. Поэтому решил пойти длинным путём и попробовать автоматизировать данный процесс с помощью встроенных в Visual Studio макросов.

В связи с тем, что от меня так же требовали немного причесать код, было решено отказаться от полной автоматизации (полного сканирования всех xaml файлов с поиском русских букв и вынесением в ресурсы). Плюс не смог придумать нормальной автоматизации замены строковых констант в .cs файлах.

После анализа были выработаны следующие требования к макросу:
  • проанализировать выделенную пользователем фразу (по нажатию на определённую комбинацию клавиш);
  • найти перевод фразы в google translate (чтобы не напрягать пользователя придумыванием названия ресурса);
  • добавить фразу в указанные заранее ресурсы (причем необходимо, чтобы изменения производились через VS, так как нам нужен сгенерированный прокси класс);
  • заменить выделенную пользователем фразу на биндинг к ресурсу.
В Visual Studio встроен удобный редактор макросов. Чтобы его вызвать необходимо выбрать в меню Tools/Macros/Macros IDE. Перед началом работы, необходимо создать файл с макросами (код пишется на VB .Net). Любая public процедура без параметров — видна в списке макросов и её можно вызывать при нажатии на горячую клавишу, либо через Macro Explorer.

Задача 1. Определение выделенного слова в VS

Dim doc As Document = DTE.ActiveDocument
Dim d As TextDocument = doc.Object
Dim bp = d.Selection.AnchorPoint.CreateEditPoint, ep = d.Selection.BottomPoint.CreateEditPoint
Dim caption As String = bp.GetText(ep)
If (String.IsNullOrWhiteSpace(caption)) Then Exit Sub ' если у нас ничего не выделено - то выходим

Получаем активный документ, приводим его к текстовому документу (более удобный класс, для работы с текстом). Получаем две точки: начало и конец выделения (можно было бы проще, через doc.Selection.Text, но при открытии нового файла в студии и возвращении обратно в редактируемому файлу — сбивается выделение, что очень неудобно, а эти точки нам помогут восстановить выделение текста).

Задача 2. Получение имени ресурса

Наиболее простым способом получения имени ресурса — является перевод выделенной фразы на английский язык (примечание: наиболее простой способ — не является наиболее правильным). Для перевода было решено использовать сервис Google Translate, так как этот сервис имеет простое API
В результате запроса получаем следующий JSON объект:
{"responseData": {"translatedText":"Organization Structure"}, "responseDetails": null, "responseStatus": 200}

Private Function ConvertToResourceName(ByVal text As String) As String
Dim result As String = (New WebClient()).DownloadString("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + text + "&langpair=ru|en")
Dim stream As New MemoryStream(Encoding.Unicode.GetBytes(result))
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(TranslateResult))
Return String.Join("", CType(serializer.ReadObject(stream), TranslateResult).responseData.translatedText _
                                .Split(" ", ".", ",", "!", "(", ")", vbCrLf, vbCr) _
                                .Where(Function(word) Not String.IsNullOrWhiteSpace(word)) _
                                .Select(Function(word) word(0).ToString().ToUpper() + word.Substring(1)) _
                                .ToArray())
End Function

Read more: Habrahabr.ru

Posted via email from Jasper-net

Simple effective Weak Event Dispatcher in C#

|
Introduction

Some time ago, I needed to register quite a lot of event handlers. At that point, I got aware of the memory leaking if you do not unregister unneeded event handlers. The reason is that such a handler's instance keeps being referenced by the corresponding event dispatcher, preventing the garbage collector from garbage collecting that corresponding instance.

Another related problem was that unneeded handlers kept being executed since their instances could not be garbage collected, resulting in loss of performance. So unregistering events is an important thing to do if you have the opportunity to do that.

But of course, it would be comfortable not to worry about unregistering events at all.

I discovered this to be a fairly common issue and I found many solutions and some nice articles on the web referring to the WeakReference and WeakEventManager classes. These solutions partly worked for me as they dealt with the memory leakage. But for each, I encountered performance or usability issues, and I decided to write a simple weak event dispatcher with focus on usability and performance.

Background

A weak reference is a reference which does not count for the garbage collector when it needs to decide about garbage collecting the corresponding instance. This implies that a weak reference can be null at a sudden moment because it was garbage collected as there were no other strong references anymore to that particular instance. This also means that you need to take care when using weak references.

Using the code

This WeakEventDispatcher acts like a "normal" event dispatcher on the outside, i.e., you can add and remove handlers easily. On the inside, handlers are bucketed together with weak references to their instances. The invocation is done by compiled lambda expressions, i.e., delegates. These delegates are cached and reused where possible. The purging (getting rid of handlers belonging to garbage collected instances) is done on a regular basis which can be configured by a threshold setting. As a result, there is no memory leakage anymore, and the event invocation performance increases significantly if you have to deal with a lot of event handling.

A unit test class is included which shows how to deal with the WeakEventDispatcher. Further, a test method is included for performance measurement. It shows the performance differences between applying standard .NETevent handling and applying the weak event dispatcher.

The performance test tells that you gain more performance benefit as you increase the number of event handling iterations. If you largely increase the number of iterations, the standard .NET event handling eventually entangles by the number of handler invocations since "lost" instances are not garbage collected and as a result the corresponding handlers keep being invoked. The WeakEventDispatcher prevents that from happening.

The following example shows how to apply the WeakEventDispatcher:

public class Entity {
    private readonly WeakEventDispatcher<EventArgs> _changeNotificationDispatcher;

    public event EventHandler<EventArgs> DataChanged {
        add { _changeNotificationDispatcher += value; }
        remove { _changeNotificationDispatcher -= value; }
    }
 
    protected virtual void OnDataChanged(EventArgs e) {
        if(_changeNotificationDispatcher!= null)
            _changeNotificationDispatcher.Invoke(this, e);
    }
}

Inside the event dispatcher, some housekeeping needs to be done once in a while, i.e., the handlers which belonged to garbage collected instances need to be removed. The housekeeping is performed by Purge(). The purging can be performed manually, but is done regularly as well every configurable number of times that a public dispatcher method is called. The interval is configured by the PurgeThreshold, and the corresponding value can be passed with the dispatcher's constructor. You could instantiate the dispatcher at declaration and pass a purge threshold setting, like:

private readonly WeakEventDispatcher<EventArgs> 
  _changeNotificationDispatcher = new WeakEventDispatcher<EventArgs>(10);

Read more: Codeproject

Posted via email from Jasper-net

How to use stored procedure in simple easy way with Web.Config file?

|
In this article I have given simple stored Procedure. After running the first page in Internet Browser, only enter user Id and the data is retrieved from table, showing that it is there in Cookies. You cannot imagine the how faster it is.

I am using stored Procedure in SQL 2005 and connected this in font endASP.Net. There are three fields named- ID, Name, and Salary. We are using stored procedure for pre compilation, which is faster for execution. Many interview, I asked why we use stored Procedure? We I got really time, I understood these concept. You see, how it is benefit for you.
  1. Create Table in SQL2005 and save this table named as tblemp.
  2. Add values in tblemp by right click on tblemp on Object Explorer. And select Open table, add values one by one
  3. Create stored Procedure in SQL2005
Here my data base is msdb. Write these stored Procedure query and select thes query, then execute it. If no error, after execution, then u will see dbo.usp_selectrow in object Explorer.

In asp.net3.5 , I added these.

In Web.config file,
 
<connectionStrings>
<add name="config" connectionString="Data Source=leonora\sqlexpress;Initial Catalog=msdb;Integrated Security=True"   providerName="System.Data.SqlClient"/>
</connectionStrings>

I used Windows authentication mode in SQL2005, So web Config file I used- Integrated Security=True. If you want SQL Server Authentication mode in SQL 2005, then Give uid=sa, Pwd=test and cut Integrated Security=True.

In Default.aspx.cs, copy and Past the following code-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string web = ConfigurationManager.ConnectionStrings["config"].ConnectionString;
        SqlConnection con = new SqlConnection(web);
        //string q = "insert into tblsal";
        SqlCommand com = new SqlCommand("usp_selectrow",con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@id",TextBox1.Text);
        com.Parameters.AddWithValue("@name", TextBox2.Text);
        com.Parameters.AddWithValue("@sal", TextBox3.Text);
        con.Open();
        SqlDataReader dr;
        dr = com.ExecuteReader();

Read more: C# Corner

Posted via email from Jasper-net

Using PDB files and symbols to debug your application

|
Introduction

Errare humanum est (Latin for "to err is human") is a well known proverb which is applicable in nearly every aspect of life. You probably won't be able to find a programmer who has never encountered an error when running a program and has searched for ages to find the cause of it. Today, where code is often widely spread or even outsourced to the Cloud (think of Windows Azure, for example), this task gets even more complicated. That is the reason why efforts were always made to find mechanics that simplify debugging. When working with C++, there is also another problem that makes error finding very hard. After compilation, there is nothing left that lets us map an error onto a particular line of source code or even to a certain function. All names are "lost".

With PDB files, Windows offers us a powerful tool to deal with the problem mentioned in the last paragraph as they preserve information about the executable after compilation. With the help of those files, you are able to recover the source code as it was before compilation from the bits and bytes at runtime. The whole API that covers the work with PDB files and symbols is extremely huge and powerful. It is my goal to provide you an introduction to every aspect of that API in this article. But due to the fact that it is so big, this may take some time, and if you are interested in the topic, it is a good idea to recheck if there are new versions of this article with more things explained.

Loading symbols

Loading symbols for a process is a very easy task. All you have to do is call SymInitialize with the handle of the process for which the symbols should be loaded. If you are debugging a foreign process, you should pass the handle of that process to the function and not the handle of the application that debugs the process, because you want to load the symbols of the process that gets debugged. As a process may have loaded additional modules (DLLs) which also could have symbols, it is important to see if the function also loads the symbols for those modules. In fact, you are free to choose if they should be loaded or not. The third parameter of SymInitialize is a boolean indicating if the process should be "invaded", which means that symbols for all loaded DLLs will be loaded too, or not.

Usually, SymInitialize is called right after the process has started, and SymCleanup is used to unload all symbols when the process finishes. When calling SymInitialize multiple times for the same process, it fails, giving ERROR_INVALID_PARAMETER with GetLastError. This is a bit confusing as you cannot really distinguish multiple calls from an invalid process handle. Nevertheless, in the code attached to this article, you will see that SymInitialize is called in the constructor of a class and can therefore be called multiple times, and ERROR_INVALID_PARAMETER is used like it only indicates multiple calls. When using GetCurrentProcess, this basically is safe enough.

Now, let's imagine you load the symbols for the process at the startup and perform some tasks in that process. This may load new DLLs in the address space of the application and the symbols for those modules may not yet be loaded as they were not present at startup. To make sure symbols for those modules are also loaded, the function SymRefreshModuleList can be used, which is pretty simple to understand. It is also possible to load the symbols for a specific module only using SymLoadModule64, but I recommend you to use it only if you are debugging a process and receive an event that a module was loaded, because in that case, you have all the information to represent the symbols for the module as it is currently loaded.

Obtaining and working with a symbol

After symbols are loaded, you may want to actually get a specific symbol. To obtain symbols, there are various functions which use different approaches:
  • SymFromName - Searches a symbol by its name
  • SymFromAddr - Searches a symbol by its address
  • SymFromIndex - Searches a symbol by its index
  • SymFromToken - Searches a symbol by its managed token
Depending on how you have received the symbol, the first things you probably want to know are the name of the symbol and/or its address. Both of them can be accessed in the SYMBOL_INFO structure that gets filled by the above functions. But there is an important thing with that structure: it has a variable length and you are responsible to allocate the space. This is because the name is stored in a variable length array and truncated to fit its size (indicated by a member). As this array is the last member of the struct, you can just allocate as much space as you need to store the whole struct plus the full name, and pass that pointer to the functions. Have a look at the following example:

char memory[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
PSYMBOL_INFO sym = reinterpret_cast<PSYMBOL_INFO>(memory);
sym->NameLen = MAX_SYM_NAME;
sym->SizeOfStruct = sizeof(SYMBOL_INFO);
SymFromName(GetCurrentProcess(), "myFunction", sym);
//...

// or using malloc:
PSYMBOL_INFO sym = reinterpret_cast<PSYMBOL_INFO>(
                      malloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME));
sym->NameLen = MAX_SYM_NAME;
sym->SizeOfStruct = sizeof(SYMBOL_INFO);
SymFromName(GetCurrentProcess(), "myFunction", sym);
//...
free(sym);

Read more: Codeproject

Posted via email from Jasper-net

MyRouter (Virtual WiFi Router)

|
Project Description
MyRouter is a virtual WiFi AP (Access Point)
it allows you to connect all your WiFi Enabled devices to the internet using your Windows 7 laptop or Desktop (WiFi card adapter / USB adapter required) it is still under development with major changes coming

Read more: Codeplex

Posted via email from Jasper-net

LibVLC.NET

|
FileDownload.aspx?ProjectName=libvlcnet&DownloadId=224664&Build=17748

LibVLC.NET provides .NET bindings to the LibVLC core library of the VLC media player.

The VLC media player must either be installed in its default location or available in the application’s directory. Since some newer LibVLC features are used LibVLC.NET requires VLC version 1.2 which can be downloaded here:

Read more: Codeplex

Posted via email from Jasper-net

Silverlight 4 OOB - Handwriting Recognition & Text-To-Speech

|
I have been sitting on this sample for quite a while, but never found the time to get it ready for a post. Before I switch the focus of my blog over to Windows Phone 7 development, I wanted to get this out of the way first :-)

With Silverlight 4, we introduced an exciting new capability for Out-Of-Browser apps: Trusted Applications - one of the key new fatures of Trusted Applications is the ability to integrate with COM Automation interfaces on your Windows PC. What does this mean? This allows you to call into native components on your system that are either provided by the OS or installed by the user or system admin. On MSDN you can find some sample code for the canonical example that highlights the power of this feature: integrating Microsoft Office features into your Silverlight application.

In this blog post, however, I want to show some other cool things you can do with these new APIs on your PC: I want to use the systems handwriting recognizer as well as the systems speech synthesizer within my Silverlight application. Let's do the easy part first and take a look at how we get the speech synthesis done (in the attached sample, this plays back the recognized handwriting):

private void btnSpeak_Click(object sender, RoutedEventArgs e)
{
    dynamic spVoice = AutomationFactory.CreateObject("SAPI.SpVoice.1");
    spVoice.Speak(tbResult.Text);
}

In line 3 we create an instance of the SAPI.SpVoice (SAPI = Microsoft Speach API). Now we can just call the Speak() method (line 4) in order to have the desired text spoken by the machine. Make sure you turn on your speakers.

For the handwriting recognition part, the code looks a little bit more complicated, mostly for two reasons: The COM Automation API for Ink has some oddities & we need to convert the users strokes from pixel space into HiMetric. Here is the full code needed to implement this as extension method on Inkpresenter to have its writing recognized by the system's handwriting recognizer:

Posted via email from Jasper-net

Amazon Cloud Drive and Amazon Cloud Player - Your 5GB free cloud storage and digital music locker (and web based player)

|
Amazon Cloud Drive is your hard drive in the cloud. Store your music, videos, photos, and documents on Amazon’s secure servers. All you need is a web browser to upload, download, and access your files from any computer.

What is Amazon Cloud Drive?

Amazon Cloud Drive is your hard-drive in the cloud. Securely store your music, videos, photos, and documents online and access them from anywhere.
All you need is a web browser to upload, download and access your files from any computer. Back up your files to ensure that your music, photos and personal documents are available to you wherever you go.

The Amazon Cloud drive offers 5 GB of free online storage that you can access from any computer. If you need more storage space, paid plans are available for storage up to 1,000 GB.

Automatically store your Amazon MP3 Purchases

When you purchase digital downloads from the Amazon MP3 Store, you can choose to automatically save your purchases to your Cloud Drive. All your purchases will be backed up and available to download anywhere, anytime.

Safe and secure storage

Amazon Cloud Drive provides customers with reliable, secure server storage. Each file is stored within Amazon Simple Storage Service (S3); the same highly scalable, reliable, fast, data storage infrastructure that Amazon uses to run its own global network of web sites.

Access to your Cloud Drive is controlled through your Amazon.com user ID and password. All communications are encrypted using HTTPS, so that your data can pass securely over the Internet.

Frequently Asked Questions

Do I need to make a purchase to use Cloud Drive?

No, if you have an Amazon account, you have access to 5 GB of free online storage on Amazon Cloud Drive. If you purchase an album from the Amazon MP3 Store, you may be eligible for a free upgrade to 20 GB of Cloud Drive space for one year (this promotion is open to U.S. customers only). New Amazon MP3 purchases delivered to Cloud Drive do not count against a customer's storage space. If you need more storage space, paid plans are available for storage up to 1,000 GB.

Read more: Amazon Cloud Drive

Posted via email from Jasper-net

Although the default icon for a shortcut is the icon of the target, you can override that

|
A customer reported that a shortcut they deployed to their employees' desktops was triggering unwanted server traffic.

My customer deploys a shortcut on %ALLUSERSPROFILE%\Desktop, and this shortcut points to an EXE file on a remote server. Once a local user logs on, the computer will try logging onto the remote computer to query information and generate a login failure alert on the server.

Is there any way to stop Explorer from querying the shortcut information?

Fortunately, the customer provided context for the question, because the question the customer is asking doesn't actually match the scenario. The customer doesn't want to stop Explorer from querying the shortcut information; the customer just wants to stop Explorer from contacting the server to get the icon.

Posted via email from Jasper-net

10+ High Quality Free Business PSD Web Templates

|
We’ve gathered up 10+ high quality free business PSD web templates for you to use for next project . These templates are all excellent quality templates. we can learn how to make a business layout from these templates.

image1.png  image4.png

Read more: WebDesign14

Posted via email from Jasper-net

A simple wrapper for asynchronous file I/O (ReadFileEx,WriteFileEx)

|
Introduction

Hi all, here Iam dealing with a subject which is comparatively less discussed. The people new to programming world will start with samples which create, read or write files. In Windows all file related calls finally reach in CreateFile, ReadFile or WriteFile. We are all familiar with these APIs. Technically, ReadFile and WriteFile APIs are  synchronous APIs. That is these APIs return only after the requested data is read or written. Now, coming to today’s topic. There are asynchronous versions of these APIs. The ReadFileEx and WriteFileEx. Actually ReadFile and WriteFile can also behave asynchronous. But our discussion is on the explicitly asynchronous APIs, ReadFilEx and WriteFilEx.

Background

Normally, when we need asynchronous behaviour or parallelism we create threads. The asynchronous file I/O APIs allows us to leverage the asynchronous behaviour without introducing threads. So we can issue ReadFileEx or WriteFileEx and perform other operations. Then finally when the application needs the result of I/O, it can check the status of asynchronous operation with the help of some APIs which we will discuss shortly. The file should be opened with FILE_FLAG_OVERLAPPED for using the asynchronous APIs.

See the prototype for ReadFileEx below. It is the same for WriteFileEx.

BOOL WINAPI ReadFileEx(
__in HANDLE hFile,
__out_opt LPVOID lpBuffer,
__in DWORD nNumberOfBytesToRead,
__inout LPOVERLAPPED lpOverlapped,
__in_opt LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

Here we are interested in the last two parameters lpOverlapped and lpCompletionRoutine. We need to specify OVERLAPPED structure filled with offset from where data is to be read or written. There is a hEvent member in this structure. The MSDN documentation says that we are free to use this for our purpose. But there is asynchronous behaviour exhibited by ReadFile and WriteFile when its last parameter OVERLAPPED pointer is provided. In this case some MSDN documentation says that we need to supply separate event handles for each instance of OVERLAPPED structure. So there is a confusion that we need to specify the hEvent or not. Also it mentions that this event object will be signalled when the specified overlapped operation completes. The lpCompletionRoutine is the callback function to be called by the system when the specified asynchronous operation completes. It will be invoked per ReadFileEx/WriteFileEx call. There is a side track for this. This callback routine is invoked only when the thread enters in an “alertable” wait state. This state can be set with the help of SleepEx, WaitForSingleObjectEx, WaitForMultipleObjectsEx, MsgWaitForMultipleObjectsEx etc. A thread can issue asynchronous I/O operations and freely do other jobs. Then, once all its other tasks are completed, it can enter the alertable wait state. The callback routines are then called in the context of such APIs. The status of an overlapped operation can be checked with the help of GetOverlappedResult API.

Using the code

I have wrapped all these knowledge in to a small class AsyncFile.

class IAsyncOperationCompletionNotifier {
public:
    virtual void OnAsyncOperationComplete(BOOL bRead,DWORD dwErrorCode)=0;
};

class AsyncFile{
public:
     AsyncFile(LPCTSTR lpctszFileName,BOOL bCreate,DWORD dwDesiredAccess,
                   DWORD dwShareMode, IAsyncOperationCompletionNotifier* pINotifier,
                   BOOL bSequentialMode=FALSE, __int64 nStartOffset=0,
                   BOOL bInUIThread=FALSE);
     BOOL IsOpen();
     BOOL Write(LPVOID pvBuffer,DWORD dwBufLen,DWORD dwOffsetLow=0,DWORD dwOffsetHigh=0);
     BOOL Read(LPVOID pvBuffer,DWORD dwBufLen,DWORD dwOffsetLow=0,DWORD dwOffsetHigh=0);
     BOOL IsAsyncIOComplete(BOOL bFlushBuffers=TRUE);
     BOOL AbortIO();
     DWORD GetFileLength(DWORD* pdwOffsetHigh);
     __int64 GetLargeFileLength();
     VOID Reset(BOOL bSequentialMode=FALSE,__int64 nStartOffset=0);
     operator HANDLE()
     {
        return m_hAsyncFile;
     }
     BOOL SeekFile(__int64 nBytesToSeek,__int64& nNewOffset,DWORD dwSeekOption);
     ~AsyncFile(void);
private:
....
};

Read more: Codeproject

Posted via email from Jasper-net