Wednesday, December 15, 2010

Configuration of Windows Remote Management for PowerShell

1.   winrm quickconfig

PS C:\Windows\system32> Winrm quickconfig
WinRM already is set up to receive requests on this machine.
WinRM is not set up to allow remote access to this machine for management.
The following changes must be made:

Create a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
Enable the WinRM firewall exception.

Make these changes [y/n]? y

WinRM has been updated for remote management.

Created a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
WinRM firewall exception enabled.
PS C:\Windows\system32>

2.  winrm quickconfig -transport:https

PS C:\Windows\system32> winrm quickconfig -transport:https
WinRM already is set up to receive requests on this machine.
WinRM is not set up to allow remote access to this machine for management.
The following changes must be made:

Create a WinRM listener on HTTPS://* to accept WS-Man requests to any IP on this machine.
Configure CertificateThumbprint setting for the service, to be used for CredSSP authentication.

Make these changes [y/n]? y

WinRM has been updated for remote management.

Created a WinRM listener on HTTPS://* to accept WS-Man requests to any IP on this machine.
Configured CertificateThumbprint setting for the service.

3. Listener and WS-Management protocol Default Settings

winrm enumerates winrm/config/listener

4. Remote Admin IIS for TFS 2010 Builds

Enable IIS7 PowerShell snapin in PowerShell session

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Import-Module webadministration | Out-Null

P.S. PowerShell is installed by default on Windows Server 2008 R2

Tuesday, December 14, 2010

Set-ExecutionPolicy in PowerShell

To alllow all user to execute scripts in PowerShell:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted

Wednesday, December 8, 2010

"Load needed DLLs for kernel": Windows recovery console example

Lately I read a lot of people are having this error which stops your system from booting.
This is a very awful error which is solved by Microsoft with the solution to do a in-place install from Windows XP. This is a lot of work and I have a much safer and fast solution.
Boot your system from the Windows XP Cdrom and choose to repair your system which will put you in the "Recovery Console" mode.

Now make the following steps:

CHKDSK (which will fix the error(s) on your disk)
BOOTCFG /rebuild (you will rebuild your boot configuration now, 
just give enters when it asked extra info).
FIXBOOT (to fix your current bootsector)
FIXMBR (to fix your current master boot record).
EXIT (leaves the recovery console and reboots your system).

All should be fine now, however sometimes it is possible that you have to choose which operating system needs to be booted every time you switch on your system.

This can be easily solved when you are in Windows XP:
Go to START > right mouse button on MY COMPUTER > click PROPERTIES > click ADVANCED tab > in startup recovery click SETTINGS > choose your default operating system which is Windows XP > uncheck TIME TO DISPLAY LIST OF OPERATING SYSTEMS > click OK > click OK again.
This is all, your system will boot normally again.

Features about some commands:

bootcfg /rebuild

This utility will scan all your hard drive for any windows xp installations
and then displays the result.

The first prompt asks Add installation to boot list (Yes/No/All)
This is the name of the operating system, for example, type Windows XP Home and press enter.

The final prompt will be Enter OS load options:
Type /Fastdetect and press enter.

Additional command could be helpful:

bootcfg /scan
bootcfg /add

Saturday, September 4, 2010

Twitter auth changes

There are over 250,000 applications built using the Twitter API. To use most applications, you first authorize the application to access your Twitter account, after which you can use it to read and post Tweets, discover new users and more. Applications come in many varieties, including desktop applications like TweetDeck, Seesmic, or EchoFon, websites such as TweetMeme, fflick, or Topsy, or mobile applications such as Twitter for iPhone, Twitter for Blackberry, or Foursquare.
Update 1: New authorization rules for applications
Starting August 31, all applications will be required to use “OAuth” to access your Twitter account.
What's OAuth?
  • OAuth is a technology that enables applications to access Twitter on your behalf with your approval without asking you directly for your password.
  • Desktop and mobile applications may still ask for your password once, but after that request, they are required to use OAuth in order to access your timeline or allow you to tweet.
What does this mean for me?
  • Applications are no longer allowed to store your password.
  • If you change your password, the applications will continue to work.
  • Some applications you have been using may require you to reauthorize them or may stop functioning at the time of this change.
  • All applications you have authorized will be listed at
  • You can revoke access to any application at any time from the list.

Update 2: URL wrapping
In the coming weeks, we will be expanding the roll-out of our link wrapping service, which wraps links in Tweets with a new, simplified link. Wrapped links are displayed in a way that is easier to read, with the actual domain and part of the URL showing, so that you know what you are clicking on. When you click on a wrapped link, your request will pass through the Twitter service to check if the destination site is known to contain malware, and we then will forward you on to the destination URL. All of that should happen in an instant.
You will start seeing these links on certain accounts that have opted-in to the service; we expect to roll this out to all users by the end of the year. When this happens, all links shared on or third-party apps will be wrapped with a URL.
What does this mean for me?

Thursday, July 15, 2010

HTML5 Mobile App Framework

Sunday, July 4, 2010

Convert .dmg files to .iso files

hdiutil convert /path/to/filename.dmg -format UDTO -o /path/to/savefile.iso

Wednesday, June 30, 2010

Business Logic Toolkit for .NET


Tuesday, June 29, 2010

Анонимная рекурсия на C# и лямбды

Лямбды есть анонимные функции, а рекурсия требует определения имен.
Определение функции, которая вычисляет число Фибоначчи:

Func fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

Но работать это не будет, т.к. компилятор выдаст ошибку:
Use of unassigned local variable 'fib'

Проблема в том, что правая сторона выражения оценивается до того, как fib будет определена.

Быстрый обход этой проблемы - присвоить fib null, то есть явно определить fib перед тем, как она будет использована.

Func fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Console.WriteLine(fib(6));                        // displays 8

Но это решение не является настоящей рекурсией. Рекурсия требует, чтобы функция вызывала саму себя. В данном случае функция fib просто вызывает делегат, на который ссылается локальная переменная fib. На первый вгзгляд, это игра слов, но рассмотрим следующий пример:

Func fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Func fibCopy = fib;
Console.WriteLine(fib(6));                        // displays 8
Console.WriteLine(fibCopy(6));                    // displays 8
fib = n => n * 2;
Console.WriteLine(fib(6));                        // displays 12
Console.WriteLine(fibCopy(6));                    // displays 18

Можно заметить, как меняется результат вызова fib и даже вызов fibCopy отличается от вызова fib. Этот беспредел можно остановить, передавая функцию, которая будет использоваться для рекурсивного вызова:

(f, n) => n > 1 ? f(f,n - 1) + f(f,n - 2) : n

Таким образом, лямбда выглядит почти так же за тем исключением, что она первым параметром принимает функцию f. Когда вызывается фунцкия f, нужно передать ее в себя первым аргументом.

Чтобы это реализовать и преобразовать лямбду к делегату, необходимо определить тип делегата. Начнем с типа fib, Func. Возвращаемый тип - int, принимаемым вторым аргументов типом также должен быть int. Что касается первого аргумента, им должен быть делегат, который должен вызываться с теми же аргументами, которые мы определяем в данном случае, что и есть рекурсия:

delegate int Recursive(Recursive r, int n);

Этот делегат можно обобщить через параметризацию аргумента и возвращаемого типа:

delegate R Recursive(Recursive r, A a);

Теперь можно использовать лямбду, определенную выше:

Recursive fib = (f, n) => n > 1 ? f(f,n - 1) + f(f,n - 2) : n;
Console.WriteLine(fib(fib,6));                      // displays 8
Хотя это является решением, выглядит оно не так красиво, как первоначальный код...

(продолжение следует)

Friday, June 11, 2010

Ошибки файловых операций - I/O Error

Исходный список можно посмотреть здесь:

Интерес представляют 4 и 6, поскольку в последнее время часто приходилось сталкиваться с этим.
Такой файл средствами .NET невозможно ни удалить, ни переименовать.
Вкратце одно из возможных решений:
1. Преобразовать файл к короткому имени.
2. Выполнить копирование файла в новое имя при помощи CopyFileEx

  1.     [Flags]
  2.     public enum CopyFileFlags : uint
  3.     {
  4.       COPY_FILE_FAIL_IF_EXISTS = 0x00000001,
  5.       COPY_FILE_RESTARTABLE = 0x00000002,
  6.       COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,
  8.     }
  10.     public enum CopyProgressCallbackReason : uint
  11.     {
  12.       CALLBACK_CHUNK_FINISHED = 0x00000000,
  13.       CALLBACK_STREAM_SWITCH = 0x00000001
  14.     }
  16.     public enum CopyProgressResult : uint
  17.     {
  19.       PROGRESS_CONTINUE = 0,
  20.       PROGRESS_CANCEL = 1,
  21.       PROGRESS_STOP = 2,
  22.       PROGRESS_QUIET = 3
  23.     }
  25.     public delegate CopyProgressResult CopyProgressRoutine(
  26.       long totalFileSize,
  27.       long totalBytesTransferred,
  28.       long streamSize,
  29.       long streamBytesTransferred,
  30.       uint dwStreamNumber,
  31.       CopyProgressCallbackReason dwCallbackReason,
  32.       IntPtr hSourceFile,
  33.       IntPtr hDestinationFile,
  34.       IntPtr lpData);
  36.     public static bool XCopy(string oldFile, string newFile)
  37.     {
  38.       var pbCancel = 0;
  39.       return CopyFileEx(oldFile, newFile, CopyProgressHandler, IntPtr.Zero, ref pbCancel, CopyFileFlags.COPY_FILE_RESTARTABLE);
  40.     }
  42.     public static CopyProgressResult CopyProgressHandler(long total, long transferred, long streamSize,
  43.                                long streamByteTrans, uint dwStreamNumber,
  44.                                CopyProgressCallbackReason reason, IntPtr hSourceFile,
  45.                                IntPtr hDestinationFile, IntPtr lpData)
  46.     {
  47.       return CopyProgressResult.PROGRESS_CONTINUE;
  48.     }
  50.     [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  51.     [return: MarshalAs(UnmanagedType.Bool)]
  52.     public static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName,
  53.                        CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel,
  54.                        CopyFileFlags dwCopyFlags);
  56.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  57.     public static extern int GetShortPathName([MarshalAs(UnmanagedType.LPTStr)] string path,
  58.                          [MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,
  59.                          int shortPathLength);
  62.     public static string UPath(string path)
  63.     {
  64.       const string PreNet = @"\\?\UNC\";
  65.       const string PreLoc = @"\\?\";
  67.       var isNetworkPath = path.StartsWith(@"\\");
  68.       var pre = isNetworkPath ? PreNet : PreLoc;
  69.       var res = path.StartsWith(pre) ? path : pre + path;
  71.       return res.EndsWith(@"\") ? res.Substring(0, res.Length - 1) : res;
  72.     }
  74.     public static FileInfo XCopy(FileInfo fileInfo, string target)
  75.     {
  76.       var filename = Win32IOManaged.UPath(Path.GetDirectoryName(fileInfo.FullName)) + @"
  77. \" + fileInfo.Name;
  78.       var buffer = new StringBuilder(255);
  79.       var length = Win32IOManaged.GetShortPathName(filename, buffer, buffer.Capacity);
  81.       if (length <= 0)
  82.       {
  83.         return null;
  84.       }
  86.       var result = Win32IOManaged.XCopy(buffer.ToString(), target);
  87.       var lasterror = Marshal.GetLastWin32Error();
  89.       if (!result || lasterror != 0)
  90.       {
  91.         return null;
  92.       }
  94.       return new FileInfo(target);
  95.     }
* This source code was highlighted with Source Code Highlighter.

Monday, June 7, 2010

CallContext Data Slots, CallContext

CallContext - удобный способ обмена информации между клиентом и сервером.
CallContext записывает данные в Thread Local Storage.

Чтобы для каждого потока информация была уникальной, необходимо использовать методы
SetData и GetData, но передаваться через границы AppDomain они будут только в том случае, если унаследованы от интерфейса ILogicalThreadAffinative.
Объекты, сохраненные через метод LogicalSetData, будут передаваться через границы домена даже в том случае, если они не унаследованы от ILogicalThreadAffinative.

Logical[Get/Set]Data добавляет/удаляет значения из Hashtable. 
Hashtable живёт в инстансе класса LogicalCallContext, который, в свою очередь, живёт внутри ExecutionContext, а тот — внутри Thread. Чтобы не разматывать весь стек: при переходе в новый контекст вызывается метод LogicalCallContext.Clone, а при возврате — LogicalCallContext.Merge.
Merge заменяет значения в Hashtable теми, что были установлены в новом контексте. 

И может выполниться в другом потоке, если EndInvoke был вызван асинхронно В результате значение вот этого абсолютно непредсказуемо:
Stack<int> stack = (Stack<int>)(CallContext.LogicalGetData("MyContext"));
Вот дополнительная информация:

The LogicalCallContext is able to flow bi-directionally through an async invocation or a .net remoting call. When you call EndInvoke, the child context's LogicalCallContext is merged back into the parent's, as you have observed. This is intentional, so that callers of remote methods can get access to any values set by the remote method. You can use this feature to flow data back from the child, if you'd like.
Debugging this with the help of the .NET Framework source stepping, there are explicit comments to this effect:

in System.Runtime.Remoting.Proxies.RemotingProxy.Invoke:
    case Message.EndAsync: 
         // This will also merge back the call context
         // onto the thread that called EndAsync
         RealProxy.EndInvokeHelper(m, false);
in System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper:
    // Merge the call context back into the thread that
    // called EndInvoke 
If you want to avoid having the data merge, it's pretty easy to skip, just avoid calling EndInvoke from the main thread. You could for example use ThreadPool.QueueUserWorkItem, which will flow the LogicalCallContext in but not out, or call EndInvoke from an AsyncCallback.
Looking at the example on the Microsoft Connect site, the reason that you're not seeing the LogicalSetData value get flowed back from the RunWorkerCompleted call is that BackgroundWorker does not flow the context back. Also, remember that LogicalSetData is not the same as thread-local storage, so it doesn't matter that RunWorkerCompleted happens to be running on the UI thread -- the LogicalCallContext there is still a child context, and unless the parent explicitly flows it back by calling EndInvoke from the spawning thread, it will be abandoned. If you want thread-local storage, you can access that from Thread, like so:

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        Thread.SetData(Thread.GetNamedDataSlot("foo"), "blah!!");

    private void button1_Click(object sender, EventArgs e)
        var val = (string)Thread.GetData(Thread.GetNamedDataSlot("foo"));
        MessageBox.Show(val ?? "no value");


Recently I was working on a server side caching strategy for permissions data. The key to the strategy was to place a user's permissions returned from a database call into the CallContext of WCF service. The code to do this looked something like this...

CallContext.SetData("permissionsKey", myPermissionsData);

All subsequent requests for permissions data would then be returned from the CallContext's cache permissions, thereby saving me from having to make redundant database calls for data that I already have.

myPermissionsData = (PermissionData)CallContext.LogicalGetData("permissionsKey")

Simple caching strategy...

During my testing I found that my cached data was not being returned. After further investigation I realized that I was setting the data using the CallContext's SetData method, but I was getting the data using the CallContext's LogicalGetData method. Come to find out, these are not the same. Seems there is a LogicalGetData method, LogicalSetData method, GetData method and SetData method on the CallContext object. So, it was a simple fix to use the LogicalSetData method in conjunction with the LogicalGetData method when implementing my caching strategy.

But why are there two methods that seemingly do the same thing? The documentation on MSDN doesn't really specify the differnce between the two.

Well... after doing some resarch and finding a post by Lucian Bargaoanu on the subject it seems that the difference has to do with AppDomains. Come to find out there is a LogicalCallContext and an IllogicalCallContext. LogicalCallContext will flow across appdomains. It will do this regardless of what type of object you have placed in context. The object doesn't have to implement ILogicalThreadAffinitive. When you call SetData with an ILogicalThreadAffinitive object, the data is set in the LogicalCallContext. When you call GetData it will first look in the LogicalCallContext and then in the IllogicalCallContext. You cannot have the same key in both CallContext(s).

In summary, objects stored using SetData will only flow across AppDomains if they implement ILogicalThreadAffinitive. Objects stored in LogicalSetData will flow across AppDomains even if they don't implement ILogicalThreadAffinitive. LogicalSetData handles seems to handle the ILogicalThreadAffinitive implementation for you.

Friday, June 4, 2010

Y Combinator

Wednesday, June 2, 2010

Flash Cookies and Supercookies

Дополнительная ссылка:
Сниффинг истории посещений через чтение ‘visited’ стиля ссылок и через Cache timing

Several browsers give you the option to select a privacy option that supposedly lets you surf the Web without leaving fingerprints. Don't believe it.
That option generally stops the browser from storing the URLs of pages you've visited in a pull down under the browser bar or recently visited tab. But it does nothing to conceal the pages and images you've viewed from advertisers who want to serve tailored ads to you, or even worse, from assorted snoops including private detectives and law enforcement agents.
The old solution, simply deleting cookies or clicking a setting that keeps your browser from accepting them, is much less effective than it used to be. That's because many Web sites are now using something called a "Flash cookie," which is maintained by the Adobe Flash plug-in on behalf of Flash applications embedded in Web pages, says Peter Eckersley a researcher with the Electronic Frontier Foundation.
Unlike standard cookies, flash cookies and a variation known as a supercookie are stored outside of the browser's control and users cannot view or directly delete them and they never expire. Flash cookies can track users in all the ways traditionally HTTP cookies do, and can be stored or retrieved whenever a user accesses a page containing a Flash application, says Eckersley. 

Data Structures And Algorithms Alfred V. Aho

Tuesday, June 1, 2010


DryadLINQ is a simple, powerful, and elegant programming environment for writing large-scale data parallel applications running on large PC clusters.

Differential Privacy

Friday, May 7, 2010

Grand Central Dispatch, Apple

Только что обнаружил:
технология Apple предназначенная для создания приложений, использующих преимущества многоядерных процесссоров и других SMP-систем[1]. Эта технология является реализацией параллелизма задач и основана на шаблоне проектирования "Пул потоков". GCD впервые была представлена в Mac OS X 10.6. Исходные коды библиотеки libdispatch, реализующей сервисы GCD, были выпущены под лицензией Apache 10 сентября 2009 г.[1]. Впоследствии библиотека была портирована[2] на другуюоперационную систему FreeBSD [3].

Ссылки для дополнительного изучения:Блоки_(расширение_языка_Си)

В связи с чем: Ruby поддерживает GCD в отличие от остальных динамических языков.

Historically, the Ruby language has been firmly founded in the single-processor paradigm. Mainline Ruby uses green threads to simulate multiprocessing in Ruby; unfortunately, it’s difficult to properly harness the power of multicore processors with green threads. In late 2009, MacRuby bridged Ruby threads to native threads and removed the Global Interpreter Lock. Recently, however, MacRuby took a step forward that no other Ruby implementation – indeed, no other dynamic language – has offered: support for Apple’s Grand Central Dispatch library.
Grand Central Dispatch, or GCD, is a technology designed to let programmers easily harness the power of multi-core processors. GCD hides the details of creating, managing, and destroying POSIX threads from the programmer, making it trivial to write programs that take full advantage of the power of multicore and multiprocessor systems. GCD is built into the foundations of Mac OS X, implemented in both the kernel and userspace, and is so remarkably efficient that it’s being used within system frameworks such as Cocoa and CoreFoundation.

Thursday, May 6, 2010

Monday, May 3, 2010


Sunday, May 2, 2010

Google labs

Social Graph

HackDay -- это два дня работы, в течении которых участники делают решительный шаг от обсуждения идей к их практической реализации.
В этот раз HackDay будет посвящен разработкам в области медиа и контента. Мы приглашаем три категории участников:
(1) профессионалов медиа - журналистов, редакторов, сотрудников IT отделов, операторов, ведущих, актеров, режиссеров и блоггеров;
(2) программистов, дизайнеров и продюсеров интернет-проектов;
(3) студентов технических и медийных направлений.

Будет идти работа над проектами в трех направлениях:
   1. IT-проекты, ориентированные на сбор, обработку, представление и потребление контента во всех его проявлениях, приложения для мобильных устройств, электронных книг и планшетных компьютеров, проекты под iPad, iPhone, Android и другие мобильные операционные системы. Интерфейсы для чтения и обмена новостями, трансляции событий в реальном времени. Мы будем рады и IT проектам, не относящимся к медиа.
   2. Производство наполнения СМИ в новых форматах -- видео, подкасты, контент собранный по социальным сетям. Применение уже существующих и новых технологий в СМИ и в онлайне, использование твиттера, контакта и фейсбука в журналистике. Визуализация данных, математический анализ медиа, рейтинги популярности, инфографика для телевидения и интернет-порталов. Запуск новых блогов, онлайн журналов и онлайн телеканалов. Съемки пилотных версий новых телепрограмм и сериалов, запись радиопередач. Видео-инсталляции и арт-проекты.
   3. Продвижение и раскрутка -- вирусное распространение контента, создание популярных видео, групп в социальных сетях, твиттер-аккаунтов. Новые подходы к формированию каналов обратной связи. Рекламные технологии. Продвижение в социальных сетях. Повышение эффективности рекламных компаний.

HackDay начнется с серии мастер-классов и экспресс-докладов. Дальше участники разбиваются на команды (обмен идеями и формирование команд будет проходить на в течении нескольких недель перед мероприятием) и приступают к интенсивной работе. HackDay  завершится демофестом - выставкой созданных прототипов и контент-проектов.

Wednesday, April 21, 2010

Using the QTKit Framework

From here:

The heart of QuickTime is its comprehensive underlying framework which is powerful, extensible, and flexible. This framework provides developers with the ability to display, import, export, modify, and capture more than 200 different media types. Until recently, however, using this power from Cocoa applications hasn't always been straightforward. Before the release of Mac OS X Tiger, anything more than display and playback of QuickTime files required using a set of Carbon APIs that were distinctly foreign to most Cocoa developers.
That has all changed. With Mac OS X Tiger comes QuickTime 7, which features a redesigned core architecture and provides a modernized Cocoa interface called QTKit. QTKit allows Cocoa developers to leverage a useful subset of QuickTime's capabilities. It not only allows you to play QuickTime movies, but to edit, splice, combine, and transcode them. And, if you need to go beyond its abilities, QTKit makes it easy to get to the underlying QuickTime primitives and directly use the more than 2500 functions in the QuickTime procedural API.
In essence, QTKit brings a deeper level of integration with QuickTime to the premier programming environment on Mac OS X.
This article shows how the QTKit framework is structured and introduces you to the essential concepts you'll need to understand to get up and running. First, let's review why QuickTIme is so important and what it brings to developers.

QTKit API Overview

For more info see the link above.

What Can You Do With QTKit?

With just the overview of QTKit that we've given here, you can see that QTKit lets you access an enormous amount of power from QuickTime and build it into your application in a straightforward fashion. What can you do with this knowledge now? You could create a media browser that would let you keep tabs on all the various kinda of meta-data about a large collection of QuickTime movies. You could build a command-line tool that would grab several frames from a set of movies and make a web page that allowed users to browse a collection remotely and choose the movie they wanted to download. Or, you could even build the next video editing tool customized for your own internal workflow.
The sky is the limit. QTKit brings an unprecedented ease of development to more than 15 years of multimedia experience in the QuickTime platform. It brings the premier multimedia platform to the premier application creation platform.

For More Information on QTKit

Using this article as a springboard, you should be able to dive into code and, with the help of the documentation, create your own QuickTime based Cocoa application. Along the way, you'll want to take advantage of the following resources:

Powered by Blogger.