I am trying to pass a collection of objects to a method in c#.
Here are the methods.
First one expects a single property to be passed.
/// <summary>
/// Adds an EXIF property to an image.
/// </summary>
/// <param name="inputPath">file path of original image</param>
/// <param name="outputPath">file path of modified image</param>
/// <param name="property"></param>
public static void AddExifData(string inputPath, string outputPath, ExifProperty property)
{
using (Image image = Image.FromFile(inputPath))
{
ExifWriter.AddExifData(image, property);
image.Save(outputPath);
}
}
The second one expects a collection of properties. This is the method I want to pass data too.
/// <summary>
/// Adds a collection of EXIF properties to an image.
/// </summary>
/// <param name="inputPath">file path of original image</param>
/// <param name="outputPath">file path of modified image</param>
/// <param name="properties"></param>
public static void AddExifData(string inputPath, string outputPath, ExifPropertyCollection properties)
{
using (Image image = Image.FromFile(inputPath))
{
ExifWriter.AddExifData(image, properties);
image.Save(outputPath);
}
}
To pass data as a single property I use this code.
// Add folder date to exif tag
ExifProperty folderDate = new ExifProperty();
folderDate.Tag = ExifTag.DateTime;
folderDate.Value = lastPart.ToString();
ExifWriter.AddExifData(imagePath, outputPath, copyright);
Here I only pass one property to the method. How could I send multiple items to the method like this.
// add copyright tag
ExifProperty copyright = new ExifProperty();
copyright.Tag = ExifTag.Copyright;
copyright.Value = String.Format(
"Copyright (c){0} Lorem ipsum dolor sit amet. All rights reserved.",
DateTime.Now.Year);
// Add folder date to exif tag
ExifProperty folderDate = new ExifProperty();
folderDate.Tag = ExifTag.DateTime;
folderDate.Value = lastPart.ToString();
Then pass both these properties?
ExifWriter.AddExifData(imagePath, outputPath, ??????????);
Thanks
You're trying to create a params ExifProperty[] parameter.
public static void AddExifData(string inputPath, string outputPath, params ExifProperty[] properties)
{ ... }
ExifWriter.AddExifData(imagePath, outputPath, copyright, folderDate);
Here is the full class without the new code added.
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
namespace ExifUtils.Exif.IO
{
/// <summary>
/// Utility class for writing EXIF data
/// </summary>
public static class ExifWriter
{
#region Fields
private static ConstructorInfo ctorPropertyItem = null;
#endregion Fields
#region Write Methods
/// <summary>
/// Adds a collection of EXIF properties to an image.
/// </summary>
/// <param name="inputPath">file path of original image</param>
/// <param name="outputPath">file path of modified image</param>
/// <param name="properties"></param>
public static void AddExifData(string inputPath, string outputPath, ExifPropertyCollection properties)
{
using (Image image = Image.FromFile(inputPath))
{
ExifWriter.AddExifData(image, properties);
image.Save(outputPath);
}
}
/// <summary>
/// Adds an EXIF property to an image.
/// </summary>
/// <param name="inputPath">file path of original image</param>
/// <param name="outputPath">file path of modified image</param>
/// <param name="property"></param>
public static void AddExifData(string inputPath, string outputPath, ExifProperty property)
{
using (Image image = Image.FromFile(inputPath))
{
ExifWriter.AddExifData(image, property);
image.Save(outputPath);
}
}
/// <summary>
/// Adds a collection of EXIF properties to an image.
/// </summary>
/// <param name="image"></param>
/// <param name="properties"></param>
public static void AddExifData(Image image, ExifPropertyCollection properties)
{
if (image == null)
{
throw new NullReferenceException("image was null");
}
if (properties == null || properties.Count < 1)
{
return;
}
foreach (ExifProperty property in properties)
{
ExifWriter.AddExifData(image, property);
}
}
/// <summary>
/// Adds an EXIF property to an image.
/// </summary>
/// <param name="image"></param>
/// <param name="property"></param>
public static void AddExifData(Image image, ExifProperty property)
{
if (image == null)
{
throw new NullReferenceException("image was null");
}
if (property == null)
{
return;
}
PropertyItem propertyItem;
// The .NET interface for GDI+ does not allow instantiation of the
// PropertyItem class. Therefore one must be stolen off the Image
// and repurposed. GDI+ uses PropertyItem by value so there is no
// side effect when changing the values and reassigning to the image.
if (image.PropertyItems == null || image.PropertyItems.Length < 1)
{
propertyItem = ExifWriter.CreatePropertyItem();
}
else
{
propertyItem = image.PropertyItems[0];
}
propertyItem.Id = (int)property.Tag;
propertyItem.Type = (short)property.Type;
Type dataType = ExifDataTypeAttribute.GetDataType(property.Tag);
switch (property.Type)
{
case ExifType.Ascii:
{
propertyItem.Value = Encoding.ASCII.GetBytes(Convert.ToString(property.Value) + '\0');
break;
}
case ExifType.Byte:
{
if (dataType == typeof(UnicodeEncoding))
{
propertyItem.Value = Encoding.Unicode.GetBytes(Convert.ToString(property.Value) + '\0');
}
else
{
goto default;
}
break;
}
default:
{
throw new NotImplementedException(String.Format("Encoding for EXIF property \"{0}\" has not yet been implemented.", property.DisplayName));
}
}
propertyItem.Len = propertyItem.Value.Length;
// This appears to not be necessary
//foreach (int id in image.PropertyIdList)
//{
// if (id == exif.PropertyItem.Id)
// {
// image.RemovePropertyItem(id);
// break;
// }
//}
image.SetPropertyItem(propertyItem);
}
#endregion Write Methods
#region Copy Methods
/// <summary>
/// Copies EXIF data from one image to another
/// </summary>
/// <param name="source"></param>
/// <param name="dest"></param>
public static void CloneExifData(Image source, Image dest)
{
ExifWriter.CloneExifData(source, dest, -1);
}
/// <summary>
/// Copies EXIF data from one image to another
/// </summary>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <param name="maxPropertyBytes">setting to filter properties</param>
public static void CloneExifData(Image source, Image dest, int maxPropertyBytes)
{
bool filter = (maxPropertyBytes > 0);
// preserve EXIF
foreach (PropertyItem prop in source.PropertyItems)
{
if (filter && prop.Len > maxPropertyBytes)
{
// skip large sections
continue;
}
dest.SetPropertyItem(prop);
}
}
#endregion Copy Methods
#region Utility Methods
/// <summary>
/// Uses Reflection to instantiate a PropertyItem
/// </summary>
/// <returns></returns>
internal static PropertyItem CreatePropertyItem()
{
if (ExifWriter.ctorPropertyItem == null)
{
// Must use Reflection to get access to PropertyItem constructor
ExifWriter.ctorPropertyItem = typeof(PropertyItem).GetConstructor(Type.EmptyTypes);
if (ExifWriter.ctorPropertyItem == null)
{
throw new NotSupportedException("Unable to instantiate a System.Drawing.Imaging.PropertyItem");
}
}
return (PropertyItem)ExifWriter.ctorPropertyItem.Invoke(null);
}
#endregion Utility Methods
}
}
You could use the params keyword:
public static void AddExifData(
string inputPath,
string outputPath,
params ExifProperty[] properties)
{
using (Image image = Image.FromFile(inputPath))
{
ExifWriter.AddExifData(image, new ExifPropertyCollection(properties));
image.Save(outputPath);
}
}
And then call:
ExifWriter.AddExifData(imagePath, outputPath, copyright, folderDate);
Related
3 month project about to be scrapped because of this.
Makes zero sense why this does not work.
I've tried rebooting etc. I have a sample project with the same versions of Forms etc which works.
I've tried taking the AppMapViewModelBase from that project into mine and the error still there.
Any ideas?
using System;
using System.ComponentModel;
using Prism;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace bla.Infrastructure {
public abstract class AppMapViewModelBase : BindableBase, IInitialize, INavigationAware, IConfirmNavigation, IDestructible
{
private bool _isBusy;
public bool IsBusy
{
get => _isBusy;
set => SetProperty(ref _isBusy, value);
}
private int _cartItemCount;
public int CartItemCount
{
// get => _password;
get { return App.Current.CartItemCount; }
//set => SetProperty(ref _cartItemCount, value);
set
{
_cartItemCount = value;
App.Current.CartItemCount = value;
RaisePropertyChanged();
}
}
const string RootUriPrependText = "/";
DelegateCommand<string> _navigateAbsoluteCommand;
DelegateCommand<string> _navigateCommand;
DelegateCommand<string> _navigateModalCommand;
DelegateCommand<string> _navigateNonModalCommand;
private bool _isNotConnected;
public bool IsNotConnected
{
get
{
if (DesignMode.IsDesignModeEnabled)
{
return false;
}
else
{
return _isNotConnected;
}
}
set
{
SetProperty(ref _isNotConnected, value);
}
}
/// <summary>
/// Gets the navigate absolute command.
/// </summary>
/// <value>The navigate absolute command.</value>
public DelegateCommand<string> NavigateAbsoluteCommand => _navigateAbsoluteCommand ?? (_navigateAbsoluteCommand = new DelegateCommand<string>(NavigateAbsoluteCommandExecute, CanNavigateAbsoluteCommandExecute));
/// <summary>
/// Gets the navigate command.
/// </summary>
/// <value>The navigate command.</value>
public DelegateCommand<string> NavigateCommand => _navigateCommand ?? (_navigateCommand = new DelegateCommand<string>(NavigateCommandExecute, CanNavigateCommandExecute));
/// <summary>
/// Gets the navigate modal command.
/// </summary>
/// <value>The navigate modal command.</value>
public DelegateCommand<string> NavigateModalCommand => _navigateModalCommand ?? (_navigateModalCommand = new DelegateCommand<string>(NavigateModalCommandExecute, CanNavigateModalCommandExecute));
/// <summary>
/// Gets the navigate non modal command.
/// </summary>
/// <value>The navigate non modal command.</value>
public DelegateCommand<string> NavigateNonModalCommand => _navigateNonModalCommand ?? (_navigateNonModalCommand = new DelegateCommand<string>(NavigateNonModalCommandExecute, CanNavigateNonModalCommandExecute));
/// <summary>
/// Gets the navigation service.
/// </summary>
/// <value>The navigation service.</value>
protected INavigationService NavigationService { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AppMapViewModelBase"/> class.
/// </summary>
/// <param name="navigationService">The navigation service.</param>
/// <exception cref="System.ArgumentNullException">navigationService</exception>
protected AppMapViewModelBase(INavigationService navigationService)
{
if (navigationService == null)
{
throw new ArgumentNullException(nameof(navigationService));
}
this.NavigationService = navigationService;
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
IsNotConnected = Connectivity.NetworkAccess != NetworkAccess.Internet;
}
void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
if (e.NetworkAccess != NetworkAccess.Internet)
{
//NavigationService.NavigateAsync("NavigationPage/NoInternet");
}
IsNotConnected = e.NetworkAccess != NetworkAccess.Internet;
}
/// <summary>
/// Determines whether this instance accepts being navigated away from. This method is invoked by Prism before a navigation operation and is a member of IConfirmNavigation.
/// </summary>
/// <param name="parameters">The navigation parameters.</param>
/// <returns><c>True</c> if navigation can continue, <c>False</c> if navigation is not allowed to continue</returns>
public virtual bool CanNavigate(INavigationParameters parameters)
{
return true;
}
/// <summary>
/// Determines whether this instance can execute the NavigateAbsoluteCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateAbsoluteCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateAbsoluteCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// Determines whether this instance can execute the NavigateAbsoluteCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateAbsoluteCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// Determines whether this instance can execute the NavigateModalCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateModalCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateModalCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// Determines whether this instance can execute the NavigateNonModalCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateNonModalCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateNonModalCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// <p>Invoked by Prism Navigation when the instance is removed from the navigation stack.</p>
/// <p>Deriving class can override and perform any required clean up.</p>
/// </summary>
public virtual void Destroy()
{
}
/// <summary>
/// Navigates to the uri after creating a new navigation root. (Effectively replacing the Application MainPage.)
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateAbsoluteCommandExecute(string uri)
{
if (!CanNavigateAbsoluteCommandExecute(uri))
{
return;
}
if (!uri.StartsWith(RootUriPrependText))
{
uri = string.Concat(RootUriPrependText, uri);
}
await this.NavigationService.NavigateAsync(uri, null, false,false);
}
/// <summary>
/// Navigates to the uri.
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateCommandExecute(string uri)
{
if (!CanNavigateCommandExecute(uri))
{
return;
}
await this.NavigationService.NavigateAsync(uri);
}
/// <summary>
/// Navigates to the uri using a Modal navigation.
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateModalCommandExecute(string uri)
{
if (!CanNavigateModalCommandExecute(uri))
{
return;
}
await this.NavigationService.NavigateAsync(uri,null, useModalNavigation: true,animated:false);
}
/// <summary>
/// Navigates to the uri using Non-Modal navigation.
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateNonModalCommandExecute(string uri)
{
if (!CanNavigateNonModalCommandExecute(uri))
{
return;
}
await this.NavigationService.NavigateAsync(uri,null, useModalNavigation: false,false);
}
/// <summary>
/// Invoked by Prism immediately after the ViewModel has been created.
/// </summary>
/// <param name="parameters">The parameters.</param>
public virtual void InitializeAsync(INavigationParameters parameters)
{
}
/// <summary>
/// Invoked by Prism after navigating away from viewmodel's page.
/// </summary>
/// <param name="parameters">The parameters.</param>
public virtual void OnNavigatedFrom(INavigationParameters parameters)
{
}
/// <summary>
/// Invoked by Prism after navigating to the viewmodel's page.
/// </summary>
/// <param name="parameters">The parameters.</param>
public virtual void OnNavigatedTo(INavigationParameters parameters)
{
}
public virtual void Initialize(INavigationParameters parameters)
{
}
}
}
The signature of the method is wrong.
The prefix I is missing before NavigationParameters, because OnNavigatedFrom expects an interface of type INavigationParameters as parameter:
Change NavigationParameters to INavigationParameters
public override void OnNavigatedFrom (INavigationParameters navigationParameters)
{
}
I need to create an app thats basically functions like a multi-user realtime questionnaire or trivia.
I've gotten to the point where i've created a questionnaire and associated users to it, but i'm hitting a road block on how to go forward.
Basically what i need to do next is
For each question in the questionnaire:
1) have the server send the users a question
2) wait for all of the users to respond or a set timeout period
3) display to the users a question result page
I was wondering how i should attempt to do something like this. Any help or resources would be wonderful
I am building a chat application that has something very similar using Server Side Blazor.
The way I did was I inject a class I created called SubscriberService:
#inject Services.SubscriberService SubscriberService
Then in my ConfigureServices method in Startup.cs I add this:
services.AddSingleton<SubscriberService>();
The Add Singleton means only 1 instance will be created for all your browser instances (users).
This makes my Subscriber Services available to all my subcribers, which is just a name, Guid Id and a callback delegate
#region using statements
using DataJuggler.UltimateHelper.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
#endregion
namespace BlazorChat.Services
{
#region class SubscriberService
/// <summary>
/// This class is used to subscribe to services, so other windows get a notification a new message
/// came in.
/// </summary>
public class SubscriberService
{
#region Private Variables
private int count;
private Guid serverId;
private List<SubscriberCallback> subscribers;
#endregion
#region Constructor
/// <summary>
/// Create a new instance of a 'SubscriberService' object.
/// </summary>
public SubscriberService()
{
// Create a new Guid
this.ServerId = Guid.NewGuid();
Subscribers = new List<SubscriberCallback>();
}
#endregion
#region Methods
#region BroadcastMessage(SubscriberMessage message)
/// <summary>
/// This method Broadcasts a Message to everyone that ins't blocked.
/// Note To Self: Add Blocked Feature
/// </summary>
public void BroadcastMessage(SubscriberMessage message)
{
// if the value for HasSubscribers is true
if ((HasSubscribers) && (NullHelper.Exists(message)))
{
// Iterate the collection of SubscriberCallback objects
foreach (SubscriberCallback subscriber in Subscribers)
{
// if the Callback exists
if ((subscriber.HasCallback) && (subscriber.Id != message.FromId))
{
// to do: Add if not blocked
// send the message
subscriber.Callback(message);
}
}
}
}
#endregion
#region GetSubscriberNames()
/// <summary>
/// This method returns a list of Subscriber Names ()
/// </summary>
public List<string> GetSubscriberNames()
{
// initial value
List<string> subscriberNames = null;
// if the value for HasSubscribers is true
if (HasSubscribers)
{
// create the return value
subscriberNames = new List<string>();
// Get the SubscriberNamesl in alphabetical order
List<SubscriberCallback> sortedNames = Subscribers.OrderBy(x => x.Name).ToList();
// Iterate the collection of SubscriberService objects
foreach (SubscriberCallback subscriber in sortedNames)
{
// Add this name
subscriberNames.Add(subscriber.Name);
}
}
// return value
return subscriberNames;
}
#endregion
#region Subscribe(string subscriberName)
/// <summary>
/// method returns a message with their id
/// </summary>
public SubscriberMessage Subscribe(SubscriberCallback subscriber)
{
// initial value
SubscriberMessage message = null;
// If the subscriber object exists
if ((NullHelper.Exists(subscriber)) && (HasSubscribers))
{
// Add this item
Subscribers.Add(subscriber);
// return a test message for now
message = new SubscriberMessage();
// set the message return properties
message.FromName = "Subscriber Service";
message.FromId = ServerId;
message.ToName = subscriber.Name;
message.ToId = subscriber.Id;
message.Data = Subscribers.Count.ToString();
message.Text = "Subscribed";
}
// return value
return message;
}
#endregion
#region Unsubscribe(Guid id)
/// <summary>
/// This method Unsubscribe
/// </summary>
public void Unsubscribe(Guid id)
{
// if the value for HasSubscribers is true
if ((HasSubscribers) && (Subscribers.Count > 0))
{
// attempt to find this callback
SubscriberCallback callback = Subscribers.FirstOrDefault(x => x.Id == id);
// If the callback object exists
if (NullHelper.Exists(callback))
{
// Remove this item
Subscribers.Remove(callback);
// create a new message
SubscriberMessage message = new SubscriberMessage();
// set the message return properties
message.FromId = ServerId;
message.FromName = "Subscriber Service";
message.Text = callback.Name + " has left the conversation.";
message.ToId = Guid.Empty;
message.ToName = "Room";
// Broadcast the message to everyone
BroadcastMessage(message);
}
}
}
#endregion
#endregion
#region Properties
#region Count
/// <summary>
/// This property gets or sets the value for 'Count'.
/// </summary>
public int Count
{
get { return count; }
set { count = value; }
}
#endregion
#region HasSubscribers
/// <summary>
/// This property returns true if this object has a 'Subscribers'.
/// </summary>
public bool HasSubscribers
{
get
{
// initial value
bool hasSubscribers = (this.Subscribers != null);
// return value
return hasSubscribers;
}
}
#endregion
#region ServerId
/// <summary>
/// This property gets or sets the value for 'ServerId'.
/// </summary>
public Guid ServerId
{
get { return serverId; }
set { serverId = value; }
}
#endregion
#region Subscribers
/// <summary>
/// This property gets or sets the value for 'Subscribers'.
/// </summary>
public List<SubscriberCallback> Subscribers
{
get { return subscribers; }
set { subscribers = value; }
}
#endregion
#endregion
}
#endregion
}
Here is my SubscriberCallback.cs:
#region using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
#endregion
namespace BlazorChat
{
#region class SubscriberCallback
/// <summary>
/// This class is used to register a subscriber with the ChatService
/// </summary>
public class SubscriberCallback
{
#region Private Variables
private string name;
private Guid id;
private Callback callback;
private List<Guid> blockedList;
#endregion
#region Constructor
/// <summary>
/// Create a new instance of a SubscriberCallback instance
/// </summary>
public SubscriberCallback(string name)
{
// store the Name
Name = name;
// Create the Id
Id = Guid.NewGuid();
// create a BlockedList
BlockedList = new List<Guid>();
}
#endregion
#region Methods
#region ToString()
/// <summary>
/// This method is used to return the Name of the Subscriber when ToString is called.
/// </summary>
/// <returns></returns>
public override string ToString()
{
// return the Name when ToString is called
return this.Name;
}
#endregion
#endregion
#region Properties
#region BlockedList
/// <summary>
/// This property gets or sets the value for 'BlockedList'.
/// </summary>
public List<Guid> BlockedList
{
get { return blockedList; }
set { blockedList = value; }
}
#endregion
#region Callback
/// <summary>
/// This property gets or sets the value for 'Callback'.
/// </summary>
public Callback Callback
{
get { return callback; }
set { callback = value; }
}
#endregion
#region HasBlockedList
/// <summary>
/// This property returns true if this object has a 'BlockedList'.
/// </summary>
public bool HasBlockedList
{
get
{
// initial value
bool hasBlockedList = (this.BlockedList != null);
// return value
return hasBlockedList;
}
}
#endregion
#region HasCallback
/// <summary>
/// This property returns true if this object has a 'Callback'.
/// </summary>
public bool HasCallback
{
get
{
// initial value
bool hasCallback = (this.Callback != null);
// return value
return hasCallback;
}
}
#endregion
#region HasName
/// <summary>
/// This property returns true if the 'Name' exists.
/// </summary>
public bool HasName
{
get
{
// initial value
bool hasName = (!String.IsNullOrEmpty(this.Name));
// return value
return hasName;
}
}
#endregion
#region Id
/// <summary>
/// This property gets or sets the value for 'Id'.
/// </summary>
public Guid Id
{
get { return id; }
set { id = value; }
}
#endregion
#region Name
/// <summary>
/// This property gets or sets the value for 'Name'.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
#endregion
#endregion
}
#endregion
}
And here is my delegate class:
/// <summary>
/// This delegate is used by the SubscriberService to send messages to any subscribers
/// </summary>
/// <returns></returns>
public delegate void Callback(SubscriberMessage message);
Then in my component I call methods like this:
// Send this message to all clients
SubscriberService.BroadcastMessage(message);
And each client has a listen method:
SubscriberCallback callback = new SubscriberCallback(SubscriberName);
callback.Callback = Listen;
callback.Name = SubscriberName;
// Get a message back
SubscriberMessage message = SubscriberService.Subscribe(callback);
Here is my Listen method, it just waits for messages;
using DataJuggler.UltimateHelper.Core; // Nuget package
public void Listen(SubscriberMessage message)
{
// if the message exists (part of DataJuggler.UltimateHelper.Core Nuget Package)
// Same as (message != null)
if (NullHelper.Exists(message))
{
// if the message contains Joined the conversation
if ((message.Text.Contains("joined the conversation")) ||
(message.Text.Contains("left the conversation")))
{
// this updates my list of 'Whose On' whenever a user joins or leaves
// Get the Names again
this.Names = SubscriberService.GetSubscriberNames();
// Update the UI
Refresh();
}
else
{
// my display message code is here
}
}
And finally here is my Subscriber message:
#region using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#endregion
namespace BlazorChat
{
#region class SubscriberMessage
/// <summary>
/// This class is used to send information between components / pages.
/// </summary>
public class SubscriberMessage
{
#region Private Variables
private string text;
private Guid fromId;
private Guid toId;
private string fromName;
private string toName;
private object data;
private string valid;
private DateTime sent;
private string invalidReason;
#endregion
#region Properties
#region Data
/// <summary>
/// This property gets or sets the value for 'Data'.
/// </summary>
public object Data
{
get { return data; }
set { data = value; }
}
#endregion
#region FromId
/// <summary>
/// This property gets or sets the value for 'FromId'.
/// </summary>
public Guid FromId
{
get { return fromId; }
set { fromId = value; }
}
#endregion
#region FromName
/// <summary>
/// This property gets or sets the value for 'FromName'.
/// </summary>
public string FromName
{
get { return fromName; }
set { fromName = value; }
}
#endregion
#region HasText
/// <summary>
/// This property returns true if the 'Text' exists.
/// </summary>
public bool HasText
{
get
{
// initial value
bool hasText = (!String.IsNullOrEmpty(this.Text));
// return value
return hasText;
}
}
#endregion
#region InvalidReason
/// <summary>
/// This property gets or sets the value for 'InvalidReason'.
/// </summary>
public string InvalidReason
{
get { return invalidReason; }
set { invalidReason = value; }
}
#endregion
#region Sent
/// <summary>
/// This property gets or sets the value for 'Sent'.
/// </summary>
public DateTime Sent
{
get { return sent; }
set { sent = value; }
}
#endregion
#region Text
/// <summary>
/// This property gets or sets the value for 'Text'.
/// </summary>
public string Text
{
get { return text; }
set { text = value; }
}
#endregion
#region ToId
/// <summary>
/// This property gets or sets the value for 'ToId'.
/// </summary>
public Guid ToId
{
get { return toId; }
set { toId = value; }
}
#endregion
#region ToName
/// <summary>
/// This property gets or sets the value for 'ToName'.
/// </summary>
public string ToName
{
get { return toName; }
set { toName = value; }
}
#endregion
#region Valid
/// <summary>
/// This property gets or sets the value for 'Valid'.
/// </summary>
public string Valid
{
get { return valid; }
set { valid = value; }
}
#endregion
#endregion
}
#endregion
}
BlazorChat is a sample project I am still working on as part of my Nuget package:
DataJuggler.Blazor.Components, which contains a Sprite component, ProgressBar and Validation component.
The full code is here in the Samples folder of this project if I left anything out.
https://github.com/DataJuggler/DataJuggler.Blazor.Components
Documentation and SQL scripts are missing, so sorry, its a work in progress.
I am using BizTalk server 2006(R2) and Visual Studio 2005,
In my application i have a html which has to be converted into XML in a customized pipeline component
I am passing a html like this,
<HTML><Customer><Data><Name>Udaya</Name><Age>18</Age><Nation>India</Nation></Data></Customer></HTML>
I must get a out as XML like this
<ns0:Customer xmlns:ns0="http://CWW.com">
<Data>
<Name>Udaya</Name>
<Age>18</Age>
<Nation>India</Nation>
</Data>
</ns0:Customer>
Can anyone give me some suggestion is there any other way to do the same without using customized pipeline?
I am trying with the below pipeline component, but it doesn't work
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.ComponentModel;
using Microsoft.BizTalk.Component.Interop;
using Microsoft.BizTalk.Message.Interop;
//using System.Windows.Forms;
using System.CodeDom;
using HtmlAgilityPack;
namespace MessageBatchPipelineCompoent
{
[ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
[ComponentCategory(CategoryTypes.CATID_DisassemblingParser)]
[System.Runtime.InteropServices.Guid("6118B8F0-8684-4ba2-87B4-8336D70BD4F7")]
public class DisassemblePipeline : IBaseComponent,
IDisassemblerComponent,
IComponentUI,
IPersistPropertyBag
{
//Used to hold disassembled messages
private System.Collections.Queue qOutputMsgs = new System.Collections.Queue();
private string systemPropertiesNamespace = #"http://schemas.microsoft.com/BizTalk/2003/system-properties";
/// <summary>
/// Batch size used to batch records
/// </summary>
private int _BatchSize;
public int BatchSize
{
get { return _BatchSize; }
set { _BatchSize = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public DisassemblePipeline()
{
}
/// <summary>
/// Description of pipeline
/// </summary>
public string Description
{
get
{
return "Component to convert HTML to XML";
}
}
/// <summary>
/// Name of pipeline
/// </summary>
public string Name
{
get
{
return "HTMLToXMLComponent";
}
}
/// <summary>
/// Pipeline version
/// </summary>
public string Version
{
get
{
return "1.0.0.0";
}
}
/// <summary>
/// Returns collecton of errors
/// </summary>
public System.Collections.IEnumerator Validate(object projectSystem)
{
return null;
}
/// <summary>
/// Returns icon of pipeline
/// </summary>
public System.IntPtr Icon
{
get
{
return new System.IntPtr();
}
}
/// <summary>
/// Class GUID
/// </summary>
public void GetClassID(out Guid classID)
{
classID = new Guid("ACC3F15A-C389-4a5d-8F8E-2A951CDC4C19");
}
/// <summary>
/// InitNew
/// </summary>
public void InitNew()
{
}
/// <summary>
/// Load property from property bag
/// </summary>
public void Load(IPropertyBag propertyBag, int errorLog)
{
object val = null;
try
{
propertyBag.Read("BatchSize", out val, 0);
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
throw new ApplicationException("Error reading PropertyBag: " + ex.Message);
}
if (val != null)
_BatchSize = (int)val;
else
_BatchSize = 1;
}
/// <summary>
/// Write property to property bag
/// </summary>
public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
{
object val = (object)BatchSize;
propertyBag.Write("BatchSize", ref val);
}
/// <summary>
/// Disassembles (breaks) message into small messages as per batch size
/// </summary>
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
{
string originalDataString;
try
{
//fetch original message
Stream originalMessageStream = pInMsg.BodyPart.GetOriginalDataStream();
byte[] bufferOriginalMessage = new byte[originalMessageStream.Length];
originalMessageStream.Read(bufferOriginalMessage, 0, Convert.ToInt32(originalMessageStream.Length));
originalDataString = System.Text.ASCIIEncoding.ASCII.GetString(bufferOriginalMessage);
}
catch (Exception ex)
{
throw new ApplicationException("Error in reading original message: " + ex.Message);
}
//XmlDocument originalMessageDoc = new XmlDocument();
//HtmlDocument originalMessageDoc = new HtmlDocument();
HtmlAgilityPack.HtmlDocument originalMessageDoc = new HtmlAgilityPack.HtmlDocument();
originalMessageDoc.Load(originalDataString);
StringBuilder messageString;
try
{
//load original message
// HtmlNode.
// originalMessageDoc.GetElementsByTagName("HTML");
//originalMessageDoc.DocumentElement.FirstChild.RemoveChild(originalMessageDoc.DocumentElement.FirstChild);
// originalMessageDoc.DocumentElement.FirstChild.Attributes.Append("ns0");
// String RootElement = originalMessageDoc.DocumentElement.Name;
messageString = new StringBuilder();
String RootNode = originalMessageDoc.DocumentNode.Name;
System.Diagnostics.EventLog.WriteEntry("Hello", "What doing");
//originalMessageDoc.DocumentNode.Attributes(RootNode,ns0);
//messageString.Insert();
messageString.Append(true);
// messageString.Append("<" + RootNode + " xmlns:ns0='" + "http://SomeContent" + "'>");
//messageString.Append("</" + "Sample" + ">");
CreateOutgoingMessage(pContext, messageString.ToString(), "http://SomeContent", "Sample", pInMsg);
}
catch (Exception ex)
{
throw new ApplicationException("Error in writing outgoing messages: " + ex.Message);
}
finally
{
messageString = null;
originalMessageDoc = null;
}
}
/// <summary>
/// Used to pass output messages`to next stage
/// </summary>
public IBaseMessage GetNext(IPipelineContext pContext)
{
if (qOutputMsgs.Count > 0)
return (IBaseMessage)qOutputMsgs.Dequeue();
else
return null;
}
/// <summary>
/// Queue outgoing messages
/// </summary>
private void CreateOutgoingMessage(IPipelineContext pContext, String messageString, string namespaceURI, string rootElement, IBaseMessage pInMsg)
{
IBaseMessage outMsg;
try
{
//create outgoing message
outMsg = pContext.GetMessageFactory().CreateMessage();
outMsg.Context = pInMsg.Context;
outMsg.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);
outMsg.Context.Promote("MessageType", systemPropertiesNamespace,"Sample");
// outMsg.Context.Promote("MessageType", systemPropertiesNamespace, "http://SomeText" + "#" + rootElement.Replace("ns0:", ""));
byte[] bufferOoutgoingMessage = System.Text.ASCIIEncoding.ASCII.GetBytes(messageString);
outMsg.BodyPart.Data = new MemoryStream(bufferOoutgoingMessage);
qOutputMsgs.Enqueue(outMsg);
}
catch (Exception ex)
{
throw new ApplicationException("Error in queueing outgoing messages: " + ex.Message);
}
}
}
}
This is the component i have created but this is not working.
Now I am having an error like illegal characters in path.
previously i was using originalMessageDoc.Load(originalDataString);
in the dissassemble function so i was getting the illegal characters in path error ,Now i have solved that particular issue buy replacing it with
originalMessageDoc.LoadHTML(originalDataString);
Now i can see in the event log that i my xml is created but still i have a minor error
when
String RootNode = originalMessageDoc.DocumentNode.Name;
Previously i have given like this now i did hard cored it
now it says rootnode is not declared
A question for Laurent and others.
I've added extension functions to the MVVM Light messenger to push and pop messages. The idea is that when a viewmodel needs to open another view/viewmodel, it would push the parameters from the message stack and then the newly opened viewmodel (or possibly the viewmodellocator) would subscribe to the message and pop the message to get the parameters. I'm looking for feedback on this idea. The code is posted below.
MVVMlightMessengerStackExtension.cs (code below has been updated since the original post to clean things up a bit and be more consistent with stack behavior)
namespace GalaSoft.MvvmLight.Messaging
{
public static class MessageHelper
{
/// <summary>
/// Store a list of all the pushed messages
/// </summary>
private static List<Tuple<int, object, object>> _q = new List<Tuple<int, object, object>>();
private static int _q_idx = Int32.MaxValue; // SL has no SortedList or SortedDictionary so keep an index the of the list to push/pops are in order
/// <summary>
/// Push a message for later retrival. Typically by a viewmodel constructor.
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <param name="M"></param>
/// <param name="message"></param>
/// <param name="token"></param>
[DebuggerStepThrough()]
public static void Push<TMessage>(this Messenger M, TMessage message, object token = null)
{
Monitor.Enter(_q);
try
{
_q.Add(Tuple.Create<int, object, object>(_q_idx--, message, token));
}
finally
{
Monitor.Exit(_q);
}
}
/// <summary>
/// Send a stored/delayed message
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <param name="M"></param>
[DebuggerStepThrough()]
public static void PopAndSend<TMessage>(this Messenger M, object token = null)
{
TMessage mesg = M.Pop<TMessage>(token);
if (token != null)
M.Send(mesg, token);
else
M.Send(mesg);
}
/// <summary>
/// Pop a stored/delayed message
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <param name="M"></param>
[DebuggerStepThrough()]
public static TMessage Pop<TMessage>(this Messenger M, object token = null)
{
Monitor.Enter(_q);
try
{
var result = _q.OrderBy(a => a.Item1).FirstOrDefault(a => a.Item2 is TMessage && a.Item3 == token);
if (result == null)
throw new InvalidOperationException("The stack is empty.");
_q.Remove(result);
return (TMessage)result.Item2;
}
finally
{
Monitor.Exit(_q);
}
}
/// <summary>
/// Peek at a stored/delayed message
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <param name="M"></param>
[DebuggerStepThrough()]
public static TMessage Peek<TMessage>(this Messenger M, object token = null)
{
Monitor.Enter(_q);
try
{
var result = _q.OrderBy(a => a.Item1).FirstOrDefault(a => a.Item2 is TMessage && a.Item3 == token);
if (result == null)
throw new InvalidOperationException("The stack is empty.");
return (TMessage)result.Item2;
}
finally
{
Monitor.Exit(_q);
}
}
/// <summary>
/// Clear the stack
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <param name="M"></param>
[DebuggerStepThrough()]
public static void Clear(this Messenger M)
{
Monitor.Enter(_q);
try
{
_q.Clear();
}
finally
{
Monitor.Exit(_q);
}
}
/// <summary>
/// Clear the stack
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <param name="M"></param>
[DebuggerStepThrough()]
public static void Clear<TMessage>(this Messenger M)
{
Monitor.Enter(_q);
try
{
var delList = _q.Where(a => a.Item2 is TMessage);
foreach (var item in delList)
_q.Remove(item);
}
finally
{
Monitor.Exit(_q);
}
}
}
}
I have a somewhat similar concept in my backlog, very interesting implementation here. I will bookmark it and come back to it when the time comes.
Cheers and thanks for sharing!
Laurent
Given two tables, Make and Model, where a make can contain many models and resulting in the following EF generated entity types...
/// <KeyProperties>
/// ID
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="CarsModel", Name="Make")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Make : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Make object.
/// </summary>
/// <param name="id">Initial value of ID.</param>
public static Make CreateMake(int id)
{
Make make = new Make();
make.ID = id;
return make;
}
/// <summary>
/// There are no comments for Property ID in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int ID
{
get
{
return this._ID;
}
set
{
this.OnIDChanging(value);
this.ReportPropertyChanging("ID");
this._ID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("ID");
this.OnIDChanged();
}
}
private int _ID;
partial void OnIDChanging(int value);
partial void OnIDChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Models in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("CarsModel", "FK_Model_Make", "Model")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityCollection<Model> Models
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<Model>("CarsModel.FK_Model_Make", "Model");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<Model>("CarsModel.FK_Model_Make", "Model", value);
}
}
}
}
/// <KeyProperties>
/// ID
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="CarsModel", Name="Model")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Model : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Model object.
/// </summary>
/// <param name="id">Initial value of ID.</param>
public static Model CreateModel(int id)
{
Model model = new Model();
model.ID = id;
return model;
}
/// <summary>
/// There are no comments for Property ID in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int ID
{
get
{
return this._ID;
}
set
{
this.OnIDChanging(value);
this.ReportPropertyChanging("ID");
this._ID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("ID");
this.OnIDChanged();
}
}
private int _ID;
partial void OnIDChanging(int value);
partial void OnIDChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Make in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("CarsModel", "FK_Model_Make", "Make")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public Make Make
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make").Value;
}
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make").Value = value;
}
}
/// <summary>
/// There are no comments for Make in the schema.
/// </summary>
[global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityReference<Make> MakeReference
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Make>("CarsModel.FK_Model_Make", "Make", value);
}
}
}
I am trying to store an instance of the Make class into ASP.NET ViewState, along with the associated models as follows...
private Make Make {
get { return this.ViewState[#"EditContext"] as Make; }
set { this.ViewState[#"EditContext"] = value; }
}
and
this.Make = (from make in context.Makes.Include(#"Models")
where make.ID == 1
select make).FirstOrDefault();
But upon PostBack, this.Make.Models is always empty (depite definitely being populated when the entity was placed into the ViewState.
According to the MS Help,
Because entity types support binary
serialization, objects can be saved in
the view state of an ASP.NET
application during a postback
operation. When required, the object
and its related objects are retrieved
from the view state and attached to an
existing object context.
I would therefore expect what I am doing to work. Can anybody explain why this is not the case?
Thanks.
It seems that the problem was my own fault.
After adding the entity to the ViewState, I was manually detaching it from the object context. This was then clearing the links between the Make and the associated Model objects.
By simply adding the object to the ViewState without calling context.Detach(), the Models remain in the list, and I can still call context.Attach() to facilitate the manipulation of the object during the postback.