Accessing Google.Apis.Analytics.v3 from web application without .p12 file - asp.net

I have an ASP.NET 4.5 application with a separate class library for accessing the Google analytics data. Every try to use the common methods (loading the certificat from .p12 file) ends in an "internal error" (the file will be found!) in 3rd line (Dim certificat...)
Dim scopes As String() = New String() {AnalyticsService.Scope.Analytics}
Dim serviceAccountEmail = "info#xxx.biz"
Dim certificate = New X509Certificate2(System.Web.HttpContext.Current.Server.MapPath("Certificates/MyDashboard-b335c24b1a76.p12"), "notasecret", X509KeyStorageFlags.Exportable)
Dim credential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {.Scopes = scopes}.FromCertificate(certificate))
Dim service = New AnalyticsService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = "MyDashboard" _
})
Dim MyRequest As DataResource.GaResource.GetRequest = service.Data.Ga.Get("ga:44582845", "2016-01-01", "2016-01-01", "ga:sessions")
MyRequest.MaxResults = 1000
Dim MyResult As GaData = MyRequest.Execute()
[CryptographicException: Interner Fehler.
]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +307
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +92
GoogleAnalyticsClient.Class1..ctor() in P:\Google Analytics\GoogleAnalyticsClient\Class1.vb:59
preisvergleich.Statistik.Page_Load(Object sender, EventArgs e) in \web\Webs\AFFILIATE 2.0\preisvergleich\Statistik.aspx.vb:16
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
Is there any possibility to access the analytics data without the certificate (I think it was in former times)?
BR Jan

Related

SmtpClient.Send(msg); error

I used this one to send the email, but when I submit, it was showing me "Line 41: smtp.Send(msg);" error. I do not know what's wrong with this. Thanks for the help!
public partial class Contact : Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("xxxxx#gmail.com");
msg.To.Add("xxxxx#hotmail.com");
msg.Subject = txtSubject.Text;
msg.Body = txtFirstName.Text + " " + txtLastName.Text + "'s phone number is: " + txtPhone.Text + ". <br />" + "Email Address is: " + txtEmail.Text + "Message: <br />" + txtMessage.Text;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "xxxxx#gmail.com";
NetworkCred.Password = "xxxxx";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(msg);
lblMessage.Text = "Email has been successfully sent!";
}
}
Stack Trace:
[SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at]
System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) +1844406
System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) +46
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) +88
System.Net.Mail.SmtpClient.Send(MailMessage message) +1856
XinNing_Web.Contact.btnSubmit_Click(Object sender, EventArgs e) in E:\Projects\ASP.NET\XinNing_Web\XinNing_Web\Contact.aspx.cs:41
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9767618
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1738
Allow less secure app to true in your gmail account from which your are trying to send the mail.
Go to my account -> sign-in & security -> Allow less secure app( at bottom of the page).
Some time due to this error occured.

Upload File to FTP site throws error on particular line of code

I am using the below code to upload file in FTP Site
Protected Sub FTPUpload(ByVal sender As Object, ByVal e As EventArgs)
'FTP Server URL.
Dim ftp As String = "myftpsitehere"
'FTP Folder name. Leave blank if you want to upload to root folder.
Dim ftpFolder As String = "Attachments/"
Dim fileBytes As Byte() = Nothing
'Read the FileName and convert it to Byte array.
Dim fileName As String = Path.GetFileName(FileUpload1.FileName)
Using fileStream As New StreamReader(FileUpload1.PostedFile.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
End Using
Try
'Create FTP Request.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftp & ftpFolder & fileName), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
'Enter FTP Server credentials.
'request.Credentials = New NetworkCredential("UserName", "Password")
'request.Credentials = New NetworkCredential()
request.ContentLength = fileBytes.Length
request.UsePassive = True
request.UseBinary = True
request.ServicePoint.ConnectionLimit = fileBytes.Length
request.EnableSsl = False
Using requestStream As Stream = request.GetRequestStream()
requestStream.Write(fileBytes, 0, fileBytes.Length)
requestStream.Close()
End Using
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
lblMessage.Text &= fileName & " uploaded.<br />"
response.Close()
Catch ex As WebException
Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription)
End Try
End Sub
The above code uploads the file in ftp site when I test it in VS-2010 development mode.
When I try to upload file from the live website I am getting the below error.
Server Error in '/' Application.
Exception of type 'System.Exception' was thrown.
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.Exception: Exception of type 'System.Exception' was thrown.
Line 50: 'response.Close()
Line 51: Catch ex As WebException
Line 52: Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription)
Line 53: End Try
Line 54: End Sub
[Exception: Exception of type 'System.Exception' was thrown.]
_Default.FTPUpload(Object sender, EventArgs e) in h:\root\home\Website-001\www\site15\Default.aspx.vb:52
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

Error in Application : The specified string is not in the form required for an e-mail address

I am trying to send an email to the user's account when the user clicks send button. But I am getting the above error. Below is my sendClick code.
protected void btnsendCode_Click(object sender, EventArgs e)
{
try
{
if (txtemail.Text != "")
{
Random rd = new Random();
veri = rd.Next(1000, 10000);
MailMessage mm = new MailMessage();
mm.To.Add(new MailAddress(txtemail.Text.ToString()));
mm.From = new MailAddress("xxx#yyy.in", "Verification Mail");
mm.Body = "Your Verification Code is - " + veri.ToString();
mm.IsBodyHtml = true;
mm.Subject = "Verification mail";
SmtpClient smcl = new SmtpClient();
smcl.Host = "smtp.gmail.com";
smcl.Port = 587;
smcl.Credentials = new NetworkCredential("xxx#yyy.in", "xxx");
//smcl.EnableSsl = true;
smcl.Send(mm);
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Verification Code sent to your Email ID! Please Check your Email!!');", true);
txtverify.Enabled = true;
btnsendCode.Text = "Send Code Again";
lblmsg.Visible = false;
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "Please enter Email ID!!";
lblmsg.ForeColor = System.Drawing.Color.Yellow;
lblmsg.BorderColor = System.Drawing.Color.Red;
lblmsg.BorderStyle = BorderStyle.Ridge;
lblmsg.BorderWidth = new Unit("2");
lblmsg.Focus();
}
}
catch (WebException we)
{
lblmsg.Visible = true;
lblmsg.Text = we.Message.ToString();
lblmsg.ForeColor = System.Drawing.Color.Yellow;
lblmsg.BorderColor = System.Drawing.Color.Red;
lblmsg.BorderStyle = BorderStyle.Ridge;
lblmsg.BorderWidth = new Unit("2");
}
}
Stack Trace
[FormatException: The specified string is not in the form required for
an e-mail address.]
System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(String
data, Int32 index) +1475945
System.Net.Mail.MailAddressParser.ParseDomain(String data, Int32&
index) +135 System.Net.Mail.MailAddressParser.ParseAddress(String
data, Boolean expectMultipleAddresses, Int32& index) +99
System.Net.Mail.MailAddressParser.ParseAddress(String data) +23
System.Net.Mail.MailAddress..ctor(String address, String displayName,
Encoding displayNameEncoding) +220
System.Net.Mail.MailMessage..ctor() +130
events.btnsendCode_Click(Object sender, EventArgs e) in
d:\inetpub\vhosts\marpallichande.in\httpdocs\Test\events.aspx.cs:101
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9552874
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
Which part I am committing mistake and need to correct it?
The reason it fails is using the empty constructor without the mail settings to match:
MailMessage mm = new MailMessage();
The empty constructor relies on:
<system.net>
<mailSettings>
<smtp from="report#company.com" />
</mailSettings>
</system.net>
in your app or web.config file. So either use the constructor that expects a from and to address, or add that node to your app/web.config file.
I firmly believe this is a bug in the .Net framework, because we were able to create new MailMessage() objects and then assign the "from" later on, but in .Net 4.0 and under certain conditions—which I still don't fully understand—this fails. I welcome being corrected of course, but for now, this seems like an oversight.
So some of our customers never encountered this issue, but to fix it we had to add that dummy setting to the web.config files.
I had a similar problem with getting [FormatException: The specified string is not in the form required for an e-mail address.] too. My problem was with this code:
void SendMail(string destinationEmail)
MailMessage message=new MailMessage("mytestmail#test.com",destinationEmail);
SmtpClient mailClient = new SmtpClient("mail.test.com", 587);
mailClient.Credentials = new System.Net.NetworkCredential("mytestmail", "pswd");
try{
mailClient.Send(mail);
}
catch (Exception ex){...}
As you can see I just tried and caught only sending part. But this problem was thrown from MailMessage constructor. I would have never guessed that a constructor would throw an exception. So I just tried this code independently:
MailMessage mail = new MailMessage("test", "test");
The result of this code is [FormatException: The specified string is not in the form required for an e-mail address.]. If you try this:
MailMessage mail = new MailMessage("", "");
you'll get ArgumentException: The parameter 'from'(or 'to') cannot be an empty string.
So what you need to do in these kind of cases is you include the MailMessage construction part in the try catch block too and make sure that the exception you catch covers exception types that MailMessage constructor might throw, in this particular case, FormatException. Although I hate cathcing the Exception class, in this case it seems to be a perfect fit.

Facebook SDK 5+ authentication token error: A connection attempt failed because the connected party did not properly respond after a period of time

I have an issue I have been trying to fix since this morning (now over 8h). I got the facebook cookie contents, found the auth token which works fine on its own in the browser
https://graph.facebook.com/me?access_token=201856003211297|2.AQAHJg3GugHIHhec.3600.1314442800.1-100002411647354|RAylZSUax4pdKcIt--QruS-Qcgc
But
Whenever I try to get the user information, the web-page crashes down very nicely with the error below.
I have tried to read from the page using web request:
'Dim inputFile As String = "https://graph.facebook.com/me?access_token=" & access_token
'Dim sDiskFile As String = "auth.txt"
'Dim _wrequest As WebRequest = WebRequest.Create(inputFile)
'Dim _wresponse As WebResponse
'_wresponse = _wrequest.GetResponse()
'Dim _stream As Stream = _wresponse.GetResponseStream()
'Dim oReader As New StreamReader(_stream, Encoding.ASCII)
And it crashed with the same error. I decided to give the Facebook SDK 5 a go and the same error is happening:
Dim access_token As String = GetFacebookTokenFromCookie()
If access_token = "" Then
litUser.Text = "<fb:login-button perms='email'>Login with Facebook</fb:login-button>"
Else
Dim app As New DefaultFBApp
Dim _ctx As New FacebookWebContext(app)
Dim fb As New Facebook.FacebookClient(app)
fb.AccessToken = access_token
Dim parameters As New Dictionary(Of String, Object)()
parameters("fields") = "id,name"
Dim result As Object = fb.Get(parameters)
Dim id = result.id
Dim name = result.name
Dim firstName As String = result.first_name
Dim lastName = result.last_name
Dim link = result.link
Dim username = result.username
Dim gender = result.gender
Dim male = result.locale
litUser.Text = "Welcome " & firstName
End If
DefaultFBApp is:
Public Class DefaultFBApp
Implements Facebook.IFacebookApplication
With all the must-implement fields added in and the api key and secret filled in.
Same error:
Server Error in '/' Application.
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 69.171.224.21:443
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.Sockets.SocketException: 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 69.171.224.21:443
Source Error:
Line 25: parameters("fields") = "id,name"
Line 26:
Line 27: Dim result As Object = fb.Get(parameters)
Line 28:
Line 29: Dim id = result.id
Source File: masterpage.master Line: 27
Stack Trace:
[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 69.171.224.21:443]
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
[WebExceptionWrapper: Unable to connect to the remote server]
FluentHttp.HttpHelper.OpenRead() +191
Facebook.FacebookClient.Api(String path, IDictionary`2 parameters, HttpMethod httpMethod, Type resultType) +253
Facebook.FacebookClient.Get(IDictionary`2 parameters) +44
ASP.masterpage_master.Page_Load(Object sender, EventArgs e) in E:\kunden\homepages\6\d364763622\www\wsb6301158401\masterpage.master:27
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.5446; ASP.NET Version:2.0.50727.5420
Any help would be mostly appreciated

asp.net FileUpload control works on server but not for clients

I have a strange thing going on with the .net fileupload control.
If I remote desktop to the server that houses the web app and db server, I am able to upload files and store them into a varbinary(max) column.
However, when clients connect to the web server from their desktop, then can do all the things they need to such as browsing web pages, fill out forms that store/save data to the database, etc.
However, when they try to upload a pdf to the sever, the following exception occurs:
The web app uses .net 3.5, the db is sql 2005, and code is c#. And insights would be welcomed. Code and Exception below.
Any insights will be welcomed.
protected void btnSave_Click(object sender, EventArgs e)
{
int intDocLen = 0;
string str = "";
Stream objStream = default(Stream);
SqlConnection Conn = default(SqlConnection);
SqlCommand cmdUploadDoc = default(SqlCommand);
string ConnString = null;
lblMessage.Text = "";
try
{
if (FileUpload1.HasFile)
{
Guid NewDOCGUID = System.Guid.NewGuid();
intDocLen = FileUpload1.PostedFile.ContentLength;
byte[] Docbuffer = new byte[intDocLen];
objStream = FileUpload1.PostedFile.InputStream;
objStream.Read(Docbuffer, 0, intDocLen);
ConnString = ConfigurationManager.ConnectionStrings["CFDConnectionString1"].ConnectionString;
Conn = new SqlConnection(ConnString);
if (!isMM)
{
string query = "INSERT INTO DisclosureFiles "
+ "(DisclosuerSummaryId, FileName, Contents, DocGUID, DateModified) "
+ "VALUES(#DisclosuerSummaryId, #FileName, #Contents, #DocGUID, #DateModified) ";
cmdUploadDoc = new SqlCommand();
cmdUploadDoc.CommandType = CommandType.Text;
cmdUploadDoc.Connection = Conn;
cmdUploadDoc.CommandText = query;
cmdUploadDoc.Parameters.Add("#DisclosuerSummaryId",
SqlDbType.Int).Value = disclosureId;
cmdUploadDoc.Parameters.Add("#FileName",
SqlDbType.VarChar).Value = FileUpload1.PostedFile.FileName;
cmdUploadDoc.Parameters.Add("#Contents",
SqlDbType.VarBinary).Value = FileUpload1.FileBytes;
cmdUploadDoc.Parameters.Add("#DocGUID",
SqlDbType.UniqueIdentifier).Value = NewDOCGUID;
cmdUploadDoc.Parameters.Add("#DateModified",
SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
string query = "INSERT INTO DisclosureFiles "
+ "(massMediaId, FileName, Contents, DocGUID, DateModified) "
+ "VALUES(#massMediaId, #FileName, #Contents, #DocGUID, #DateModified) ";
cmdUploadDoc = new SqlCommand();
cmdUploadDoc.CommandType = CommandType.Text;
cmdUploadDoc.Connection = Conn;
cmdUploadDoc.CommandText = query;
cmdUploadDoc.Parameters.Add("#massMediaId",
SqlDbType.Int).Value = disclosureId;
cmdUploadDoc.Parameters.Add("#FileName",
SqlDbType.VarChar).Value = FileUpload1.PostedFile.FileName;
cmdUploadDoc.Parameters.Add("#Contents",
SqlDbType.VarBinary).Value = FileUpload1.FileBytes;
cmdUploadDoc.Parameters.Add("#DocGUID",
SqlDbType.UniqueIdentifier).Value = NewDOCGUID;
cmdUploadDoc.Parameters.Add("#DateModified",
SqlDbType.DateTime).Value = DateTime.Now;
}
Conn.Open();
int result = cmdUploadDoc.ExecuteNonQuery(); //this is where it crashes
Conn.Close();
if (result > 0)
{
lblMessage.Text = "File Saved Successfully";
}
}
else
{
lblMessage.Text = "Please Select a File to Upload";
}
}
catch (Exception ex)
{
lblMessage.Text = "Please report the following error: "
+ ex.Message;
}
finally
{
Conn.Close();
}
}
Exception
System.Data.SqlClient.SqlException: String or binary data would be truncated. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at TestForm.btnSave_Click(Object sender, EventArgs e) in c:\inetpub\wwwdev\UploadPdf.aspx.cs:line 104
That error indicates you're trying to store too much data in a database field, like trying to store a filename of length 200 in a field that's varchar(100). What are the capacites for the other table columns and what are the lengths of the content you're trying to store in them?
Try commenting a column one by one and re-execute the code, it seems you have defined a column with less size, and trying to store data which is causing this error.
can you please see the column size defined and make sure all the columns are capable to store the data for the file?

Resources