Access Google Drive Files from C# Web Application - c#

Hi I am having some trouble accessing the Google Drive SDK, mainly the authentication steps.
I have two main pages in my .Net Web app - Default.aspx.cs and WebForm1.aspx.cs.
In Default.aspx I have a hyperlink control that takes the user to the Google authentication page when they click on the link:
https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/drive.file+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile&redirect_uri=http://localhost/GoogleDriveTest/GoogleDriveTest/GoogleDriveTest/WebForm1.aspx&state=/profile&client_id=*CLIENT_ID*&approval_prompt=force
Once the user is redirected back to the REDIRECT_URI (WebForm1), I use this piece of code to access the authorization code:
HttpRequestInfo request = new HttpRequestInfo(Request);
code = Request.QueryString["code"];
Now I am stuck. I know I need to now POST this code to:
https://accounts.google.com/o/oauth2/token <insert POST parameters here>
But I am completely stuck as to how to do this. I have tried many things, but all I am getting:
Server time out error - it failed to connect to the requested server
How do I resolve this issue?
EDIT 24/09/2012:
With the new release of Visual Studio 2012, they have incorporated OAuth so it takes care of authentication:
http://www.asp.net/vnext/overview/videos/oauth-in-the-default-aspnet-45-templates
This means a user can log in to the local web application with an external account such as Google.
Does this mean, once the user is logged in via Google, that I can then grab the Google Drive files that I need? Or is this just for making registration handling easier in the local web application?
Thanks again.
Here is my error:
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [2404:6800:4008:c01::54]:443]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +251
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +279
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +6098637
System.Net.HttpWebRequest.GetRequestStream() +13
GoogleDriveTest.WebForm1.Page_Load(Object sender, EventArgs e) in C:\Projects\GoogleDriveTest\GoogleDriveTest\GoogleDriveTest\WebForm1.aspx.cs:101
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
SOLVED!!
My issue was that there is a proxy in my workplace that didn't allow any connections to the required URL. So I turned off the proxy in my browser and it bypassed it going directly the the required URL successfully getting the access token :D

Refer to the QuickStart (note the .NET tab!) that shows how to do this with the DotNetOpenAuth library.
Note the following line:
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);

The documentation includes a complete web application sample written in C# that you can use as reference:
https://developers.google.com/drive/examples/dotnet
It is an ASP.NET MVC application but the authorization part can be easily reused in a Web Forms application.
For more details about the authorization flow, check the documentation on how to Retrieve and Use OAuth 2.0 Credentials

Related

unable to know what is blocking to my application to communicate to Web service

Recently we were facing an issue in client place is that we were unable to communicate to web service even we checked that there is no system proxy set in that system, to overcome this we had given a dummy proxy (localhost:port) and its started working well but after some days with dummy proxy it was unable to communicate to service if we remove dummy proxy then it started working well. i am not able to understand what is blocking me to communicate to service. what may be the issue and how can we overcome this problem. This issue is happening only on some system.
Actually it has to go and hit this URL http://********-tech.in:8080/******dp/ClientVersion but suddenly it started hitting this one 125.21.244.38:8080 why i am not able to conclude.
2017-05-05 00:19:44,721 ERROR [Heartbeat Service ] - Exception while sending heartbeat to manager.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 125.21.244.38:8080
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at HeartbeatWSImplService.heartbeat(String probeUid, heartbeatRequest heartbeatRequest)
at ProHance.ProbeHeartBeat.HeartBeat.timer_Elapsed(Object sender, ElapsedEventArgs e)
Please read this post here they are telling to set the default proxy for the webservice request, they are trying to the proxy details while connecting to google. If there is no proxy configured you can try the method mentioned there. Set the default proxy.

EWS Managed: Root Element is missing

I'm developing an Exchange Web Services Managed API client on top of ASP.NET MVC. Everything worked until we installed the latest Exchange CU update yesterday. Then I periodically got "target principal name is incorrect" errors after some time on my web server when connecting to EWS. These could get fixed temporarily by restarting the web server.
I then used this post to configure Kerberos correctly: Set up Kerberos Authentication with Delegation on IIS 7 w/ Windows Server 2008
Now I am stuck with the following error that I never had before:
Exception Details: System.Xml.XmlException: Root element is missing.
[XmlException: Root element is missing.]
System.Xml.XmlTextReaderImpl.Throw(Exception e) +88
System.Xml.XmlTextReaderImpl.ParseDocumentContent() +1383
System.Xml.XmlCharCheckingReader.Read() +153
Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read() +63
Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read(XmlNodeType nodeType) +44
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadXmlDeclaration(EwsServiceXmlReader reader) +54
[ServiceRequestException: The response received from the service didn't contain valid XML.]
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadXmlDeclaration(EwsServiceXmlReader reader) +165
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadSoapFault(EwsServiceXmlReader reader) +43
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ProcessWebException(WebException webException) +413
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) +139
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request) +573
Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute() +42
Microsoft.Exchange.WebServices.Data.ExchangeService.FindAppointments(FolderId parentFolderId, CalendarView calendarView) +104
Because this is a managed version of the Exchange Web Services API I have nothing to do with the XML Requests and Responses directly. It's basically a black box for me. As you can see from the error, it occurs when calling for data from EWS.

SocketException when calling WCF service from MVC on same server

I have a Windows 2008 Server with IIS 7.5 and one IP. There are two Application under the root, /web and /service. /web is a MVC4 application, and /service is a WCF 4.0 service.
When I consume the service from MVC, I use the following code:
// Create the web request
HttpWebRequest request = WebRequest.Create(TripServiceUrl + id) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
tripJson = reader.ReadToEnd();
}
I get the following SocketException:
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.243.6.43:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +273
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +584
However, I can see 10.243.6.43:80 (an internal address) from a browser on the server and successfully call the service. The IP is not publicly accessible.
What configuration should I have to do to make a self referential call like that work?
It's probably a loopback problem (security issue). See http://support.microsoft.com/kb/896861.
To summarize:
In Registry Editor, locate and then click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
Right-click Lsa, point to New, and then click DWORD Value.
Type DisableLoopbackCheck, and then press ENTER.
Right-click DisableLoopbackCheck, and then click Modify.
In the Value data box, type 1, and then click OK.
Don't follow the step about DisableStrictNameChecking.
You'll also find a lot of reasons not to do this (you are, after all, disabling a security check), followed by a lot of people saying it's the only way to get SharePoint to work properly. In any event, it will help you determine if this is the problem.

Configuring web services on Windows Server 2003

We have recently moved from an online hosting provider to a local server and we are currently trying to set up a .net website with web services and are having difficulties.
We have two websites running on IIS (in Windows Server 2003) - one that is the actual website where we gain input from the user and one which is running the web services where we talk to the database / deal with logic etc...
At the moment we can display the main website page but as soon as it accesses the web services it receives the following 404 error:
The request failed with HTTP status 404: Not Found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The request failed with HTTP status 404: Not Found.
Source Error:
Line 1120: >[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost:58605/Dev_GetVersion", RequestNamespace="http://localhost:58605", ResponseNamespace="http://localhost:58605", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
Line 1121: public string Dev_GetVersion() {
Line 1122: object[] results = this.Invoke("Dev_GetVersion", new object[0]);
Line 1123: return ((string)(results[0]));
Line 1124: }
Source File: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\b0534295\1f56ee4c\App_WebReferences.mjxicnrr.0.cs Line: 1122
Stack Trace:
[WebException: The request failed with HTTP status 404: Not Found.]
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +431289
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +204
IPASWebServices.AccountManagementServices.Dev_GetVersion() in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\b0534295\1f56ee4c\App_WebReferences.mjxicnrr.0.cs:1122
MasterPage.displayVersionDetails() in c:\www_ipas\MasterPage.master.cs:46
MasterPage.Page_Load(Object sender, EventArgs e) in c:\www_ipas\MasterPage.master.cs:28
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
I see it's trying to access the web server and then the method ("http://localhost:58605/Dev_GetVersion") but it is leaving out the actual web service name. (It should be "http://localhost:58605/AccountManagementServices.asmx?op=Dev_GetVersion").
Any idea why it does this? It works perfectly fine on the online web hosting and on the development computer, just not in this new environment.
Make sure the App is running as an account that has the proper rights in IIS. If unsure, make sure the account the app is running as is in the IIS_WPG group.
Here is more details on properly setting up the IIS App Pool Identity: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/12a3d96c-65ea-4210-96ad-86a801f6a88c.mspx?mfr=true

Webservice SocketException - Only Breaks On One Application

I have a few applications which use a single Web Service which resides on the same server as the applications.
Why would only one of the applications have a problem connecting to a web service? And is there a way I can better diagnose exactly what the problem is with the connection?
It won't even connect to a web service the application itself is hosting
I have tried running it from my local machine and it works fine (updated the web ref url and the connection string to point to the liver server), which should rule out that the code itself is the problem.
I have tried setting up a different virtual directory to point to the application; and later copying the entrie app to another location on the same server and setting it up there. No luck.
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xx.xx.xx:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream() +5321194
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +103
...
Found it... the proxy was the cause of the issue and it is the only application where I specify proxy different from the default:
Since I only need the proxy locally I disabled it on the live web.config with enabled="false"
<defaultProxy enabled="false">
<proxy
autoDetect="False"
bypassonlocal="True"
scriptLocation="http://www.proxy.something"
proxyaddress="http://proxy.com" />
</defaultProxy>

Categories

Resources