SecurityException with Silverlight Web Services - c#

I've been following along with this Silverlight tutorial, using Twitter instead of Digg. Everything is working fine, until I get to the step where I try to get data from the service.
private const string TWITTER_API_URL_FORMAT = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name={0}";
private void Button_Click(object sender, RoutedEventArgs e)
{
string username = searchBox.Text;
string url = String.Format(TWITTER_API_URL_FORMAT, username);
WebClient twitterService = new WebClient();
twitterService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitterService_DownloadStringCompleted);
label.Text = "Loading... " + url;
twitterService.DownloadStringAsync(new Uri(url));
}
void twitterService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
label.Text = String.Format("Error: {0}", e.Error);
return;
}
// ...
}
It fails with the following error:
[System.Security.SecurityException] = {System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<E...
I'm not sure why this is happening. The URL is legit. I have a wp7 Silverlight project that uses this same code, and it works fine. What could I be doing wrong?

You're probably running into a cross site scripting (XSS) error. Take a look here: Making a Service Available Across Domain Boundaries

Related

Is it possible to communicate with AppServiceConnection and uwp in WinForm

Is it possible to communicate with AppServiceConnection and uwp in WinForm? Error: does not contain the definition of "GetAwaiter", this is my code:
Thank you!
This is the code in WinForm:
private AppServiceConnection calculatorService;
static Form1 mainForm;
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
//Add the connection
if (calculatorService == null)
{
calculatorService = new AppServiceConnection();
calculatorService.AppServiceName = "com.yanscorp.appservicedemo.Values";
calculatorService.PackageFamilyName = "c97887ad-1f75-4b48-9e3b-21b89c061715_6evysfdvxt248";
var status = await calculatorService.OpenAsync();//A mistake here
if (status != AppServiceConnectionStatus.Success)
{
string d = "Failed to connect";
return;
}
}
var message = new ValueSet();
message.Add("Request", "GetCallCount");
AppServiceResponse response = await calculatorService.SendMessageAsync(message);//A mistake here
string result = "";
if (response.Status == AppServiceResponseStatus.Success)
{
result = response.Message["Response"] as string;
// Get the data that the service sent to us.
textBlock.Text = result;
}
}
Error:
错误 CS4036 “IAsyncOperation”不包含“GetAwaiter”的定义,并且找不到可接受类型为“IAsyncOperation”的第一个参数的扩展方法“GetAwaiter”(是否缺少针对“System”的 using 指令?) WindowsFormsApplication1
Is it possible to communicate with AppServiceConnection and uwp in WinForm
Yes. You could use App service in WinForm. Check this article for more details.
Error: does not contain the definition of "GetAwaiter"
You could access the Windows 10 APIs in WinForm by reference winmd file and System.Runtime.WindowsRuntime.dll. It looks like you have already referenced winmd , but you may forget to reference System.Runtime.WindowsRuntime.dll which you could find it in the directory C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.
Adding the reference of System.Runtime.WindowsRuntime.dll will resolve your issue. Details please reference Calling Windows 10 APIs From a Desktop Application.

Upload Files to Google Drive using Google Drive API in ASP.Net with C#

Upload Files to Google Drive using Google Drive API in ASP.Net with C#.
Initially I have completed all the steps that needs to create the API with google and get Client ID and Client Secret.
And then used this code.
protected void Page_Load(object sender, EventArgs e)
{
connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
con = new SqlConnection(connStr);
cm = new ClassMain();
cmd = new SqlCommand();
google();
}
protected void UploadFile(object sender, EventArgs e)
{
Session["File"] = FileUpload1.PostedFile;
GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.file");
}
protected void google()
{
GoogleConnect.ClientId = "<Client ID>";
GoogleConnect.ClientSecret = "<Client Secret>";
GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
GoogleConnect.API = EnumAPI.Drive;
if (!string.IsNullOrEmpty(Request.QueryString["code"]))
{
string code = Request.QueryString["code"];
string json = GoogleConnect.PostFile(code, (HttpPostedFile)Session["File"], "");
GoogleDriveFile file = (new JavaScriptSerializer()).Deserialize<GoogleDriveFile>(json);
}
if (Request.QueryString["error"] == "access_denied")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
}
}
It will work properly for small size of file like 1 to 10 MB, If File size Increase then give error-
The webpage at http://localhost:1762/ChangeADCUploadedNewded/BlankPage.aspx?code=4%2fAk03HmpOQsV5Na_pM2fs5vzdfJTa2yoMzWAy-lD_CVE might be temporarily down or it may have moved permanently to a new web address.
resolve the error.
403-Invalid Credential error is not come at this time.
I did a little research and found that Google used to have the 10MB limit for uploads as you can see here: https://productforums.google.com/forum/#!topic/drive/N9Ruvnf0Jx8 but they increased that limit last year to 1TB. The only limitation that I was able to find for files larger than 10MB is when the uploaded file needs to be converted to a Google Doc, Sheet or Slides.

Google Access on WP7

I am having problems building an app that can access google accounts. I have the following code that gets the sign in page for google accounts and then the access permissions page is also displayed!. Once i click on "Allow Access" the app is redirected to error page. here are few screenshots so that whoever is trying to help can understand better.. and below is the code that am using
private void browseGoogle_Loaded(object sender, RoutedEventArgs e)
{
string address = "https://accounts.google.com/o/oauth2/auth" +
"?client_id=" + "*******.apps.googleusercontent.com" +
"&scope=" + "https://www.googleapis.com/auth/plus.me" +
"&response_type=code" +
"&redirect_uri=" + "https://www.****.com/oauth2callback";
browseGoogle.Navigate(new Uri(address, UriKind.Absolute));
}
https://accounts.google.com/o/oauth2/approval?as=634f855389bf10ff&hl=en_GB&xsrfsign=APsBz4gAAAAAUHZvwB3xTqisyv8hEcWem5X3eKvwAHN9
this is the URI its navigating to after allow access is selected/clicked. What does this mean?
This is all am doing. My BrowserNavigated Method doesn't contain any code as of now. I dunno what to do further.hence seeking help.
Please help me resolve this issue.. All answers and suggestion appreciated.
Just check the GDrive open-source application code here.
The Authorization View and ViewModel show you how you can make OAuth sign-in with Google credentials.
Download the code, read the pre-build instructions on the site, and test it!
private void browseGoogle_Loaded(object sender, RoutedEventArgs e)
{
try
{
StringBuilder autheticateURL = new StringBuilder();
autheticateURL.Append(GmailSettings.AuthorizeUri).Append("?client_id=").Append(GmailSettings.clientID).Append("&scope=").
Append(GmailSettings.ScopeValue).Append("&response_type=code").Append("&redirect_uri=").Append(GmailSettings.CallbackUri);
browseGoogle.Navigate(new Uri(autheticateURL.ToString(), UriKind.Absolute));
}
catch (Exception ex)
{
Logger.log(TAG, "browseGoogle_Loaded()", ex.Message);
}
}
/// <summary>
/// Called when the web browser initiates Navigation to various pages
/// </summary>
/// <param name="sender">Browser</param>
/// <param name="e">Navigating event arguments</param>
private void browseGoogle_Navigating(object sender, NavigatingEventArgs e)
{
try
{
string hostName = e.Uri.Host;
string URL = e.Uri.ToString();
if (hostName.StartsWith("localhost"))
{
NavigationService.Navigate(new Uri("/HomePage.xaml", UriKind.Relative));
}
}
catch (Exception ex)
{
Logger.log(TAG, "browseGoogle_Navigating()", ex.Message);
}
}
The XAML goes like this
<phone:WebBrowser x:Name="browseGoogle" Loaded="browseGoogle_Loaded" IsScriptEnabled="true" Navigating="browseGoogle_Navigating" />
My mistakes were two:-
1) as vignesh has mentioned in his comments I was using a wrong Redirect URI.
2)IsScriptEnabled was not at all set in my Web Browser Controls. Once i set it true everything was fine.

The URI prefix is not recognized OnDownloadStringCompleted

I've got a problem with simply method whch gets string from asp.net 4 ashx. I'm running below methods from silverlight application which is being hosted by this asp.net application.
private void LoadPlugins()
{
var serviceAddress = _baseAddress
+ "PluginsService.ashx?"
+ DateTime.Now.Ticks;
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(serviceAddress));
}
void client_DownloadStringCompleted(
object sender,
DownloadStringCompletedEventArgs e)
{
var plugins = e.Result.Split(
new string[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
foreach (var plugin in plugins)
{
AddXap(_baseAddress + plugin);
}
}
PluginsService.ashx.cs:
namespace MefPlugins.Web
{
/// <summary>
/// Summary description for PluginsService
/// </summary>
public class PluginsService : IHttpHandler
{
private const string PluginsFolderName = "Plugins/";
public void ProcessRequest(HttpContext context)
{
//var pluginFolder = new DirectoryInfo(
// HttpContext.Current.Server.MapPath(
// PluginsFolderName));
//var response = new StringBuilder();
//if (pluginFolder.Exists)
//{
// foreach (var xap in pluginFolder.GetFiles("*.xap"))
// {
// response.AppendLine(
// PluginsFolderName + xap.Name);
// }
//}
var response = new StringBuilder();
response.Append("test");
context.Response.ContentType = "text/plain";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I get an error:
System.Reflection.TargetInvocationException was unhandled by user code
Message=An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
StackTrace:
w System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
w System.Net.DownloadStringCompletedEventArgs.get_Result()
w MefPlugins.MainPage.client_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
w System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
w System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
InnerException: System.Net.WebException
Message=An exception occurred during a WebClient request.
InnerException: System.NotSupportedException
Message=The URI prefix is not recognized.
StackTrace:
w System.Net.WebRequest.Create(Uri requestUri)
w System.Net.WebClient.GetWebRequest(Uri address)
w System.Net.WebClient.DownloadStringAsync(Uri address, Object userToken)
InnerException:
Where could be a bug? this is an example from http://www.galasoft.ch/sl4u/code/chapter20/20.02-Mef/MefPlugins.zip
The reason for the error lies in which project is startup object selected as your startup project.
When your startup project is the MefPlugins projec (a Silverlight Project)t, the project settings indicate that a web page should be dynamically created to host your Silverlight application (right click on project, select Properties and go to the Debug tab).
The problem you runing into has to do with the location that is used as a prefix for the PluginsService.ashx file. The _baseAddress is set by in the main page constructor by the following code:
var xapUri = App.Current.Host.Source;
_baseAddress = xapUri.AbsoluteUri
.Substring(0, xapUri.AbsoluteUri.IndexOf(xapUri.AbsolutePath))
+ "/";
This means that the Uri of the xap file is used to determine the base uri. Now, as the project is using a dynamically generated container page - which is located on your hard drive and started from there - the above code takes the filesystem root is the _baseAddress. Obviously, the code will not find the PluginsService.ashx page, as it is not there.
Additionally, an .ashx file needs some form of http listener that routes the request from a port to your .ashx page. The listener can be a web server like IIS or the development web server, or some listener you implemented yourself.
To solve the problem make the MefPlugins.Web project your startup project and set MefPluginsTestPage.aspx as your startup page. Now _baseAddress should be something simlilar to http://localhost:6584/.
When this base address is now used to find the PluginsService.ashx page, it will result in a correct URI for the resource (http://localhost:6584/PluginsService.ashx in our case).
In general .ashx files are extensions to a web service (IIS, debug web server, or even some own implementation) they are not part of the silverlight client.
I suspect the problem is that the Uri you're passing to DownloadStringAsync is a relative Uri. That is: "file://PluginsService.ashx" is relative to the current directory. You probably want an absolute Uri (i.e. fully-qualified path name) as in "file://C:\projects\test\PluginsService.ashx".

Loading data from a site in Silverlight

I'm trying to load data into my Silverlight app. However, when it launches, I get a TargetInvocationException as soon as I hit e.Result:
public MainPage() {
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.google.com"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
Stream st = e.Result;
StreamReader sr = new StreamReader(st);
String result = sr.ReadToEnd();
}
Why does this fail, and what should I do to make it work?
PS, I'm afraid I cannot make a local proxy, because the app is going to be deployed as part of an app on an Apache Tomcat server, not an IIS.
Cheers
Nik
Silverlight cannot make cross-domain requests without a cross-domain policy file on the target domain. If you can't set up a proxy, you won't be able to get data from any domain other than the one hosting your application.

Categories