mvvm Failed to create target binding for binding - data-binding

I've read a lot of solutions on the current problem but none of them worked and I cannot
figure out how to do the following:
the converter
public class HexToUIColorValueConverter : MvxValueConverter<int, UIColor>
{
protected override UIColor Convert(int value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return UIColor.FromRGB(
(((float)((value & 0xFF0000) >> 16)) / 255.0f),
(((float)((value & 0xFF00) >> 8)) / 255.0f),
(((float)(value & 0xFF)) / 255.0f)
);
}
}
the binding
public SubtitleDetailViewCell(IntPtr handle)
: base(handle)
{
Initialize();
this.DelayBind(() =>
{
Accessory = UITableViewCellAccessory.DisclosureIndicator;
var set = this.CreateBindingSet<SubtitleDetailViewCell, ObservationMedicale>();
set.Bind(MainLbl).To(observation => observation.Texte).WithConversion(new ByteArrayToStringValueConverter(), null);
set.Bind(LeftDetailLbl).To(observation => observation.SaisieLe).WithConversion(new StringFormatValueConverter(), "d MMM, HH:mm");
set.Bind(RightDetailImgLbl.Label).SourceDescribed("PraticienNom + ' ' + PraticienPrenom");
set.Bind(Label.Color).To(observation => observation.ObsCategorieCouleur).WithConversion(new HexToUIColorValueConverter(), null);
set.Apply();
});
}
the binded object
using System;
using System.Drawing;
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Next.Client.Application.iOS.Views.UI
{
[Register("CellLabelView")]
public class CellLabelView : UIView
{
public UIColor Color { get; set; }
public CellLabelView()
{
Initialize();
}
public CellLabelView(IntPtr handle)
: base(handle)
{
}
public CellLabelView(RectangleF bounds)
: base(bounds)
{
Initialize();
}
void Initialize()
{
BackgroundColor = UIColor.Clear;
Opaque = false;
}
public override void Draw(RectangleF rect)
{
base.Draw(rect);
// get graphics context
using (CGContext gc = UIGraphics.GetCurrentContext())
{
// set up drawing attributes
gc.SetLineWidth(1);
_color.SetFill();
UIColor.Clear.SetStroke();
//create geometry
var path = new CGPath();
path.AddLines(new PointF[]{
new PointF (0, 0),
new PointF (0, 8),
new PointF (4, 4),
new PointF (8, 8),
new PointF (8, 0)
});
path.CloseSubpath();
//add geometry to graphics context and draw it
gc.AddPath(path);
gc.DrawPath(CGPathDrawingMode.FillStroke);
}
}
}
}
I don't understand how it fails to bind the color, the SET method on CellLabel is never called and so my Color in the Draw() method isn't a valid object.

Currently you are trying to bind the color object directly - rather than trying to bind the color property on your label.
Try:
set.Bind(Label).For(l => l.Color).To(observation => observation.ObsCategorieCouleur).WithConversion(new HexToUIColorValueConverter(), null);
For a breakdown on this fluent syntax, including For, see https://github.com/MvvmCross/MvvmCross/wiki/Databinding#fluent
Beyond this, you probably also should try to change your Color auto-property to a property with some code inside that requests a redraw via Invalidate whenever the color is changed.

Related

Issue with Custom Pipeline component

The Custom Pipeline component developed reads the incoming stream to a folder and pass only some meta data through the MessageBox.I am using the one already availaible in Code Project
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component.Interop;
using System.IO;
namespace SendLargeFilesDecoder
{
[ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
[ComponentCategory(CategoryTypes.CATID_Decoder)]
[System.Runtime.InteropServices.Guid("53fd04d5-8337-42c2-99eb-32ac96d1105a")]
public class SendLargeFileDecoder : IBaseComponent,
IComponentUI,
IComponent,
IPersistPropertyBag
{
#region IBaseComponent
private const string _description = "Pipeline component used to save large files to disk";
private const string _name = "SendLargeFileDecoded";
private const string _version = "1.0.0.0";
public string Description
{
get { return _description; }
}
public string Name
{
get { return _name; }
}
public string Version
{
get { return _version; }
}
#endregion
#region IComponentUI
private IntPtr _icon = new IntPtr();
public IntPtr Icon
{
get { return _icon; }
}
public System.Collections.IEnumerator Validate(object projectSystem)
{
return null;
}
#endregion
#region IComponent
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
if (_largeFileLocation == null || _largeFileLocation.Length == 0)
_largeFileLocation = Path.GetTempPath();
if (_thresholdSize == null || _thresholdSize == 0)
_thresholdSize = 4096;
if (pInMsg.BodyPart.GetOriginalDataStream().Length > _thresholdSize)
{
Stream originalStream = pInMsg.BodyPart.GetOriginalDataStream();
string srcFileName = pInMsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();
string largeFilePath = _largeFileLocation + System.IO.Path.GetFileName(srcFileName);
FileStream fs = new FileStream(largeFilePath, FileMode.Create);
// Write message to disk
byte[] buffer = new byte[1];
int bytesRead = originalStream.Read(buffer, 0, buffer.Length);
while (bytesRead != 0)
{
fs.Flush();
fs.Write(buffer, 0, buffer.Length);
bytesRead = originalStream.Read(buffer, 0, buffer.Length);
}
fs.Flush();
fs.Close();
// Create a small xml file
string xmlInfo = "<MsgInfo xmlns='http://SendLargeFiles'><LargeFilePath>" + largeFilePath + "</LargeFilePath></MsgInfo>";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(xmlInfo);
MemoryStream ms = new MemoryStream(byteArray);
pInMsg.BodyPart.Data = ms;
}
return pInMsg;
}
#endregion
#region IPersistPropertyBag
private string _largeFileLocation;
private int _thresholdSize;
public string LargeFileLocation
{
get { return _largeFileLocation; }
set { _largeFileLocation = value; }
}
public int ThresholdSize
{
get { return _thresholdSize; }
set { _thresholdSize = value; }
}
public void GetClassID(out Guid classID)
{
classID = new Guid("CA47347C-010C-4B21-BFCB-22F153FA141F");
}
public void InitNew()
{
}
public void Load(IPropertyBag propertyBag, int errorLog)
{
object val1 = null;
object val2 = null;
try
{
propertyBag.Read("LargeFileLocation", out val1, 0);
propertyBag.Read("ThresholdSize", out val2, 0);
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
throw new ApplicationException("Error reading PropertyBag: " + ex.Message);
}
if (val1 != null)
_largeFileLocation = (string)val1;
if (val2 != null)
_thresholdSize = (int)val2;
}
public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
{
object val1 = (object)_largeFileLocation;
propertyBag.Write("LargeFileLocation", ref val1);
object val2 = (object)_thresholdSize;
propertyBag.Write("ThresholdSize", ref val2);
}
#endregion
}
}
The issue here is the LargeFileLocation is configurable in the receive pipeline. If I give a location for the first time for example E:\ABC\ the files are sent to the location.
But if I change the location to E:\DEF\ the files are still being sent to the previous location E:\ABC. I tried to create a new biztalk application deleting the old one but still I get the files dropped in to the old location E:\ABC\ not sure why.
Most likely the issue is with respect to Property definition of LargeFileLocation and its implementation and usage in IPersistPropertyBag interfaces. You can try following things:
Check if you have added E:\ABC path in Pipeline at design time. If
yes remove it from there and set in Admin console for first time
also and see how it behaves, my feeling is it will take temp path
location.
Change the Properties and IPersistPropertyBag implementation to use property with declaration such as public string LargeFileName {get;set;} i.e. no local variables _largeFileName.
Have you deleted the dll in %BizTalkFolder%\Pipeline Components\ ?
To refresh the pipeline component, you need delete the old dll file/remove the item in VS toolbox. then restart the VS, deploy it again.
and for this LargeFileLocation , I suggest you make it as a property so you can config it.

Generating a Barcode in c#.net

I am working on a project where i want to generate Bar-code based on an user-ID. I need a code which can generate bar-code and also is encrypted. I have found a few codes but they do not seem very helpful. Thank you in advance for help. i have tried this code but it does not provide me the barcode image.
`private void Page_Load(object sender, System.EventArgs e)
{
// Get the Requested code to be created.
string Code = Request["code"].ToString();
// Multiply the lenght of the code by 40 (just to have enough width)
int w = Code.Length * 40;
// Create a bitmap object of the width that we calculated and height of 100
Bitmap oBitmap = new Bitmap(w,100);
// then create a Graphic object for the bitmap we just created.
Graphics oGraphics = Graphics.FromImage(oBitmap);
// Now create a Font object for the Barcode Font
// (in this case the IDAutomationHC39M) of 18 point size
Font oFont = new Font("IDAutomationHC39M", 18);
// Let's create the Point and Brushes for the barcode
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
// Now lets create the actual barcode image
// with a rectangle filled with white color
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
// We have to put prefix and sufix of an asterisk (*),
// in order to be a valid barcode
oGraphics.DrawString("*" + Code + "*", oFont, oBrushWrite, oPoint);
// Then we send the Graphics with the actual barcode
Response.ContentType = "image/jpeg" ;
oBitmap.Save (Response.OutputStream, ImageFormat.Jpeg);
}`
Check out this link it is a simple code 39 barcode display which supports a header and footer, printing, saving, and is pretty well customizable. For the encryption part you will have to encrypt your message before converting it to a barcode.
From the link.
Using the code The code is very simple to use, just plop the control
onto a form and you are ready to start customizing it via the
Properties window or through your code. In addition to the
properties, there are also two public functions of interest: public
void Print() This function will display a print dialog and then print
the contents of the control to the selected printer. public void
SaveImage(string filename) This function will save the contents of the
control to a bitmap image specified by filename.
http://www.codeproject.com/Articles/10344/Barcode-NET-Control
Please try Following Code you have to add "FREE3OF9.TTF" font file in your code
Default.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
////GenerateBarCode.GenerateBarCodes("dfdfdf", Label1);
GenerateBarCode();
}
}
private void GenerateBarCode()
{
WSBarcodeGenerator.BarCodeGenerator barCodeGen = new WSBarcodeGenerator.BarCodeGenerator();
int barSize = 30;
System.Byte[] imgBarcode =Code39("123456", barSize, true, "Centralbiz...");
MemoryStream memStream = new MemoryStream(imgBarcode);
Bitmap bitmap = new Bitmap(memStream);
bitmap.Save(memStream, ImageFormat.Png);
var base64Data = Convert.ToBase64String(memStream.ToArray());
imgBar.Attributes.Add("src", "data:image/png;base64," + base64Data);
//Response.Write(bitmap);
//var base64Data = Convert.ToBase64String(memStream.ToArray());
//imgBar.Attributes.Add("src", "png");
}
public byte[] Code39(string code, int barSize, bool showCodeString, string title)
{
Code39 c39 = new Code39();
// Create stream....
MemoryStream ms = new MemoryStream();
c39.FontFamilyName = "Free 3 of 9";
c39.FontFileName = Server.MapPath("FREE3OF9.TTF");
c39.FontSize = barSize;
c39.ShowCodeString = showCodeString;
if (title + "" != "")
c39.Title = title;
Bitmap objBitmap = c39.GenerateBarcode(code);
objBitmap.Save(ms, ImageFormat.Png);
//return bytes....
return ms.GetBuffer();
}
}
public class Code39
{
private const int _itemSepHeight = 3;
SizeF _titleSize = SizeF.Empty;
SizeF _barCodeSize = SizeF.Empty;
SizeF _codeStringSize = SizeF.Empty;
#region Barcode Title
private string _titleString = null;
private Font _titleFont = null;
public string Title
{
get { return _titleString; }
set { _titleString = value; }
}
public Font TitleFont
{
get { return _titleFont; }
set { _titleFont = value; }
}
#endregion
#region Barcode code string
private bool _showCodeString = false;
private Font _codeStringFont = null;
public bool ShowCodeString
{
get { return _showCodeString; }
set { _showCodeString = value; }
}
public Font CodeStringFont
{
get { return _codeStringFont; }
set { _codeStringFont = value; }
}
#endregion
#region Barcode Font
private Font _c39Font = null;
private float _c39FontSize = 12;
private string _c39FontFileName = null;
private string _c39FontFamilyName = null;
public string FontFileName
{
get { return _c39FontFileName; }
set { _c39FontFileName = value; }
}
public string FontFamilyName
{
get { return _c39FontFamilyName; }
set { _c39FontFamilyName = value; }
}
public float FontSize
{
get { return _c39FontSize; }
set { _c39FontSize = value; }
}
private Font Code39Font
{
get
{
if (_c39Font == null)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(_c39FontFileName);
FontFamily family = new FontFamily(_c39FontFamilyName, pfc);
_c39Font = new Font(family, _c39FontSize);
}
return _c39Font;
}
}
#endregion
public Code39()
{
_titleFont = new Font("Arial", 10);
_codeStringFont = new Font("Arial", 10);
}
#region Barcode Generation
public Bitmap GenerateBarcode(string barCode)
{
int bcodeWidth = 0;
int bcodeHeight = 0;
// Get the image container...
Bitmap bcodeBitmap = CreateImageContainer(barCode, ref bcodeWidth, ref bcodeHeight);
Graphics objGraphics = Graphics.FromImage(bcodeBitmap);
// Fill the background
objGraphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, bcodeWidth, bcodeHeight));
int vpos = 0;
// Draw the title string
if (_titleString != null)
{
objGraphics.DrawString(_titleString, _titleFont, new SolidBrush(Color.Black), XCentered((int)_titleSize.Width, bcodeWidth), vpos);
vpos += (((int)_titleSize.Height) + _itemSepHeight);
}
// Draw the barcode
objGraphics.DrawString(barCode, Code39Font, new SolidBrush(Color.Black), XCentered((int)_barCodeSize.Width, bcodeWidth), vpos);
// Draw the barcode string
if (_showCodeString)
{
vpos += (((int)_barCodeSize.Height));
objGraphics.DrawString(barCode, _codeStringFont, new SolidBrush(Color.Black), XCentered((int)_codeStringSize.Width, bcodeWidth), vpos);
}
// return the image...
return bcodeBitmap;
}
private Bitmap CreateImageContainer(string barCode, ref int bcodeWidth, ref int bcodeHeight)
{
Graphics objGraphics;
// Create a temporary bitmap...
Bitmap tmpBitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
objGraphics = Graphics.FromImage(tmpBitmap);
// calculate size of the barcode items...
if (_titleString != null)
{
_titleSize = objGraphics.MeasureString(_titleString, _titleFont);
bcodeWidth = (int)_titleSize.Width;
bcodeHeight = (int)_titleSize.Height + _itemSepHeight;
}
_barCodeSize = objGraphics.MeasureString(barCode, Code39Font);
bcodeWidth = Max(bcodeWidth, (int)_barCodeSize.Width);
bcodeHeight += (int)_barCodeSize.Height;
if (_showCodeString)
{
_codeStringSize = objGraphics.MeasureString(barCode, _codeStringFont);
bcodeWidth = Max(bcodeWidth, (int)_codeStringSize.Width);
bcodeHeight += (_itemSepHeight + (int)_codeStringSize.Height);
}
// dispose temporary objects...
objGraphics.Dispose();
tmpBitmap.Dispose();
return (new Bitmap(bcodeWidth, bcodeHeight, PixelFormat.Format32bppArgb));
}
#endregion
#region Auxiliary Methods
private int Max(int v1, int v2)
{
return (v1 > v2 ? v1 : v2);
}
private int XCentered(int localWidth, int globalWidth)
{
return ((globalWidth - localWidth) / 2);
}
#endregion
}
Default.aspx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:Image ID="imgBar" runat="server" />
</asp:Content>

Caliburn Micro: How to add text to the bottom of a list box and display it

I'm trying to figure out how to add text to the bottom of a list box and display it. In WPF with code behind, I would grab the ScrollViewer and manipulate it, but I can't figure out how to do it with Caliburn...
You have a couple options.
1) In your ViewModel you can call GetView and cast it to your view type and get a reference to the ScrollViewer. Something like:
var myView = this.GetView() as MyView;
var myScrollView = myView.MyScrollView;
That works fine but isn't ideal if you're trying to not couple the view to the view model.
Option 2) is to implement IResult, see docs here.
public class ScrollViewResult : IResult
{
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
private ScrollViewResult ()
{
}
public void Execute (ActionExecutionContext context)
{
var view = context.View as FrameworkElement;
var scrollViewer = FindVisualChild<ScrollViewer>(view);
//do stuff to scrollViewer here
Completed (this, new ResultCompletionEventArgs { });
}
private static TChildItem FindVisualChild<TChildItem> (DependencyObject obj)
where TChildItem : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount (obj); i++)
{
var child = VisualTreeHelper.GetChild (obj, i);
if (child != null && child is TChildItem)
return (TChildItem)child;
var childOfChild = FindVisualChild<TChildItem> (child);
if (childOfChild != null)
return childOfChild;
}
return null;
}
//this isn't required of course but comes in handy for
//having a static method and passing parameters to the
//ctor of the IResult
public static IResult DoSomething ()
{
return new ScrollViewResult ();
}
Then you can call it like:
public IEnumerable<IResult> SomeAction()
{
yield return ScrollViewResult.DoSomething();
}

Moq how to do a setup when the item could be any of a type but must have a particular property set

I'm trying to setup for a method which will run:
dataAccess.Setup(x => x.GetCars(It.IsAny<CarFilter>()));
Ok, so I'm saying to setup the method GetCars when it is passed any object of type CarFilter.
I want to make this a little more specific.
I want to make it so it will setup when it is passed any object of type CarFilter when the property on CarFilter Color = "Red".
Does anybody know how to write this?
You can put a condition on the match using It.Is(...)
public class Car {
public string Color { get; set; }
}
public interface IFoo {
void DoIt(Car car);
}
[TestMethod]
public void PassesWhenRed() {
var mockFoo = new Mock<IFoo>();
var redCar = new Car { Color = "Red" };
mockFoo.Object.DoIt(redCar);
mockFoo.Verify(mk=>mk.DoIt(It.Is<Car>(car => car.Color == "Red"))); // Passes
}
[TestMethod]
public void FailsWhenNotRed() {
var mockFoo = new Mock<IFoo>();
var blueCar = new Car { Color = "Blue" };
mockFoo.Object.DoIt(blueCar);
mockFoo.Verify(mk=>mk.DoIt(It.Is<Car>(car => car.Color == "Red"))); // Fails
}
Ended up needing:
dataAccess.Setup(x => x.GetCars(It.Is<CarFilter>(z => z.Color == "Red")));

Unity.BuildUp unable to disambiguate

I have a class with two constructors, both constructors have one parameter. Due to restrictions not worth explaining I cannot alter the constructors or use a descendent class.
I can't use unity to create instances of this class because Unity sees 2 constructors with the same number of parameters and complains that it doesn't know which to use, which is fair enough. So instead I create the instance myself and then try to use UnityContainer.BuildUp()
var result = constructorInfo.Invoke(new object[] { content });
UnitContainer.BuildUp(result);
The above code does not set any of my [Dependency] properties nor does it call an [InjectionMethod] if I use that instead.
var result = constructorInfo.Invoke(new object[] { content });
UnitContainer.BuildUp(typeOfObject, result);
This throws another exception about ambiguous constructors, even though I am not asking it to construct the instance.
Does anyone have any ideas?
Here is an example app
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Reflection;
namespace ConsoleApplication7
{
public interface IConstructorType1 { }
public interface IConstructorType2 { }
public interface INeedThisDependency { }
public class NeedThisDependency : INeedThisDependency { }
public class MyDomainObject
{
public MyDomainObject(IConstructorType1 constructorType1) { }
public MyDomainObject(IConstructorType2 constructorType2) { }
[Dependency]
public INeedThisDependency Needed { get; set; }
}
class Program
{
static void Main(string[] args)
{
IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<INeedThisDependency, NeedThisDependency>();
//Try with type 1 constructor
ConstructorInfo constructorInfo1 = typeof(MyDomainObject).GetConstructor(new Type[] { typeof(IConstructorType1) });
MyDomainObject instance1 = CreateTheInstance(unityContainer, typeof(MyDomainObject), constructorInfo1, null);
//Try with type 2 constructor
ConstructorInfo constructorInfo2 = typeof(MyDomainObject).GetConstructor(new Type[] { typeof(IConstructorType2) });
MyDomainObject instance2 = CreateTheInstance(unityContainer, typeof(MyDomainObject), constructorInfo2, null);
}
//This is the only point I have any influence over what happens
//So this is the only place I get to change the code.
static MyDomainObject CreateTheInstance(IUnityContainer unityContainer, Type type, ConstructorInfo constructorInfo, object parameters)
{
var result = (MyDomainObject)constructorInfo.Invoke(new object[] { parameters });
//This will throw an ambiguous constructor exception,
//even though I am not asking it to construct anything
unityContainer.BuildUp(type, result);
//This will not build up dependencies
unityContainer.BuildUp(result);
if (result.Needed == null)
throw new NullReferenceException("Needed");
return result;
}
}
}
It's a bug in BuildUp, unfortunately.
Instead of calling BuildUp call this CallInjectionMethod helper.
public static class UnityContainerHelper
{
public static void CallInjectionMethod(this IUnityContainer unityContainer, object instance, params ResolverOverride[] overrides)
{
if (instance == null)
throw new ArgumentNullException("Instance");
var injectionMethodInfo = instance.GetType().GetMethods().Where(x => x.GetCustomAttributes(typeof(InjectionMethodAttribute), true).Any()).SingleOrDefault();
if (injectionMethodInfo == null)
return;
var parameters = injectionMethodInfo.GetParameters();
if (parameters.Length == 0)
return;
var dependencies = new object[parameters.Length];
int index = 0;
foreach (Type parameterType in parameters.Select(x => x.ParameterType))
{
dependencies[index] = unityContainer.Resolve(parameterType, overrides);
index++;
}
injectionMethodInfo.Invoke(instance, dependencies);
}
}

Resources