Convert NUnit To MSTest Unit Test
Posted by
jasper22
at
12:07
|
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 MSBuildBecause 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:
ReferenceYou 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:
Create Custom Activity to run NUnit executable
Convert the NUnit Syntax to MSBuildBecause 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:
ReferenceYou 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:
2.1 million users’ data breached in Massachusetts
Posted by
jasper22
at
12:06
|
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:
QR:
Throwing Exceptions from WCF Service (FaultException)
Posted by
jasper22
at
12:03
|
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 interfacepublic 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:
public interface IMarketDataProvider
{ [FaultContract(typeof(ValidationException))]
[OperationContract]
double GetMarketPrice(string symbol);
}Here is implementation of IMarketDataProviderService interfacepublic 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:
Integrate Validation Block with WCF
Posted by
jasper22
at
12:02
|
IntroductionValidation 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.BackgroundWCF 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 configureAlthough 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:
How to configureAlthough 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:
15 Incredibly Useful (and Free) Microsoft Tools for IT Pros
Posted by
jasper22
at
12:01
|
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 CenterMy 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.0Everyone 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:
RichCopy 4.0Everyone 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:
Продолжение истории с UEFI Secure Boot
Posted by
jasper22
at
11:59
|
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:
Win-8 сертификация не требует от производителя предусматривать возможность отключения Secure Boot.
Win-8 сертификация не требует наличия в системе ключей, отличных от ключей MS.
И в каком-то комментарии на MSDN (не могу сейчас найти) я прочитал, что MS будет поощрять поставщиков, если они будут соблюдать требования Win-8 Secure Boot по-минимуму (то есть, ключи только от MS без возможности отключить). Read more: Habrahabr.ru
QR:
Man-in-the-Middle Attack Against SSL 3.0/TLS 1.0
Posted by
jasper22
at
11:54
|
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.0which 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:
QR:
Маленькие чудеса C#/.NET: забавы с методами enum
Posted by
jasper22
at
11:53
|
Еще раз позвольте окунуться в "Маленькие чудеса .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:
IsDefined() - проверка, что данное значение присутствует в перечисленииВы считываете значение для перечисления из источника данных, но не уверены, что это действительно допустимое значение? Приведение не скажет вам этого, и Parse() не гарантирует разбора, если вы передаете ему int или комбинацию флагов. Итак, что мы можем сделать? Давайте предположим, что у нас есть небольшое перечисление, содержащее коды результатов, которые мы хотим возвращать из нашего слоя бизнес-логики:public enum ResultCode
{
Success,
Warning,
Error
}В этом перечислении Success (Успешно) будет равен нулю (если другое значение не задано явно), Warning (Предупреждение) будет 1, а Error (Ошибка) будет 2.Read more: Addicted to .NET
QR:
Understanding Memory
Posted by
jasper22
at
11:51
|
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

Read more: Ualberta.ca
QR:
Contents
- Introduction
- Programs and Processes
- Storage Class and Scope
- Program Size
- Memory Map
- Call Stack
- Page Table
- Libraries
- Memory Limits
- Memory Allocation
- Implementation Details
- References

Read more: Ualberta.ca
QR:
MonoDevelop 2.8 is Here!
Posted by
jasper22
at
11:50
|
Re-using WCF service among several Silverlight applications
Posted by
jasper22
at
11:48
|
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 project1 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.
QR:
Why does my single-byte write take forever?
Posted by
jasper22
at
11:01
|
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 SetFileValidData function, but be very careful since it comes with serious security implications.) Read more: The Old New Thing
QR:
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 SetFileValidData function, but be very careful since it comes with serious security implications.) Read more: The Old New Thing
QR:
Bcdedit Tips and Tricks For Debugging Part 1
Posted by
jasper22
at
10:59
|
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 allThis 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:
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:
Common Language Runtime (CLR) Integration Programming in .NET
Posted by
jasper22
at
10:58
|
CLR Stored ProceduresStored 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_procedureThe @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
{EXECUTE @return_status = your_procedureThe @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)
{
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)
{
con.Open();
SqlCommand cmd = new SqlCommand(“SELECT Rate FROM Products”, con);
SqlDataReader reader = cmd.ExecuteReader();using (reader)
{
while( reader.Read() )
{
{
value += reader.GetSqlInt32(0);
}
}}
} Development Tip – Dispatching calls to the UI thread
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:
Read more: Yet Another Coding Blog
QR:
Extension Methods in .NET
Posted by
jasper22
at
16:05
|
IntroductionIn 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 LinksWhat 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:
Contents What are extension methods?
How do we create extension methods?
Examples of extension methods
Related LinksWhat 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:
Internals of .NET Objects and Use of SOS
Posted by
jasper22
at
16:02
|
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 TypesIn .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.
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:
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 TypesIn .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.
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:
Android’s HTTP Clients
Posted by
jasper22
at
16:01
|
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 ClientDefaultHttpClient 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.
HttpURLConnectionHttpURLConnection 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: gzipTake 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:
Apache HTTP ClientDefaultHttpClient 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.
HttpURLConnectionHttpURLConnection 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: gzipTake 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:
Атрибуты в NUnit для реализации Data Driven Tests
Posted by
jasper22
at
15:58
|
Начиная с версии 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:
[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:
Subscribe to:
Posts (Atom)

