I want to read the patched attributes that are in Sitecore.ItemWebApi.config to determine whether the Sitecore Item API is enable in my site. This value I'm looking for is itemwebapi.mode, and I want to see whether it's set to 'Off' or not.
<site name="mysite">
<patch:attribute name="itemwebapi.mode">StandardSecurity</patch:attribute>
<patch:attribute name="itemwebapi.access">ReadOnly</patch:attribute>
<patch:attribute name="itemwebapi.allowanonymousaccess">false</patch:attribute>
</site>
I tried getting ConfigurationManager.AppSettings["itemwebapi.mode"] but it returns null. How do I get this value?
I think you need to use sitecore configuration factory to read the configuration stuff.
(http://sitecore-community.github.io/docs/documentation/Sitecore%20Fundamentals/Sitecore%20Configuration%20Factory/#config_factory)
Try as below. If not working experiment in similar way.
var refObj = Sitecore.Configuration.Factory.CreateObject("site/patch:attribute", true) as itemwebapi.mode;
If not useful, put a comment. I will delete it.
You can access the attributes on the site node using the Properties accessor,
if the attribute is not set then the value will be empty. For the current Context site:
string mode = Sitecore.Context.Site.Properties["itemwebapi.mode"];
string access = Sitecore.Context.Site.Properties["itemwebapi.access"];
string anon = Sitecore.Context.Site.Properties["itemwebapi.allowanonymousaccess"];
If you are checking within an ItemWebApi request (beginning with -/item/) then you can check the ItemWebApi.Context:
if (Sitecore.ItemWebApi.Context.Current != null)
{
Mode mode = Sitecore.ItemWebApi.Context.Current.Settings.Mode;
AccessType access = Sitecore.ItemWebApi.Context.Current.Settings.Access;
bool anon = Sitecore.ItemWebApi.Context.Current.Settings.AnonymousAcessAllowed;
}
This will give you strongly typed access to the settings using enums. Unfortunately the overloaded constructor for RuntimeSettings() is marked as internal so it is not possible to new this up yourself in a normal web request but could check the code and do something similar if you need.
Related
I have to do paging for an odata endpoint built using Entity Framework . I know I can do it using
private ODataQuerySettings settings = new ODataQuerySettings();
settings.PageSize = myPageSize; // I keep this value in web.config of solution
and
options.ApplyTo(IQueryable, settings);
But I am constrained not to use ApplyTo (i.e. I don't want to use the settings above) and take the page size from the web.config of my solution without modifying the url presented by the web api i.e. no client size paging.
So, far I haven't found a way to do this. I can't put page size in [ Enable Query ] as that is not dynamically lifting page size parameter from web.config.
I wonder if what I want could be done or am I trying to do something too tricky.
You can extend the default behavior of the EnableQuery attribute to use web.config's value as you want. Maybe something like this:
public class EnablePagedQueryAttribute : EnableQueryAttribute
{
public EnablePagedQueryAttribute()
{
int myPageSizeFromWebConfig = 0;
// Get value from web.config as you want:
if (int.TryParse(ConfigurationManager.AppSettings["myPageSize"], out myPageSizeFromWebConfig))
{
this.PageSize = myPageSizeFromWebConfig;
}
}
}
I'm writing an ASP.NET C# web site that needs to access data from a database and show it to the user for viewing and editing. The specific data it accesses is based on the user who logs in, and I need for multiple users to be able to use the site simultaneously, viewing and editing different data as they do so. I stumbled upon the concept of Session States, and after a lot of reading and not as much understanding. I've come across a problem.
In my default page, I do this to create a Session variable:
Session.Add("UserData",userdata);
I have also tried this:
Session["UserData"] = userdata;
Then in a later page, I do this to try to call it:
object myobject = Session["UserData"];
This gives me an error, saying that Session["UserData"] is not set to an instance of an object. This is the method everyone seems to be using, is there something I'm missing?
My site is configured on IIS to have the Session State Mode set to "In Process", but most people seem to set this manually using their web.config file. However, when I try to do this in my web.config file I am always greeted with "unrecognized configuration section". My compiler doesn't know what this is:
<sessionstate mode="inproc"/>
EDIT, more detailed code:
MyClass userdata = new MyClass();
userdata.name = "myname";
userdata.number = 5;
Session["UserData"] = userdata;
later...
MyClass mydata = (MyClass)(Session["UserData"]);
This returns the error that Session["UserData"] is null.
The fact that you can't set the session mode in the web.config is a red flag to me of something weird and smelly going on. So ...
Check that the session mode is under the system.web element of the web.config otherwise it won't be valid.
Check that enableSessionState hasn't been set to false in either the web.config or the page directive
Try to rule out IIS. If possible convert your website to a web app and run through visual studio so it starts with it's own built in web server. What happens then? Is the Session state back?
It should n't make a difference but if you are not doing the test in Page_Load then just try it there - just in case you are doing these tests somewhere unusual.
Whatever the answer is to this when we know it will be headachingly obvious. I'm geninuely looking forward to finding out what it is. Good luck
Session variables are good to manage multiple users on your website, but to initialize them you should use the Global.asax file in your web application. This file has two methods specifically for Session variables, Session_Start and Session_End. To initialize your Session variable you would use code liked the following in Global.asax:
void Session_Start(object sender, EventArgs e)
{
// initialize session variable
Session["MySessionVar"] = 1;
}
Also you may have to cast the value of your session variable if you are doing operations on it like +, for example if you have a session variable holding an integer value, you may have to do like the following:
Session["MySessionVar"] = ((int) Session["MySessionVar]) + 1;
Also, if you try to use your session variable outside of a method like Page_Load or other method, like trying to use it as a property of the System.Web.UI.Page class in your C# code behind file, that may not work, you can only use your session variables within a method.
I would search for any calls to Session.Clear or Session.Abandon to see if your session is being purged in between those two actions.
You could also hook up to the Session_End event and see if that gets hit sometime in between the two calls.
Where you have
Session.Add("UserData",userdata);
you want to check the value you need to cast the object with (string) like this
string userdata= (string)(Session["UserData"]);
you could then run a check to see
if(string.IsNullOrEmpty(userdata))
but not sure how you are initializing and assigning a a value to userdata
Does it complain the your myobject is null or that Session is null? When you try to retrieve the value you are doing this from the method of what class?
Yet another question - by any chance are you trying to access it in a parallel thread?
Most things that I've found about the .net AdWords API mention creating a bunch of settings for the application that will be used when you create an instance of the AdWordsUser class; however, I've had no luck with this. My user always ends up nil and no settings are being read even though I named them as indicated in the AdWordsAppConfig class.
AdWordsAppConfig appConfig = new AdWordsAppConfig();
appConfig.AdWordsApiServer = "https://adwords-sandbox.google.com";
appConfig.Email = "fname.lname#gmail.com";
appConfig.Password = "password";
appConfig.DeveloperToken = "fname.lname#gmail.com++USD";
AdWordsUser user = new AdWordsUser();
The AdWordsUser has an overloaded constructor that accepts a dictionary of strings containing configuration parameters but doesn't have on that accepts an AdWordsAppConfig object.
http://code.google.com/p/google-api-adwords-dotnet/source/browse/trunk/src/AdWords/Lib/AdWordsAppConfig.cs
According to the AdWordsAppConfig class the following is used to retreive the settings when you call the constructor; however, how do you create a section called "AdWordsApi" in the App.Config? I don't see that option in the settings editor.
ReadSettings((Hashtable) ConfigurationManager.GetSection("AdWordsApi"));
Any ideas on the proper way to set the configuration information and create the user instance that I need?
What Eric mentioned is the long-term solution, but if anyone is looking for a quick answer, this is how you do it:
AdWordsUser user = new AdWordsUser();
(user.Config as AdWordsAppConfig).Password = "XXXXX";
//TODO (Add more configuration settings here.
CampaignService campaignService = (CampaignService) user.GetService(AdWordsService.v201109.CampaignService);
//TODO (Add your code here to use the service.)
Cheers,
Anash
You may want to post this question on the official AdWords API forum, as it is monitored by the current maintainers of that library:
http://code.google.com/apis/adwords/forum.html
I have a logging class that, well, logs things. I would like to add the ability to automatically have the current page be logged with the messages.
Is there a way to get the information I'm looking for?
Thanks,
From your class you can use the HttpContext.Current property (in System.Web.dll). From there, you can create a chain of properties:
Request
Url and RawUrl
The underlying object is a Page object, so if you cast it to that, then use any object you would normally use from within a Page object, such as the Request property.
It's brittle and hard to test but you can use System.Web.HttpContext.Current which will give you a Request property which in turn has the RawUrl property.
public static class MyClass
{
public static string GetURL()
{
HttpRequest request = HttpContext.Current.Request;
string url = request.Url.ToString();
return url;
}
}
I tried to break it down a little :)
In the past I've also rolled my own logging classes and used Console.Writeln() but really there are a number of good logging options that already exist so why go there? I use NLog pretty much everywhere; it is extremely flexible with various log output destinations including console and file, lots of log format options, and is trivial to set up with versions targeting the various .net frameworks including compact. Running the installer will add NLog config file options to the Visual Studio Add New Item dialog. Using in your code is simple:
// declare in your class
private static Logger logger = LogManager.GetCurrentClassLogger();
...
// use in your code
logger.Debug(() => string.Format("Url: {0}", HttpContext.Current.Request.Url));
When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings?
Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls.
I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.
tvanfosson- Thanks for the help. (if I had the 15 points necessary I would vote you up)
From your link I was able to figure it out. It turns out the second parameter to the Initialize proceedure was the list of parameters from the provider and could be reached in the following way:
string configPath = "~/web.config";
Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
MembershipSection section = (MembershipSection)config.GetSection("system.web/membership");
ProviderSettingsCollection settings = section.Providers;
NameValueCollection membershipParams = settings[section.DefaultProvider].Parameters;
Initialize(section.DefaultProvider, membershipParams);
Not sure why you want to create a new one, but if you create it yourself, you'll need to read the web config and get the values yourself to pass to Initialize() as this is done outside the class. I'm sure, though, that there is already a section handler for this section so it should be just a matter of doing:
MembershipSection section = WebConfigurationManager.GetSection("membership");
Then find your provider and accessing its properties to construct the NameValueCollection. I don't think you will have to write any code to parse the configuration section.
Here is the MembershipSection documentation at MSDN. Drill down from there.
In any case you shouldn't create instance of MembershipProvider. It is creating and initializating by standard asp.net infrastructure. You can access to it by code like this one:
var customerMembership = Membership.Provider;