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

Write your own Debugger to handle Breakpoints

| Tuesday, May 3, 2011
Introduction

Building your very own debugger is a great way to understand workings of a commercially available debugger. In this article, the reader will be exposed to certain aspects of the OS and CPU opcode (x86-32-bit only). This article will show the workings of breakpoints and working of OutputDebugString (since we will be handling these two events only) used commonly while debugging, readers are urged to investigate conditional breakpoint and step wise execution (line by line) that are commonly supported by most debuggers. Run to cursor is similar to breakpoint.

Background

Before we start, reader will require basic knowledge of OS. Discussions related to OS is beyond the scope of this article, please feel free to refer other articles (or write to me) while reading this. Reader would be required to be exposed to commercially available debuggers (for this article: VS2010) and have debugged applications before using break points

Break Points

Breakpoint allows users to place a break in the flow of a program being debugged. The user may do this to evaluate certain conditions at that point in execution.

The debugger adds an instruction : int 3 (opcode : 0xcc) at the particular address (where break point is desired) in the process space of the executable being debugged. After this instruction is encountered:-

the EIP is moved to the interrupt service routine (in this case int 3),
The service routine will save the CPU registers (all Interrupt service routines must do this) ,signal the attached debugger, the program that called DebugActiveProcess(process ID of the exe being debugged) look up MSDN for this API.
The debugger will run a debug loop (mentioned in code as EnterDebugLoop() in file Debugger.cpp)
The signal from the service routine will trigger WaitForDebugEvent(&de, INFINITE), the debug loop (mentioned in the code as EnterDebugLoop) will loop through every debug signal encountered by WaitForDebugEvent. After processing the debug routine, the debugger will restore the instruction by replacing 0xcc (int 3) with the original instruction and return from the service routine by calling ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE). ( Before Placing the break point, the debugger must use ReadProcessMemory to get the original BYTE at that memory location).
when it returns from an interrupt service routine( using IRET) , EIP will point to the next byte to be executed, but we want it to point to the previous byte (the one we restored), this is done while handling the break point, use GetThreadContext to get value of ESP (this holds on the stack, the return address of EIP). Subtract one from the return address (get the return address by using ReadprocessMemory) and use WriteProcessMemory to update it, now EIP will be restored correctly (there are different ways to achieve this, VS2010 and other debuggers may use a different approach).
OutputDebugString

This API is used to display a string on the debug console, the user may use this to display certain state related information or trace.

when this is API is occured , OUTPUT_DEBUG_STRING_EVENT event is triggered.
An attached debugger will handle this event in the debug loop (mentioned in the code as EnterDebugLoop).
The event handling API will provide information of the string relative to the Debuggee's process space
use ReadProcessMemory to acquire the string (memory dump) from another process.
Using the code

The attached code must be referred to at all times while reading this article. The break point (opcode: 0xcc) is introduced by

BYTE p[]={0xcc}; //0xcc=int 3            // Any source code blocks look like this
::WriteProcessMemory(pi.hProcess,(void*)address_to_set_breakpoint, p, sizeof(p), &d); 

Read more: Codeproject

Posted via email from Jasper-net

How to Score a Google Onsite Interview

|
You might have heard that Google is looking to hire some 6,000 new employees this year. What that means is a lot of time spent by recruiters looking for candidates, talking with them, and then setting them up with one of us for a phone interview. If that goes well, we invite you onsite for a day’s worth of more intensive interviews, and if everything matches up we extend an offer, you take it, and you become a Noogler.

As it turns out, I get to do a lot of these phone screens, at least for aspiring front-end developers. And I’m frustrated by how bad it usually goes; that is, the interview itself was already a waste of time, but it’s compounded by the necessity to write a detailed account of the conversation to avoid frivolous discrimination lawsuits.

Of course, this is not a new problem; the reason why we don’t just bring everybody onsite immediately is that it’s better to waste one person’s time and discover a bad match than it is to waste 4-5 people’s time to make the same conclusion. That said, if you’re applying to an engineering position, here are some tips to save everyone some time and unnecessary frustration.

Clean up your resume
Be honest about what you know and what you don’t know in your resume. Yes, putting in a bunch of buzzwords will get you noticed by the recruiter, but quantify your experience with various technologies (e.g., “I’ve worked in: C++, Java; I’m familiar with: Python, Rails) so I know what’s fair game.

For whatever reason, front-end engineering candidates are particularly offensive; I’ll see someone put “expert in Javascript” on their resume, only to find that they barely know the syntax to jQuery and if I take the library away they will stutter and sulk in the corner. Be realistic about what you’ve done, and we’ll tailor our expectations accordingly; call yourself a “10″ in Python, and we’ll have Guido van Rossum interview you.

Know your computer science
It’s hardly a secret anymore that Google will ask its interviewees CS-type questions, from algorithms to runtime analysis to data structures. For whatever reason, we have people with 15 years experience, having forgotten what they learned in school, applying and then completely freezing up when we touch on these subjects. The truly outrageous ones will attempt to stall the interviewer while they frantically try to Google an answer.

If you’re not going to bother reviewing CS concepts or think that stuff is beneath you, you will probably not pass the phone screen and you’ll definitely not pass the onsite. I’m not even necessarily saying that this is a good metric – I’m a fan of giving small interview projects and pair programming for technical screening myself – but this is what Google does and you simply won’t get past the interview process.

Be comfortable with coding without a compiler/interpreter and in a shared document
Some programmers live by their REPL shell, and some hate having another programmer look over their shoulder while they code. Unfortunately, we use a shared Google doc to test your coding abilities, so you’d be better off being used to the feeling of coding in a shared environment.

Read more: AC

Posted via email from Jasper-net

2007 Microsoft Office System Update: Redistributable Primary Interop Assemblies

|
The 2007 Microsoft Office system Primary Interop Assemblies (PIA) redistributable is a Microsoft Windows Installer package that contains the Primary Interop Assemblies for 2007 Microsoft Office system products.

Read more: MS Download

Posted via email from Jasper-net

A Plethora Parallel Programming PDF’s - 12 Parallel Programming with the .NET Framework 4 articles for download

|
A set of articles that provide information on parallel programming with the .NET Framework 4.

OptimizingUsingConcurrencyVisualizer.pdf 2.1MB
ParallelProgramsinNET4_CodingGuidelines.pdf 964KB
ParentChildTPLTasksRelationship.pdf 787KB
PerformanceCharacteristicsOfSyncPrimitives.pdf 800KB
PerformanceCharacteristicsOfThreadSafeCollection.pdf 682KB
PLINQOrderingModel.pdf 1.0MB
TPLOptionsTour.pdf 1.1MB
Using Net4ToAchieveDataParallelism.pdf 925KB
UsingCancellationinNET4.pdf 1.1MB
UsingPLINQinOfficeAddins.pdf 761KB
WhenToUseParallelForEachOrPLINQ.pdf 527KB
WorkflowAndParallelExtensionsinNET4.pdf 648KB

Posted via email from Jasper-net

Convert Flash(R) to Silverlight(R)

|
silverx_overview.png

SilverX products are aimed to help to migrate existing Flash movies into Silverlight platform. Using SilverX and SilverX Expression you can easily

Convert your SWF file to ready-to-run Silverlight application (or Silverlight XAP file)
Convert or import your Flash file into Silverlight, Windows Presentation Foundation (WPF) or Silverlight for Windows phone project
Extract vector graphics and animations in XAML format
Extract raster images in PNG or JPEG format
Extract sounds in MP3 or WMA format
The results of Flash to Silverlight conversion then can be used in Microsoft Expression Blend,
Microsoft Visual Studio or any other Silverlight/WPF authoring environment.

Read more: SilverX

Posted via email from Jasper-net

Wireless LAN Security and Penetration Testing Megaprimer

|
This video series will take you through a journey in wireless LAN (in)security and penetration testing. We will start from the very basics of how WLANs work, graduate to packet sniffing and injection attacks, move on to audit infrastructure vulnerabilities, learn to break into WLAN clients and finally look at advanced hybrid attacks involving wireless and applications.

Read more: SecurityTube

Posted via email from Jasper-net

Drop Shadow / Glow Effect using XAML

|
As most of know Silverlight has built in effects, however these effects can be pretty memory intensive. One solution would be is to use an image for the shadow, however if you’re planning for the object casting the shadow or glow to dynamically scale the image will either pixelate or not scale. The other solution is to create your drop shadows using rectangles in XAML.

Here I illustrate the memory usage of a drop shadow effect, a drop shadow built in XAML, and no drop shadow at all on a Dialog Window in Silverlight.

We can see that no drop shadow is the winner in terms of performance but a drop shadow built with XAML is a very close second using only an extra 12kb. The Built in effect in Silverlight uses over 3,000 kb more!

So how do you create a drop shadow effect in XAML? It’s actually very easy. Just create an offset grid with negative margins (this will be the distance from you object the drop shadow will cast) and add a series of Rectangles with varying corner radiuses, margins, and opacity.

<Grid Margin="-2,-2,-6,-6">
<Rectangle Stroke="Black" Margin="5" RadiusX="7" RadiusY="7" Opacity="0.3"/>
                <Rectangle Stroke="Black" Margin="4" RadiusX="8" RadiusY="8" Opacity="0.25"/>
                <Rectangle Stroke="Black" Margin="3" RadiusX="9" RadiusY="9" Opacity="0.2"/>
                <Rectangle Stroke="Black" Margin="2" RadiusX="10" RadiusY="10" Opacity="0.15"/>
                <Rectangle Stroke="Black" Margin="1" RadiusX="11" RadiusY="11" Opacity="0.1"/>

Read more: Infragistics

Posted via email from Jasper-net

Switching Between HTTP and HTTPS Like A Bigshot Hotshot

|
Introduction

When we, as developers, encounter the same coding scenario time and time again, we naturally tend to encapsulate the coding logic and reuse it in an effort to save time and minimize maintenance.

Recently, while developing a website called Bigshot Hotshot, I reevaluated the need to switch between secure (HTTPS/SSL) and non-secure (HTTP/non-SSL) pages. I noticed that while coding, we do not, in most cases, think about using SSL. One reason is that (at the time of this writing) the ASP.NET Development Server does not support SSL. To test SSL pages, we need to add our application/website to IIS and configure it accordingly. Another problem I wanted to solve was how to hint to IIS that certain pages should always use HTTPS while others should always use HTTP. To complicate things even further, I wanted to take SEO (search engine optimization) into account as well so that redirecting between secure and non-secure pages does not have a negative impact on the website's SEO.

This article presents one way of solving the aforementioned issues. For brevity, we will abbreviate the phrase: switch(ing) between HTTP and HTTPS to HTTP <=> HTTPS.

Background Research

Solution/Proposal 1

While researching potential solutions for the issue of HTTP <=> HTTPS, I came across an article by Matt Sollars: Switching Between HTTP and HTTPS Automatically: Version 2. It is a well-written solution to the above problem. I like how you can enforce entire directories to use SSL, as well as individual pages. I also like the web.config based approach to specify which files should use SSL. On the other hand, the solution is more complicated than what I needed. In addition, HTTP <=> HTTPS by calling Response.Redirect([path], true), and ending the Response is not very SEO friendly.

Solution/Proposal 2

Another solution to HTTP <=> HTTPS I came across was by Yohan B: RequireSSL Attribute for ASP.NET. I like the Attribute based approach of specifying that certain pages are required to use SSL. I also like the use of the #if DEBUG directive to tell the compiler not to HTTP <=> HTTPS while running in Debug mode (since ASP.NET Development Server does not support SSL anyway). What I am not quite fond of, however, is the use of a base Page that all other Pages inherit from to call the Validate() method and control HTTP <=> HTTPS. Also, just like in the above article, HTTP <=> HTTPS by calling Response.Redirect([path], true), and ending the Response is not very SEO friendly.

Our Strategy

What we will be looking at in the next section is another way to HTTP <=> HTTPS. We will use Attributes to mark which Pages require SSL, and we will implement a custom HTTP module responsible for intercepting requests to our ASPX pages and for HTTP <=> HTTPS when necessary. We will also examine how to do this in an SEO friendly manner.

The Code

First off, we need to define an Attribute so we can decorate the Pages that require SSL with that Attribute. Let's define an Attribute called RequireSSL:

/// <summary>
/// Attribute decorated on classes that use SSL
/// <summary>
[AttributeUsage(AttributeTargets.Class)]
sealed public class RequireSSL : Attribute
{
}

In our example project, the login.aspx and signup.aspx pages require SSL. We will mark them accordingly (notice the RequireSSL attribute):

/// <summary>
/// The Login Page
/// </summary>
[RequireSSL]
public partial class login : System.Web.UI.Page
{
    ...
}

/// <summary>
/// The SignUp Page
/// </summary>    
[RequireSSL]
public partial class signup : System.Web.UI.Page
{
    ...
}

Next, we will implement our custom HTTP module. It will be configured so that the code for HTTP <=> HTTPS only runs when compiled in Release mode:

/// <summary>
/// HttpModule for switching between HTTP and HTTPS (HTTP <=> HTTPS)
/// </summary>
public class RequireSSLModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
// only attach the event if the build is not set to Debug
#if !DEBUG
        // The PreRequestHandlerExecute event occurs just
        // before ASP.NET begins executing a handler such as a Page
        // In here we can acquire a reference
        // to the currently executing ASPX Page
        context.PreRequestHandlerExecute += 
           new EventHandler(OnPreRequestHandlerExecute);
#endif
    }
    
    ...
}

Let's take a closer look at the PreRequestHandlerExecute event.

/// <summary>
/// Handle switching between HTTP and HTTPS.
/// It only switches the scheme when necessary.
/// Note: By scheme we mean HTTP scheme or HTTPS scheme.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
    // obtain a reference to the ASPX Page 
    System.Web.UI.Page Page = 
       HttpContext.Current.Handler as System.Web.UI.Page;

Read more: Codeproject

Posted via email from Jasper-net

The Basics of Task Parallelism via C#

|
Preface

The trend towards going parallel means that .NET Framework developers should learn about the Task Parallel Library (TPL). But in general terms, data parallelism uses the input data to some operation as the means to partition into smaller pieces. The data is divvied up among the available hardware processors in order to achieve parallelism. It is then often followed by replicating and executing some independent operation across these partitions. It is also typically the same operation that is applied concurrently to the elements in the dataset.

Task parallelism takes the fact that the program is already decomposed into individual parts – statements, methods, and so on – that can be run in parallel. More to the point, task parallelism views a problem as a stream of instructions that can be broken into sequences called tasks that can execute simultaneously. For the computation to be efficient, the operations that make up the task should be largely independent of the operations taking place inside other tasks. The data-decomposition view focuses on the data required by the tasks and how it can be decomposed into distinct chunks. The computation associated with the data chunks will only be efficient if the data chunks can be operated upon relatively independently. While these two are obviously inter-dependent when deciding to go parallel, they can best be learned if both views are separated. A powerful reference about Tasks re Compute-bound asynchronous operations is Jeffrey Richter’s book, “CLR via C#, 3rd Edition.” It is a good read.

In this brief article we will focus on some of the characteristics of the System.Threading.Tasks Task object. To perform a simple Task, create a new instance of the Task class, passing in a System.Action delegate that represents the workload that you want performed as a constructor argument. You can explicitly create the Action delegate so that it refers to a named method, use an anonymous function, or use a lambda function. Once you have created an instance of Task, call the Start() method, and your Task is then passed to the task scheduler, which is responsible for assigning threads to perform the work. Here is example code:

using System;
using System.Threading.Tasks;

public class Program {
 public static void Main() {
// use an Action delegate and named method
Task task1 = new Task(new Action(printMessage));
// use an anonymous delegate
Task task2 = new Task(delegate { printMessage() });
// use a lambda expression and a named method
Task task3 = new Task(() => printMessage());
// use a lambda expression and an anonymous method
Task task4 = new Task(() => { printMessage() });

task1.Start();
task2.Start();
task3.Start();
task4.Start();
Console.WriteLine("Main method complete. Press <enter> to finish.");
Console.ReadLine();
 }
private static void printMessage() {
  Console.WriteLine("Hello, world!");
 }
}

To get the result from a task, create instances of Task, where T is the data type of the result that will be produced and return an instance of that type in your Task body. To read the result, you call the Result property of the Task you have created. For example, let's say that we have a method called Sum. We can construct a Task object, and we pass for the generic TResult argument the operation's return data type:

using System;
using System.Threading.Tasks;
public class Program {

 private static Int32 Sum(Int32 n)
 {
  Int32 sum = 0;
  for (; n > 0; n--)
  checked { sum += n; } 
  return sum;
 }

 public static void Main() {
   Task<int32> t = new Task<int32>(n => Sum((Int32)n), 1000);
   t.Start();
  t.Wait(); 

        // Get the result (the Result property internally calls Wait) 
        Console.WriteLine("The sum is: " + t.Result);   // An Int32 value
    }
 }

Produces:
The sum is: 500500

If the compute-bound operation throws an unhandled exception, the exception will be swallowed, stored in a collection, and the thread pool is allowed to return to the thread pool. When the Wait method or the Result property is invoked, these members will throw a System.AggregateException object. You can use CancellationTokenSource to cancel a Task. we must rewrite our Sum method so that it accepts a CancellationToken, after which we can write the code, creating a CancellationTokenSource object.

Read more: Codeproject

Posted via email from Jasper-net

Even if you have a lock, you can borrow some lock-free techniques

|
Even if you prefer to use a lock (after all, they are much easier to program), you can borrow some lock-free techniques. For example, consider this:

CRITICAL_SECTION g_cs;
GORILLADATA g_data;

void PokeGorilla(double intensity)
{
  EnterCriticalSection(&g_cs);
  DeformGorilla(intensity, &g_data);
  Reticulate(&g_data.spline);
  int stress = CalculateTension(&g_data.spline);
  if (stress < 25)      g_data.mood = RELAXED;
  else if (stress < 50) g_data.mood = ANNOYED;
  else                  g_data.mood = ANGRY;
  DeleteObject(g_data.hbmGorilla);
  g_data.hbmGorilla = RenderGorilla(&g_data);
  LeaveCriticalSection(&g_cs);
}
There are some concerns here. First of all, there's the lock hierarchy issue: If reticulating a spline takes the geometry lock, that may violate our lock hierarchy.

If the lock g_cs is a hot lock, you may be concerned that all this gorilla stuff will hold the lock for too long. Maybe rendering a gorilla is a slow and complicated operation because it's hard to get the fur just right.

These issues become less onerous if you switch to a lock-free algorithm, but that's an awful lot of work, and it's hard to get right. But maybe you can do just 20% of the work to get 80% of the benefit.

void PokeGorilla(double intensity)
{
  // Capture
  EnterCriticalSection(&g_cs);
  GORILLADATA data = g_data; // typo fixed
  LeaveCriticalSection(&g_cs);

  // Recalculate based on captured data
  DeformGorilla(intensity, &data);
  Reticulate(&data.spline);
  int stress = CalculateTension(&data.spline);
  if (stress < 25)      data.mood = RELAXED;
  else if (stress < 50) data.mood = ANNOYED;
  else                  data.mood = ANGRY;
  data.hbmGorilla = RenderGorilla(&data);

  // Commit
  EnterCriticalSection(&g_cs);
  HBITMAP hbmToDelete = g_data.hbmGorilla;
  g_data = data;
  LeaveCriticalSection(&g_cs);
  DeleteObject(hbmToDelete);
}
Here, we use the capture/try/commit model. We capture the state of the gorilla into a local variable, then perform our update based on that captured state. The spline reticulation takes place without any locks held, which avoids introducing a lock hierarchy violation. And rendering the gorilla is done without any locks held, which avoids introducing a choke point on the lock. After the calculations are done, we then re-enter the lock and commit the changes.

This pattern uses a last-writer-wins model. If another thread pokes the gorilla while we are still calculating the previous gorilla state, we will overwrite that gorilla state when we complete. For some scenarios, that's acceptable. But maybe the gorilla's emotional state needs to be an accumulation of all the times he's ben poked. We want to detect that somebody has poked the gorilla while we were busy calculating so that we can incorporate that new information into the final result.

Posted via email from Jasper-net

Manipulate XML data with XPath and XmlDocument (C#)

|
Introduction

Based on a section of easy-to-read XML source data, I'll show you how to select and locate XML nodes and navigate through them using XPathNavigator and XPathNodeIterator. I will provide a few straightforward samples about XPath expression with which you could follow without difficulty. In the last part, there is some sample code to update, insert and remove XML nodes.

Some Concepts

XML - Extensible Markup Language, describe data structures in text format and with your own vocabularies, which means it does not use predefined tags and the meaning of these tags are not well understood.
XSL - Extensible Stylesheet Language, is designed for expressing stylesheets for XML documents. XSL is to XML as CSS is to HTML.
XML Transformation - is a user-defined algorithm that transforms a given XML document to another format, such as XML, HTML, XHTML. The algorithm is described by XSL.
XSLT - is designed for use as part of XSL, transforming an XML document into another XML document, or another type of document that is recognized by a browser, like HTML or XHTML. XSLT uses XPath.
XPath - is a set of syntax rules for defining parts of an XML document.
To keep this article simple and clear, I'll break it down into two parts, and put XSL, XSLT to my next article.

Using the code

Here is the source XML data:

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd country="USA">
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <price>10.90</price>
  </cd>
  <cd country="UK">
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <price>10.0</price>
  </cd>
  <cd country="USA">
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <price>9.90</price>
  </cd>
</catalog>

If you want to select all of the price elements, here is the code:

using System.Xml;
using System.Xml.XPath;
....
string fileName = "data.xml";
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();

// Compile a standard XPath expression

XPathExpression expr; 
expr = nav.Compile("/catalog/cd/price");
XPathNodeIterator iterator = nav.Select(expr);

// Iterate on the node set

listBox1.Items.Clear();
try
{
  while (iterator.MoveNext())
  {
     XPathNavigator nav2 = iterator.Current.Clone();
     listBox1.Items.Add("price: " + nav2.Value);
  }
}
catch(Exception ex) 
{
   Console.WriteLine(ex.Message);
}

In the above code, we used "/catalog/cd/price" to select all the price elements. If you just want to select all the cd elements with price greater than 10.0, you can use "/catalog/cd[price>10.0]". Here are some more examples of XPath expressions:

/catalog selects the root element
/catalog/cd selects all the cd elements of the catalog element
/catalog/cd/price selects all the price elements of all the cd elements of the catalog element
/catalog/cd[price>10.0] selects all the cd elements with price greater than 10.0
starts with a slash(/) represents an absolute path to an element
starts with two slashes(//) selects all elements that satisfy the criteria
//cd selects all cd elements in the document
/catalog/cd/title | /catalog/cd/artist selects all the title and artist elements of the cd elements of catalog
//title | //artist selects all the title and artist elements in the document
/catalog/cd/* selects all the child elements of all cd elements of the catalog element
/catalog/*/price selects all the price elements that are grandchildren of catalog
/*/*/price selects all price elements which have two ancestors
//* selects all elements in the document
/catalog/cd[1] selects the first cd child of catalog
/catalog/cd[last()] selects the last cd child of catalog
/catalog/cd[price] selects all the cd elements that have price
/catalog/cd[price=10.90] selects cd elements with the price of 10.90
/catalog/cd[price=10.90]/price selects all price elements with the price of 10.90
//@country selects all "country" attributes
//cd[@country] selects cd elements which have a "country" attribute
//cd[@*] selects cd elements which have any attribute
//cd[@country='UK'] selects cd elements with "country" attribute equal to 'UK'

Read more: Codeproject

Posted via email from Jasper-net

12 Excellent Cloud Computing Operating Systems

|
Cloud is not just a natural form of smoke. It is also the most hyped term in the IT industry right now. Everyone is talking about cloud and vendors all cloudify their products and service offerings. In the area of operating systems this is also happening and a cloud OS is simply a simplified operating system that runs just a web browser (at least that is one definition of it), providing access to a variety of web-based applications that allow the user to perform many simple tasks without booting a full-scale operating system. Because of its simplicity a cloud OS can boot in just a few seconds. The operating system is designed for Netbooks, Mobile Internet Devices, and PCs that are mainly used to browse the Internet. From a cloud OS the user can quickly boot into the main OS, because it is possible to continue booting the main OS in the background while using a cloud OS (at least this is the goal).

glide.jpg

Glide OS 4.0 is a comprehensive Ad-Free cloud computing solution. Glide is a free suite of rights-based productivity and collaboration applications with 30GBs of storage. Users who want extra storage or would like to add extra users can upgrade to Glide Premium now with 250 GBs for $50.00 a year or 20 cents per GB per year. With a Glide Premium account you can set up and administer up to 25 users. The Glide OS provides automatic file and application compatibility across devices and operating systems. With Glide OS you also get the Glide Sync App which helps you to synchronize your home and work files.

Posted via email from Jasper-net

Back to Basics: Delegates, Anonymous Methods and Lambda Expressions

| Monday, May 2, 2011
Introduction

Like generics, delegates are one of those features that developers use without really understanding. Initially this wasn’t really a problem since delegates were reserved for fairly specific purposes: implementing callbacks and as the building-block for events (amongst a few other edge cases). However, each version of .NET has seen delegates evolve, first with the introduction of anonymous methods in 2.0 and now with lambda expressions in C# 3.0. With each evolution, delegates have become less of an specific pattern and more of a general purpose tool. In fact, most libraries written specifically for .NET 3.5 are likely to make heavy use of lambda expressions. As always, our concern isn’t just about understanding the code that we use, but also about enriching our own toolset. Seven years ago it wouldn’t have been abnormal to see even a complex system make little (or no) us of delegates (except for using the events of built-in controls). Today, however, even the simplest systems heavily relies on them.

Delegates

The best way to learn about all three framework/language feature is to start from the original and build our way up, seeing what each evolution adds. Delegates have always been pretty simple to understand, but without any good reason to use them, people never really latched on to the concept. It’s always easier to understand something when you can see what problem it solves and how it’s used – and examples of delegates always seem contrived.

Delegates are .NETs version of function pointers – with added type safety. If you aren’t familiar with C or C++ (or another lower level languages) that might not be very helpful. Essentially they let you pass a method into another method as an argument. Although many developers understand the concept in languages such as JavaScript, the strictness of C#/VB.NET makes it a little more confusion. For example, the following JavaScript code is completely valid (and even common):

function executor(functionToExecute)
{
   functionToExecute(9000);
}
var doSomething = function(count){alert(“It’s Over ” + count);}
executor(doSomething);

Read more: CodeBetter

Posted via email from Jasper-net

Finally, You Can Kiss People Over the Internet [VIDEO]

|
kiss_internet.jpg

Tactile communications: it may not sound too exciting, but it’s precisely the field of research that produced a device which lets users “transmit the feeling of a kiss” long-distance.

The Kajimoto Laboratory at the University of Electro-Communications has created a device which consists of a hardware receptacle which is placed into the mouth, and software that remembers the movements of your tongue and sends them to the other connected device, which moves accordingly.

Of course, there’s more to a kiss than just the movement of the tongue, and the folks from Kajimoto plan to recreate them all. “The elements of a kiss include the sense of taste, the manner of breathing, and the moistness of the tongue. If we can recreate all of those I think it will be a really powerful device,” they explain in a video showcasing the device prototype.

Read more: Mashable

Posted via email from Jasper-net

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

|
MDT - Microsoft Deployment Toolkit, הינה מערכת של כלי עזר וסקריפטים המאפשרת הפצה של מערכות הפעלה מבית מיקרוסופט. כיום אני בדעה שזו אחת המערכות הטובות שיש בשוק (עבור מערכות הפעלה של מיקרוסופט בלבד) ולמרבה הפליאה היא אף חינמית, אך כמו רומנים רבים אחרים, ההתחלה הייתה קשה, כמו כל פולניה טובה היא לא התמסרה בקלות . כאמור מדובר בערכה חינמית וככזו היא דורשת הרבה יותר התאמות והכנות, מאשר מוצרי מדף מסחריים מקבילים, אבל אל דאגה המערכת מגיעה עם תיעוד ענף. "נאלצתי" לקרוא ולקרוא ובסוף לקרוא עוד קצת, לפני שניגשתי למלאכה, אך לטעמי עבודת ההכנה בתחילת הקשר השתלמה מאוד (פירוט בהמשך)

image_thumb_0DC0C9AF.png

פתרון חינמי. יתרון שאנו הישראלים אוהבים מאוד  . בעוד שפתרונות מסחריים מקבילים עולים כסף רב, פתרון זה ניתן חינם אין כסף, בהסתייגות קלה, אם בוחרים ביישום של הפצה אוטומטית לחלוטין יש צורך להשתמש בבסיס נתונים. SQL כידוע לא ניתן חינם, אך ניתן להשתמש ב-SQL Express או ב-SQL אירגוני ובכך לחסוך גם בעלות זאת.

מערכת פתוחה. כאמור הפתרון מורכב מסט של כלים וסקריפטים ולכן ניתן להתאימו לדרישות האתר ביתר קלות. אפשר להוסיף למערך סקריפטים, אפליקציות, ושינוי הגדרות בהתאם לדרישות הלקוח. מסיבה זו ניתן למצוא תוספים רבים למוצר, ברחבי רשת האינטרנט. המוצר גם זוכה לשדרוגים תכופים של מיקרוסופט עצמה.

הפצה חצי אוטומטית (LTI - Lightwight installation) . הכוונה היא שניתן ליצר מנגנון הפצה שיתשאל , תוך כדאי התהליך, את המשתמש לגבי העדפותיו (באמצעות טפסי הזנת נתונים) כגון שם מחשב, רזולוציית מסך, הגדרות אזור וכ"ו.

Read more: MS Support blog

Posted via email from Jasper-net

C# Silverlight WCF: Thread Safe Multiple Async Call Strategy With Final Operation To Join Data.

|
This article describes one way to handle asynchronous or async calls in .Net 3.5 or .Net 4.0 when using WCF in Silverlight in C#. The goal is to have a final operation wait for all the calls to finish so to combine all the data gathered, all in a thread safe way. A secondary goal is to minimize the consumer code required to perform this operation from what is currently available in straight WCF async calls.
This article has a short shelf life because after .Net 4 (see What’s Next in C#? Get Ready for Async!) one will use the built in Asynchrony methodology developed. Until that time if one is using any version of Silverlight and WCF then this article describes how to handle those multiple async calls and join the data in a final method call.

Final Result Example
Before delving into the solution, here is how the consumer will use the methodology. Below a user is getting account information of user requests, departments and accounts to join all the data on the view model in the final method for display on a Silverlight page. Thesee operations as shown are setup when the view model class (MyViewModel) is created and no blocking occurs keeping UI thread clear.

public MyViewModel()
{
    DataContext = new MyServiceClient();
 
    FinalAsync(CombineDataAndDisplay); // When all the data is retrieved, do this method to combine the data From the 3 async callls below
 
    // Provide the operation as a lambda (could be a method call) to assign data to our target backing store property
    // and if all has gone well (no errors in other async calls) and it is the final completing operation. Do the final
    // Processing call automatically.
    DataContext.GetUserRequestsCompleted   += (s, e) => { AssignResultCheckforAllAsyncsDone(e, e.Result, ref _UserRequests, "Acquisition failure for User Requests");};
    DataContext.GetAccountsCompleted       += (s, e) => { AssignResultCheckforAllAsyncsDone(e, e.Result, ref _Accounts, "Acquisition Failure for Accounts"); };
    DataContext.GetDepartments             += (s, e) => { AssignResultCheckforAllAsyncsDone(e, e.Result, ref _Departments, "Failed to get Department Info."); };   
 
    // Start the Async processes
    MultipleAsyncRun(DataContext.GetUserRequestsAsync);
    MultipleAsyncRun(DataContext.GetAccountsAsync);
    MultipleAsyncRun(DataContext.GetDepartmentsAsync);
 
    // Exit out and return the UI thread to the user operations.
}
 
// Once all the data is done, combine and assign into our
// PagedCollectionView property for display on the screen.
public void CombineDataAndDisplay()
{
    // Combine missing data on the calls
   _UserRequests.ToList()
                .ForEach(ur =>
                {
                ur.BillingName     = _Accounts.First(ac => ur.AccountID == ac.AccountID).Name;
                ur.DepartmentName  = _Departments.First(dp => dp.DepartmentID == ur.DepartmentID).Name;
                });
 
    UserRequests = new PagedCollectionView( _UserRequests);
    UserRequests.GroupDescriptions.Add(new PropertyGroupDescription("DepartmentName"));
 
}

Posted via email from Jasper-net

Microsoft has magic iOS to WP7 conversion tool?

|
Microsoft has launched a free-to-download interoperability pack to help developers convert existing iOS applications to Windows Phone. But don't get too excited - the result is not as impressive as you might imagine.
 
If you think about it for even a few moments then it is obvious that one way that Microsoft can pick up some easy apps for its Windows Phone (WP) is to create a converter that reads in an iOS app and spits out a WP Silverlight/XNA app and this is exactly what they haven't done.
What they have done amounts more to encouragement than anything really helpful. The have put together a free to download package of things that might make it a bit easier to convert an iOS app to WP.
The items in the download include a 90-page guide to converting your iOS to WP and a series of "developer stories" - videos of developers talking about how they ported their iPhone apps to WP including why they did it.
The biggest and most useful item in the package is the API mapping tool. This simply takes iOS API calls and lists the nearest equivalents under WP - classes, events and methods are covered. This is undeniably useful but of course it doesn't provide a perfect or automatic solution simply because the structure of the frameworks involved is different. However there are plenty of simple, easy-to-devise, one-to-one mappings - and here is the problem. The mapping tool only does the easy bits and leaves the difficult reimplementation to the programmer. It's a welcome help but not a solution to anything and I doubt it is going to get iOS programmers to convert their programs any faster than they might already have done.

wpiostranslate.png

Read more: I Programmer

Posted via email from Jasper-net

The Basics of Task Parallelism via C#

|
Preface

The trend towards going parallel means that .NET Framework developers should learn about the Task Parallel Library (TPL). But in general terms, data parallelism uses the input data to some operation as the means to partition into smaller pieces. The data is divvied up among the available hardware processors in order to achieve parallelism. It is then often followed by replicating and executing some independent operation across these partitions. It is also typically the same operation that is applied concurrently to the elements in the dataset.

Task parallelism takes the fact that the program is already decomposed into individual parts – statements, methods, and so on – that can be run in parallel. More to the point, task parallelism views a problem as a stream of instructions that can be broken into sequences called tasks that can execute simultaneously. For the computation to be efficient, the operations that make up the task should be largely independent of the operations taking place inside other tasks. The data-decomposition view focuses on the data required by the tasks and how it can be decomposed into distinct chunks. The computation associated with the data chunks will only be efficient if the data chunks can be operated upon relatively independently. While these two are obviously inter-dependent when deciding to go parallel, they can best be learned if both views are separated. A powerful reference about Tasks re Compute-bound asynchronous operations is Jeffrey Richter’s book, “CLR via C#, 3rd Edition.” It is a good read.

In this brief article we will focus on some of the characteristics of the System.Threading.Tasks Task object. To perform a simple Task, create a new instance of the Task class, passing in a System.Action delegate that represents the workload that you want performed as a constructor argument. You can explicitly create the Action delegate so that it refers to a named method, use an anonymous function, or use a lambda function. Once you have created an instance of Task, call the Start() method, and your Task is then passed to the task scheduler, which is responsible for assigning threads to perform the work. Here is example code:

using System;
using System.Threading.Tasks;

public class Program {
 public static void Main() {
// use an Action delegate and named method
Task task1 = new Task(new Action(printMessage));
// use an anonymous delegate
Task task2 = new Task(delegate { printMessage() });
// use a lambda expression and a named method
Task task3 = new Task(() => printMessage());
// use a lambda expression and an anonymous method
Task task4 = new Task(() => { printMessage() });

task1.Start();
task2.Start();
task3.Start();
task4.Start();
Console.WriteLine("Main method complete. Press <enter> to finish.");
Console.ReadLine();
 }
private static void printMessage() {
  Console.WriteLine("Hello, world!");
 }
}

To get the result from a task, create instances of Task, where T is the data type of the result that will be produced and return an instance of that type in your Task body. To read the result, you call the Result property of the Task you have created. For example, let's say that we have a method called Sum. We can construct a Task object, and we pass for the generic TResult argument the operation's return data type:

using System;
using System.Threading.Tasks;
public class Program {

 private static Int32 Sum(Int32 n)
 {
  Int32 sum = 0;
  for (; n > 0; n--)
  checked { sum += n; } 
  return sum;
 }

 public static void Main() {
   Task<int32> t = new Task<int32>(n => Sum((Int32)n), 1000);
   t.Start();
  t.Wait(); 

        // Get the result (the Result property internally calls Wait) 
        Console.WriteLine("The sum is: " + t.Result);   // An Int32 value
    }
 }

Produces:

The sum is: 500500

If the compute-bound operation throws an unhandled exception, the exception will be swallowed, stored in a collection, and the thread pool is allowed to return to the thread pool. When the Wait method or the Result property is invoked, these members will throw a System.AggregateException object. You can use CancellationTokenSource to cancel a Task. we must rewrite our Sum method so that it accepts a CancellationToken, after which we can write the code, creating a CancellationTokenSource object.

Read more: Codeproject

Posted via email from Jasper-net

Widget Library for Windows Phone 7

|
Project Description
Create Windows Phone 7 apps using HTML, CSS and Javascript over the WebBroweser control inside the phone.

Widget Library for Windows Phone 7 allows you to build new applications for Windows Phone 7 in a easy way. You can migrate your widgets from iPhone or Android to Windows Phone 7 with this library. You have access to:
Play music on background
Show notifications
Navigate between pages
Play video
Download files
Save and load files from the IsolatedStorage

The communication between the WebBrowser Control and the Windows Phone 7 Apps is implemented using the script capabilities on the control.

Read more: Codeplex

Posted via email from Jasper-net

The Factory Design Pattern in C#

|
I have recently started to create video clips that explain the classic design patterns (GOF) and their implementation in C#. You can find the video clips and the source code they use available for free at www.CSharpBook.co.il. The video clips were prepared in Hebrew. The following video clip explains the factory design pattern and its implementation in C#.

Read more: Life Michael

Posted via email from Jasper-net