EntityState.Modify instead of Delete in my database - asp.net-mvc

I am using AuditTrail for logging but I have problem. I tried this method ;
http://kamoga.net/audit-trail-and-entity-change-tracking-using-entity-framework-dbcontext/
But I don't delete record for delete operations. I have 'IsDeleted' column and set this column true.
If I use EntityState.Modified in my ActionResult, my 'Action' column value set 'U' but I want to set'D' in database.
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
dbContext = new dbContext();
Gallery gallery = dbContext.Gallery.Find(id);
gallery.IsDeleted = true;
dbContext.Entry(gallery).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
}
My Enum;
public enum AuditActions
{
I,
U,
A
}
AuditTrail.cs ;
public class AuditTrail
{
public int Id { get; set; }
public string TableName { get; set; }
public string UserName { get; set; }
public string Actions { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
public string ChangedColums { get; set; }
public string TableIdValue { get; set; }
}
AuditFactoryTrail.cs;
public AuditTrail GetAudit(DbEntityEntry entry)
{
AuditTrail audit = new AuditTrail();
audit.UserName = "Current User"; //You can pass the current user as a parameter
audit.TableName = GetTableName(entry);
audit.TableIdValue = GetKeyValue(entry);
//entry is Added
if (entry.State == EntityState.Added)
{
var newValues = new StringBuilder();
SetAddedProperties(entry, newValues);
audit.NewData = newValues.ToString();
audit.Actions = AuditActions.I.ToString();
}
//entry in deleted
else if (entry.State == EntityState.Deleted)
{
var oldValues = new StringBuilder();
SetDeletedProperties(entry, oldValues);
audit.OldData = oldValues.ToString();
audit.Actions = AuditActions.D.ToString();
}
//entry is modified
else if (entry.State == EntityState.Modified)
{
var oldValues = new StringBuilder();
var newValues = new StringBuilder();
SetModifiedProperties(entry, oldValues, newValues);
audit.OldData = oldValues.ToString();
audit.NewData = newValues.ToString();
audit.Actions = AuditActions.U.ToString();
var modifiedProperties = entry.CurrentValues.PropertyNames.Where(propertyName => entry.Property(propertyName).IsModified).ToList();
var properties = string.Join("||", modifiedProperties.ToList());
audit.ChangedColums = properties;
}
return audit;
}
private void SetAddedProperties(DbEntityEntry entry, StringBuilder newData)
{
foreach (var propertyName in entry.CurrentValues.PropertyNames)
{
var newVal = entry.CurrentValues[propertyName];
if (newVal != null)
{
newData.AppendFormat("{0}={1} || ", propertyName, newVal);
}
}
if (newData.Length > 0)
newData = newData.Remove(newData.Length - 3, 3);
}
private void SetDeletedProperties(DbEntityEntry entry, StringBuilder oldData)
{
DbPropertyValues dbValues = entry.GetDatabaseValues();
foreach (var propertyName in dbValues.PropertyNames)
{
var oldVal = dbValues[propertyName];
if (oldVal != null)
{
oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
}
}
if (oldData.Length > 0)
oldData = oldData.Remove(oldData.Length - 3, 3);
}
private void SetModifiedProperties(DbEntityEntry entry, StringBuilder oldData, StringBuilder newData)
{
DbPropertyValues dbValues = entry.GetDatabaseValues();
foreach (var propertyName in entry.OriginalValues.PropertyNames)
{
var oldVal = dbValues[propertyName];
var newVal = entry.CurrentValues[propertyName];
if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
{
newData.AppendFormat("{0}={1} || ", propertyName, newVal);
oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
}
}
if (oldData.Length > 0)
oldData = oldData.Remove(oldData.Length - 3, 3);
if (newData.Length > 0)
newData = newData.Remove(newData.Length - 3, 3);
}
private string GetKeyValue(DbEntityEntry entry)
{
var objectStateEntry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
string id = "0";
if (objectStateEntry.EntityKey.EntityKeyValues != null)
id = objectStateEntry.EntityKey.EntityKeyValues[0].Value.ToString();
return id;
}
private string GetTableName(DbEntityEntry dbEntry)
{
TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;
return tableName;
}
private EntityObject CloneEntity(EntityObject obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
EntityObject newObject = (EntityObject)dcSer.ReadObject(memoryStream);
return newObject;
}
}
DbContext.cs;
public override int SaveChanges()
{
var auditFactory = new AuditTrailFactory(this);
var entityList = ChangeTracker.Entries().Where(p =>
p.State == EntityState.Added ||
p.State == EntityState.Deleted ||
p.State == EntityState.Modified ||
!(p.Entity is AuditTrail) ||
p.Entity != null);
entityList.ToList().ForEach(entity =>
{
AuditTrail audit = auditFactory.GetAudit(entity);
AuditTrail.Add(audit);
});
return base.SaveChanges();
}

Related

How do I programmatically add records to an Umbraco v8 form?

I'm looking to add records to an Umbraco v8 form. I know I need the form guid. Is this how I'd do it? Something like this?
public void PostFormData()
{
Guid FormGuid = new Guid("8494a8f0-94da-490e-bd61-7e658c226142");
var form = _formService.Get(FormGuid);
//place for field data into fieldDic
var fieldDic = new Dictionary<Guid, RecordField>();
var firstName = form.AllFields.First(f => f.Alias == "firstName");
var firstNameRecord = new RecordField(firstName);
firstNameRecord.Values = new List<object>() { "Mad Max" };
fieldDic.Add(firstName.Id, firstNameRecord);
var record = new Record()
{
Created = DateTime.Now,
Form = form.Id,
RecordFields = fieldDic,
State = FormState.Submitted,
};
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
}
Here's how I do it. Note, I'm hard-coding the Record.UmbracoPageId to -1 while you might want to actually pass in the correct page ID.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Core.Services;
namespace myProject.Services
{
public class FormServiceComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IFormService, FormService>(Lifetime.Request);
}
}
public interface IFormService
{
void InsertFormData(Guid formGuid, object formModel, string ipAddress);
}
public class FormService : IFormService
{
private readonly ILogger _logger;
private readonly Umbraco.Forms.Core.Services.IFormService _formService;
private readonly IRecordStorage _recordStorage;
private readonly IRecordFieldStorage _recordFieldStorage;
private readonly IWorkflowService _workflowService;
public FormService(ILogger logger, Umbraco.Forms.Core.Services.IFormService formService, IRecordStorage recordStorage, IRecordFieldStorage recordFieldStorage, IWorkflowService workflowService)
{
_logger = logger;
_formService = formService;
_recordStorage = recordStorage;
_recordFieldStorage = recordFieldStorage;
_workflowService = workflowService;
}
#region IFormService
public void InsertFormData(Guid formGuid, object formModel, string ipAddress)
{
try
{
Form form = _formService.GetForm(formGuid);
Record record = new Record();
foreach (Field field in form.AllFields)
{
string caption = CleanCaption(field.Caption);
if (formModel.GetType().GetProperty(caption) == null) continue;
var propertyValue = formModel.GetType().GetProperty(caption).GetValue(formModel, null);
if (propertyValue != null)
{
List<object> values = ExtractValues(propertyValue);
RecordField recordField = new RecordField
{
Alias = field.Alias,
FieldId = field.Id,
Field = field,
Key = Guid.NewGuid(),
Record = record.Id,
Values = values
};
_recordFieldStorage.InsertRecordField(recordField);
record.RecordFields.Add(recordField.Key, recordField);
}
}
record.Form = formGuid;
record.IP = ipAddress;
record.UmbracoPageId = -1;
record.State = Umbraco.Forms.Core.Enums.FormState.Approved;
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
_recordStorage.DisposeIfDisposable();
}
catch (Exception ex)
{
_logger.Error<FormService>(ex, "Failed inserting Umbraco Forms data for {formGuid}");
}
}
#endregion IFormService
#region Private
private string CleanCaption(string caption)
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
return rgx.Replace(caption.Trim().Replace(" ", ""), "");
}
private List<object> ExtractValues(object propertyValue)
{
List<object> result = new List<object>();
if (propertyValue is string == false && propertyValue.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IEnumerable<object> _propertyValue = (IEnumerable<object>)propertyValue;
if (_propertyValue.Any())
{
if (_propertyValue.First().GetType().GetProperties().Count() > 1)
{
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
string _value = string.Empty;
foreach (var _property in _propertyValue.First().GetType().GetProperties())
{
string _key = _property.Name;
_value = _value + (_value == "" ? "" : " - ") + item[_key].ToString();
}
result.Add(_value);
}
}
else
{
string _key = _propertyValue.First().GetType().GetProperties().First().Name;
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
result.Add(item[_key].ToString());
}
}
}
}
else
{
result.Add(propertyValue);
}
return result;
}
#endregion Private
}
}

How to send message/notification to browser/client in Kendo Mvc Ajax Bound Grid (confirm update or create) ( by cookies)

how to send notification to client in kendo mvc ajax bound ,
i do not know if this is good way ..
of course you can add ModelState.AddModelError("notification","….msg.")
and …. But it tell to datasource ajax action failed.. So..
Addclass:
public class AjaxErrorMsg
{
public AjaxErrorMsg()
{
CssClass = "gray";
AutoHide = false;
AutoHideDelay = 200;
Kind = "error";
Title = "error";
}
public string Msg { get; set; }
public string Kind { get; set; }
public Boolean AutoHide { get; set; }
public Int32 AutoHideDelay { get; set; }
public string CssClass { get; set; }
public string Title { get; set; }
}
In controller
public void StoreMessageInCookie(string msg, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
StoreMessageInCookie(new Exception(msg), isError, msgDivClass, preMessage, msgTitle);
}
public void StoreMessageInCookie(Exception ee, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
List<AjaxErrorMsg> rs;
var js = new JavaScriptSerializer();
if (this.Response.Cookies[Common1.MsgCookie].HasKeys )
{
try
{
rs = js.Deserialize<List<AjaxErrorMsg>>(this.Response.Cookies[Common1.MsgCookie].Value);
}
catch
{
rs = new List<AjaxErrorMsg>();
}
}
else
{
rs = new List<AjaxErrorMsg>();
}
var msg0 = new AjaxErrorMsg();
if (isError)
{
msgDivClass = msgDivClass == "" ? "DivAlarmStyle6 fontMitra" : msgDivClass;
msg0.Kind = "error";
msg0.AutoHide = false;
msg0.Title = "Error";
}
else
{
msg0.Kind = "alert";
msg0.AutoHide = true;
msg0.Title = "Warning";
}
msg0.Title = msgTitle == "" ? msg0.Title : msgTitle;
msg0.Msg = preMessage + cm2.FilterMessageText(ee, IsAdminUser);
if (msgDivClass.Trim() != "")
msg0.Msg = Common1.WrapTextInDivWithClass(msg0.Msg, msgDivClass);
rs.Add(msg0);
this.Response.Cookies.Add(new HttpCookie(Common1.MsgCookie, js.Serialize(rs)));
}
cm2.FilterMessageText is function to remove database object name from error message string ..also include any inner exception message
Then when you what to send message use command
StoreMessageInCookie("Message 1 2 ! ");
And in your MainProject.js
Add all of code below
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function ReadAnShowCookieForDeliverMessages() {
try {
var listMsg = readCookie("CookieForDeliverMessages")
if (!!listMsg) {
eraseCookie("CookieForDeliverMessages");
ShowAndLogMessageListOfAjaxError($.parseJSON(listMsg));
}
} catch (ee) {
alert(" error in ReadAnShowCookieForDeliverMessages")
}
}
function ShowAndLogMessageListOfAjaxError(ListOfAjaxError) {
if (ListOfAjaxError == undefined)
return;
ListOfAjaxError.forEach(function (AjaxError) {
ShowAndLogMessageByAjaxErrorClass(AjaxError)
})
}
function ShowAndLogMessageByAjaxErrorClass(AjaxError) {
if ((AjaxError != undefined) && (AjaxError.Msg != "")) {
// I used freeow => https://github.com/pjdietz/Freeow
$("#freeow").freeow(AjaxError.Title, AjaxError.Msg, { classes: [AjaxError.CssClass, AjaxError.Kind], autoHide: AjaxError.AutoHide, autoHideDelay: AjaxError.AutoHideDelay });
// LogMsg(AjaxError.Msg, AjaxError.Title); function to log message on client
}
}
$(function () {
MyAjaxSetting();
ReadAnShowCookieForDeliverMessages();
}
function MyAjaxSetting() {
$(document).ajaxComplete(function (o) {
ReadAnShowCookieForDeliverMessages()
});
}

uBlogsy (webforms) PostService showing no posts on landing page

I'm using uBlogsy WebForms 3.0.2 on Umbraco 6.1.5...
And the posts on the landing page are not showing up.
The function PostService.Instance.GetPosts is returning 0 posts, even though there are posts in the correct location.
I still get 0 posts when I try to substitute this:
var posts = PostService.Instance
.GetPosts(
IPublishedContentHelper.GetNode((int)Model.Id)
).ToIPublishedContent(true);
int postCount = posts.Count();
Would anyone know why the PostService isn't working? Or, what is going on?
I had same problem couple of times with Ublogsy. So I decided to write my own codes as below:
(Its a bit long)
// get tag, label, or author from query string
var tag = Request.QueryString["tag"] ?? "";
var label = Request.QueryString["label"] ?? "";
var author = Request.QueryString["author"] ?? "";
var searchTerm = Request.QueryString["search"] ?? "";
var commenter = Request.QueryString["commenter"] ?? "";
int page = int.TryParse(Request.QueryString["page"], out page) ? page : 1;
var year = Request.QueryString["year"] ?? "";
var month = Request.QueryString["month"] ?? "";
var day = Request.QueryString["day"] ?? "";
int postCount;
IEnumerable<IPublishedContent> posts = new BlockingCollection<IPublishedContent>();
var filterResults = this.FilterAgainstPosts(this.Model.Content, tag, label, author, searchTerm, commenter, year, month);
if (filterResults != null)
{
posts = Enumerable.Take(filterResults.Skip((page - 1) * itemsPerPage), itemsPerPage);
}
#RenderForLanding(posts)
And my FilterAgainstPosts method is as follow:
#functions
{
private IEnumerable<IPublishedContent> FilterAgainstPosts(IPublishedContent landing, string tag, string label, string author, string searchTerm, string commenter, string year, string month)
{
IEnumerable<IPublishedContent> filteredPosts = landing.DescendantsOrSelf("uBlogsyPost").Where(x => x.GetProperty("umbracoNaviHide").Value.ToString() != "1");
if (!String.IsNullOrEmpty(searchTerm))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterAgainstTerm(i, searchTerm));
}
if (!String.IsNullOrEmpty(tag))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponTag(i, i.GetProperty("uBlogsyPostTags").Value.ToString(), tag));
}
if (!String.IsNullOrEmpty(label))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponLabel(i, i.GetProperty("uBlogsyPostLabels").Value.ToString(), label));
}
if (!String.IsNullOrEmpty(author))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponAuthor(i, i.GetProperty("uBlogsyPostAuthor").Value.ToString(), author));
}
//
//TODO: Coomenter search needs to added
//
if (!string.IsNullOrEmpty(year))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponYear(i, i.GetProperty("uBlogsyPostDate").Value.ToString(), year));
}
if (!string.IsNullOrEmpty(month))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponMonth(i, i.GetProperty("uBlogsyPostDate").Value.ToString(), month));
}
return filteredPosts.WhereNotNull();
}
private IPublishedContent FilterUponMonth(IPublishedContent currentNode, string postDate, string month)
{
DateTime postedDate;
if (DateTime.TryParse(postDate, out postedDate) && postedDate.Month.ToString() == month) return currentNode;
return null;
}
private IPublishedContent FilterUponYear(IPublishedContent currentNode, string postDate, string year)
{
DateTime postedDate;
if (DateTime.TryParse(postDate, out postedDate) && postedDate.Year.ToString() == year) return currentNode;
return null;
}
private IPublishedContent FilterUponAuthor(IPublishedContent currentNode, string authorId, string author)
{
if (String.IsNullOrEmpty(authorId)) return null;
//Loads relevant node
int authorNodeId = -1;
if (!Int32.TryParse(authorId, out authorNodeId)) return null;
Node authorNode = new Node(authorNodeId);
//Trims the author name and search for given name
if (authorNode.GetProperty("uBlogsyAuthorName") != null && authorNode.GetProperty("uBlogsyAuthorName").Value.ToUpper().Trim().Contains(author.ToUpper())) return currentNode;
return null;
}
private Boolean FilterUponAuthor(string authorId, string author)
{
if (String.IsNullOrEmpty(authorId)) return false;
int authorNodeId = -1;
if (!Int32.TryParse(authorId, out authorNodeId)) return false;
Node authorNode = new Node(authorNodeId);
if (authorNode.GetProperty("uBlogsyAuthorName") != null && authorNode.GetProperty("uBlogsyAuthorName").Value.ToUpper().Trim().Contains(author.ToUpper())) return true;
return false;
}
private Boolean FilterUponCategories(string categoryIds, string category)
{
if (String.IsNullOrEmpty(categoryIds)) return false;
int categoryNodeID = -1;
foreach (string catID in categoryIds.Split(','))
{
if (!Int32.TryParse(catID, out categoryNodeID)) continue;
Node categoryNode = new Node(categoryNodeID);
if (categoryNode.GetProperty("uBlogsyLabelName") != null && categoryNode.GetProperty("uBlogsyLabelName").Value.ToUpper().Trim().Contains(category.ToUpper())) return true;
}
return false;
}
private Boolean FilterUponTags(string tagIds, string tag)
{
if (String.IsNullOrEmpty(tagIds)) return false;
int tagNodeID = -1;
foreach (string tagID in tagIds.Split(','))
{
if (!Int32.TryParse(tagID, out tagNodeID)) continue;
Node tagNode = new Node(tagNodeID);
if (tagNode.GetProperty("uTagsyTagName") != null && tagNode.GetProperty("uTagsyTagName").Value.ToUpper().Trim().Contains(tag.ToUpper())) return true;
}
return false;
}
private IPublishedContent FilterUponLabel(IPublishedContent currentNode, string nodeIDs, string label)
{
if (String.IsNullOrEmpty(nodeIDs)) return null;
foreach (string nodeId in nodeIDs.Split(','))
{
int labelNodeId = -1;
if (!Int32.TryParse(nodeId, out labelNodeId))
continue;
//Loads relevant node
Node labelNode = new Node(labelNodeId);
if (labelNode.GetProperty("uBlogsyLabelName") != null && labelNode.GetProperty("uBlogsyLabelName").Value.ToUpper().Trim().Contains(label.ToUpper())) return currentNode;
}
return null;
}
private IPublishedContent FilterAgainstTerm(IPublishedContent currentNode, string searchTerm)
{
if (String.IsNullOrEmpty(searchTerm)) return currentNode;
if (currentNode.GetProperty("uBlogsyContentTitle").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyContentSummary").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyContentBody").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsySeoKeywords").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsySeoDescription").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyNavigationTitle").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
FilterUponAuthor(currentNode.GetProperty("uBlogsyPostAuthor").Value.ToString(), searchTerm.ToUpper()) ||
FilterUponCategories(currentNode.GetProperty("uBlogsyPostLabels").Value.ToString(), searchTerm.ToUpper()) ||
FilterUponTags(currentNode.GetProperty("uBlogsyPostTags").Value.ToString(), searchTerm.ToUpper())
)
return currentNode;
return null;
}
private IPublishedContent FilterUponTag(IPublishedContent currentNode, string nodeIDs, string tag)
{
if (String.IsNullOrEmpty(nodeIDs)) return null;
foreach (string nodeId in nodeIDs.Split(','))
{
int tagNodeId = -1;
if (!Int32.TryParse(nodeId, out tagNodeId))
continue;
// Loads relevant TagNode
Node tagNode = new Node(tagNodeId);
if (tagNode.GetProperty("uTagsyTagName") != null && tagNode.GetProperty("uTagsyTagName").Value.ToUpper().Contains(tag.ToUpper())) return currentNode;
}
return null;
}
}

How create a MultipartFormFormatter for ASP.NET 4.5 Web API

These links didn't help me:
Way 1
Way 2
Example:
//Model:
public class Group
{
public int Id { get; set; }
public File File { get; set; }
}
//Controller:
[HttpPost]
public void SaveGroup([FromBody]Group group) {}
//Formatter:
public class MultipartFormFormatter : MediaTypeFormatter
{
private const string StringMultipartMediaType = "multipart/form-data";
public MultipartFormFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringMultipartMediaType));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return false;
}
public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
//Implementation? What here should be?
}
}
What should the method ReadFromStreamAsync return?
How do I make it so that you can properly transmit parameter to the action?
public class MultipartFormFormatter : FormUrlEncodedMediaTypeFormatter
{
private const string StringMultipartMediaType = "multipart/form-data";
private const string StringApplicationMediaType = "application/octet-stream";
public MultipartFormFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringMultipartMediaType));
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringApplicationMediaType));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return false;
}
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var parts = await content.ReadAsMultipartAsync();
var obj = Activator.CreateInstance(type);
var propertiesFromObj = obj.GetType().GetRuntimeProperties().ToList();
foreach (var property in propertiesFromObj.Where(x => x.PropertyType == typeof(FileModel)))
{
var file = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));
if (file == null || file.Headers.ContentLength <= 0) continue;
try
{
var fileModel = new FileModel(file.Headers.ContentDisposition.FileName, Convert.ToInt32(file.Headers.ContentLength), ReadFully(file.ReadAsStreamAsync().Result));
property.SetValue(obj, fileModel);
}
catch (Exception e)
{
}
}
foreach (var property in propertiesFromObj.Where(x => x.PropertyType != typeof(FileModel)))
{
var formData = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));
if (formData == null) continue;
try
{
var strValue = formData.ReadAsStringAsync().Result;
var valueType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var value = Convert.ChangeType(strValue, valueType);
property.SetValue(obj, value);
}
catch (Exception e)
{
}
}
return obj;
}
private byte[] ReadFully(Stream input)
{
var buffer = new byte[16 * 1024];
using (var ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
public class FileModel
{
public FileModel(string filename, int contentLength, byte[] content)
{
Filename = filename;
ContentLength = contentLength;
Content = content;
}
public string Filename { get; set; }
public int ContentLength { get; set; }
public byte[] Content { get; set; }
}
Please see below link for detail implementation:
https://github.com/iLexDev/ASP.NET-WebApi-MultipartDataMediaFormatter
Nuget:
https://www.nuget.org/packages/MultipartDataMediaFormatter/
I actually need to do "multipart/form-data" file upload and model binding today, I tried above lib from nuget and turns out it works as my expectation. Validation on model also works fine. Hopefully it helps to answer your question.

ASP.NET MVC 3 inheriting Membership userId

I am looking to extend the aspnet_membership in an MVC 3 application by storing extra member details in a separate model/table. I am not looking at using the ASP.NET ProfileProvider.
I would like to use the userId of a member as the primary/foreign key in the additional model/table. How can I achieve this? Is the example code along the right lines?
Thanks for any help.
public class Profile
{
[Key]
public Guid ProfileId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public virtual MembershipUser User
{
get { return Membership.GetUser(ProfileId); }
}
public string FullName
{
get { return LastName + ", " + FirstName; }
}
}
That's what I do in my project, I have an other class wich is Member and inside I have the Email. I have a AuthenticationService that I use to sing in my user here's the code of this AuthenticationService...
In the web.config I have two differents connection string, one for the application BD and the other for the membership BD.
public class AuthenticationService : IAuthenticationService
{
private readonly IConfigHelper _configHelper;
private readonly ISession _session;
public AuthenticationService(IConfigHelper configHelper, ISession session)
{
_configHelper = configHelper;
_session = session;
}
public bool IsValidLogin(string email, string password)
{
CheckLocked(email);
return Membership.ValidateUser(email, password);
}
public void SignIn(string email, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
public User GetLoggedUser()
{
var email = GetLoggedInUserName();
if (IsMember())
return _session.Single<Member>(x => x.Email == email);
return _session.Single<DelegateMember>(x => x.Email == email);
}
public string GetLoggedInUserName()
{
return Membership.GetUser() != null ? Membership.GetUser().UserName : string.Empty;
}
public MembershipCreateStatus RegisterUser(string email, string password, string role)
{
MembershipCreateStatus status;
//On doit laisser Guid.NewGuid().ToString() sinon ça ne passe pas
Membership.CreateUser(email, password, email, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, out status);
if (status == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(email, role);
}
return status;
}
public MembershipUserCollection GetAllUsers()
{
return Membership.GetAllUsers();
}
public string GeneratePassword()
{
var alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
var alphaLow = "qwertyuiopasdfghjklzxcvbnm";
var numerics = "1234567890";
var special = "##$";
var allChars = alphaCaps + alphaLow + numerics + special;
var r = new Random();
var generatedPassword = "";
for (int i = 0; i < MinPasswordLength - 1; i++)
{
double rand = r.NextDouble();
if (i == 0)
{
//First character is an upper case alphabet
generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
//Next one is numeric
rand = r.NextDouble();
generatedPassword += numerics.ToCharArray()[(int) Math.Floor(rand*numerics.Length)];
}
else
{
generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
}
}
return generatedPassword;
}
public int MinPasswordLength
{
get
{
return Membership.Provider.MinRequiredPasswordLength;
}
}
public string AdminRole
{
get { return "admin"; }
}
public string MemberRole
{
get { return "member"; }
}
public string DelegateRole
{
get { return "delegate"; }
}
public string AgentRole
{
get { return "agent"; }
}
public bool Delete(string email)
{
return Membership.DeleteUser(email);
}
public bool IsAdmin()
{
return Roles.IsUserInRole(AdminRole);
}
public bool IsMember()
{
return Roles.IsUserInRole(MemberRole);
}
public bool IsDelegate()
{
return Roles.IsUserInRole(DelegateRole);
}
public bool IsAgent()
{
return Roles.IsUserInRole(AgentRole);
}
public bool ChangePassword(string email, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
try
{
var currentUser = Membership.Provider.GetUser(email, true);
return currentUser.ChangePassword(oldPassword, newPassword);
}
catch (ArgumentException)
{
return false;
}
catch (MembershipPasswordException)
{
return false;
}
}
public string ResetPassword(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
Unlock(email);
var currentUser = Membership.Provider.GetUser(email, false);
return currentUser.ResetPassword();
}
public bool CheckLocked(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
if (currentUser == null) return false;
if (!currentUser.IsLockedOut) return false;
if (currentUser.LastLockoutDate.AddMinutes(30) < DateTime.Now)
{
currentUser.UnlockUser();
return false;
}
return true;
}
public bool Unlock(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
if (currentUser == null) return false;
currentUser.UnlockUser();
return true;
}
}
I hope it can help!

Resources