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

Facebook and You

| Thursday, October 6, 2011

Convert NUnit To MSTest Unit Test

|
Today one of my customers decide to work with MSTest Unit Test instead of NUnit, he asked me what he need to do to make it happen?

There are couple of options to accomplish that":

    Add Build Extension to Support NUnit run from MSBuild.
    Create Custom Activity to run NUnit executable
    Convert the NUnit Syntax to MSBuild

Because the customer had nothing special in NUnit and the entire company works in .NET and Team Build we decide to convert the NUnit Tests to MBuild Unit Tests Format.

Here is the steps you need to do:
Reference

You need to change “Nunit.framework.dll” with “Microsoft.VisualStudio.QualityTools.UnitTestFramework”.

And change the using from “using NUnit.Framework;” with “using Microsoft.VisualStudio.TestTools.UnitTesting;”.

Read more: Shai Raiten
QR: convert-nunit-to-mstest-unit-test.aspx

Posted via email from Jasper-net

2.1 million users’ data breached in Massachusetts

|
Since 2010 that is, following a law enacted in 2007 that requires all companies doing business in Massachusetts to inform consumers and state regulators about security breaches that might result in identity theft. Attorney General Martha Coakley’s office released the information, including a breakdown of the data.

It seems her office received 1,166 data breach notices since January 2010, including 480 between January and August of 2011. About 25 percent were as a result of a deliberate hacking attempt, followed by 23 percent for accidental unauthorized sharing of information, i.e. faxes or e-mails with personal information sent to the wrong recipient. 15 percent of cases were reports of customer credit card numbers. Data was also lost through thefts or accidental losses of laptop computers and paper documents, or in cases in which workers deliberately gained unauthorized access to client files.

The biggest single data breach in the report occurred last July, when South Shore Hospital said it lost 14 years’ worth of records on 800,000 patients, employees, volunteers, and vendors. The hospital blamed an outside data management company for losing a batch of records they had been ordered to destroy.

Coakley predicted the problem will get worse as more Americans store vital personal data on various computer networks. “There is going to be more room for employee error, for intentional hacking,’’ continuing along this vein she stated, “this is going to be an increasing target.’

Read more: ESET Threat Blog
QR: 2-1-million-users-data-breached-in-massachusetts

Posted via email from Jasper-net

Throwing Exceptions from WCF Service (FaultException)

|
Handling exceptions in WCF service is different than usual exceptions handling in .Net. If service raise exception it should propagate to clients and properly handle by client application. Since Exception object is .Net specific so it cannot propagate to clients because clients can be of different technologies, so to propagate to all kinds of clients it should be converted to generic exceptions which can be understand by clients.SoapFault is technology independent and industry accepted based exception which can be any clients. SoapFault Carries error and status information within a SOAP message.

.Net has FaultException<T> generic class which can raise SoapFault exception. Service should throw FaultException<T> instead of usual CLR Exception object. T can be any type which can be serialized.

Now I’ll cover one example to show how service can throw fault exception and same can catch on client.

First I create Service Contract IMarketDataProvider which is having operation contract GetMarketPrice which provide market data of instrument.

IMarketDataProviderService

[ServiceContract]
    public interface IMarketDataProvider
    {

        [FaultContract(typeof(ValidationException))]
        [OperationContract]
        double GetMarketPrice(string symbol);
      
    }

Here is implementation of IMarketDataProviderService interface

public class MarketDataProviderService : IMarketDataProvider
    {
       
       public double GetMarketPrice(string symbol)
        {
            //TODO: Fetch market price
            //sending hardcode value
            if (!symbol.EndsWith(".OMX"))
                throw new FaultException(new ValidationException { ValidationError = "Symbol is not valid" }, new FaultReason("Validation Failed"));

            return 34.4d;
        }
    }

Operation contract which might raise exception should have FaultContract attribute

[FaultContract(typeof(ValidationException))]


Read more: Beyond Relational
QR: throwing-exceptions-from-wcf-service-faultexception.aspx

Posted via email from Jasper-net

Integrate Validation Block with WCF

|
Introduction

Validation block is used for validation purposes and supports technology specific integration features such WPF and WCF. It offers an easy and relatively simpler way to validate data compared with the validation methods provided by most technologies. I will focus on how to integrate the validation block in Microsoft Enterprise Library 5.0 with WCF.

You can learn what the validation block is and how to use it in your projects from the following article: Microsoft Enterprise Library 5.0 - Introduction to Validation Block.

Background

WCF employs its own validation methods through the implementation of the IParameterInspector interface. You can find a good article showing how to consume the IParameterInspector interface for validation from the following address: How to: Perform Input Validation in WCF.

This method actually requires more effort and offers more complex ways than the validation block does. Through the validation block, you just focus on what to validate rather than how to validate. This makes the validation block appeal. Also, it prevents you from complexities, writing your own validations and maintaining them.
How to configure

Although it saves you from complexities, I dream of a technology without configuration, but nice news, because you just need to put the following setting into the configuration of your WCF.

<system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="validation"
             type="Microsoft.Practices.EnterpriseLibrary.
                    Validation.Integration.WCF.ValidationElement,
                  Microsoft.Practices.EnterpriseLibrary.
                    Validation.Integration.WCF,
                  Version=5.0.414.0,
                  Culture=neutral,
                  PublicKeyToken=31bf3856ad364e35" />
      </behaviorExtensions>
    </extensions>
    .......
</system.serviceModel>


Read more: Codeproject
QR: IntegrateValidationBlock.aspx

Posted via email from Jasper-net

15 Incredibly Useful (and Free) Microsoft Tools for IT Pros

|
We've dug through the jungle that is Microsoft Downloads and found 15 of the best free tools you've probably never heard of.

WSCC Windows System Control Center

My first pick isn't actually a Microsoft (MSFT) tool per se: Windows System Control Center is a one-stop downloader for almost 300 maintenance tools from Microsoft's Sysinternals and the ever-popular NirSoft suites: simply download WSCC from KLS-Soft, check all the tools you need and hit "Install". Minutes later you're equipped with some of the most useful tools out there, including Disk2Vhd, Autologon and Autoruns (also described below). WSCC saves these files under C:Program Files (x86)Sysinternals Suite, while NirSofts tools are found under C:Program Files (x86)NirSoft Utilities.


RichCopy 4.0

Everyone knows Robocopy, the command line "Pro" version of Windows Explorer's built-in file transfer tool, but now there's a great UI frontend for Robocopy -- RichCopy 4.0. This Microsoft TechNet invention spares you the headache of learning, checking and retyping command lines. Here are just a few of reasons why RichCopy is so great:

• Copy data on a regular schedule (e.g. copy files from your HD to an external disk every night)


Read more: CIO
QR: 15_Incredibly_Useful_and_Free_Microsoft_Tools_for_IT_Pros

Posted via email from Jasper-net

Продолжение истории с UEFI Secure Boot

|
Microsoft решила ответить на возникшую вокруг проблемы шумиху

blogs.msdn.com/b/b8/archive/2011/09/22/protecting-the-pre-os-environment-with-uefi.aspx

Естественно, ничего путного тут не написано, обычное MS style бла-бла-бла на тему того, как они заботятся о пользователях и единственное, что интересно, так это то, что там рассказано (по ошибке :) о ещё одном варианте загрузки, когда OS может следить за профилем своего использования.

Этот пост от Microsoft привёл к тому, что на него отреагировал Мэтью Гэррет из Red Hat, которая с августа общается с производителями оборудования на эту тему. В своём ответном посте

mjg59.dreamwidth.org/5850.html

он раскрывает кое-какие детали этого общения.

    Win-8 сертификация требует от от производителей поставлять оборудование со включенной Secure Boot.
    Win-8 сертификация не требует от производителя предусматривать возможность отключения Secure Boot.
    Win-8 сертификация не требует наличия в системе ключей, отличных от ключей MS.


И в каком-то комментарии на MSDN (не могу сейчас найти) я прочитал, что MS будет поощрять поставщиков, если они будут соблюдать требования Win-8 Secure Boot по-минимуму (то есть, ключи только от MS без возможности отключить).

Read more: Habrahabr.ru
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=habrahabr.ru/blogs/linux/129069/

Posted via email from Jasper-net

Man-in-the-Middle Attack Against SSL 3.0/TLS 1.0

|
It's the Browser Exploit Against SSL/TLS Tool, or BEAST:

    The tool is based on a blockwise-adaptive chosen-plaintext attack, a man-in-the-middle approach that injects segments of plain text sent by the target's browser into the encrypted request stream to determine the shared key. The code can be injected into the user's browser through JavaScript associated with a malicious advertisement distributed through a Web ad service or an IFRAME in a linkjacked site, ad, or other scripted elements on a webpage.

    Using the known text blocks, BEAST can then use information collected to decrypt the target's AES-encrypted requests, including encrypted cookies, and then hijack the no-longer secure connection. That decryption happens slowly, however; BEAST currently needs sessions of at least a half-hour to break cookies using keys over 1,000 characters long.

    The attack, according to Duong, is capable of intercepting sessions with PayPal and other services that still use TLS 1.0­which would be most secure sites, since follow-on versions of TLS aren't yet supported in most browsers or Web server implementations.

Read more: Schneier on Security
QR: man-in-the-midd_4.html

Posted via email from Jasper-net

Маленькие чудеса C#/.NET: забавы с методами enum

|
Еще раз позвольте окунуться в "Маленькие чудеса .NET" - эти маленькие "штучки" в языках платформы .NET и классах BCL, которые делают разработку проще за счет повышения читаемости кода, сопровождаемости или производительности.

Вероятно, каждый из нас использует перечисляемые типы время от времени в программах на C#. Перечисляемые типы, которые мы создаем - это отличный способ передать то, что значение может быть одним из набора дискретных значений (или сочетанием этих значений в случае битовых флагов).

Но возможности перечисляемых типов выходят далеко за рамки простого присваивания и сравнения, есть много методов в классе Enum (от которого "наследуются" все перечисления), которые могут дать вам еще больше возможностей при работе с ними.
IsDefined() - проверка, что данное значение присутствует в перечислении

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

Давайте предположим, что у нас есть небольшое перечисление, содержащее коды результатов, которые мы хотим возвращать из нашего слоя бизнес-логики:

public enum ResultCode
{
    Success,
    Warning,
    Error
}

В этом перечислении Success (Успешно) будет равен нулю (если другое значение не задано явно), Warning (Предупреждение) будет 1, а Error (Ошибка) будет 2.

Read more: Addicted to .NET
QR: malenkie-chudesa-csharp-net-zabavy-s-metodami-enum

Posted via email from Jasper-net

Understanding Memory

|
Our context for this discussion is the AICT Linux Cluster, which runs 64-bit GNU/Linux on AMD Opteron hardware. If you have a comment or question about the material presented, please send a note to research.support@ualberta.ca.


Contents

Introduction

Under Linux, all programs run in a virtual memory environment. If a C programmer prints the value of a pointer (never necessary in practice), the result will be a virtual memory address. In Fortran, although pointers are not a standard feature, virtual memory addressing is implicit in every variable reference and subroutine call.

Of course, a program's code and data actually reside in real physical memory. Therefore, each virtual memory address is mapped by the operating system to a physical memory address in a structure known as the page table (see Figure 1). So, for example, to retrieve or update the value of a variable, a program must first acquire the variable's real memory address by looking up the associated virtual memory address in the page table. Fortunately, this step is handled transparently by Linux. Optimized code in the Linux kernel and specialized circuitry in the CPU combine to make this a reasonably efficient operation. Nevertheless, you may wonder why do it at all.

figure1.png

Read more: Ualberta.ca
QR: mem.html

Posted via email from Jasper-net

MonoDevelop 2.8 is Here!

|
md-header1.png?w=350&h=131

We’re excited to announce that MonoDevelop 2.8 is now available for download!

Read more: Xamarin
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://blog.xamarin.com/2011/10/05/monodevelop-2-8-released/

Posted via email from Jasper-net

Re-using WCF service among several Silverlight applications

|
image_thumb_6D868CDC.png

This article is about creating WCF RIA service in class library assembly instead of in the Silverlight application. For unknown reason (at least for me) most, if not all of the Silverlight samples implement the service logic in the main Silverlight application project. But since MVVM is all about de-coupling and re-using, Those services should be implemented in class library and exposed by the application.

Press here to download demo solution. In this solution you will find a working service as shown above.
Creating the service in class library project

1 Open your application solution.
2  Add project of type 'Class Library' (Notice not to select 'Silverlight class library').
3 In the newly created project add an item of type 'WCF service'. This file extension is '.cs' and not '.svc'. Don't worry about it at the moment.

image_thumb_18C04201.png

Read more: Eran Sakal's blog
QR: creating-silverlight-wcf-ria-service-in-class-library-assembly.aspx

Posted via email from Jasper-net

Why does my single-byte write take forever?

|
A customer found that a single-byte write was taking several seconds, even though the write was to a file on the local hard drive that was fully spun-up. Here's the pseudocode:

// Create a new file - returns quickly
hFile = CreateFile(..., CREATE_NEW, ...);

// make the file 1GB
SetFilePointer(hFile, 1024*1024*1024, NULL, FILE_BEGIN);
SetEndOfFile(hFile);

// Write 1 byte into the middle of the file
SetFilePointer(hFile, 512*1024*1024, NULL, FILE_BEGIN);
BYTE b = 42;
/ this write call takes several seconds!
WriteFile(hFile, &b, &nBytesWritten, NULL);

The customer experimented with using asynchronous I/O, but it didn't help. The write still took a long time. Even using FILE_FLAG_NO_BUFFERING (and writing full sectors, naturally) didn't help.

The reason is that on NTFS, extending a file reserves disk space but does not zero out the data. Instead, NTFS keeps track of the "last byte written", technically known as the valid data length, and only zeroes out up to that point. The data past the valid data length are logically zero but are not physically zero on disk. When you write to a point past the current valid data length, all the bytes between the valid data length and the start of your write need to be zeroed out before the new valid data length can be set to the end of your write operation. (You can manipulate the valid data length directly with the Set­File­Valid­Data function, but be very careful since it comes with serious security implications.)

Read more: The Old New Thing
QR: 10215053.aspx

Posted via email from Jasper-net

Bcdedit Tips and Tricks For Debugging Part 1

|
Hello everyone, my name is Sean Walker, and I am on the Platforms OEM team in Washington.  This article is for those people who have had a hard time switching from the old boot.ini configuration to the new BCD store (myself included). Doing the simple tasks such as enabling kernel debugging over com1 are easy to do with bcdedit.exe or the msconfig GUI, you just enable them and reboot the computer. However, if you need to do something more advanced such as break into the early boot process during resume from hibernation, things get a more complicated.

 

This article has some samples for enabling and disabling debug settings that you may not be familiar with, and a list of bcdedit debug settings for Windows Vista/Server 2008 and Windows 7/Server 2008 R2.  This information has been helpful to me for quickly and accurately getting to the debug at hand rather than fumbling around with bcdedit.  Much of the following information has been taken from various sources, including the windbg help files, the OEM team blog, the MSDN bcdedit reference, and the WHDC debugger site.

 

NOTE: For the examples below, you will need to run bcdedit.exe from an administrator (UAC-elevated) command prompt.  To output a summary view of the current state of the BCD store, just run "bcdedit.exe" from the command prompt.  To get detailed information about all of the store(s) that Windows knows about, use the following command:

bcdedit /enum all

 

What is a BCD store?

A BCD store is a binary file that contains boot configuration data for Windows, basically it is a small registry file.  Boot applications use the system BCD store, located on the system partition, during the boot process.  You can also create additional BCD stores in separate files but only one store at a time can be designated as the system store.

 

NOTE: The "/store" switch can be used to specify a particular BCD store for bcdedit commands (instead of the default store).  To enumerate all the settings in another BCD store, in this case e:\bcd_store\BCD, use the following command:

bcdedit /store e:\bcd_store\BCD /enum all

This will show you which options are currently set, and what their values are.  When /store switch is omitted, the system store is used.

 
Using bootdebug

To enable debugging for early boot problems, you may need to enable the bootdebug switch.  This is easy to do with bcdedit:

bcdedit /set bootdebug on

 
However, this only sets bootdebug for the current "boot application", which is generally winload.exe, so it does not break into the very early boot process.  There are multiple applications used for booting, hibernating, and resuming (bootmgr.exe, winload.exe and winresume.exe are examples of these).  Each application (called BCD Objects) has its own settings (called BCD Elements) in the BCD store and each can be modified globally and/or individually.

So, to deal with different (or multiple) debug scenarios, you just enable boot debugging based on the boot application you are concerned with.  For early debugging, you can enable bootdebug for bootmgr:

bcdedit /set {bootmgr} bootdebug on

 
To set bootdebug for winload.exe (which will most often be your current, and default, boot object) all three of the following will give you the same result:

bcdedit /set bootdebug on
bcdedit /set {current} bootdebug on
bcdedit /set {default} bootdebug on


Read more: Ntdebugging Blog
QR: bcdedit-tips-and-tricks-for-debugging-part-1.aspx

Posted via email from Jasper-net

Common Language Runtime (CLR) Integration Programming in .NET

|
CLR Stored Procedures

Stored procedures cannot be used in scalar expressions, unlike scalar expressions they are able to return tabular format data, can invoke data definition language (DDL) and data manipulation language (DML) statements and return Output parameters. In CLR, stored procedures are created as public static method in .NET framework assembly. This static method can be of void or integer type, if it returns an integer value, it is treated as return code of procedure as –
EXECUTE @return_status = your_procedure

The @return_status variable will contain the value returned by the method. If the method is declared void, the return code will be 0. The following code snippet shows a stored procedure returning information through an OUTPUT parameter:

using System;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public class StoredProcedures

{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void RateSum(out SqlInt32 value)
{
using(SqlConnection con = new SqlConnection(“context connection=true”))
{
value = 0;
con.Open();
SqlCommand cmd = new SqlCommand(“SELECT Rate FROM Products”, con);
SqlDataReader reader = cmd.ExecuteReader();

using (reader)
{

while( reader.Read() )
{
value += reader.GetSqlInt32(0);
}
}
}
}
}

Read more: Crispy coding
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://crispycoding.com/common-language-runtime-clr-integration-programming-in-dotnet/

Posted via email from Jasper-net

Development Tip – Dispatching calls to the UI thread

| Wednesday, October 5, 2011
In Silverlight and WPF, if you wanted to update the UI from a thread you had launched, it was important that the UI update be executed on the UI thread, lest you get an invalid-cross-thread-access error.

You could ensure this by initially getting a pointer to the dispatcher for the UI thread, and then asking it to run your code. Something like this:

_OriginalDispatcher = Application.Current.RootVisual.Dispatcher;

_OriginalDispatcher.BeginInvoke(myAction);


Read more: Yet Another Coding Blog
QR: windows-8-development-tip-dispatching-calls-to-the-ui-thread.aspx

Posted via email from Jasper-net

Extension Methods in .NET

|
Introduction

In this article, we will take a look at what extension methods are and how to use them in .NET. Personally, they are one of the best things that have been introduced into the .NET Framework in terms of readability. I will take you through what extension methods are, how to create them (in C# and VB), then I will show you some of the extension methods that I have created (in C# only, conversion is for you to try).
Contents

    What are extension methods?
    How do we create extension methods?
    Examples of extension methods
    Related Links

What are Extension Methods?

Extension methods allow you to easily extend a type, such as an integer or string, without re-compiling or modifying the type. In essence, they are a type of static (shared in VB) method, but they are called as if the method is native to the type. Extension methods are available from the 3.5 version of the .NET Framework and can be implemented on any type in the .NET Framework or any custom type that you define.

One downside to extension methods is if that you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.
Warning
If you declare an extension method on the type Object, you will effectively create the extension method for every type in the framework including but not limited to String, Integer and Lists.
How Do We Create Extension Methods?

The basic outline of creating an extension methods goes something like this:

    Create a public static class (module in VB)
    Define functions that you wish to perform
    Make the functions an extension method

Following through a complete example, I will now demonstrate how to create an extension method that returns the first 3 characters of a string. Using the list above, I must first create a static class or module:

// C#
public static class Extensions
{

}


Read more: Codeproject
QR: ExtensionMethodsInDotnet.aspx

Posted via email from Jasper-net

Internals of .NET Objects and Use of SOS

|
Well, now getting deeper into the facts, lets talk about how objects are created in .NET and how type system is laid out in memory for this post in my Internals Series.  As this is going to be very deep dive post, I would recommend to read this only if you want to kill your time to know the internal details of .NET runtime and also you have considerable working experience with the CLR types and type system.


Recently I have been talking with somebody regarding the actual difference between the C++ type system and managed C# type system. I fact the CLR Type system is different from the former as any object (not a value type) is in memory contains a baggage of information when laid out in memory. This makes CLR objects considerable different from traditional C++ programs.

Classification of Types

In .NET there are mainly two kind of Types.

    Value Types (derived from System.ValueType)
    Reference  Type (derived directly from System.Object)

Even though ValueTypes are internally inherited from System.Object in its core, but CLR treats them very differently.  Indeed from your own perception the Value Types are actually allocated in stacks (occationally) while reference types are allocated in Heaps. This is to reduce the additional contension of GC heaps for Heap allocation, GC cycles, occasional call to OS for additional memory needs etc. The object that is allocated in managed Heap is called Managed Object and the pointer that is allocated in stack to refer to the actual object in heap is called Object Reference (which is sometimes called as Managed Pointer).


Additional to this basic difference a Value Type is treated completely different from CLR point of view. CLR treats any object that is derived from System.ValueType differently in respect of any other object derived from System.Object directly. The memory of a ValueType contains just the value of its fields and the size of the Value Type is just the addition to its content, while for reference types the size is completely different. Let us consider looking at the memory layout of both the types.

stack.PNG

In case of Value Types, the Managed Pointer holds reference to the initial location of the actual Memory.Thus in this case, the Managed pointer holds reference to 0x0000 which is the address location of Field 1. Hence CLR needs to do pointer arithmetic to find Fields ... N.  Thus we can easily use Sizeof operator on ValueTypes to get the actual size of the object.


Read more: DOT NET TRICKS
QR: internals-of-net-objects-and-use-of-sos.html

Posted via email from Jasper-net

Android’s HTTP Clients

|
Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.
Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.

But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.
HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.

Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:

private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

Accept-Encoding: gzip

Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.


Read more: Android developer
QR: androids-http-clients.html

Posted via email from Jasper-net

Атрибуты в NUnit для реализации Data Driven Tests

|
Начиная с версии NUnit 2.5 содержит ряд замечательных атрибутов, которые смогут упростить жизнь при написании юнит(и не только) тестов, используя методологию Data Driven Tests.

и другие, подробное описание которых вы можете почитать в официальной документации.

Resharper начиная с 6.x поддерживает данные атрибуты.

Для наглядности приведу конно-вакуумный пример с TestСase:

        [TestCase(4, 2, 2, TestName = "TC-10010", Description = "Right division result assertion test")]
        [TestCase(6, 2, 2, TestName = "TC-10020", Description = "Wrong division result test")]
        [TestCase(3, 0, 0, ExpectedException = typeof(DivideByZeroException), TestName = "TC-10030", Description = "Testing division by zero")]
        public void TestWithParamsAndNames(int arg1, int arg2, int arg3)
        {
          Assert.AreEqual(arg1 / arg2, arg3);
        }


Read more: Habrahabr.ru
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://habrahabr.ru/blogs/net/129480/

Posted via email from Jasper-net

Visual Studio 2010 Tools for Office Runtime

|
Overview

This download installs the Visual Studio 2010 Tools for Office Runtime, which is required to run Microsoft Office based solutions built using Microsoft Visual Studio 2010.

Read more: MS Download
QR: details.aspx?id=20479

Posted via email from Jasper-net

That Tricky StackTrace

|
This post is a copy of my second quiz on GeekQuiz.Net called Walking Up the StackTrace.

This question is very simple: what does this application print and why? The answer may not be as simple as you think.

using System;

namespace StackTrace
{
    class Program
    {
        static void Main()
        {
            Method1();
            Console.ReadLine();
        }

        static void Method1()
        {
            var stackTrace = new System.Diagnostics.StackTrace(1);
            var stackFrame = stackTrace.GetFrame(0);
            Console.WriteLine(stackFrame.GetMethod().Name);

            Method2();
        }

        static void Method2()
        {
...
...

static void Method3()
        {
            var stackTrace = new System.Diagnostics.StackTrace(1);
            var stackFrame = stackTrace.GetFrame(0);
            Console.WriteLine(stackFrame.GetMethod().Name);
        }
    }
}

Feel free to run it!!

At the first look and even when you run it the answer seems to be:

Main

Method1

Method2

which is right but not always! In fact, in production (i.e. in release mode) that answer is always wrong!! Let me explain:

Obviously StackTrace is populated at RunTime and not at compile time. When you are debugging this application or even when you are running it when it is built with 'debugging' configuration the StackTrace is what you would hope it to be, which is what I wrote above. However if you run the very same application in release mode, the situation is different.

At RunTime, when it comes the time for JIT compiler to compile this module, it has a look at the methods and thinks to itself: "Hey, you know what. These calls are very simple and I could inline these methods and save myself, CPU and memory from a lot trouble. This way we will not have to deal with pushing addresses into stack and popping them up later. So I am just going to inline this. This not only performs better but is also really cool. So yeah, let's do it". OK, maybe JIT does not think like this; but the result is the same! :)

So what is going to happen at RunTime in release mode (and depending on your machine's CPU architecture) is that JIT is going to inline these methods and the application output all of a sudden becomes:

Main

Main

Main


Read more: Mehdi Khalilis blog
QR: that-tricky-stacktrace

Posted via email from Jasper-net

Waiting for Parallel Tasks to Complete

|
Synchronisation

When you are developing software that uses the Task class to include parallel operations, you will often have situations where a task must be completed before the main thread can continue processing. This may be because the parallel task generates results that are needed later in the process and you must wait for the results to be available before you attempt to use them. The parallel tasks must therefore be synchronised for the correct operation of the software.

The Task Parallel Library (TPL) includes several methods that allow you to wait for one or more parallel tasks to complete before continuing processing. In this article we will examine three such methods. They are all members of the Task class, which resides in the System.Threading.Tasks namespace. We will also be using the Thread class from the System.Threading namespace in order to simulate long-running tasks. To follow the samples, create a new console application project and add the following using directives to the initial class.

using System.Threading;
using System.Threading.Tasks;

Task.Wait Method

Often you will wish to wait for a single task to complete, either successfully or with an exception, before continuing. This can be achieved with the Task class' Wait method. In the most basic situation this blocks the thread from which it is called until the task being waited for stops. Once the task completes or throws an exception, the primary thread restarts.

As discussed earlier in the tutorial, the scheduling of tasks by the TPL is quite sophisticated. This is the case with the Wait method. Although it can be assumed that the main thread is blocked whilst a parallel task finishes its work, this is not always the case. If there is enough processor capability available and the task being waited for has not yet started, the task may be transferred to the main thread for processing. This can be more efficient, as a thread does not need to be blocked, and can mean that the task is started sooner than expected.

To demonstrate the use of the Wait method, first consider the following sample code. Here we start a task that simulates retrieving some numeric data from an external data source. The task shows a message, pauses for five seconds and then returns an array of ten integers. The main thread uses the results of the task by summing them and outputting the result.

When you run the program you will see that it throws an ArgumentNullException. This is caused by trying to use the array before it has been populated by the parallel task.

int[] values = null;

Task loadDataTask = new Task(() =>
{
    Console.WriteLine("Loading data...");
    Thread.Sleep(5000);
    values = Enumerable.Range(1,10).ToArray();
});
loadDataTask.Start();

Console.WriteLine("Data total = {0}", values.Sum());    // ArgumentNullException


Read more: BlackWasp
QR: TaskWait.aspx

Posted via email from Jasper-net

Keep it secret, keep it safe

|
A lot of people really love the idea of cryptography. To computer geeks like us there is nothing cooler than the idea that computing relatively simple arithmetic on a message can enable you to communicate secretly with anyone in the world, even if there are eavesdroppers. Unfortunately, this means that there are a lot of computer people out there who are enamoured with the idea of creating their own cryptosystems, or their own implementations of the cryptosystems invented by others. It also means there are a lot of software product managers who are convinced that security equals cryptography, and that their products will magically become "secure" if only there is more crypto in them. I've gotten a fair number of questions over the years about how to add crypto to applications -- a subject that I am actually not an expert on -- and most of the time the answer is "don't". Many times the question comes from a developer who, though an expert developer of applications in their line of business doesn't "get" the basic idea of cryptography. As a public service, let me lay it out for you. The fundamental idea of modern cryptography is this:

The strength of the security of a large quantity of data -- known as the "plaintext" -- against discovery or modification by a motivated attacker depends upon the security of a small quantity of data -- known as the "key". (*)

That is, modern crypto is essentially a form of mechanical advantage. With a gearing system or a lever you can turn a small motion into a large motion. With a strong cryptosystem you can turn the security of a 1 KB key file into the security of a 10 MB data file. Cryptosystems do not manufacture new security, any more than a lever manufactures new motion. Cryptosystems turn the security of one thing (the key) into the security of another much larger thing (the plaintext).

It is the failure to understand that fundamental idea that underlies most of the questions I get from non-crypto experts about implementing crypto in their applications. Non-crypto experts get enamoured with the math of the cryptosystem but that is not the part that provides the security. The part that provides the security is the security of the key. The cryptosystem itself (or its implementation) might be weak or strong, but even the strongest modern cryptosystem depends fundamentally on the correct management of the keys for its security.

Read more: Fabulous Adventures In Coding
QR: keep-it-secret-keep-it-safe.aspx

Posted via email from Jasper-net

Building Metro Style Apps with C++ and JavaScript

|
Hi, I’m Raman Sharma, a Program Manager with the Visual C++ team.

As seen a few weeks ago at //BUILD, in the next version of Visual Studio you’ll be able to create Metro style app with Javascript. But this doesn't mean that Javascript is the only language you can use. There are several reasons to leverage compiled code as well.

In this video I recently posted in Channel 9, you’ll learn how your Metro style app with HTML5 can directly access native code.

Read more: Visual C++ Team Blog
QR: 10216117.aspx

Posted via email from Jasper-net

Cross-Site Request Forgery explained

|
A Cross-site Request Forgery, aka CSRF or one-click attack, is a diffused security issue issue where unathorized commands are sent from the user's browser to a web site or a web application. CSRF is different from Cross-Site Scripting in the sense that it does not need to inject code into trusted pages, but can work from untrusted ones thanks to the open architecture of the web.


A quick example

I was browsing the bug tracker of a popular web service to propose an improvement, where I saw that the only Critical ticket was related to CSRF vulnerabilities.

The website uses links for the deletion of the current user's data, such as /delete_my_items. When a user follows the link present on his account page, his session cookie establish his identity and his data is deleted.

To perform an attack, we only have to make the user load this URL. A simple link would probably not work, but we can easily reach the same goal with an image:

<img src="http://application.com/delete_my_items" />

We just have to provide a link to a page containing this image for the user, or send it to him in an HTML email.

How it works

Unlike for XMLHttpRequest, images and other resources can be loaded from whatever hostname, and even if the image tag is hosted on a different website it won't matter.

Since the request is performed by the user's browser, it will transmit the session cookie as it would for any application.com page.

The point of all CSRF attacks is tricking the browser into sending an unwanted HTTP request, so that there is no need to steal the identity of the user. That's probably why our banks log us out after 2 minutes of inactivity, or require one-time tokens to authorize money transfers.


Read more: Web Builder Zone
QR: cross-site-request-forgery

Posted via email from Jasper-net

How to create a memory mapped file with C# (Windows Vista / Windows 7)

|
Hi all,

 

The following C# sample shows how to create a memory mapped file and use private namespaces to allow access to specific groups of users:

 

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.Runtime.InteropServices;
 using System.Security.Principal;
 using System.IO;
 
 namespace Alejacma
 {

 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }
 
 private void button1_Click(object sender, EventArgs e)
 {
 bool bResult = false;
 IntPtr hBoundary = IntPtr.Zero;
 IntPtr pSid = IntPtr.Zero;
 int cbSid = Win32.SECURITY_MAX_SID_SIZE;
 IntPtr hNamespace = IntPtr.Zero;
 Win32.SECURITY_ATTRIBUTES securityAttributes = new Win32.SECURITY_ATTRIBUTES();
 IntPtr hFile = IntPtr.Zero;
...
...

// Create file mapping, and give access to all users with access to the namespace
 hFile = Win32.CreateFileMapping(
 Win32.INVALID_HANDLE_VALUE,
 ref securityAttributes,
 Win32.PAGE_READWRITE,
 0,
 20971520,
 "Alejacma\\TestFileMapping"
 );

 if (hFile == IntPtr.Zero) { throw new Exception("CreateFileMapping", new Win32Exception(Marshal.GetLastWin32Error())); }
 
 // Map file and write something to it
 pView = Win32.MapViewOfFile(
 hFile,
 Win32.FILE_MAP_WRITE,
 0,
 0,
 11
 );

 if (pView == IntPtr.Zero) { throw new Exception("MapViewOfFile", new Win32Exception(Marshal.GetLastWin32Error())); }
 
 pData = Marshal.StringToHGlobalAnsi("Hello World");
 Win32.MemCopy(pView, pData, 11);


Read more: Decrypt my World
QR: how-to-create-a-memory-mapped-file-with-c-windows-vista-windows-7.aspx

Posted via email from Jasper-net

How CPU cycles are used when encoding

|
Once in a while on our forum, somebody asks why the CPU usage isn't at 100% when encoding. I recently took the time to provide a thorough answer, which I think would be beneficial posted here.

So first, let's explore what's happening when encoding a media file using Expression Encoder. The encoding process involves 5 phases:

    Reading the source(s) from storage.
    Demuxing and decoding the source(s) into uncompressed frames.
    Pre-processing the frames (deinterlacing, resizing, cropping, etc).
    Encoding and muxing the frames.
    Writing the stream to storage.

If any one of those operations is slower than the others, all the encoding pipeline will suffer in terms of performance because it will bottleneck the flow of frames into it.

#1 and #5 are usually the bottleneck when source files are either not local (aka slow Network share) or are very high-bandwidth coupled with a slow storage. Possible solutions: making sure the source files are copied locally on your fastest storage available and outputting to a different local storage are good solutions to reduce the bottleneck in those two areas.

#2 usually becomes a bottleneck because of the type of sources and the codecs used to decode them. Obviously, using complex HD sources will use significantly more resources than simple lower-resolution sources. Some 3rd party codecs are extremely slow, running only on one core. Trying to test other codecs available on the PC by disabling some of the codecs listed in the "Tools -> Options -> Compatibility" dialog may help reducing the bottleneck. It's also worth noting that because many codecs are single-thread, having faster cores can help enormeously here. This is the main reason why a 3.4MHz 4-core is faster than a 2.6MHz 8-core PC in many cases.

Read more: Expression Encoder
QR: 10219213.aspx

Posted via email from Jasper-net

Internals of Constants and Readonly

|
Introduction

In this article i shall be discussing about constants and read only fields which we all use in our .NET variant language codes viz C#, VB .NET, VC++, etc.

Background

Constants are not changeable values in the entire code base once it is defined.
Description

Lets dig a bit deeper into the const keyword which we use in our C# code. Basically, constants are by default/implicitly static for the scope in which it is defined. Also note that there wont be any memory created for the constants by the run time. So what happens under the hood, lets see via IL and a C# code.

public static void Main(string[] args)
        {
            const int TCPPortNumber = 25;
        }

As you can see from the above image, i have used a constant inside the main method. Now lets look at the IL (using ILSPY/ILDASM) to see if there is any memory created for the variable or not:

nWqKW.png

Read more: Codeproject
QR: Constants_Readonly.aspx

Posted via email from Jasper-net

Close window from ViewModel

|
Although this is somewhat corny, I will dedicate for it a post. Scenario: you want to close a window from the ViewModel, without exposing the Window to it. This can be done in a simple and clean way.
(Some code removed for brevity)

HTH,
Shimmy

XAML:

<Window
  x:Name="this"
  xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity
  xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
  <i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding}" EventName="Closed">
      <ei:CallMethodAction
        TargetObject="{Binding ElementName=this}"
        MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
<Window>

Code (from the ViewModel - DelegateCommand refers to the one of Prism's library, but it's the same idea of RelayCommand etc.):

private ICommand _SaveAndCloseCommand;
public ICommand SaveAndCloseCommand
{
  get
  {
    return _SaveAndCloseCommand ??
      (_SaveAndCloseCommand = new DelegateCommand(SaveAndClose));
  }
}

Read more: Shimmy on .NET
QR: close-window-from-viewmodel.aspx

Posted via email from Jasper-net

Microsoft SQL Server Connector for Apache Hadoop RTW

|
Microsoft SQL Server Connector for Apache Hadoop (SQL Server-Hadoop Connector) RTM is a Sqoop-based connector that facilitates efficient data transfer between SQL Server 2008 R2 and Hadoop. Sqoop supports several databases.

Version: 1.0
Date Published: 10/4/2011

Language: English

    Microsoft SQL Server-Hadoop Connector User Guide.pdf, 878 KB
    SQL Server Connector for Apache Hadoop MSLT.pdf, 220 KB
    sqoop-sqlserver-1.0.tar.gz, 1.0 MB
    THIRDPARTYNOTICES FOR HADOOP-BASED CONNECTORS.txt, 33 KB

The Microsoft SQL Server Connector for Apache Hadoop extends JDBC-based Sqoop connectivity to facilitate data transfer between SQL Server and Hadoop, and also supports the JDBC features as mentioned in SQOOP User Guide on the Cloudera website. In addition to this, this connector provides support for nchar and nvarchar data types

With SQL Server-Hadoop Connector, you import data from:

    tables in SQL Server to delimited text files on HDFS
    tables in SQL Server to SequenceFiles files on HDFS
    tables in SQL Server to tables in Hive*
    result of queries executed on SQL Server to delimited text files on HDFS
    result of queries executed on SQL Server to SequenceFiles files on HDFS
    result of queries executed on SQL Server to tables in Hive*


Read more: Greg's Cool [Insert Clever Name] of the Day
Read more: Microsoft SQL Server Connector for Apache Hadoop
QR: details.aspx?id=27584

Posted via email from Jasper-net

"Express file" - server of information exchange.

|
ex-2.gif

You can use anonymously the server saving the files. In this case the access to the objects will be possible only with a key which you will receive after creating the object.
Objects which are not used for longer than 30 days can be deleted by the system.


Read more: ex.ua
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://www.ex.ua/

Posted via email from Jasper-net

If I have .Net 4 installed do I need the previous versions? [Yes]

|
"Question:

I recently installed the .NET Framework 4 on my system. Afterwards, I looked in Add/Remove Programs, and it shows that I have all of the following versions of the .NET Framework installed on my system:

    Microsoft .NET Framework 1.1
    Microsoft .NET Framework 2.0 SP2
    Microsoft .NET Framework 3.0 SP2
    Microsoft .NET Framework 3.5 SP1
    Microsoft .NET Framework 4 Client Profile
    Microsoft .NET Framework 4 Extended

Do I need any of these older versions of the .NET Framework now that I’ve installed the .NET Framework 4, or can I safely uninstall them?

Answer:

In general, my recommendation is to leave the .NET Framework 2.0 SP2, 3.0 SP2, 3.5 SP1 and 4 installed on your computer.

Read more: Greg's Cool [Insert Clever Name] of the Day
QR: if-i-have-net-4-installed-do-i-need.html

Posted via email from Jasper-net

Porting existing .NET code to Metro style apps [Wes]

| Tuesday, October 4, 2011
As many of you know at //build we announced that there will be a new .NET target framework for Metro style apps. To learn more about the goals of this new target framework I encourage you to watch Krzystzof Cwalina’s build talk "A .NET developer's view of Windows 8 app development".

One of the things we know people want to do is reuse existing .NET code but due to the constraints on Metro style apps it is not possible to directly reuse existing .NET class libraries nor is it always possible to simply recompile existing code. We realize this is going to be a pain point for many current .NET developers so we are working on a guide at the .NET for Metro style apps overview page which will assist developers in translating their existing .NET skill set into the Metro style apps world. Sometimes that means explaining why something was removed and other times it means giving another .NET or WinRT API to call instead. Today the page is limited but we are actively working on it internally to update it with more data for Beta and RTM.

Read more: BCL Team Blog
QR: porting-existing-net-code-to-metro-style-apps.aspx

Posted via email from Jasper-net

Large Object Heap Improvements in .NET 4.5

|
    Garbage collection is one of premiere features of the .NET managed coding platform. As the platform has become more capable, we’re seeing developers allocate more and more large objects. Since large objects are managed differently than small objects, we’ve heard a lot of feedback requesting improvement. Today’s post is by Surupa Biswas and Maoni Stephens from the garbage collection feature team. -- Brandon

The CLR manages two different heaps for allocation, the small object heap (SOH) and the large object heap (LOH). Any allocation greater than or equal to 85,000 bytes goes on the LOH. Copying large objects has a performance penalty, so the LOH is not compacted unlike the SOH. Another defining characteristic is that the LOH is only collected during a generation 2 collection. Together, these have the built-in assumption that large object allocations are infrequent.

Because the LOH is not compacted, memory management is more like a traditional allocator. The CLR keeps a free list of available blocks of memory. When allocating a large object, the runtime first looks at the free list to see if it will satisfy the allocation request. When the GC discovers adjacent objects that died, it combines the space they used into one free block which can be used for allocation. Because a lot of interaction with the free list takes place at the time of allocation, there are tradeoffs between speed and optimal placement of memory blocks.

Read more: .NET Blog
QR: large-object-heap-improvements-in-net-4-5.aspx

Posted via email from Jasper-net

Choices I hate to make: Constructor exceptions vs. Initialize patterns

|
I'm writing a little sample for Silverlight 5 in Action. Part of it involves a class which integrates with a 3d accelerometer sensor on Windows. In order to use the accelerometer, I have to check to see if elevated permissions is enabled before I go about constructing objects which rely on COM automation. There's also a fair bit of construction activity after that check to create the actual sensor object and prepare the class for use.

There are three approaches to creating this object and performing the initialization. All three have issues. Here they are.
Code in the Constructor

It "feels" right to handle the permissions check in the constructor. However, throwing exceptions from a constructor is generally considered a bad… no, an EVIL practice. The code in this example is the smallest, and tends to be the most easily understood by other developers. Here's an example of what the code might look like (don't get hung up on the specifics of the code itself, as it happens to use the Native Extensions for Silverlight, but could be any similar functionality) :

public class AccelerometerJoystick
{

    private SensorManager _sensorManager = null;

    private Sensor _accelerometer = null;

    private PropertyKey _keyXGs = null;

    private PropertyKey _keyYGs = null;

    public AccelerometerJoystick()
    {
        if (Application.Current.HasElevatedPermissions)


Read more: 10REM.net
QR: choices-i-hate-to-make-constructor-exceptions-vs-initialize-patterns

Posted via email from Jasper-net

Expression Blend 4 does not start after installing the NET Framework 4.5 Developer Preview

|
Over the last couple of days I have been trying out different combinations for app development on the Metro/WinRT platform and one of these involved installing VS 2011 Ultimate on to my main box that runs Win 7. Unfortunately Blend and the VS 11 Ultimate Developer Preview bits don’t play together out of the box. This is a known issue, and following the steps below will fix the issue.

You can Copy and Paste the commands below.

Open a command prompt window with administrative privileges and then run the following commands:

%windir%\Microsoft.NET\Framework\v4.0.30319\ngen uninstall “%ProgramFiles(x86)%\Microsoft Expression\Blend 4\Microsoft.Expression.Framework.dll”

%windir%\Microsoft.NET\Framework\v4.0.30319\ngen uninstall “%ProgramFiles(x86)%\Microsoft Expression\Blend 4\Microsoft.Expression.Blend.dll”


Read more: XAML Ninja
QR: expression-blend-4-does-not-start-after-installing-the-net-framework-4-5-developer-preview

Posted via email from Jasper-net

What is a dispatcher Object?

| Monday, October 3, 2011
    Every UIElement in WPF is derived from DispatcherObject which defines a property called Dispatcher that points to the UI thread.
    A dispatcher is used to raise calls on another thread.
    Dispatcher can also be called as a  class that handles thread affinity.

Thread Affinity

As mentioned  above Dispatcher thread holds all UI elements. This is called thread affinity. All Most all of the WPF elements have thread affinity. If we have a background thread working, and if at all we need to update the UI thread, then a dispatcher is definitely required for this. Thus from any other thread, if at all we want to access UI component, we need to do it using Dispatcher thread.

DispatcherObject class contains two methods .

1. CheckAccess() : This method provides access to current dispatcher that an object is tied to . This returns a Boolean value as true if the current thread has access to use the object and returns false if the current thread can not use the object.

2. VerifyAccess() : The purpose of this method is to Verify  if the thread has access to the object. If the thread does not have access to the object, an exception is thrown.

If we make a call to a DispatcherObject from a non-UI thread, it will throw an exception. So if we are working on a non-UI thread, we need to update DispatcherObjects by using dispatcher.

The below picture represents object hierarchy in WPF.  It gets inherited from Object class.

WPFobjectheirarchy_5F00_thumb_5F00_112BC62A.png

Read more: Beyond Relational
QR: what-is-a-dispatcher-object.aspx

Posted via email from Jasper-net

Public Key Infrastructure at Microsoft

|
Overview

Microsoft IT installed a public key infrastructure to implement a security-enhanced communications and remote authentication infrastructure. This enabled the use of S/MIME signatures and encryption, helped secure Web connections by using Secure Sockets Layer or Transport Layer Security, helped ensure the confidentiality of stored data by using Encrypting File System, helped ensure the confidentiality and integrity of transmitted data by using IPsec, and enabled strong network user authentication by using smart cards.

Read more: MS Download
QR: details.aspx?id=27581

Posted via email from Jasper-net

Using WCF Service with Silverlight

|
Introduction

In one of our products, we had to use WCF service with Silverlight. While working on Silverlight and WCF, I found out some very interesting things and I feel that those are worth sharing. Whenever we want to work with Silverlight and need some kind of service communication, we would encounter those common problems. In this article, we are going to discuss a few interesting findings about WCF and Silverlight Bridge.

For the purpose of demonstration, we are going to use a demo application with some simple class. Let's say we have an expense management application and we have a client build with Silverlight. And the client communicated to server via WCF. Let's take this example to fit our explanation process.
Using WCF with Silverlight

In this section, we will see how we can use WCF service with Silverlight. I am sure every reader has a nice grip on what is WCF and how we can use it in web applications. Some of the stuff is repeated and discussed again and may sound familiar. But as we need some parts as a subset, I am discussing it again. First, we would look at the basics and then we would see some other relevant tricks and information.
The WCF Basics

WCF has three basic building blocks. Those are called A,B,C of WCF. A stands for Address, B stands for Binding and C stands for contract. In a later section, we would see the most common knowledge that is necessary to work with WCF, of course communication with Silverlight context. WCF can be hosted in several ways. Most common ones are given below:

    Hosting in Internet Information Services
    Hosting in Windows Process Activation Service
    Hosting in a Windows Service Application
    Hosting in a Managed Application

We are not going to discuss about the above hosting options in this article as those need further study, and assumes to not be the focused area of the article. I would recommend that you spend some time on MSDN or Google to learn more about WCF hosting process.

Read more: Codeproject
QR: WCFServiceWithSilverlight.aspx

Posted via email from Jasper-net

There's also a large object heap for unmanaged code, but it's inside the regular heap

|
Occasionally, a customer will ask for assistance explaining some strange heap behavior, or at least heap behavior that appears to be strange if you assume that the heap behaves purely classically.

    I need to understand the heap behavior we're seeing. I have a sample program which allocates five blocks of memory from the process heap, each of size 100 bytes. When we dump the heap blocks with the !heap -x command, we find that all of them belong to the same heap segment, and when we do a !vadump -v, we find that they all live on the same page. On the other hand, if we allocate five blocks of size 512KB, then we find that each one gets placed in its own virtually-allocated range, and the range is not size 512KB but rather 516KB.

    Questions:

        Why does the system combine the 100-byte allocations? Why is there no extra overhead for the small allocations, but the large allocations have a 4KB overhead?
        Why does the system allocate a separate virtual address range for the 512KB block? Which component makes this decision and what are the factors involved?
        Why does allocating a 512KB block require 4KB of overhead?
        Is there any documentation for this behavior?

Let's look at the last question first. There is no documentation for this behavior because it is all implementation detail. All the heap is required to do is return you a block of memory of the size you requested. How it goes about getting this memory block is at the discretion of the heap manager, and as we've seen in the past, the precise algorithm has varied over time.

Read more: The Old New Thing
QR: 10218384.aspx

Posted via email from Jasper-net