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

Win32 and Metro–CreateFile(2)

| Friday, May 4, 2012
When a new Windows version comes out, I’m always curious about the new Windows API (Win32) functions that are added to the release.

With Windows 8, things get a little more complicated, as there are desktop apps and there are metro apps. Now, for every Windows API function the documentation states whether this API is valid for desktop apps only or for desktop apps and metro apps.

One classic function is CreateFile. This is one of the oldest functions – exists since the very first Windows NT version. In Windows 8, it’s marked for desktop apps only. This may be understandable, as the Windows Runtime has other ways to use files, such as the StorageFile class. However, Windows 8 has a new function called CreateFile2. This one, in contrast to CreateFile, can be used in desktop and metro apps. Here’s its prototype:

HANDLE WINAPI CreateFile2(
  _In_      LPCWSTR lpFileName,
  _In_      DWORD dwDesiredAccess,
  _In_      DWORD dwShareMode,
  _In_      DWORD dwCreationDisposition,
  _In_opt_  LPCREATEFILE2_EXTENDED_PARAMETERS pCreateExParams
);

Here’s the prototype of CreateFile:

HANDLE WINAPI CreateFile(
  __in      LPCTSTR lpFileName,
  __in      DWORD dwDesiredAccess,
  __in      DWORD dwShareMode,
  __in_opt  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  __in      DWORD dwCreationDisposition,
  __in      DWORD dwFlagsAndAttributes,
  __in_opt  HANDLE hTemplateFile
);

The first four arguments of CreateFile2 exist in both CreateFile and CreateFile2. The new extended parameters structure of CreateFile2 simply packages the “missing” arguments into an single optional structure:

typedef struct _CREATEFILE2_EXTENDED_PARAMETERS {
  DWORD                 dwSize;
  DWORD                 dwFileAttributes;
  DWORD                 dwFileFlags;
  DWORD                 dwSecurityQosFlags;
  LPSECURITY_ATTRIBUTES lpSecurityAttributes;
  HANDLE                hTemplateFile;
} CREATEFILE2_EXTENDED_PARAMETERS, *PCREATEFILE2_EXTENDED_PARAMETERS, *LPCREATEFILE2_EXTENDED_PARAMETERS;

Read more: Pavel's Blog
QR: Inline image 1

Posted via email from Jasper-net

Monocross

|
Inline image 2

What is Monocross?

Monocross is used to build enterprise mobile applications in C# that can be delivered on all the major mobile platforms. Applications share code on native iPad, iPhone, Android, Windows Phone, and the mobile web. All of the essentials of cross-platform mobile development are covered with the Monocross framework.

Open Source

Monocross is an open source mobile framework maintained and developed by a community of users and developers. Monocross is released under the MIT license, which means that anyone is free to download, contribute and share the framework. With an open development model Monocross is constantly evolving to support the latest technologies as the mobile landscape changes.

Read more: Monocross
QR: Inline image 1

Posted via email from Jasper-net

Creating Windows Phone, iPhone and Android Apps with iFactr in Visual Studio 2010

|
Inline image 1

iFactr is a cross-platform mobile framework created by ITR Mobility. With iFactr as a plug in to Visual Studio 2010, developers can create iPhone, Android and Windows Phone apps by writing C# and .NET code. Essentially iFactr compiles the code to a native app for a specified target platform. It is worth noting that the current version does require that the code be built and debugged on a Mac with iOS installed.

It currently supports native output for iPhone/iPad/iPod touch, Android, Windows Mobile, Windows Phone 7, and Windows XP/Vista/7. iFactr also offers web/hybrid app support for Android, BlackBerry, iPhone/iPad/iPod touch, Symbian, and Web OS via HTML 5.0, CSS, and JavaScript. The Windows desktop-optimized browser-based Web support and basic HTML/WAP for feature phone support is also in development.

Read more: DZone
QR: Inline image 2

Posted via email from Jasper-net

A Stick Figure Guide to the Advanced Encryption Standard (AES)

|
Inline image 1 Inline image 2

Read more: MOSERWARE 
360
QR: Inline image 3

Posted via email from Jasper-net

Check Point Unveils Free Antivirus and Firewall

| Thursday, May 3, 2012
Networking security firm Check Point Software Technologies has unveiled a new free firewall and antivirus product in a move that promises to raise the company’s consumer standing while giving its brand a boost in SMB markets.

ZoneAlarm Free Antivirus + Firewall, available as a free download, features Check Point’s established firewall technology coupled with an antivirus engine designed to block viruses, spyware and other salient security threats.

The free consumer product strategy isn’t entirely new for Check Point. The company acquired Zone Labs, maker of personal firewall product ZoneAlarm, in 2003, and has offered free firewalls for years. However, the recent move puts renewed emphasis on the Israel-based company’s consumer and small-business branding at a time when APTs and sophisticated new attacks are running rampant, and organizations, especially SMBs, have fewer and fewer resources with which to adequately defend their networks.

Check Point maintains the reason for the launch is to bolster customers’ security defenses with a multi-layered approach, especially for organizations that can’t or are unwilling to pay for third-party security products.

“Most consumers are unwittingly making themselves an easy target for cyber criminals,” says Bari Abdul, Check Point Software Technologies vice president and head of ZoneAlarm, consumer business. “They lack a strong two-way firewall, are unwilling or unable to pay for security, or they just have left their security on the backburner. People are putting themselves at serious risk by not having minimum security, which at least includes a firewall and antivirus software. It’s basically like leaving your home with the doors unlocked.”

Both the firewall and antivirus functions are designed to work seamlessly and efficiently together, eliminating any compatibility problems, which ultimately simplifies the entire security experience for the customer, the company said.

And no doubt, the move puts Check Point on par with other high-profile vendors that have leveraged consumer marketing and free products and services to gain brand recognition and, ultimately, traction in other commercial markets.

Read more: Channel nomics
QR: Inline image 1

Posted via email from Jasper-net

Создание msi-пакетов и установка любого ПО средствами групповых политик Windows

| Wednesday, May 2, 2012
Доброго времени суток, Хабр! Хочу представить интересный, по моему мнению, способ создания msi-инсталляторов для любого программного обеспечения и, как следствие, развертывание его средствами GPO. Подчеркну, что описанный метод не подразумевает создание «слепков» системы, а использует нативные инсталляторы софта, при чем для создания msi применяются только бесплатные для коммерческого использования продукты.

Введение, пара ссылок и дисклеймер

Каждый нормальный инсталлятор ПО имеет возможность автоматической установки с определенными или заложенными по умолчанию параметрами. Суть моего метода проста и заключается в том, чтобы запаковать нативный инсталлятор в «контейнер» msi и запустить его с необходимыми параметрами командной строки. В сети куча информации по автоматической установке того или иного приложения, и я не буду заострять на этом внимание. Наша цель, повторюсь, — установка ПО средствами групповых политик. Кстати, некоторые из вас могут возразить, что установку можно производить через ZAW, но, к сожалению, данный метод применим только для установки с правами текущего пользователя и не может применяться для централизованной автоматической установки приложений.

Интересный цикл статей по установке ПО через ГП. Для новичков рекомендую прочитать все, чтобы потом не спрашивать, чем отличается тип установки «назначенный» от «публичный».

Необходимый софт. Exe to MSI Converter freeware и всем известная orca Первый нужен для того, чтобы создать msi из exe, а вторая — чтобы получившийся msi-ник смог установиться через групповые политики.

Метод не претендует на полную уникальность и в некоторых местах могут встречаться излишества, которых можно было бы избежать, но это связанно отсутствием желания и необходимости слишком глубоко вникать в параметры таблиц msi-пакетов. Первоначальной целью ставилось быстро найти бесплатный способ создания msi и после нескольких часов, проведенных в чтении зарубежных форумов и бесконечных перезагрузках виртуальной машины, метод был найден. Также, статья — это не обзор интерфейса программ, и скриншотов вы не увидите.

Создание и подготовка пакета

  • Пример установки будет произведен для Mozilla Firefox, т. к. это широко известный продукт, не имеющий msi-инсталлятора от разработчиков. 
  • Запускаем exe to msi и указываем в нем путь к exe-установщику firefox. По ранее найденной в сети информации становится понятно, что по-тихому установить огнелиса можно с параметрами -ms -ira. Их-то и указываем во втором поле exe to msi и жмем «Build MSI».
  • Казалось бы все, msi-пакет готов. Действительно, запустив получившийся результат мы получим установленный в системе firefox и в статье можно было бы ставить точку. К сожалению, не все так просто. Текущий пакет установки не пригоден для развертывания через GPO и при загрузке компьютера вы будете получать совершенно ничего не объясняющие ошибки в логах «произошла неисправимая ошибка...» А все дело в том, что разработчики exe to msi тоже хотят есть и их бесплатный продукт генерирует msi «не по правилам».
  • Ну что ж, берем орку и открываем в ней наш эмсиайник.
  • Первым делом находим в левом списке таблицу Property и обращаем внимания на два поля — ProductCode и UpgradeCode. Эти два поля должны быть уникальны для каждого продукта, а наш exe to msi генерит всегда одинаковые. Ну что ж, не беда, жмем в верхнем меню View -> Summary Information, находим поле PackageCode и жмем New GUID. Получившийся результат копируем в буфер обмена и вставляем в ProductCode. Повторяем для UpgradeCode и наконец для самого PackageCode. Тут же в Summary Information правим поле Title на Mozilla Firefox, остальное по желанию. Это, по сути, ни на что не влияет.
  • Опять же в таблице Property меням ProductName на Mozilla Firefox (я до кучи меняю еще ARPCONTACT и Manufacturer). Можно так же поставить правильное значение для ProductVersion.
  • Вроде бы GUID и прочие «IDы» поменяли, но как показывает практика, этого недостаточно. Жмите в orca Tools –> Validate, снимите птицу Show INFO Messages и нажимайте Go.
  • Как видите, вылезла куча ошибок на наличие/отсутствие некоторых таблиц и значений. Я не стал заморачиваться и просто взял первый попавшийся (7zip x64 9.20) небольшой msi и скопировал оттуда 4 недостающие таблицы (через Export-Import, естественно): _Validation, AdminExecuteSequence, AdminUISequence и AdvtExecuteSequence. На самом деле, я уверен, что можно создать «правильный» msi-инсталлятор, без лишнего мусора, но не забывайте, наша цель всего лишь запустить родной setup приложения в тихую.
  • После добавления таблиц проходим снова Tools –> Validate (к слову, первый раз проверку можно вообще не делать и сразу импортировать таблицы). Если вы тоже взяли за основу msi от 7zip, то результатом будет шесть эрроров, которые необходимо устранить. Жмите Close, удаляйте лишние поля, отмеченные красным.
  • В конце можно еще раз проверить валидацию и убедиться что остались лишь ничем не мешающие варнинги. Сохраняем msi.
  • Вот в принципе и все, осталось добавить msi в ГП и назначить необходимые свойства.

Нюансы

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

Send an email with an embedded image in its body

|
Introduction

The article is about how to send an email with an image within its body and not as an attachment (like a company's logo). The only possible solution is to format the body of the message as an "HTML" document. We will have to use the .NET classes LinkedResource and AlternateView as merely setting the src of the HTML <img> tag won't help.

Background

Before going through this article, we need to have a basic understanding of ASP.NET 2.0 (and ofcourse, HTML).

Using the code

First of all, we need to import the namespace System.Net.Mail. Then in the configSections of the web.config file, add the following:

<appSettings>
<add key="SMTP" value="SMTP Address"/>  //like mail.gmail.com
<add key="MailFrom" value="Mail From"/>
<add key="Port" value="Port Number"/> //usually 25
<add key="MailUserName" value="user name of the mail from which the mail will be sent"/>
<add key="MailPwd" value="Password"/>
<add key="To" value="To whom you're sending the mail"/>
<add key="CC" value="If there's any cc to add"/>
</appSettings>

Now in the .NET class file, write the following code. (Note that here we are not concerned about validations.)

 Collapse | Copy Code
MailMessage msg = new MailMessage();

string To, Cc;
string strMailContent = "You can include your text here";

To = ConfigurationManager.AppSettings["To"].ToString();
Cc = ConfigurationManager.AppSettings["CC"].ToString();

//checking that if there exist a Cc
if (Cc != "" && Cc != String.Empty && Cc != null)
{
  msg.CC.Add(Cc);
}
msg.To.Add(To);
msg.From = new MailAddress(ConfigurationManager.AppSettings["MailUserName"].ToString());
msg.Subject = sub;

string path = Server.MapPath(@"images/Logo.jpg"); // my logo is placed in images folder

LinkedResource logo = new LinkedResource(path);
logo.ContentId = "companylogo";

//now do the HTML formatting
AlternateView av1 = AlternateView.CreateAlternateViewFromString(
      "<html><body><img src=cid:companylogo/>" + 
      "<br></body></html>" + strMailContent, 
      null, MediaTypeNames.Text.Html);

//now add the AlternateView
av1.LinkedResources.Add(logo);

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

Securing WCF

|
Securing a WCF service is quite easy but several methods with different fields of applications exist. This post describes the different available securing mechanisms and how they are set up.

Securing your network service is important because if a service is not secured, every peer on your communication way can read your communication.

Basically two different approaches of securing a service exist:

  • Message security: This approach encrypts the contents of a message, therefore the security is delegated to the protocol. If a well-known and tested standard for the protocol in use is available this approach has the advantage that the encryption is transparent to all peers and no special treatment is required. But not all protocols provide a payload encryption. Developing your own message security scheme is dangerous and requires special security skills. SOAP with the WS-Security extension is an example for a message-security scheme, but the WS-Security extension is not supported by many frameworks, especially it is not supported on Android out of the box.

  • Transport security: Transport layer security is independent of the protocol and is supported by far more applications. A well-known transport security mechanism is SSL/TLS which is used for HTTPS, SSH and many others. It establishes an end-to-end encryption based on X509-Certificates and associated private keys. The disadvantage of this approach is that non-end-to-end connections are not supported. The communication needs to be decrypted and encrypted on every hop.
WCF and Message Security

To enable service security for your service add the following to your binding configuration:

<security mode="Message">
  <message clientCredentialType="Certificate/IssuedToken/None/UserName/Windows" />
</security>

For a detailed explanation of the message security tag look at MSDN.

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

Xml Serialize Interface Typed Members

|
If you try to serialize a class that has a public member of an interface type to xml file using the regular .net XmlSerializer, you will get an error: “Cannot serialize member {m} of type {t} because it is an interface.” ({m} and {t} are placeholders). 
In this post I suggest a workaround to this issue.

Consider the following scenario:

You have an object model like this:

 1: public class Car
   2: {
   3:     public string Model { get; set; }
   4:     public int Year { get; set; }
   5:     public IEngine Engine { get; set; }
   6: }
   7:  
   8: public interface IEngine
   9: {
  10:     void Work();
  11: }
  12:  
  13: public class ElectricEngine : IEngine
  14: {
  15:     int batteryPrecentageLeft;
  16:     public int BatteryPrecentageLeft
  17:     {
  18:         get { return this.batteryPrecentageLeft; }
  19:         set { this.batteryPrecentageLeft = value; }
  20:     }
  21:  
  22:     void IEngine.Work() { }
  23: }

If you would try to serialize myCar using the regular XmlSerializer, you will get the error above.

There are many reasons why you shouldn’t want to serialize an interface typed member. I will not dive into this debate right now. I assume that you have considered this before, and are just looking for a workaround.

So first lets understand what we are trying to achieve. 
In the example above, I expect the serialized output of myCar to be something like this:

   2:   <Model>Ford Focus</Model>
   3:   <Year>2011</Year>
   4:   <Engine>
   5:     <ElectricEngine FullAssemblyQualifiedTypeName="Common.ElectricEngine, Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
   6:       <BatteryPrecentageLeft>70</BatteryPrecentageLeft>
   7:     </ElectricEngine>
   8:   </Engine>
   9: </Car>

Read more: itaysk
QR: Inline image 1

Posted via email from Jasper-net

Updated Archive of the NtDebugging Twitter Debug Tips

|
Every Wednesday (usually) we post a debug tip to our twitter page at https://twitter.com/#!/ntdebugging. This blog is an archive of these tips to allow our readers to find this information easily. Periodically we post an updated blog with the current archive. Follow us on twitter if you want to see the new tips as we post them.

The goal of these tips is to share debug commands, and forms of commands (parameters, flags, etc) that we in Platforms Global Escalation Services find useful. I hope you can add these commands to your toolkit and they will help you debug more efficiently.

Tips:

!thread/!process [address] e - on x64 will not show you the meaningless Args to Child information.

.frame /c [FrameNumber] - sets context to specificied stack frame. On x64 provides more reliable register information than .trap.

kn - Dumps call stack with frame numbers, easier than counting stacks for .frame.

.frame /r [FrameNumber] - same as .frame /c, but shows registers without changing context.

Note: With .frame /c or /r you can only trust the nonvolatile registers. See http://bit.ly/dik4OR for vol/nonvol regs.

k=rbp rip FrameCount - Dumps call stack starting at rbp/rip on x64. Useful when the stack is corrupt.

.process/.thread /p /r [address] - sets new process context, sets .cache forcedecodeuser, and reloads user symbols.

!process [address] 17 - Sets the context for this command, avoids the need for .process to see user stacks. Try !process 0 17

~~[ThreadID]s - Changes threads in user mode. Use Thread ID number from output such as !locks. Ex: ~~[1bd4]s

runas /netonly /u:<account> windbg.exe - Launch windbg with domain account. Use when dbg computer isn't in domain and symbol server is.

!heap -p -a <address> - Shows information about the heap block containing <address>, even if you aren't using pageheap.

ub - Unassembles starting at a location prior to your address. Accepts l<number> to specify how many instructions to go back. ub . l20

!stacks 2 [FilterString] - Finds kernel mode call stacks that contain the FilterString in a symbol.

Read more: NtDebugging
QR: Inline image 1

Posted via email from Jasper-net

WRITING A BOOTLOADER

|
I’ve been working on a simple bootloader for PIC18F devices called pbldr. In this article I’ll explain what a bootloader is, and how pbldr currently works. Note that is code is experimental, and is intended to show how a bootloader works.

What is a Bootloader?

The simplest bootloader just runs a program: it could be as simple as a single jump instruction that jumps to the program. In embedded systems, bootloaders usually provide a method of flashing new code to the device and initialize the hardware before running the main program. One example of this is the Arduino bootloader, which loads code from the Arduino IDE to the ATmega microcontroller over asynchronous serial (UART). Bootloaders can include other features, such as code decryption and power-on tests of the device.

Bootloaders allow code to be flashed to a microcontroller without specific programming hardware. This allows end-users to upgrade firmware without needing special hardware.  It can also simplify firmware updates for installed devices that are difficult to physically connect to. For example, an automotive controller might use Controller Area Network to load new code.

How does it work?

A bootloader runs immediately after the device is powered on. It first checks if the user is trying to load new code. If so, it receives the code and loads it into program memory at a specific memory location. Otherwise, it jumps to the start of the user’s program, which has already been loaded at that specific memory location.

Lets look at pbldr, which is currently a (very) minimal example of a bootloader. Full source is available from github.

UART

The UART1 port is used to load programs. There are a few functions that deal with UART:

/********************
 UART 1 Functions
********************/
 
// initializes UART1 at specified baud rate
void UART1Init(long baud){
    RCSTA1bits.SPEN = 1; // enable port
    TRISCbits.TRISC7 = 1; // make rx pin an input
    RCSTA1bits.CREN = 1; // enable receive
    TRISCbits.TRISC6 = 0; // make tx pin an output
    TXSTA1bits.TXEN = 1; // enable transmit
    TXSTA1bits.SYNC = 0; // use async serial
    TXSTA1bits.BRGH = 1; // high speed mode
    BAUDCON1bits.BRG16 = 1; // use 16 bit baud rate generator
    SPBRG1 = (FCY/baud/4)-1; // set baud rate generator
    return;
}
 
// writes a byte to UART1
void UART1TxByte(char byte)
{
    while (!TXSTA1bits.TRMT); // wait until buffer is empty
    TXREG1 = byte;            // write the byte
    return;
}
 
// reads a byte from UART 1
char UART1RxByte(unsigned int timeout)
{
    while (!PIR1bits.RC1IF && timeout > 0) // wait for data to be available
        timeout--;
    return RCREG1; // return data byte
 
}
// writes a string from ROM to UART1
void UART1TxROMString(const rom char *str)
{
    int i = 0;
 
    while(str[i] != 0){
        UART1TxByte(str[i]);
        i++;
    }
    return;
}
 
// writes a string from RAM to UART1
void UART1TxString(char *str)
{
    int i = 0;
 
    while(str[i] != 0){
        UART1TxByte(str[i]);
        i++;
    }
    return;
}

Read more: ERIC EVENCHICK
QR: Inline image 1

Posted via email from Jasper-net

Android Ported to C#

|
Inline image 2

Oracle and Google are currently in a $1 billion wrestling match over Google’s use of Java in Android.

But Java is not the only way to build native apps on Android. In fact, it’s not even the best way: we have been offering C# to Android developers as a high-performance, low-battery consuming alternative to Java. Our platform, Mono, is an open source implementation of the .NET framework that allows developers to write their code using C# while running on top of the Java-powered operating system, and then share that same code with iOS and Windows Phone.

Unlike Sun with Java, Microsoft submitted C# and the .NET VM for standardization to ECMA and saw those standards graduated all the way to ISO strong patent commitments. The .NET framework is also covered by Microsoft’s legally binding community promise.

Last July when Xamarin was getting started, we got our team together in Boston to plan the evolution of Mono on iOS and Android. After a day of kayaking in the Charles River, we sat down to dinner and turned our attention to how we could improve the performance and battery life of applications on Android, and make our own Mono for Android even better.

Over and over we came back to the basics: Dalvik is a young virtual machine, it is not as performant or tuned as Mono and suffers from many of Java’s performance limitations without the benefit of the high-end optimizations from Oracle’s HotSpot. One crazy idea that the team had at that dinner was to translate Android’s source code to C#. Android would benefit from C# performance features like structures, P/Invoke, real generics and our more mature runtime.

Although nothing happened back in July, this idea stuck in the back of our minds.

Fast forward a few months: Mono for Android is doing great, and we are starting to think again about improving our own product’s performance on Android. What if we could swap out Java with faster C# and get rid of various Dalvik limitations in the process? Could we create an Android phone completely free of Java, and free of the limitations of the Dalvik VM?

We decided it was crazy enough to try. So we started a small skunkworks project with the goal of doing a machine translation of Android from Java to C#. We called this project XobotOS.

Inline image 3

The XobotOS Research Project

The result of our efforts is that today we have most of Android’s layouts and controls entirely in C#. Here are some screenshots of XobotOS running on a Linux workstation, no Java involved:

Read more: Xamarian
QR: Inline image 1

Posted via email from Jasper-net

ספר חינמי של Apress - פיתוח לחלונות 8 ב HTML5

|
Inline image 1

הוצאת הספרים APress מחלקת הלילה ספר פיתוח לחלונות 8 עם HTML5 בחינם לגמרי!
ההצעה תקפה עד 12 בלילה, אני מניח זמן ניו יורק (ככה שיש עד הבוקר שלנו)

מהרו והורידו עכשיו!

QR: Inline image 2

Posted via email from Jasper-net

Упражнения по взлому Linux-систем

| Monday, April 30, 2012
Для тех, кто интересуется вопросами безопасности и уязвимостями Linux, создан обучающий проект exploit-exercises.com с подборкой виртуальных Linux-машин, описаниями уязвимостей, документацией и практическими заданиями.

1. Виртуальная машина Nebula
торрент-файл
прямая ссылка

Самые общие уязвимости, связанные с эскалацией привилегий в Linux: это SUID-файлы, разрешения, состояние гонки (race conditions), метапеременные оболочки, уязвимости $PATH, уязвимости скриптовых языков, ошибки компиляции бинарных файлов.

Nebula включает в себя 19 уровней, для загрузки уровня следует залогиниться под именем levelXX, где XX — номер уровня от 00 до 19. Некоторые уровни можно пройти только в удалённом режиме. В случае необходимости рутового доступа для изменения каких-то настроек, можно залогиниться с именем nebula, пароль nebula, после чего выполнить команду sudo -s с паролем nebula.

2. Виртуальная машина Protostar
торрент-файл
прямая ссылка

Введение в ошибки памяти Linux/x86: переполнение стека (8 упражнений), сетевое программирование: работа с сокетами и порядок байтов (4 упражнения), форматный вывод (5 упражнений), переполнение кучи (4 упражнения), итоговые упражнения (3).

Войти в систему можно под логином user, с паролем user. Описание уровней находится в директории /opt/protostar/bin.

3. Виртуальная машина Fusion (на базе Protostar)
торрент-файл

Продвинутые эксплойты, криптографические задачи, атака по времени, различные сетевые протоколы (Protocol Buffers, Sun RPC и другие), а также демонстрация некоторых механизмов защиты, таких как рандомизация адресного пространства, исполнение кода в зависимости от позиции (Position Independent Executables), неисполняемая память, фортификация исходного кода (_DFORTIFY_SOURCE=), защита от переполнения буфера (ProPolice / SSP), всего 28 упражнений.

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

C#/.NET Little Wonders: The Enumerable.Range() Static Method

|
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.

Thanks for all of your patience while I’ve been dealing with other matters these last few weeks.  I didn’t want to let my post slide a third week, so I decided to say a few words about a small static method in the Enumerable class from System.Linq. 

Using Range() to generates a sequence of consecutive integers

So, if we look in the Enumerable static class, where most of the linq extension methods are defined, we will also see a static method called Range() whose purpose is to generate a range of integers from a given start value and for a given count. 

It’s syntax looks like:

Range(int start, int count)

Returns a sequence of int from start to (start + count – 1).
So, for example, the code snippet below will create an List<int> of the numbers from 1 to 10:

 var numbers = Enumerable.Range(1, 10).ToList();

So, this seems simple enough, right? Well, yes, it is a handy way to create a sequence of consecutive int values that you can use directly, but when coupled with other constructs, it has many other uses as well.

Using Range() to feed a more complex LINQ expression

For example, if we wanted a list of the first 5 even numbers, we could start with the number of expected items and multiply up by our step factor in a Select():

     // take sequence 0, 1, 2, 3, 4 and multiply each by two...
     var evens = Enumerable.Range(0, 5).Select(n => n*2).ToList();

Or, you could create a range over the total range of values and use Where() to filter it down:

    // generates sequence from 0..9, but only selects even ones
    var odds = Enumerable.Range(0, 10).Where(n => (n % 2) == 0).ToList();

But the great thing about Range() is you don’t have to use it to just produce numbers, you can use the sequence it generates either directly or as the starting point for a more complex LINQ expression. 

For example, if we wanted to generate a series of strings for font sizes we want to allow in a windows form, we could do that easily:

// takes the range from 1 to 10 and multiples by 10 and puts % on end.
var percentages = Enumerable
   .Range(1, 10)
   .Select(i => (i * 10) + " pt")
   .ToArray();

This would give us an array of strings containing “10 pt”, “20 pt”, “30 pt”, … “100 pt”.

Read more: James Michael Hare
QR: Inline image 2

Posted via email from Jasper-net

Google Drive SDK

| Sunday, April 29, 2012
How Drive Apps Work

Drive apps allow users to create, open, save, and share files in Google Drive. Any type of file can be stored in Drive, up to the user's storage limit or maximum file size of 10GB. Most file types are indexed for search, and you can optionally provide indexable text for other resources such as drawings or video files.

The privacy and security of users' data is ensured by application authorization and file-level access control. After users authorize a third-party app to access their Drive files, then opening and saving files with that app is an uninterrupted flow very similar to what they'd experience using a local file system.

The rest of this page describes how users interact with Google Drive apps in these ways:

Installing a Drive app
Authorizing access
Granting file-level access
Opening and creating files from the Drive UI
Opening Drive files from an external app
Creating Google Drive shortcuts to external files
To get started developing an app that supports these operations, see Start Building your Google Drive application.

Read more: Google drive SDK
QR: Inline image 1

Posted via email from Jasper-net

NHibernate 3.3.0.GA released

|
NHibernate 3.3.0.GA is now available for download from Sourceforge. 
Nuget will be updated as soon as possible. 

A big thanks to everyone that's contributed to this release! 

Summary of changes: 

* Many improvements to the LINQ provider to extend the set of queries which  it can handle. 

* Introduction of the "enhanced" family of id generators. These can be backed by either a sequence or a table, have built in support for tracking several 
 id series in the same table, and share a common set of optimizers, which implement e.g. HiLo or Pooled algorithms. 

* Some new abilities in Mapping-By-Code. 

* And a nice batch of bug fixes in other areas. 

** Known BREAKING CHANGES from NH3.2.0.GA to NH3.3.0.GA 

   ##### Possible Breaking Changes ##### 
        * [NH-2214] - SQL Server 2005/2008: Exception is now thrown when paging a statement that requires distinct results, and is ordered by a column that is not included in the result set of the query 
                    - Dialog.ExtractColumnOrAliasNames method signature and visibility changed - may affect custom dialects that use this method 
        * [NH-2950] - IAccessCallback.NextValue property renamed and changed to a method called IAccessCallback.GetNextValue() 

Read more: Google Groups
QR: Inline image 1

Posted via email from Jasper-net

Оп, ап! — You've got an App

|
Inline image 1

Становится ясно, что большая часть программного обеспечения будет распространяться через магазины приложений. Первыми прелести этих магазинов вкусили владельцы мобильных устройств на базе iOS и Android, чуть позже пользователи операционных систем MacOS и Ubuntu получили App Store и Ubuntu Software Center. 
Сегодня я хочу вам рассказать о магазине приложений от Intel — AppUp, который работает уже более двух лет.
Среди моих знакомых Intel AppUp не слишком широко известен. Я думаю, в первую очередь это связано с тем, что он не устанавливается вместе с операционной системой, в отличии от MacOS и Ubuntu.

Для работы с магазином приложений пользователям необходимо установить Intel AppUp center, скачав его с сайта appup.com.
Зарегистрировавшись и авторизовавшись, можно приступать к шоппингу. Для жителей России пока доступны только бесплатные приложения. Поскольку статистика говорит о том, что большинство скачиваний приходится как раз на них, это не должно слишком огорчать.

Read more: Habrahabr.ru
Read more: Intel AppUp
QR: Inline image 3

Posted via email from Jasper-net

Async Targeting Pack for Visual Studio 11 now available for .NET 4 and Silverlight 5 [Greg]

|
We would like to announce that you can now download an Async Targeting Pack for Visual Studio 11 that lets you use Visual Studio 11 Beta to create projects that target .NET 4.0 and Silverlight 5.

The Async Targeting Pack includes DLLs that address an incompatibility between Visual Studio 11 Beta compilers and the DLLs that shipped with the Async CTP for Visual Studio 2010. This issue has been previously discussed on the PFX team blog.

The Async Targeting Pack is available as a NuGet package, with installation details available here.

Read more: BCL Team Blog 
QR: Inline image 1

Posted via email from Jasper-net

Creating a DirectX XAML control using C++/CX

|
Inline image 1

   With Windows 8 Metro style apps, you can now also build XAML controls not only with C# and VB.NET but also with C++. If you are a .NET developer you will probably wonder why you would do that – and granted there might be several reasons you wouldn’t. However there is a few nice things about C++ that .NET libraries doesn’t give you: 
1. You can use existing C++ libraries and link them directly in. This will allow you to re-use an enormous amount of code already out there. 
2. DirectX is a first-class citizen in C++ 11, and officially the only way to use DirectX in XAML (although there are ways to access this from C#).

If you need high-performance rendering or 3D, DirectX is the way to go on the Windows Platform, and finally we can effortless mix DX and XAML (well at least compared to how it was in WPF). So this blogpost will show you how to build the base control you will need to make DirectX-in-XAML possible.

If you haven’t made any custom controls before, I urge you to read my earlier post on why they are so awesome and how they work: Why Custom Controls are underrated

So let’s open up Visual Studio 11, and go: New Project –> Visual C++ –> WinRT Component DLL

Read more: SharpGIS
QR: Inline image 2

Posted via email from Jasper-net

Bringing CLR’s Power to non .NET languages - Part 1

|
The .NET Framework helps developer boost their productivity by giving them a set of tools and libraries they need to quickly start implementing the core of their software without loosing time on details. The idea behind the Common Language Infrastructure (CLI) is to allow programming languages to interoperate by sharing code through libraries.

To take advantage of these libraries, a lot of languages got their .NET implementation counterparts, with for example: IronPython, IronRuby, or IronScheme. See http://en.wikipedia.org/wiki/List_of_CLI_languages#CLI_languages for more implementations.

Most of these languages when interpreted are implemented in .NET languages and can easily interact with the underlying platform. For compiled languages they generate IL and the result is a .NET assembly.

In the same way you can dynamically load symbols from a shared library, there are times you would like to be able to interact with the .NET Framework from non .NET languages such as C, C++, Java, Perl or PHP.

Through a short series of articles I am going to show you how to achieve this goal and get the power of .NET in all your favorite languages in less than 500 lines of code.

Back to the origin…

Like for software components at a higher level, the best way to make programming languages interoperate with each other is to define some kind of interfaces. If we look what has been done in the past with native languages we can consider as part of this interface: the processor architecture and its instruction set, the binary format with the way symbols are exported, the type sizes and the conventions to call code.

Assuming that your binaries respect this same interface they can freely share symbols. We are going to respect this interface in order to build a bridge library between the native and the .NET worlds. This native library would be then accessible from non .NET languages.

C++++++…

But don’t worry I have good news for you, a nice version of C++ exists in this world! It is C++/CLI! As you probably guessed this version of C++ is targeting the Common Language Infrastructure. Besides the fact it fills some C++ lacks such as automatic memory management and boilerplate code generation for data member accessors, one of the good thing is that it provides you a seamless and simple way to mix native and managed code. Moreover once compiled the binary has both native and managed sections and can export native symbols such as functions using CLR objects.

As a solution for our problem I then suggests to use C++/CLI to build an interoperability DLL, whose functions are dynamically loadable by non .NET languages and which will allow us to use the .NET Framework.

Bridge the two worlds

Exporting the API

To export our DLL symbols we define a macro CLR_API:

Notice that we use extern “C” to avoid C++ symbol names mangling.

QR: Inline image 1

Posted via email from Jasper-net

Перевод туториалов по libGDX — часть 1 (настройка проекта в Eclipse)

|
Эта статья — перевод первого туториала для проекта libGDX. Оригинал находится здесь — 

От переводчика: недавно у меня появилось желание написать игру под Android. У меня есть некоторый опыт программирования на Java, но я почти не сталкивался с разработкой под Android. Тут я наткнулся на библиотеку libGDX, которая позволяет писать кросплатформенные игры. Также я наткнулся, что по ней не хватает русской документации, а конкретно — туториалов. Поэтому у меня появилось желание перевести туториалы. Это мой первый перевод, поэтому буду рад любым замечаниям и указаниям на неточности.

Настройка проекта

Примечание: есть проблемы с использованием Java 1.7 для Android-приложений. Убедитесь, что вы используете Java 1.6
Примечание: надо сделать несколько шагов для настройки приложения под Android. Смотрите ниже.

Эта статья описывает, как настроить Eclipse для разработки и запуска приложений как на настольном компьютере, так и на Android-устройствах.

Настройка главного проекта

1. Создайте новый Java-проект в Eclipse.
2. Перейдите к каталогу проекта в файловой системе и создайте в нем каталог с названием libs. Загрузите nightly zip (nightly zip — это архив из последней сборкой проекта — прим. переводчика) и положите gdx.jar и gdx-sourses.jar в каталог libs/
3. Щелкните правой кнопкой мыши на проекте в Eclipse, и нажмете Refresh. Снова щелкните правой кнопкой, выберите Properties -> Java Build Path -> Libraries -> Add JARs, выберите jdx.jar и нажмите OK.
4. Щелкните правой кнопкой мыши по файлу gdx.jar -> Properties -> Java source attachment. Нажмите Workspace, выберите gdx-sources.jar и нажмите ОК.
5. Щелкните по вкладке Order and Export, поставьте галочку напротив gdx.jar и нажмите ОК.
Примечание: пятый шаг сделает gdx.jar транзитивно зависимым. Это означает, что проекты, которые зависят от главного проекта, также будут иметь gdx.jar в своем classpath. Однако, это не касается Android-приложений.

Настройка приложения для настольного ПК.

1. Создайте новый проект в Eclipse. Назовите его соответствующим образом (gamename-desktop, например).
2. Перейдите к каталогу проекта в файловой системе и создайте в нем подкаталог с названием libs. Положите библиотеки gdx-natives.jar, gdx-backend-lwjgl.jar, gdx-backend-lwjgl-natives.jar в каталог libs.
3. Щелкните правой кнопкой мыши на проекте, нажмите Refresh. Снова щелкните правой кнопкой мыши -> Properties -> Java Build Path -> Libraries -> Add JARs, выберите три библиотеки из каталога libs и нажмите ОК.
4. Перейдите на вкладку Projects, нажмите Add, выберите созданный выше главный проект и нажмите ОК.

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

Windows 8 development Links

|
I am just on my way home from a great Windows 8 event in Manchester. We had a full house (sorry that the room was a little packed) and loads of talks. During my two presentations I promised to share some links and example code that I showed during the talk… So here they are:

Views
Overview (Link)
Visual State Manager (App tiles and badges sample)
Pixel Density (Sample Application)

Tiles
Overview (Link)
App Tiles (Sample Application)
Toast Notifications (Sample Application)

Suspend and Resume
Overview (JavaScript, XAML)
Suspension (Sample Application)
Background Tasks (Sample Application)

Read more: thebeebs 
QR: Inline image 1

Posted via email from Jasper-net

WinRT XAML Toolkit - Controls, extensions and helper classes for WinRT

|
A set of controls, extensions and helper classes for Windows Runtime XAML applications

Features
  • A copy of the AsyncUI library - a set of extension methods for UI classes that add support for async/await to wait for events such as:
  • Wait for a BitmapImage to load
  • Wait for a Button or one of a list of buttons to be clicked
  • Wait for a FrameworkElement to load, unload or become non-zero-sized
  • Wait for a MediaElement to change state - eg. to start or finish playback
  • Wait for a Selector (e.g. ListBox) to change selected item
  • Wait for a Storyboard to complete

Controls
  • AnimatingContainer - a container control that will animate its contents rotating or zooming in/out, eg. to make them feel more alive
  • CascadingTextBlock - a TextBlock replacement that animates the individual letters in a cascade - fading in while falling down into position, then optionally fading out while falling down from the standard position
  • CountdownControl - a movie-style control that animates a ring-slice shape while counting down seconds - e.g. to take a picture with a camera after a given number of seconds (supports async/await)
  • DelayedLoadControl - given a content/DataTemplate - loads the contents after a given amount of time - e.g. to allow for staged loading of contents on screen
  • PieSlice - a pie slice path/shape given StartAngle, EndAngle and Radius
  • RingSlice - a pie slice path/shape given StartAngle, EndAngle, Radius and InnerRadius
  • TextBlockExtensions/GetCharacterRect() - an extension method that returns a rectangle that holds a character at a given index in the TextBlock

Conterters

  • BooleanToDataTemplateConverter - given two DataTemplates (TrueTemplate and FalseTemplate) - converts the input value to the given template. A different take on DataTemplateSelector.

Extensions
WriteableBitmap - a set of extension methods for a WriteableBitmap
  • ColorExtensions - Conversions between pixels and pixel buffer types of byte, int and Color
  • IBufferExtensions - Adds a GetPixels() extension method to the PixelBuffer property of a WriteableBitmap that reads in the buffer to a byte array and exposes an indexer compatible to the one of the Pixels property in Silverlight's WriteableBitmap
  • WriteableBitmapSaveExtensions - support for loading and saving the bitmap to/from files
  • WriteableBitmapBlitBlockExtensions - support for quick blitting of a full-width section of a bitmap to another bitmap of same width
  • WriteableBitmapCopyExtensions - support creating a copy of a WriteableBitmap
  • WriteableBitmapCropExtensions - support for creating a cropped version of a WriteableBitmap
  • WriteableBitmapFloodFillExtensions - support for flood-filling a region of a WriteableBitmap - either limited by an outline color or by replacing a given color - usually a color at the starting position or colors similar to it

Read more: WinRT XAML Toolkit
QR: Inline image 1

Posted via email from Jasper-net

AVoD ( Аудио и Видео по запросу ) через торренты, новый уровень!

|
На сегодняшний день все еще многих пользователей Интернет можно удивить возможностью онлайн проигрывания видео и аудио контента через торренты, без необходимости ожидания загрузки контента. 
Безусловно, этим уже не удивишь хабрасообщество, учитывая что еще первые топики освещающие такую возможность появились на хабре более двух лет назад ( к примеру: habrahabr.ru/post/87509/, — где не обошли стороной нашу первую пробную поделку, которая уже в той своей реализации превосходила все существующие в мире решения, включая и решение флагмана торрент-клиентов, а именно utorrent со своей новой функцией «stream» ). 

Так чем же еще можно удивить хабрасообщество и продвинутых гиков, по истечении двух лет?

Поверьте, есть чем! 

Ну а чтобы проверить, милости просим под кат. 

Для начала я хочу поздравить нашу команду и всех наших пользователей с долгожданным выпуском новой версии ПО Torrent Stream ( релиз 1.0.5 Full ). Это был не просто выход клиентского приложения, это было изменение архитектуры всей системы, ее программной логики и даже сайты пришлось новые делать. Так что, c удовольствием примем от вас поздравления. 

А теперь обо всем по порядку. 

Учитывая, что для нас выпуск релиза Torrent Stream 1.0.5 Full, является очень важным и значимым событием, поэтому с него и начну. 

Выходом данного релиза мы хотим обратить внимание всех, что TS P2P Multimedia Plug-In не является единственной и исключительной основой системы Torrent Stream! В основе Системы TS находится только сам движок Torrent Stream (TS Engine ), который может работать как с любыми десктопными плеерами (VLC; The KMPlayer; MPlayer и т.п.) и Медиа-центрами (XBMC;Mediaportal и т.п), так и с веб-плеерами, построенными на базе любой технологии, включая HTML5. 

Версия 1.0.5 Full представлена в виде установочного пакета программного обеспечения Torrent Stream, в который включены следующие продукты: 

TS Engine – Основной программный продукт, обеспечивающий работу всех функций и возможностей технологии Torrent Stream (движок управления мультимедийными потоками) 

Он является базовым ядром платформы Torrent Stream и может использоваться, посредством API ( TS Engine API ), любыми разработчиками при создания собственных продуктов, интегрируя в них функционал и возможности Torrent Stream. 

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

The Case of The Unquoted Command Line: Process Monitor and MPGO.EXE

|
A few months ago I wrote about MPGO, a new Microsoft tool that ships with .NET 4.5 and enables profile-guided optimization of managed assemblies. Specifically, MPGO optimizes the layout of native images for managed assemblies, which reduces startup times, working set sizes, and page fault costs.

Shameless plug: Pro .NET Performance has a large section dedicated to improving startup performance, and I’ve written about this before: Using Prefetch to improve startup performance, Rebasing and compression.

Anyway, I was experimenting with MPGO and encountered a strange error when working with some of my assemblies. Specifically:

C:\Temp\mpgo test>mpgo -scenario App.exe -assemblylist App.exe -OutDir . 

Error:  Timeout or error when trying to instrument assembly C:\Temp\mpgo test\App.exe (FFFFFFFF) 
Profile information will not be collected for this assembly. 
This will not prevent information from being collected for other assemblies 

Error:  Timeout or Error when trying to remove instrumented assembly C:\Temp\mpgo test\App.exe (FFFFFFFF) 
Failed to merge collected profile data into assembly C:\Temp\mpgo test\App.exe: 
Unexpected Internal Exception The file "C:\Temp\mpgo test\App.ibc" does not exist

This error struck me as odd, because the application in question was really simple, and I certainly didn’t know what error FFFFFFFF meant. I tried specifying the full path to the executable, and got a different error instead:

C:\Temp\mpgo test>mpgo -scenario "C:\temp\mpgo test\App.exe" -assemblylist "C:\temp\mpgo test\App.exe" -OutDir . 

Session executable does not appear to exist.

QR: Inline image 1

Posted via email from Jasper-net

How to: Make Innerglows with Expression Blend.

|
Inline image 3

I'm knee deep in a WPF project i'm writing for my team. I had the need today to have an innerglow, and noticed that we seem to have forgotten this little BitmapEffect of goodness (which I'll be promptly hassling Jon tomorrow for in the next revision).

That being said, as stubborn as I am I decided to try my hand at producing my own InnerGlow effect. It was actually very simple procedure to replicate inside Expression Blend.

Step 1.

Inline image 1

Define your shape. In this case I went with a rounded Rectangle, but you can use any shape you see fit and firstly you need to figure out your base shape.

Note: Now it's important here to note, that you need to think of this as being "Pancakes" in terms of the design composition.

Don't worry to much about pixel perfect precision inside Vector either.  A illustrator friend of mine once gave me a basic rule to live with when it comes to Vector art:

You can hide a lot of imperfections, as given you can zoom endlessly you get to the point were the naked eye can't see it and move on..

Couldn't agree more.

Step 2.
Simply copy the shape (CTRL+C) and hit Paste keys (CTRL+V). It should paste exactly on top of the previous shape and retain the exact x/y co-ordinates.

Rename your layer to something suites you, I myself called it IcnInnerGlow

QR: Inline image 2

Posted via email from Jasper-net