handle the new windows phone software buttons (WinRT) - xaml

What is the best way to handle the windows phone software buttons that pop up overlaying my app content.Earlier they had these hardware buttons(Back, Windows,Search Buttons) but now in some devices they have introduced software keys.Example Lumia 730 device.

There are 2 ways:
1) You can set the app or the page to auto-resize layout using
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseVisible);
However by doing this, AppBar will affect layout if ClosedDisplayMode changes...
2) To overcome problem 1, I've created the following helper class, which notifies if software buttons are being shown or not, and also gives the page's height that's being occluded by software buttons. This allows me to adjust page contents exclusively affected/hidden by software buttons.
/// <summary>
/// Handles software buttons events on Windows Phone
/// Use this to control to show occluded parts if software buttons are being shown
/// and Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().DesiredBoundsMode are set to "UseCoreWindow"
/// </summary>
public static class SoftwareButtonsHelper
{
public delegate void SoftwareButtonsChangedDelegate(Visibility softwareButtonsVisibility, double diffSize);
/// <summary>
/// Raised when software buttons visibility changes
/// </summary>
public static event SoftwareButtonsChangedDelegate SoftwareButtonsChanged;
/// <summary>
/// Current window bottom size
/// </summary>
private static double currentBottonSize = 0.0;
/// <summary>
/// Are software buttons being monitored?
/// </summary>
public static bool Listening { get; private set; }
/// <summary>
/// Software buttons visibility
/// </summary>
public static Visibility SoftwareButtonsVisibility { get; private set; }
/// <summary>
/// Current page height that's being occluded
/// </summary>
public static double CurrentInvisibleDifference { get; private set; }
/// <summary>
/// Start listening for software buttons
/// (event will raise if they appear/disappear)
/// </summary>
public static void Listen()
{
if (!Listening)
{
currentBottonSize = ApplicationView.GetForCurrentView().VisibleBounds.Bottom;
ApplicationView.GetForCurrentView().VisibleBoundsChanged += (ApplicationView sender, object args) =>
{
if (currentBottonSize != ApplicationView.GetForCurrentView().VisibleBounds.Bottom)
{
currentBottonSize = ApplicationView.GetForCurrentView().VisibleBounds.Bottom;
var currentPageAppBar = ((Window.Current.Content as Frame).Content as Page).BottomAppBar;
var isAppBarVisible = currentPageAppBar != null && currentPageAppBar.Visibility == Visibility.Visible;
var diff = Window.Current.Bounds.Bottom - currentBottonSize;
var diffAppBar = diff;
if (isAppBarVisible)
{
diffAppBar = Math.Round(diff - currentPageAppBar.Height);
diff = diffAppBar;
}
else
{
diff = Math.Round(diff);
}
if ((isAppBarVisible && diffAppBar == 0)
|| (!isAppBarVisible && diff == 0))
{
// Either contents are visible or are occluded by app bar, do nothing..
OnSoftwareButtonsChanged(Visibility.Collapsed, diff);
}
else
{
// Software buttons are active...
OnSoftwareButtonsChanged(Visibility.Visible, diff);
}
}
};
Listening = true;
}
}
/// <summary>
/// Raise event
/// </summary>
/// <param name="newVisibility"></param>
/// <param name="difference"></param>
private static void OnSoftwareButtonsChanged(Visibility newVisibility, double difference)
{
CurrentInvisibleDifference = difference;
if (SoftwareButtonsVisibility != newVisibility)
{
SoftwareButtonsVisibility = newVisibility;
if (SoftwareButtonsChanged != null)
{
SoftwareButtonsChanged(newVisibility, difference);
}
}
}
}
You just need to call SoftwareButtonsHelper.Listen(); AFTER Window.Current.Activate(); on App.xaml.cs and subscribe SoftwareButtonsHelper.SoftwareButtonsChanged on the target(s) page(s).
Hope it helps!

Related

XAML event handler in a nonroot object

Imagine the following XAML:
<Page
x:Class="MyProject.MainPage"
xmlns:local="using:MyProject">
<local:MyStackPanel>
<Button Content="Go" Click="OnGo"/>
</local:MyStackPanel>
</Page>
XAML assumes that OnGois a method in the page class. Can I somehow tell it declaratively that OnGo resides in MyStackPanel instead?
I know I can assign the event handler programmatically once the page is loaded. I'm wondering if it's possible by purely XAML means. "No" is an acceptable answer :)
For your requirement, you could bind the MyStackPanel DataContext with itself. Then create BtnClickCommand that used to bind button command in the MyStackPanel class like following.
public class MyStackPanel : StackPanel
{
public MyStackPanel()
{
}
public ICommand BtnClickCommand
{
get
{
return new RelayCommand(() =>
{
});
}
}
}
public class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
/// <summary>
/// Raised when RaiseCanExecuteChanged is called.
/// </summary>
public event EventHandler CanExecuteChanged;
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
/// <summary>
/// Determines whether this RelayCommand can execute in its current state.
/// </summary>
/// <param name="parameter">
/// Data used by the command. If the command does not require data to be passed,
/// this object can be set to null.
/// </param>
/// <returns>true if this command can be executed; otherwise, false.</returns>
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
/// <summary>
/// Executes the RelayCommand on the current command target.
/// </summary>
/// <param name="parameter">
/// Data used by the command. If the command does not require data to be passed,
/// this object can be set to null.
/// </param>
public void Execute(object parameter)
{
_execute();
}
/// <summary>
/// Method used to raise the CanExecuteChanged event
/// to indicate that the return value of the CanExecute
/// method has changed.
/// </summary>
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Usage
<local:MyStackPanel DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Button Command="{Binding BtnClickCommand}" Content="ClickMe" />
</local:MyStackPanel>

Auto detect URL, phone number, email in TextBlock

I would like to automatically highlight URL, Email and phone number in UWP. It is possible in Android but it seems this features has been forgotten by Microsoft.
In my use case, I get the text from a web service, so I don't know the text format which is a user text input on the web platform.
The platform is not supporting this feature (yet). When I've to do the same thing, I've ended with my own solution which is to:
create an attached property receiving the text to format
use some regex to extract the URL, phone numbers, email addresses from it
generate an Inlines collection which I'm injecting to the attached TextBlock control
The regex used are covering a lot of cases but some edge cases can be still missing.
It is used this way:
<TextBlock uwpext:TextBlock.InteractiveText="Here is a link www.bing.com to send to a#a.com or 0000000000" />
The attached property code:
// -------------------------------------------------------------------------------------------
/// <summary>
/// The regex to detect the URL from the text content
/// It comes from https://gist.github.com/gruber/249502 (http://daringfireball.net/2010/07/improved_regex_for_matching_urls)
/// </summary>
private static readonly Regex UrlRegex = new Regex(#"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’]))", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500));
// -------------------------------------------------------------------------------------------
/// <summary>
/// The regex to detect the email addresses
/// It comes from https://msdn.microsoft.com/en-us/library/01escwtf.aspx
/// </summary>
private static readonly Regex EmailRegex = new Regex(#"(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500));
// -------------------------------------------------------------------------------------------
/// <summary>
/// The regex to detect the phone numbers from the raw message
/// </summary>
private static readonly Regex PhoneRegex = new Regex(#"\+?[\d\-\(\)\. ]{5,}", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
// -------------------------------------------------------------------------------------------
/// <summary>
/// The default prefix to use to convert a relative URI to an absolute URI
/// The Windows RunTime is only working with absolute URI
/// </summary>
private const string RelativeUriDefaultPrefix = "http://";
// -------------------------------------------------------------------------------------------
/// <summary>
/// The dependency property to generate an interactive text in a text block.
/// When setting this property, we will parse the value and transform the hyperlink or the email address to interactive fields that the user can interact width.
/// The raw text will be parsed and convert to a collection of inlines.
/// </summary>
public static readonly DependencyProperty InteractiveTextProperty = DependencyProperty.RegisterAttached("InteractiveText", typeof(string), typeof(TextBlock), new PropertyMetadata(null, OnInteractiveTextChanged));
// -------------------------------------------------------------------------------------------
/// <summary>
/// The event callback for the interactive text changed event
/// We will parse the raw text and generate the inlines that will wrap the interactive items (URL...)
/// </summary>
/// <param name="d">the object which has raised the event</param>
/// <param name="e">the change information</param>
private static void OnInteractiveTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBlock = d as Windows.UI.Xaml.Controls.TextBlock;
if(textBlock == null) return;
// we remove all the inlines
textBlock.Inlines.Clear();
// if we have no data, we do not need to go further
var rawText = e.NewValue as string;
if(string.IsNullOrEmpty(rawText)) return;
var lastPosition = 0;
var matches = new Match[3];
do
{
matches[0] = UrlRegex.Match(rawText, lastPosition);
matches[1] = EmailRegex.Match(rawText, lastPosition);
matches[2] = PhoneRegex.Match(rawText, lastPosition);
var firstMatch = matches.Where(x => x.Success).OrderBy(x => x.Index).FirstOrDefault();
if(firstMatch == matches[0])
{
// the first match is an URL
CreateRunElement(textBlock, rawText, lastPosition, firstMatch.Index);
lastPosition = CreateUrlElement(textBlock, firstMatch);
}
else if(firstMatch == matches[1])
{
// the first match is an email
CreateRunElement(textBlock, rawText, lastPosition, firstMatch.Index);
lastPosition = CreateContactElement(textBlock, firstMatch, null);
}
else if(firstMatch == matches[2])
{
// the first match is a phonenumber
CreateRunElement(textBlock, rawText, lastPosition, firstMatch.Index);
lastPosition = CreateContactElement(textBlock, null, firstMatch);
}
else
{
// no match, we add the whole text
textBlock.Inlines.Add(new Run { Text = rawText.Substring(lastPosition) });
lastPosition = rawText.Length;
}
}
while(lastPosition < rawText.Length);
}
// -------------------------------------------------------------------------------------------
/// <summary>
/// This method will extract a fragment of the raw text string, create a Run element with the fragment and
/// add it to the textblock inlines collection
/// </summary>
/// <param name="textBlock">the textblock where to add the run element</param>
/// <param name="rawText">the raw text where the fragment will be extracted</param>
/// <param name="startPosition">the start position to extract the fragment</param>
/// <param name="endPosition">the end position to extract the fragment</param>
private static void CreateRunElement(Windows.UI.Xaml.Controls.TextBlock textBlock, string rawText, int startPosition, int endPosition)
{
var fragment = rawText.Substring(startPosition, endPosition - startPosition);
textBlock.Inlines.Add(new Run { Text = fragment });
}
// -------------------------------------------------------------------------------------------
/// <summary>
/// Create an URL element with the provided match result from the URL regex
/// It will create the Hyperlink element that will contain the URL and add it to the provided textblock
/// </summary>
/// <param name="textBlock">the textblock where to add the hyperlink</param>
/// <param name="urlMatch">the match for the URL to use to create the hyperlink element</param>
/// <returns>the newest position on the source string for the parsing</returns>
private static int CreateUrlElement(Windows.UI.Xaml.Controls.TextBlock textBlock, Match urlMatch)
{
Uri targetUri;
if(Uri.TryCreate(urlMatch.Value, UriKind.RelativeOrAbsolute, out targetUri))
{
var link = new Hyperlink();
link.Inlines.Add(new Run { Text= urlMatch.Value });
if(targetUri.IsAbsoluteUri)
link.NavigateUri = targetUri;
else
link.NavigateUri = new Uri(RelativeUriDefaultPrefix + targetUri.OriginalString);
textBlock.Inlines.Add(link);
}
else
{
textBlock.Inlines.Add(new Run { Text= urlMatch.Value });
}
return urlMatch.Index + urlMatch.Length;
}
// -------------------------------------------------------------------------------------------
/// <summary>
/// Create a hyperlink element with the provided match result from the regex that will open the contact application
/// with the provided contact information (it should be a phone number or an email address
/// This is used only if the email address / phone number is not prefixed with the mailto: / tel: scheme
/// It will create the Hyperlink element that will contain the email/phone number hyperlink and add it to the provided textblock.
/// Clicking on the link will open the contact application
/// </summary>
/// <param name="textBlock">the textblock where to add the hyperlink</param>
/// <param name="emailMatch">the match for the email to use to create the hyperlink element. Set to null if not available but at least one of emailMatch and phoneMatch must be not null.</param>
/// <param name="phoneMatch">the match for the phone number to create the hyperlink element. Set to null if not available but at least one of emailMatch and phoneMatch must be not null.</param>
/// <returns>the newest position on the source string for the parsing</returns>
private static int CreateContactElement(Windows.UI.Xaml.Controls.TextBlock textBlock, Match emailMatch, Match phoneMatch)
{
var currentMatch = emailMatch ?? phoneMatch;
var link = new Hyperlink();
link.Inlines.Add(new Run { Text= currentMatch.Value });
link.Click += (s, a) =>
{
var contact = new Contact();
if(emailMatch != null) contact.Emails.Add(new ContactEmail { Address = emailMatch.Value });
if(phoneMatch != null) contact.Phones.Add(new ContactPhone { Number = phoneMatch.Value.StripNonDigitsCharacters() });
ContactManager.ShowFullContactCard(contact, new FullContactCardOptions());
};
textBlock.Inlines.Add(link);
return currentMatch.Index + currentMatch.Length;
}
// -------------------------------------------------------------------------------------------
/// <summary>
/// Return the InteractiveText value on the provided object
/// </summary>
/// <param name="obj">the object to query</param>
/// <returns>the InteractiveText value</returns>
public static string GetInteractiveText(DependencyObject obj)
{
return (string) obj.GetValue(InteractiveTextProperty);
}
// -------------------------------------------------------------------------------------------
/// <summary>
/// SEt the InteractiveText value on the provided object
/// </summary>
/// <param name="obj">the object to query</param>
/// <param name="value">the value to set</param>
public static void SetInteractiveText(DependencyObject obj, string value)
{
obj.SetValue(InteractiveTextProperty, value);
}

MVC Custom ClientSide Validation

I have the following custom required attribute code:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class AddressRequiredAttribute : RequiredAttribute, IClientValidatable
{
/// <summary>
/// The _property name
/// </summary>
private string _propertyName;
/// <summary>
/// Initializes a new instance of the <see cref="AddressRequiredAttribute"/> class.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
public AddressRequiredAttribute(string propertyName)
: base()
{
_propertyName = propertyName;
}
/// <summary>
/// Checks that the value of the required data field is not empty.
/// </summary>
/// <param name="value">The data field value to validate.</param>
/// <returns>
/// true if validation is successful; otherwise, false.
/// </returns>
protected override ValidationResult IsValid(object value, ValidationContext context)
{
if (context.ObjectType.BaseType == typeof(AddressModel))
{
PropertyInfo property = context.ObjectType.GetProperty(_propertyName);
if (property != null && (bool)property.GetValue(context.ObjectInstance))
{
return base.IsValid(value, context);
}
}
return ValidationResult.Success;
}
/// <summary>
/// When implemented in a class, returns client validation rules for that class.
/// </summary>
/// <param name="metadata">The model metadata.</param>
/// <param name="context">The controller context.</param>
/// <returns>
/// The client validation rules for this validator.
/// </returns>
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
string errorMessage = this.ErrorMessage;
// Get the specific error message if set, otherwise the default
if (string.IsNullOrEmpty(errorMessage) && metadata != null)
{
errorMessage = FormatErrorMessage(metadata.GetDisplayName());
}
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = errorMessage,
ValidationType = "requiredaddress"
};
return new[] { clientValidationRule };
}
and the following jquery for the client side validation which is run on window.load:
$.validator.addMethod('requiredaddress', function (value, element, params) {
return value != '';
}, '');
$.validator.unobtrusive.adapters.add('requiredaddress', {}, function (options) {
options.rules['requiredaddress'] = true;
options.messages['requiredaddress'] = options.message;
});
However, the clientside doesn't kick in so I get the normal clientside validation working, then the form will submit but come back with the custom errors after postback. All the examples that I have looked at say that my code should be correct so I'm not sure what is wrong here.
Can anyone see anything obvious I'm doing wrong here, thanks
I did something similar to this and found that if I put the code in the document.ready on window.load it wouldn't work. In the end I went with using the following code placed after the jquery validate scripts:
(function ($) {
$.validator.addMethod('requiredaddress', function (value, element, params) {
return value != '';
}, 'Clientside Should Not Postback');
// i think you should be able to use this as your adapter
$.validator.unobtrusive.adapters.addBool('requiredaddress');
})(jQuery);

WCF multipart/form data with multiple files

I can't find any examples anywhere on how to process multipart/form data which contains multiple files in the request.
I'm trying to build a WCF service endpoint which contains a set of parameters in a text file, and then two image files, all in all including three files in one post. Using Fiddler, I am able to build the request and it looks like this:
HEADERS: Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Host: dhiibews.brandonb.com
Content-Length: 107865
REQUESTBODY: ---------------------------acebdf13572468
Content-Disposition: form-data; name="Json"; filename="depositcheckrequest.txt"
Content-Type: application/json
<#INCLUDE *C:\depositcheckrequest.txt*#>
---------------------------acebdf13572468
Content-Disposition: form-data; name="frontImage"; filename="front.jpg"
Content-Type: image/jpeg
<#INCLUDE *C:\front.jpg*#>
---------------------------acebdf13572468
Content-Disposition: form-data; name="rearImage"; filename="rear.jpg"
Content-Type: image/jpeg
<#INCLUDE *C:\rear.jpg*#>
---------------------------acebdf13572468--
The include tags basically end up spitting out the file content as raw data.
I've been searching and all I can find are people who can tell me how to get the information for one file which in my case ends up being the first one. I don't want to get just one file though; as you can see I am trying to upload THREE files.
How do I parse multiple files in a single multipart/form data POST request?
Ok I figured out a solution. It turns out that the framework Nancyfx includes a multipart data processor which separates the boundaries for you into substreams. So I stole the relevant files from Nancy's source code and copied them into my project. The relevant files are:
HttpMultipart.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyProjectNamespace
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
/// <summary>
/// Retrieves <see cref="HttpMultipartBoundary"/> instances from a request stream.
/// </summary>
public class HttpMultipart
{
private const byte LF = (byte)'\n';
private readonly byte[] boundaryAsBytes;
private readonly HttpMultipartBuffer readBuffer;
private readonly MemoryStream requestStream;
private readonly byte[] closingBoundaryAsBytes;
/// <summary>
/// Initializes a new instance of the <see cref="HttpMultipart"/> class.
/// </summary>
/// <param name="requestStream">The request stream to parse.</param>
/// <param name="boundary">The boundary marker to look for.</param>
public HttpMultipart(Stream requestStream, string boundary)
{
this.requestStream = new MemoryStream(ToByteArray(requestStream));
this.boundaryAsBytes = GetBoundaryAsBytes(boundary, false);
this.closingBoundaryAsBytes = GetBoundaryAsBytes(boundary, true);
this.readBuffer = new HttpMultipartBuffer(this.boundaryAsBytes, this.closingBoundaryAsBytes);
}
/// <summary>
/// Gets the <see cref="HttpMultipartBoundary"/> instances from the request stream.
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance, containing the found <see cref="HttpMultipartBoundary"/> instances.</returns>
public IEnumerable<HttpMultipartBoundary> GetBoundaries()
{
return
(from boundaryStream in this.GetBoundarySubStreams()
select new HttpMultipartBoundary(boundaryStream)).ToList();
}
private static byte[] GetBoundaryAsBytes(string boundary, bool closing)
{
var boundaryBuilder = new StringBuilder();
boundaryBuilder.Append("--");
boundaryBuilder.Append(boundary);
if (closing)
{
boundaryBuilder.Append("--");
}
else
{
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
}
var bytes =
Encoding.ASCII.GetBytes(boundaryBuilder.ToString());
return bytes;
}
private IEnumerable<HttpMultipartSubStream> GetBoundarySubStreams()
{
var boundarySubStreams = new List<HttpMultipartSubStream>();
var boundaryStart = this.GetNextBoundaryPosition();
while (MultipartIsNotCompleted(boundaryStart))
{
var boundaryEnd = this.GetNextBoundaryPosition();
boundarySubStreams.Add(new HttpMultipartSubStream(
this.requestStream,
boundaryStart,
this.GetActualEndOfBoundary(boundaryEnd)));
boundaryStart = boundaryEnd;
}
return boundarySubStreams;
}
private bool MultipartIsNotCompleted(long boundaryPosition)
{
return boundaryPosition > -1 && !this.readBuffer.IsClosingBoundary;
}
//we add two because or the \r\n before the boundary
private long GetActualEndOfBoundary(long boundaryEnd)
{
if (this.CheckIfFoundEndOfStream())
{
return this.requestStream.Position - (this.readBuffer.Length + 2);
}
return boundaryEnd - (this.readBuffer.Length + 2);
}
private bool CheckIfFoundEndOfStream()
{
return this.requestStream.Position.Equals(this.requestStream.Length);
}
private long GetNextBoundaryPosition()
{
this.readBuffer.Reset();
while (true)
{
var byteReadFromStream = this.requestStream.ReadByte();
if (byteReadFromStream == -1)
{
return -1;
}
this.readBuffer.Insert((byte)byteReadFromStream);
if (this.readBuffer.IsFull && (this.readBuffer.IsBoundary || this.readBuffer.IsClosingBoundary))
{
return this.requestStream.Position;
}
if (byteReadFromStream.Equals(LF) || this.readBuffer.IsFull)
{
this.readBuffer.Reset();
}
}
}
private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
return ms.ToArray();
}
ms.Write(buffer, 0, read);
}
}
}
}
}
HttpMultipartBuffer.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyProjectNamespace
{
public class HttpMultipartBuffer
{
private readonly byte[] boundaryAsBytes;
private readonly byte[] closingBoundaryAsBytes;
private readonly byte[] buffer;
private int position;
/// <summary>
/// Initializes a new instance of the <see cref="HttpMultipartBuffer"/> class.
/// </summary>
/// <param name="boundaryAsBytes">The boundary as a byte-array.</param>
/// <param name="closingBoundaryAsBytes">The closing boundary as byte-array</param>
public HttpMultipartBuffer(byte[] boundaryAsBytes, byte[] closingBoundaryAsBytes)
{
this.boundaryAsBytes = boundaryAsBytes;
this.closingBoundaryAsBytes = closingBoundaryAsBytes;
this.buffer = new byte[this.boundaryAsBytes.Length];
}
/// <summary>
/// Gets a value indicating whether the buffer contains the same values as the boundary.
/// </summary>
/// <value><see langword="true"/> if buffer contains the same values as the boundary; otherwise, <see langword="false"/>.</value>
public bool IsBoundary
{
get { return this.buffer.SequenceEqual(this.boundaryAsBytes); }
}
public bool IsClosingBoundary
{
get { return this.buffer.SequenceEqual(this.closingBoundaryAsBytes); }
}
/// <summary>
/// Gets a value indicating whether this buffer is full.
/// </summary>
/// <value><see langword="true"/> if buffer is full; otherwise, <see langword="false"/>.</value>
public bool IsFull
{
get { return this.position.Equals(this.buffer.Length); }
}
/// <summary>
/// Gets the the number of bytes that can be stored in the buffer.
/// </summary>
/// <value>The number of butes that can be stored in the buffer.</value>
public int Length
{
get { return this.buffer.Length; }
}
/// <summary>
/// Resets the buffer so that inserts happens from the start again.
/// </summary>
/// <remarks>This does not clear any previously written data, just resets the buffer position to the start. Data that is inserted after Reset has been called will overwrite old data.</remarks>
public void Reset()
{
this.position = 0;
}
/// <summary>
/// Inserts the specified value into the buffer and advances the internal position.
/// </summary>
/// <param name="value">The value to insert into the buffer.</param>
/// <remarks>This will throw an <see cref="ArgumentOutOfRangeException"/> is you attempt to call insert more times then the <see cref="Length"/> of the buffer and <see cref="Reset"/> was not invoked.</remarks>
public void Insert(byte value)
{
this.buffer[this.position++] = value;
}
}
}
HttpMultipartBoundary.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace DHIWebSvc.Models
{
public class HttpMultipartBoundary
{
private const byte LF = (byte)'\n';
private const byte CR = (byte)'\r';
/// <summary>
/// Initializes a new instance of the <see cref="HttpMultipartBoundary"/> class.
/// </summary>
/// <param name="boundaryStream">The stream that contains the boundary information.</param>
public HttpMultipartBoundary(HttpMultipartSubStream boundaryStream)
{
this.Value = boundaryStream;
this.ExtractHeaders();
}
/// <summary>
/// Gets the contents type of the boundary value.
/// </summary>
/// <value>A <see cref="string"/> containing the name of the value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string ContentType { get; private set; }
/// <summary>
/// Gets or the filename for the boundary value.
/// </summary>
/// <value>A <see cref="string"/> containing the filename value if it is available; otherwise <see cref="string.Empty"/>.</value>
/// <remarks>This is the RFC2047 decoded value of the filename attribute of the Content-Disposition header.</remarks>
public string Filename { get; private set; }
/// <summary>
/// Gets name of the boundary value.
/// </summary>
/// <remarks>This is the RFC2047 decoded value of the name attribute of the Content-Disposition header.</remarks>
public string Name { get; private set; }
/// <summary>
/// A stream containig the value of the boundary.
/// </summary>
/// <remarks>This is the RFC2047 decoded value of the Content-Type header.</remarks>
public HttpMultipartSubStream Value { get; private set; }
private void ExtractHeaders()
{
while (true)
{
var header =
this.ReadLineFromStream();
if (string.IsNullOrEmpty(header))
{
break;
}
if (header.StartsWith("Content-Disposition", StringComparison.CurrentCultureIgnoreCase))
{
this.Name = Regex.Match(header, #"name=""(?<name>[^\""]*)", RegexOptions.IgnoreCase).Groups["name"].Value;
this.Filename = Regex.Match(header, #"filename=""(?<filename>[^\""]*)", RegexOptions.IgnoreCase).Groups["filename"].Value;
}
if (header.StartsWith("Content-Type", StringComparison.InvariantCultureIgnoreCase))
{
this.ContentType = header.Split(new[] { ' ' }).Last().Trim();
}
}
this.Value.PositionStartAtCurrentLocation();
}
private string ReadLineFromStream()
{
var readBuffer = new StringBuilder();
while (true)
{
var byteReadFromStream = this.Value.ReadByte();
if (byteReadFromStream == -1)
{
return null;
}
if (byteReadFromStream.Equals(LF))
{
break;
}
readBuffer.Append((char)byteReadFromStream);
}
var lineReadFromStream =
readBuffer.ToString().Trim(new[] { (char)CR });
return lineReadFromStream;
}
}
}
and finally...
HttpMultipartSubStream.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace DHIWebSvc.Models
{
public class HttpMultipartSubStream : Stream
{
private readonly Stream stream;
private readonly long end;
private long start;
private long position;
/// <summary>
/// Initializes a new instance of the <see cref="HttpMultipartSubStream"/> class.
/// </summary>
/// <param name="stream">The stream to create the sub-stream ontop of.</param>
/// <param name="start">The start offset on the parent stream where the sub-stream should begin.</param>
/// <param name="end">The end offset on the parent stream where the sub-stream should end.</param>
public HttpMultipartSubStream(Stream stream, long start, long end)
{
this.stream = stream;
this.start = start;
this.position = start;
this.end = end;
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
/// </summary>
/// <returns><see langword="true"/> if the stream supports reading; otherwise, <see langword="false"/>.</returns>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <returns><see langword="true"/> if the stream supports seeking; otherwise, <see langword="false"/>.</returns>
public override bool CanSeek
{
get { return true; }
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
/// </summary>
/// <returns><see langword="true"/> if the stream supports writing; otherwise, <see langword="false"/>.</returns>
public override bool CanWrite
{
get { return false; }
}
/// <summary>
/// When overridden in a derived class, gets the length in bytes of the stream.
/// </summary>
/// <returns>A long value representing the length of the stream in bytes.</returns>
/// <exception cref="NotSupportedException">A class derived from Stream does not support seeking. </exception><exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.</exception>
public override long Length
{
get
{
return this.end - this.start;
}
}
/// <summary>
/// When overridden in a derived class, gets or sets the position within the current stream.
/// </summary>
/// <returns>
/// The current position within the stream.
/// </returns>
/// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception><exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception><exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>
public override long Position
{
get { return this.position - this.start; }
set { this.position = this.Seek(value, SeekOrigin.Begin); }
}
public void PositionStartAtCurrentLocation()
{
this.start = this.stream.Position;
}
/// <summary>
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <remarks>In the <see cref="HttpMultipartSubStream"/> type this method is implemented as no-op.</remarks>
public override void Flush()
{
}
/// <summary>
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. </returns>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source. </param>
/// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream. </param>
public override int Read(byte[] buffer, int offset, int count)
{
if (count > (this.end - this.position))
{
count = (int)(this.end - this.position);
}
if (count <= 0)
{
return 0;
}
this.stream.Position = this.position;
var bytesReadFromStream =
this.stream.Read(buffer, offset, count);
this.RepositionAfterRead(bytesReadFromStream);
return bytesReadFromStream;
}
/// <summary>
/// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
if (this.position >= this.end)
{
return -1;
}
this.stream.Position = this.position;
var byteReadFromStream = this.stream.ReadByte();
this.RepositionAfterRead(1);
return byteReadFromStream;
}
/// <summary>
/// When overridden in a derived class, sets the position within the current stream.
/// </summary>
/// <returns>The new position within the current stream.</returns>
/// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
/// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
public override long Seek(long offset, SeekOrigin origin)
{
var subStreamRelativePosition =
this.CalculateSubStreamRelativePosition(origin, offset);
this.ThrowExceptionIsPositionIsOutOfBounds(subStreamRelativePosition);
this.position = this.stream.Seek(subStreamRelativePosition, SeekOrigin.Begin);
return this.position;
}
/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <remarks>This will always throw a <see cref="InvalidOperationException"/> for the <see cref="HttpMultipartSubStream"/> type.</remarks>
public override void SetLength(long value)
{
throw new InvalidOperationException();
}
/// <summary>
/// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream. </param>
/// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream. </param>
/// <param name="count">The number of bytes to be written to the current stream. </param>
/// <remarks>This will always throw a <see cref="InvalidOperationException"/> for the <see cref="HttpMultipartSubStream"/> type.</remarks>
public override void Write(byte[] buffer, int offset, int count)
{
throw new InvalidOperationException();
}
private void ThrowExceptionIsPositionIsOutOfBounds(long subStreamRelativePosition)
{
if (subStreamRelativePosition < 0 || subStreamRelativePosition > this.end)
{
throw new InvalidOperationException();
}
}
private long CalculateSubStreamRelativePosition(SeekOrigin origin, long offset)
{
var subStreamRelativePosition = 0L;
switch (origin)
{
case SeekOrigin.Begin:
subStreamRelativePosition = this.start + offset;
break;
case SeekOrigin.Current:
subStreamRelativePosition = this.position + offset;
break;
case SeekOrigin.End:
subStreamRelativePosition = this.end + offset;
break;
}
return subStreamRelativePosition;
}
private void RepositionAfterRead(int bytesReadFromStream)
{
if (bytesReadFromStream == -1)
{
this.position = this.end;
}
else
{
this.position += bytesReadFromStream;
}
}
}
}
The usage is relatively simple for what I was trying to do. I simply defined a boundary and only look for specific part names. So for the example in my question, I used the boundary "-------------------------acebdf13572468" with three files: Json, frontImage, and rearImage.

Workflow services scalability issue

I'm currently experiencing some issues with workflow services.
They work fine if I start 4, 5 in short sequence, but if I increase this value (starting from ~10) then I get the following exception:
This channel can no longer be used to send messages as the output session was auto-closed due to a server-initiated shutdown. Either disable auto-close by setting the DispatchRuntime.AutomaticInputSessionShutdown to false, or consider modifying the shutdown protocol with the remote server.
I think that the problem is in the way I create proxies. I use the following code to provide proxies, attempting to reuse existing ones:
public abstract class ProxyProvider<TService>
where TService : class
{
/// <summary>
/// Static reference to the current time provider.
/// </summary>
private static ProxyProvider<TService> current = DefaultProxyProvider.Instance;
private TService service;
/// <summary>
/// Gets or sets the current time provider.
/// </summary>
/// <value>
/// The current time provider.
/// </value>
public static ProxyProvider<TService> Current
{
get
{
return ProxyProvider<TService>.current;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
ProxyProvider<TService>.current = value;
}
}
/// <summary>
/// Resets to default.
/// </summary>
public static void ResetToDefault()
{
ProxyProvider<TService>.current = DefaultProxyProvider.Instance;
}
/// <summary>
/// Loads the proxy.
/// </summary>
/// <param name="forceNew">if set to <c>true</c> [force new].</param>
/// <returns>The instance of the proxy.</returns>
public virtual TService Provide(bool forceNew = false)
{
if (forceNew || !this.IsInstanceValid())
{
this.service = this.CreateInstance();
return this.service;
}
return this.service;
}
/// <summary>
/// Internals the load.
/// </summary>
/// <returns>The new created service.</returns>
protected abstract TService CreateInstance();
private bool IsInstanceValid()
{
var instance = this.service as ICommunicationObject;
if (instance == null)
{
return false;
}
return instance.State != CommunicationState.Faulted && instance.State != CommunicationState.Closed && instance.State != CommunicationState.Closing;
}
/// <summary>
/// Defines the default <see cref="ProxyProvider<TService>"/> which uses the System DateTime.UtcNow value.
/// </summary>
private sealed class DefaultProxyProvider : ProxyProvider<TService>
{
/// <summary>
/// Reference to the instance of the <see cref="ProxyProvider<TService>"/>.
/// </summary>
private static ProxyProvider<TService> instance;
/// <summary>
/// Gets the instance.
/// </summary>
public static ProxyProvider<TService> Instance
{
get
{
if (DefaultProxyProvider.instance == null)
{
DefaultProxyProvider.instance = new DefaultProxyProvider();
}
return DefaultProxyProvider.instance;
}
}
/// <summary>
/// Loads the specified force new.
/// </summary>
/// <returns>A non-disposed instance of the given service.</returns>
protected override TService CreateInstance()
{
var loadedService = Activator.CreateInstance<TService>();
return loadedService;
}
}
With an additional "lazy" provider:
public class CustomConstructorProxyProvider<TService> : ProxyProvider<TService>
where TService : class
{
private readonly Func<TService> constructor;
/// <summary>
/// Initializes a new instance of the <see cref="CustomConstructorProxyProvider<TService>"/> class.
/// </summary>
/// <param name="constructor">The constructor.</param>
public CustomConstructorProxyProvider(Func<TService> constructor)
{
this.constructor = constructor;
}
/// <summary>
/// Internals the load.
/// </summary>
/// <returns>The new created service.</returns>
protected override TService CreateInstance()
{
var service = this.constructor();
return service;
}
}
Used this way:
var proxy = ProxyProvider<IWorkflowService>.Current.Provide();
proxy.DoSomething();
Initialized like this:
ProxyProvider<IWorkflowService>.Current = new CustomConstructorProxyProvider<IWorkflowService>(() => new WorkflowServiceProxy("endpoint"));
Workflow services are hosted by IIS and I added the following throttling settings:
<serviceThrottling
maxConcurrentCalls="512"
maxConcurrentInstances="2147483647"
maxConcurrentSessions="1024"/>
which should be enough for my needs.
I hope that someone can help me configuring client and server to have achieve the desired scalability (a few hundreds started in sequence and running in parallel, using the WorkflowInstance sql store).
UPDATE:
I'm using NetTcpBinding for all services.
UPDATE 2:
All services are hosted and consumed by now locally.
Thanks
Francesco