Check for but allow duplicates entries in the Db - asp.net-mvc

My Db allows duplicate monuments, so the traditional method of checking for duplicates will not work. The user first inputs a monument name, then I run a check against the Db and if no duplicates found, great, allow the user to input the rest of the data. If one of more monuments with the same name are found, display a list of the monuments already in the Db. If this is truly a new monument with the same name, allow the user to input the new monument.
What I have so far:
[Authorize]
public ActionResult MonumentTitle(string battleRecordID, int callingRecordID)
{
ViewBag.monumentBattleRecID = battleRecordID; // ID of the battle
ViewBag.battleName = getBattleName(battleRecordID);
var vModel = new MonumentTitle();
vModel.BattleRecID = ViewBag.monumentBattleRecID;
vModel.BattleName = ViewBag.battleName;
vModel.CallingRecID = callingRecordID;
return View(vModel);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitle(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
ViewBag.battleName = monumentTitle.BattleName;
ViewBag.MonumentName = monumentTitle.MonumentName;
var NmonumentTitle = monumentTitle;
ViewBag.battleName1 = NmonumentTitle.BattleName;
var List_monument = from s in db.Monuments
where (s.MonumentStatus == "A" &&
s.MonumentBattleRecID == monumentTitle.BattleRecID &&
s.MonumentName == monumentTitle.MonumentName
)
select s;
List_monument = List_monument.OrderBy(s => s.MonumentName);
var vModel = new MonumentTitleDuplicate();
vModel.MonumentTitle = NmonumentTitle;
vModel.Monument = List_monument.ToList();
if (vModel.Monument.Count == 0)
{
return RedirectToAction("MonumentCreate", new { battleRecord = vModel.MonumentTitle.BattleRecID, callingRecordID = vModel.MonumentTitle.CallingRecID, monumentName = vModel.MonumentTitle.MonumentName });
}
{
return RedirectToAction("MonumentTitleDuplicate", vModel );
}
}
Works for when there is not a duplicate. Where I run into a problem is trying to switch control to "MonumentTitleDuplicate" and pass the model.
[Authorize]
[HttpGet]
public ViewResult MonumentTitleDuplicate(MonumentTitleDuplicate monumentTitleDuplicate)
{
return View("MonumentTitleDuplicate", monumentTitleDuplicate);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitleDuplicate(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
return RedirectToAction("MonumentCreate", new { battleRecord = monumentTitle.BattleRecID, callingRecordID = monumentTitle.CallingRecID, monumentName = monumentTitle.MonumentName });
}
[Authorize]
public ActionResult MonumentCreate(string battleRecord, int callingRecordID, string monumentName)
{

Got it -- needed to use TempData to pass the model to the new controller so:
[Authorize]
public ActionResult MonumentTitle(string battleRecordID, int callingRecordID)
{
ViewBag.monumentBattleRecID = battleRecordID; // ID of the battle
ViewBag.battleName = getBattleName(battleRecordID);
var vModel = new MonumentTitle();
vModel.BattleRecID = ViewBag.monumentBattleRecID;
vModel.BattleName = ViewBag.battleName;
vModel.CallingRecID = callingRecordID;
return View(vModel);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitle(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
ViewBag.battleName = monumentTitle.BattleName;
ViewBag.MonumentName = monumentTitle.MonumentName;
var NmonumentTitle = monumentTitle;
ViewBag.battleName1 = NmonumentTitle.BattleName;
var List_monument = from s in db.Monuments
where (s.MonumentStatus == "A" &&
s.MonumentBattleRecID == monumentTitle.BattleRecID &&
s.MonumentName == monumentTitle.MonumentName
)
select s;
List_monument = List_monument.OrderBy(s => s.MonumentName);
var vModel = new MonumentTitleDuplicate();
vModel.MonumentTitle = NmonumentTitle;
vModel.Monument = List_monument.ToList();
if (vModel.Monument.Count == 0)
{
return RedirectToAction("MonumentCreate", new { battleRecord = vModel.MonumentTitle.BattleRecID, callingRecordID = vModel.MonumentTitle.CallingRecID, monumentName = vModel.MonumentTitle.MonumentName });
}
{
TempData["monumentTitleDuplicate"] = vModel;
return RedirectToAction("MonumentTitleDuplicate");
}
}
[Authorize]
public ActionResult MonumentTitleDuplicate()
{
MonumentTitleDuplicate monumentTitleDuplicate = TempData["MonumentTitleDuplicate"] as MonumentTitleDuplicate;
return View(monumentTitleDuplicate);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitleDuplicate(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
return RedirectToAction("MonumentCreate", new { battleRecord = monumentTitle.BattleRecID, callingRecordID = monumentTitle.CallingRecID, monumentName = monumentTitle.MonumentName });
}
Probably have some cleanup work to do (like getting rid of the stuff where I was trying to use ViewBag), but does appear to be working.

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
}
}

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'Int32' for method 'Edit(Int32)'

I am performing CRUD operation using linq to sql. But while clicking on Edit, Details or delete it gives me error i.e. "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'CRUD_using_LinQ_to_SQL_in_MVC.Controllers.OTDController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
I checked the solution and found that, while running application url didn't get ID parameter. But i dont understand what should i change in my code.. Can you please help me...
My Controller Code:
using System;
namespace CRUD_using_LinQ_to_SQL_in_MVC.Controllers
{
public class OTDController : Controller
{
private IOTddataRepository repository;
public OTDController()
: this(new OtdDataRepository())
{
}
public OTDController(IOTddataRepository _repository)
{
repository = _repository;
}
//-----------------------Index--------------------------
public ActionResult Index()
{
var otddata = repository.Getallotddata();
return View(otddata);
}
//-----------------------Details--------------------------
public ActionResult Details(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
//-----------------------Create--------------------------
public ActionResult Create()
{
return View(new OtdModelClass());
}
[HttpPost]
public ActionResult Create(OtdModelClass otdmodel)
{
try
{
if (ModelState.IsValid)
{
repository.Insertotddata(otdmodel);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in Data Saving");
}
return View(otdmodel);
}
//-----------------------EDIT--------------------------
public ActionResult Edit(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost]
public ActionResult Edit(OtdModelClass otdclass)
{
try
{
if (ModelState.IsValid)
{
repository.Updateotddata(otdclass);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in editing and Updating data");
}
return View(otdclass);
}
//-----------------------Delete--------------------------
public ActionResult Delete(int id, bool? savechangeserror)
{
if (savechangeserror.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Problem in Deleting";
}
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
try
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
repository.Deleteotddata(id);
}
catch (DataException)
{
return RedirectToAction("Delete", new System.Web.Routing.RouteValueDictionary {
{"id",id},
{"SaveChangesError",true}});
}
return RedirectToAction("Index");
}
}
}
My OTD class Code:
public class OtdDataRepository : IOTddataRepository
{
private MVCLoginMasterLogDataClassesDataContext otdcontextobj;
public OtdDataRepository()
{
otdcontextobj = new MVCLoginMasterLogDataClassesDataContext();
}
public IEnumerable<OtdModelClass> Getallotddata()
{
IList<OtdModelClass> otddatalist = new List<OtdModelClass>();
var myselectallquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs select otduser;
var otd = myselectallquery.ToList();
foreach (var otddata in otd)
{
otddatalist.Add(new OtdModelClass()
{
Srno=Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
});
}
return otddatalist;
}
public OtdModelClass Getotddatabysrno(int id)
{
var getotddataquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs
where otduser.Srno == id
select otduser;
var otddata = getotddataquery.FirstOrDefault();
var otdmodel = new OtdModelClass()
{
Srno = Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
};
return otdmodel;
}
public void Insertotddata(OtdModelClass otdmodel_obj)
{
var empdata = new tbl_MVC_Login_Master_Log()
{
Srno = Convert.ToInt32(otdmodel_obj.Srno),
MemberCode = otdmodel_obj.MemberCode,
LoginID = otdmodel_obj.LoginID,
OTDPassword = otdmodel_obj.OTDPassword,
BBSID = otdmodel_obj.BBSID,
IPAddress = otdmodel_obj.IPAddress,
ServerType = otdmodel_obj.ServerType,
OTDStatus = otdmodel_obj.OTDStatus,
RemoteIP = otdmodel_obj.RemoteIP,
RemotePort = otdmodel_obj.RemotePort,
AllowDownload = otdmodel_obj.AllowDownload,
OTDTimeStamp = otdmodel_obj.OTDTimeStamp,
MemberType = otdmodel_obj.MemberType,
EQ = otdmodel_obj.EQ,
EQD = otdmodel_obj.EQD,
BFX = otdmodel_obj.BFX,
SLB = otdmodel_obj.SLB,
Others = otdmodel_obj.Others
};
otdcontextobj.tbl_MVC_Login_Master_Logs.InsertOnSubmit(empdata);
otdcontextobj.SubmitChanges();
}
public void Deleteotddata(int id)
{
tbl_MVC_Login_Master_Log otd_deletelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser => otduser.Srno == id).SingleOrDefault();
otdcontextobj.tbl_MVC_Login_Master_Logs.DeleteOnSubmit(otd_deletelog);
otdcontextobj.SubmitChanges();
}
public void Updateotddata(OtdModelClass otdmodel_obj)
{
tbl_MVC_Login_Master_Log otd_updatelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser=>otduser.Srno==otdmodel_obj.Srno).SingleOrDefault();
otd_updatelog.Srno = otdmodel_obj.Srno;
otd_updatelog.MemberCode = otdmodel_obj.MemberCode;
otd_updatelog.LoginID = otdmodel_obj.LoginID;
otd_updatelog.OTDPassword = otdmodel_obj.OTDPassword;
otd_updatelog.BBSID = otdmodel_obj.BBSID;
otd_updatelog.IPAddress = otdmodel_obj.IPAddress;
otd_updatelog.ServerType = otdmodel_obj.ServerType;
otd_updatelog.OTDStatus = otdmodel_obj.OTDStatus;
otd_updatelog.RemoteIP = otdmodel_obj.RemoteIP;
otd_updatelog.RemotePort = otdmodel_obj.RemotePort;
otd_updatelog.AllowDownload = otdmodel_obj.AllowDownload;
otd_updatelog.OTDTimeStamp = otdmodel_obj.OTDTimeStamp;
otd_updatelog.MemberType = otdmodel_obj.MemberType;
otd_updatelog.EQ = otdmodel_obj.EQ;
otd_updatelog.EQD = otdmodel_obj.EQD;
otd_updatelog.BFX = otdmodel_obj.BFX;
otd_updatelog.SLB = otdmodel_obj.SLB;
otd_updatelog.Others = otdmodel_obj.Others;
otdcontextobj.SubmitChanges();
}
}
Can you please help me...
The framework is telling you that the link you are clicking on to call the Edit and Delete action methods is not providing an int parameter named id which the action method is expecting to find somewhere in the submitted data. This is usually provided either in the URL, query string or submitted variables.
If that is not enough for you to spot the problem, post your view code specially the section related to the links.

run EF6 async request in mvc controller

I have mvc 5 and EF6 and never really use async in mvc before so want ask best way for run sql requests.
public ActionResult SearchTest(string id)
{
string searchtxt = UsefulClass.ConvertObjectToString(id).Replace(",", " ").Trim();
var model = new SearchResult();
if (!String.IsNullOrEmpty(searchtxt))
{
//get the data from 3 requests
var ArtistList = _db.Artists.SqlQuery("SELECT top 6 * FROM Artists WHERE CONTAINS(Name, N'Queen') and TopTracksStatus = 1 and GrabStatus > 1 order by playcount desc").ToList();
var tracks = _db.Database.SqlQuery<TrackInfo>("exec SearchTracks #SearchText=N'Queen', #TopCount=10,#LengthCount=100").ToList();
var TagsList = _db.Tags.Where(x => x.TagName.Contains(searchtxt)).Take(5).ToList();
//work with ArtistList and add to model
if (ArtistList.Any())
{
int i = 0;
foreach (var artist in ArtistList)
{
i++;
if (i == 1) //top artist
{
model.BestArtist = artist;
model.BestArtistTrackCount = _db.TopTracks.Count(x => x.Artist_Id == artist.Id);
}
else
{
model.ArtistList = ArtistList.Where(x => x.Id != model.BestArtist.Id);
break;
}
}
}
//work with tracks and add to model
if (tracks.Any())
{
model.TopTrackList = tracks;
}
//work with tags and add to model
if (TagsList.Any())
{
model.TagList = TagsList;
}
}
return View(model);
}
Here I have 3 requests which return ArtistList, tracks, TagsList and I need add them to model and then pass to view. How to do it in async way?
Try below example, hope it gives you a good idea.
public async Task<ActionResult> SearchTestAsync(string id)
{
string searchtxt = UsefulClass.ConvertObjectToString(id).Replace(",", " ").Trim();
var model = new SearchResult();
if (!String.IsNullOrEmpty(searchtxt))
{
var art = GetArtistListResulst(model);
var track = GetTracksResults(model);
var tag = GetTagsListResults(model,searchtxt);
await Task.WhenAll(art, track, tag);
}
return View(model);
}
private Task GetArtistListResulst(SearchResult model)
{
return Task.Run(() =>
{
var artistList = _db.Artists.SqlQuery("SELECT top 6 * FROM Artists WHERE CONTAINS(Name, N'Queen') and TopTracksStatus = 1 and GrabStatus > 1 order by playcount desc").ToList();
// You don't need to use foreach because the artistList is ordered by playcount already.
model.BestArtist = artistList.Take(1);
model.BestArtistTrackCount = _db.TopTracks.Count(x => x.Artist_Id == model.BestArtist.Id);
model.ArtistList = artistList.Where(x => x.Id != model.BestArtist.Id);
});
}
private Task GetTracksResults(SearchResult model)
{
return Task.Run(() =>
{
model.TopTrackList = _db.Database.SqlQuery<TrackInfo>("exec SearchTracks #SearchText=N'Queen', #TopCount=10,#LengthCount=100").ToList();
});
}
private Task GetTagsListResults(SearchResult model, string searchtxt)
{
return Task.Run(() =>
{
model.TagsList = _db.Tags.Where(x => x.TagName.Contains(searchtxt)).Take(5).ToList();
});
}

Combine model in asp.net mvc

I combine my tables to Result. İt works with no problem.
public ActionResult Index()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
However, when using multiple actions, i have to write the above code every time.
For instance:
public ActionResult Customer()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
public ActionResult Product()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
İ have to combine my tables in every actionresult.
How can i write only one time and use my Result everywhere ?
You may do as follows. I always use this approach:
public Modeller GetResult()
{
var result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return result;
}
public ActionResult Customer()
{
var Result = GetResult();
return View(Result);
}
public ActionResult Product()
{
var Result = GetResult();
return View(Result);
}
One option is to just reference a shared class/service. For example:
public class YourService
{
public static Modeller GetCombinedTables()
{
return new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList()
};
}
}
Then, in your action you can just call that method:
public ActionResult Customer()
{
var Result = YourService.GetCombinedTables();
return View(Result);
}
You can also create the Result variable at controller level, so that way you don't have to assign it for every action.

Help! I've got repository access in my MVC master page! Refactor time!

I've got the following code in my master page to load some customization stuff, like a css file, some address info in the footer, a header/footer logo etc. And I'm faced with load times of up to a minute! This is terrible practice, and I know - I just hacked it out to make it work. What would be the best practice of loading this type of customization information?
Currently, I try to load a cookie - check if it has the required keys, and if it doesnt - load the information from the database. I would like to have something similar to a .config file that's cached on the clients machine, if possible.
All the information is stored in a table called StoreSettings, which is linked to the Reseller table with StoreSettingsID.
<head id="Head1">
<%
HttpCookie storeSettingsCookie = Request.Cookies["StoreSettings"];
try
{
if (storeSettingsCookie == null || storeSettingsCookie.HasKeys == false)
{
if (Context.User.Identity.IsAuthenticated && Context.User.IsInRole("Reseller"))
{
var reseller = new Reseller();
var storeSettings = new StoreSettings();
var resellerRepository = new ResellerRepository();
reseller = resellerRepository.GetResellerByUsername(Context.User.Identity.Name);
if (reseller.StoreSettingsID != null && reseller.StoreSetting.Theme != null)
{
var storeSettingsRepository = new StoreSettingsRepository();
storeSettings = storeSettingsRepository.GetStoreSettings((int)reseller.StoreSettingsID);
storeSettingsCookie = new HttpCookie("StoreSettings");
storeSettingsCookie["HeaderImage"] = storeSettings.Image1.FileName;
storeSettingsCookie["FooterImage"] = storeSettings.Image.FileName;
storeSettingsCookie["ThemeLocation"] = storeSettings.Theme.StylesheetLocation;
storeSettingsCookie["StoreName"] = storeSettings.StoreName;
storeSettingsCookie["Address1"] = storeSettings.Address1;
storeSettingsCookie["Address2"] = storeSettings.Address2;
storeSettingsCookie["City"] = storeSettings.City;
storeSettingsCookie["PostalCode"] = storeSettings.PostalCode;
storeSettingsCookie["ProvinceCode"] = storeSettings.Province.Abbreviation;
storeSettingsCookie["Phone"] = storeSettings.Phone;
Response.Cookies.Add(storeSettingsCookie);
}
else
{
storeSettingsCookie = new HttpCookie("StoreSettings");
storeSettingsCookie["ThemeLocation"] = "~/Content/jquery-ui-1.8.9.custom.css";
storeSettingsCookie["StoreName"] = "";
storeSettingsCookie["Address1"] = "";
Response.Cookies.Add(storeSettingsCookie);
}
}
}
}
catch
{
}
%>
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
|
<%: string.IsNullOrEmpty(storeSettingsCookie["StoreName"]) ? "My Store Name" : storeSettingsCookie["StoreName"] %>
</title>
... <%-- Css/JS --%>
</head>
Any suggestions are appreciated. I expect a lot of sighs from the MVC guys. I know this isn't how MVC is supposed to work, so please refrain from reminding me of that, haha. :)
edit
Okay, so following LukLed's advice, I've created a base controller class, stuck the code above in its constructor and had my controllers inherit it. This appears like it is going to work, however the User object is null. How should I work around this? Here's what I've got:
public BaseController()
{
var resellerRepository = new ResellerRepository();
var reseller = resellerRepository.GetResellerByUsername(User.Identity.Name);
if (reseller.StoreSettingsID != null && reseller.StoreSetting.Theme != null)
{
var storeSettingsRepository = new StoreSettingsRepository();
var storeSettings = storeSettingsRepository.GetStoreSettings((int)reseller.StoreSettingsID);
ViewData["HeaderImage"] = storeSettings.Image1.FileName;
ViewData["FooterImage"] = storeSettings.Image.FileName;
ViewData["ThemeLocation"] = storeSettings.Theme.StylesheetLocation;
ViewData["StoreName"] = storeSettings.StoreName;
ViewData["Address1"] = storeSettings.Address1;
ViewData["Address2"] = storeSettings.Address2;
ViewData["City"] = storeSettings.City;
ViewData["PostalCode"] = storeSettings.PostalCode;
ViewData["ProvinceCode"] = storeSettings.Province.Abbreviation;
ViewData["Phone"] = storeSettings.Phone;
}
else
{
ViewData["ThemeLocation"] = "~/Content/jquery-ui-1.8.9.custom.css";
ViewData["StoreName"] = "";
ViewData["Address1"] = "";
}
}
The reseller must be logged on in order to view the store.
edit
So here is where I am at after following Darins advice - I upgraded to MVC3 and used a GlobalActionFilter, which is executing after EVERY action called. How do I prevent this - because it executes 4-5 times. Also - the viewdata is null every time. What am I doing wrong?
Here is my action filter (I didn't use Automapper from Darin's example because StoreSettings doesn't translate directly to StoreSettingsViewModel, and I wanted to see this working, first)
public class StoreSettingsActionFilter : ActionFilterAttribute
{
private readonly IResellerRepository _resellerRepository;
private readonly IStoreSettingsRepository _storeSettingsRepository;
public StoreSettingsActionFilter(
IResellerRepository resellerRepository,
IStoreSettingsRepository storeSettingsRepository
)
{
_resellerRepository = resellerRepository;
_storeSettingsRepository = storeSettingsRepository;
}
public StoreSettingsActionFilter()
: this(new ResellerRepository(), new StoreSettingsRepository())
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
var settingsViewModel = new StoreSettingsViewModel();
settingsViewModel.ThemeLocation = "~/Content/jquery-ui-1.8.9.custom.css";
var user = filterContext.HttpContext.User;
if (!user.Identity.IsAuthenticated || !user.IsInRole("Reseller"))
{
filterContext.Controller.ViewData["storeSettings"] = settingsViewModel;
return;
}
var session = filterContext.HttpContext.Session;
var reseller = session["reseller"] as Reseller;
if (reseller == null)
{
reseller = _resellerRepository.GetResellerByUsername(user.Identity.Name);
session["reseller"] = reseller;
}
if (reseller.StoreSettingsID != null && reseller.StoreSetting.Theme != null)
{
var storeSettings = session["storeSettings"] as StoreSettings;
if (storeSettings == null)
{
storeSettings = _storeSettingsRepository.GetStoreSettings((int)reseller.StoreSettingsID);
session["storeSettings"] = storeSettings;
}
// Using AutoMapper to convert between the model and the view model
//settingsViewModel = Mapper.Map<StoreSettings, StoreSettingsViewModel>(storeSettings);
settingsViewModel.ThemeLocation = storeSettings.Theme.StylesheetLocation;
settingsViewModel.Address1 = storeSettings.Address1;
settingsViewModel.Address2 = storeSettings.Address2;
settingsViewModel.City = storeSettings.City;
settingsViewModel.FooterImage = storeSettings.Image.FileName;
settingsViewModel.HeaderImage = storeSettings.Image1.FileName;
settingsViewModel.Phone = storeSettings.Phone;
settingsViewModel.PostalCode = storeSettings.PostalCode;
settingsViewModel.ProvinceCode = storeSettings.Province.Abbreviation;
settingsViewModel.StoreName = storeSettings.StoreName;
}
filterContext.Controller.ViewData["storeSettings"] = settingsViewModel;
}
}
Here is where i register the global action filter
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//Register the global action filter
GlobalFilters.Filters.Add(new StoreSettingsActionFilter());
//RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
I would use an action filter that will inject the store settings on each request. The view model could look like this:
public class StoreSettingsViewModel
{
public string HeaderImage { get; set; }
public string FooterImage { get; set; }
public string ThemeLocation { get; set; }
public string StoreName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string ProvinceCode { get; set; }
public string Phone { get; set; }
}
And the action filter:
public class StoreSettingsActionFilter : ActionFilterAttribute
{
private readonly IResellerRepository _resellerRepository;
private readonly IStoreSettingsRepository _storeSettingsRepository;
public StoreSettingsActionFilter(
IResellerRepository resellerRepository,
IStoreSettingsRepository storeSettingsRepository
)
{
_resellerRepository = resellerRepository;
_storeSettingsRepository = storeSettingsRepository;
}
public StoreSettingsActionFilter()
: this(new ResellerRepository(), new StoreSettingsRepository())
{ }
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
var settingsViewModel = new StoreSettingsViewModel();
settingsViewModel.ThemeLocation = "~/Content/jquery-ui-1.8.9.custom.css";
var user = filterContext.HttpContext.User;
if (!user.Identity.IsAuthenticated || !user.IsInRole("Reseller"))
{
filterContext.Controller.ViewData["storeSettings"] = settingsViewModel;
return;
}
var session = filterContext.HttpContext;
var reseller = session["reseller"] as Reseller;
if (reseller == null)
{
reseller = _resellerRepository.GetResellerByUsername(user.Identity.Name);
session["reseller"] = reseller;
}
if (reseller.StoreSettingsID != null && reseller.StoreSetting.Theme != null)
{
var storeSettings = session["storeSettings"] as StoreSettings;
if (storeSettings == null)
{
storeSettings = _storeSettingsRepository.GetStoreSettings((int)reseller.StoreSettingsID);
session["storeSettings"] = storeSettings;
}
// Using AutoMapper to convert between the model and the view model
settingsViewModel = Mapper.Map<StoreSettings, StoreSettingsViewModel>(storeSettings);
}
filterContext.Controller.ViewData["storeSettings"] = settingsViewModel;
}
}
Now we need to apply this attribute on the base controller so that it is executed for each action:
[StoreSettings]
public abstract class BaseController : Controller
{
}
If you are using ASP.NET MVC 3 you could have a global action filter.
And finally inside the master page you would have access to the store settings:
<%
var storeSettings = (StoreSettingsViewModel)ViewData["storeSettings"];
%>
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
<%: storeSettings.StoreName ?? "My Store Name" %>
</title>
<%-- Css/JS --%>
...

Resources