Thursday

banki

здесь рядом обсуждали будущие флэш(забавные уважаемые люди =)**), а самое интересное оказалось о конкретно одном проекте - Танки Онлайн. А они приносят в месяц 750k$ - круто(Наверно это gross)*. Технические расходы - 30к$/месяц, еще 10к или 30к где то на поддержку уходят. Делали их вроде где то год, гдето 20-30 человек. Наверно 500к$-900к$ ушло на разработку, и еще на маркетинг несколько сотен.



Вообще, тема мультиплеерных танков на флэше - до сих пор являеться одной из самой популярной. Как то пример - успех клонов Advanced Wars и Tanks. ShellShock - мультиплеерные танки великолепен не только сам по себе - а по деньгам тоже - всеголишь в 10-15 раз зарабатывает меньше Танков Онлайн.



*Пруф - сказали узнавать в вашей налоговой! =)


**ЗЫ флэш всех переживет!






Джо Ейґбобо (Joe Aigboboh) 22 роки і на відміну від багатьох своїх однолітків у нього немає облікового запису в Facebook. Втім, це не завадило йому разом зі своїм партнером Джессом Тевелоу (Jesse Tevelow) добре заробити на цій соціальній мережі. Хлопці створили міні-додаток Sticky Notes і тепер тільки на рекламі заробляють близько 45 тисяч доларів на місяць.
Sticky Notes – досить простенький Facebook-додаток, що дозволяє залишати короткі замітки. Його розробка зайняла менше тижня, проте витрачений час окуповується в декілька раз. Після того, як творцям вдалося вийти на заробіток у кілька десятків тисяч доларів на місяць, вони вирішили сконцентруватися на створенні інших додатків. Була навіть зареєстрована компанія J-Squared. Інший додаток, Glitterbox, дозволяє відправляти яскраві повідомлення та зображення.
І хоча різноманітних додатків для Facebook створено кілька тисяч, по-справжньому популярних не так багато – згідно Business Week лише близько сотні з них були встановлені понад півмільйона разів. Згадане Sticky Notes було встановлено 3,5 мільйона разів, а щодня ним користуються трохи більше 200 тисяч чоловік.
Цікаво, що навіть рідні та близькі засновників здивовані їх успіхами. Мати Джесса Тевелоу вважає сина божевільним і не вірить, що в цій області можуть бути мільйонні оборудки.

connect skydrive to windows explorer


1.Go to http://skydrive.live.com/.

2.Log in with your Windows Live ID.

3.Copy of ID cid URL https://skydrive.live.com/?wa=wsignin1.0 # cid = 1234567890abcdef

4.Open Windows Explorer.

5.In the left pane, right-click on the Network (Network Neighborhood). Select Map network drive (Network Drive).

6.Enter the address URL: \ \ docs.live.net @ SSL \ 1234567890abcdef (1234567890abcdef replace your ID)

7.Select the drive letter and click OK.

8.You will be asked to enter user accounts Windows Live ID. Enter them.

9. Now your network drive connected!

Wednesday

change favicon blogger

1.upload icon on photobucket (hello senon:) ) et a link and add following to your blogger template after </head/> tag:


<link href='{image url}' rel='shortcut icon'/>
<link href='{image url}' rel='shortcut icon' type='image/vnd.microsoft.icon'/>
<link href='{image url}' rel='icon'/>
<link href='{image url}' rel='icon' type='image/vnd.microsoft.icon'/>

Tuesday

dday ical example

         
// #1: Monthly meetings that occur on the last Wednesday from 6pm - 7pm

// Create an iCalendar
iCalendar iCal = new iCalendar();

// Create the event
Event evt = iCal.Create<Event>();
evt.Summary = "Test Event";
evt.Start = new iCalDateTime(2008, 1, 1, 18, 0, 0); // Starts January 1, 2008 @ 6:00 P.M.
evt.Duration = TimeSpan.FromHours(1);

// Add a recurrence pattern to the event
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Monthly;
rp.ByDay.Add(new DaySpecifier(DayOfWeek.Wednesday, FrequencyOccurrence.Last));
evt.AddRecurrencePattern(rp);

// #2: Yearly events like holidays that occur on the same day each year.
// The same as #1, except:
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Yearly;
evt.AddRecurrencePattern(rp);

// #3: Yearly events like holidays that occur on a specific day like the first monday.
// The same as #1, except:
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Yearly;
rp.ByMonth.Add(3);
rp.ByDay.Add(new DaySpecifier(DayOfWeek.Monday, FrequencyOccurrence.First));
evt.AddRecurrencePattern(rp);

/*
Note that all events occur on their start time, no matter their
recurrence pattern. So, for example, you could occur on the first Monday
of every month, but if your event is scheduled for a Friday (i.e.
evt.Start = new iCalDateTime(2008, 3, 7, 18, 0, 0)), then it will first
occur on that Friday, and then the first Monday of every month after
that.
*/

Thursday

plugin architecture in air

links:
http://stackoverflow.com/questions/344705/building-a-plugin-architecture-with-adobe-air

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/modules/ModuleManager.html

http://livedocs.adobe.com/flex/3/loading_applications.pdf

http://livedocs.adobe.com/flex/3/html/help.html?content=18_Client_System_Environment_5.html#119371

Monday

get country name in winforms c#


// return two letter iso number like :"ES", "SE", "CA", "BE", "DE", "AT", "NL", "NO", "CH", "FI", "FR", "IR", "LU", "SW", "AU", "UK",
public string getCountry()
{
return RegionInfo.CurrentRegion.TwoLetterISORegionName.ToUpper();
}

Thursday

caching in .net system.runtime.caching example

 
using System.Runtime.Caching;
public class UseCacheSample {
private static void UseCacheSampleMethod()
{

Demo demo;
ObjectCache cache = MemoryCache.Default;
if (cache.Contains("demo"))
{
demo = (Demo)cache.Get("demo");
}
else
{
demo = new Demo();
demo.SetTimes();
cache.Add("demo", demo, new CacheItemPolicy());
}

}
}

Wednesday

windows cannot connect to the domain vmware


here is steps how to solve this :
1. Log in as a local administrator to the VM
2. Right click on Computer. Choose Properties
3. Click Network ID
4. Run through the Wizard - you will need a Domain level administrator password that is able to validate your domain login.


Tuesday

Are you solving a real problem?

Has your customer got a ?bleeding neck?? Is your software solving a problem compelling enough that someone is going to download it, install it, evaluate it, buy it and then learn to use it, with the accompanying risks of credit card fraud and malware? It is hard to change people?s habits. They are going to keep doing what they are doing now (e.g. pen and paper or Excel) unless you can convince them your software offers them very significant advantages.



2. How much will people pay for this product?


This is a complex question and depends on many factors. You should be able to get a rough idea by looking at your closest potential competitors. But there are some types of software that people don?t expect to pay for, no matter how difficult or expensive it is to develop ? for example web browsers and media players. There are some users who can?t pay ? for example children and people in some developing countries. And there are some people who won?t pay ? for example many Linux users. So good luck selling a media player aimed at teenage Linux users in China.


3. Is the market big enough?


Is the market big enough for you to make a living? How many people are looking for solutions to this sort of problem? This is less of a problem than most people think. Given the huge number of people with Internet access and credit cards it is possible for a small company to make a decent living from a market that appears very narrow. Narrowing your market also allows you to be much more focussed in your marketing.


4. Can you promote it cost effectively?


How are you going to reach customers: Adwords, SEO, partners, magazine ads, direct mail, social media, affiliates, resellers or other methods? Can you do it cost effectively? How much is each sale from Adwords going to cost you assuming a 1% conversion rate? If it costs you $31 in advertising for each sale of a $30 product, you aren?t going to be in business long. But if you can cross-sell it to customers you already have a relationship with, that is a huge plus.



5. How much competition is there?


If there are lots of established competitors, you may have a hard time getting noticed. Personally I wouldn?t want to go into any market where I didn?t have a reasonable shot of getting to the first page on Google for at least some of the important search terms. For example, I think it would be incredibly tough to succeed with yet another Twitter, RSS, todo list or backup application. Conversely, if there are no competitors, that means that there may be no market. Creating a new market is tough, especially for a small company. Ideally you want a market where there are competitors making a decent living, but you think you can do a better job than them, or at least be different to them in some important way.


6. How is your product different?


Many vendors try very hard to reach feature parity with their competitors. But successful marketing means being different to your competitors. How is your product going to be different? What is your positioning? Note that just being cheaper than your competitors is not enough.


7. How high is the barrier to entry?


How long will it take you to create a minimum sellable product? If the barrier to entry is too high, you may never have the time, cashflow and energy to reach v1.0. As a self-funded microISV I wouldn?t want to work on any product where I couldn?t deliver something sellable (a minimum viable product) within 6 months. Conversely if the barrier to entry is too low, then it will be easy for others to copy your idea if it is successful.



8. Can you reach critical mass?


Some types of applications need a certain number of users before they can take off (network effect). For example, a massively multi-player game or auction site isn?t going to be very interesting until the number of users reaches a certain threshold. Do you have the contacts and financial resources to reach this threshold?


9. Do you have the technical skills and domain knowledge to create this product?


If not, how long will it take to learn them? Different technologies suit different types of problems. Using an inappropriate technology, just because it is one you have experience in, is unlikely to end well.


10. Are you scratching your own itch?


If you can be your own customer, then this can be very helpful in coming up with a good solution. But be wary about assuming that your needs are the same as everyone elses.



11. What is the lifetime of the product?


Is the technology is going to be obsolete or will the market disappear within a couple of years?  Are customers likely to buy upgrades to new versions? The longer you can sell a product for, the more profitable it is likely to be.


12. Is a good domain available?


Can you get a good domain for your product? Domains that contain keywords that people are likely to search on will help with SEO.


13. What are the risk factors?


Every dependency is a risk factor. If the platform your products runs on dies, then your product dies.  If you are writing an add-on for another product, then you can be put out of business pretty much overnight if the core product dies or if the functionality of your add-on is incorporated into the core product. Can you get source code for third party libraries?



14. Is the passion there?


Good software takes a lot of time and effort. Don?t believe the hype about 4 hour work weeks. Is it going to be interesting and fun? Do you have the passion and commitment to still be working on this product in 10 years time?


15. Will it make the world a better place?


Software products can be an enormous force for good in the world, increasing productivity and allowing people to do things they couldn?t do otherwise. You don?t have to be the next Google to be doing something worthwhile. But creating a ?me too? clone of an existing software package or a product that encourages anti-social behaviour (e.g. spamming) isn?t going to make the world a better place.


Making a decision


You need to look at all these criteria before you make a decision. For example, a short lifespan or a small market might be compensated for by a high ticket price. If you are evaluating several products, create a simple table with a row for each criteria and a column for each product and compare them side by side.


Did I miss any important criteria?


Friday

best mobile app ideas

В течение моды и денег: разработка мобильных приложений

Последнее время постоянно слышу о том, как знакомые начинают заниматься разработкой приложений для мобильных устройств. Их становится все больше и больше. Не понятно, откуда берутся эти команды? И где они находят разработчиков? Ответ один – это тренд и все хотят попасть в течение моды и денег.

Немного подумав, я решила собрать советы для тех, кто сам начинает заниматься разработкой мобильных приложений, верю в то, что будет полезно ))




Для начала разработки приложения нужно:

• Провести анализ мобильных платформ (необходимо разбираться в особенностях)

• Провести анализ мобильных устройств (возможности)

• Набрать команду разработчиков

• Составить возможный бюджет

• Составить маркетинговую стратегию



Чтобы правильно попасть в течение, нужно ответить на вопросы:

• Какие отрасли бизнеса нуждаются в выходе на мобильный рынок?




Актуальные отрасли для разработки приложений:

• Бизнес: планирование и менеджмент

• Общение

• Образование

• Развлечения, игры

• Финансы: управление деньгами, банковские услуги

• Геолокация

• Медицина и Фитнес


• Новости

• Социальные сети и блоги

• Видео и музыка



• Какие особенности потребительского поведения?



Занимательная схема потребительского поведения в Японии, США и Европе (по данным comscore.com)





• Как сделать приложение более эффективным в использовании конечным пользователем?




В хорошем мобильном приложении должно сочетаться три свойства:

1. Удобство в использовании. Это значит интуитивный дизайн и объединение всех возможностей мобильного устройства. Самые популярные платформы iPhone и Android, у них есть много общего, но продуманное приложение будет включать в себя функции, которые используют особенности каждой из них.

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

3. Польза. Приложение должно принести существенную пользу пользователю. Тогда он будет использовать его долгое время.




• Какие особенности монетизации на российском рынке.



Понятно, что в России ситуация обстоит иначе, чем на Американском или Европейском рынках. Активные позиции уже заняли несколько компаний, которые специализируются на разработке приложений, они понимают, что нужно рынку и как это сделать.

Считается, что около 90 процентов разработчиков не могут добиться успеха и вернуть деньги, которые вкладывались в их проекты.

На самом деле Россия — самый выгодный рынок для производителей мобильного ПО. Смартфонами в нашей стране пользуются всего 7% сотовых абонентов. Для сравнения: в Западной Европе – 28%. Российский рынок смартфонов в ближайшие годы, по прогнозам, ожидает титанический рост. Так что начинайте разрабатывать приложения уже сейчас.



Подводя итоги:

Наверное, выше представлены основные аспекты, о которых стоит задуматься до начала разработки мобильных приложений. Когда вами будет разработано первое приложение, появится опыт, вы получите feedback от пользователей, учтете его и следующее приложение будет гораздо лучше. В интернете есть множество постов, когда разработчики рассказывают о своем опыте, их тоже будет полезно почитать.

Еще полезно послушать людей, которые этим занимаются, как раз на тему создания мобильных приложений будет проходить интересное мероприятие 2 июня в Бизнес-инкубаторе «Ингрия» (Санкт-Петербург). Приглашены несколько спикеров, как со стороны агентства, так и со стороны заказчика. Подробнее на сайте ingria-startup.ru/novosti1/novosti/lead_the_way_sozdanie_mobilnih_prilozhenii/




Еще немного интересных фактов и рынке мобильных приложений:

• ТОП мобильных социальных медиа возглавляет Facebook в Европе и США, а в Японии это Mixi





• Статистика говорит о том, что к 2014 году будет скачено около 79.6 биллионов мобильных приложений



• Индустрия мобильных приложений будет составлять 35$ биллионов к 2014 году

flex urlencode

use encodeURIComponent() for that

UrlParam = UrlParam + '&name=' + encodeURIComponent(name.text) +
'&business=' + encodeURIComponent(buisness.text);
navigateToURL(new URLRequest(UrlParams),'_self');

Thursday

flex replace all string

here is example of code how to use flex replace function in order to get all replacements:

var str:String = "test xxx test yyy";
str.replace(/test/g, "WOW");
// str is now "WOW xxx WOW yyy"

flex grid refresh

here refresh samples of posible grid refresh calls

private function refresh():void{
MyDataProvider.MyDataArrayCollection.refresh();
myGrid.data=MyDataProvider.MyDataArrayCollection;
myGrid.invalidateList();
myGrid.invalidateDisplayList();
myGrid.dataProvider.refresh;
myGrid.executeBindings(false);
ArrayCollection(myGrid.dataProvider).refresh();
}

Wednesday

convert ape to mp3

with opensource software only, no installations required

1.Download ffmpg http://ffmpeg.zeranoe.com/builds/

2.Conver ape into Wav by ffmpeg.exe -i file1.ape file1.wav

3.Download lame http://lame.sourceforge.net/download.php

4.encode wav into mp3 with lame file1.wav

singelton c# (thread safe, lazy initialization )

       
public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

Friday

game sample OGS Mahjong 0.7

OGS Mahjong 0.7

Не далее чем в августе прошлого года, я писал топик о разрабатываемой силами программиста kornerr и моими небольшой игре под названием OGS Mahjong.




Будучи «проектом свободного времени», OGS Mahjong развивался медленно и неторопливо, однако за 9 месяцев его версия подросла до цифр 0.7.





Видео новой версии:

www.youtube.com/watch?v=rZ9RrAUGX7E

www.youtube.com/watch?v=3u1sxg4K5sQ



Что же изменилось в OGS Mahjong за эти 9 месяцев?




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


  • Добавлена поддержка сохранения и загрузки партии.

  • Добавлен игровой режим «Шисен-сё» в вариантах «с гравитацией» и «без гравитации».

  • Добавлено приблизительное определение оптимальных настроек при первом запуске игры.

  • Значительно изменен интерфейс.

  • Добавлена автокамера, следящая за курсором. (включается в настройках управления)

  • Добавлены понятные сообщения об ошибках и подробное логирование по принципу «все в один файл».

  • Убрана поддержка неполных тем фишек, в связи с чем удалена тема «9 мая».


  • Улучшены алгоритмы подсчета доступных ходов и выбора фишек. Это уменьшает задержки, возникающие при игре на больших раскладках.

  • Добавлена немецкая локализация.

  • По многочисленным просьбам, в архив с игрой для каждой ОС были включены файлы данных, теперь их не нужно скачивать отдельным архивом.





По этим ссылкам можно скачать игру:





При желании, можно скачать архив с дополнительной музыкой. Его нужно распаковать в директорию с игрой.



Желающие покопаться в коде могут найти исходники в Mercurial-репозитарии:

http://osrpgcreation.hg.sourceforge.net:8000/hgroot/osrpgcreation/osrpgcreation



Подробные инструкции по сборке здесь:

code.google.com/p/ogstudio/wiki/InstallMJIN

code.google.com/p/ogstudio/wiki/InstallMJ




В технологическом плане, мы считаем что вышли на финишную прямую.



Дальнейшая работа будет сосредоточена на исправлении ошибок, улучшении юзабилити и внешнего вида игры, добавлении инсталлера, а также сборке deb и rpm пакетов для обладателей соответствующих дистрибутивов linux. Со всеми этими планами попробуем уложиться в следующие полгода. Как оно получится на самом деле — увидим.



Любые отзывы по поводу проблем юзабилити и прочих багов приветствуются.



Ну и если кто-то хочет помочь нам с визуальным оформлением игры — будем рады. К сожалению, ничего кроме строчки в титрах предложить не можем.



P.S. В комментариях к прошлому топику один из хабралюдей интересовался потраченным на разработку временем. Рассказ kornerr об этом опубликован на этой странице.







Monday

distinct linq example

1.Create IEqualityComparer class

public class DistinctTitle : IEqualityComparer<SourceType> {
public bool Equals(SourceType x, SourceType y) {
return x.title.Equals(y.title);
}

public int GetHashCode(SourceType obj) {
return obj.title.GetHashCode();
}
}

2. Comparer can be used as follows:

var x = (from t in dc.table
where t.sourceId = 5
order by t.itemId descending
select t)
.Distinct(new DistinctTitle())
.Select(t=>new{t.itemId, t.sourceId, t.title });

links for learning dot.net/c#

  • XNA RPG - изучение XNA на примере построения RPG-игры (руководство из 26 частей) (link);
  • Список событий в GLOBAL.ASAX (link);

  • Проект для ASP.NET- Git Web Access (link);

ASP.NET MVC

  • ASP.NET MVC 3 для начинающих: добавляем ввод даты с помощью jQueryUI и NuGet (link);


  • Руководство по Orchard, часть 1 - запуск блога (link);

  • Руководство по Orchard, часть 2 (link);

  • Custom Role Provider. Часть 1 (link);

  • Настройка шаблонов T4 MvcScaffolding (link);


  • Управление сессиями NHibernate в приложениях ASP.NET MVC (link);

  • patterns & practices- Project Silk Drop 7 (link);

  • Исопльзование Entity Framework Fluent API и Code First в ASP.NET MVC (link);


HTML5, JavaScript, веб-стандарты:

  • Работа с CSS 3 в Expression Web (link)

  • Мнение о том, когда использовать Canvas и SVG (link);

  • Новые полезные JavaScript CSS решения 2011 года. 16 свежих плагинов для веб-разработчика (link);


  • Результаты тестирования скорости JS в браузерах (link);

  • IE9 Compat Inspector - инструмент анализа сайта на проблемы с JavaScript (link);

  • Фрактал на JavaScript с помощью HTML5 (link);

  • 14 браузерных javascript - игр, использующих HTML5 (link);


  • Расширение ваших jQuery-приложений с Amplify.js (link);

  • Useful jQuery Plugins - April 2011 (link);

  • Взрывной логотип с помощью CSS3 и MooTools или jQuery (link);



Silverlight/WP7:

  • Создание приложения для Windows Phone 7 от начала до конца (link);

  • Обновление Silverlight 4 от 19 апреля (link);

  • Новый конкурс мобильных приложений под Windows Phone 7 (link);


  • Официальный гайдлайн по использованию кнопки Download for Windows Phone 7 (link);

  • Официальное руководство по построению WP7-приложений для работы с SharePoint и UAG (link);

  • Silverlight 5.0- Custom Markup Extensions and Roles (link);

  • Лучшие БЕСПЛАТНЫЕ платформы, инструменты и элементы управления для Windows Phone 7 (link);


  • Выпущены инструменты Phoney Tools 1.0 (link);

  • Уроки по Silverlight PivotViewer (link);

  • Silverlight 5 Beta Rough Notes–Linked RichTextBoxes (link);

  • Доступны исходные коды Silverlight 5 3D-проекта Housebuilder, показанного на MIX11 (link);


  • XAML и Data Binding- Расширенные возможности разметки и связывания данных в Silverlight (link);

Облачные технологии:

  • Апрельское обновление Windows Azure AppFabric SDK и анонс доступности сервиса Windows Azure AppFabric Caching Service (link);

  • 17 диаграмм Visio с описанием работы сценариев Windows Azure AppFabric Access Control Service (link);


  • Простая организация VPN с помощью Windows Azure Connect (link);

  • Сбор диагностических данных в вашем приложении Windows Azure (link);

  • Размещение Ruby on Rails на Windows Azure - часть 2 (link);

  • Как добавить тип проекта MVC 3.01 в мастер Azure Cloud Service (link);


  • Расширения IIS для Windows Azure (link);

Инструменты:

  • Выпущена новая версия пакетного менеджера NuGet 1.3 (link);

  • Выпущена предварительная версия SQL Server 2008 R2 Service Pack 1 (link);


  • Выпущены новые версии инструментов для миграции баз данных Oracle, Sybase, Access и MySQL на SQL (link);

  • А еще в Visual Studio есть External Tools… (link);

  • Обзор новых инструментов от команды WCF, которые были представлены на MIX11 (link);

  • Reflector Умер? Да здравствует JustDecompiler (link);


Другое:

  • Сертифицированным специалистам Microsoft платят на 21 % больше (link);

  • Продукты Microsoft Windows 7, Windows Server 2008 R2 и SQL Server 2008 SP2 получили сертификацию (link);

  • Dependency Injection pattern- три способа реализации (link);

  • Associations in EF 4.1 Code First- Part 4 – Table Splitting (link);


  • Entity Framework- Database Initializers and EF Code First (link);

  • Ускоряя Stackoverflow.com (link);

Thursday

flex/air open link in new window of system browser


<mx:LinkButton label="Click here " color="#0000FF" fontWeight="bold"
click='OpenUrl(event)' x="55" y="140" width="254" textDecoration="underline"/>


<fx:Script>
<![CDATA[
import flash.net.*;
import flash.system.*;

protected function OpenUrl(event:MouseEvent):void
{
navigateToURL( new URLRequest( "http://sourcefield.blogspot.com"));
}

Friday

calculate lrc

here is procedure how to claculate LRC for a string in c#

public static byte calculateLRC(byte[] ba, int offset, int length)
{
byte lrc = 0x0;
for (int i = offset; i < length; i++)
lrc ^= ba[i];
return lrc;
}

public static byte calculateLRC(string s, int offset, int length)
{
byte[] b = Encoding.ASCII.GetBytes(s);
byte l = calculateLRC(b, offset, length);
return l;
}
public static byte calculateLRC(string s)
{
byte l = calculateLRC(s, 0, s.Length);
return l;
}

binary serializer c

below is binary serializer class sample, could be used for serialization objects into strings (not XML , fixed length string) and back.
This class is good for creation network transport protocol layer classes.
here is sample of object to serialize
 
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using CSharp.Core;
using CSharp.Core.Utility;

namespace CCLib.CCEngine
{

namespace COMDATA
{

public class ControlCharacters
{

public const byte STX = 0x2;
public const byte EOT = 0x4;
public const byte NAK = 0x15;
public const byte ACK = 0x06;
public static Char StartOfText = Convert.ToChar(0x02);
public static Char FieldSeparator = Convert.ToChar(0x1C); //Convert.ToChar(28);
public static Char RecordSeparator = Convert.ToChar(0x1D);
public static Char EndOfText = Convert.ToChar(0x03);
public static Char MessageDelimiter = Convert.ToChar(".");
}

public class ControlBytes
{
public static byte StartOfText = 0x02;
public static byte EndOfText = 0x03;
}

/// <summary>
/// Class used for converting data-structures into byte
/// </summary>
public class BinFormatter
{

public static string RemoveContrChars(string s)
{
string rt = String.Empty;
if (!String.IsNullOrEmpty(s))
{
try
{
int si = s.IndexOf(ControlCharacters.StartOfText);
int se = s.IndexOf(ControlCharacters.EndOfText);

int spos = si + 1;
int epos = se - 1;

if (epos > spos) s = s.Substring(spos, epos - spos - 1);
rt = s.Replace(ControlCharacters.FieldSeparator, '|').Replace(ControlCharacters.RecordSeparator,'?');

//replace non printable characters with whitespace
rt = Regex.Replace(rt,"[\x01-\x1F]", "");

}
catch (Exception ex)
{
Logger.prn(ex);
}
}
return rt;
}

public static string Cut(string s)
{
int st = s.IndexOf(ControlCharacters.StartOfText);
int end = s.IndexOf(ControlCharacters.EndOfText);
return s.Substring(st + 1, end - st);
}


public static byte[] AddControlCharsAndLRC(string s)
{
return AddControlCharsAndLRC(Encoding.ASCII.GetBytes(s));
}

public static byte[] AddControlCharsAndLRC(byte[] s)
{
byte[] r = new byte[s.Length + 3];
r[0] = ControlBytes.StartOfText;
s.CopyTo(r, 1);

r[s.Length + 1] = ControlBytes.EndOfText;
r[s.Length + 2] = calculateLRC(r, 1, s.Length + 2);
return r;
}


public static object RawDeserializeStr(string s, Type anytype)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(s);
return RawDeserializeEx(data, anytype);
}

public static object RawDeserializeEx(byte[] rawdatas, Type anytype)
{
int rawsize = Marshal.SizeOf(anytype);
if (rawsize > rawdatas.Length)
return null;
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
object retobj = Marshal.PtrToStructure(buffer, anytype);
handle.Free();
return retobj;

}

public static byte calculateLRC(byte[] ba, int offset, int length)
{
byte lrc = 0x0;
for (int i = offset; i < length; i++)
lrc ^= ba[i];
return lrc;
}

public static byte calculateLRC(string s, int offset, int length)
{
byte[] b = Encoding.ASCII.GetBytes(s);
byte l = calculateLRC(b, offset, length);
return l;
}
public static byte calculateLRC(string s)
{
byte l = calculateLRC(s, 0, s.Length);
return l;
}
public static byte[] RawSerializeEx(object anything)
{
int rawsize = Marshal.SizeOf(anything);
byte[] rawdatas = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr(anything, buffer, false);
handle.Free();
return rawdatas;
}

public string StrFromByte(byte[] des2)
{
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}

public static string RawSerializeStr(object anything)
{
byte[] des2 = RawSerializeEx(anything);
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}

public static string sSet(string st, int plen)
{
if (st == "" || st.Length == plen)
{
return st;
}
else
{
char[] pro = Set(st, plen);
return new string(pro);
}
}

public static string CutTill(string st, int plen)
{
if (st.Length > plen)
{
return st.Substring(0, plen);
}
else
{
return st;
}
}


public static char[] Set(string st, int plen)
{
return Set(st, plen, ' ');
}

public static char[] Set(char st)
{
char[] pro = new char[1];
pro[0] = st;
return pro;
}

public static char[] Set(string st, int plen, char white_space)
{
int slen = st.Length;
char[] pro = new string(white_space, plen).ToCharArray();// new char[plen];
int count = slen > pro.Length ? pro.Length : slen;
st.CopyTo(0, pro, 0, count);
return pro;
}




public static string GetStringFromHex(string s)
{
string result = "";
string s2 = s.Replace(" ", "");
for (int i = 0; i < s2.Length; i += 2)
{
result += Convert.ToChar(int.Parse(s2.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
}
return result;
}

public static string GetLRC(string s)
{
int checksum = 0;
foreach (char c in GetStringFromHex(s))
{
checksum ^= Convert.ToByte(c);
}
return checksum.ToString("X2");
}


}
}
}

binary serialize object c

here's sample of the object that could be serialized into string (binary not xml! ) and can be deserialized back.

it useful for creation protocols layer classes and here is example of
binary serializer
.
 
using System.Runtime.InteropServices;
using System.Text;
using CCLib.CCEngine.COMDATA;

namespace CCLib.CCEngine
{


namespace COMDATA
{
public class CApprovalCode
{
#region "Internal structures"

private SApprovalCode struc;

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct SApprovalCode
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public char[] ApprovalCode;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public char[] RetrievalRefNumber;
}

public const int struc_size = 18;

#endregion

#region "Properties"

public string ApprovalCode
{
set { struc.ApprovalCode = BinFormatter.Set(value, 6); }
get { return new string(struc.ApprovalCode); }
}

public string RetrievalRefNumber
{
set { struc.RetrievalRefNumber = BinFormatter.Set(value, 12); }
get { return new string(struc.RetrievalRefNumber); }
}

#endregion

#region "Methods"

public CApprovalCode()
{
struc = new SApprovalCode();
struc.ApprovalCode = BinFormatter.Set("", 6);
struc.RetrievalRefNumber = BinFormatter.Set("", 12);
}

/// <summary>
/// Method for serializing structure into string
/// </summary>
public string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(BinFormatter.RawSerializeStr(struc));

return sb.ToString();
}


/// <summary>
/// Method for de-serializing structure
/// </summary>
public void Parse(string s)
{
if (s != null && s != "")
{
struc = (SApprovalCode)BinFormatter.RawDeserializeStr(s.Substring(0, struc_size), struc.GetType());
}
}

#endregion
} //end CApprovalCode
}
}

convert object to string

 
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using CSharp.Core;
using CSharp.Core.Utility;

// serializing object into byte array
public static byte[] RawSerializeEx(object anything)
{
int rawsize = Marshal.SizeOf(anything);
byte[] rawdatas = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr(anything, buffer, false);
handle.Free();
return rawdatas;
}


// serializing object into string
public static string RawSerializeStr(object anything)
{
byte[] des2 = RawSerializeEx(anything);
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}

convert byte array to string c

 public string StrFromByte(byte[] des2)
{
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}

convert string into array


byte[] s = Encoding.ASCII.GetBytes("convert this string into byte array");

the maximum array length quota 16384 has been exceeded while reading

this is client-side error, below is the correct way to call service:

        

[Test]
public void CC_Test_HTTPS()
{
//var svc = new Service();
//Console.WriteLine(svc.TransactionReport(args));


ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
var endpointAddress = new EndpointAddress("https://dev/CreateAccount/Service.svc");

var wsHttpBinding = new WSHttpBinding(SecurityMode.Transport)
{
MaxReceivedMessageSize = 2147483647,
MaxBufferPoolSize = 2147483647,
ReaderQuotas =
{
MaxStringContentLength = 2147483647,
MaxArrayLength = 2147483647,
MaxBytesPerRead = 2147483647,
MaxDepth = 2147483647
}
};


var s = ChannelFactory<IService>.CreateChannel(wsHttpBinding, endpointAddress);
NewAccountResp newAccountResp = s.CreateAccount(CCTestRequest);

}

Monday

http://changethis.com/manifesto/show/80.03.MicropreneurManifesto

1. "Это трудно". Это в самом деле не просто и требует много размышлений, знаний, опыта, везения и усилий.
2. "Работайте одни". Тут я не хочу соглашаться. Мне реально хочется разделить с кем нибудь хотя-бы программирование. Т.к. на него постоянно не хватает времени. У меня последний месяц на программирование осталось 5% от всего фуллтаймого времени.
3. "Сфокусируйтесь на своих сильных качествах". Это я согласен. Особенно это касается выбора темы для программы. Конечно можно делать менеджеры закладок, но гораздо лучше применять свои знания в хорошо вам знакомых профессиональных областях. Плюсов много — например там меньше конкуренция, хотя зачастую там очень трудоемкие задачи. Я пришел к своей теме, после нескольких лет размышлений.

4. "Фриланс опасен". Мне очевидно, что свой продукт создавать выгоднее.
5. "Ищите рычаг. Сделайте один раз и продавайте всегда". Согласен.
6. "Не стреляйте в луну". Это да. Лучше синица в руках, чем журавль в небе. Хотя прямо сейчас, мой знакомый создает что-то масштабов Фэйсбука.
7. "Продукт в конце. Рынок в начале". Это безусловно надо начинать с исследования рынка. Именно поэтому моя первая программа была неуспешной.
8. "Берите деньги за свою программу". Согласен на все 100%. А ведь начинал с фривары.
9. "Любите сам процесс". Да. Я заметил что полюбил процесс гораздо больше, чем само программирование.
10."Работайте ради своей свободы". Согласен. Это меня очень сильно мотивировало.
11."Станьте "черным поясом" по интернет маркетингу". Ну в определенной мере понимать в нем надо.
12. "Автоматизируйте свою работу". Это безусловно. Не жалея денег.
13. "Чем больше вы публичны, тем быстрее оно пойдет" Это не обязательно. Хотя если Вы очередной Джоэл Спольски, то блог не помешает.
14. "Провал это тоже вариант". Лучше думать о хорошем.
15. "Живите скромно, тратьте деньги на бизнес". Жить скромно трудно. А тратить деньги на бизнес лично мне еще труднее.
16. "Отвергайте рост. Вместо работников ищите фрилансеров". Лично я до сих пор не могу определиться — то ли сотрудника взять, то ли фрилансеров нанять.
С сотрудником проще работать, но трудней его заменить.

Tuesday

constant array in c#


static readonly ArrayList a = new ArrayList() { "1", "2", "3", "4", "5", "6", "7", "8" };
public bool CheckIfContains(uint i)
{
return a.Contains(""+i);
}

Thursday

cut avi files (freeware , mac included)

1.Download mcoder

from developer site:

or mencoder for MACOS


2.After unpacking mencoder run following command in unpacked directory.
(first time is start-time , second is duration.)

>mencoder -ss 00:08:57 -endpos 00:08:12 -ovc copy -oac copy file2cut.avi  -o result.avi

Tuesday

template engine .net

 
using System.Collections;

namespace Business.CustomerServices
{
public class SimpleTemplateEngine
{

public string ReadFile(string f)
{
System.IO.StreamReader file = new System.IO.StreamReader(f);
string testxmldata = file.ReadToEnd(); file.Close();
return testxmldata;
}


public string RenderFile(Hashtable values, string fileName)
{
return Render(values, ReadFile(fileName));
}


public string Render(Hashtable values, string template)
{
foreach (DictionaryEntry entry in values)
{
template = template.Replace("{$" + entry.Key + "}",""+ entry.Value);
}
return template;
}

}

}

Monday

wcf test client visual studio 2010

here is simple wcf service tester source:
    
using System;
using System.ServiceModel;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Business.CustomerServices;
using Business.WebService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
namespace BusinessWeb.Tests
{
[TestClass]
public class CreateAccountTester
{
[Test]
[Timestamp]
public void CreateAccount_Test()
{

var endpointAddress = new EndpointAddress(@"http://it003/CreateAccount/Service.svc");
var basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.MaxReceivedMessageSize = 2147483647;
basicHttpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
var s = ChannelFactory<IService>.CreateChannel(basicHttpBinding, endpointAddress);

// now I can call webservice
NewAccountResp newAccountResp = s.CreateAccount(_newAccountArgs);
Console.WriteLine(newAccountResp.AuthResponse);
}
}
}

Thursday

ninject singleton behavior

      
using Ninject.Core;
[TestClass]
public class NinjectTestClass
{

[TestMethod]
public void NinjectTestMethod()
{
// ninject mapping
var module = new InlineModule(
m => m.Bind<IDataProvider>().To<TestProvider>().Using(new SingletonBehavior()),
//....


ninject example

       
using Ninject.Core;
[TestClass]
public class ChangePaymentSourceTest
{


[TestMethod]
public void PaymentSourceChange()
{
// ninject mapping
var module = new InlineModule(
m=>m.Bind<IDataProvider>().To<TestProvider>(),
m=>m.Bind<IFeeCanceller>().To<FeeCanceller>(),
m=>m.Bind<IFeeCreator>().To<FeeCreator>(),
m => m.Bind<IAccountSynchroniser>().To<AccountSynchroniser>(),
m => m.Bind<IPaymentSourceChanger>().To<PaymentSourceChanger>()
);
//creation ninject kernel
var kernel = new StandardKernel(module);
// creation provider- test provider in our case
var provider = kernel.Get<IDataProvider>();

// getting data
IAccountBusinessObject account = provider.GetAccountBusinessObject(new AccountIdentity() { customer = 1, sub = 1 });
IInvoiceOriginator i = provider.GetInvoiceOriginator(1);
UserInfo userInfo = provider.getUserInfo(1);

var changer = kernel.Get<IPaymentSourceChanger>();
i = changer.ChangePaymentSource(userInfo, account,i, 2, 3, 1);

// 5.Synchronise account
var synchroniser = kernel.Get<IAccountSynchroniser>();
synchroniser.Synchronize(account);

Scope scope = provider.BeginTransaction();
provider.SaveInvoiceOriginator(i, scope);
provider.SaveAccountBusinessObject(account, scope);
provider.CommitTransaction(scope);
}
}

Tuesday


Я тут недавно прбежался по регистраторам. Самые дешевые


shareit
4.9% + $1 или 8.9% (мин. $1)
перевод на счет стоит $2

пэйпро
4.9% + $1
перевод на счет стоит $21
PayPro Global


фастспринг
5.9% + $.95 или 8.9%.
(Правда у фастспринга для неамериканских покупателей только карточки и paypal)
FastSpring


Есть еще esellerate и swreg которые еще дешевле, но там как я понял на дешевой комиссии они будут extended download ползователям втюхивать


Avantage

BMT Micro

Plimus

Monday

air logging framework

Using this simple logging for now:
     
package Pomodorium
{
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;


public class Logger {

public static function Write(s:String): void {
var file:File = File.applicationStorageDirectory.resolvePath('pomodorium.log');
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.APPEND);
fileStream.writeUTFBytes("\n"+s);
fileStream.close();

}

}
}

Thursday

the connection was interrupted


I was working on moving certificates from one server to another,
and when I was doing that over exporting certificates as .SST file I was getting
"The connection was interrupted" error .

I order to fix it I have to export certificates on-by-one as PFX file from another server and import
them on new one.

After this problem has been fixed.

Wednesday

UnicodeDecodeError: 'ascii' codec can't decode byte

This error can be fixed by adding this code on top of python script:

import sys
reload(sys)
sys.setdefaultencoding("latin1")

create certificate for iis


1.Downloaded and installed The IIS 6.0 Resource Kit Tools:
http://support.microsoft.com/kb/840671
download link :http://www.microsoft.com/downloads/details.aspx?FamilyID=56fc92ee-a71a-4c73-b628-ade629c89499

2.Created certificate by
C:\Program Files\IIS Resources\SelfSSL\SelfSSL.exe /N:CN=www.mysite.com /V:1000

3.Go to IIS Manager , add certificate for virtual server you will see certificate you have created in a list.

linq Ilist select

paymentApplicableTransaction subcollection is List here is how to get it:
  
var accountTransactions = from dataObject in objectsDataContext.AccountTransactions
where
(dataObject.TransactionId == transactionID || dataObject.ParentId == transactionID) &&
dataObject.StatusId != deletedStatus
select new InvoiceRecord
{
TransactionId = dataObject.TransactionId,
Amount = dataObject.TotalAmountDue,
InvoiceDueDate = dataObject.DueDate,
Tax = dataObject.Tax ?? 0,
AdditionalGracePeriod = dataObject.AdditionalGracePeriod,
StatusId = dataObject.StatusId,
RecordStatus = (int) ScopeRecordStatus.Active
,
paymentApplicableTransaction = (from pats in dataObject.BillingTransactionDetails
where pats.StatusId != deletedStatus
select new PaymentApplicableTransaction
{
AccountTransactionId =
pats.AccountTransactionId
,
BillingTransactionId =
pats.BillingTransactionId

}).OfType<IPaymentApplicableTransaction>()
.ToList()
};


Monday

csharp binary operators sample

1. declaring values to be masked : all must be pow2

public enum EnumInvoiceFlags
{
LateFeeApplied = 1,
DelinquencyApplied = 2,
Unfreezed = 4
}


applying masks:
 invoice.Flags = invoice.Flags | (int)EnumInvoiceFlags.DelinquencyApplied; 



checking if mask has specific value:
 
if ((invoice.Flags & (int)EnumInvoiceFlags.DelinquencyApplied) != (int)EnumInvoiceFlags.DelinquencyApplied)



vb.net Teleric Recurrence rule parser with boolean operations

 
Dim RecRule8 As RecurrenceRule = Nothing
If RecurrenceRule.TryParse(dtSchedule.Rows(0)("RecurrenceRule").ToString(), RecRule8) Then
Dim days As RecurrenceDay = RecRule8.Pattern.DaysOfWeekMask
chkWeekDays.Items(0).Selected = ((days And RecurrenceDay.Sunday) = RecurrenceDay.Sunday)
chkWeekDays.Items(1).Selected = ((days And RecurrenceDay.Monday) = RecurrenceDay.Monday)
chkWeekDays.Items(2).Selected = ((days And RecurrenceDay.Tuesday) = RecurrenceDay.Tuesday)
chkWeekDays.Items(3).Selected = ((days And RecurrenceDay.Wednesday) = RecurrenceDay.Wednesday)
chkWeekDays.Items(4).Selected = ((days And RecurrenceDay.Thursday) = RecurrenceDay.Thursday)
chkWeekDays.Items(5).Selected = ((days And RecurrenceDay.Friday) = RecurrenceDay.Friday)
chkWeekDays.Items(6).Selected = ((days And RecurrenceDay.Saturday) = RecurrenceDay.Saturday)
End If

Tuesday

"Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive."

If you use Visual Studio to open a Web project that was developed for the .NET Framework 2.0, the .NET Framework 3.0, or the .NET Framework 3.5, Visual Studio can automatically perform all the changes to Web.config files that are required to be able to run using .NET Framework version 4. If the project is a local IIS project and you are using IIS 7.0, Visual Studio can also reassign the application to an application pool that is associated with the .NET Framework version 4.

It is recommended that you use Visual Studio to perform the tasks that are required in order to upgrade. If you do not use Visual Studio to perform the upgrade automatically, you must manually edit the Web.config file and must manually associate the application in IIS with the .NET Framework version 4. 

Typically the procedures covered in this topic are sufficient for upgrading a Web application, because later versions of the .NET Framework are designed to be backward compatible with earlier versions. However, you should also look in the readme documentation for breaking changes. The behavior of a component that was developed for an earlier version of the .NET Framework might have changed in the newer version of the .NET Framework.

NoteNote

Do not upgrade an IIS application if it has nested applications within it that target earlier versions of the .NET Framework. If an IIS application that targets the .NET Framework 3.5 or earlier is nested within an IIS application that targets the .NET Framework 4, the compiler might report errors when it compiles the nested application. This is because Web.config files inherit settings from files that are higher in the configuration file hierarchy. The .NET Framework 4 is backward compatible; therefore, a nested Web application that targets the .NET Framework 4 can inherit settings from Web.config files that are for earlier versions. But earlier versions of the .NET Framework are not forward compatible; therefore, they cannot inherit settings from a .NET Framework 4 Web.config file.

To upgrade an application by using Visual Studio

  1. Open the Web site or project in Visual Studio.

  2. If a Visual Studio Conversion Wizard welcome dialog box appears, click Next.

    This wizard appears when you open a Web Application Project or a solution. It does not appear when you open a Web Site project that is not in a solution.

    Visual Studio Conversion Wizard dialog box
  3. If you are converting a project, in the Visual Studio Conversion Wizard, select backup options and click Next in the Choose Whether to Create a Backup dialog box.

    Visual Studio Conversion Wizard backup dialog box

    Visual Studio upgrades your project file to the Visual Studio 2010 format. If you are upgrading a solution instead of an individual project, Visual Studio upgrades the solution file to the Visual Studio 2010 format.

  4. If you are converting a project, in the Visual Studio Conversion Wizard, click Next in the Ready to Convert dialog box.

    Visual Studio Conversion Wizard Ready dialog box
  5. If you are opening the Web project on a computer that does not have the .NET Framework 3.5 installed, in the Project Target Framework Not Installed dialog box, select Retarget the project to .NET Framework 4 and click OK.

    Project Target Framework Not Installed dialog box
  6. If you are opening the Web project on a computer that does have the .NET Framework 3.5 installed, in the Web Site targeting older .NET Framework Found dialog box, clear the check box if you do not want to upgrade all Web sites or projects in a solution.

    .NET Framework version selection Dialog Box
  7. In the dialog box, click Yes.

    Visual Studio updates the Web.config file. The changes that are made to the Web.config file are listed in the procedure later in this topic that explains how to update the Web.config file manually. Visual Studio does not update comments. Therefore, after the conversion, the Web.config file might contain comments that reference earlier versions of the .NET Framework. 

    Visual Studio automatically sets the controlRenderingCompatibilityVersion attribute of the pages element to 3.5. You can remove this setting in order to take advantage of XHTML and accessibility improvements in ASP.NET 4. For more information, see the procedure later in this topic that explains how to update the Web.config file manually.

  8. If you are converting a project, in the Visual Studio Conversion Wizard, click Close in the Conversion Complete dialog box.

    Visual Studio Conversion Wizard Close dialog box
  9. If the project is not a local IIS project, associate its IIS application with the Visual Studio when it is deployed to IIS. For more information, see the procedure later in this topic that corresponds to the version of IIS that you are using.

    If the IIS application is associated with the .NET Framework 2.0, the site will not work. ASP.NET will generate errors that indicate that the targetFramework attribute is unrecognized.

  10. If the project is a local IIS project and the IIS version is 6.0, associate its IIS application with the Visual Studio by following the procedure later in this topic for IIS 6.0. 

    If the project is a local IIS project, Visual Studio automatically performs this association. It assigns the application to the first available application pool for the .NET Framework version 4. If no application pool exists, Visual Studio creates one.

    NoteNote

    By default, the IIS 6.0 Metabase API that Visual Studio uses to assign and create application pools is not available in Windows Vista or Windows 7. To make it available, enable IIS 6 Metabase Compatibility Layer in the Windows Control Panel by selecting Programs and Features and Turn Windows Features On or Off. The following illustration shows the Windows Features dialog box.

    Turn Windows Features On or Off dialog box
  11. If the project includes code that accesses the HttpBrowserCapabilities object (in the HttpRequest.Browser property), test the code to make sure that it works as expected.

    The browser definition files that provide information to the HttpBrowserCapabilities object were changed in ASP.NET 4, and the changes are not backward compatible with earlier versions of ASP.NET. If you discover a problem and prefer not to change your code to accommodate the ASP.NET 4 changes, you can copy the ASP.NET 3.5 browser definition files from the ASP.NET 3.5 Browsers folder of a computer that has ASP.NET 3.5 installed to the ASP.NET 4 Browsers folder. The Browsers folder for a version of ASP.NET can be found in the following location:

    %SystemRoot%\Microsoft.NET\Framework\versionNumber\Config\Browsers

    After you copy the browser definition files, you must run the aspnet_regbrowsers.exe tool. For more information, see ASP.NET Web Server Controls and Browser Capabilities.

To manually upgrade an application's Web.config file from the .NET Framework 3.5 to the .NET Framework 4

  1. Make sure that the application currently targets ASP.NET 3.5.

    NoteNote

    This topic explains how to convert a Web.config file from the .NET Framework 3.5 to the .NET Framework 4. To upgrade a Web application that is earlier than the .NET Framework 3.5, you must first convert the application to the .NET Framework 3.5. For more information, see Converting to ASP.NET 3.5.

  2. Open the Web.config file in the application root.

  3. In the configSections section, remove the sectionGroup element that is named "system.web.extensions".

  4. In the system.web section, in the compilation collection, remove every add element that refers to an assembly of the .NET Framework.

    Framework assemblies generally begin with "System.". Typically these have Version=3.5.0.0 in the assembly attribute. However, some assembly entries that have the 3.5.0.0 version number might refer to assemblies that were installed as part of add-on releases, or to custom assemblies. Do not delete these. If the Web.config file contains any of these references, you must investigate them individually to determine whether a later version is available and whether the version reference must be changed.

  5. Add a targetFramework attribute to the compilation element in the system.web section, as shown in the following example:

    <compilation targetFramework="4.0">

    In the opening tag for the pages section, add a controlRenderingCompatibility attribute, as shown in the following example:

    <pages controlRenderingCompatibilityVersion="3.5"/>

    Many ASP.NET 4 controls render HTML that is compliant with XHTML and accessibility standards. However, the Web site that you are converting might have CSS rules or client script that will not work correctly if Web pages change the way they render HTML. If you want to take advantage of the control rendering enhancements in ASP.NET 4, you can omit this attribute. For more information, see ControlRenderingCompatibilityVersion.

  6. In the system.codedom section, in the compilers collection, remove the compiler elements for c# and vb.

  7. Delete everything between the system.webserver section start and end tags, but leave the tags themselves.

  8. Delete everything between the runtime section start and end tags, but leave the tags themselves.

  9. If you have customized the Web.config file, and if any customizations refer to custom assemblies or classes, make sure that the assemblies or classes are compatible with the .NET Framework version 4.

    The following example shows an example Web.config file for a simple Web application that was converted from the .NET Framework version 3.5 to the .NET Framework version 4.

    <?xml version="1.0"?>

    <!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
    -->
    <configuration>
    <appSettings/>
    <connectionStrings>
    <add name="NorthwindConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

    </connectionStrings>
    <system.web>
    <!--
    Set compilation debug="true" to insert debugging
    symbols into the compiled page. Because this
    affects performance, set this value to true only
    during development.
    -->
    <compilation debug="true" targetFramework="4.0">
    <assemblies>
    </assemblies>

    </compilation>
    <!--
    The <authentication> section enables configuration
    of the security authentication mode used by
    ASP.NET to identify an incoming user.
    -->
    <authentication mode="Windows"/>
    <!--
    The <customErrors> section enables configuration
    of what to do if/when an unhandled error occurs
    during the execution of a request. Specifically,
    it enables developers to configure html error pages
    to be displayed in place of a error stack trace.
    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">

    <error statusCode="403" redirect="NoAccess.htm" />
    <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>
    -->
    <pages controlRenderingCompatibilityVersion="3.5"/></system.web>
    <system.codedom>

    </system.codedom>
    <!--
    The system.webServer section is required for running ASP.NET AJAX under Internet Information Services 7.0. It is not necessary for previous version of IIS.
    -->
    <system.webServer>
    </system.webServer>
    </configuration>

To associate an IIS application with the .NET Framework 4 in IIS 7.0

  1. In Windows, start Inetmgr.

  2. In the Connections pane, expand the server node and then click Application Pools.

  3. On the Application Pools page, select the application pool that contains the application that you want to change.

  4. In the Actions pane, click View Applications.

  5. Select the application whose application pool hat you want to change and then click Change Application Pool in the Actions pane.

  6. In the Select Application Pool dialog box, select an application pool that is associated with .NET Framework version 4 from the Application pool list, and then click OK.

To associate an IIS application with the .NET Framework 4 in IIS 6.0

make ubuntu business casual

to make ubuntu business casual - make it black remove background: gsettings set org.gnome.desktop.background picture-options ...