Passing data between a parent app and a virtual directory - c#

I have an application that runs as a child application in a virtual directory.
I want to pass a value from the parent application, but I believe that Session is keyed per application, and won't work.
To further complicate things, the parent application is WebForms, while the child is NVelocity MVC.
Does anyone know a trick that allows me to use some sort of Session type functionality between virtual applications?
EDIT: A webservice isn't really what I had in mind, all I need to do is pass the logged in users username to the child app. Besides, if calling a webservice back on the parent, I won't get the same session, so I won't know what user.

Sounds like web service is the way to go. You could do something like the following:
Have the WebForms app create some data in its database with a key of some kind associated to it.
Pass that key in the URL to the NVelocity MVC application.
Allow the NVMVC application to call a web service (REST,XML-RPC,SOAP,whatever) on the WebForms app using the key that was passed.
This will get around any kind of session keying or cookie-domain problem you may have and allow you to pass some nicely structured data.

You can do a server-side HTTP Request, it looks something like this in C#:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("/ASPSession.ASP?SessionVar=" + SessionVarName);
req.Headers.Add("Cookie: " + SessionCookieName + "=" + SessionCookieValue);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream receiveStream = resp.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
string response = readStream.ReadToEnd();
resp.Close();
readStream.Close();
return response;
On the ASP side, I just verify that the request only comes from localhost, to prevent XSS-style attacks, and then the response is just the value of the Session variable.
Finding the cookie is easy enough, Session cookies all have similar names, so just examine the cookies collection until you find the appropriate cookie. Note, this does only work if the cookies are valid on the entire domain, and not just on the subfolder your are on.

Store the data you need to share on a place where both applications can query it, with a key both applications know.
A database is something you can use,if you don't want a Web service.

Use a classic asp form on your page to pass using post, in child app pick up using request.form

Why could it not simply be passed as an encrypted query string?
The child app could decrypt it, validate it, and bob is your uncle.

Related

How to connect to Outpan.com API with C#?

I am working on a university project in which I need to get some product information out of the database of outpan.com into a string or an array of strings.
I am new to coding, that's why I am needing quite a lot of help still. Does anyone of you know how to send a request & get the answer from a c#-environment (Windows Form Application)?
The description on outpan itself (https://www.outpan.com/developers.php) says to send the call by using HTTPS in curl, but what does it practically mean? Do I need to install extra libraries?
I would be glad, if someone could help me with this problem or provide me with a tutorial on how to make these curl calls to a database starting from a c# environment.
If there are more information needed about my settings, let me know.
The Outpan API uses Basic HTTP auth, so all the request will need to have a header like:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
In the request. In order to do that with C#, you could do the following:
var request = (HttpWebRequest)WebRequest.Create("https://api.outpan.com/v1/products/0796435419035");
var encodedString = Convert.ToBase64String(Encoding.Default.GetBytes("-your-api-key-here-:"));
request.Headers["Authorization"] = "Basic " + encodedString;
var response = request.GetResponse();
For a full description of the header, check out the wiki page http://en.wikipedia.org/wiki/Basic_access_authentication. Note that the base64 encoded string can be in the form [username]:[password], but the outpan api docs ( https://www.outpan.com/developers.php ) write that they do not use the password part.
Also see: Forcing Basic Authentication in WebRequest for a nice method wrapper for this logic.

How to clear the cache of an asp.net application from another asp.net application on the same server?

Got a bit of an odd problem. Here goes:
I have two ASP.NET applications: A web app and a web service app.
Information arriving via the webservice effects data in the database used by the web app.
One particular bit of data controls items in a drop down menu - when the data is altered in the app it can call:
HttpContext.Current.Cache.Remove
but I now need to clear the cache in the web service as i can recieve messages which update that information.
Can anyone recommend a way of doing this?
Cache invalidation can be hard. Off the top of my head I can think of 3 solutions of varying complexity which may or may not work for you.
First, you could write a web service for the web app that the web service app calls to invalidate the cache. This is probably the hardest.
Second, you could have the web service app write a "dirty" flag in the database that the web app could check before it renders the drop down menu. This is the route I would go.
Third, you could simply stop caching that particular data.
You could have a web method whose sole purpose is to clear the cache.
var webRequest = HttpWebRequest.Create(clearCacheURL);
var webResponse = webRequest.GetResponse();
// receive the response and return it as function result
var sr = new System.IO.StreamReader(webResponse.GetResponseStream());
var result = sr.ReadToEnd();
Implement the cache with an expiry time.
Cache.Insert("DSN", connectionString, null,
DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration);
Cache.Insert Method
You can try SQL Dependency. It will trigger an event when the table you have subscribed has any changes.
https://www.codeproject.com/Articles/12335/Using-SqlDependency-for-data-change-events

Moodle and C# - Web Service Configuration

I'm currently stuck with quite a significant issue that i'm hoping someone may be able to shed some light on, regarding configuring an XML-RPC based web service to talk between my game based learning virtual world and a dedicated Moodle site
To the best of my knowledge, from following some sparse information on how to configure a Moodle web service, i've done the following steps:
Enabled Web Services
Enabled the XML-RPC protocol
Edited my admin role to allow use of the protocol and creation of a token for logging
in
Creation of a service for authenticated users which my admin has been added to
The moodle documentation sends you in a bit of a loop but from what I can see i've the check list covered
I'm now trying to plug this into the backend of my virtual world to populate my dynamic terrain engine with sets of topics,assignments etc based on what the user would have access to etc
My issue comes from the simple HttpWebRequest for retrieving the token for the user
I'm using the following method to return a string containing the token
public string GetToken(string uname,string pword)
{
byte[] buffer = Encoding.ASCII.GetBytes("username="+uname+"&password="+pword+"&service=reflex");
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url + "login/token.php?username=" + uname + "&password=" + pword + "&service=myservice");
WebReq.Method = WebRequestMethods.Http.Post;
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using(Stream PostData = WebReq.GetRequestStream())
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using(StreamReader reader = new StreamReader(WebResp.GetResponseStream()))
return token = reader.ReadToEnd();
}
When I debug this to validate the token is generated, it throws an error saying the web service is down, but to the best of my knowledge the web service isnt called here, this uses a built in primitive php file to return a string and no more. I have checked the PostData.Write and its throwing a .Length NotSupportedException which i'm unsure as to if its having an impact upon the second using statement
I'm hoping if someone can aid regarding configuration settings that the next steps should fall into place easily as the XML-RPC dll seems quite robust and easy to use
Any help would be greatly appreciated
Many thanks
Barry
Now resolved
Worked around to retrieve the token manually through a sql call and have the web service functioning now
If you have a look in the table mdl_external_services there is a field called short name, which is likely null as you can't seem to populate it through the moodle UI. It's this value that needs to be used as the service parameter rather than the service name.

Facebook Links without browser

I've read a lot of post on here, and other sites, but still not getting any clarification of my question. So here goes.
I have a Facebook link that requires you to be logged in. Is there a way using .Net (C#) that I can use Facebook API or something to "click" this link without a browser control.
Essentially, I have an application that I wrote that detects certain Farmville links. Right now I'm using a browser control to process the links. However, it's messy and crashes a lot.
Is there a way I can send the url along with maybe a token and api key to process the link?
Does anyone even understand what I'm asking? lol.
Disclaimer: I don't know what Facebook's API looks like, but I'm assuming it involves sending HTTP requests to their servers. I am also not 100% sure on your question.
You can do that with the classes in the System.Net namespace, specifically WebRequest and WebResponse:
using System.Net;
using System.IO;
...
HttpWebRequest req = WebRequest.Create("http://apiurl.com?args=go.here");
req.UserAgent = "The name of my program";
WebResponse resp = req.GetResponse();
string responseData = null;
using(TextReader reader = new StreamReader(resp.GetResponseStream())) {
responseData = reader.ReadToEnd();
}
//do whatever with responseData
You could put that in a method for easy access.
Sounds like your are hacking something... but here goes.
You might want to try a solution like Selenium, which is normally used for testing websites.
It is a little trouble to setup, but you can programmatically launch the facebook website in a browser of your choosing for login, programmatically enter username and password, programmatically click the login button, then navigate to your link.
It is kind of clunky, but get's the job done no matter what, since it appears to facebook that you are accessing their site from a browser.
I've tried similar sneaky tricks to enter my name over and over for Publisher's Clearing House, but they eventually wised up and banned my IP.

C# maintaining session over HTTPS on the client

I need to login to a website and perform an action. The website is REST based so I can easily login by doing this (the login info is included as a querystring on the URL, so I dont't need to set the credentials):
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest firstRequest = (HttpWebRequest) WebRequest.Create(loginUrl);
firstRequest.CookieContainer = cookieJar;
firstRequest.KeepAlive = true;
firstRequest.Method = "POST";
HttpWebResponse firstResponse = (HttpWebResponse)firstRequest.GetResponse();
That works and logs me in. I get a cookie back to maintain the session and it's stored in the cookieJar shown above. Then I do a second request such as this:
HttpWebRequest secondRequest = (HttpWebRequest) WebRequest.Create(actionUrl);
secondRequest.Method = "POST";
secondRequest.KeepAlive = true;
secondRequest.CookieContainer = cookieJar;
WebResponse secondResponse = secondRequest.GetResponse();
And I ensure I assign the cookies to the new request. But for some reason this doesn't appear to work. I get back an error telling me "my session has timed out or expired", and this is done one right after the other so its not a timing issue.
I've used Fiddler to examine the HTTP headers but I'm finding that difficult since this is HTTPS. (I know i can decrypt it but doesn't seem to work well.)
I can take my URL's for this rest service and paste them into firefox and it all works fine, so it must be something I'm doing wrong and not the other end of the connection.
I'm not very familiar with HTTPS. Do I need to do something else to maintain my session? I thought the cookie would be it, but perhaps there is something else I need to maintain across the two requests?
Here are the headers returned when I send in the first request (except I changed the cookie to protect the innocent!):
X-DB-Content-length=19
Keep-Alive=timeout=15, max=50
Connection=Keep-Alive
Transfer-Encoding=chunked
Content-Type=text/html; charset=WINDOWS-1252
Date=Mon, 16 Nov 2009 15:26:34 GMT
Set-Cookie:MyCookie stuff goes here
Server=Oracle-Application-Server-10g
Any help would be appreciated, I'm running out of ideas.
I finally got it working after decrypting the HTTP traffic from my program.
The cookie I'm getting back doesn't list the Path variable. So .NET takes the current path and assigns that as the path on the cookie including the current page. ie: If it was at http://mysite/somepath/somepage.htm it would set the cookie path=/somepath/somepage.htm. This is a bug as it should be assigned to "/" which is what all web browsers do. (hope they fix this.)
After noticing this I grabbed the cookie and modified the path property and everything works fine now.
Anyone else with a problem like this check out Fiddler. .NET uses the windows certificate store so to decrypt http traffic from your program you will need to follow the instructions here: http://www.fiddler2.com/Fiddler/help/httpsdecryption.asp . You will also need to turn on decryption under the Options\HTTPS tab of Fiddler.
From MSDN:
When a user moves back and forth between secure and public areas, the ASP.NET-generated session cookie (or URL if you have enabled cookie-less session state) moves with them in plaintext, but the authentication cookie is never passed over unencrypted HTTP connections as long as the Secure cookie property is set.
So basically, the cookie can be passed over both HTTP and HTTPS if the 'Secure' property is set to 'false'.
see also how can I share an asp.net session between http and https

Categories