Exception thrown when using GData .NET Analytics API - asp.net

I am facing an issue while trying to fetch data from GoogleAnalytics API on piece of code that has been working well just a couple of days ago.
For this I am referencing the following DLL's:
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
And I am using the following code:
Dim visits As String = String.Empty
Dim username As String = "myuser#mydomain.com"
Dim pass As String = "mypassword"
Const dataFeedUrl As String = "https://www.google.com/analytics/feeds/data"
Dim query As AccountQuery = New AccountQuery()
Dim service As AnalyticsService = New AnalyticsService("MyWebAnalyticsService")
service.setUserCredentials(username, pass)
Dim accountFeed As AccountFeed = service.Query(query) ''----------> Exception thrown in this line: GDataRequestException Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
I thought it had to do with a blocking to the account I was using but it wasn't the case because I verified registering the site for another analytics account and is still not working.
This code has been working flawlessly as I've said but all of a sudden has stopped doing so yesterday.
Could you please help me figuring out what's wrong?. Maybe the way the user credentials are set has changed and I am missing something.
Thank you very much for your help.
'----Update----
I managed to make it work and now I can query the visits for a desired domain. The code goes as follows:
Dim visits As String = String.Empty
Dim username As String = "myuser#mydomain.com"
Dim pass As String = "mypassword"
'Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key
'Once you have it set it as part of the querystring to request our GA service
Dim gkey As String = "key=yourkeystring"
'Set the new URI to retrieve the feed data and append it the generated key
Dim dataFeedUrl As String = "https://www.google.com/analytics/feeds/data?" & gkey
'Create and authenticate on our service instance
Dim service As AnalyticsService = New AnalyticsService("MyAnaliticsService")
service.setUserCredentials(username, pass)
'Use the profile id for the account you want to get ths visits from, you can find it
'logging in your analytics account, select the desired domain on your list (blue link)
click on the administrator button and on the profiles tab find the profile
'configuration subtab, right there you will find the profile id in this case the eight characters long id 12345678
Dim query1 As DataQuery = New DataQuery(dataFeedUrl)
With query1
.Ids = "ga:12345678"
.Metrics = "ga:visits"
.Sort = "ga:visits"
.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd")
.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
.StartIndex = 1
End With
'Use the generated datafeed based on the former query to get the visits
Dim dataFeedVisits As DataFeed = service.Query(query1)
For Each entry As DataEntry In dataFeedVisits.Entries
Dim st As String = entry.Title.Text
Dim ss As String = entry.Metrics(0).Value
visits = ss
Next

I have the same problem and it looks like google recently shut down the feed. It is answered in another post. Issue com.google.gdata.util.ResourceNotFoundException: Not Found with Google Analytic

Please make sure you registered your project in the APIs Console and you are sending the API Key with your requests.
If that is not the issue, inspecting the inner exception will give you more details about the error. As an alternative, you can use Fiddler to capture the HTTP request and the response. The latter will include a more descriptive error message.

Related

WooCommerce REST API The remote server returned an error: (401) Unauthorized VB.NET

My site (https://www.trs.is) recently switched to https and now I am getting an Unauthorized error when I try to get all products from my WooCommerce store. I have tried many things with the WebClient() to use basic authentication but I always get this error.
I have also tested this with Postman from Google with basic auth and using the client key and client secret but the error is always the same.
Scratching my head here and after hours of searching I can not see why the this is happening.
Here is my latest code (actual client keys are removed)
Dim url As String = "https://www.trs.is/wc-api/v3/products"
'Dim client As New WebClient()
Dim userName As [String] = "myclientkey"
Dim passWord As [String] = "myclientsecret"
'client.Credentials = New System.Net.NetworkCredential(userName, passWord)
Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord))
wc.Headers(HttpRequestHeader.Authorization) = Convert.ToString("Basic") & credentials
Dim result = wc.DownloadString(url)
Any help guys ?
Try using wc.UseDefaultCredentials = True and post your API keys instead.

Setting reminders in google calendar through .net api

I am writing an asp.net webpage that creates events in google calendar. I want to add a "notification" to the event that will send an email 30 minutes before the event begins.
Reading through the api, I see that there is an attribute for inserting events called "reminders" that seems to be the same thing. Using google's api playground, I can successfully create the event and specify the reminder.
However, using the .net api version 1.9.0.990 I can create the event, but no reminders are set for it. Below is the code I have written:
Shared Sub eventWithReminder(calendarIdentifier As String, startTime As DateTime, endTime As DateTime, eventTitle As String)
Dim calendarID As String
Dim calList As CalendarList = RoomReservations_RoomReservationsServiceAccount.calService.CalendarList.List().Execute
For Each Calendar In calList.Items
If Calendar.Id = calendarIdentifier Then
calendarID = Calendar.Id
End If
Next
Dim anotherNewEvent As New [Event]
anotherNewEvent.Summary = eventTitle
Dim edtStart As New EventDateTime
edtStart.DateTime = startTime
Dim edtEnd As New EventDateTime
edtEnd.DateTime = endTime
anotherNewEvent.Start = edtStart
anotherNewEvent.End = edtEnd
Dim reminder As New EventReminder
reminder.Method = "email"
reminder.Minutes = 30
Dim reminderList As New List(Of EventReminder)
reminderList.Add(reminder)
Dim remindData As New [Event].RemindersData
remindData.UseDefault = False
remindData.Overrides = reminderList
anotherNewEvent.Reminders = remindData
System.Net.ServicePointManager.Expect100Continue = False
RoomReservations_RoomReservationsServiceAccount.calService.Events.Insert(anotherNewEvent, calendarID).Execute()
End Sub
I then view the event in the google calendar web interface, but the Notifications section reads "No notifications set"
Is this functionality not yet built in to the api?
If it is, am I using it incorrectly?
Reminders are tied to the authenticated user. In this case Bob was creating events using service account but on user's calendar. Service accounts do not have privileges to modify reminders for users.
In order to change reminders for someone, you need to be authenticated as that person (use their Oauth token).

User details stored in separate table ASP.NET Identity

I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...

Different approaches for finding users within Active Directory

I'm a newbie to AD programming, but after a couple of weeks of research have found the following three ways to search for users in Active Directory using the account name as the search parameter:
Option 1 - FindByIdentity
Dim ctx As New PrincipalContext(ContextType.Domain, Environment.MachineName)
Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MYDOMAIN\Administrator")
If u Is Nothing Then
Trace.Warn("No user found.")
Else
Trace.Warn("Name=" & u.Name)
Trace.Warn("DisplayName=" & u.DisplayName)
Trace.Warn("DistinguishedName=" & u.DistinguishedName)
Trace.Warn("EmployeeId=" & u.EmployeeId)
Trace.Warn("EmailAddress=" & u.EmailAddress)
End If
Option 2 - DirectorySearcher
Dim connPath As String = "LDAP://" & Environment.MachineName
Dim de As New DirectoryEntry(connPath)
Dim ds As New DirectorySearcher(de)
ds.Filter = String.Format("(&(objectClass=user)(anr={0}))", Split(User.Identity.Name, "\")(1))
ds.PropertiesToLoad.Add("name")
ds.PropertiesToLoad.Add("displayName")
ds.PropertiesToLoad.Add("distinguishedName")
ds.PropertiesToLoad.Add("employeeId")
ds.PropertiesToLoad.Add("mail")
Dim src As SearchResult = ds.FindOne()
If src Is Nothing Then
Trace.Warn("No user found.")
Else
For Each propertyKey As String In src.Properties.PropertyNames
Dim valueCollection As ResultPropertyValueCollection = src.Properties(propertyKey)
For Each propertyValue As Object In valueCollection
Trace.Warn(propertyKey & "=" & propertyValue.ToString)
Next
Next
End If
Option 3 - PrincipalSearcher
Dim ctx2 As New PrincipalContext(ContextType.Domain, Environment.MachineName)
Dim sp As New UserPrincipal(ctx2)
sp.SamAccountName = "MYDOMAIN\Administrator"
Dim s As New PrincipalSearcher
s.QueryFilter = sp
Dim p2 As UserPrincipal = s.FindOne()
If p2 Is Nothing Then
Trace.Warn("No user found.")
Else
Trace.Warn(p2.Name)
Trace.Warn(p2.DisplayName)
Trace.Warn(p2.DistinguishedName)
Trace.Warn(p2.EmployeeId)
Trace.Warn(p2.EmailAddress)
End If
All three of these methods return the same results, but I was wondering if any particular method is better or worse than the others?
Option 1 or 3 seem to be the best as they provide strongly-typed property names, but I might be wrong? My overall objective is to find a single user within AD based on the user principal value passed via the web browser when using Windows Authentication on a site (e.g. "MYDOMAIN\MyUserAccountName")
For me 1 and 3 are quite the same. In Querying an LDAP in C# answer, I introduce a third way using managed code which is low level (native LDAP) protocol with System.DirectoryServices.Protocols (S.DS.P).
I don't know if your purpose is just to authenticate a user or authenticate a user and retrieve some datas (profile) from Active-Directory, but keep in mind that a LDAP query is first a query, and the old fashion (your solution 2) let's you specify the properties you retrieve. Before choosing, make some test on a performance point of view.
If you just want to authenticate you can compare native LDAP and user Principal responses from another article

Issue Querying LDAP DirectoryEntry in ASP.NET

I have users login to my application via Active Directory and then pull from their AD information to garner information about that user like so:
Dim ID as FormsIdentity = DirectCast(User.Identity, FormsIdentity)
Dim ticket as FormsAuthenticationTicket = ID.Ticket
Dim adDirectory as New DirectoryEntry("LDAP://DC=my,DC=domain,DC=com")
Dim adTicketID as String = ticket.Name.Substring(0, 5)
Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value
Session("person_name") = adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value
Now, I want to be able to impersonate other users...so that I can "test" the application as them, so I added a textbox and a button to the page and when the button is clicked the text is assigned to a session variable like so:
Session("impersonate_user") = TextBox1.Text
When the page reloads I check to see if Session("impersonate_user") has a value other than "" and then attempt to query Active Directory using this session variable like so:
If CStr(Session("impersonate_user")) <> "" Then
Dim adDirectory as New DirectoryEntry(LDAP://DC=my,DC=domain,DC=com")
Dim adTicketID as String = CStr(Session("impersonate_user"))
Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value
Session("person_name")= adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value
Else
[use the actual ticket.name to get this info.]
End If
But this doesn't work. Instead, it throws an error on the first Session line stating, "DirectoryServicesCOMException was unhandled by user code There is no such object on the server."
Why? I know I'm giving it a valid username! Is something strange happening in the casting of the session? The code is essentially the same between each method except that in one method rather than pulling from ticket.Name I pull from a session variable for the login I'll be looking up with AD.
Maybe the identity your process is running under needs permissions to access the active directory. You could do this by changing the identity your application runs under in the IIS application pool.
What is entered in the textbox?

Resources