ActionFilter to read Contents before RedirectToAction - asp.net-mvc-3

I wish to record deletes and edits, and thought the best way would be to apply An actionFilter
Attribute to my delete and edit [ post ] methods
But because the end results is a redirect to action, my Context.Result is always null
because there is only a Context.RedirectToAction results available.
Now before i go creating some code to plug into my delete and Edit functions, has anyone tried something like this!, and could you possibly advise?
Thanks
Action Code:
[HttpPost, ValidateInput(false)]
[SiteChangeLogger(LogType = "Update", TableName = "Affiliates")]
public ActionResult Edit(Affiliate affiliate, FormCollection form)
{
var existing = db2.Affiliates.SingleOrDefault(x => x.AffiliateId == affiliate.AffiliateId);
ViewBag.before = Common.Strings.Base64Encode(Common.Strings.ToJsonString(existing));
if (ModelState.IsValid)
{
try
{
var curFiles = new NameValueCollection();
curFiles["AffiliateLogo"] = affiliate.AffiliateLogo;
if (!String.IsNullOrWhiteSpace(form["AffiliateLogo"]))
{
UploadFiles(form,curFiles);
TryUpdateModel(affiliate, form);
var oldFileName = affiliate.AffiliateLogo;
var newFileName = Common.Strings.RandomFileName();
new WebImage(Server.MapPath("~/Content/images/" + affiliate.AffiliateLogo))
.Resize(200, 50, true, true)
.Crop(1, 1)
.Save(Server.MapPath("~/Content/images/" + newFileName), "png", true);
affiliate.AffiliateLogo = newFileName + ".png";
Common.Common.TryAndDeleteFile("~/Content/images/" + oldFileName);
}
else
{
affiliate.AffiliateLogo = existing.AffiliateLogo;
}
}
catch (Exception ex)
{
Common.Common.CompileErrorMessage(ex,"ADMIN.Affiliate.Edit");
}
finally
{
db.Entry(affiliate).State = EntityState.Modified;
db.SaveChanges();
}
ViewBag.after = Common.Strings.Base64Encode(Common.Strings.ToJsonString(affiliate));
return RedirectToAction("Index");
}
return View(affiliate);
}
my Filter Code
public override void OnResultExecuted(ResultExecutedContext fc)
{
var viewResult = fc.Result as ViewResult;
if(viewResult == null) return;
var beforeData = viewResult.ViewBag.before;
var afterData = viewResult.ViewBag.after;
if (beforeData == null && afterData == null) return;
var ctx = new SgeGamesContext();
var eventId = 0;
var siteChangeLogEvent = ctx.SiteChangeLogEvents.SingleOrDefault(x => x.SiteChangeLogEventName == LogType);
if (siteChangeLogEvent != null)
{
eventId = siteChangeLogEvent.SiteChangeLogEventId;
}
var model = new Sge.Games.Data.Models.SiteChangeLog
{
SiteChangeLogTable = TableName,
SiteId = 1,
SiteChangeLogAfterContent = afterData,
SiteChangeLogBeforeContent = beforeData,
SiteChangeLogEventId = eventId
};
ctx.SiteChangeLogs.Add(model);
ctx.SaveChanges();
base.OnResultExecuted(fc);
}

You could access the ViewBag directly, you don't need a ViewResult:
public override void OnResultExecuted(ResultExecutedContext fc)
{
var before = fc.Controller.ViewBag.before;
var after = fc.Controller.ViewBag.after;
...
}
Also you probably want to use the OnActionExecuted event instead of OnResultExecuted.

Related

Send Mail/Task/Appointment with Redemption

I am trying to programmatically send a Mail/Task/Appointment to a user and I have the problem, that every time I send them the first one will get stuck in my outbox... It seems that the first one sent to Outlook has no/looses its sent-date and will stay forever in my outbox.
Here is the code for example "sending a task notification"
using (MapiSession session = new MapiSession())
{
var item = session.CreateItem(Outlook.OlItemType.olTaskItem) as RDOTaskItem;
[..]
try
{
item.Subject = "SUBJECT";
item.Body = "BODY;
item.StartDate = DateTime.Now;
item.DueDate = DateTime.Now;
item.Recipients.Add("test#mail.com");
item.Recipients.Add("test2#mail.com");
item.Recipients.ResolveAll();
item.Assign();
item.Save();
item.Send();
}
[..]
}
Thanks in advance.
So I am not really shure what is the problem so far...
If all receivers are other persons then myself this should work...
Here is my code for sendig a TaskItem
private void NotifyByTask(OutlookNotificationTypes notificationType)
{
Application app = new Application();
var item = app.CreateItem(OlItemType.olTaskItem) as TaskItem;
try
{
item.Subject = this.Subject;
item.Body = this.Body;
if (this.Start != DateTime.MinValue)
{
item.StartDate = this.Start;
item.ReminderSet = true;
item.ReminderPlaySound = true;
item.ReminderTime = this.Start.AddMinutes(-5);
}
if (this.End != DateTime.MinValue)
{
item.DueDate = this.End;
}
item.PercentComplete = this.PercentComplete;
StringBuilder categories = new StringBuilder();
foreach (String category in this.Categories)
{
categories.Append(category);
}
item.Categories = categories.ToString();
bool sendingToMyself = false;
if (this.NotificationType == OutlookNotificationTypes.TaskRequest)
{
// this will add all recipients and checks if Receiver is yourself
sendingToMyself = item.AddRecipients(this.Recipients, OlMailRecipientType.olTo);
}
if (this.NotificationType == OutlookNotificationTypes.TaskRequest
&& (!sendingToMyself))
{
item.Recipients.ResolveAll();
item.Assign();
item.Save();
item.Send();
}
else
{
item.Save();
//insert element
if (this.ItemSaved != null)
{
Microsoft.Office.Interop.Outlook.MAPIFolder folder =
item.Parent as Microsoft.Office.Interop.Outlook.MAPIFolder;
if (folder != null)
{
try
{
String storeId = folder.StoreID;
String entryId = item.EntryID;
this.ItemSaved(storeId, entryId);
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
}
}
}
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
}
}

Save files in asp.net folder with reference in the database from a desktop client

ASP.NET WEB API: Hi, I would like to know to save files in asp.net web api folder with the link reference in database from desktop client. I searched it online and got some implementation still it's not workin.
Below are what I got so far. I hope someone can help me out with that.
Your contribution will really help.
My api controller code
[HttpPost]
public HttpResponseMessage PostFile()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
if (postedFile != null)
{
var filePath = HttpContext.Current.Server.MapPath("~/files" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
My client side code
OpenFileDialog fd = new OpenFileDialog();
private void btnUpload_Click(object sender, EventArgs e)
{
bool uploadStatus = false;
fd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp;)|*.jpg; *jpeg; *.gif; *.bmp;";
fd.Title = "Choose image";
if (fd.ShowDialog() == DialogResult.OK)
{
picUpload.Image = new Bitmap(fd.FileName);
foreach(String localfile in fd.FileNames)
{
var url = "url";
var filepath = #"\";
Random ran = new Random();
var uploadFileName = "img" + ran.Next(999).ToString();
uploadStatus = UploadConfig(url, filepath, localfile, uploadFileName);
}
}
if (uploadStatus)
{
MessageBox.Show("Successful");
}
else
{
MessageBox.Show("Failed");
}
}
bool UploadConfig(string url, string filePath, string localFileName, string UploadFileName)
{
bool isFileUploaded = false;
try
{
using (HttpClient client = new HttpClient())
{
var fs = File.Open(localFileName, FileMode.Open);
var fi = new FileInfo(localFileName);
UploadDetails uploadDetails = null;
bool fileUpload = false;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Headers.Add("filePath",filePath);
content.Add(new StreamContent(fs), "\"files\"",
string.Format("\"{0}\"", UploadFileName + fi.Extension));
Task taskUpload = client.PostAsync(url, content).ContinueWith(task =>
{
if(task.Status == TaskStatus.RanToCompletion)
{
var res = task.Result;
if (res.IsSuccessStatusCode)
{
uploadDetails = res.Content.ReadAsAsync<UploadDetails>().Result;
if (uploadDetails != null)
{
fileUpload = true;
}
}
}
fs.Dispose();
});
taskUpload.Wait();
if (fileUpload)
{
isFileUploaded = true;
client.Dispose();
}
}
}
catch (Exception e)
{
isFileUploaded = false;
}
return isFileUploaded;
}

Exception in HttpControllerDispatcher

In my WebApiConfig::Register(...) I replaced the HttpControllerSelector with my own controller selector. When I fire off a POST request the SelectController member is correctly called and I return a ControllerDescriptor with the correct type of my controller.
But then HttpControllerDispatcher is raising an exception saying "The given was not present in the dictionary." Anyone has an idea how to debug such error?
The complete exception is message is:
The given key was not present in the dictionary.","ExceptionType":"System.Collections.Generic.KeyNotFoundException","StackTrace":" at System.Collections.Generic.Dictionary`2.get_Item(TKey key)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.FindActionMatchRequiredRouteAndQueryParameters(IEnumerable`1 candidatesFound)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.FindMatchingActions(HttpControllerContext controllerContext, Boolean ignoreVerbs)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
And here is my Controller Selector:
public class Namespace_HTTP_Controller_Selector : IHttpControllerSelector
{
private readonly HttpConfiguration _configuration;
private readonly Lazy<Dictionary<string, HttpControllerDescriptor>> _controller;
public Namespace_HTTP_Controller_Selector(HttpConfiguration Config)
{
_configuration = Config;
_controller = new Lazy<Dictionary<string, HttpControllerDescriptor>>(Initialize_Controller_Dictionary);
}
public HttpControllerDescriptor SelectController(HttpRequestMessage Request)
{
var Route_Data = Request.GetRouteData();
if(Route_Data == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var Controller_Name = Get_Controller_Name(Route_Data);
if(Controller_Name == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var Name_Space = Get_Version(Route_Data);
if (Name_Space == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var Controller_Key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", Name_Space, Controller_Name);
HttpControllerDescriptor Descriptor;
if(_controller.Value.TryGetValue(Controller_Key, out Descriptor))
{
return Descriptor;
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
public IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
return _controller.Value;
}
private Dictionary<string, HttpControllerDescriptor> Initialize_Controller_Dictionary()
{
var Dictionary = new Dictionary<string, HttpControllerDescriptor>(StringComparer.OrdinalIgnoreCase);
var Assemblies_Resolver = _configuration.Services.GetAssembliesResolver();
var Controller_Resolver = _configuration.Services.GetHttpControllerTypeResolver();
var Controller_Types = Controller_Resolver.GetControllerTypes(Assemblies_Resolver);
foreach(var ct in Controller_Types)
{
var Segments = ct.Namespace.Split(Type.Delimiter);
var Controller_Name = ct.Name.Remove(ct.Name.Length - DefaultHttpControllerSelector.ControllerSuffix.Length);
var Controller_Key = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", Segments[Segments.Length - 1], Controller_Name);
if(Dictionary.Keys.Contains(Controller_Key) == false)
{
Dictionary[Controller_Key] = new HttpControllerDescriptor(_configuration, ct.Name, ct);
}
}
return Dictionary;
}
private T Get_Route_Variable<T>(IHttpRouteData Route_Data, string Name)
{
object Result;
if(Route_Data.Values.TryGetValue(Name, out Result))
{
return (T)Result;
}
return default(T);
}
private string Get_Controller_Name(IHttpRouteData Route_Data)
{
var SubRoute = Route_Data.GetSubRoutes().FirstOrDefault();
if( SubRoute == null )
{
return null;
}
var Data_Token_Value = SubRoute.Route.DataTokens.First().Value;
if(Data_Token_Value == null)
{
return null;
}
var Controller_Name = ((HttpActionDescriptor[])Data_Token_Value).First().ControllerDescriptor.ControllerName.Replace("Controller", string.Empty);
return Controller_Name;
}
private string Get_Version(IHttpRouteData Route_Data)
{
var Sub_Route_Data = Route_Data.GetSubRoutes().FirstOrDefault();
if(Sub_Route_Data== null)
{
return null;
}
return Get_Route_Variable<string>(Sub_Route_Data, "apiVersion");
}
}
This is because you are not setting subroute data in request before returning descriptor.
HttpControllerDescriptor Descriptor;
if(_controller.Value.TryGetValue(Controller_Key, out Descriptor))
{
var subRoutes = Route_Data.GetSubRoutes();
IEnumerable<IHttpRouteData> filteredSubRoutes = subRoutes.Where(attrRouteData =>
{
HttpControllerDescriptor currentDescriptor = ((HttpActionDescriptor[])Route_Data.Route.DataTokens["actions"]).First().ControllerDescriptor;
return currentDescriptor != null && currentDescriptor.ControllerName.Equals(Descriptor.ControllerName, StringComparison.OrdinalIgnoreCase);
});
Route_Data.Values["MS_SubRoutes"] = filteredSubRoutes.ToArray();
return Descriptor;
}
Take a look at:
Versioning ASP.NET Web API 2 with Media Types
public class CustomSelectorController : DefaultHttpControllerSelector
{
HttpConfiguration _config;
public CustomSelectorController(HttpConfiguration config) : base(config)
{
_config = config;
}
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
IHttpRouteData routeData = request.GetRouteData();
IEnumerable<IHttpRouteData> attributeSubRoutes = routeData.GetSubRoutes();
var actions = attributeSubRoutes.LastOrDefault()?.Route?.DataTokens["actions"] as HttpActionDescriptor[];
var controllerName = "";
if (actions != null && actions.Length > 0)
{
controllerName = actions[0].ControllerDescriptor.ControllerName;
}
IEnumerable<string> headerValues = null;
//Custom Header Name to be check version
if (request.Headers.TryGetValues("Accept-Version", out headerValues))
{
var apiVersion = headerValues.First().ToUpper();
if (apiVersion == "V2")
{
controllerName = controllerName + apiVersion;
}
}
HttpControllerDescriptor controllerDescriptor = null;
IEnumerable<IHttpRouteData> filteredSubRoutes = attributeSubRoutes.Where(attrRouteData =>
{
HttpControllerDescriptor currentDescriptor = GetControllerDescriptor(attrRouteData);
bool match = currentDescriptor.ControllerName.Equals(controllerName);
if (match && (controllerDescriptor == null))
{
controllerDescriptor = currentDescriptor;
}
return match;
});
routeData.Values["MS_SubRoutes"] = filteredSubRoutes.ToArray();
return controllerDescriptor;
}
private HttpControllerDescriptor GetControllerDescriptor(IHttpRouteData routeData)
{
return ((HttpActionDescriptor[])routeData.Route.DataTokens["actions"]).First().ControllerDescriptor;
}
}

How can i return Json Result + Web api + validate model + actionfilters +OnActionExecuting method

string message = string.Empty;
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
foreach (var key in modelState.Keys)
{
var state = modelState[key];
if (state.Errors.Any())
{
message = message + state.Errors.First().ErrorMessage;
}
}
}
Here i want to return message variable with Jsonresult, please help me on it.
Try this
public override void OnActionExecuting(HttpActionContext context)
{
var modelState = context.ModelState;
if (!modelState.IsValid)
{
var errors = new JObject();
foreach (var key in modelState.Keys)
{
var state = modelState[key];
if (state.Errors.Any())
{
errors[key] = state.Errors.First().ErrorMessage;
}
}
context.Response = context.Request.CreateResponse<JObject>(HttpStatusCode.BadRequest, errors);
}
}
From the client ajax request, on error, get the responseText to process the validation error messages.
You might want to pick a HttpStatusCode based on what you are trying to do, since the

How to add QueryString in OnActionExecuting()?

i want to add two queryString in current request URL if it is not exsist
Edited:
I tried this ---
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.QueryString["mid"] == null && filterContext.RequestContext.HttpContext.Request.QueryString["mod"] == null)
{
mid = Convert.ToString(HttpUtility.ParseQueryString(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Query)["mid"]);
mod = Convert.ToString(HttpUtility.ParseQueryString(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Query)["mod"]);
if (!string.IsNullOrEmpty(mid) || !string.IsNullOrEmpty(mod))
{
RouteValueDictionary redirecttargetDictionary = new RouteValueDictionary();
NameValueCollection Qstr = null;
if (filterContext.HttpContext.Request.RequestType == "GET")
{
Qstr = HttpUtility.ParseQueryString(filterContext.HttpContext.Request.Url.Query);
foreach (string item in Qstr)
{
redirecttargetDictionary.Add(item, Qstr[item]);
}
if (Qstr["mid"] == null)
{
redirecttargetDictionary.Add("mid", mid);
}
if (Qstr["mod"] == null)
{
redirecttargetDictionary.Add("mod", mod);
}
filterContext.Result = new RedirectToRouteResult(redirecttargetDictionary);
}
}
}
This code works fine.
-check for quesrystring exsist if no
-then take qstring value from 'Urlreferrer'
-if request type is GET
-then add two querystring with exsisting querystring
But but I having problem if querystring in current request has null value url like http://localhost:53372/question/index?type=&stage.if this ll b the current request url then code ll check for mid n mod qstring as its not exsist it will add both the qstring with exsisting type n stage but value ll b null then before hitting action again OnActionExecuting() get call this time first 'if' is not true and then index method get call but I m not getting type n stage querystring which suppose to null I found url in address bar is http://localhost:53372/question/index?mid=1&mod=5.
If I remove filter the I got URL http://localhost:53372/question/index?type=&stage=&mid=1&mod=5 here I m getting both stage n type querystring though its null.
Edited--
[HttpGet]
public ActionResult Index(ProjectType? projectType, int? projectStageID, int? page)
{
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
IPagedList<ProjectModule> moduleList = null;
IDictionary<string, string> queryParam = new Dictionary<string, string>();
queryParam["ProjectType"] = string.Empty;
queryParam["ProjectStageID"] = string.Empty;
ViewBag.ProjectType = null;
ViewBag.ProjectStage = null;
ViewBag.message = "";
if ((projectType != null || projectType.HasValue) && projectStageID.HasValue && page.HasValue)
{
queryParam["ProjectType"] = Request.QueryString["ProjectType"];
queryParam["ProjectStageID"] = Request.QueryString["ProjectStageID"];
//
//Set View Bag
//
ViewBag.ProjectType = Enum.Parse(typeof(ProjectType), Request.QueryString["ProjectType"]);
ViewBag.ProjectStage = Convert.ToInt32(Request.QueryString["ProjectStageID"]);
//
// Set Query String formcollection for Pagging purpose
//
ViewBag.QueryParam = queryParam;
moduleList = new ProjectModuleService().GetProjectModulesByProjectStageID(Convert.ToInt32(Request.QueryString["ProjectStageID"])).ToPagedList(currentPageIndex, Utility.ConstantHelper.AdminDefaultPageSize); ;
if (moduleList.Count == 0)
{
ViewBag.message = "Record(s) not found.";
}
return View(moduleList);
}
else
{
if (!string.IsNullOrEmpty(Request.QueryString["ProjectType"]) && !string.IsNullOrEmpty(Request.QueryString["ProjectStageID"]) && !string.Equals(Request.QueryString["ProjectStageID"], "0"))
{
if (!string.IsNullOrEmpty(Request.Params.Get("Index")))
{
queryParam["ProjectType"] = Request.QueryString["ProjectType"];
queryParam["ProjectStageID"] = Request.QueryString["ProjectStageID"];
//
//Set View Bag
//
ViewBag.ProjectType = Enum.Parse(typeof(ProjectType), Request.QueryString["ProjectType"]);
ViewBag.ProjectStage = Convert.ToInt32(Request.QueryString["ProjectStageID"]);
//
// Set Query String formcollection for Pagging purpose
//
ViewBag.QueryParam = queryParam;
moduleList = new ProjectModuleService().GetProjectModulesByProjectStageID(Convert.ToInt32(Request.QueryString["ProjectStageID"])).ToPagedList(currentPageIndex, Utility.ConstantHelper.AdminDefaultPageSize); ;
if (moduleList.Count == 0)
{
ViewBag.message = "Record(s) not found.";
}
return View(moduleList);
}
else if (!string.IsNullOrEmpty(Request.Params.Get("Create")))
{
return RedirectToAction("Create", new { projectStageID = Convert.ToInt32(Request.QueryString["ProjectStageID"]) });
//return RedirectToAction("Create", new { projectStageID = Convert.ToInt32(Request.QueryString["ProjectStageID"]), projectType = Enum.Parse(typeof(ProjectType), Request.QueryString["ProjectType"]) });
}
}
if (Request.QueryString["ProjectType"] == "" || Request.QueryString["ProjectStageID"] == "" || string.Equals(Request.QueryString["ProjectStageID"], "0"))
{
ViewBag.message = "Please select all fields.";
return View();
}
return View();
}
}
What I m doing wrong?
Here what I understand that if there are no querystring in the URL,you need to add two query string parameters. If you are adding this two querystring parameters explicitly than, it will be default value for that queryparameters.
It's better to provide default value in action method instead of adding queryparameters in URL. You can achieve by following code.
public ActionResult ComposeEmail(int queryParameter1 = 0,string queryParameter2 = string.Empty)
{
}
Do let me know, if you have any query.

Resources