вторник, августа 21, 2012
среда, июля 11, 2012
VirtualBox машина, доступная по WiFi снаружи (VirtualBox machine available outside using WiFi connection)


Тот же самый IP мы можем увидеть, используя ipconfig и рассмотрев подключение Wireless LAN adapter.



Потребуется настроить файрволл на гостевой ОС, в простейшем случае его можно просто отключить, и пробуем пропинговать нашу виртуалку, используя WiFi. В случае с iOS я установил бесплатную утилиту Free Ping, пингуем:

четверг, марта 29, 2012
Верх насилия над собой (или как отпилить сук, на котором сидишь) - 2
пятница, ноября 11, 2011
iPad 2 Тихий звук в наушниках
Уже подумал было, что возможен производственный брак (тем более, есть оказывается и у девайсов от такого известного производителя дефекты, о чем можно убедиться немного погуглив), как нарыл решение - оно оказалось простым и наверняка о нем знает каждый уверенный пользователь iPad:
Идем в настройки, раздел Музыка, видим там чекбокс на ограничение громкости, снимаем его и выставляем в слайдере максимальное значение, которое хотим - далее можно глохнуть в наушниках настолько насколько мы этого хотим :)
пятница, октября 07, 2011
Regex для распарсивания выражений с форматирующей маской {name: formatMask, formatLength}
Привожу код такого regex:
\{\s*(?<FieldExpression>\s*(?<FieldName>\w{1,}){1}\s*(?<FormatExpression>(\s*(?<ColonSeparator>[:])|(?<CommaSeparator>[,]))\s*(?(ColonSeparator)(?<FormatMask>\w*)|)[,]*\s?(?<Length>\d+)*)*)\s?\}
В группах имеем возможность получить сам fieldName, его маску fieldMask и длину length. Еще хочу отметить, что при работе с regex очень помогает такой инструмент как Rad Software Regular Expressions Designer -http://www.radsoftware.com.au/?from=RegexDesigner.

Пишем ajax available user control
Привет.
public partial class DemoUserControl : AjaxWebModule
{
#region demo methods here
public AjaxResponse MyDemoMethod1(string arg1, string arg2, int arg3, bool arg4)
{
AjaxResponse result = new AjaxResponse
{
AdditionalSettings = String.Format("This is response to callback with parameters {0}/{1}/{2}/{3} from server side", arg1, arg2, arg3, arg4),
CurrentPage = 0,
Records = new List<object>()
{
new
{
Date = DateTime.Now,
Data = int.MinValue
}
},
TotalRecords = 1,
TotalPages = 1
};
return result;
}
public AjaxResponse MyDemoMethod2(int arg1, bool arg2)
{
AjaxResponse result = new AjaxResponse
{
AdditionalSettings = String.Format("This is response to callback with parameters {0}/{1} from server side", arg1, arg2),
Records = new List<object>()
{
new
{
Date = DateTime.Now,
Data = int.MinValue,
OtherProperties = new List<object>{1, 2, 3}
}
}
};
return result;
}
#endregion
}
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DemoUserControl.ascx.cs" Inherits="AjaxAvailableUserControls.Application.AjaxUserControls.DemoUserControl" %>
<input type="button" onclick="click_handler();" value="click me to call server side method 1" id="btnDemo1"/><br />
<input type="button" onclick="click_handler();" value="click me to call server side method 2" id="btnDemo2"/><br />
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$("#btnDemo1").click(function()
{
jQuery.execute("MyDemoMethod1",
{ "arg1": "test string 1", "arg2": "test strign 2", "arg3": 2, "arg4": false },
{
onSuccess: function (data) {
debugger;
alert("settings:" + data.AdditionalSettings + ";currentPage:" + data.CurrentPage.toString());
},
onError: function (exception) { alert(exception); }
});
});
$("#btnDemo2").click(function () {
jQuery.execute("MyDemoMethod2",
{ "arg1": 1, "arg2": false },
{
onSuccess: function (data) {
debugger;
alert("settings:" + data.AdditionalSettings + ";currentPage:" + data.CurrentPage.toString());
},
onError: function (exception) { alert(exception); }
});
});
});
</script>
{ "arg1": 1, "arg2": false } - (int arg1, bool arg2)

Как видно, со стороны клиента мы вызываем серверный метод MyDemoMetho1 и получаем результат в объектном виде, без всяких преобразований - магия :), более того, мы имеем возможность обработать как нормальное выполнение метода, так и его ошибку в случае какой-либо исключительной ситуации.
jQuery.execute("MyDemoMethod1",
{ "arg1": "test string 1", "arg2": "test strign 2", "arg3": 2, "arg4": false },
{
onSuccess: function (data) {
debugger;
alert("settings:" + data.AdditionalSettings + ";currentPage:" + data.CurrentPage.toString());
},
onError: function (exception) { alert(exception); }
});

Как видно, результат нормально десериализован, мы имеем на руках как обычные свойства объекта data, так и коллекцию вложенных объектов Records.

Собственно, все, надеюсь вам понравилась идея? Далее идет объяснение некоторых моментов.
Итак, в первую очередь нам важно, как реализован класс AjaxWebModule, именно он предоставляет возможность вызова серверного метода со стороны клиента.
Итак, его сигнатура:
///
/// Base class for all modules contained ajax logic
///
public class AjaxWebModule : UserControl, ICallbackEventHandler
{
..................
}
/// <summary>
/// Обрабатывает запрос со стороны клиента, вызывает соотвествующий метод из текущего модуля, формирует ответ, json-сериализует его в строку и
/// отправляет обратно на клиента
/// </summary>
/// <param name="e"></param>
private void ProcessRequest(ClientDataReceivedEventArgs e)
{
e.Cancel = false;
// Данные со стороны клиента, передаваемые в качестве параметров в наш ajax метод
// Параметры должны соотвествовать структуре класса AjaxRequestParameters
// e.ClientData
AjaxRequestParameters parameters = this.ParseParameters(e.ClientData);
// вызов серверного ajax-метода
AjaxResponse response = this.MethodInvoke(parameters);
// Сериализованное состояние ответа от сервера, отправляемое клиенту в качестве ответа
// e.ServerResponse
// формируем ответ клиенту
JavaScriptSerializer serializer = new JavaScriptSerializer();
e.ServerResponse = serializer.Serialize(response);
}
Мы пока рассматриваем только серверную логику, до клиентской еще дойдем. Класс AjaxRequestParameters представляет собой следующее:
/// <summary>
/// Параметры, передаваемый в ajax метод со стороны клиента
/// </summary>
public class AjaxRequestParameters
{
/// <summary>
/// Имя вызываемого метода
/// </summary>
public string MethodName
{
get;
set;
}
/// <summary>
/// Список ЗНАЧЕНИЙ параметров, которые должны соотвествовать соотвествующим аргументам указанного метода - передаются со стороны клиента в виед пар Ключ-Значение
/// </summary>
public Dictionary<string, object> Parameters
{
get;
set;
}
}
Код его приводить наверно нет смысла, он использует рефлексию для поиска метода с заданной сигнатурой, важно то,что возвращаемый результат искомого метода должен быть AjaxResponse.
Почему нам важна сигнатура возвращаемого результата? Только потому, что нам придется данный результат передавать на клиента, а чтобы его передать, нам нужно его сериализовать в строку, потому ответ от сервера должен отвечать определенным требованиям, а именно, он должен отвечать правилам сериализации. В данном примере я просто использовал простые типы данных для объвления интерфейса AjaxResponse, вы можете использовать другой интерфейс.
// Сериализованное состояние ответа от сервера, отправляемое клиенту в качестве ответа // e.ServerResponse // формируем ответ клиенту JavaScriptSerializer serializer = new JavaScriptSerializer(); e.ServerResponse = serializer.Serialize(response);
// core. client scripts library
// created on 20111007 by smirnov andrey - duШes
// #region execute extension method
$.execute = function (methodName, parameters, options) {
/// <summary>
/// Вызывает серверный public-Метод текущего AjaxWebModule
/// </summary>
/// <param name="methodName" type="Object">
/// Аргумент methodName представляет собой имя вызываемого серверного метода, например,
/// "DemoMethod2"
/// </param>
/// <param name="parameters" type="Object">
/// Объект parameters представляет собой хеш с указанием списка параметров в виде хеш - Имя параметра - Значение, например,
/// { "id", 1 }, { "name", "test" }
/// </param>
/// <param name="options" type="Object">
/// Объект options представляет собой хеш с указанием OnSuccess handler в случае успешного завершения вызова и OnErrorHandler в случае ошибки, например
/// {
/// onSuccess: function(data) {
/// alert(deserialized_request.AdditionalSettings);
/// }
/// onError: function(data) {
/// alert("Exception thrown");
/// }
/// </param>
/// <returns type="undefined">
var settings = jQuery.extend({
control_id: null,
onSuccess: function (data) { },
onError: function (data) { alert("Exception thrown ->" + data); }
}, options || {});
var localOnSuccessHandler = function (data) {
/// <summary>
/// Данная функция является callback функцией, которая вызывается в случае успешного завершения внутреннего вызова ajaxRequest
/// </summary>
/// <param name="data" type="String">
/// Результат в виде строки - сериализованное состояние объекта-ответа со стороны серверной части
/// </param>
/// <returns type="undefined" />
var deserialized_request = $.JSON.decode(data);
settings.onSuccess(deserialized_request);
}
var localOnErrorHandler = function (exception) {
/// <summary>
/// Данная функция является callback функцией, которая вызывается в случае НЕуспешного завершения внутреннего вызова ajaxRequest
/// </summary>
/// <param name="data" type="String">
/// Результат ошибки в виде строки
/// </param>
/// <returns type="undefined" />
settings.onError(exception);
}
var arrayParameters = [];
$.each(parameters, function (name, value) {
var wrapperParameter =
{ "Key": name,
"Value": value
};
arrayParameters.push(wrapperParameter);
});
var request = {
MethodName: methodName,
Parameters: arrayParameters
};
ajaxRequest(settings.control_id, request, localOnSuccessHandler, localOnErrorHandler);
}
// #endregion
var settings = jQuery.extend({
control_id: null,
onSuccess: function (data) { },
onError: function (data) { alert("Exception thrown ->" + data); }
}, options || {});
var localOnSuccessHandler = function (data) {
/// <summary>
/// Данная функция является callback функцией, которая вызывается в случае успешного завершения внутреннего вызова ajaxRequest
/// </summary>
/// <param name="data" type="String">
/// Результат в виде строки - сериализованное состояние объекта-ответа со стороны серверной части
/// </param>
/// <returns type="undefined" />
var deserialized_request = $.JSON.decode(data);
settings.onSuccess(deserialized_request);
}
var localOnErrorHandler = function (exception) {
/// <summary>
/// Данная функция является callback функцией, которая вызывается в случае НЕуспешного завершения внутреннего вызова ajaxRequest
/// </summary>
/// <param name="data" type="String">
/// Результат ошибки в виде строки
/// </param>
/// <returns type="undefined" />
settings.onError(exception);
}
Теперь уже осталось немного, мы дошли до подготовки наших данных для отправки на сервер, здесь подгатавливаем объект request, в котором мы указали имя метода и список его параметров.
Помните класс AjaxRequestParameters на серверной стороне? да, это именно его представление, в объект класса AjaxRequestParameters может быть преобразован данный объект со стороны клиента.
var arrayParameters = [];
$.each(parameters, function (name, value) {
var wrapperParameter =
{ "Key": name,
"Value": value
};
arrayParameters.push(wrapperParameter);
});
var request = {
MethodName: methodName,
Parameters: arrayParameters
};
Все готово, вызываем ajaxRequest:
ajaxRequest(settings.control_id, request, localOnSuccessHandler, localOnErrorHandler);
Стоп, что это !!! что это за ajaxRequest такой?!!
А формируется оно в уже рассмотренном нами классе AjaxWebModule:
/// <summary>
/// Имя функции, которая будет использоваться для вызова серверного сценария со стороны клиента, принимает один аргумент ARG в виде строки
/// </summary>
[Browsable(true)]
[Category("Callback Handlers")]
[DefaultValue("serverCall")]
[Description("Имя функции, которая будет использоваться для вызова серверного сценария со стороны клиента, принимает один аргумент ARG в виде строки ")]
public string ServerCallFunctionName
{
get
{
return "ajaxRequest";
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
#region регистрация server callback function со стороны клиента - здесь формируем wrapper на функцией WebFormdoCallback
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.Page.GetType(), "AjaxRequestWebFormDoCallbackScript"))
{
string webFormDoCallbackScript = this.Page.ClientScript.GetCallbackEventReference("control_id", "serialized_request", "localOnSuccessHandler", null, "localOnErrorHandler", true);
string serverCallScript = "function " + this.ServerCallFunctionName + "(control_id, arg, localOnSuccessHandler, localOnErrorHandler){" +
"\r\n" +
"var serialized_request = $.JSON.encode(arg);\r\n" +
"if (typeof(control_id) == 'undefined' || control_id == null)\r\n" +
String.Format("{{ control_id='{0}';}}\r\n", this.UniqueID) +
webFormDoCallbackScript +
";\n}\n";
this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "AjaxRequestWebFormDoCallbackScript", serverCallScript, true);
}
#endregion
#region WebformDoCallback script registration
// fix проблемы описанной http://www.codeproject.com/KB/aspnet/pendingcallbacks.aspx
// регистрируем функцию WebForm_CallbackComplete_SyncFixed, в которой нет ошибки с обращение к переменной i в цикле for
string callbackCompleteFixScriptName = "WebForm_CallbackComplete_SyncFixed";
string callbackCompleteFixScript = @"
function WebForm_CallbackComplete_SyncFixed() {
// the var statement ensure the variable is not global
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest &&
(callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = '__CALLBACKFRAME' + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
";
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.Page.GetType(), callbackCompleteFixScriptName))
{
this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), callbackCompleteFixScriptName, callbackCompleteFixScript, true);
}
// заменяем функцию WebForm_CallbackComplete на нашу WebForm_CallbackComplete_SyncFixed и регистрируем ее на момент
// полной загрузки страницы
string onloadScriptName = "pageload_callback_complete_fix";
string onloadScript = @"
if (typeof (WebForm_CallbackComplete) == 'function') {
WebForm_CallbackComplete = WebForm_CallbackComplete_SyncFixed;
}
";
if (!this.Page.ClientScript.IsStartupScriptRegistered(callbackCompleteFixScriptName))
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName, onloadScript, true);
}
#endregion
}
Если мы посмотрим исходный код нашей страницы, то увидим результат выполнения OnPrerender:
function ajaxRequest(control_id, arg, localOnSuccessHandler, localOnErrorHandler){
var serialized_request = $.JSON.encode(arg);
if (typeof(control_id) == 'undefined' || control_id == null)
{ control_id='ctl00$Content$DemoUserControl1';}
WebForm_DoCallback(control_id,serialized_request,localOnSuccessHandler,null,localOnErrorHandler,true);
}
Собственно, здесь как раз и происходит "заворачивание" нашего "объектного" вызова в строку и передача его в WebForm_DoCallback.
Сигнатура данного метода подробно описана как в msdn, так и у меня в статьях по выполнения cakkback со стороны клиента ранее.
Передача параметров туда и обратно осталось такой же - а именно - только путем передачи строковых значений.
Мы же просто обернули все это в красивую оболочку, которой будет приятно пользоваться, но понимание того, как это все работает, важно. Вы можете расширить возможности данного подхода, например, для поддержки какого-то jQuery ui-контрола, например, грида и прочее.
Нужен этот параметр только для того, чтобы разделить вызовы из разных user controls, т.е. в том случае, когда на странице есть несколько user controls, из клиенских скриптов которых осуществляется вызов серверных методов, причем, сигнатура их может быть совпадать. Или, в том случае, когда на странице два инстанса нашего ajax available user control - тут нам и пригодится controlid, чтобы разделить вызовы, идущие к конкретному инстансу user control. Делается это так:
jQuery.execute("DemoMethod1", { "id": 1, "name": "testName" },
{
control_id: '<%= UniqueID %>',
onSuccess: function(data) {
alert("settings:" + data.AdditionalSettings + ";currentPage:" + data.CurrentPage.toString());
},
onError: function(exception) { alert(exception); }
});
среда, сентября 28, 2011
SharePoint 2010 unit testing in Visual Studio 2010
Бля ну что за лажа с шарпоинт, точнее даже не с ним :) (не кидайте камнями, решение внизу)
Вдруг выяснилось, что нельзя написать ms test targeted to .net 3.5 в Visual Studio 2010, чтобы написать парочку тестов, связанных с sharepoint 2010.
В конечном итоге так и придется использовать какие-нить тулзы типа nUnit...
Ладно, в любом случае в процессе гуглинга надыбал интересную фишку, а именно, все же можно заставить ms test выполняться в x64 mode.
Подробности здесь
http://msdn.microsoft.com/en-us/library/ee782531.aspx
что удивительно, описание в картинках, вот так бы почаще :)
Достучаться до этого диалога можно, находясь в контексте ms тестового проекта:

Как выяснилось, решение все же есть:
http://msdn.microsoft.com/en-us/library/gg601487.aspx
Testing SharePoint 2010 Applications
The capabilities listed above also enable you to write unit tests and integration tests for SharePoint 2010 applications using Visual Studio 2010 Service Pack 1. For more information about how to develop SharePoint 2010 applications using Visual Studio 2010, see SharePoint Development in Visual Studio, Building and Debugging SharePoint Solutions and Verifying and Debugging SharePoint Code by Using ALM Features.
Limitations
The following limitations apply when you re-target your test projects to use the .NET Framework 3.5:
In the .NET Framework 3.5, multitargeting is supported for test projects that contain only unit tests. The .NET Framework 3.5 does not support any other test type, such as coded UI or load test. The re-targeting is blocked for test types other than unit tests.
Execution of .NET Framework 3.5 tests is supported only in the default host adapter. It is not supported in the ASP.NET host adapter. ASP.NET applications that have to run in the ASP.NET Development Server context must be compatible with the .NET Framework 4.
Data collection support is disabled when you run tests that support .NET Framework 3.5 multitargeting. You can run code coverage by using the Visual Studio command-line tools.
Unit tests that use .NET Framework 3.5 cannot run on a remote machine.
В описании сервис-пака:
http://support.microsoft.com/kb/983509
Basic Unit Testing support for the .NET Framework 3.5
In Visual Studio 2010 SP1, you now have the functionality to test your applications that target the .NET
Итак, поехали, сервиспак радостно качаем отсюда:
http://www.microsoft.com/download/en/confirmation.aspx?id=23691

Теперь выставляем targetting framwework в .net 3.5, хост выполнения теста в x64 mode:
Наслаждаемся:

Будут вопросы, пишите :) Будет время, отвечу :)
четверг, июля 21, 2011
пятница, июля 08, 2011
[Window Server 2008, SharePoint 2010, Visual Studio, TFS] How to connect to TFS with different user credentials
Собственно, потребовалось подключиться к TFS под другим аккаунтом, оказалось, это достаточно проблематично, если сама студия уже сохранила user credentials.
Никакого диалога в студии вы не найдете, попытки disconnect в team viewer и обратный connect ничего не дадут, вы будете работать под предыдущим аккаунтом.
Проблема рассматривалась также вот здесь:
Connect to TFS with different user credentials
но мне как-то это не сильно помогло, итак мой рецепт, как это лечить:
1. Идем в control panel, фильтруем по manage passwords:

2. Далее, manage windows credentials:
Здесь видим тот аккаунт, который windows будет использовать по умолчанию для доступа к TFS:

Делаем Remove from vault, перегружаем студию, в следующей попытке сделать connect to TFS студия запросит новый аккаунт.
Кеширование аккаунта происходит по той причине, что мы сами его и сохраняем, когда выбираем чекбокс Remember my credentials:

среда, марта 31, 2010
Тесты и Exception вида "System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used"....
<Execution parallelTestCount=""<вставить нужное="" значение="">
если parallelTestCount == 0, то тесты выполняются параллельно, количество тестов в пуле выбирается самой студией...
Мне же был нужен следующий вариант:
<TestSettings name="Local" id="38863d1e-30b7-4b4a-a629-4add84f4982e" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"> <Description>These are default test settings for a local test run.</Description> <Execution parallelTestCount="1"> <TestTypeSpecific /> <Timeouts runTimeout="900000" testTimeout="900000" /> <ExecutionThread apartmentState="MTA"/> <AgentRule name="Execution Agents"> </AgentRule> </Execution> </TestSettings>
Важно: чтобы ваши изменения вступили в силу, нужно перегрузить проект/решение;
ps: попутно читал следующие ресурсы:
http://connect.microsoft.com/VisualStudio/feedback/details/534124/exception-running-tests-that-use-waithandle-waitall-waithandles
VS2010 tip: How to run unit tests in parallel
http://blogs.microsoft.co.il/blogs/dhelper/archive/2010/03/02/vs2010-tip-how-to-run-unit-tests-in-parallel.aspx
Parallel Test Execution in Visual Studio 2010
http://msmvps.com/blogs/p3net/pages/parallel-test-execution-in-visual-studio-2010.aspx
Executing Unit Tests in parallel on a multi-CPU/core machine
http://blogs.msdn.com/vstsqualitytools/archive/2009/12/01/executing-unit-tests-in-parallel-on-a-multi-cpu-core-machine.aspx
четверг, марта 25, 2010
Конфигурация WCF Service без app.config
<system.servicemodel> <!-- диагностика - включим трассировку сообщений, который будут сохраняться в файлах, указанных листенерах --> <diagnostics> <messagelogging logmalformedmessages="true" logmessagesattransportlevel="true"> </messagelogging> <behaviors> <servicebehaviors> <behavior name="SampleService.Behavior.Service"> <!-- отдаем пока исключение в процесс отдладки --> <servicedebug includeexceptiondetailinfaults="true"> <!-- разрешаем сервису отдавтать описание - wsdl --> <servicemetadata httpgetenabled="true"> </servicemetadata > </servicedebug> </behavior> <!-- привязки и их настройки --> <bindings> <webhttpbinding> <binding name="SampleService.EndPointConfiguration.Web"> allowCookies="true" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" maxBufferPoolSize="10000000" useDefaultWebProxy="true" maxReceivedMessageSize="4096"> <security mode="None"></security> </binding> </webhttpbinding> </bindings> <services> <!-- указываем сервис --> <service name="SampleService"> behaviorConfiguration="SampleService.Behavior.Service"> <endpoint address="http://127.0.0.1:9999/"> binding="webHttpBinding" behaviorConfiguration="SampleService.Behavior.EndPointBehavior" bindingConfiguration="SampleService.EndPointConfiguration.Web" contract="SampleService.IServiceContract"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"> <host> <baseaddresses> <add baseaddress="http://127.0.0.1:9999/"> </add> </baseaddresses> </host> </endpoint> </service > </system.servicemodel>
[sample_service] host=127.0.0.1 port=9999
#region binding
WebHttpBinding binding = new WebHttpBinding();
binding.AllowCookies = true;
binding.CloseTimeout = TimeSpan.FromMinutes(10);
binding.SendTimeout = TimeSpan.FromMinutes( 10 );
binding.OpenTimeout = TimeSpan.FromMinutes( 10 );
binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 );
binding.BypassProxyOnLocal = false;
binding.UseDefaultWebProxy = true;
binding.MaxBufferPoolSize = 1000000;
binding.MaxReceivedMessageSize = 1000000;
binding.Security.Mode = WebHttpSecurityMode.None;
#endregion
#region endpoint adress
Uri endpointUri = GlobalConfiguration.SETTINGS_SAMPLE_SERVICE_BASE_ADDRESS;
Uri mexEndpointUri = new Uri(String.Format("{0}/mex", endpointUri.ToString()));
#endregion
SampleServiceHost.Instance = new ServiceHost(typeof(SampleService), endpointUri);
#region wcf behaviour setup
// behoviours
SampleServiceHost.Instance.Description.Behaviors.Clear();
ServiceBehaviorAttribute behaviour = new ServiceBehaviorAttribute();
behaviour.InstanceContextMode = InstanceContextMode.Single;
behaviour.ConcurrencyMode = ConcurrencyMode.Single;
SampleServiceHost.Instance.Description.Behaviors.Add(behaviour);
ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
serviceMetadataBehavior.HttpGetEnabled = true;
SampleServiceHost.Instance.Description.Behaviors.Add(serviceMetadataBehavior);
ServiceDebugBehavior serviceDebugBehavior = new ServiceDebugBehavior();
serviceDebugBehavior.HttpHelpPageEnabled = true;
serviceDebugBehavior.HttpsHelpPageEnabled = true;
serviceDebugBehavior.IncludeExceptionDetailInFaults = true;
SampleServiceHost.Instance.Description.Behaviors.Add(serviceDebugBehavior);
#endregion
// listening end point
SampleServiceHost.Instance.AddServiceEndpoint(typeof(SampleService.IServiceContract), binding, endpointUri.ToString()).Behaviors.Add(new WebHttpBehavior());
// and mex endpoint
SampleServiceHost.Instance.AddServiceEndpoint(typeof(IMetadataExchange), binding, mexEndpointUri.ToString());
// start service
SampleServiceHost.Instance.Open();
вторник, января 19, 2010
Просто в архив ссылок
How to: Install and Configure WCF Activation Components
0. http://msdn.microsoft.com/en-us/library/ms731053.aspx
0. A Guide to Designing and Building RESTful Web Services with WCF 3.5
http://msdn.microsoft.com/en-us/library/dd203052.aspx
документация по WCF REST Services
http://msdn.microsoft.com/en-us/library/ee391967.aspx
1. javascript class, расширяющий object методами расширения для сериализации/десериализации из json
http://www.json.org/json.js
2. json-сериализация в javascript
http://www.onegeek.com.au/articles/programming/javascript-serialization.php
3. как реализовать enum в javascript
http://www.javascriptkata.com/2007/03/22/how-to-do-enumerations-enum-in-javascript/
3.1 OOP в javascript - интересная статья
http://www.webmonkey.com/tutorial/Make_OOP_Classes_in_JavaScript
3.2 Классическое наследование в javascript
http://www.crockford.com/javascript/inheritance.html
4. Использование custom-templates во flex project
http://www.hemtalreja.com/?p=136
http://www.morearty.com/blog/2006/05/19/customizing-flex-builders-html-templates/
5. Библиотека для работы с JSON в Action Script
http://code.google.com/p/as3corelib/source/browse/trunk/tests/src/com/adobe/serialization/json/JSONTest.as?r=82
Использвание JSON
http://www.mikechambers.com/blog/2006/03/28/tutorial-using-json-with-flex-2-and-actionscript-3/
http://summitprojectsflashblog.wordpress.com/2008/11/06/json-and-nested-objects/
http://www.actionscript.org/resources/articles/516/1/JSON-Communication-with-Flash-Loading-Data/Page1.html
6. Настройка WCF as WEB Service
Интересная статья о том как настросить WCF Как WebService
http://kjellsj.blogspot.com/2006/12/how-to-expose-wcf-service-also-as-asmx.html
http://community.irritatedvowel.com/blogs/pete_browns_blog/archive/2008/03/19/WCF-Integration-in-Silverlight-2-Beta-1.aspx
7. Настройка WCF
CrossDomain & Clientaccesspolicy XML
http://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx
Hosting
WCF Services and ASP.NET
http://msdn.microsoft.com/en-us/library/aa702682.aspx
8. Настройка прокси
http://support.microsoft.com/kb/318140
9. Интересная статья про появление злосчастной "d" в результатх json сериализации
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/83f486af-8249-461e-9d28-2a2df539c63e
10. ASP.NET Compatibility Mode
http://blogs.msdn.com/wenlong/archive/2006/01/23/516041.aspx
11. Compress your javascript and css files
http://www.scriptalizer.com/
12. Экранная типографика
http://www.artlebedev.ru/kovodstvo/sections/62/
13. Шрифты диапозоны и специальные символы
http://www.unicode.org/charts/
DevExpress
Последние версии AspxExperience
http://www.devexpress.com/Downloads/NET/DXperience/
Клиентский центр DX
http://www.devexpress.com/Support/Center/
community & Blogs
http://community.devexpress.com/
http://community.devexpress.com/blogs/
On-line Tutorials с исходным кодом
http://demos.devexpress.com/Tutorials/
ajax toolkit tab container customization:
http://mattberseth.com/blog/2007/09/creating_a_yui_tabview_style_t.html
html colors charts:
http://www.tayloredmktg.com/rgb/
http://www.febooti.com/products/iezoom/online-help/html-color-names-16-color-chart.html
SubVersion
Написание hook-ов
http://eugene.muzychenko.net/articles/software/numeric.txt
http://icons4swrus.com/subversion-na-svoem-kompyutere.php
release notes
http://subversion.tigris.org/svn_1.5_releasenotes.html
Интеграция с системами отслеживания ошибок/проблем
http://tortoisesvn.net/docs/nightly/TortoiseSVN_ru/tsvn-dug-bugtracker.html
Консультант по Subversion - его блог и интересные заметки
http://rocksun.cn/about/
Настройка прав доступа на отдельные каталоги:
Path-Based Authorization
http://svnbook.red-bean.com/en/1.5/svn.serverconfig.pathbasedauthz.html
Flex Links
0. Explorers
http://www.jamesward.com/easingFunctionFun/easingFunctionFun.html
http://www.madeinflex.com/img/entries/2007/05/customeasingexplorer.html
http://www.merhl.com/flex2_samples/filterExplorer/
http://examples.adobe.com/flex2/consulting/styleexplorer/Flex2StyleExplorer.html
http://www.flexonrails.net/stylescreator/public/
http://www.alex-uhlmann.de/flash/adobe/blog/distortionEffects/effectCube/
0. Performing object introspection - Аналог технологии Reflection
http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_8.html
0. Flex Internals
http://www.docsultant.com/site2/articles/flex_internals.html
1. Flex 3 Essential Training with David Gassner
video lessons
http://www.lynda.com/home/DisplayCourse.aspx?lpk2=438
2. Load External CSS File
http://grfxguru.wordpress.com/2008/05/28/load-an-external-css-file-using-actionscript-3-sample-code/
3. Использование откомпилированных таблиц стилей
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html
4. Flex Component Kit Alpha for Flex 2.0.1
http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&loc=en_us&extid=1273018
The Flex Component Kit for Flash CS3 allows you to create interactive,
animated content in Flash, and use it in Flex as a Flex component.
This is an Alpha version that was built for Flex 2.0.1.
The final version will be included as part of the Flex 3 SDK.
You can watch the presentation at http://adobedev.adobe.acrobat.com/p75214263/ to learn more about the component kit.
It includes the steps required to prepare your Flash content for Flex, and examples of various interaction possibilities....
SUPPORT INFORMATION
None, the Flex 3 version will be supported. ZIP as updated on 10/10 to avoid corruption.
5. Flex Resources
Flex Components Flexbox
The Advanced Form component provides Reset, Undo and Redo functionality. Undo and Redo are accessed by pressing “ctrl-Z” and “ctrl-Y” respectively.
This component is part of flexlib (which is an awesome project). The source link above will download the whole flexlib library, you can get more information on using the flexlib components here
fle[ks]ray
Adobe Flex Components
Adobe Flex is a still young Developer Framework. For that reason there are not so many Open Source Projects out there like for other topics. Anyway, there are a few jewels. Components here
FlexLib
FlexLib is a source code repository for Flex components under an MIT license. The repository contains there open source components: ConvertibleTreeList, Draggable Slider, PromptingTextInput, Scrollable Menu Controls, SuperTabNavigator, Alternative Scrolling Canvases, Horizontal Accordion
FlexBox
FlexBox is a directory of 101 Flex components in a Flex RIA. It is a great source for locating various Flex components scattered all over the Internet.
FlexComponents Discussion List
If you are making components or extending Flex this is the mother of all lists. Backed by some of the framework engineers and packed with great devs, FlexComponents is a great resource.
Flex Exchange
Flex Exchange at Adobe.com is a directory of Flex components submitted by developers.
Adobe Flex cookbook beta
http://www.tiny.cc/VbU44
AnimatedGIfLoader Flex Component
Allows you to load animated gif files into your Flex applications
http://dougmccune.com/blog/animatedgifloader-flex-component/
Asdia
Provides an easy way to integrate flowcharts, uml or any other diagrams in flash tools.
http://code.google.com/p/asdia/
as3flexunitlib
ActionScript 3.0 framework for unit testing.
http://code.google.com/p/as3flexunitlib/
AsWing A3
Allows programmers to make their flash application(or RIA) UI easily
http://www.aswing.org/
Cairngorm
http://labs.adobe.com/wiki/index.php/Cairngorm
DisplayShelf Component
Provides a rich, templatable control to display a faux-3d view of a list of items
http://www.quietlyscheming.com/blog/components/tutorial-displayshelf-component/
flex2treemap
Treemap Component for Adobe Flex 2
http://code.google.com/p/flex2treemap/
flex4filemaker
Flex4FileMaker is an Adobe Flex 2 FileMaker API modeled after the FileMaker PHP library.
http://code.google.com/p/flex4filemaker/
FlexBook
Flex flip book component. Supports transparantcy.
http://www.quietlyscheming.com/blog/components/flexbook/
flexbox
Directory of Flex Components
http://flexbox.mrinalwadhwa.com/
flexcalendar
Flex Calendar Components
http://code.google.com/p/flexcalendar/
flexedtoolkit
Flexed Toolkit
http://code.google.com/p/flexedtoolkit/
FlexLib
community effort to create open source user interface components for Adobe Flex 2.
http://code.google.com/p/flexlib/
flexservicelocator
ServiceLocator for flex to use web service
http://code.google.com/p/flexservicelocator/
flextube
FlexTube is an flex UI front end for youtube
http://code.google.com/p/flextube/
Flex 2 Basic Email Form
Cut and dry example using an HTTP Service to send an email in Adobe Flex 2 via a simple PHP email script.
http://augiemarcello.com/flex-2-basic-email-form/
Flex 2 Debug Component
http://www.mikenimer.com/index.cfm/2006/7/5/FlexDebugPanel
Flex 2 Primitive Explorer
http://www.3gcomm.fr/Flex/PrimitiveExplorer/Flex2PrimitiveExplorer.html
Flex Developers Journal
The first and only independent magazine serving Adobe Flex developers worldwide.
http://flex.sys-con.com/
Flex Style Explorer
http://examples.adobe.com/flex2/consulting/styleexplorer/Flex2StyleExplorer.html
Fluorine
FLUORINE is an open source .NET Flash Remoting Gateway.
http://fluorine.thesilentgroup.com
Free Visual Reflection Component for Flex 2
http://blog.benstucki.net/?id=20
Granite Data Services
Free, open source (LGPL’d), alternative to AdobeA® Flex 2 Data Services for J2EE application servers.
http://www.graniteds.org/confluence/display/INTRO/Granite+Data+Services
JAM - Just ActionScript and MXML
http://www.onflex.org/code/
Live reflectiona component
http://www.rictus.com/muchado/2006/07/05/live-reflection-component/
osflash-xray
Open Source Flash Debugger for AS2/AS3/Flex1.5/Flex2
http://code.google.com/p/osflash-xray/
scale nine
themes for flex and apollo/AIR
http://www.scalenine.com/
SpringGraph
Adobe Flex 2.0 component that displays a set of items that are linked to each other.
http://mark-shepherd.com/blog/springgraph-flex-component/
The Flex Show
Jeffry Houser and Ryan Stewart’s Poscast covering Flex related topics.
http://www.theflexshow.com/blog
The ServeBox Foundry
Based on several design patterns, and includes tools built to resolve some of the recurrent Flex 2 development challenges.
http://sourceforge.net/projects/sbasfoundry
Yahoo Astra Components
Tree, Menu, TabBar, AutoComplete, and Charts
http://developer.yahoo.com/flash/astra-flash
Yahoo! Maps Web Services - Flexa„? API
http://developer.yahoo.com/maps/flash/flexGettingStarted.html
ZoomFrame
http://www.zeuslabs.us/2007/08/14/open-source-flex-component-zoomframe/
6. Eclipse & Subversion
http://subclipse.tigris.org/servlets/ProjectProcess;jsessionid=94A3F7DC2D06438DF2CB9C249CF2A1D8?pageID=p4wYuA
7. Загрузка шрифтов и их внедрение runtime
http://www.flashmorgan.com/index.php/2007/06/18/runtime-font-embedding-in-as3-there-is-no-need-to-embed-the-entire-fontset-anymore/
http://nochump.com/blog/?p=20
* Uppercase : U+0020,U+0041-U+005A
* Lowercase : U+0020,U+0061-U+007A
* Numerals : U+0030-U+0039,U+002E
* Punctuation : U+0020-U+002F,U+003A-U+0040,U+005B-U+0060,U+007B-U+007E
* Basic Latin : U+0020-U+002F, U+0030-U+0039, U+003A-U+0040, U+0041-U+005A, U+005B-U+0060, U+0061-U+007A, U+007B-U+007E
Flex Tips
0. Reducing module size ___________________________________________________________________
http://livedocs.adobe.com/flex/3/html/modular_4.html
Module size varies based on the components and classes that are used in the module.
By default, a module includes all framework code that its components depend on,
which can cause modules to be large by linking classes that overlap with the application's classes.
To reduce the size of the modules, you can optimize the module by instructing it to externalize classes
that are included by the application.
This includes custom classes and framework classes.
The result is that the module includes only the classes it requires,
while the framework code and other dependencies are included in the application.
To externalize framework classes with the command-line compiler,
you generate a linker report from the application that loads the modules.
You then use this report as input to the module's load-externs compiler option.
The compiler externalizes all classes from the module for which the application contains definitions.
This process is also necessary if your modules are in a separate project from your main application in Flex Builder.
Create and use a linker report with the command-line compiler
1. Generate the linker report and compile the application:
mxmlc -link-report=report.xml MyApplication.mxml
The default output location of the linker report is the same directory as the compiler. In this case, it would be in the bin directory.
2. Compile the module and pass the linker report to the load-externs option:
mxmlc -load-externs=report.xml MyModule.mxml