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

Host Web Pages on Google Drive

| Monday, December 3, 2012
Google has added a new feature to Drive: You can now serve up web content from within your Google Drive folder, even ones that run JavaScript. All you need to do is upload your HTML files and assets (e.g., images) and make them public.

The Google Developers site has more details on publishing a folder as a website, but essentially, besides having the folder and site assets public, you also need to link to the files in the folder using a "webViewLink" code. If you don't have an index.html file in the folder, Drive will display a list of the folder's contents.

Read more: Lifehacker

Posted via email from Jasper-net

Немного об интерфейсах в .Net (по мотивам одного интервью)

|
В прошедний понедельник мне посчастливилось попасть на собеседование на Senior .Net Developer в одну международную компанию. Во время собеседования мне предложили пройти тест, где ряд вопросов был связан с .Net. В частности в одном из вопросов надо было дать оценку (истина/ложь) ряду утверждений, среди которых было и такое:

В .Net любой массив элементов, например int[], по умолчанию реализует IList, что позволяет использовать его в качестве коллекции в операторе foreach.

Быстро ответив на этот вопрос отрицательно и отдельно дописав на полях. что для foreach необходима реализация не IList, а IEnumerable, я перешел к следующему вопросу. Однако по дороге домой меня мучал вопрос: реализует ли массив все-таки этот интерфейс или нет?

Про IList я смутно помнил, что этот интерфейс дает мне IEnumerable, индексатор и свойство Count, содержащее число элементов коллекции, а также еще пару редко используемых свойств, типа IsFixedCollection(). Массив имеет свойство Length для своего размера, а Count в IEnumerable является методом расширения от LINQ, что было бы невозможно, если бы этот метод был реализован в классе. Таким образом, получалось, что массив не мог реализовывать интерфейс IList, однако какое-то смутное чувство не давало мне покоя. Поэтому вечером после интервью я решил провести небольшое исследование.

Класс System.Array

Поскольку Reflector.Net у меня не был установлен, я просто написал короткую программку на С# чтобы узнать, что за интерфейсы реализуются целочисленным массивом.

var v = new int[] { 1, 2, 3 };
var t = v.GetType();
var i = t.GetInterfaces();
foreach(var tp in i)
     Console.WriteLine(tp.Name);

Вот полный список полученных интерфейсов из окна консоли:

ICloneable
IList
ICollection
IEnumerable
IStructuralComparable
IStructuralEquatable
IList`1
ICollection`1
IEnumerable`1
IReadOnlyList`1
IReadOnlyCollection`1

...
...

Всё сразу встает на свои места, когда вспоминаешь о том, что в С# можно реализовывать интерфейсы не только 
неявно (implicit), но и явно (explicit). Я знал об этой возможности из учебников, где приводился пример такой имплементации в случае. когда базовый класс уже содержит метод с тем же именем, что и метод интерфейса. Я также видел такую возможность в ReSharper. Однако до настоящего времени мне напрямую не приходилось сталкиваться с необходимостью явной реализации интерфейсов в моих собственных проектах.

Сравнение явной и неявной реализации интерфейсов

Давайте сравним эти два вида реализации интерфейсов:.

Критерии
Неявная (implicit) реализация
Явная (explicit) реализация
Базовый синтаксис
interface ITest { void DoTest(); } public class ImplicitTest : ITest { public void DoTest() { } }

interface ITest { void DoTest(); } public class ExplicitTest : ITest { void ITest.DoTest() { } }

Видимость
Неявная имплементация всегда являелся открытой (public), поэтому к методам и свойствам можно обращаться напрямую.
var imp = new ImplicitTest(); imp.DoTest();

Явная имплементация всегда закрыта (private). 
Чтобы получить доступ к имплементации необходимо кастовать инстанцию класса к интерфейсу (upcast to interface).
var exp = new ExplicitTest(); ((ITest)exp).DoTest();

Полиморфия
Неявная имплементация интерфейса может быть виртуальной (virtual), что позволяет переписывать эту имплементацию в классах-потомках.
Явная имплементация всегда статична. Она не может быть переписана (override) или перекрыта (new) в классах-потомках. Прим. 1
Абстрактный класс и реализация
Неявная реализация может быть абстрактной и реализовываться только в классе-потомке.
Явная реализация не может быть абстрактной, но сам класс может иметь другие абстрактные методы и сам быть абстрактным.Прим. 2

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

Анатомия атаки: Как я взломал StackOverflow

|
Почти два года назад я наткнулся на довольно значительную уязвимость в сети сайтов StackExchange. Я говорю «наткнулся» потому, что я не пытался взломать сайт. Обстоятельства приоткрыли мне дверь. Сама уязвимость является довольно интересной, и содержит урок для всех, кто создает и занимается поддержкой сайтов или серверной инфраструктуры. Итак, вот история о том, как я взломал StackOverflow…

Исходные данные

В то время я работал в небольшой компании, где имелся фаервол с совершенно драконовскими ограничениями. Он резал все заголовки запросов и ответов, не соответствующие спецификации HTTP/1.1 (и даже резал валидные HTTP/1.1 заголовки). Это играло злую шутку с сайтами, которые полагаются на такие вещи, как X-Requested-With. Поэтому, для своих «внешних похождений», я настроил прокси.

У меня было несколько серверов в то время, так что я просто поставил на одном из них Squid. Так как я кое-что соображал, я разрешил подключения к прокси только с 127.0.0.1. Я поднял SSH туннель к серверу и указал браузеру localhost в качестве прокси. Браузер подключался к туннелю, который подключался к Squid'у на сервере. Все было отлично. Кроме того, что весь мой трафик шифровался, я получил возможность нормально пользоваться сайтами.

Для тех из вас, кто хочет мне сказать, что я поступил плохо, я хочу обратить ваше внимание на то, что у меня была возможность сделать это. И не просто возможность, мне открыто было сказано использовать прокси, так как мы должны были работать с некоторыми сайтами, которые не работали через наш фаервол. Так что я не делал ничего «неправильного».

Атака

В то время я часто бывал в чате StackOverflow. Тогда он еще только появился, и в нем была парочка багов. В один прекрасный день сайт начал показывать мне стек вызовов. Я не придал этому значения, так как часто встречался с этим по всему интернету. Вообще-то, почти каждый раз, когда я получал сообщение об ошибке на сайте, написанном на ASP.NET, я видел стек вызовов.

И тут я заметил новый пункт меню в чате. Этот новый пункт меню назывался «Admin». Чисто из любопытства, я нажал на ссылку, полагая, что мне будет отказано в доступе. То, что произошло дальше, удивило меня. Я получил полный доступ ко всему. У меня была консоль разработчика, где я мог видеть кто что делает. У меня был интерфейс для работы с базой данных, где я мог напрямую запрашивать что угодно из любой базы данных. Я получил полные админские права.

Read more: Habrahabr
QR: Inline image 1

Posted via email from Jasper-net

Visual Studio 2012 Image Library - 5,000+ images downloadable now... (Think, flat "modern" images...)

|
The Visual Studio Image Library contains application images that appear in Microsoft Visual Studio, Microsoft Windows, the Office system and other Microsoft software.

Visual Studio 2012 Image Library EULA.rtf, 182 KB

VS2012 Modern Image Library.zip, 19.4 MB

The Visual Studio Image Library contains application images that appear in Microsoft Visual Studio, Microsoft Windows, the Office system and other Microsoft software. The library of over 5,000 images can be used to create applications that look visually consistent with Microsoft software.

...

The image library includes five main categories of images: Common Elements, Actions, Annotations, AppIcons and Objects. Readme files are also included in the PDF format for the Common Elements and Icon types. These readme files include information about how to use these images appropriately in your applications.

QR: Inline image 1

Posted via email from Jasper-net

Understanding the Visual Tree and Logical Tree in WPF

|
Inline image 2

Introduction

This article discusses nuances of and differences between the visual tree and logical tree in WPF. It also presents a small application with which you can investigate this topic further. If you are completely unfamiliar with the concepts of the visual tree and/or logical tree, I suggest you read this page in the SDK documentation first.

Background

The existing documentation about the visual tree and logical tree in the Windows SDK leaves much to be desired. Ever since I started with WPF, I have felt unsure about what exactly differentiates the two. I knew that the logical tree and visual tree both only contain visual elements and controls, right? Wrong. I knew that a Window/Page/Control/etc. contains one and only one logical tree, right? Wrong. I knew what I was doing, right? Wrong.

It turns out that the element trees in WPF are rather complicated and require detailed knowledge of low-level WPF classes to work with them correctly. Walking an element tree in a generic fashion; where you assume no knowledge of its constituents; is not as simple as it might seem. Unfortunately WPF does not publicly expose a class which simplifies walking the element trees to the point where it is "really easy".

At this point you might be wondering what makes walking the element trees so complicated. Good question. The answer has several parts, which are discussed in the following sections.

The Visual Tree

The visual tree represents all of the elements in your UI which render to an output device (typically, the screen). The visual tree is used for many things like rendering, event routing, locating resources (if an element has no logical parent), and more. Walking up and down the visual tree can be a simple matter of just using VisualTreeHelper and some simple recursive methods.

However, there is one wrinkle which makes this a little more complicated. Anything which descends from ContentElement can appear in a user interface, but is not actually in the visual tree. WPF will "pretend" that those elements are in the visual tree, to facilitate consistent event routing, but it's just an illusion. VisualTreeHelper does not work with ContentElement objects because ContentElement does not derive from Visual or Visual3D. Here are all of the classes in the Framework which descend from ContentElement, as seen in Reflector:

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

Mysterious google two step authentication - in debug

|
Introduction 

 I hope you have enabled your google account for two step authentication? If not -I strongly recommend to do so.  Do you know the nature of the code generated by Google Authenticator?  There are no myth here  - this is just implementation of RFC6238. And even more - you can add new level of security to your application very easy without need to use some monstrous security library. 

I will use PHP in this article - this means that server side can use this code to validate the client one. But nothing stops you from implementing OTP generation algorythm in javascript.  

Background 

2-step verification drastically reduces the chances of having the personal information in your Google account stolen by someone else. Why? Because hackers would have to not only get your password and your username, they'd have to get your personal key used to generate 6 digit combination. 

How this combination is generated? Let's move through process:

Assume, that secret code in base32 is  GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ (this is actually base32 encoded secret key  12345678901234567890. 

Why base32 and not base64 is used? My guess takes into consideration following points:

The resulting character set is all one case (usually represented as uppercase), which can often be beneficial when using a case-insensitive filesystem, spoken speech, or human memory.
The alphabet was selected to avoid similar-looking pairs of different symbols, so the strings can be accurately transcribed by hand. (For example, the symbol set omits the symbols for 1, 8 and zero, since they could be confused with the letters 'I', 'B', and 'O'.) 
The result can be included in a URL without encoding any characters. 
in other words  -  encoded message is much easier to remember than base 64.

 Variance of the code is time (to be more precise, it's 30sec intervals). Bearing in mind, that not all devices use ntp to synchronize, we might want to check 3-5 sequential codes to be sure, that right code is entered. The more secure is your solution - the less 30sec intervals you might want to check,

 

 Let us take current Unix Time Stamp: 

UnixTimeStamp (time()/30): 44376117.366667 

and calculate  HOTP - onetime password based on HMAC  (http://en.wikipedia.org/wiki/HOTP) 

What do we need to calculate 6 digit code:

Take trunc of the value above - 44376117 and convert to hex 2a52035

Pack to byte string: 

5(35)
 (20)
¥(a5)
<(2)
 (0)
 (0)
 (0)
 (0) 

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

Новое в рефлексии для .NET 4.5

|
.NET 4.5 включает в себя некоторые изменения к System.Reflection. Самое значительно из них это то, что Type теперь разделён на два отдельных класса: Type и TypeInfo. Объект TypeInfo хранит в себе полное определение, а сам Type теперь хранит только общие данные. Если вы используете рефлексию из вашего десктопного или веб-приложения под NET 4.5, то старое API до сих пор тоже доступно наряду с новыми методами рефлексии. Сегодня я сфокусируюсь на том, как использовать некоторые из основных функций нового API.

Обзор Type и TypeInfo

Класс Type обеспечивает общее проредстваление о структуре объекта. TypeInfo же представляет полное определение объекта, включая его связи с родительским и наследованными классами. Более того, API класса Type было обновлено и теперь возвращает коллекции в виде типизированных IEnumerable, а не как раньше — массивов. В случае больших и сложных сборок это позволяет читать значения результатов рефлексии по одному, а также упрощает использование метаданных типов при помощи LINQ. Приложения Windows Store имеют доступ только к этим новым IEnumerable коллекциям.

Изменения API класса Type

Давайте посмотрим на некоторые метаданные, которые могут быть получены из Type без использования TypeInfo, а затем погрузимся в API TypeInfo. API класса Type позволяет получать общую информацию о типах. Это означает, что вы можете получить такие метаданные как имя, пространство имён, полное имя, модуль и так далее. Это осуществляется через то же самое API как и в .NET 4.0. Например, чтобы получить полное имя и пространство имён некоторого типа, вы можете сделать следующее:

Type stringType = typeof(string);
string fullName = stringType.FullName;
string stringNameSpace = stringType.Namespace;

API TypeInfo

Как вы видите, Type обеспечивает общее представление о структуре класса. Если вы хотите погрузиться немного глубже, то вы можете использовать новое API класса TypeInfo. Значение TypeInfo вы можете получить из Type вызовом его метода GetTypeInfo(). Возьмём, например, класс Person, который содержит в себе свойства имени (FirstName), фамилии (LastName), событие Modified и метод Save:

public class Person 
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public event EventHandler Modified;
    public void Save()
    {
        // сохраняем объект в репозиторий...
    }
}

Теперь допустим, что вам нужно узнать какие свойства, методы и события определены в классе Person. Это можно легко узнать из TypeInfo при помощи его свойств DeclaredProperties, DeclaredMethods и DeclaredProperties:

TypeInfo personInfo = personType.GetTypeInfo();
IEnumerable<PropertyInfo> declaredProperties = personInfo.DeclaredProperties;
IEnumerable<MethodInfo> declaredMethods = personInfo.DeclaredMethods;
IEnumerable<EventInfo> declaredEvents = personInfo.DeclaredEvents;

Другой общей задачей рефлексии является необходимость найти все типы внутри сборки. При помощи обновленного API System.Reflection, класс Assembly теперь возвращает коллекцию TypeInfo вместо массива Type. Например чтобы получить все типы определённые в выполняемой сборке, вы можете использовать свойство TypeInfo.Assembly, а затем прочитать свойство DefinedTypes на полученном объекте Assembly:

Assembly myAssembly = this.GetType().GetTypeInfo().Assembly;
IEnumerable<TypeInfo> myTypes = myAssembly.DefinedTypes;

Read more: Habrahabr
QR:  Inline image 1

Posted via email from Jasper-net

Quick fix for very slow to load “Downloads” folder in Windows 7 & 8

| Sunday, December 2, 2012
Inline image 2

I don’t usually post “tips” but this issue has frustrated me to no end for many months and I finally found a simple but instant effective solution. It’s too good not to spread the word about.

In the last couple of months, I started noticing that clicking the “Downloads” folders in Windows Explorer took around 15 seconds to load. This become quite annoying as I frequently access downloaded files from browsers. I tried deleting clearing out the folder but that didn’t have a lasting effect.

After a bit of research, it turns out apparently Windows 7 (and Windows 8) tries to guess-timate what the contents of the folder are and assigns special “rules” to them to optimize the view settings and sorting.

For some reason, the “Downloads” folder likes to be categorized as a “Pictures” folder (I’m guessing because people store a lot of JPGs in it). The problem with this view is that it tries to generate thumbnails for all the files in this folder, even if they’re not pictures.

The fix is to ensure the folder settings for “Downloads” is optimized for “General items”. This should have an instant effect (the next time you add files to the folder since the thumbnails are otherwise cached anyway).

QR: Inline image 1

Posted via email from Jasper-net

.NET 4.5 Async “ConfigureAwait” – Keep the Synchronization Context in Mind

|
I assume you have heard about the great addition in .NET 4.5 – The Async Keyword.

It is truly one of the key changes made to the .NET language, and it is awesome. 
Asynchrony should be part of our code, there’s no escape from that.

  • If you write UI applications – you need asynchrony to avoid blocking the UI thread.
  • If you make I/O operations – you should use its asynchronous model that utilizes the I/O completion threads instead of occupying a worker thread.
  • If you build a service – you may want to implement the service using the asynchronous approach if you’re doing mainly I/O work.
  • If you want to parallelize your code – you may want to use the TPL and invoke operations asynchronously and in parallel.
  • And more..
Prior to .NET 4.5, the code looks quite awful in terms of all the nested lambda expressions, error handling, and the use of the synchronization context. 
It was also easy to make mistakes writing in this fairly complex paradigm, but I guess it comes down to the developer’s maturity and habits. I specifically got quite used to that by now, so it is all readable to me .

In .NET 4.5, Microsoft introduced us with the new ‘async’ and the ‘await’ keywords. 
The goal of this post isn’t to explain what it does, there are enough resources out there already that you can follow up on if you like to catch up.

I would like to discuss a specific feature of the ‘await’ keyword, which is continuing the execution on the captured synchronization context. 

When you write the following code -

async void Do()
{
    Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
 
    await DoSomethingAsync();
    
    Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
}
 
private Task DoSomethingAsync()
{
    return Task.Run(() =>
        {
            Thread.Sleep(1000);
 
            Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
        });
}

Q: What would be printed in line 7? Would it be the same as in line 3?

QR: Inline image 1

Posted via email from Jasper-net

Visual Studio 2012 Update 1

| Wednesday, November 28, 2012
Visual Studio 2012 Update 1

Visual Studio 2012 Update 1 (Visual Studio 2012.1) provides enhancements and fixes to address a variety of issues reported through Connect and Windows Error Reporting. In addition, Update 1 delivers a wealth of new functionality into Visual Studio 2012. Most of the new functionality appears in Ultimate and Premium, but there are some features for Professional and Express products, too. The new functionality in Update 1 primarily spans four key areas: Windows development, SharePoint development, agile teams, and continuous quality.

Windows development

For the release of Windows 8, Visual Studio 2012 added new templates, designers, and testing & debugging tools to support this new platform, including support for Windows Store apps with the Windows 8 Simulator. Update 1 adds support for mixed-mode (managed/native) debugging of Windows Store apps, and support for native ARM dump debugging. This update also includes code analysis support for Windows Phone 8 apps. But Update 1 isn’t just about new Windows platforms. It also enables you to target Windows XP with native C++ applications in Visual Studio 2012.

SharePoint development

With Update 1, we also invested in expanding our lifecycle tools for SharePoint 2010, especially for testing and quality assurance. You can now use unit tests and coded UI tests for simulating user interaction, including the Microsoft Fakes Framework to stub out SharePoint dependencies. Load testing support enables stress testing of SharePoint applications under simulated load and network conditions. In addition, you can now capture SharePoint logging information using IntelliTrace to provide a rich analysis experience for SharePoint applications.

Agile teams

Visual Studio 2012 brought a lot of new features to support the work of agile teams. Update 1 builds upon these advancements with significant usability improvements in Team Foundation Server’s web interface and a much improved source viewing and diffing experience. Update 1 also includes functionality for Team Foundation Server that first appeared in Team Foundation Service, such as Kanban support with a Kanban board and a cumulative flow diagram. In the IDE, Code Maps enable you to create and view dynamic visualizations of relevant code to understand and navigate its relationships faster.

Continuous quality

Enabling continuous quality is a key focus area of Update 1. Code coverage for automated tests is now available for manual testing, which enables you to analyze which areas of a code base are used during manual testing. Update 1 also supports cross-browser testing, with the ability to record web tests in Internet Explorer and then later replay them with most modern browsers. Using Test Explorer, you can group and run tests based on their traits (Test Category, Test Property, Priority, and Owner). You can also pause and resume manual test sessions in Microsoft Test Manager, and automatically create an image log of all actions performed during an exploratory testing session.

Read more: Visual Studio 
QR: Inline image 1

Posted via email from Jasper-net

Tutorial: The best tips & tricks for bash, explained

| Thursday, November 22, 2012
Running a command from your history
Sometimes you know that you ran a command a while ago and you want to run it again. You know a bit of the command, but you don’t exactly know all options, or when you executed the command. Of course, you could just keep pressing the Up Arrow until you encounter the command again, but there is a better way. You can search the bash history in an interactive mode by pressing Ctrl + r. This will put bash in history mode, allowing you to type a part of the command you’re looking for. In the meanwhile, it will show the most recent occasion where the string you’re typing was used. If it is showing you a too recent command, you can go further back in history by pressing Ctrl + r again and again. Once you found the command you were looking for, press enter to run it. If you can’t find what you’re looking for and you want to try it again or if you want to get out of history mode for an other reason, just press Ctrl + c. By the way, Ctrl + c can be used in many other cases to cancel the current operation and/or start with a fresh new line.

Repeating an argument
You can repeat the last argument of the previous command in multiple ways. Have a look at this example:

[rechosen@localhost ~]$ mkdir /path/to/exampledir
[rechosen@localhost ~]$ cd !$

The second command might look a little strange, but it will just cd to /path/to/exampledir. The “!$” syntax repeats the last argument of the previous command. You can also insert the last argument of the previous command on the fly, which enables you to edit it before executing the command. The keyboard shortcut for this functionality is Esc + . (a period). You can also repeatedly press these keys to get the last argument of commands before the previous one.

Some keyboard shortcuts for editing
There are some pretty useful keyboard shortcuts for editing in bash. They might appear familiar to Emacs users:

  • Ctrl + a => Return to the start of the command you’re typing
  • Ctrl + e => Go to the end of the command you’re typing
  • Ctrl + u => Cut everything before the cursor to a special clipboard
  • Ctrl + k => Cut everything after the cursor to a special clipboard
  • Ctrl + y => Paste from the special clipboard that Ctrl + u and Ctrl + k save their data to
  • Ctrl + t => Swap the two characters before the cursor (you can actually use this to transport a character from the left to the right, try it!)
  • Ctrl + w => Delete the word / argument left of the cursor
  • Ctrl + l => Clear the screen

Dealing with jobs
If you’ve just started a huge process (like backupping a lot of files) using an ssh terminal and you suddenly remember that you need to do something else on the same server, you might want to get the huge process to the background. You can do this by pressing Ctrl + z, which will suspend the process, and then executing the bg command:

[rechosen@localhost ~]$ bg
[1]+ hugeprocess &

Read more: Pinehead.tv

Posted via email from Jasper-net

Microsoft has failed

|
Microsoft is largely irrelevant to computing of late, the only markets they still play in are evaporating with stunning rapidity. Their long history of circling the wagons tighter and tighter works decently as long as there is not a credible alternative, and that strategy has been the entirety of the Microsoft playbook for so long that there is nothing else now. It works, and as the walls grow higher, customer enmity builds while the value of an alternative grows. This cycle repeats as long as there is no alternative. If there is, everything unravels with frightening rapidity.

A company that plays this game for too long becomes set in their ways, and any chance of real change simply becomes impossible. Microsoft is there, and has been for a long long time. Their product lines have stagnated, creating customer lock in is prioritized over creating customer value, and the supply chain is controlled by an iron fisted monopoly. Any attempt at innovation with a Windows PC has been shut out for over a decade, woe betide anyone who tried to buck that trend. The history books are littered with the corpses of companies that tried to make change the ‘Windows experience’. Microsoft’s displeasure is swift and fatal to those that try. Or at least it was.
In the end, Windows advanced only to the point of undercutting any competition, and even then to the minimum extent possible. The rules in Redmond were, “Do not change anything unless it is to crush someone doing something innovative”. They didn’t unless they did, and it worked. And the market stagnated. Ask yourself when the last time Microsoft did something innovative? Did it come from internal impetuses, or a clone of the competition?

Sooner or later, someone will come along and do a better job than the treacle that Microsoft, offers. Actually that happens all the time. How about, sooner or later, someone will come along and do a better job than the treacle that Microsoft offers, and for some reason, Microsoft won’t be able to crush them like a bug. Then the circled wagons have an alternative. Then the decades of built up enmity have an outlet. Then Microsoft is in trouble.

In such a situation, a company has two choices, both of which are quite stark. They can radically change their ways or they can wither and die. Before you point to Windows 8 and say, “But they are changing and innovating”, hold off a moment, it isn’t what you think.

Microsoft has three product lines that underpin everything, Windows, Windows Server, and Windows Mobile/Phone/WART/whatevertheynameitthisweek. On those, the other moneymakers, Office and Exchange, run exclusively. The apps use protocols that are locked down with dubious methods, and will not run on any competition. The competition is likewise excluded from doing what Microsoft can, either directly like Novell, or by raising the cost to the point of it not being profitable. This is how the wagons are circled, with every iteration, the cost of competing go up, and value of alternatives go up too.

Read more: SemiAccurate

Posted via email from Jasper-net

How do I forward an exported function to an ordinal in another DLL?

|
The syntax for specifying that requests to import a function from your DLL should be forwarded to another DLL is

; A.DEF
EXPORTS
 Dial = B.Call
This says that if somebody tries to call Dial() from A.DLL, they are really calling Call() in B.DLL. This forwarding is done in the loader. Normally, when a client links to the function A!Dial, the loader says, "Okay, let me get the address of the Dial function in A.DLL and store it into the __imp__Dial variable." It's the logical equivalent of

client::__imp__Dial = GetProcAddress(hinstA, "Dial");
When you use a forwarder, the loader sees the forwarder entry and says, "Whoa, I'm not actually supposed to get the function from A.DLL at all! I'm supposed to get the function Call from B.DLL!" So it loads B.DLL and gets the function Call from it.

hinstB = LoadLibrary("B.DLL");
client::__imp__Dial = GetProcAddress(B, "Call");
(Of course, the loader doesn't actually do it this way, but this is a good way of thinking about it.)

But what if the function Call was exported by ordinal? How do you tell the linker, "Please create a forwarder entry for Dial that forwards to function 42 in B.DLL?"

I didn't know, but I was able to guess.

Back in the days of 16-bit Windows, there were two ways to obtain the address of a function exported by ordinal. The first way is the way most people are familiar with:

FARPROC fp = GetProcAddress(hinst, MAKEINTRESOURCE(42));
The second way uses an alternate formulation, passing the desired ordinal as a string prefixed with the number-sign:

FARPROC fp = GetProcAddress(hinst, "#42");

Read more: The old new thing

Posted via email from Jasper-net

Elementary OS

|
Hello, Luna Beta 1

Developers and testers, today we are happy to announce the first beta release of elementary OS Luna. We've been working hard the past year and a half to create the next generation of elementary, and it begins with this beta.

What’s New

Luna is our greatest undertaking yet, and along with it have come many new apps, features and development libraries. By integrating and innovating with the latest technologies, we’re building a platform that free software developers can be excited about.

Pantheon

Inline image 1

Underlying Technologies

Luna is powered by newer technologies, both developed by elementary and other open source projects, bringing a wide number of improvements to the OS.
Below the UI, elementary OS uses the Linux kernel. The kernel has seen significant improvements, including wider hardware compatibility, better wireless drivers, improved graphics drivers, and many low-level advancements.

Throughout the OS we’ve focused on pushing GTK3 as much as possible. Every default user-oriented app uses GTK3, meaning they take advantage of our sleek new theme.

During the Luna cycle, we’ve built out our user interface technology, Granite. Granite is an extension of GTK, providing a select number of improved, useful, well-designed, and consistent widgets for apps. Granite now includes a welcome screen, thin panes, popovers, modebuttons, static notebook, dynamic notebook, decorated window, source list, and the about dialog. Each of these widgets are available to app developers and are used throughout the OS, bringing beautiful design and both visual and behavioral consistency between apps.

Read more: Elementary OS

Posted via email from Jasper-net

Adventures in Microsoft UEFI Signing

|
As I explained in my previous post, we have the code for the Linux Foundation pre-bootloader in place.  However, there was a delay while we got access to the Microsoft signing system.

The first thing you have to do is pay your $99 to Verisign (now Symantec) and get a verified by Verisign key.  We did this for the Linux Foundation, and all they want to do is call head office to verify. The key comes back in a URL that installs it in your browser, but the standard Linux SSL tools can be used to extract this and create a usual PEM certificate and key.  This is nothing to do with UEFI signing, but it’s used to validate to the Microsoft sysdev system that you are who you say you are.  Before you can even create a sysdev account, you have to prove this by signing an executable they give you and upload it.  They make strict requirements that you sign it on a specific Windows platform, but sbsign worked just as well and bingo our account is created.

Once the account is created, you still can’t upload UEFI binaries for signature without first signing a paper contract.  The agreements are pretty onerous, include a ton of excluded licences (including all GPL ones for drivers, but not bootloaders).  The most onerous part is that the agreements seem to reach beyond the actual UEFI objects you sign.  The Linux Foundation lawyers concluded it is mostly harmless to the LF because we don’t ship any products, but it could be nasty for other companies.  According to Matthew Garrett, Microsoft is willing to negotiate special agreements with distributions to mitigate some of these problems.

Once the agreements are signed then the real technical fun begins.  You don’t just upload a UEFI binary and have it signed.  First of all you have to wrap the binary in a Microsoft Cabinet file.  Fortunately, there is one open source project that can create cabinet files called lcab. Next you have to sign the cabinet file with your Verisign key.  Again, there is one open source project that can do this: osslsigncode. For anyone else needing these tools, they’re now available in my openSUSE Build Service UEFI repository. The final problem is that the file upload requires silverlight.  Unfortunately, moonlight doesn’t seem to cut it and even with the version 4 preview, the upload box shows up blank, so time to fire up windows 7 under kvm. When you get to this stage, you also have to certify that the binary “to be signed must not be licensed under GPLv3 or similar open source licenses”.  I assume the fear here is key disclosure but it’s not at all clear (or indeed what “similar open source licences” actually are).

Once the upload is done, the cabinet file goes through seven stages.  Unfortunately, the first test upload got stuck in stage 6 (signing the files).  After about 6 days, I sent a support email in to Microsoft asking what was going on.  The response: “The error code thrown by our signing process  is that your file is not a valid Win32 application? Is it valid Win32 application?”.  Reply: obviously not, it’s a valid UEFI 64 bit binary.  No further response …

Posted via email from Jasper-net

Using Reactive Extensions with Mono

|
I first learned about Reactive Extensions (Rx) begin this month when it was open sourced by Microsoft. Although I found a few scattered references on the internet on how to get Rx working with Mono, I had to jump through quite a few hoops. This blogpost is a detailled account and will hopefully save you a couple of hours.

Getting Reactive Extensions
When you are using Windows this is pretty straightforward. But then again, in that case you are probably using .NET and not reading this blogpost at all. However when you are using Linux or OS-X it gets a bit more complicated. In that case your only option is to use NuGet.

Getting NuGet

I didn’t download the recommended version (NuGet.exe Bootstrapper 2.0) but used the NuGet.exe Command Line. This didn’t work out of thebox. According to this excellent blog post you first have to import some root certificates so that Mono will trust NuGet:

$ mozroots --import --sync

Next you type:

$ mono NuGet.exe

This will result in output similar to:

NuGet bootstrapper 1.0.0.0
Found NuGet.exe version 2.1.2.
Downloading…
Update complete.

You now have NuGet running. To get help type:

$ mono NuGet.exe help

Getting Rx-Main

Ok, so let’s finally get Rx. I started with the latest and greatest (Rx-Main 2.0.21114 at the moment of writing) but I didn’t get that working. However version Rx-Main 1.0.11226 does seem to work with Mono. To see all available versions enter:

$ mono NuGet.exe list Rx-Main -AllVersions

To install the latest Rx 1.0 enter:

$ mono NuGet.exe install Rx-Main -Version 1.0.11226

This will download Rx-Main into your current working directory. You can find the dll you need as: ./Rx-Main.1.0.11226/lib/Net4/System.Reactive.dll

Posted via email from Jasper-net

Step-By-Step Guide to Controlling Device Installation Using Group Policy

| Wednesday, November 21, 2012
Summary: By using the Windows Server 2008 and Windows Vista operating systems, administrators can determine what devices can be installed on computers they manage. The guide summarizes the device installation process and demonstrates several techniques for controlling device installation. (34 printed pages.)

Contents

Introduction
   Who Should Use This Guide?
   Benefits of Controlling Device Installation Using Group Policy
Scenario Overview
Technology Review
   Device Installation in Windows
   Group Policy Settings for Device Installation
   Group Policy settings for Removable Storage Access
Requirements for completing the scenarios
   Prerequisite Procedures
Prevent installation of all devices
   Prerequisites for preventing installation of all devices
   Steps for preventing installation of all devices
Allow users to install only authorized devices
   Prerequisites for allowing users to install only authorized devices
   Steps for allowing users to install only authorized devices
Prevent installation of prohibited devices
   Prerequisites for preventing installation of prohibited devices
   Steps for preventing installation of prohibited devices
Control read and write permissions on removable media
   Prerequisites for controlling read and write permissions on removable media
   Steps for controlling read and write permissions on removable media
Conclusion
Additional resources
Logging bugs and feedback


Introduction


This step-by-step guide describes how you can control device installation on the computers that you manage, including designating which devices users can and cannot install. Specifically, in Windows Server 2008 and Windows Vista you can apply computer policy to:


Prevent users from installing any device.

Allow users to install only devices that are on an "approved" list. If a device is not on the list, then the user cannot install it.

Prevent users from installing devices that are on a "prohibited" list. If a device is not on the list, then the user can install it.

Deny read or write access to users for devices that are themselves removable, or that use removable media, such as CD and DVD burners, floppy disk drives, external hard drives, and portable devices such as media players, smart phones, or Pocket PC devices.

This guide describes the device installation process and introduces the identification strings that Windows uses to match a device with the device driver packages available on a computer. The guide also illustrates three methods of controlling device installation. Each scenario shows, step by step, one method you can use to allow or prevent the installation of a specific device or a class of devices. The fourth scenario shows how to deny read or write access to users for devices that are removable or that use removable media.


Read more: MSDN


Posted via email from Jasper-net

Using Caller Info Attributes in .NET 4.5

|
Introduction

When developing complex .NET applications sometimes you need to find out the details about the caller of a method. .NET Framework 4.5 introduces what is known as Caller Info Attributes, a set of attributes that give you the details about a method caller. Caller info attributes can come in handy for tracing, debugging and diagnostic tools or utilities. This article examines what Caller Info Attributes are and how to use them in a .NET application.  

Overview of Caller Info Attributes

Caller Info Attributes are attributes provided by the .NET Framework (System.Runtime.CompilerServices) that give details about the caller of a method. The caller info attributes are applied to a method with the help of optional parameters. These parameters don't take part in the method signature, as far as calling the method is concerned. They simply pass caller information to the code contained inside the method. Caller info attributes are available to C# as well as Visual Basic and are listed below:

Caller Info Attribute Description
CallerMemberName This attribute gives you the name of the caller as a string. For methods, the respective method names are returned whereas for constructors and finalizers strings ".ctor" and "Finalizer" are returned.
CallerFilePath This attribute gives you the path and file name of the source file that contains the caller.
CallerLineNumber This attribute gives you the line number in the source file at which the method is called.
A common use of these attributes will involve logging the information returned by these attributes to some log file or trace.

Using Caller Info Attributes

Now that you know what Caller Info Attributes are, let's create a simple application that shows how they can be used. Consider the Windows Forms application shown below:

Read more: Codeguru

Posted via email from Jasper-net

MediaSuite.NET

|
Overview:

MediaSuite.NET is the independent Multimedia Framework for Microsoft .NET. Providing unmatched performance and flexibility for all your Multimedia needs. Self contained and independent of other frameworks such as Directshow, Media Foundation or FFmpeg, MediaSuite.NET features all aspects usually only provided through native frameworks and functionality sold by multiple vendors. With MediaSuite, everything is in the box. Ready for use commercially.

Sample Code:

RTP Reception, H.263 decoding and display

  • CamCapture.NET, WaveInput & WaveOutput
  • Audio Encoder/Decoder setup and feedback loop
  • Using AVIWriter.NET
  • Using MP4Writer.NET
  • Using MP4Toolkit
  • Using Resampler.NET
  • Encoding and sending G.711 over RTP
  • Receiving G.711 over RTP, decoding & Playout
  • Generating DTMF Tones
  • How to extract information from a FLV (Flash Video) file
  • RTP Send & Receive symmetric using RTPSession with one participant

Summary:

I hope this post will be useful for people who work with video and audio in Microsoft.NET environment.

Posted via email from Jasper-net

Step by step guide to setting up Xen and XAPI (XenAPI) on Ubuntu 12.04 and managing it with Cirtix XenCenter

| Monday, November 19, 2012
XCP ( Xen Cloud Platform ) is the open source version similar to Citrix XenServer that uses the Xen Hypervisor. It is currently distributed as an ISO installer also called as XCP appliance. XCP uses XAPI or XenAPI to manage Xen hosts. XCP is based on CentOS 5.5

Project Kronos is an initiative to port the XAPI  tool stack to Debian and Ubuntu. It is a management stack implemented in OCaml that configures and controls Xen hosts, attached storage, networking and virtual machine life cycle.  It exposes a HTTP API and provides a command line interface (xe) for resource management.

XenCenter is windows desktop application by Citrix that is distributed with XenServer for managing servers running XenServer. It uses XAPI for talking to Xen resource pools. Since we are setting up XAPI, we can use XenCenter to manage the server

Why use XCP-XAPI on Debian/Ubuntu when XCP appliance exists ?

  • Manage dom0 using a configuration management framework (Puppet, Chef)
  • Apply security updates to dom0 root file system
  • Run Xen version 4.1. XCP appliance runs version <to be filed>
  • Ubuntu 12.04 is a LTS release that is supported for 5 years
Prerequisites

  • A fresh installation of Ubuntu 12.04 on the server
  • Small root file system partition – I usually have a 10GB partition for  root fs (/) and the rest of the space is setup as a physical volume for setting up LVM later. This LVM partition will be used for vm storage and snapshots later. You can choose any partition layout that you are comfortable with, just remember to keep the root partition small and have a large space dedicated for a LVM volume
  • root access to the host
Installing and configuring Xen Hypervisor

Install the Xen Hypervisor
  1. $sudo apt-get install xen-hypervisor
  2. Setup GRUB to boot the Xen Hypervisor
  • $sudo sed -i ‘s/GRUB_DEFAULT=.*\+/GRUB_DEFAULT=”Xen 4.1-amd64″/’ /etc/default/grub
  1. Disable apparmor at boot
  •  $sudo sed -i ‘s/GRUB_CMDLINE_LINUX=.*\+/GRUB_CMDLINE_LINUX=”apparmor=0″/’ /etc/default/grub
  1. Restrict dom0 to 2GB of memory and 2 vcps
  • $sudo vi /etc/default/grub
after GRUB_CMDLINE_LINUX=”apparmor=0″  add the line GRUB_CMDLINE_XEN=”dom0_mem=2G,max:2G dom0_max_vcpus=2″
  1. Update Grub with the config changes we just made
  • $sudo  update-grub
  1. Reboot the server so that Xen boots on the server
  • $sudo reboot
  1. Once the server is back online ensure that Xen is running
  • cat /proc/xen/capabilities should display “control_d”
Installing and configuring XAPI (XenAPI)

  1. Install XCP-XAPI
QR: Inline image 1

Posted via email from Jasper-net