Can't get profile data in Application_Start - asp.net

I have the following code at some point in Application_Start
MembershipUserCollection users = Membership.GetAllUsers();
foreach (MembershipUser u in users)
{
ProfileBase profile = ProfileBase.Create(u.UserName, false);
if (profile["Index"] != null)
{
// Some code
}
}
The problem is that when i try to access the profile properties I get "Request is not available in this context" httpException. I have tried using profile.GetPropertyValue but no luck also.
Why does profile need the request object and how can I get this to work?
EDIT:
I have looked into the .NET code and found that at some point SqlProfileProvider.GetPropertyValuesFromDatabase(string userName, SettingsPropertyValueCollection svc) is called, inside of which rests this string of code:
if (!current.Request.IsAuthenticated)
Apparently this will never work if not in request context. The workaround descripbed in Onur's answer will work fine.

Apparently you are trying to access request object which is not possible in your case.
Please take a look following link and apply one of workarounds if possible.
http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart
and if you give more information what are you trying to achieve we can find another way.

You could get the "string value" properties by querying the aspnet_Profiles table and parsing the string.
SELECT [UserName]
,[PropertyNames]
,[PropertyValuesString]
FROM [aspnet_Profile]
LEFT JOIN [aspnet_Users] on [aspnet_Users].UserId = [aspnet_Profile].UserId
The PropertyValuesString can be parsed with a bit of code. This link should explain the format in detail https://msdn.microsoft.com/en-us/library/aa478953.aspx#persistence_format.

Related

Adding an Event for Espresso on Wordpress from C#

Working with WordPress and the Espresso Plugin for Events. I've never dealt with WP or Plugin's before, so I'm in new territory.
I am attempting to add an event and I keep getting the following error:
{"code":"rest_cannot_create_events","message":"Sorry, you are not allowed to create events. Missing permissions: ee_edit_events,ee_edit_others_events,ee_edit_private_events","data":{"status":403}}
I've gone into the WP admin pages and made sure the user I am trying to login as has all the permissions for this plugin.
The first thing I do is access the /wp-login.php page to get the Cookies:
string formVars = "";
string result = "";
string eventUrl = $"<url>/wp-login.php";
Dictionary<string, string> headers = new Dictionary<string, string>();
formVars = $"log={UserName}&pwd={Password}";
Cookie = new System.Net.CookieContainer();
AllowAutoRedirect = false;
result = PerformPost(eventUrl, formVars, true, headers);
The PerformPost uses an HttpWebRequest to send and receive.
That part seems to work and I get what looks like valid cookies.
I then do another post to /wp-json/ee/v4.8.29/events/ and pass in the body just the name of the event like EVT_name=TestEvent.
It's at this point that I get the the error mentioned above.
So a couple of questions.
1) Has anyone done this before? (Added an Event to Espresso on WordPress)
2) If Espresso doesn't like what I am feeding it, does it generate this error rather than just telling me I'm not giving it the correct information?
I've also tried using the Basic Auth plugin with the same results.
Any help is greatly appreciated.

Firebase and Angularfire nightmare migration for Update

I am new to firebase and I am having a bit of a nightmare trying to adapt old code to what is now deprecated and what is not. I am trying to write a function which updates one "single" record in my datasource using the now approved $save()promise but it is doing some really strange stuff to my data source.
My function (should) enables you to modify a single record then update the posts json array. However, instead of doing this, it deletes the whole datasource on the firebase server and it is lucky that I am only working with testdata at this point because everything would be gone.
$scope.update = function() {
var fb = new Firebase("https://mysource.firebaseio.com/Articles/" + $scope.postToUpdate.$id);
var article = $firebaseObject(ref);
article.$save({
Title: $scope.postToUpdate.Title,
Body: $scope.postToUpdate.Body
}).then(function(ref) {
$('#editModal').modal('hide');
console.log($scope.postToUpdate);
}, function(error) {
console.log("Error:", error);
});
}
Funnily enough I then get a warning in the console "after" I click the button:
Storing data using array indices in Firebase can result in unexpected behavior. See https://www.firebase.com/docs/web/guide/understanding-data.html#section-arrays-in-firebase for more information. Also note that you probably wanted $firebaseArray and not $firebaseObject.
(No shit?) I am assuming here that $save() is not the right call, so what is the equivalent of $routeParams/$firebase $update()to do a simple binding of the modified data and my source? I have been spending hours on this and really don't know what is the right solution.
Unless there's additional code that you've left out, your article $firebaseObject should most likely use the fb variable you created just before it.
var article = $firebaseObject(fb);
Additionally, the way in which you're using $save() is incorrect. You need to modify the properties on the $firebaseObject directly and then call $save() with no arguments. See the docs for more.
article.Title = $scope.postToUpdate.Title;
article.Body = $scope.postToUpdate.Body;
article.$save().then(...

How to get inserted row ID with WebMatrix

There is a GetLastInsertId method in WebMatrix. However, using Reflector, I can see that it's implemented like this:
[return: Dynamic]
public object GetLastInsertId()
{
return this.QueryValue("SELECT ##Identity", new object[0]);
}
Which, as far as I can see, is a very bad way of doing it, because ##Identity returns the last insert considering every table and every session. I need this restricted to the scope and session I'm working with, so I was expecting this to use SELECT SCOPE_IDENTITY(), since that also seems to be what is most often used according to my reading.
My questions are:
Do the WebMatrix wrappers do something that makes this ok to use in my case?
If not, is there a simple way to get the inserted ID of an insert query using WebMatrix classes, or should I fall back on stuff like SqlClient for this?
I am interested in answers for SQL Server (not compact) if that makes a difference.
I had the same problem, and I read these answers but still couldn't get the code to work correctly. I possibly was misreading the solutions above, but what seemed to work for me was as follows:
var db=Database.Open(...);
var lastInsertID = db.QueryValue("INSERT name into Names; SELECT SCOPE_IDENTITY()");
To quote David Fowler, one of the devs on the Data APIs in WebMatrix: "[SCOPE_IDENITTY] doesn't work on ce". Since we wanted a data API that would work on both CE and regular SQL Server, we used ##Identity. So if you want to use SCOPE_IDENTITY specifically, you should use db.QueryValue method:
var db = Database.Open(...);
db.Insert(...);
var lastInsertId = db.QueryValue("SELECT SCOPE_IDENTITY()")
here is my solution
var db.Database.open('..');
var lastId = db.GetLastInsertId();

Programicatlly visit (all) ASP.Net page(s) in a website?

In the Security model for out ASP.Net website (.Net 3.5) we store the page name:
page.GetType().Name
as the primary key in a database table to be able to lookup if a user has access to a certain page. The first time a page is visited this record is created automatically in the database.
We have exported these database statements to insert scripts, but each time a new page gets created we have to update the scripts, not a huge issue, but I would like to find an automated way to do this.
I created an attribute that I tagged a few pages with and then wrote a small process to get all the objects that have this attribute, through the reflection create an instance and insert the record using the same code to for page records mentioned above:
IEnumerable<Type> viewsecurityPages = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsDefined(typeof(ViewSecurityAttribute),false));
foreach (Type t in viewsecurityPages)
{
object obj = Activator.CreateInstance(t, false);
//clip..(This code just checks if the record already exists in the DB)
if (feature == null)
{
Attribute attb = Attribute.GetCustomAttribute(t, typeof(ViewSecurityAttribute));
if (attb != null)
{
CreateSecurableFeatureForPage((Page)obj, uow, attb.ToString());
}
}
}
The issue is that page.GetType().Name when the page goes through the actual page cycle process is something like this:
search_accounts_aspx
but when I used the activator method above it returns:
Accounts
So the records don't match the in the security table. Is there anyway to programtically "visit" a webpage so that it goes through the actual page lifecycle and I would get back the correct value from the Name parameter?
Any help/reference will be greatly appreciated.
Interesting problem...
Of course there's a (too obvious?) way to programmatically visit the page... use System.Net.HttpWebRequest. Of course, that requires the URI and not just a handle to the object. This is a "how do we get there from here?" problem.
My suggestions would be to simply create another attribute (or use that same one) which stores the identifier you need. Then it will be the same either way you access it, right?
Alternatively... why not just use a 3rd party web spider/crawler to crawl your site and hit all the pages? There are several free options. Or am I missing something?

Drupal node.save and JSONP

I am having an issue with call Drupal node.save using MooTool's JSONP. Here is an example.
Here is my request:
callback Request.JSONP.request_map.request_1
method node.save
sessid 123123123123123
node {"type":"blog","title":"New Title","body":"This is the blog body"}
Here is my result
HTTP/1.0 500 Internal Server Error
I got this working before, but i used AMFPHP and was able to send objects to drupal. I am assuming that this has to do with Drupal expecting an object, but since it is a GET it gets transformed as a string. Is there any way of getting around this with out hacking the code?
Here is my code:
$('newBlogSubmit').addEvent('click', function()
{
var node = {
type : "blog",
title:"New Title",
body :"This is the blog body"
}
var string = JSON.encode(node);
string.escapeRegExp()
var sessID = _sessID;
DrupalService.getInstance().node_save(string, sessID, drupal_handleBlogSubmit);
});
My Drupal Service JS Code:
//NODE
DrupalService.prototype.node_save = function(node, sessid, callback){
var dataObj = {
method : "node.save",
sessid : sessid,
node : node
}
DrupalService.getInstance().request(dataObj, callback);
}
//SEND REQUEST AND CALLBACK FUNCTION
DrupalService.prototype.request = function(dataObject, callback){
new JsonP('http://myDrupalSite.com/services/json', {data: dataObject,onComplete: callback}).request();
}
I am trying to connect the dots, but not too familiar with Drupal, but i would guess all I need to do is turn the string back into an object. Any ideas where I should be looking, or if there is an existing patch?
A first question could be why you use mootools since Drupal comes with jQuery and use it extensively throughout the different modules and Drupal core itself.
Anyways I don't know mootools so can't help you there, but if your request in ending in a internal server error, you have a problem with your drupal code or your js code. So even if I knew exactly what you were doing, I couldn't tell you the problem without looking at the drupal code for your http://myDrupalSite.com/services/json callback.
In general, what you want to make sure is:
You make a POST request, as drupal will cache get's and the semantic of this, is that you are posting data - the node - to the server.
Your data should be sent as post params, this will make them end up in the PHP $_POST variable
Your callback should validate the data and act accordingly, creating a node when the data is intact. You don't need session id's since the script will have the same session the browser has.
I've answered a similar question in detail, which was about altering a field instead of saving a node, but much of the work is still the same. You can take a look on the post, although this is with jQuery and not Mootools.

Resources