ASP.NET MVC 4 Custom Action filters with dynamic data - asp.net

So I am building a web application that I want to sell once Im done with it. It allows the user to enter data such as their website name, meta keywords, their contact email, phone, address etc in the admin panel. I wrote a Action Filter in order to include these values in every request that I put the filter on so I didnt have to query for them every time because these values are included in the common footer throughout the site. However, I learned that if I update the database with new or different information for these values, it does not update on the web pages which im guessing is because Action Filters are configured at application start up. In the Action Filter I am using a repository pattern to query for these values. I have included the code for the action filter below. How can I have the convenience of the Action Filter but be able to update it dynamically when the data changes in the database? Thanks!
public class ViewBagActionFilter : ActionFilterAttribute,IActionFilter
{
Repositories.SettingsRepository _repo = new Repositories.SettingsRepository();
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
string siteName = _repo.GetSiteName();
string siteDesc = _repo.GetSiteDescription();
string siteKeywords = _repo.GetSiteKeywords();
string googleAnalytics = _repo.GetGoogleAnalytics();
string streetAddress = _repo.GetStreetAddress();
string zipCode = _repo.GetZipCode();
string city = _repo.GetCity();
string state = _repo.GetState();
string aboutUs = _repo.GetAboutUs();
string phone = _repo.GetPhoneNumber();
string contactEmail = _repo.GetContactEmail();
if (!string.IsNullOrWhiteSpace(siteName) && siteName.Length > 0)
{
string[] splitSiteName = new string[siteName.Length/2];
splitSiteName = siteName.Split(' ');
if (splitSiteName.Length > 1)
{
filterContext.Controller.ViewBag.SiteName1 = splitSiteName[0];
filterContext.Controller.ViewBag.SiteName2 = splitSiteName[1];
}
else
{
filterContext.Controller.ViewBag.SiteName1 = splitSiteName[0];
filterContext.Controller.ViewBag.SiteName2 = "";
}
}
//Set default values for common viewbag items that are on every page using ternary syntax
filterContext.Controller.ViewBag.SiteDescription = (!string.IsNullOrWhiteSpace(siteDesc) && siteDesc.Length > 0) ? siteDesc : "";
filterContext.Controller.ViewBag.SiteKeywords = (!string.IsNullOrWhiteSpace(siteKeywords) && siteKeywords.Length > 0) ? siteKeywords : "";
filterContext.Controller.ViewBag.GoogleAnalytics = (!string.IsNullOrWhiteSpace(googleAnalytics) && googleAnalytics.Length > 0) ? googleAnalytics : "";
filterContext.Controller.ViewBag.StreetAddress = (!string.IsNullOrWhiteSpace(streetAddress) && streetAddress.Length > 0) ? streetAddress : "";
filterContext.Controller.ViewBag.ZipCode = (!string.IsNullOrWhiteSpace(zipCode) && zipCode.Length > 0) ? zipCode : "";
filterContext.Controller.ViewBag.City = (!string.IsNullOrWhiteSpace(city) && city.Length > 0) ? city : "";
filterContext.Controller.ViewBag.State = (!string.IsNullOrWhiteSpace(state) && state.Length > 0) ? state : "";
filterContext.Controller.ViewBag.AboutUs = (!string.IsNullOrWhiteSpace(aboutUs) && aboutUs.Length > 0) ? aboutUs : "";
filterContext.Controller.ViewBag.PhoneNumber = (!string.IsNullOrWhiteSpace(phone) && phone.Length > 0) ? phone : "";
filterContext.Controller.ViewBag.ContactEmail = (!string.IsNullOrWhiteSpace(contactEmail) && contactEmail.Length > 0) ? contactEmail : "";
base.OnActionExecuting(filterContext);
}
}

I will try to explain how action filters works.
So if you extend Action filter you can override 4 base methods :
OnActionExecuting – This method is called before a controller action is executed.
OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.
So thats mean that you method will be called each time before Controller will run action.
Now about optimization. You have
string siteName = _repo.GetSiteName();
string siteDesc = _repo.GetSiteDescription();
string siteKeywords = _repo.GetSiteKeywords();
string googleAnalytics = _repo.GetGoogleAnalytics();
string streetAddress = _repo.GetStreetAddress();
string zipCode = _repo.GetZipCode();
string city = _repo.GetCity();
string state = _repo.GetState();
string aboutUs = _repo.GetAboutUs();
string phone = _repo.GetPhoneNumber();
string contactEmail = _repo.GetContactEmail();
I would suggest you to create one class
public class Site{
public string SiteName{get;set;}
public string City{get;set;}
//And so on just to add all properties
}
then in repository add one more method
_repo.GetSite(); //Which will return object Site
Then
filterContext.Controller.ViewBag.CurrentSite = _repo.GetSite();
And now probably the most important for you. Why it doesnot work as you want and its a bit simple. Attribute class is initialized only once on Application start and after that it doesnot reloads, and your implementation is a bit strange since
Repositories.SettingsRepository _repo = new Repositories.SettingsRepository();
I suppose here you are loading settings. So after you load you did not reload it anymore... thats mean you will get same result each time you reload page, but if you restart iis for instance you will refresh data.
Possible solution
Move initialization of _repo to OnActionExecuting then it will reload data each time, or rewrite repository as i suggested and
filterContext.Controller.ViewBag.CurrentSite = _repo.GetSite();
Should always load new data from db.
Hope it helps :)

Related

How to identify that user send same querystring more than once in url

Here is my sample website page.I am giving this url(Api) to others :
http://localhost:someport/Test.aspx?name=pinky&SId=123&PhoneNo=XXXX
In this page I am accessing the query string like this
if (Request.QueryString["name"] != null)
{
Name = Request.QueryString["name"].ToString();
}
Others can make request/call my page from their software.Some time they can pass same query string more than twice.Like this
http://localhost:someport/Test.aspx?name=pinky&SId=123&PhoneNo=XXXX&SId=43
In my page
String SId = "";
if (Request.QueryString["SId"] != null)
{
SId= Request.QueryString["SId"].ToString();
}
SId= "123,43";
If SId come like this entire my logic changes/fails.I don't want like this.If
Same query string come more than one, should show message.
How to identify if query string present more than once
If user passes name=pinky&rani, my page picks up only pinky
How to handle both?
Why you don't use String.Split ?
Try this:
if (Request.QueryString["SId"] != null)
{
var SIds = Request.QueryString["SId"].ToString().Split(',');
if(SIds.Count()>1)
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('SIds come more than one!')", true);
else
SId = SIds[0];
}
With the help of below code,I am able to find out ,how many time same querystring is passed
string productID = null;
foreach (string productID_loopVariable in Request.QueryString.GetValues("Password"))
{
productID = productID_loopVariable;
// do something with productID
}

The localhost page isn’t working. localhost redirected you too many times

I got a problem when debugging my MVC program and I want to acces to my db called "UserActivity".
on the browser, it saying that "The localhost page isn’t working
localhost redirected you too many times."
but without showing the specific error location.
here is my UserActivtyController, GET /UserActivity/Index code:
public class UserActivityController : BaseController
{
//GET /UserActivity/Index
public ActionResult Index(string returnUrl, int page = 1, string sort = "Id", string sortDir = "ASC", string filter = null)
{
String query = #"
SELECT Id
,CreatedBy
,CreatedOn
,ModifiedBy
,ModifiedOn
,ContactId
,EntityName
,EntityId
,ActivityType
,ActivityStatus
,DueDate
,ActualEndDate
,MasqueradeOn
,MasqueradeBy
FROM UserActivity
-- ORDER BY CreatedOn DESC
-- OFFSET (#PageNumber -1) * 30 ROWS
-- FETCH NEXT 30 ROWS ONLY
";
//string countQuery = #""
List<UserActivityModels> userActivity = null;
using (IDbConnection db = new MySqlConnection(ConfigurationManager.ConnectionStrings["CRMPORTALSQLCONN"].ConnectionString))
{
userActivity = (List<UserActivityModels>)db.Query<UserActivityModels>(query, new
{
#PageNumber = page,
});
/*ViewData["TotalCount"] = (int)db.ExecuteScalar(countQuery, new
{
#PageNumber = page,
#Id = string.IsNullOrEmpty(filter) ? null : filter
});
*/
ViewData["PageSize"] = 30;
ViewData["Filter"] = filter;
}
if (userActivity != null)
{
return RedirectToAction(returnUrl);
}
return View(userActivity);
}
}
Really appreciate if there anyone who know something about this problem. Thanks
if (userActivity != null)
{
return RedirectToAction(returnUrl);
}
If the returnUrl points to the same action ("UserActivity/Index") it will create infinite redirect loop. If you want to redirect request to different action make sure you pass correct name.
You have a loop back situation. This is similar to endless while loop. To fix it change your code redirection implementation to redirect to an action method. Notice how I have changed the implementation below. This will fix the issue "localhost redirected you too many times". You can improve on it to support passing in parameters, etc suitable for your situation. Also take a look at RedirectToAction with support for additional parameters, if you want to pass parameters to the action method, this link will be useful.
public class UserActivityController : BaseController
{
//GET /UserActivity/Index
public ActionResult Index(int page = 1, string sort = "Id", string sortDir = "ASC", string filter = null)
{
// Your other implementation here. I have removed it for brevity.
if (userActivity != null)
{
return RedirectToAction("Index");
}
return View(userActivity);
}
public ActionResult Index()
{
return View();
}
}
I don't know what is the value of redirectUrl but I suppose it to be null. I also suppose that your userActivity is not null. So return RedirectToAction(returnUrl); gets called.
When you call RedirectToAction(null) you actually redirect to the same action and everything repeats again.
I also am wondering why would you need to return View(userActivity); when your userActivity is null. I suppose you have a logical error.

DevExpress XtraScheduler hanging on adding appointment to Storage

I have a XtraScheduler SchedulerControl configured as the following:
private DevExpress.XtraScheduler.SchedulerControl _SchedulerControl;
public DevExpress.XtraScheduler.SchedulerControl ConvSchedulerControl
{
get
{
if (_SchedulerControl == null)
{
_SchedulerControl = new DevExpress.XtraScheduler.SchedulerControl();
_SchedulerControl.Storage = new SchedulerStorage();
_SchedulerControl.Storage.Appointments.Mappings.Subject = "StandingOrderIDString";
_SchedulerControl.Storage.Appointments.Mappings.Start = "ScheduledDate";
_SchedulerControl.Storage.Appointments.Mappings.RecurrenceInfo = "RecurrenceInfo";
_SchedulerControl.Storage.Appointments.Mappings.Type = "Type";
_SchedulerControl.Storage.Appointments.CustomFieldMappings.Add(new DevExpress.XtraScheduler.AppointmentCustomFieldMapping("Inactive", "Inactive"));
_SchedulerControl.Storage.Appointments.CustomFieldMappings.Add(new DevExpress.XtraScheduler.AppointmentCustomFieldMapping("StandingOrderKEY", "StandingOrderKEY"));
BindingSource bs = new BindingSource();
bs.DataSource = new List<StandingOrder>();
_SchedulerControl.Storage.Appointments.DataSource = bs;
}
return _SchedulerControl;
}
}
and I am attempting to programmatically add an appointment with recurrence information, as in the examples given at http://help.devexpress.com/#WindowsForms/CustomDocument6201 . However, when the method execution reaches its final line (indicated) that adds the created appointment to the storage, it "hangs." No exception is ever thrown; I have left it running for upwards of 15 minutes with no change:
public void SetRecurrence(DateTime startDate, DateTime? endDate)
{
Appointment appointmentObj = ConvSchedulerControl.Storage.CreateAppointment(AppointmentType.Pattern);
if (endDate != null &&
endDate != DateTime.Parse("12/31/2999"))
{
appointmentObj.End = (DateTime)endDate;
}
else
{
appointmentObj.RecurrenceInfo.Range = RecurrenceRange.NoEndDate;
}
appointmentObj.Start = startDate;
appointmentObj.RecurrenceInfo.Type = RecurrenceType.Weekly;
appointmentObj.RecurrenceInfo.WeekDays = WeekDays.Monday;
appointmentObj.AllDay = true;
//Program execution reaches this line, but never proceeds past it.
ConvSchedulerControl.Storage.Appointments.Add(appointmentObj);
}
I would imagine that there's something wrong with the configuration that's preventing the storage from being able to successfully add the appointment, but I've been unable to turn up any other information on the subject. Does anyone know why this method isn't appropriate for adding an appointment to the storage, and how it can be corrected?
You've failed to provide a mapping for the 'End' field. This is a required mapping. Honestly, I only know this from having created a calendar in the designer. When you place a SchedulerControl onto a form/control, one of the things the designer gives you is a "Mappings Wizard". The 'Start' and 'End' fields are marked in the wizard as being required.

How to get Publication WebDAV URL in C# .NET

I am trying to get my publication WebDAV url and below is the logic which I am trying, I am succesfully getting the webdavurl of page and component, however struggling to get publication url.
public static string getPublicationWebDav(string partialWebdavURL, Package package, Engine engine)
{
string webDav = string.Empty;
string pubURI = string.Empty;
if (!string.IsNullOrEmpty(partialWebdavURL))
{
_log.Info("partialWebdavURL" + partialWebdavURL);
RepositoryLocalObject repLocalObject = null;
if (repLocalObject == null)
{
Item pubItem = package.GetByType(ContentType.Publication);
repLocalObject = (Publication)engine.GetObject(pubItem.GetAsSource().GetValue("ID"));
}
webDav = repLocalObject.WebDavUrl + partialWebdavURL;
}
_log.Info("webDav" + webDav);
return webDav;
}
this line give me error
repLocalObject = (Publication)engine.GetObject(pubItem.GetAsSource().GetValue("ID"));
However when I am trying to get the page object is working fine, below code works fine.
if (package.GetByType(ContentType.Page) != null)
{
Item pageItem = package.GetByType(ContentType.Page);
//_log.Info("pageItem" + pageItem);
repLocalObject = (Page)engine.GetObject(pageItem.GetAsSource().GetValue("ID"));
pubURI = package.GetValue("Page.Publication.ID");
}
else
{
Item component = package.GetByType(ContentType.Component);
repLocalObject = (Component)engine.GetObject(component.GetAsSource().GetValue("ID"));
pubURI = package.GetValue("Component.Publication.ID");
}
My objective is to get Publication webdavURL.
After long search in tridion forums, I have found below solution. Thanks to Nuno!!
// First we have to find the current object we're rendering
RepositoryLocalObject context;
if (p.GetByName(Package.PageName) != null)
context = e.GetObject(p.GetByName(Package.PageName)) as RepositoryLocalObject;
else
context = e.GetObject(p.GetByName(Package.ComponentName)) as RepositoryLocalObject;
Repository contextPublication = context.ContextRepository;
string webdavUrl = contextPublication.WebDavUrl;
Note that the following code will work on 2011 but not on 2009 (WebDavUrl of repository is not exposed). In 2009 I get the contextPublication.RootFolder.WebDavUrl instead.

How do I get an already (basic) authenticated context to call a web service behind the same authentication?

I have a site behind basic authentication (IIS6).
Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.
However, when this happens the calling code receives a 401 Authentication Error.
I've tried a couple of things, with the general recommendation being code like this:
Service.ServiceName s = new Service.ServiceName();
s.PreAuthenticate = true;
s.Credentials = System.Net.CredentialCache.DefaultCredentials;
s.Method("Test");
However, this does not seem to resolve my problem.
Any advice?
Edit
This seems to be a not uncommon issue but so far I have found no solutions.
Here is one thread on the topic.
Solution: (I am almost certain this will help someone)
See this link for the source of this solution in VB (thanks jshardy!), all I did was convert to C#.
NB: You must be using ONLY basic authentication on IIS for this to work, but it can probably be adapted. You also need to pass a Page instance in, or at least the Request.ServerVariables property (or use 'this' if called from a Page code-behind directly). I'd tidy this up and probably remove the use of references but this is a faithful translation of the original solution and you can make any amendments necessary.
public static void ServiceCall(Page p)
{
LocalServices.ServiceName s = new LocalServices.ServiceName();
s.PreAuthenticate = true; /* Not sure if required */
string username = "";
string password = "";
string domain = "";
GetBasicCredentials(p, ref username, ref password, ref domain);
s.Credentials = new NetworkCredential(username, password, domain);
s.ServiceMethod();
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void GetBasicCredentials(Page p, ref string rstrUser, ref string rstrPassword, ref string rstrDomain)
{
if (p == null)
{
return;
}
rstrUser = "";
rstrPassword = "";
rstrDomain = "";
rstrUser = p.Request.ServerVariables["AUTH_USER"];
rstrPassword = p.Request.ServerVariables["AUTH_PASSWORD"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
/* MSDN KB article 835388
BUG: The Request.ServerVariables("AUTH_PASSWORD") object does not display certain characters from an ASPX page */
string lstrHeader = p.Request.ServerVariables["HTTP_AUTHORIZATION"];
if (!string.IsNullOrEmpty(lstrHeader) && lstrHeader.StartsWith("Basic"))
{
string lstrTicket = lstrHeader.Substring(6);
lstrTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(lstrTicket));
rstrPassword = lstrTicket.Substring((lstrTicket.IndexOf(":") + 1));
}
/* At least on my XP Pro machine AUTH_USER is not set (probably because we're using Forms authentication
But if the password is set (either by AUTH_PASSWORD or HTTP_AUTHORIZATION)
then we can use LOGON_USER*/
if (string.IsNullOrEmpty(rstrUser) && !string.IsNullOrEmpty(rstrPassword))
{
rstrUser = p.Request.ServerVariables["LOGON_USER"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
}
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void SplitDomainUserName(string pstrDomainUserName, ref string rstrDomainName, ref string rstrUserName)
{
rstrDomainName = "";
rstrUserName = pstrDomainUserName;
int lnSlashPos = pstrDomainUserName.IndexOf("\\");
if (lnSlashPos > 0)
{
rstrDomainName = pstrDomainUserName.Substring(0, lnSlashPos);
rstrUserName = pstrDomainUserName.Substring(lnSlashPos + 1);
}
}
The Line:
s.Credentials = System.Net.CredentialCache.DefaultCredentials();
Maybe you should try :
s.Credentials = HttpContext.Current.User.Identity;

Resources