Blazor multi-user questionaire - asp.net

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.

Related

How to return a BadRequest from a Controller?

I have a form that allow to the user to update his profile. When the form is submitted an ajax request is raised:
$.ajax({
url: url,
data: formData,
type: 'POST',
success: function (response) {
alert(true);
},
error: function (jqXHR, textStatus, errorThrown) {
//Handle error
}
});
inside the ajax request I need to check if an error happened, if yes, based on the generated error I want display a different exception message.
Now the main problem is that the method called return a ViewModel of the updated user, something like:
publi class UserController : Controller
{
private readonly IUserRepository _repo;
public UserController(IUserRepository repo)
{
_repo = repo;
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateUser(UserProfileViewModel updateUser)
{
if(ModelState.IsValid)
{
updateUser = await _repo.UpdateUserAsync(updateUser);
}
return RedirectToAction("Profile");
}
The controller have a dependency injection of IUserRepository which actually handle the logic to update the user, eg:
public async Task<User> UpdateUserAsync(UserProfileViewModel updatedUser)
{
if(updatedUser.FirstName == "")
throw new Exception("FirstName not filled");
}
as you can see from the example above, if the FirstName is not filled, then an exception is thrown.
I want avoid the use of the exception; after some research I found BadRequest(), the problem is that BadRequest seems missing from AspNetCore, seems only available in the API version.
Someone have a good way to manage that?
#poke and #agua from mars are completely right; you should use model validation. If, however, your validation is a bit more complex and you have to handle it in your service, you can use this pattern. First, create a class that represents not just the data, but an indicator of the service's success in getting the data.
public class Result<T>
{
public bool HasError { get; set; }
public T Data { get; set; }
}
This above is very simplistic; you'd likely want more information.
Then, in your service, change the signature to return a Result<T> and add code to create the appropriate one:
public async Task<Result<User>> UpdateUserAsync(UserProfileViewModel updatedUser) {
if (updatedUser.FirstName == "")
return new Result<User> {
HadError = true,
Data = (User)null
};
// do something to save
return new Result<User> {
HadError = false,
Data = updatedUser
};
}
And then update your action to receive the Result<T> and return the appropriate result:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateUser(UserProfileViewModel updateUser) {
var result = new Result<User> {
HadError = true,
Data = (User) null
};
if (ModelState.IsValid) {
result = await _repo.UpdateUserAsync(updateUser);
}
return result.HadError ? BadRequest() : RedirectToAction("Profile");
}
Again, for something like a required property, there are much better methods. I've found the above pattern useful when errors occur in the service and I want to communicate that fact to the controller/action/UI.
As poke told you, use can use model validation by decorating your UserProfileViewModel.FirstName with Required attribute :
public class UserProfileViewModel
{
[Required]
public string Name { get; set; }
}
I add filters to my configuration to factorize the code.
One to check model:
/// <summary>
/// Check api model state filter
/// </summary>
public class ApiCheckModelStateFilter : IActionFilter
{
private readonly PathString _apiPathString = PathString.FromUriComponent("/api");
/// <summary>
/// Called after the action executes, before the action result.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext" />.</param>
public void OnActionExecuted(ActionExecutedContext context)
{
}
/// <summary>
/// Called before the action executes, after model binding is complete.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext" />.</param>
/// <exception cref="InvalidOperationException"></exception>
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.HttpContext.Request.Path.StartsWithSegments(_apiPathString))
{
return;
}
var state = context.ModelState;
if (!state.IsValid)
{
var message = string.Join("; ", state.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new InvalidOperationException(message);
}
}
}
And another one to manage status code depending on exception:
/// <summary>
/// Api exception filter
/// </summary>
public class ApiExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
{
private readonly PathString _apiPathString = PathString.FromUriComponent("/api");
private readonly ILogger<ApiExceptionFilter> _logger;
/// <summary>
/// Initialize a new instance of <see cref="ApiExceptionFilter"/>
/// </summary>
/// <param name="logger">A logger</param>
public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
{
_logger = logger;
}
/// <summary>
/// Called after an action has thrown an <see cref="T:System.Exception" />.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ExceptionContext" />.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task" /> that on completion indicates the filter has executed.
/// </returns>
public Task OnExceptionAsync(ExceptionContext context)
{
Process(context);
return Task.CompletedTask;
}
/// <summary>
/// Called after an action has thrown an <see cref="T:System.Exception" />.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ExceptionContext" />.</param>
public void OnException(ExceptionContext context)
{
Process(context);
}
private void Process(ExceptionContext context)
{
var e = context.Exception;
_logger.LogError(e, e.Message);
if (!context.HttpContext.Request.Path.StartsWithSegments(_apiPathString))
{
return;
}
else if (e is EntityNotFoundException)
{
context.Result = WriteError(HttpStatusCode.NotFound, e);
}
else if (e is InvalidOperationException)
{
context.Result = WriteError(HttpStatusCode.BadRequest, e);
}
else if (e.GetType().Namespace == "Microsoft.EntityFrameworkCore")
{
context.Result = WriteError(HttpStatusCode.BadRequest, e);
}
else
{
context.Result = WriteError(HttpStatusCode.InternalServerError, e);
}
}
private IActionResult WriteError(HttpStatusCode statusCode, Exception e)
{
var result = new ApiErrorResult(e.Message, e)
{
StatusCode = (int)statusCode,
};
return result;
}
}
It returns an ApiErrorResult with the error message in the reason phrase:
/// <summary>
/// Api error result
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.Mvc.ObjectResult" />
public class ApiErrorResult : ObjectResult
{
private readonly string _reasonPhrase;
/// <summary>
/// Initializes a new instance of the <see cref="ApiErrorResult"/> class.
/// </summary>
/// <param name="reasonPhrase">The reason phrase.</param>
/// <param name="value">The value.</param>
public ApiErrorResult(string reasonPhrase, object value) : base(value)
{
_reasonPhrase = reasonPhrase;
}
/// <inheritdoc />
public override async Task ExecuteResultAsync(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var reasonPhrase = _reasonPhrase;
reasonPhrase = reasonPhrase.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[0];
context.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = reasonPhrase;
await base.ExecuteResultAsync(context);
}
}
Thoses filters are set upped in the Startup ConfigureServices method:
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">A service collection</param>
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(configure =>
{
var filters = configure.Filters;
filters.Add<ApiExceptionFilter>();
filters.Add<ApiCheckModelStateFilter>();
})
.AddJsonOptions(configure =>
{
configure.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
This way I don't need to check if the model is valid in controllers methods:
[HttpPost]
[ValidateAntiForgeryToken]
public Task<IActionResult> UpdateUser(UserProfileViewModel updateUser) => _repo.UpdateUserAsync(updateUser);

can i find out the orignial value of a control with ViewState

In my ASP.NET web form, say I have something like this:
<asp:Literal ID="Literal1" runat="server" Text="abc"></asp:Literal>
Now say I change the text in the code behind. The control has viewstate enabled and so the new text value persists throughout postbacks which is exactly what I want. But in some scenarios I want to reset the control back to the original value (i.e. "abc") without having to hardcode it in the code behind. So without disabling viewstate, is there any way I can retrieve the original value that the control had when the screen was first loaded?
Thanks
You could try to get the text from the control in the Page_Init method. The viewstate is restored to the control tree later in the page processing pipeline. So if you access the text in Page_Init and store the value in some suitable place you can get the value from markup (aspx) file.
I dont know how to do it with viewstate. but you could create a base page for your site with options to track changes and store the default values when the page is loaded. And a class to do the actual checking.
for example:
Change Tracker:
/// <summary>
/// Class to Track changes in a web page
/// </summary>
[Serializable]
public class ChangeTracker : IDisposable
{
//- MEMBER VARIABLES --------------------------------------------------------------------------------------------------------
#region Members
private bool m_ChangesMade = false;
private Dictionary<string, object> m_OriginalValues = new Dictionary<string, object>();
private Dictionary<string, object> m_ChangedValues = new Dictionary<string, object>();
private List<string> m_ControlsToIgnore = new List<string>();
#endregion Members
//- PROPERTIES --------------------------------------------------------------------------------------------------------------
#region Properties
/// <summary>
/// Gets or Sets the Controls to Ignore (ClientID array)
/// </summary>
public List<string> ControlsToIgnore
{
get { return m_ControlsToIgnore; }
set { m_ControlsToIgnore = value; }
}
/// <summary>
/// Gets or Sets the Dictionay of Changed Values
/// </summary>
public Dictionary<string, object> ChangedValues
{
get { return m_ChangedValues; }
set { m_ChangedValues = value; }
}
/// <summary>
/// Gets or Sets the Dictionay of Original Values
/// </summary>
public Dictionary<string, object> OriginalValues
{
get { return m_OriginalValues; }
set { m_OriginalValues = value; }
}
/// <summary>
/// Gets or Sets Whether changes have been made to the control collection
/// </summary>
public bool ChangesMade
{
get
{
try
{
return m_ChangesMade;
}
catch (Exception)
{
throw;
}
}
set { m_ChangesMade = value; }
}
#endregion Properties
#region Constructor
/// <summary>
/// Constructor (required for serialization)
/// </summary>
public ChangeTracker()
{
}
#endregion Constructor
#region Methods
/// <summary>
/// Adds all relivant controls recursively to the list
/// </summary>
/// <param name="oControl">The control to add</param>
private void AddControls(Control oControl)
{
try
{
if (oControl != null)
{
//Check whether the control shoudl be ignored
if (!this.ControlsToIgnore.Contains(oControl.ClientID))
{
//loop recursively
foreach (Control aControl in oControl.Controls)
{
this.AddControls(aControl);
}
if (oControl is IEditableTextControl)
{
if (this.OriginalValues.ContainsKey(oControl.ClientID))
{
this.OriginalValues[oControl.ClientID] = (oControl as IEditableTextControl).Text;
}
else
{
this.OriginalValues.Add(oControl.ClientID, (oControl as IEditableTextControl).Text);
}
}
if (oControl is ICheckBoxControl)
{
if (this.OriginalValues.ContainsKey(oControl.ClientID))
{
this.OriginalValues[oControl.ClientID] = (oControl as ICheckBoxControl).Checked;
}
else
{
this.OriginalValues.Add(oControl.ClientID, (oControl as ICheckBoxControl).Checked);
}
}
}
}
else
{
throw new ArgumentNullException("oControl");
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Checks the controls for changes
/// </summary>
/// <param name="oControl">The control to check</param>
private void CheckControl(Control oControl)
{
try
{
//Check the control should not be ignored
if (!this.ControlsToIgnore.Contains(oControl.ClientID))
{
//loop recursively
foreach (Control aControl in oControl.Controls)
{
this.CheckControl(aControl);
}
if (oControl is IEditableTextControl)
{
if (this.OriginalValues.ContainsKey(oControl.ClientID))
{
if (this.OriginalValues[oControl.ClientID].ToString() != (oControl as IEditableTextControl).Text)
{
if (!this.ChangedValues.ContainsKey(oControl.ClientID))
{
this.ChangedValues.Add(oControl.ClientID, (oControl as IEditableTextControl).Text);
}
else
{
this.ChangedValues[oControl.ClientID] = (oControl as IEditableTextControl).Text;
}
this.ChangesMade = true;
}
}
}
if (oControl is ICheckBoxControl)
{
if (this.OriginalValues.ContainsKey(oControl.ClientID))
{
if ((bool)this.OriginalValues[oControl.ClientID] != (oControl as ICheckBoxControl).Checked)
{
if (!this.ChangedValues.ContainsKey(oControl.ClientID))
{
this.ChangedValues.Add(oControl.ClientID, (oControl as ICheckBoxControl).Checked);
}
else
{
this.ChangedValues[oControl.ClientID] = (oControl as ICheckBoxControl).Checked;
}
this.ChangesMade = true;
}
}
}
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Stores the default values
/// </summary>
///<param name="oControl">The control to store</param>
public void StoreDefaultValues(Control oControl)
{
try
{
//Reset the Original Values collection
this.OriginalValues = new Dictionary<string, object>();
this.ChangesMade = false;
//Add all relevant controls
this.AddControls(oControl);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Checks the form for changes
/// </summary>
///<param name="oControl">The control to check for changes</param>
public void CheckForChanges(Control oControl)
{
try
{
//Instantiate changed values
this.ChangedValues = new Dictionary<string, object>();
//Reset changes made flag
this.ChangesMade = false;
//Check controls for changes
this.CheckControl(oControl);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Dispose of the object
/// </summary>
public void Dispose()
{
try
{
m_ChangedValues = null;
m_ControlsToIgnore = null;
m_OriginalValues = null;
}
catch (Exception)
{
throw;
}
}
#endregion Methods
}
Base Web Page:
/// <summary>
/// Adds Extra functionality to a web page
/// </summary>
public class WebPage : System.Web.UI.Page
{
#region Properties
/// <summary>
/// Gets or Sets the Change Tracker
/// </summary>
protected ChangeTracker ChangeTracker
{
get
{
if (Session[String.Format("ChangeTracker{0}", this.ClientID)] == null)
{
Session[String.Format("ChangeTracker{0}", this.ClientID)] = new ChangeTracker();
}
return Session[String.Format("ChangeTracker{0}", this.ClientID)] as ChangeTracker;
}
set
{
Session[String.Format("ChangeTracker{0}", this.ClientID)] = value;
}
}
/// <summary>
/// Gets or Sets whether changes have been made
/// </summary>
protected bool ChangesTracked
{
get
{
if (ViewState["ChangesTracked"] == null)
{
ViewState["ChangesTracked"] = false;
}
return (bool)ViewState["ChangesTracked"];
}
set
{
ViewState["ChangesTracked"] = value;
}
}
#endregion Properties
#region Events
/// <summary>
/// Stores the value of the controls after the load completes
/// </summary>
/// <param name="e">order</param>
protected override void OnLoadComplete(EventArgs e)
{
try
{
base.OnLoadComplete(e);
//Dont store on postback
if (!Page.IsPostBack)
{
//Check whether to track changes
if (this.ChangesTracked)
{
//Store the default values
this.ChangeTracker.StoreDefaultValues(this);
}
}
}
catch (Exception)
{
throw;
}
}
#endregion Events
}
Useage (on a save event for example):
//Check for changes
base.ChangeTracker.CheckForChanges(this);
//If changes have been made, flag as dirty
if (base.ChangeTracker.ChangesMade)
{
//Do stuff
}
As you can see the initial values are stored when the page loaded is complete so they are all available for comparison, or in your case, to reset to original values.

Creating Customized biztalk pipeline component to convert HTML to XML?

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

How to pass multiple Property Collections to method C#

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);

Saving Entity Framework objects in ViewState

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.

Resources