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

Invoking events without worrying about cross-thread exceptions

| Thursday, May 13, 2010
InvalidOperationException:"Cross-thread operation not valid: Control '<name>' accessed from a thread other than the thread it was created on."

This exception is something often seen by someone who needs work done on a background thread to leave the application UI responsive to users and maybe even allow the user to cancel the current opperation, while changing properties of controls on the UI from within the background opperation.

I will explain in this a solution in dealing with this particular problem, given a scenario in which the solution is appopriate, where I use extension methods to provide a general solution to the problem.

Background

It should be noted that when particular opperations need to be executed in the background, a the BackgroundWorker is by far the best way to accomplish this.

However, it is not always possible to use the background worker 'as is' and you could even have a need to write your own thread handling classes. This is where the following extension method comes in handy.

The problem

Consider the scenario in which you want to wrap a BackgroundWorker and provide an extra event that reports a status message of the work being done in the worker.

public class ThreadedCall
{

// The worker being wrapped by our class
private BackgroundWorker bw;

// Our new event that will be called whenever our class wants to report a status
public event StatusChangedEventHandler StatusChanged;

// The entry point of our class to start background opperation
public void Start()
{

bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}

// The method that does the actual work, run inside our wrapped worker
void bw_DoWork(object sender, DoWorkEventArgs e)
{

// Report a status here
if (StatusChanged!= null) StatusChanged.Invoke(this,new StatusChangedEventArgs("Phase 1"));
Thread.Sleep(100);  // Do some work

// Report another status here
if (StatusChanged!= null) StatusChanged.Invoke(this,new StatusChangedEventArgs("Phase 2"));
}
}

Our event handler code:

// Delegate to eventhandler that takes a StatusChangedEventArgs as paramater
public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

public class StatusChangedEventArgs : EventArgs
{
private string status;

// The status property added to the eventargs used to supply status to the callee
public string Status
{
get { return status; }
set { status = value; }
}

public StatusChangedEventArgs(string status)
{
this.status = status;
}
}

Some code to test our class (The UI code):

private void button1_Click(object sender, EventArgs e)
{

// Instantiate and start or worker wrapper
ThreadedCall t = new ThreadedCall();
t.StatusChanged += new StatusChangedEventHandler(t_StatusChanged);
t.Start();
}

void t_StatusChanged(object sender, StatusChangedEventArgs e)
{
// The following line will raise an exception!
textBox1.Text = string.Format("Status: {0}", e.Status);
}


Read more: Codeproject

Posted via email from jasper22's posterous

Importing an Excel File into a Silverlight DataGrid in XML Format

|
Introduction

Microsoft Excel is a wonderful tool which allows you to capture and analyze all kind of data, but one of the great features of Excel, is its ability to do simple data entry, whether you are a programmer or not. What if you could click a button and have your Excel data displayed inside a grid in the browser? Then anyone could see your data, if they are on a Mac or PC, and they don't even need to own Excel to see it. This article will illustrate that moving Excel Documents into Silverlight is a snap if your Excel spreadsheet is saved in an XML file.

Saving your spreadsheet in XML

To save your Excel spreadsheet as XML, first open up your Excel spreadsheet and go to the file menu (the little round circle in the upper left hand corner with the logo in it). Click Save As and choose XML spreadsheet 2003 (*.xml). This is what you will see if you are using Office 2007. Choose the directory you want to save the spreadsheet and click the Save button.

Your xml file will have an XML representation of your spreadsheet as you might expect, with nodes containing workbook, worksheet, rows, and cells. You can see that all the data is contained within the cell structure much like the programmable Excel COM interface you might use to extract data from Excel.

Listing 1 - Excel Worksheet saved in XML

<Worksheet ss:Name="Sheet1">
 <Table ss:ExpandedColumnCount="4" ss:ExpandedRowCount="4" x:FullColumns="1"
  x:FullRows="1" ss:DefaultRowHeight="15">
  <Column ss:Width="74.25"/>
  <Column ss:Width="84.75"/>
  <Column ss:Index="4" ss:Width="130.5"/>
  <Row ss:AutoFitHeight="0">
   <Cell><Data ss:Type="String">Name</Data></Cell>
   <Cell><Data ss:Type="String">Address</Data></Cell>
   <Cell><Data ss:Type="String">State</Data></Cell>
   <Cell><Data ss:Type="String">How did you hear about us</Data></Cell>
  </Row>
  <Row ss:AutoFitHeight="0">
   <Cell><Data ss:Type="String">Mahesh Chand</Data></Cell>
   <Cell><Data ss:Type="String">40W Maple Drive</Data></Cell>
   <Cell><Data ss:Type="String">PA</Data></Cell>
   <Cell><Data ss:Type="String">Web</Data></Cell>
  </Row>
  <Row ss:AutoFitHeight="0">
   <Cell><Data ss:Type="String">Mike Gold</Data></Cell>
   <Cell><Data ss:Type="String">100 Lamar Drive</Data></Cell>
   <Cell><Data ss:Type="String">TX</Data></Cell>
   <Cell><Data ss:Type="String">Google Search</Data></Cell>
  </Row>

Read more: C# Corner

Posted via email from jasper22's posterous

Running WordPress on Windows Server

|
A few days ago, I saw someone posted on Twitter a question about running WordPress on Windows Server.  Since I had done this for a few sites, I responded with my thoughts and tips.  Another suggested that I post those here, and so here I go.

WordPress is a blogging/content-management platform that has been around for a while.  It has been gaining more in popularity for general purpose content sites over the past year I’d say, but is primarily seen as a blogging platform by most.  Even though I use Subtext for my platform, I have to admit that if I hadn’t already started using Subtext, it would be really hard to sway me away from WordPress.  It’s just the killer app for blogging.  Why?  Because of the immense ecosystem of people using it, there is pretty much a plethora of plugins, themes and tools for it.

WordPress is a PHP application and mostly used on Linux environments.  But guess what—PHP has been running on Windows for years.  In fact, our IIS team created a FastCGI implementation for IIS to make PHP applications even run better on Windows.  So here’s how I got started…

Install WordPress
First you obviously need to install the pieces.  I’m assuming here you have access to the actual server.  WordPress requires PHP, MySQL and the WordPress bits themselves.  You can certainly hunt around for those yourself, or you can use the Web Platform Installer from Microsoft and install WordPress on your box in about 15 minutes including download time.  No hunting for the right bits, no tinkering for the right configs.  Just install WebPI, select WordPress and go.  Honestly, this is the best way to get it started on Windows.

After installing you should be up and running with a starting site.  Login to complete the process.

Decide on your permalinks or ‘pretty/clean URLs’
Here’s the main issue with WordPress on Windows.  By default Windows 2003 is still using ISAPI filters to process requests.  What this means is that it needs something to trigger the subsystem it will use to render.  In this case it’s .php for the php files of WordPress – IIS then knows to use PHP to render the files/logic.

However because of this the default pattern of WordPress URLs on Windows 2003 will be <domain>/?page_id=12345.  For everything.  That isn’t very clean or friendly according to the SEO experts.

Read more: Method ~ of ~ failed

Posted via email from jasper22's posterous

An HTML5 Remote Desktop

|
VNC and Remote Desktop software were around for a long while now. Undoubtedly they work great for most of purposes but, I wanted to bring the old VNC / Remote Desktop concept over the web, to allow full web-application integration and full cross-browser cross-platform support out-of-the-box.

Despite its name, ThinVNC is not a traditional VNC, as it does not implement the AT&T RFB protocol. Instead, it is built on top of today's web standards: AJAX, JSON and HTML5.

The Code (Part I)

In this first part we'll see the code to do the screen capture. The standard aproach is to capture the whole desktop. However, in this case, we'll capture every window individually, applying clipping regions and saving the individual bitmap for later comparison and difference extracting.

Firstly we need to enumerate all visible top windows:

TWin = class(TObject)
private
 Wnd : Hwnd;
 Rect : TRect;
 Pid : Cardinal;
public
 constructor Create(AWnd:HWND;ARect:TRect;APid:Cardinal);
end;

function EnumWindowsProc(Wnd: HWnd; const obj:TList<TWin>): Bool; export; stdcall;
var ProcessId : Cardinal;
 R,R1 : TRect;
 Win : TWin;
begin
 Result:=True;
 GetWindowThreadProcessId(Wnd,ProcessId);
 if IsWindowVisible(Wnd) and not IsIconic(wnd)then begin
   GetWindowRect(Wnd,R);
   IntersectRect(R1,R,Screen.DesktopRect);
   if not IsRectEmpty(R1) then begin
     win := TWin.Create(Wnd,R,ProcessId);
     obj.Add(win);
   end;
 end;
end;

procedure GetProcessWindowList(WinList:TList<TWin>);
begin
 WinList.Clear;
 EnumWindows(@EnumWindowsProc, Longint(WinList));
end;
We want to keep a list of windows, with their basic attributes and their bitmaps, so we can compare with the new ones and send the differences to the client. Here we merge the window list into a list of TWindowMirror:

TWindowMirror = class
private
 FIndex : Integer;
 FRgn : HRGN;
 FHandle : THandle;
 FBoundsRect : TRect;
 FProcessId : Integer;
 FImage : TBitmap;
 FDiffStreamList : TList<TImagePart>;
 ...
 ...
end;

procedure TMirrorManager.RefreshMirrorList(out OneMoved:Boolean);
 procedure GetProcessWindowList(WinList:TList<TWin>);
 begin
   WinList.Clear;
   EnumWindows(@EnumWindowsProc, Longint(WinList));
 end;

Read more: Codeproject

Posted via email from jasper22's posterous

Backup All databases

|
Here is the script that takes backup of all databases excluding system databases

The file name would be databasename_yyyymmdd where yyyymmdd is the formatted value of current date

create procedure Backup_all_databases
as
Declare @sql varchar(8000)
set @sql=''
select @sql=@sql+
'
Backup database '+name+' to disk=''E:\backup\'+name+'_'+convert(varchar(8),getdate(),112)+'.bak'''
from master..sysdatabases
where
name not in ('master','tempdb','model','msdb','pubs','Northwind')
--print @sql
EXEC(@sql)

Read more: Beyond Relational

Posted via email from jasper22's posterous

A quick introduction to the Google C++ Testing Framework

|
Why use the Google C++ Testing Framework?

There are many good reasons for you to use this framework. This section describes several of them.
Some categories of tests have bad memory problems that surface only during certain runs. Google's test framework provides excellent support for handling such situations. You can repeat the same test a thousand times using the Google framework. At the first sign of a failure, the debugger is automatically invoked. In addition, all of this is done with just two switches passed from command line: --gtest_repeat=1000 --gtest_break_on_failure.
Contrary to a lot of other testing frameworks, Google's test framework has built-in assertions that are deployable in software where exception handling is disabled (typically for performance reasons). Thus, the assertions can be used safely in destructors, too.
Running the tests is simple. Just making a call to the predefined RUN_ALL_TESTS macro does the trick, as opposed to creating or deriving a separate runner class for test execution. This is in sharp contrast to frameworks such as CppUnit.
Generating an Extensible Markup Language (XML) report is as easy as passing a switch: --gtest_output="xml:<file name>". In frameworks such as CppUnit and CppTest, you need to write substantially more code to generate XML output.

Creating a basic test

Consider the prototype for a simple square root function shown in Listing 1.

Listing 1. Prototype of the square root function

double square_root (const double);

For negative numbers, this routine returns -1. It's useful to have both positive and negative tests here, so you do both. Listing 2 shows that test case.

Listing 2. Unit test for the square root function

#include "gtest/gtest.h"

TEST (SquareRootTest, PositiveNos) {
   EXPECT_EQ (18.0, square-root (324.0));
   EXPECT_EQ (25.4, square-root (645.16));
   EXPECT_EQ (50.3321, square-root (2533.310224));
}

TEST (SquareRootTest, ZeroAndNegativeNos) {
   ASSERT_EQ (0.0, square-root (0.0));
   ASSERT_EQ (-1, square-root (-22.0));
}

Listing 2 creates a test hierarchy named SquareRootTest and then adds two unit tests, PositiveNos and ZeroAndNegativeNos, to that hierarchy. TEST is a predefined macro defined in gtest.h (available with the downloaded sources) that helps define this hierarchy. EXPECT_EQ and ASSERT_EQ are also macros—in the former case test execution continues even if there is a failure while in the latter case test execution aborts. Clearly, if the square root of 0 is anything but 0, there isn't much left to test anyway. That's why the ZeroAndNegativeNos test uses only ASSERT_EQ while the PositiveNos test uses EXPECT_EQ to tell you how many cases there are where the square root function fails without aborting the test.

Running the first test

Now that you've created your first basic test, it is time to run it. Listing 3 is the code for the main routine that runs the test.

Listing 3. Running the square root test

#include "gtest/gtest.h"

TEST(SquareRootTest, PositiveNos) {
   EXPECT_EQ (18.0, square-root (324.0));
   EXPECT_EQ (25.4, square-root (645.16));
   EXPECT_EQ (50.3321, square-root (2533.310224));
}

TEST (SquareRootTest, ZeroAndNegativeNos) {
   ASSERT_EQ (0.0, square-root (0.0));
   ASSERT_EQ (-1, square-root (-22.0));
}

int main(int argc, char **argv) {
 ::testing::InitGoogleTest(&argc, argv);
 return RUN_ALL_TESTS();
}

The ::testing::InitGoogleTest method does what the name suggests—it initializes the framework and must be called before RUN_ALL_TESTS. RUN_ALL_TESTS must be called only once in the code because multiple calls to it conflict with some of the advanced features of the framework and, therefore, are not supported. Note that RUN_ALL_TESTS automatically detects and runs all the tests defined using the TEST macro. By default, the results are printed to standard output. Listing 4 shows the output.

Read more: IBM

Posted via email from jasper22's posterous

History of SQL Server

|
As techies, we won’t much consider the history, for us what matters is the what we have today and what we will get tomorrow. But history teacher will tell, if you don’t know your history, you will not a success man for today and future.

What ever the point it is, let us look into the history of this great database SQL Server.

SQL Server 1.0

This version was release in 1989 and was released my jointly Microsoft, Sybase and Ashton-Tate. This edition was same as Sybase 3.0

SQL Server 4.2.1

SQL Server 4.2.1 for Windows NT was released in 1 993. Microsoft began making changes to the code. Microsoft SQL Server 4.21 for Windows NT was released at the same time as Windows NT 3.1.

SQL Server 6.0 & 6.5

SQL Server 6.0 was released in 1 995. In 1 996, the 6.5 upgrade was released.

It included the first version of Enterprise Manager and SQL Server Agent.

SQL Server 7.0

SQL Server 7.0 was released in 1998, and was a full rewrite of the Database Engine by Microsoft. You can say this was the first Microsoft SQL Server. SQL Server 7 also included English Query, OLAP Services, replication, Database Design and Query tools and Full-Text Search. Data Transformation Services (DTS) is also introduced. This was a major enhancement really. Especially features like DTS, OLAP were really new tools to the database users.

SQL Server 2000

SQL Server 2000 looks like SQL Server 7.0 and Microsoft entered into database market in big time. This SQL Server version was featured with clustering, much better performance, and real OLAP. It added user-defined functions, indexed views, Distributed Partition Views, and improved replication.

SQL Server 2000 64-bit version for Intel Itanium was released in 2003, along with the first version of Reporting Services and Data Mining tools. DTS became more powerful than SQL Server 7. Northwind joined Pubs as the sample database.

Read more: a true friend on database matters

Posted via email from jasper22's posterous

Net 4 Client Profile/Full silent install/repair/uninstall command line options

|
I have previously posted command lines that can be used to install, repair and uninstall the versions of the .NET Framework in silent mode and unattended mode.  Now that the .NET Framework 4 has shipped, I wanted to post an equivalent set of steps to install, repair and uninstall the .NET Framework 4 Client Profile and Full.

The .NET Framework 4 uses a different setup chainer than in previous versions of the .NET Framework.  As a result, the command lines are somewhat different than in previous releases.  There are also a few differences in how the repair and uninstall processes work that I wanted to call out specifically:

There are different repair and uninstall command lines for 32-bit and 64-bit versions of the .NET Framework 4
The .NET Framework 4 includes both a client profile and a full version.  Uninstalling the full version requires 2 steps – one to uninstall the extended component and another to uninstall the client profile.

Read more: Greg's Cool [Insert Clever Name] of the Day

Posted via email from jasper22's posterous

ADO .NET: Creating and Executing Parameterized Queries

|
In this post we’ll discuss how we can execute parameterized queries in .Net. At times when you can’t use the most recommended way to retrieve/update data through Stored Procedures, you can rely on parameterized queries. It is much safer and recommended than building a sql string dynamically, which is a bit more error prone as well as hard to maintain. Parameterized queries are queries that have one or more embedded parameters in sql statement which are also type safe. You build them separately and attach them into the sql statement.

Following example shows how to use parameterized queries with ADO.Net.

static void GetCustomersWithCity(string city)
{
   DataSet ds;
   SqlConnection con = new SqlConnection("server=localDBServer;database=AdventureWorks;Trusted_Connection=yes");

   SqlCommand cmd = new SqlCommand("select c.FirstName, c.LastName  from Person.Contact c " +
                                       " inner join Person.Address a " +
                                       " on c.ContactID = a.AddressID " +
                                       " where a.City = @CityParam;", con);

   SqlParameter cityParam = cmd.Parameters.Add("@CityParam", SqlDbType.VarChar);
   cityParam.Value = city;

   ds = new DataSet();
   SqlDataAdapter adapter = new SqlDataAdapter();
   adapter.SelectCommand = cmd;
   adapter.Fill(ds);
}

Read more: Beyond Rational

Posted via email from jasper22's posterous

Mercurial (hg) with Dropbox

|
I use Dropbox and Mercurial together so often now, and it's so freakin' awesome.

But just as I was setting up another repo, I realized that there was a slim possibility that there's programmers out there who don't use this trick. So they're still doing something crazy for source control, like trying to manage an SVN server, or a P4 server, or dealing with "only 1 private repo" restrictions, etc.

So... here it is, easy as pie. Or something that's easy, that isn't pie. Your Mom, etc.

First, sign up for Dropbox. (That's a referral link, you'll get an extra 250 meg on top of your free 2 gig if you use that instead of just going to the website).

Now, use Mercurial as normal. HgInit is a decent basic tutorial. You'll probably want to install hgtk on Linux, or TortoiseHg on Windows. But, just for example, here's the command line version:

~/myproj$ hg init
~/myproj$ hg addremove
~/myproj$ hg commit -m "initial commit"
Now you have revisions locally, which is nice enough, but that's just Mercurial. If your hard drive dies, you're hooped.

On the other hand, you didn't have to worry about servers or making depots, or backup, or other mucking around until you've spent at least a few hours on the exciting new "myproj" and you decide you'd rather not lose it.

So, what do you do? First, clone your repo into your Dropbox:

~$ cd ~/Dropbox
~/Dropbox$ hg clone ~/myproj ~/Dropbox/myproj-hg --noupdate

The syntax is hg clone <from> <to>. The --noupdate flag tell Mercurial to just store the repository data, not to check out a working copy. You're never going to work directly in the Dropbox directory, but instead use it as a "remote" where you push and pull to and from it. The only thing that will ever be in that directory is the .hg directory, and there's no user-serviceable parts in that particular one. That's why I renamed myproj to myproj-hg in the clone step, just so I remember that it's a Mercurial directory, and it's supposed to be "empty" (because the .hg will be hidden on Linux).

Read more: h4ck3r.net

Posted via email from jasper22's posterous

"Introduction to ASP.NET MVC by Coding a Cool App” (aka the MVC Music Store Application and Tutorial)

|
A couple weeks ago we did a soft release of a new ASP.NET MVC 2 Tutorial and Sample Application I’ve been working on over the past few months, the MVC Music Store. The source code and an 80 page tutorial are available on CodePlex. I’m also working on a video tutorial series for the ASP.NET website which will walk through building the application. After that, it’s time to talk about a feature length film and a worldwide MVC Music Store On Ice tour, but the plans aren’t completely set just yet.

Who is this for?

This tutorial is mostly written for beginners to ASP.NET MVC, including folks who are kind of new to web development. We already have a few tutorials out there at the intermediate to advanced developer level (Nerd Dinner, MVC Storefront) if you’re looking for something more advanced, but if you want to start with the basics of how ASP.NET MVC works before diving into repositories and IoC and TDD, this is a great place to get started.

However, I think it’s also pretty useful if you’ve got some experience with ASP.NET MVC 1.0 but want to get a look at using some of the new features in ASP.NET MVC 2, especially model validation.

What’s it cover?

Store features:


Store browse
Shopping cart
Checkout
Membership and registration
Basic administration (add and edit albums)

Tutorial covers:

ASP.NET MVC Basics
Controllers
Views
Models and ViewModels
Data access using Entity Framework 4
Model Validation
Editor and Display Templates
Use of ASP.NET Membership system
Client-side enhancements
Client-side validation
AJAX update showing both Ajax.ActionLink and jQuery

How’s the code?

I think this is a great tutorial sample, and I’m really proud of it. I spent a lot of time on it, and I had several reviews with Scott Guthrie and Scott Hanselman, as well as Phil Haack and Brad Wilson from the ASP.NET team. I’m hugely thankful to all of them for their input and patience, but of course I’ll take responsibility for any errors or killed kittens.

This is a beginner tutorial, so the code focuses on communicating how ASP.NET MVC works…

Read more: Greg's Cool [Insert Clever Name] of the Day
Official site: ASP.Net MVC Music Store

Posted via email from jasper22's posterous

SQL Server Maintenance Sequence

|
clip_image002_thumb.jpg

Regular maintenance is critical for running a healthy database. Maintenance reduces file fragmentation and provides backups that may be stored off site. The order in which you complete the various maintenance steps has significant consequences. In this blog post, I'll give you my recommended maintenance sequence and explain the logic behind it.

So, what should always come first? The DBCC CHECKDB statement. The database must have integrity before you take any action. An image of a corrupted database is a poor starting point for a restore and recovery process.

The typical, pro forma advice (see http://www.mssqltips.com/tip.asp?tip=1094) is to perform the following tasks in this order:

Check the database integrity.
Shrink the database.
Reorganize the index.
Rebuild the index.
Update the statistics.
Back up the database.
Clean up the history.
As you can see in the following screen shot, the SQL Server Maintenance Plan Wizard offers these tasks.

Read more: PTC Windchill on SQL Server

Posted via email from jasper22's posterous

X64 MANUAL STACK RECONSTRUCTION AND STACK WALKING

|
In this installment I would like to expand a bit on a previous post of mine called Challenges of Debugging Optimized x64 Code.  In that post I discussed the nuances of the x64 calling convention (thankfully of which there is only one) and how it is used in optimized builds of software.  The calling convention is sometimes referred to as the Application Binary Interface (ABI).  In this post, I would like to discuss the x64 unwind metadata and how you can use it in the debugger to manually walk a stack.

In some cases, you may have a corrupted stack that the debugger simply cannot effectively walk for you.  This often happens because the debugger walks a stack from the top down (assuming the stack grows upwards as if it were a stack of places on a table), and if the stack is sufficiently trashed then the debugger cannot find its bearing.  In the x86 world, a large percentage of the time, you can spot the stack frames by following the chain of base pointers and then build a crafty stack backtrace command to display the stack at some point in time.  But in the x64 calling convention there is no base pointer.  In fact, once a function’s prolog code has executed the rsp register generally never changes until the epilog code.  To read more about x64 prolog and epilog code conventions, go here.

Moreover, the syntax for creating a crafty stack backtrace command in the x64 environment is currently undocumented, and I aim to shed some light on that near the end of that blog post. J

The Example Code

For this blog post I have used the following example C# code that requires the .NET 4.0 framework and can be easily built from a Visual Studio 2010 command prompt.  You can find the code below:

using System;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;

class EntryPoint
{
   const int FactorialsToCompute = 2000;

   static void Main() {
       var numbers = new ConcurrentDictionary<BigInteger, BigInteger>(4, FactorialsToCompute);

       // Create a factorial delegate.
       Func<BigInteger, BigInteger> factorial = null;
       factorial = (n) => ( n == 0 ) ? 1 : n * factorial(n-1);

       // Now compute the factorial of the list
       // concurrently.
       Parallel.For( 0,
                     FactorialsToCompute,
                     (i) => {
                       numbers[i] = factorial(i);
                     } );
   }
}

The spirit of this code is to concurrently compute the first 2000 factorials and store the results in a dictionary.  This code uses the new Task Parallel Library to distribute this work evenly across the multiple cores on the system.  To compile the example (assuming the code is stored in test.cs), you can execute the following command from a Visual Studio 2010 command prompt:

csc /r:system.numerics.dll test.cs

Read more: NTDEBUGGING BLOG

Posted via email from jasper22's posterous

Google Releases Native Client SDK (Dev Preview) Submitted by Mitchell Pr

|
After adding module support for several modern processor architectures in March, Google's Native Client (NaCl) project has moved past the research version and released a developer preview SDK that should allow you to start writing NaCl apps in minutes.  Native Client is a plugin framework for the browser that is carefully sandboxed, and runs directly on the operating system while leveraging modern hardware architectures.  It has modules for running native x86 and ARM processor code in the browser with a native execution sandbox that isolates the application from the browser and the host's regular processes (Unlike Netscape plugins or ActiveX).

The research version of Native Client was made available about one year ago.  It consisted of a source tree snapshot that developers could download and play with, but the download was pretty bulky. The Native Client SDK is much more lightweight, giving you access to powerful APIs and allowing you to write C/C++ that works seamlessly in Chromium.  It includes only the essential components for getting an app up and running.  These components include a modified GCC compiler to generate x86-32 or x86-64 binaries from C/C++, ports of open source projects such as zlib, Lua, and libjpeg, and some samples for developing with the NPAPI Pepper Extensions.

Read more: DZone

Posted via email from jasper22's posterous

MouseShade

| Wednesday, May 12, 2010
mouseshade.JPG

  MouseShade is an essential tool for everyone doing presentations or demos. If turned on, it dims the screen and puts a spotlight on the area around the mouse pointer, easily guiding the audiences attention to an area of interest. The shape of the spotlight, the colour of the shade and the opacity of the shade can all be varied by accessing the pop up menu available from the icon in the Taskbar, simply by right clicking.
All options set are saved when the application closes, ready for the next time you use it. When in use, the shade can be minimised, giving a clear view of the whole screen, and can then be reactivated when you need to highlight a specific part of the screen by clicking the Show option on the menu.

Read more: FX Software

Posted via email from jasper22's posterous

Sharp busts out world's first 3D HD camera for mobile devices

|
10x0512noiub35sharp.jpg


Oh yeah, things just got real. Sharp has announced an industry first today, with its 720p-recordin' 3D camera module. Intended for mobile devices like smartphones and point-and-shoot digicams, this miniature wonder will be sampling in July and hitting mass production before the end of the year. Not much else is known about it at this point -- we can guess it'll cost a pretty penny when it debuts -- but Sharp has penned an effusive press release, which you may explore just past the break.

Read more: Engadget

Posted via email from jasper22's posterous

Effective C++ in an Embedded Environment

|
Summary
Artima has published a PDF document that contains the presentation materials from Scott Meyers' two-day training course on embedded C++. It provides an in-depth examination of how C++ can be applied in embedded systems, including costs of language features, ROMing, ISRs, memory management, safety-critical and real-time considerations, and more.
You can purchase a copy here:

http://www.artima.com/shop/effective_cpp_in_an_embedded_environment

The features include:

Same content as the training course: The PDF you'll get is an exact snapshot of Scott's full-color training materials on the day he generates the PDF. You'll get not only the slides Scott shows in class, you'll also get the accompanying notes—the very ones Scott uses. To see exactly what you'll get you can view a free sample.

No DRM: You may copy the PDF to as many devices as you like, annotate it in any way you want, print it in part or in full as many times as you choose. Because the PDF is for your personal use only, you are not permitted to provide copies to friends or colleagues, may not install it on servers for public access, can't use it as the basis for presentations, etc., but we trust you to adhere to these restrictions; the PDF itself doesn't try to prevent unauthorized uses. (For more permissive usage options, consider licensing the materials.)

Free updates for life: You are entitled to free updates to the materials as long as Scott produces them. Major revisions are included, so you won't have to pay again later for a "new edition."

Volume discounts: Want a copy for every member of your team or department? Discounts of 30-50% off single-PDF prices apply to purchases of as few as 10 copies. As the saying goes, the more you buy, the more you save! Consult the discount schedule for details.

Read more: Artima Developer

Posted via email from jasper22's posterous

Xcode: Static library template with Google Toolkit for Mac Testing framework.

|
For the past few posts i have been talking about how you can adjust the existing project templates and how you can use static libraries within your own project. For some time i wanted to write something about how to do unit testing within your iPhone project.

I have been using the Google Toolkit for Mac for some time now and then especially the unit testing framework that is included. This is quite a nice framework which adds some extra capabilities in comparison to the standard testing framework which is available within Xcode.

One thing that bothered me with the standard unit testing framework of Xcode is that when you create a project is is not present by default. It is also quite difficult to set it up, there are numerous explanations on this subject on the internet but almost none of them are complete. It all involves creating new build targets, setting up the dependencies between the targets and more.

To do this every time when you create a new project it is much more convenient to just adjust the existing templates so that when you create a new project it is present by default. Now there are quite a lot of project templates to begin with, not only do you have for example a project template visible in the New Project window but a lot of these also contain a number of sub-templates. For example, a lot of templates have options like Core data, this is actually a separate project template.

In an earlier post i already outlined why using static libraries are so interesting:

  • Re-usability of source code.
  • Separation of user interface logic and business logic / application logic.

Read more: Sodeso

Posted via email from jasper22's posterous

Case Study: Pack Mismatch

|
Packing is a way to arrange data  in memory using padding technique to align data at a memory offset equal to multiple of a fix size (usual the word size, but it could be byte size, DWORD size or any other size). The purpose of packing is to align the data memory layout to the microprocessor’s addressing model, and this can help increase performance (in some microprocessor architectures, misaligned data is even not allowed at all). Furthermore, packing can also be used to eliminate cache false sharing issue by forcing individual data structure to occupy an entire cache line. This is very important in high performance/parallel computing domain and it  become more and more relevant  to everybody else because the industrial trend of moving towards multi-core processors machine.

Note: See more information about pack and alignment in [MSDN-PACK]. For more on false sharing see [WVC07] Chapter 8.2 and [PPP09] Chapter 1

In this case study, a heap bug is encountered due to incorrect use of the packing. The debugging technique demonstrated here includes some basic knowledge of Windows heap as described in last post and some understanding of data alignment in 64 bits Windows.

The Bug:

MyProgram is a 64-bit native application running under Windows 7, and it crashes consistently when it is launched. From the Event Viewer (Windows Logs/Application), the following error is logged:

Faulting application name: MyProgram.exe, version: 0.0.0.0, time stamp: 0x4b9d52d7
Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5be02b
Exception code: 0xc0000374
Fault offset: 0x00000000000c6cd2
Faulting process id: 0x1074
Faulting application start time: 0x01cac3bc0628969b
Faulting application path: d:\MyProgram\x64\Release\MyProgram.exe
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 4485473b-2faf-11df-8d9f-00151736c5a7

The exception code 0xc0000374 means STATUS_HEAP_CORRUPTION. At this point, it is clear that this is a heap corruption bug, but it still requires some more debugging to find out the what actually corrupted the heap.


The Debugging:

As mentioned in last post, debugger could change the behavior of a heap related bug. Therefore, the –hd option is used during debugging so that the heap layout remains exactly the same as if the MyProgram.exe is running without debugger. In addition, the symbol path is set to Microsoft Public Symbol Server.

Note: –hd prevents the debugger to use the special heap which has a different layout than the default heap used by Windows.

The debugger outputs the following information when Windows Heap Manager detected the heap problem:

Critical error detected c0000374
(1364.dd4): Break instruction exception - code 80000003 (first chance)
ntdll!RtlUnhandledExceptionFilter+0x29f:
00000000`77bc6c9f cc              int     3

With symbols loaded, uses command !heap to show more information, only the relevant outputs are shown

0:003> !heap
Details:

Error address: 00000000048b8410
Heap handle: 00000000048b0000
Error type heap_failure_buffer_overrun (6)
Last known valid blocks: before - 00000000048b8320, after - 00000000048b8fc0
Stack trace:
               0000000077bca4a8: ntdll!RtlpAnalyzeHeapFailure+0x00000000000003a8
               0000000077b5ea71: ntdll!RtlpAllocateHeap+0x0000000000002176
               0000000077b529ac: ntdll!RtlAllocateHeap+0x000000000000016c
               0000000071a6c887: msvcr90!malloc+0x000000000000005b
               0000000071a6c987: msvcr90!operator new+0x000000000000001f
               000007fef2fdbf55: MyProvider!CGenericThreadPool::Initialize+0x0000000000000135
               000007fef2fd74c5: MyProvider!SpecialThreadPool::SpecialThreadPool+0x0000000000000075
               000007fef2fcb5cc: MyProvider!CPolicyProvider::CPolicyProvider+0x00000000000000ac
               000007fef2fd3e84: MyProvider!MyProviderInitialize+0x0000000000000034
               000007fef308e043: MyProgram!Initialize+0x00000000000002a3

As the output indicates, the heap issue is a buffer overrun, and the address where this happens is at 00000000048b8410. From the stack trace, it is obvious that overrun happens inside some constructor calls and Windows Heap Manager detected it when RtlAllocateHeap is called.

Read more: Brandon's Blog

Posted via email from jasper22's posterous

Resolving stop (blue screen) errors in Windows 7

|
Stop errors (also sometimes called blue screen or black screen errors) can occur if a serious problem causes Windows 7 to shut down or restart unexpectedly. You might see a message that says, "Windows has been shut down to prevent damage to your computer."

These errors can be caused by both hardware and software issues, and it can be difficult to troubleshoot the problem. The following tools and methods can often help get Windows up and running again.

If you can start Windows

These tools and methods can help you roll back your system to an earlier state, and help ensure your computer has the latest updates installed.

Read more: Windows Home

Posted via email from jasper22's posterous

Running ASP.NET Webforms and ASP.NET MVC side by side

|
One of the nice things about ASP.NET MVC and its older brother ASP.NET WebForms is that they are both built on top of the ASP.NET runtime environment. The advantage of this is that, you can still run them side by side even though MVC and WebForms are different frameworks.

Another point to note is that with the release of the ASP.NET routing in .NET 3.5 SP1, we are able to create SEO friendly URLs that do not map to specific files on disk. The routing is part of the core runtime environment and therefore can be used by both WebForms and MVC.

To run both frameworks side by side, we could easily create a separate folder in your MVC project for all our WebForm files and be good to go. What this post shows you instead, is how to have an MVC application with WebForm pages  that both use a common master page and common routing for SEO friendly URLs.  

A sample project that shows WebForms and MVC running side by side is attached at the bottom of this post.

So why would we want to run WebForms and MVC in the same project?  

WebForms come with a lot of server controls that provide a lot of rich functionality. One example is the ReportViewer control. Using this control and client report definition files (RDLC), we can create rich interactive reports (with charting controls). I show you how to use the ReportViewer control in a WebForm project here :  Creating an ASP.NET report using Visual Studio 2010. We can create even more advanced reports by using SQL reporting services that can also be rendered by the ReportViewer control.

Moving along, consider the sample MVC application I blogged about titled : ASP.NET MVC Paging/Sorting/Filtering using the MVCContrib Grid and Pager. Assume you were given the requirement to add a UI to the MVC application where users could interact with a report and be given the option to export the report to Excel, PDF or Word. How do you go about doing it?  

This is a perfect scenario to use the ReportViewer control and RDLCs. As you saw in the post on creating the ASP.NET report, the ReportViewer control is a Web Control and is designed to be run in a WebForm project with dependencies on, amongst others, a ScriptManager control and the beloved Viewstate.  

Read more: Raj Kaimal

Posted via email from jasper22's posterous

Microsoft Access 2010 Source Code Control

|
The Microsoft Access 2010 Source Code Control makes it easy to deploy and manage solutions built using Microsoft Access.

Read more: MS Download

Posted via email from jasper22's posterous

Integrating HTML into Silverlight Applications

|
Looking for a way to display HTML content within a Silverlight application? If you haven’t tried doing that before it can be challenging at first until you know a few tricks of the trade.  Being able to display HTML is especially handy when you’re required to display RSS feeds (with embedded HTML), SQL Server Reporting Services reports, PDF files (not actually HTML – but the techniques discussed will work), or other HTML content.  In this post I'll discuss three options for displaying HTML content in Silverlight applications and describe how my company is using these techniques in client applications.

Displaying HTML Overlays
If you need to display HTML over a Silverlight application (such as an RSS feed containing HTML data in it) you’ll need to set the Silverlight control’s windowless parameter to true. This can be done using the object tag as shown next:


   
   
   
   
   
   
   http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
        Get Microsoft Silverlight
   

By setting the control to “windowless” you can overlay HTML objects by using absolute positioning and other CSS techniques. Keep in mind that on Windows machines the windowless setting can result in a performance hit when complex animations or HD video are running since the plug-in content is displayed directly by the browser window. It goes without saying that you should only set windowless to true when you really need the functionality it offers. For example, if I want to display my blog’s RSS content on top of a Silverlight application I could set windowless to true and create a user control that grabbed the content and output it using a DataList control:

<style type="text/css">
   a {text-decoration:none;font-weight:bold;font-size:14pt;}
</style>
<div style="margin-top:10px; margin-left:10px;margin-right:5px;">
   <asp:DataList ID="RSSDataList" runat="server" DataSourceID="RSSDataSource">
       <ItemTemplate>
           
           <br />
           <%# XPath("description") %>
           <br />
       </ItemTemplate>
   </asp:DataList>
   <asp:XmlDataSource ID="RSSDataSource" DataFile="http://weblogs.asp.net/dwahlin/rss.aspx"
       XPath="rss/channel/item" CacheDuration="60" runat="server" />
</div>

The user control can then be placed in the page hosting the Silverlight control as shown below. This example adds a Close button, additional content to display in the overlay window and the HTML generated from the user control.

<div id="RSSDiv">
   <div style="background-color:#484848;border:1px solid black;height:35px;width:100%;">
       <img alt="Close Button" align="right" src="Images/Close.png" onclick="HideOverlay();" style="cursor:pointer;" />
   </div>
   <div style="overflow:auto;width:800px;height:565px;">
       <div style="float:left;width:100px;height:103px;margin-left:10px;margin-top:5px;">
           <img src=" " style="border:1px solid Gray" />
       </div>
       <div style="float:left;width:300px;height:103px;margin-top:5px;">
           Dan Wahlin's Blog
       </div>                
       <br /><br /><br />
       <div style="clear:both;margin-top:20px;">
           <uc:BlogRoller ID="BlogRoller" runat="server" />
       </div>                
   </div>            
</div>

Of course, we wouldn’t want the RSS HTML content to be shown until requested. Once it’s requested the absolute position of where it should show above the Silverlight control can be set using standard CSS styles. The following ID selector named #RSSDiv handles hiding the overlay div shown above and determines where it will be display on the screen.

Read more: Dan Wahlin's WebLog

Posted via email from jasper22's posterous

Moving Data from SQL Server 2000 to SQL Server 2008

|
I recently helped move data from a small SQL Sever 2000 database to SQL Server 2008 from one hosting environment to a different hosting environment. I tried several approaches and fortunately found one that worked well. You can find the detail in the post.

Approach #1: SQL Server Import/Export Wizard

People who were familiar with SQL Server 2000 probably enjoyed the Import and Export wizard that came with SQL Server 2000 Enterprise Manager. I used it all the times to upload a local database to a hosted server and vice versa. The wizard did exactly what it was designed for. However, this wizard doesn’t work with SQL Server 2005 or 2008. In order to import/export or copy an entire database, you will need a different tool available to SQL Server 2005/2008.

This tool (DTSWizard.exe) in SQL Server Management Studio allows you to copy data from tables and views only; it doesn’t import/export other objects such as stored procedures. Therefore, this option didn’t work for what I wanted to do.

image_3.png

Read more: Dr. Z's Blog

Posted via email from jasper22's posterous

Build Tools Roundup For .NET Systems

|
It seems there is not shortage of build tools that are available for the .NET developer these days. Of course I’m quite partial to the Ruby + Rake + Albacore solution, being the big tuna behind albacore and all… but quite honestly that amount of choice makes me very happy. It seems there is a good tool for just about every different comfort zone in the .NET developer world. At this point in time, there’s not one right answer of which build tool to use. You don’t need to choose which tool to use based on what features and functionality it supports anymore. Rather, you can make the choices based on what your comfortable with – be it the runtime environment, the language to create build steps, the data specification, etc. Choice is good. Understanding what each choice offers is even better. Here’s my take on the current set of tools that I’m aware of and what the comfort zone of these tools are.

Nant: The Godfather Of .NET Build Systems

Runtime: .NET
Build Configuration Language: XML with extensions written in .NET
URL: http://nant.sourceforge.net/

Nant is the old-school guy on the .NET block, having grown up over on Java road. This is the original .NET build tool that so many others wanted to be or wanted to be better than. If you’ve used any build tools for more than a few years in .NET, you’ve probably used Nant at least once. There are a lot of extensions and add-ons to Nant, including a user contributions project, several visual tools designed to abstract away the xml, some conventions based add-ons that make nant easier, etc. If you need to do it in your build process, chances are there is a plugin or a blog post that tells you how to do it with Nant.

Nant was originally a copy of the Java Ant build tool but quickly took its own directions in implementation becoming the defacto build tool in .NET for several years. With it’s heavy reliance on xml and its roots tracing back to java, most “enterprise” developers chose Nant because of it’s familiarity from the Java world.

Example: Build a solution

  1: <target name="compile">
  2:        <echo message="Build my solution!" />
  3:        <msbuild project="src/mysolution.sln">
  4:               <arg value="/property:Configuration=release" />                                  
  5:               <arg value="/t:Rebuild" />
  6:        </msbuild>
  7: </target>


UppercuT: You Won’t Know What Hit You

Runtime: .NET (Nant) with extensions to call out to other platforms such as Ruby/Rake.
Build Configuration Language: None for simple builds. XML/Nant, Ruby, and Powershell for extended scenarios
URL: http://code.google.com/p/uppercut/

If you’re going to use Nant and you don’t need to do anything “unusual”, then you should be using UppercuT. This is an add-on that makes Nant so easy to use, you don’t even need to know how to use Nant. UppercuT makes good on it’s promises, too. It really is that easy to get a build up and running because you don’t need to know anything other than the basic conventions that it uses to find your solutions, tests, etc.

From the project’s homepage:


It seeks to solve both maintenance concerns and ease of build to help you concentrate on what you really want to do: write code. Upgrading the build should take seconds, not hours. And that is where UppercuT will beat any other automated build system hands down.

UppercuT is targeted at those who want all of the power and stability that Nant provides, but don’t want to deal with a ton of XML and build script definitions.

Example: No, really… this project makes building with Nant so easy, you don’t need to configure any tasks for most things. Check out the website for more information.

MSBuild: Bringing ‘One Microsoft Way’ To Your Build System

Runtime: .NET
Build Configuration Language: XML with extensions written in .NET
URL: http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx


Read more: lostechies.com

Posted via email from jasper22's posterous

How to get info from client certificates issued by a CA (C#)

|
Hi all,

The following C# sample shows how to use Certadm.dll and CryptoAPI to get the name of the template and the enhanced usages of client certificates in a CA:

<SAMPLE file="Form1.cs">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using CERTADMINLib;

namespace CertAdminTest
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

       private void button1_Click(object sender, EventArgs e)
       {
           // Variables
           string strServerName = "MyServer";
           DirectoryEntry rootEntry = null;
           DirectoryEntry templatesEntry = null;

           try
           {
               // Get AD entry that we will use to translate a certificate template OID to its correspondent name
               rootEntry = new DirectoryEntry("LDAP://" + strServerName + "/rootDSE");
               templatesEntry = new DirectoryEntry("LDAP://" + strServerName + "/cn=certificate templates,cn=public key services,cn=services,cn=configuration," + (string)rootEntry.Properties["defaultNamingContext"][0]);

               // Get Certificate Services Database info
               ViewCertificateServicesDatabase(strServerName, strServerName, templatesEntry);
           }
           catch (Exception ex)
           {
               // Errors?
               MessageBox.Show(ex.Message);
           }
           finally
           {
               // Clean up
               if (rootEntry != null)
               {
                   rootEntry.Dispose();
               }
               if (templatesEntry != null)
               {
                   templatesEntry.Dispose();
               }
           }
       }

       private void ViewCertificateServicesDatabase(string strServer, string strCAName, DirectoryEntry templatesEntry)
       {
           // Variables
           CERTADMINLib.CCertView certView = null;
           CERTADMINLib.IEnumCERTVIEWROW certViewRow = null;
           CERTADMINLib.IEnumCERTVIEWCOLUMN certViewColumn = null;
           CERTADMINLib.IEnumCERTVIEWEXTENSION certViewExt = null;
           int iColumnCount = 0;
           string strBase64Value = "";
           string strValue = "";
           string strOID = "";
           int iStartIndex = 0;
           string strDisplayName = "";
           object objValue = null;
           string strOutput = "";

           // Connecting to the Certificate Authority
           certView = new CERTADMINLib.CCertViewClass();
           certView.OpenConnection(strServer + "\\" + strCAName);

           // Get a column count and place columns into the view
           iColumnCount = certView.GetColumnCount(0);
           certView.SetResultColumnCount(iColumnCount);

           // Place each column in the view.
           for (int x = 0; x < iColumnCount; x++)
           {
               certView.SetResultColumn(x);
           }

Read more: Decrypt my World

Posted via email from jasper22's posterous

Hibernate: это должен помнить каждый

|
Долго мучался, разруливая зависимости между сущностями, хранящимися в БД (т.е. персистентными сущностями). Пришлось разобраться с каскадными операциями, в итоге родилась вот такая памятка:

- cascade="none" - значение по умолчанию. Hibernate будет игнорировать ассоциации, поэтому разруливать зависимости придется самостоятельно.

- cascade="save-update" говорит Hibernate'у, что разруливать зависимости необходимо при комите транзакции в которой делается save() или update() объекта. Суть разруливания заключается в том, что новые объекты, с которыми есть ассоциации у нашего, будут сохранены до него. Это позволяет обойти constraint-violations.

- cascade="delete" говорит Hibernate'у, что надо разруливать зависимости при удалении объекта.

- cascade="all" обозначает выполнение каскадных операций при save-update и delete.

- cascade="all-delete-orphan" обозначает то же самое, что и cascade="all", но к тому же Hibernate удаляет любые связанные сущности, удаленные из ассоциации (например, из коллекции).

- cascade="delete-orphan" обозначает, что Hibernate будет удалять любые сущности, которые были удалены из ассоциации.

Part 2:

При определении идентификатора - первичного ключа - таблицы в Hibernate можно явно указать стратегию генерации его значения. Делается это в мэпинге с помощью тега generator, у которого указывается атрибут class. Например, так:

<id name="uid" column="uuid" type="string" length="32">

  <generator class="ru.naumen.bpm.commons.util.PrefixUUIDGenerator"/>

</id>


Помимо того, что можно определить свою стратегию генерации как класс, реализующий интерфейс org.hibernate.id.IdentifierGenerator, фреймворк содержит ряд уже готовых генераторов. Рассмотрим их подробнее.

increment - генерирует идентификаторы типов long, int и short, которые являются уникальными только если никакой другой процесс не добавляет данные в ту же самую таблицу. Данную стратегию нельзя использовать в кластерном окружении.

identity - поддерживает identity-столбцы в DB2, MySQL, MS SQL Server, Sybase и HypersonicSQL. Возвращаемый идентификатор имеет тип long, int или short.

sequence - использует последовательности в DB2, PostgreSQL, Oracle, SAP DB, McKoi или генераторы в Interbase. Возвращаемый идентификатор имеет тип long, int или short.

hilo - использует hi/lo алгоритм для рационального генерирования идентификаторов типа long, int или short уникальных для таблицы или колонки (по умолчанию - hibernate_unique_key и next_hi, соответственно). Hi/lo алгоритм генерирует идентификаторы, которые уникальны только для конкретной базы данных. Не стоит использовать данную стратегию для соединений, установленных с помощью JTA или с помощью определяемых пользователем соединений.

seqhilo - использует hi/lo алгоритм для рационального генерирования идентификаторов типа long, int или short. В качестве источника данных используются именованные последовательности.

Read more: БЛОГ СУРОВОГО ЧЕЛЯБИНСКОГО ПРОГРАММИСТА Part 1, Part 2

Posted via email from jasper22's posterous

Accessing Network Drive in C#

|
Problem:

One of the requirements of the product that I was doing is like this: There will be a screen in a windows based application and it consists of a combo box.  

The combo box should display the network drives of the computer. For those who are less literate about network drives; Network Drives are those locations that are mapped to a drive or folder in another system which can be accessed over network. Usually it is often painful to manually navigate to the network location and access the files there. So windows allow us to create network drives on our machines such that we can access the desired network location with just one single click.

How to create a Network Drive?

The creation of network drives is a very simple process.

Open My Computer --> Select tools from the menu bar--> Select the Map Network Drive option.

This opens a window which has a combo box with the existing network drives and non networking drives. Upon selecting a drive the text box below the drop down list will display the path that the network is mapped to. Once you select the drive letter from the combo box , Enter the Network path in the text box and click Finish. Now you should be able to view the network drives in the my computer screen.

Solution to the Problem:

If you have ever worked on .NET you would certainly know how vast the base class library of .NET is. We can do many things with it. Yet, we cannot do everything using just the .NET framework and the BCL. Windows OS( XP,VISTA,WINDOWS 7) uses a special assembly called 'mrp.dll". mpr.dll is a module containing functions that are used to handle communication between the Windows operating system and the installed network providers. This assembly basically takes care of the relation between Drive Name Versus the Network Path. So we use the same .dll to fetch us the information that we need. The assembly should be referred as an external assembly and values should be passed to it.  In order to do this we use the DllImport attribute method to point to the mpr.dll. We must point the Drive letters to the external Dll this should be done with the help of MarshallAs  attribute.

Have a look at the folowing code.

public static class Pathing
{
   [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
   public static extern int WNetGetConnection(
       [MarshalAs(UnmanagedType.LPTStr)] string localName,
       [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
       ref int length);
   /// <summary>
   /// Given a path, returns the UNC path or the original. (No exceptions
   /// are raised by this function directly). For example, "P:\2008-02-29"
   /// might return: "\\networkserver\Shares\Photos\2008-02-09"
   /// </summary>
   /// <param name="originalPath">The path to convert to a UNC Path</param>
   /// <returns>A UNC path. If a network drive letter is specified, the
   /// drive letter is converted to a UNC or network path. If the
   /// originalPath cannot be converted, it is returned unchanged.</returns>
   public static string GetUNCPath(string originalPath)
   {
       StringBuilder sb = new StringBuilder(512);
       int size = sb.Capacity;
       // look for the {LETTER}: combination ...
       if (originalPath.Length > 2 && originalPath[1] == ':')
       {
           // don't use char.IsLetter here - as that can be misleading
           // the only valid drive letters are a-z && A-Z.
           char c = originalPath[0];
           if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
           {
               int error = WNetGetConnection(originalPath.Substring(0, 2),
                   sb, ref size);
               if (error == 0)
               {
                   DirectoryInfo dir = new DirectoryInfo(originalPath);
                   string path = Path.GetFullPath(originalPath)
                       .Substring(Path.GetPathRoot(originalPath).Length);
                   return Path.Combine(sb.ToString().TrimEnd(), path);
               }
           }
       }
       return originalPath;
   }
}


Read more: C# Corner

Posted via email from jasper22's posterous

A Brief, Incomplete, and Mostly Wrong History of Programming Languages

|
1936 - Alonzo Church also invents every language that will ever be but does it better. His lambda calculus is ignored because it is insufficiently C-like. This criticism occurs in spite of the fact that C has not yet been invented.

1972 - Dennis Ritchie invents a powerful gun that shoots both forward and backward simultaneously. Not satisfied with the number of deaths and permanent maimings from that invention he invents C and Unix.

1972 - Alain Colmerauer designs the logic language Prolog. His goal is to create a language with the intelligence of a two year old. He proves he has reached his goal by showing a Prolog session that says "No." to every query.

1980 - Alan Kay creates Smalltalk and invents the term "object oriented." When asked what that means he replies, "Smalltalk programs are just objects." When asked what objects are made of he replies, "objects." When asked again he says "look, it's all objects all the way down. Until you reach turtles."

1983 - Bjarne Stroustrup bolts everything he's ever heard of onto C to create C++. The resulting language is so complex that programs must be sent to the future to be compiled by the Skynet artificial intelligence. Build times suffer. Skynet's motives for performing the service remain unclear but spokespeople from the future say "there is nothing to be concerned about, baby," in an Austrian accented monotones. There is some speculation that Skynet is nothing more than a pretentious buffer overrun.

1986 - Brad Cox and Tom Love create Objective-C, announcing "this language has all the memory safety of C combined with all the blazing speed of Smalltalk." Modern historians suspect the two were dyslexic

Read more: ONE DIV ZERO

Posted via email from jasper22's posterous

13 Top Virtualization Vendors all around the World

|
Here is the list of top virtualization vendors all around the world:

1. VMWare (Virtual Machine Software)

Find a major data center anywhere in the world that doesn't use VMware,.VMware owns anywhere from 55-85% of the virtualization market. VMware dominates the server virtualization market. VMware also dominates the desktop-level virtualization market and perhaps even the free server virtualization market with its VMware Server product. VMware remains in the dominant spot due to its innovations, strategic partnerships and rock-solid products.


2. Citrix

Open-source alternative to VMware.

3. Oracle

4. Microsoft

Microsoft Virtual Server was a dud. Virtual Server has captured a scant 7% market share.Viridian also failed to perform and comptete in the market.

5. Red Hat

For the past 15 years, everyone has recognized Red Hat as an industry leader and open source champion. Hailed as the most successful open source company, Red Hat entered the world of virtualization in 2008 when it purchased Qumranet and with it, its own virtual solution: KVM and SPICE (Simple Protocol for Independent Computing Environment). Red Hat released the SPICE protocol as open source in December 2009.

6. Amazon

Amazon's Elastic Compute Cloud (EC2) is the industry standard virtualization platform. Ubuntu's Cloud Server supports seamless integration with Amazon's EC2 services. EngineYard's Ruby application services leverage Amazon's cloud as well.

7. Google

When you think of Google, virtualization might not make the top of the list of things that come to mind, but its Google Apps, AppEngine and extensive Business Services list demonstrates how it has embraced cloud-oriented services.

Read more: Hello Tech Guys

Posted via email from jasper22's posterous

New Bing Screensaver

|
?default=content

These days, we no longer need screensavers to prevent “burn in” of images on our computer’s screens – those types of problems are, truly, a relic of another era, thank goodness (for LCD anyway).

That said, there’s no reason why you can’t use a screensaver just to brighten up your idle PC with a little beauty, art, or other images that just make you smile. (I enjoy a montage of my new baby’s pictures, for example).

If you also enjoy screensavers, there’s a lovely new one appearing here on Microsoft’s “DiscoverBing.co.uk” website. The Bing screensaver includes a number of the most popular images from the Bing.com homepage – the same images you’ll find in the popular themepacks Bing’s Best and Bing's Best 2.

Read more: on10

Posted via email from jasper22's posterous

Resolve a URL from a Partial View (ASP.NET MVC)

|
Working on an ASP.NET MVC application and needed the ability to resolve a URL from a partial view. For example, I have an image I want to display, but I need to resolve the virtual path (say, ~/Content/Images/New.png) into a relative path that the browser can use, such as ../../Content/Images/New.png or /MyAppName/Content/Images/New.png.

A standard view derives from the System.Web.UI.Page class, meaning you have access to the ResolveUrl and ResolveClientUrl methods. Consequently, you can write markup/code like the following:

<img src='=<%=Page.ResolveClientUrl("~/Content/Images/New.png")%>' />

The problem is that the above code does not work as expected in a partial view. What's a little confusing is that while the above code compiles and the page, when visited through a browser, renders, the call to Page.ResolveClientUrl returns precisely what you pass in, ~/Content/Images/New.png, in this instance. The browser doesn't know what to do with ~, it presumes it's part of the URL, so it sends the request to the server for the image with the ~ in the URL, which results in a broken image.

I did a bit of searching online and found this handy tip from Stephen Walther - Using ResolveUrl in an HTML Helper. In a nutshell, Stephen shows how to create an extension method for the HtmlHelper class that uses the UrlHelper class to resolve a URL. Specifically, Stephen shows how to add an Image extension method to HtmlHelper. I incorporated Stephen's code into my codebase and also created a more generic extension method, which I named ResolveUrl.

Read more: Scott on Writing

Posted via email from jasper22's posterous

New from Microsoft: Surreal Terrority Windows 7 Theme

|
?default=content

I love that Microsoft keeps updating their collection of themes for Windows 7 because - I have to admit - I quickly grow bored with my desktop background and color schemes. I like to switch it up pretty often and the themes feature in Windows 7 lets me do that easily. With themes, my wallpaper isn’t static – it rotates through a series of images on an interval I specify.

The latest theme to grace my desktop is the gorgeous, brightly-hued creation from artist Chuck Anderson called “Surreal Territory.” The theme includes a few different images of landscapes and sky but with a twist. Instead of the natural colors found in nature, the sky is colorized with rainbow-colored tones. Just lovely.

Read more: on10

Posted via email from jasper22's posterous

No More Boxes! Exploring the PathListBox (Silverlight TV #25)

|
In this video, Adam Kinney explains what the PathListBox is and why it is so compelling. Then, he demonstrates several ways of using it in creative examples. The PathListBox is one of the newest features available in Expression Blend and Silverlight 4. It redefines how users look at lists of data as it breaks the mold of a list "box" and opens the possibilities to use any shape or path. Don't miss this episode and be sure to download Adam's sample code.

Relevant links:

John's Blog and on Twitter (@john_papa)
Adam's Blog and on Twitter (@adkinn)
Get Expression Blend 4 RC trial
Source code for Adam's PathListBox demos
Adam's blog post on PathListBox
Follow us on Twitter @SilverlightTV or on the web at http://silverlight.tv/

Read more: JohnPapa.net
Video: Channel9

Posted via email from jasper22's posterous

Three nice opensource games for Linux

|
My today selection for Linux gamers are three nice opensource games, the games are

Go Ollie! : At first sight Go Ollie! looks like a game for kids, but once you play it you realize it can be fun for anyone, no matter what age.
Bos Wars : A futuristic real time strategy game (RTS)
Scorched 3D : A simple turn-based artillery game and also a real-time strategy game in which players can counter each others' weapons with other creative accessories, shields and tactics.


Go Ollie !

At first sight Go Ollie! looks like a game for kids, but once you play it you realize it can be fun for anyone, no matter what age.

Go Ollie! is an original platform game that stands out for several reasons. First, its main character is a worm, a tiny creature that is not usually regarded as an example of cuteness. Second, the worm is controlled with the mouse instead of cursor keys. And finally, the game scrolls automatically to one side, just like one of those old shoot'em ups.

In Go Ollie! your mission consists on collecting all the coins, fruits and whatever other valuable objects you find on your way. At the same time you'll have to avoid different kinds of enemies. Go Ollie! features two gaming modes: a Story mode that enables you to play over 60 levels with various objectives and an Action mode with unlimited replayable levels and a high score top list.

For Ubuntu Users you can install the game from Playdeb ( Be sure first to add the repositories of playdeb)

Read more: Unixmen

Posted via email from jasper22's posterous

8085 Microprocessor simulator

|
A cool way to learn and write 8085 assembly language programs. Gone are the days when you punched in the assembly language in hex format and hoped nothing went wrong.

The salient features include.
Write your programs using the syntax highlighting text editor which also gives contextual help in the status bar.
A built in 2 pass assembler and a full source level debugger to simulate/debug your 8085 programs.
View the state of the memory / register / flags.
Modify any memory location / register / instructions.
Set breakpoints.
Modify instructions at runtime with syntax checking.

This software is completely free and comes with the full source code which can be compiled using VS2005.

Read more: Codeplex

Posted via email from jasper22's posterous

May 2010 Security Release ISO Image

|
This DVD5 ISO image file contains the security updates for Windows released on Windows Update on May 11th, 2010. The image does not contain security updates for other Microsoft products. This DVD5 ISO image is intended for administrators that need to download multiple individual language versions of each security update and that do not use an automated solution such as Windows Server Update Services (WSUS). You can use this ISO image to download multiple updates in all languages at the same time.

Important:   Be sure to check the individual security bulletins at http://www.microsoft.com/technet/security prior to deployment of these updates to ensure that the files have not been updated at a later date.

This DVD5 image contains the following updates: KB978542 / (MS10-030)

Windows 2000 - 24 languages
Windows Server 2003 - 18 languages
Windows Server 2003 x64 Edition - 11 languages
Windows Server 2003 for Itanium-based Systems - 4 languages
Windows XP - 24 languages
Windows XP x64 Edition - 2 languages
Windows Vista - 36 languages
Windows Vista for x64-based Systems - 36 languages
Windows Server 2008 - 19 languages
Windows Server 2008 x64 Edition - 19 languages
Windows Server 2008 for Itanium-based Systems - 4 languages
Windows 7 - 36 languages
Windows 7 for x64-based Systems - 36 languages
Windows Server 2008 R2 x64 Edition - 19 languages
Windows Server 2008 R2 for Itanium-based Systems - 4 languages

Read more: MS Download

Posted via email from jasper22's posterous

GETTING STARTED BUILDING A WCF WEB SERVICE

|
This post is one in a series of upcoming MSDN articles.  It shows how to create a very simple web service using Windows Communications Founcation (WCF).  There is one special characteristic of the web service that I present in this article, which is that while it is very simple, it can be consumed as an External Content Type (ECT) from Business Connectivity Services (BCS).  In addition, the procedure presented in this post shows how to host this web service using Internet Information Services (IIS).

The subject of the series is creating a claims-aware web service and consuming it from SharePoint BCS.  In the short time that I’ve worked with claims-based authentication, what I experience is that while there are not very many steps to get it working, if you get anything wrong, then it just doesn’t work, and it takes some effort to figure out the problem.  My approach in these articles is to supply some procedures with small steps, with instructions all along the way to validate that what you have done so far works properly.  So the first step is to create a WCF web service, host it using IIS, and validate that it is working.

In the second article, I’m going to add some Windows Identity Framework (WIF) capabilities, so that the web service can report on the identity of the user of the web service.

In the third article, I’ll walk through consuming the web service from BCS.

In the fourth article, I’ll show how to move the web service to a different machine, make it claims-aware, and then again, consume it from BCS.  This solves the ‘double hop’ problem.

As usual, after these blog posts are published as MSDN articles, I’ll update posts with a links to the MSDN articles.

This web service contains only two methods: a ‘finder’ to retrieve a collection of items, and a ‘specific finder’ to retrieve a single item.  The ‘database’ behind the collection is just an initialized list.  The ‘schema’ of this little ‘database’ is very simple.  It is a single flat table consisting of two fields – an integer CustomerID, and a string CustomerName.  CustomerID is a unique ID.

Read more: Eric White's Blog

Posted via email from jasper22's posterous

ClosedXML - The easy way to OpenXML

|
ClosedXML makes it easier for developers to create OpenXML files for Excel 2007. It provides a nice object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents. It's developed in C# but can be used by any other .NET language.

What can you do with this?

ClosedXML allows you to create Excel 2007/2010 files without the Excel application. If you ever used the Microsoft Open XML Format SDK you know just how much code you have to write to get the same results as the following 4 lines of code.

    var workbook = new XLWorkbook("Sample.xlsx");
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = "Hello World!";
    workbook.Save();

Development Status

The current build has the following simple capabilities:
Can create new workbooks
Add worksheets
Access cells using R1C1 and A1 notation.
Add text, dates, booleans, and numbers to cells
Select ranges (not named ranges though)
Traverse a range's columns and rows

Read more: Codeplex

Posted via email from jasper22's posterous

Integrating Twitter Into An ASP.NET Website Using OAuth

|
Earlier this year I wrote an article about Twitterizer, an open-source .NET library that can be used to integrate your application with Twitter. Using Twitterizer you can allow your visitors to post tweets, view their timeline, and much more, all without leaving your website. The original article, Integrating Twitter Into An ASP.NET Website, showed how to post tweets and view a timeline to a particular Twitter account using Twitterizer 1.0. To post a tweet to a specific account, Twitterizer 1.0 uses basic authentication. Basic authentication is a very simple authentication scheme. For an application to post a tweet to JohnDoe's Twitter account, it would submit JohnDoe's username and password (along with the tweet text) to Twitter's servers. Basic authentication, while easy to implement, is not an ideal authentication scheme as it requires that the integrating application know the username(s) and password(s) of the accounts that it is connected to. Consequently, a user must share her password in order to connect her Twitter account with the application. Such password sharing is not only insecure, but it can also cause difficulties down the line if the user changes her password or decides that she no longer wants to connect her account to certain applications (but wants to remain connected to others).

To remedy these issues, Twitter introduced support for OAuth, which is a simple, secure protocol for granting API access. In a nutshell, OAuth allows a user to connect an application to their Twitter account without having to share their password. Instead, the user is sent to Twitter's website where they confirm whether they want to connect to the application. Upon confirmation, Twitter generates an token that is then sent back to the application. The application then submits this token when integrating with the user's account. The token serves as proof that the user has allowed this application access to their account. (Twitter users can view what application's they're connected to and may revoke these tokens on an application-by-application basis.)

In late 2009, Twitter announced that it was ending its support for basic authentication in June 2010. As a result, the code examined in Integrating Twitter Into An ASP.NET Website, which uses basic authentication, will no longer work once the cut off date is reached. The good news is that the Twitterizer version 2.0 supports OAuth. This article examines how to use Twitterizer 2.0 and OAuth from a website. Specifically, we'll see how to retrieve and display a user's latest tweets and how to post a tweet from an ASP.NET page. Read on to learn more!

Read more: 4 Guys from Rolla

Posted via email from jasper22's posterous