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

Create your own IaaS platform with open source CloudStack

| Thursday, August 2, 2012
Takeaway: Ian Hardenburgh offers an overview of the open source CloudStack solution that allows you to build and manage a highly available and scalable cloud computing platform, now licensed under ASL 2.0.

If you’re not one for waiting around until the ongoing debate concerning which cloud strategy (public, private or hybrid approach) is settled, and just want to take your chances and delve right into creating your very own IaaS (Infrastructure as a Service), CloudStack could be an open source solution for you.� Acquired back in July of 2011 by Citrix, it looks as if its overseers are moving its code base to the Apache Software Foundation — a move that will certainly garner it even more community support than it already has.  However, don’t feel as if you have to wait until the software gets pushed through the Apache Incubator in order to take immediate advantage of the project, as it is already licensed under ASL 2.0 and available for full download from SourceForge.

CloudStack allows you to build, manage, and deploy multi-tenant compute environments by way of a web-based interface, command line, or even through its RESTful API, both in public and private data center type settings. To oversimplify, CloudStack is a software tool for assembling a cloud computing service similar to Amazon EC2, to scale.  In fact, depending on your users’ workload requirements, you can deploy any number of hypervisors that you feel are best suited for such scalability.  Some of the more well-known hypervisors available for deployment include Citrix XenServer, KVM, vSphere and/or Oracle VM.  However, for your CloudStack users, any stack you look to provide is obscured into an on-demand and easy-to-use portal.

There are four primary components to CloudStack: the CloudStack management server, virtualized hosts, primary storage facet (what might be more universally known as the virtual machine disk files), and the secondary storage — essentially the volume where you keep your ISO template images and VM snapshots.  Hardware-wise, in order to run the management service and virtualized hosts, you’ll need at least a combined 6GB of memory, 110GB of disk storage split between two separate 64-bit x86 CPU machines running a predetermined set of operating systems, namely RHEL/CentOS, Fedora 14, Ubuntu LTS and Citrix XenServer.  An NFS storage appliance or Linux NFS server of no less than 100 GB is also needed to handle secondary storage.

Read more: TechRepublic
QR: Inline image 1

Posted via email from Jasper-net

SQL Server Scheduling Flowchart

|
Inline image 1

Read more: srgolla
QR: Inline image 2

Posted via email from Jasper-net

C#/.NET Little Wonders: The Nullable struct

|
Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

There are many times in .NET where we have an instance of a value type that we need to treat as optional.  That is, we may want to consider its value as being supplied or missing. 

The System.Nullable<T> structure in the .NET Framework can be used to represent these situations in a consistent and meaningful way.

Why Do We Use Nullable<T>?

With instances of reference types, you can easily denote an optional item by simply leaving the reference as null, but this isn’t really possible with a value type (that is, not directly), because the instance of a value type always has a value.

For example, if you had an Person class with some basic data:

   1: public class Person
   2: {
   3:     public string FirstName { get; set; }
   4:     public string LastName { get; set; }
   5:     public int YearsRetired { get; set; }
   6:  
   7:     // ...
   8: }

We could have a person with no first name (Sting, Madonna, etc… or is that no last name?), simply by setting the string property FirstName to null:

   1: aPerson.FirstName = null;

But in the case of YearsRetired, if the person hasn’t retired yet, we can’t set a simple int to null, because an int is a value type, which must always have a value (strictly speaking):

   1: // compiler error
   2: aPerson.YearsRetired = null;

That said, we could use a sentinel value (-1), or have a separate bool field (IsRetired) to say whether we should use this field or not, but these get messy and harder to maintain.  Consider that if you use a sentinel value, everyone who uses this field must know what that value would be and to test for it. 

Alternatively, if you use a bool field to tell you if the value field is usable, they aren’t encapsulated, so again there could be usage issues or consistency issues in naming, etc.

This is why Nullable<T> exists, to allow you to easily mark value type instances as optional (“nullable”) by providing a mechanism that gives values types something like null semantics in an encapsulated and uniform way. 

In this way, anyone who looks at your interface and sees Nullable<int> (can also be abbreviated int?) will know how to test whether it has a valid value or not.

How the Nullable<T> struct Works

When you have a Nullable<T> wrapped type in the .NET Framework, it doesn’t give you a reference which you can make null.  It actually is a simple struct (value type) that wraps your value type.  This is an important distinction because it clears up some common misconceptions on what the Nullable<T> type does and does not do.

For example, let’s say you have:

   1: // or int? for short…
   2: Nullable<int> yearsRetired = null;

What really is yearsRetired?  Is it a reference that points to nothing?  No, it’s actually an instance of a value type with two fields: HasValue, and Value.  Note: for you C++ boost library users out there, this is much like how boost::optional<T> works.

Read more: James Michael Hare
QR: Inline image 1

Posted via email from Jasper-net

Why do some font names begin with an at-sign?

|
It was a simple question.

For some reason, my font selection dialog (CFont­Dialog) shows a bunch of font names beginning with the at-sign (@). These fonts don't work correctly if I use them. Any idea what they are? (I tried searching the Internet, but search engines don't seem to let you search for @ so it's hard to make much headway.)
(And that's why I wrote "at-sign" in the subject instead of using the @ character.)

Fonts which begin with an @-sign are vertically-oriented fonts. They are used in languages like Chinese, Japanese, and (less often) Korean. The idea is that if you want to generate vertical text, you start with the horizontal version of the font and compose your document, then switch to the vertical version for printing.

I wasn't able to detect that your browser supports the @SimSun font, so I'll give an example with fake Chinese characters. Pretend that the shapes and Latin letters are actually Chinese characters. First, you compose your document with the horizontal font:

▴❤❦Quo123▴‌̥ 

When it's time to print, switch to the vertical version of the font.

◀❥❧℺ᴝᴑ123◀°

Hm, it looks like the Chinese characters got rotated 90° to the left, so they're all lying on their side. The result is not really all that readable, but wait, here's the trick: After the paper comes out of the printer, rotate the paper right 90°:

Read more: The Old New Thing
QR: Inline image 1

Posted via email from Jasper-net

Entity Framework and Open Source

|
The Entity Framework has advanced significantly over the last few years. A little over a year ago we released EF 4.1, which introduced the new DbContext API and EF “Code First” support.  Earlier this year we delivered EF 4.3, which provides Code First Migration support that enables developers to easily evolve database schema in a code optimized way.  And we are now in the final stages of wrapping up the EF 5 release, which adds enum support, spatial data types, table-valued function support and some significant performance and Visual Studio Tooling improvements.

One of the things the team has done throughout the EF4 and EF5 development cycles has been to involve the community early as we make design decisions and solicit as much feedback as possible. Going forward with EF 6 we are looking to take this to the next level by moving to an open development model.

The Entity Framework source code is today being released under an open source license (Apache 2.0), and the code repository is now hosted on CodePlex (using Git) to further increase development transparency. This will enable everyone in the community to be able to engage and provide feedback on code checkins, bug fixes, new feature development and build and test the product on a daily basis using the most up to date version of the source code and tests. Community contributions will also be welcomed, so you can help shape and build Entity Framework into an even better product. You can find all the details on the Entity Framework CodePlex Site.

Last December the Windows Azure SDKs adopted this open development model, and in March of this year I blogged about how ASP.NET MVC, ASP.NET Web API and ASP.NET Razor were also adopting this approach. These products have all found the open development approach to be a great way to build a tighter feedback loop with the community, and at the end of the day deliver even better products.

Read more: ScottGu's Blog
Read more: Codeplex
QR: Inline image 1

Posted via email from Jasper-net

When do I need to use GC.KeepAlive?

| Wednesday, August 1, 2012
Finalization is the crazy wildcard in garbage collection. It operates "behind the GC", running after the GC has declared an object dead. Think about it: Finalizers run on objects that have no active references. How can this be a reference to an object that has no references? That's just crazy-talk!

Finalizers are a Ouija board, permitting dead objects to operate "from beyond the grave" and affect live objects. As a result, when finalizers are involved, there is a lot of creepy spooky juju going on, and you need to tread very carefully, or your soul will become cursed.

Let's step back and look at a different problem first. Consider this class which doesn't do anything interesting but works well enough for demonstration purposes:

class Sample1 {
 private StreamReader sr;
 public Sample1(string file) : sr(new StreamReader(file)) { }
 public void Close() { sr.Close(); }
 public string NextLine() { return sr.ReadLine(); }
}

What happens if one thread calls Sample1.NextLine() and another thread calls Sample1.Close()? If the NextLine() call wins the race, then you have a stream closed while it is in the middle of its ReadLine method. Probably not good. If the Close() call wins the race, then when the NextLine() call is made, you end up reading from a closed stream. Definitely not good. Finally, if the NextLine() call runs to completion before the Close(), then the line is successfully read before the stream is closed.

Having this race condition is clearly an unwanted state of affairs since the result is unpredictable.

Now let's change the Close() method to a finalizer.

class Sample2 {
 private StreamReader sr;
 public Sample2(string file) : sr(new StreamReader(file)) { }
 ~Sample2() { sr.Close(); }
 public string NextLine() { return sr.ReadLine(); }
}

Remember that we learned that an object becomes eligible for garbage collection when there are no active references to it, and that it can happen even while a method on the object is still active. Consider this function:

string FirstLine(string fileName) {
 Sample2 s = new Sample2(fileName);
 return s.NextLine();
}

We learned that the Sample2 object becomes eligible for collection during the execution of NextLine(). Suppose that the garbage collector runs and collects the object while NextLine is still running. This could happen if ReadLine takes a long time, say, because the hard drive needs to spin up or there is a network hiccup; or it could happen just because it's not your lucky day and the garbage collector ran at just the wrong moment. Since this object has a finalizer, the finalizer runs before the memory is discarded, and the finalizer closes the StreamReader.

Boom, we just hit the race condition we considered when we looked at Sample1: The stream was closed while it was being read from. The garbage collector is a rogue thread that closes the stream at a bad time. The problem occurs because the garbage collector doesn't know that the finalizer is going to make changes to other objects.

Read more: The Old New Thing
QR: Inline image 1

Posted via email from Jasper-net

Portable Executable 101 - a windows executable walkthrough

|
This graphic is a walkthrough of a simple windows executable, that shows its dissected structure and explains how it's loaded by the operating system.

Inline image 1

Read more: corkami
QR: Inline image 2

Posted via email from Jasper-net

Writing a Visual Studio 2012 Unit Test Adapter

|
Visual Studio 2012 comes with an extensible Unit Test Framework. Many of your favorite Unit Test frameworks (xUnit.Net, nUnit..) already have built adapters to Visual Studio.  Peter Provost maintains a list of adapters here.  If you have another unit test framework you like, you can build an adapter super easy. In this article, I will walk you through the steps required to build a Visual Studio 2012 Unit Test Adapter.

For the purposes of this discussion, I am going to write a Unit Test Adapter for XML files. The XML file will contain tests in the following format.

Inline image 1

After we install the new XML Test Adapter, we will see the following status in Test Explorer.

Inline image 2

Step 1: Create a Discoverer

Inline image 3

QR: Inline image 4

Posted via email from Jasper-net

#614 – Events that Fire When You Switch Between Windows

|
If your application has multiple windows, the user can switch between the different windows.  The sequence of events when switching from one window (1) to another (2) is as follows:

Window.Deactivated  (#1)
Window.Activated  (#2)
Window.PreviewLostKeyboardFocus  (#1)
Window.PreviewGotKeyboardFocus  (#2)
Window.IsKeyboardFocusWithinChanged  (#1)
Window.IsKeyboardFocusWithinChanged  (#2)
Window.IsKeyboardFocusChanged  (#1)
Window.IsKeyboardFocusChanged  (#2)
Window.LostKeyboardFocus  (#1)
Window.GotKeyboardFocus  (#2)
Window.Deactivated  (#2)

QR: Inline image 1

Posted via email from Jasper-net

Large collection of Free Microsoft eBooks for you, including: SharePoint, Visual Studio, Windows Phone, Windows 8, Office 365, Office 2010, SQL Server 2012, Azure, and more.

|
Throughout the year I try to share resources and information with you that I think will be helpful for you. Often times these resources will include links to free eBooks that we make available on a variety of topics. Today, I thought I would post a large collection of eBooks for you here so that you can find them in one place and consume them as you see fit. Also, if you find this list helpful, please share it with your peers and colleagues so that they too can benefit from these resources.

Due to the incredible popularity of this post, I’ve also added a second post on even MORE free Microsoft eBooks and Resource Kits available for you, in case you are interested.

Inline image 2  Inline image 3  Inline image 4

QR: Inline image 1

Posted via email from Jasper-net

Google Cloud Messaging with Android

|
You might have heard of C2DM (Cloud-to-Device Messaging), which basically allowed third-party applications to send (push) lightweight messages to their Android applications. Well, C2DM as such is now deprecated and replaced with its successor up the evolutionary ladder: GCM, or Google Cloud Messaging.

GCM is a (free) service that allows developers to push 2 types of messages from their application servers to any number of Android devices registered with the service:

  1. Collapsible, "send-to-sync" messages
  2. Non-collapsible messages with a payload up to 4K in size
"Collapsible" means that the most recent message overwrites the previous one.  A "send-to-sync" message is used to notify a mobile application to sync its data with the server. In case the device comes online after being offline for a while, the client will only get the most recent server message.

If you want to add push notifications to your Android applications, the Getting Started guide will walk you through the set up process step by step, even supplying you with a two-part Demo Application (client + server) that you can just install and play around with. The set-up process will provide you with the two most essential pieces of information needed to run GCM:

  1. An API key, needed by your server to send GCM push notifications
  2. A Sender ID, needed by your clients to receive GCM messages from the server
All summarized in the following screen you get after using the Google API console:

Inline image 2

Read more: DZone
QR: Inline image 1

Posted via email from Jasper-net

Resource in Silverlight , A Brief OverView – Part 1 (Resource Files)

|
Resources are always a vital part for web application and here in Silverlight application too it plays an important role for creating Rich internet applications. In this context Resource means Images,audio,videos,object, which can be styles or datatemplete used for creating rich application. Silverlight does support various ways of storing resources and managing it. In this post, we will discover the different options available.

The complete information on resources will span across multiple posts ,where we will cover Binary Resource (Resource Files ) and XAML Resource .

Various Ways of managing Resources
In Silverlight Resources can be managed by following ways

Resource at server Side ,Loading on Demand
Resource embedded inside XAP/Assembly
Resources from external assemblies
The most important point ,we should not confuse over Assembly Resource and XAML Resource although both termed as resource .We can divide resource types in to two categories

Files other than executable or Binary/Assembly Resource (Managed through Resource Files)
Objects such as Styles,Templates etc.… or XAML Resource(Managed Through Resource Dictionary)
Basically the scope of this post is to give you a brief about Resource Files or Binary Resource or Assembly Resource .In this post we will explore how these resource files can be stored and managed from Silverlight .The subsequent post will focus on Resource Dictionary or XAML Resource.

Managing Resource Files
Before moving on the Resource Files lets have quick look into some important terminologies we will come across frequently

Application Package – The files packaged as a XAP file which includes the Silverlight assemblies and Application manifest files also Resources if any.

Application Root – The location where XAP files reside in the deployed solution most of the time ClientBin

URI - Stands for Uniform Resource Identifier , is the path to the the Resource.It can be either

...
...

Content:

Content option add the file to application package as loose resource .

Inline image 1

Here in the project Change the file BuildAction as Content and Rebuild the solution.The XAP file size is almost 42 KB which includes Image .

Inline image 2

Read more: ManasPatnak
QR: Inline image 3

Posted via email from Jasper-net

Hidden Gems inside .Net Classes

|
Surprisingly, there are loads of great data snippets hidden inside .Net classes. If you've ever found yourself adding localization to your website, you may have come across the CultureInfo Class in .Net. I know that sometimes I have needed to get a list of country ISO codes and have struggled to get a comprehensive list, or I have needed to retrieve the list from a Database containing the names. This can add an extra Database call and could result in extra code maintenance, and possibly a performance hit.

Well, this is where CultureInfo comes to the rescue. Using this Class, you will be able to easily retrieve a list of country names and their ISO codes using built-in .Net code.

Dictionary<string, string> cultureDetails = new Dictionary<string, string>();

   foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
   {
      RegionInfo regionInfo = new RegionInfo(cultureInfo.Name);

      if (!cultureDetails.ContainsKey(regionInfo.EnglishName))
      {
      cultureDetails.Add(regionInfo.EnglishName, regionInfo.Name);
      }
   }

var orderedCultureDetails = cultureDetails.OrderBy(x => x.Key);

Which gives you a list of 128 countries and their region information:

Inline image 1

QR: Inline image 2

Posted via email from Jasper-net

The outlook for Hotmail is shiny with the new Outlook.com (and a few tips on using it)

|
Inline image 2

Recently, we talked about how we've reimagined cloud services for Windows 8 and Windows Phone. And we described new apps for Windows 8, updates to SkyDrive, and how cloud services power the new Office Preview, We've also been hard at work on a mission to reimagine personal email - from the datacenter all the way to the user experience. Today, we're starting to deliver on that goal with a preview of the new Outlook.com - modern email designed for the next billion mailboxes.

QR: Inline image 1

Posted via email from Jasper-net

Phantom OS

| Tuesday, July 31, 2012
Inline image 2

Phantom OS is an operating system mostly made by Russian programmers. Phantom OS is based on a concept of persistent virtual memory, and is managed-code oriented. Phantom OS is one of a few OSes that are not based on classical concepts of UNIX-like systems. Its primary goal is to achieve simplicity and effectiveness in both the operating system and applications at the same time.

Phantom is based on the principle that "Everything is an object", in contrast to the Unix-like approach of "Everything is a file".

Read more: Wikipedia
QR: Inline image 1

Posted via email from Jasper-net

CRIU — новый амбициозный проект для сохранения и восстановления состояния процессов

|
CRIU (application Checkpoint/Restore In Userspace) — это амбициозный, быстро развивающийся проект, который позволяет сохранить состояние программы в виде контрольной точки, и впоследствии возобновить работу приложения с этой точки.
Возможности применения программного обеспечения для создания контрольных точек достаточно разнообразны. К примеру, OpenVZ использует похожий механизм для “живой” миграции. Parallels Virtuozzo использует подобный механизм для быстрого возобновления работы контейнеров после обновления ядра. CRIU уже используется в высокопроизводительных кластерах для для сохранения промежуточных результатов вычислительных процессов, используемых для возобновления работы приложения в случае сбоя.
В этой статье рассказывается, как CRIU сохраняет и восстанавливает состояние программы, и почему этот проект может быть успешнее своих предшественников.

Немного истории

CRIU — это далеко не первая попытка реализовать некий механизм сохранения и восстановления программ в Linux. Существует как минимум две рабочие реализации C/R: OpenVZ и проект linux-cr, лидером которого является Oren Laadan.
Проблема обоих проектов в том, что они реализуют весь C/R практически полностью в пространстве ядра. Однако эти проекты не стали частью основного ядро Linux из-за большого объёма и сложного кода.
Лидер команды разработчиков OpenVZ Павел Емельянов предложил изменить сам подход к C/R и перенести основную работу в пространство пользователя. Сообщество хорошо приняло эту идею и появился проект CRIU.

Сохранение состояния приложения

Приложение может состоять как из одного, так и из множества запущенных процессов. CRIU поддерживает оба типа.
Для получения информации о состоянии процесса первое, что приходит на ум, это использование механизма, которым пользуется отладчик (ptrace). Но он не предоставляет всей информации. Часть состояния процесса можно почерпнуть из файловой системы procfs и системного вызова prctl, однако и этого недостаточно.
Для получения недостающей информации в проекте CRIU был использован механизм внедрения исполняемого кода в процесс (т.н. паразитный код), который был разработан и любезно предоставлен Tejun Heo, одним из основных на сегодняшний день разработчиков ядра Linux.

Восстановление состояния приложения

Для восстановления приложения с контрольной точки необходимо сначала создать дерево его процессов. Для этого в ядре Linux был разработан отдельный механизм для создания процессов с заданными идентификаторами. После старта каждый процесс восстанавливает свою память, открытые файлы, сокеты, пайпы, IPC и т д.
Однако на самом деле всё не так просто, ведь ресурсы могут быть общими для нескольких процессов.
Регионы адресного пространства процесса могут быть уникальны (MAP_PRIVATE) либо доступны одновременно несколькими процессами (MAP_SHARED). Первый тип восстанавливается достаточно просто (если не задумываться о технологии “copy on write” — она остаётся за скобками этой статьи).
В чем же проблема во втором варианте? Если у нас регион адресного пространства отображается в файл, то все в порядке — для восстановления такого куска адресного пространства можно использовать стандартные механизмы Linux.

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

#613 – Window Event Sequence

|
The full sequence of events fired for a Window object are as follows.
On application startup, if the Window is the application’s main window.  (Application events are also shown in the correct sequence).

  • Application.Startup
  • Window.Initialized
  • Window.IsVisibleChanged
  • Window.SizeChanged
  • Window.LayoutUpdated
  • Window.SourceInitialized
  • Application.Activated
  • Window.Activated
  • Window.PreviewGotKeyboardFocus
  • Window.IsKeyboardFocusWithinChanged
  • Window.IsKeyboardFocusedChanged
  • Window.GotKeyboardFocus
  • Window.LayoutUpdated
  • Window.Loaded
  • Window.ContentRendered

On normal application shutdown, the event sequence is:

  • Window.Closing
  • Window.IsVisibleChanged
  • Window.Deactivated
  • Application.Deactivated
  • Window.IsKeyboardFocusWithinChanged
  • Window.IsKeyboardFocusedChanged
  • Window.LostKeyboardFocus
  • Window.Closed
  • Application.Exit

QR: Inline image 1

Posted via email from Jasper-net

DPAPI на пальцах

|
В далеком декабре прошлого года я впервые столкнулся с Data Protection Application Programming Interface (сокращенно DPAPI). Тогда я изучал способ хранения логинов/паролей в браузере Chrome. Я обещал, что распишу эту систему подробно и на пальцах. Негоже врать, поэтому добро пожаловать под кат!

Начну всё с азов, что же такое DPAPI, зачем он создавался и кому он нужен. И затем уже расскажу, как это работает.

Коротко о главном

Проблемы информационной безопасности уже давно коснулись всех, и Microsoft был не исключением, офисные ПК, домашние системы, сервера — все в той, или иной степени, требовали защиты от чужих рук. 
Хранение данных в открытом виде было уже, как минимум, не солидно. Поэтому с выходом Windows 2000 свет увидел зарождающуюся и сырую версию DPAPI. Её основная цель — защита хранимых паролей и конфиденциальной информации на компьютере. Причем таким способом, чтобы владелец этих данных (пользователь) даже не догадывался о существовании защиты, а взломщику эти данные были недоступны. Идеология системы с той поры не изменилась. Менялись алгоритмы, закрывались дыры, но суть была всё та же.
В итоге появилась полноценная система безопасности, в которой секретные данные были доступны исключительно пользователю-владельцу и никому другому.

Принцип работы
Inline image 1

Так выглядит тривиальная схема работы с DPAPI. 

Приложение обращается к ОС задавая параметры Mysecret(строка/байты, которые нужно засекретить) и Entropy(энтропия, о ней чуть позже. Данный параметр не обязательный).

На выходе получаем BLOB. 

BLOB – Binary Large OBject. Расшифровка является бэкронимом. По сути, это массив двоичных данных. «Большое и бесформенное».
Этот BLOB — своего рода контейнер, в котором содержаться в открытом виде данные, необходимые для расшифровки, а так же сам шифр. Приложение сохраняет его (для примера всё тот же Chrome, который записывал этот BLOB в виде массива байт в одно из полей SQLITE базы данных), а в дальнейшем, при необходимости, расшифровывает(вторая половина схемы).

Read more: Habrahabr.ru
QR: Inline image 2

Posted via email from Jasper-net

Mensa International

|
Inline image 2

   Mensa is the largest and oldest high IQ society in the world.[2][3][4] It is a non-profit organization open to people who score at the 98th percentile or higher on a standardised, supervised IQ or other approved intelligence test.[5][6] Mensa is formally composed of national groups and the umbrella organisation Mensa International, with a registered office in Caythorpe, Lincolnshire, England, United Kingdom.[7]

   Mensa ( /ˈmɛnsə/; Latin: [ˈmensa]) means "table" in Latin, as is symbolized in the organization's logo, and was chosen to demonstrate the round-table nature of the organization; the coming together of equals.

Read more: Wikipedia
QR: Inline image 1

Posted via email from Jasper-net

Памятка пользователям ssh

|
abstract: В статье описаны продвинутые функций OpenSSH, которые позволяют сильно упростить жизнь системным администраторам и программистам, которые не боятся шелла. В отличие от большинства руководств, которые кроме ключей и -L/D/R опций ничего не описывают, я попытался собрать все интересные фичи и удобства, которые с собой несёт ssh.

Предупреждение: пост очень объёмный, но для удобства использования я решил не резать его на части.

Оглавление:
управление ключами
копирование файлов через ssh
Проброс потоков ввода/вывода
Монтирование удалённой FS через ssh
Удалённое исполнение кода
Алиасы и опции для подключений в .ssh/config
Опции по-умолчанию
Проброс X-сервера
ssh в качестве socks-proxy
Проброс портов — прямой и обратный
Реверс-сокс-прокси
туннелирование L2/L3 трафика
Проброс агента авторизации
Туннелирование ssh через ssh сквозь недоверенный сервер (с большой вероятностью вы этого не знаете)

Управление ключами

Теория в нескольких словах: ssh может авторизоваться не по паролю, а по ключу. Ключ состоит из открытой и закрытой части. Открытая кладётся в домашний каталог пользователя, «которым» заходят на сервер, закрытая — в домашний каталог пользователя, который идёт на удалённый сервер. Половинки сравниваются (я утрирую) и если всё ок — пускают. Важно: авторизуется не только клиент на сервере, но и сервер по отношению к клиенту (то есть у сервера есть свой собственный ключ). Главной особенностью ключа по сравнению с паролем является то, что его нельзя «украсть», взломав сервер — ключ не передаётся с клиента на сервер, а во время авторизации клиент доказывает серверу, что владеет ключом (та самая криптографическая магия).

Генерация ключа

Свой ключ можно сгенерировать с помощью команды ssh-keygen. Если не задать параметры, то он сохранит всё так, как надо. 

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

Сменить пароль на ключ можно с помощью команды ssh-keygen -p.

Структура ключа

(если на вопрос про расположение ответили по-умолчанию).
~/.ssh/id_rsa.pub — открытый ключ. Его копируют на сервера, куда нужно получить доступ.
~/.ssh/id_rsa — закрытый ключ. Его нельзя никому показывать. Если вы в письмо/чат скопипастите его вместо pub, то нужно генерировать новый ключ. (Я не шучу, примерно 10% людей, которых просишь дать ssh-ключ постят id_rsa, причём из этих десяти процентов мужского пола 100%). 

Копирование ключа на сервер

В каталоге пользователя, под которым вы хотите зайти, если создать файл ~/.ssh/authorized_keys и положить туда открытый ключ, то можно будет заходить без пароля. Обратите внимание, права на файл не должны давать возможность писать в этот файл посторонним пользователям, иначе ssh его не примет. В ключе последнее поле — user@machine. Оно не имеет никакого отношения к авторизации и служит только для удобства определения где чей ключ. Заметим, это поле может быть поменяно (или даже удалено) без нарушения структуры ключа.

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

Perfect Viewing of PerfView - Links, Videos and More

|

Vance Morrison, Performance Architect on the Common Language Runtime (CLR) team writes and maintains a very powerful tool called PerfView that harnesses the power of Event Tracing for Windows (ETW) data produced by the CLR. The tool can be download here.

Although he had previously published some tutorial videos as a ZIP download on his blog, those videos have now been published in a more accessible way as a PerfView tutorial series here on Channel 9.

Ben Watson has also just published a very nice article on PerfView following on from his previous article outlining 4 essential tips for high performance GC on servers.

...

PerfView is a performance-analysis tool that helps isolate CPU- and memory-related performance issues.

Quick details
Version: 1.0.29 
Date published: 6/20/2012

Language: English

PerfView.zip, 6.4 MB

PerfView is a performance analysis tool focusing on ETW information (ETL files) as well as CLR memory information (heap dumps). It can collect and view ETL files as well as XPERF CSV files. Powerful grouping operators allow you to understand performance profiles in ways other tools can't. PerfView is used internally at Microsoft by a number of teams and is the primary performance investigation tool on the .NET Runtime team. Features include:

Non-invasive collection - suitable for use in live, production environments
Xcopy deployment - copy and run
Memory
Support for very large heaps (gigabytes)
Snapshot diffing
Dump files (.dmp)
CPU Performance
Support for managed, native, and mixed code
Can read XPerf logs
Profile diffing

Updates in the 1.0.29 version include:
Improved view for analyzing blocked time (thread time view)
Support for .NET 4.5 EventSources
Support for writing extensions

Read more: Dzone
QR: Inline image 1

Posted via email from Jasper-net

30 More Questions About Windows 8 That I Get Asked All The Time

|
As a developer evangelist, I interact with a lot of developers. Many developers are just meeting Windows 8 for the very first time. Some developers have started to tinker. And, others are deep into their first application – on target for the store. The common thread between them are a set of recurring questions that I get over and over. I thought I would document a few of them.
  1. Should all desktop apps be migrate to metro? No
  2. Will the Windows 8 store support trials? Yes
  3. Will the Windows 8 store support subscriptions? No
  4. Will enterprise apps deliver through the Windows 8 store? No
  5. Can enterprises disable the Windows 8 store? Yes
  6. Can enterprises disable side-loading of apps? Yes
  7. Can apps in the Windows 8 store access desktop apps & services? No
  8. Can side-loaded apps access desktop apps & services? Yes
  9. Can parents disable the Windows 8 store for kids? Yes
  10. Can parents limit the hours in the day their kids can log in? Yes
  11. Can parents limit the cumulative time in a day kids can use the PC? Yes
  12. Can parents filter available web sites? Yes
  13. Can parents disable games based on their rating? Yes
  14. Can Visual Studio 2010 be used to build Metro apps? No
  15. Can Visual Studio 2012 be used to build Windows 7 apps? Yes
  16. Can Visual Studio 2010 access Team Foundation Server 2012? Yes
  17. Can Visual Studio 2012 open 2010 projects without altering them? Yes
  18. Can Visual Studio 2010 open 2012 projects? No
  19. Does the .Net 4 async keyword work in WinRT? Yes

Read more: DZone
QR: Inline image 1

Posted via email from Jasper-net

Tools released at Defcon can crack widely used PPTP encryption in under a day

| Monday, July 30, 2012
July 29, 2012 — IDG News Service — Security researchers released two tools at the Defcon security conference that can be used to crack the encryption of any PPTP (Point-to-Point Tunneling Protocol) and WPA2-Enterprise (Wireless Protected Access) sessions that use MS-CHAPv2 for authentication.

MS-CHAPv2 is an authentication protocol created by Microsoft and introduced in Windows NT 4.0 SP4. Despite its age, it is still used as the primary authentication mechanism by most PPTP virtual private network (VPN) clients.

MS-CHAPv2 has been known to be vulnerable to dictionary-based brute force attacks since 1999, when a cryptanalysis of the protocol was published by cryptographer Bruce Schneier and other researchers.

However, the common belief on the Internet is that if you have a strong password then it's ok, said Moxie Marlinspike, the security researcher who developed ChapCrack, one of the tools released at Defcon. "What we demonstrated is that it doesn't matter. There's nothing you can do."

ChapCrack can take captured network traffic that contains a MS-CHAPv2 network handshake (PPTP VPN or WPA2 Enterprise handshake) and reduce the handshake's security to a single DES (Data Encryption Standard) key.

This DES key can then be submitted to CloudCracker.com -- a commercial online password cracking service that runs on a special FPGA cracking box developed by David Hulton of Pico Computing -- where it will be decrypted in under a day.

Read more: Data protection
QR: Inline image 1

Posted via email from Jasper-net

The Truth About .NET Objects And Sharing Them Between AppDomains

|
I have written already some time ago how big a .NET object is. John Skeet as also made a very detailed post about object sizes in .NET. I wanted to know if we can deduce the object size not by experiments (measuring) but by looking at the Rotor source code. There is indeed a simple definition in the object headers how big a .NET object minimally can be. A CLR object is still a (sophisticated) structure which is at an address that is changed quite often by the garbage collector.

Inline image 1

The picture above shows that every .NET object contains an object header which contains information about which thread in which AppDomain has locked the object (means called Monitor.Enter). Next comes the Method Table Pointer which defines a managed type for one AppDomain. If the assembly is loaded AppDomain neutral this pointer to the type object will have the same value in all AppDomains. This basic building block of the CLR type system is also visible in managed code via Type.TypeHandle.Value which has IntPtr size.

 

\sscli20\clr\src\vm\object.h

//
// The generational GC requires that every object be at least 12 bytes
// in size.   
#define MIN_OBJECT_SIZE     (2*sizeof(BYTE*) + sizeof(ObjHeader))
A .NET object has basically this layout:

class Object
{
  protected:
    MethodTable*    m_pMethTab;

};
class ObjHeader
{
  private:
    // !!! Notice: m_SyncBlockValue *MUST* be the last field in ObjHeader.
    DWORD  m_SyncBlockValue;      // the Index and the Bits
};
 

For x86 the minimum size is therefore 12 bytes = 2*4+4. And for x64 it is 24 bytes = 2*8+8. The ObjectHeader struct is padded with another 4 bytes in x64 which does add up to 24 bytes for every object instance. The MIN_OBJECT_SIZE definition has actually a factor two inside it whereas we would expect 8 as minimum empty object size. The previous sentence does contain already the answer to it. It makes little sense to define empty objects. Most meaningful objects have at least one member variable of class type which is indeed another pointer sized member hence the minimum size of 12 bytes (24) bytes in x86/x64.

It is interesting to know that the garbage collector does not know anything about AppDomains. For him the managed heap does only consist of objects which have roots or not and does clean up everything which is not rooted anymore. I found this during the development of WMemoryProfiler which uses DumpHeap of Windbg to get all object references from the managed heap. When I did access all objects found this way I got actually objects from other AppDomains as well. And they did work! It is therefore possible to share objects directly between AppDomains.

Why would you want to do that? Well it is fun and you can do really dirty stuff with that. Do you remember that you cannot unload assemblies from an AppDomain? Yes that is still true but why would you ever want to unload an assembly? Mostly because you were doing some dynamic code generation which will at some point in time dominate your overall memory consumption if you load generated assemblies into your AppDomain. I have seen this stuff many times for dynamic query generation. The problem is that if you load the dynamically created code into another AppDomain you need to serialize the data to the other AppDomain as well because you cannot share plain objects between AppDomains. To serialize potentially much data across AppDomain is prohibitively slow and therefore people live with the restriction that code gen will increase the working set quite a lot.  With some tricks you can now share plain objects between AppDomain and get unloadable code as well.

 
Warning: This following stuff well beyond the specs but it does work since .NET 2.0 up to 4.5.

Do not try this at work!

Read more: Alois Kraus
QR: Inline image 2

Posted via email from Jasper-net

Defend Your Code with Top Ten Security Tips Every Developer Must Know

|
Security is a multidimensional issue. Security risks can come from anywhere. You could write bad error handling code or be too generous with permissions. You could forget what services are running on your server. You could accept all user input.

1. Trust User Input at Your Own Peril

2. Protect Against Buffer Overruns

3. Prevent Cross-site Scripting

4. Don't Require sa Permissions

5. Watch that Crypto Code!

6. Reduce Your Attack Profile

7. Employ the Principle of Least Privilege

8. Pay Attention to Failure Modes

9.Impersonation is Fragile

10. Write Apps that Non-admins Can Actually Use

 

1.     Trust User Input at Your Own Peril

Always remember one thing: "don't trust user input." If you always assume that data is well formed and good, then your troubles are about to begin. Most security vulnerabilities revolve around
the attacker providing malformed data to the server machine. Trusting that input is well formed can lead to buffer overruns, cross-site scripting attacks, SQL injection attacks, and more.

2. Protect Against Buffer Overruns

A buffer overrun occurs when the data provided by the attacker is bigger than what the application expects, and overflows into internal memory space. Buffer overruns are primarily a C/C++ issue. The overflow causes corruption of other data structures in memory, and this corruption can often lead to the attacker running malicious code. There are also buffer underflows and buffer overruns caused by array indexing mistakes, but they are less common. Take a look to the following source code example:

void DoSomething(char *cBuffSrc, DWORD cbBuffSrc) {

    char cBuffDest[32];

    memcpy(cBuffDest,cBuffSrc,cbBuffSrc);

}

If the data comes from an untrusted source and has not been validated, then the attacker (the untrusted source) could easily make cBuffSrc larger than cBuffDest, and also set cbBuffSrc to be larger than cBuffDest. When memcpy copies the data into cBuffDest, the return address from DoSomething is clobbered because cBuffDest is next to the return address on the function's
stack frame, and the attacker makes the code perform malicious operations.

The way to fix this is to distrust user input and not to believe any data held in cBuffSrc and cbBuffSrc:

void DoSomething(char *cBuffSrc, DWORD cbBuffSrc) {

    const DWORD cbBuffDest = 32;

    char cBuffDest[cbBuffDest];

Read more: Sharing SharePoint
QR: Inline image 1

Posted via email from Jasper-net

WPF 4.5 – Part 1 : Asynchronous Data Validation

|
Here is the first post of a series about the new features of WPF 4.5. Validation of data is often if not always necessary in modern applications. From a long time, WPF provided the IDataErrorInfo interfaces which permitted the automatic validation of your properties.

Silverlight, with is asynchronous philosophy provided the INotifyDataErrorInfo which performed the same thing but asyncrhonously.

It is a newinterface of WPF 4.5 and we will discover it in this post.

What’s inside ?
Here is the definition of it:

Inline image 1

As you can see there is only 3 things inside:

HasErrors: a read-only boolean property which tells if the object as a whole have any validation errors;
GetErrors: a method which returns validation errors for a given property;
ErrorsChanged: an event which must be raised when new errors – or the lacks of errors – is detected. You have to raise this event for each property.
As a note, if you return false in the HasErrors property, the binding will act as if there were no errors, even if they exists.

How to use it ?
With the traditionnal IDataErrorInfo, you have to set to true the ValidatesOnDataErrors property on each binding to your object. There is nothing really new under the sun because this time you have to set the ValidatesOnNotifyDataErrors property to true.

In the linked demo project I create a form which display the properties of an object named ‘Person’. Here is how the validation with INotifyDataErrorInfo is enabled in the Binding:

<TextBox Text="{Binding Name,Mode=TwoWay,ValidatesOnNotifyDataErrors=True}"/>

Read more: DZone
QR: Inline image 2

Posted via email from Jasper-net

Simple Instant Messenger with SSL Encryption in C#

|
Inline image 1

Introduction

Did you ever want to write your own instant messenger program like Skype? OK, not so advanced... I will try to explain how to write a simple instant messenger (IM) in C#.NET.

First, some theory. Our instant messenger will work on a client-server model.

Inline image 2

Users have client programs which connect to the server application. Client programs know the server's IP or hostname (e.g., example.com).

The most popular internet protocols are TCP and UDP. We will use TCP/IP, because it is reliable and it has established connection. .NET offers TcpClient and TcpListener classes for this protocol. TCP/IP doesn't offer encryption. It is possible to create own encryption protocol over TCP, but I recommend using SSL (used in HTTPS). It authenticates server (and optionally client) and encrypts connection.

SSL is using X.509 certificates for authenticating. You can buy real SSL certificate (trusted) or generate self-signed certificate (untrusted). Untrusted certificates allow encryption, but authentication isn't safe. We can use them for testing. I made batch script, which generates self-signed certificate in PFX package. My script requires OpenSSL installed in system. I included also one in server application project.

At the end there is your higher-level protocol, which sends messages to specified users and does other IM stuff. I will explain my protocol during article.

You can debug your server and client on the same computer: hostname of server will be localhost or 127.0.0.1 (local IP - same computer).

Background

You should know something about SSL protocol, certificates, and networking.

Preparing

Create two projects: server and client. Server will be a console application, client - Windows Forms (or WPF). You will need to debug two projects at once, so don't place them in one solution.

Read more: Codeproject
QR: Inline image 3

Posted via email from Jasper-net

Converting Hex String To Corresponding Byte Array Using C#

|
I came across an issue where I needed to convert a string representing HEX value into corresponding byte array. I know that there are various solutions that all accomplish the same task: Take A String And Convert It To Equivalent Byte Array.

For example a string value: 0x0123456789ABCDEF would be 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD and 0xEF represented in a byte array. The basic .NET functions would give you the byte array of the actualy ASCII characters, and not the binary value that they represent. There was all kind of solutions out there. Some declared to be faster than other, or simply the fastest. I am sure the solution that I came up with is not prettiest or the most effcient. But, it is my solution that I came up with. I am sure that it has been thought before but have not seen any post that are quite a like it. I think that it is pretty good solution for what I wanted to accomplish. That said. I love learning. So, if you find a problem or have an idea to improve it. Please! All feedback is welcomed: The Good, The Bad and The Ugly.

The Problem

Convert a string it to a byte array representing the actual text values of each byte.

Considerations

I spent some time thinking about different things that I would have to take into consideration when doing the conversion of the string to the byte array.

Special Cases: Input is valid, and expected but it creates special handling conditions.

Is the input string null or empty
The string starts with the HEX indicator string '0x'.
Is the leading '0' dropped from the string.
The casing of the letter, they can be upper, lower or mixed casing.
Error Checking: We live in a World where we can't trust any, not even our input string. So, I need to have some type of validation in place for the input.

Does the string contain characters that are not valid alphanumeric values: 0-9 and A-F.
Approach

Taking into account the factors that I came up with, I came up with the following approach.

To handle the case of null or empty input, I would return an empty array. To avoid, unnecessary allocations I created a static, readonly empty byte array that I would return to the caller.

private static readonly byte[] Empty = new byte[0];
Once I have determined that I actually have some type of string. I would handle rest of conditions during the conversion, except the 'dropped' leading zero ('0') which I would handle before the actual conversion.

Read more: Heikki Ritvanen
QR: Inline image 1

Posted via email from Jasper-net

LINQ interview questions

|
In this post we will review a bunch of small and simple LINQ interview questions to get you started. Once you understand these standard query expressions, it should be a breeze for you to answer LINQ questions.

Question: Given an array of numbers, find if ALL numbers are a multiple of a provided number. For example, all of the following numbers - 30, 27, 15, 90, 99, 42, 75 are multiples of 3.

The trick here is to use the Enumerable.All<TSource> method which determines whether all elements of a sequence satisfy a condition.

static void Main(string[] args)
{
    int[] numbers = { 30, 27, 15, 90, 99, 42, 75 };

    bool isMultiple = MultipleTester(numbers, 3);
}

private static bool MultipleTester(int[] numbers, int divisor)
{
    bool isMultiple =
        numbers.All(number => number % divisor == 0);
    
    return isMultiple;
}

Question: Given an array of numbers, find if ANY of the number is divisible by 5. For example, one of the following numbers - 30, 27, 18, 92, 99, 42, 72 is divisible by 5. 

Again, the key fact here is to use Enumerable.Any<TSource> method which determines whether any element of a sequence satisfies a condition. The code is very similar to the ALL case. 

 

static void Main(string[] args)
{
    int[] numbers = { 30, 27, 18, 92, 99, 42, 72 };
        
    bool isDivisible = IsDivisible(numbers, 3);
}

private static bool IsDivisible(int[] numbers, int divisor)
{
    bool isDivisible =
        numbers.Any(number => number % divisor == 0);
    
    return isDivisible;
}

Another way to present a similar question that utilizes Enumerable.Any<TSource> method is shown below. 

Question: Given a GPSManufacturer and GPSDevice data structure as defined below, find all the manufacturers that have at least 1 or more active GPS devices. 

class GpsDevice
{
    public string Name;
    public bool IsActive;
}

QR: Inline image 1 Inline image 2

Posted via email from Jasper-net