Google calendar in vb.net - google-calendar-api

I am trying to convert the calendar code of C#.NET provided on google site to VB.NET and facing some conversion issues. Please help me.
Code in C#.net:
static void RetrieveAcls(CalendarService service)
{
FeedQuery query = new FeedQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/testingforfinals#gmail.com");
AtomFeed calFeed = service.Query(query);
Console.WriteLine();
Console.WriteLine("Sharing permissions for your calendars:");
// Retrieve the meta-feed of all calendars.
foreach (AtomEntry calendarEntry in calFeed.Entries)
{
Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text);
AtomLink link = calendarEntry.Links.FindService(
AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, null);
// For each calendar, retrieve its ACL feed.
if (link != null)
{
AclFeed feed = service.Query(new AclQuery(link.HRef.ToString()));
foreach (AclEntry aclEntry in feed.Entries)
{
Console.WriteLine("\tScope: Type={0} ({1})", aclEntry.Scope.Type,
aclEntry.Scope.Value);
Console.WriteLine("\tRole: {0}", aclEntry.Role.Value);
}
}
}
}
My code in VB.NET:
Public Sub RetrieveAcls(ByVal service As CalendarService)
Dim query As New FeedQuery
query.Uri = New Uri("http://www.google.com/calendar/feeds/testingforfinals#gmail.com")
Dim calFeed As New AtomFeed(service.Query(query))
Console.WriteLine()
Console.WriteLine("Sharing permissions for your calendars:")
Dim calendarEntry As New AtomEntry
Dim link As New AtomLink
Dim aclEntry As New AclEntry
For Each calendarEntry In calFeed.Entries
Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text)
link = calendarEntry.Links.FindService(AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, "")
If (link Is Nothing) Then
Dim feed As AclFeed()
feed = New AclFeed(query, service)
feed = service.Query(New AclQuery(link.HRef.ToString()))
For Each aclEntry In feed.Entries
Console.WriteLine("\tScope: Type={0} ({1})", aclEntry.Scope.Type, aclEntry.Scope.Value)
Console.WriteLine("\tRole: {0}", aclEntry.Role.Value)
Next
End If
Next
End Sub
Am facing error at "query" in "feed = New AclFeed(query, service)" which says Value of type Google.GData.Client.FeedQuery cannot be converted to 'System.Uri'... This issue is resolved... One more last issue is as per below...
Dim myQuery As New EventQuery(feedURI)
Dim myResultsFeed As New EventFeed(service.Query(myQuery))
I am getting error on "myResultsFeed" as "Argument not specified for parameter 'iService' of 'Public Sub New(uriBase As System.Uri, iService As Google.GData.Client.IService)'." and another error on "service.Query(myQuery)) as "Value of type 'Google.GData.Calendar.EventFeed' cannot be converted to 'System.Uri'."
static void DateRangeQuery(CalendarService service, DateTime startTime, DateTime endTime)
{
EventQuery myQuery = new EventQuery(feedUri);
myQuery.StartTime = startTime;
myQuery.EndTime = endTime;
EventFeed myResultsFeed = service.Query(myQuery) as EventFeed;
Console.WriteLine("Matching events from {0} to {1}:",
startTime.ToShortDateString(),
endTime.ToShortDateString());
Console.WriteLine();
for (int i = 0; i < myResultsFeed.Entries.Count; i++)
{
Console.WriteLine(myResultsFeed.Entries[i].Title.Text);
}
Console.WriteLine();
}

Well you've converted this:
AclFeed feed = service.Query(new AclQuery(link.HRef.ToString()));
to this:
Dim feed As AclFeed()
feed = New AclFeed(query, service)
feed = service.Query(New AclQuery(link.HRef.ToString()))
They're not the same at all! Your second line is calling a constructor for no obvious reason.
Just this would be fine:
Dim feed As AclFeed = service.Query(New AclQuery(link.HRef.ToString()))
It's also not clear why you've got lines like this:
Dim calendarEntry As New AtomEntry
Why are you calling the parameterless constructor for AtomEntry? Why are you declaring the variable outside the ForEach loop at all? Just use:
For Each calendarEntry As AtomEntry In calFeed.Entries
EDIT: For the other issue, I think you just need:
Dim myEventFeed As CType(service.Query(myQuery), EventFeed)
If you could provide the full method, that would help.

I'm not sure if it works, but this is the direct c#->VB.Net-Translation from developerfusion, the syntax seems to be correct. Only as a hint for your next problems ;)
Shared Sub RetrieveAcls(ByVal service As CalendarService)
Dim query As New FeedQuery()
query.Uri = New Uri("http://www.google.com/calendar/feeds/testingforfinals#gmail.com")
Dim calFeed As AtomFeed = service.Query(query)
Console.WriteLine()
Console.WriteLine("Sharing permissions for your calendars:")
' Retrieve the meta-feed of all calendars.
For Each calendarEntry As AtomEntry In calFeed.Entries
Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text)
Dim link As AtomLink = calendarEntry.Links.FindService(AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, Nothing)
' For each calendar, retrieve its ACL feed.
If Not link Is Nothing Then
Dim feed As AclFeed = service.Query(New AclQuery(link.HRef.ToString()))
For Each aclEntry As AclEntry In feed.Entries
Console.WriteLine(vbTab & "Scope: Type={0} ({1})", aclEntry.Scope.Type, aclEntry.Scope.Value)
Console.WriteLine(vbTab & "Role: {0}", aclEntry.Role.Value)
Next
End If
Next
End Sub

Related

Consuming Webservice - Sending Signature- Error X509Certificate2 type was not expected

I'm consume an external webservice for sending data, using a web application in asp.net and Visual Studio 2010. The
sending of data must be digitally signed using a digital signature. The webservice contains the Signature class, where I
can fill all required values ​​(SignedInfo, SignatureValue, KeyInfo).
I'm trying to fill the KeyInfo structure with the certificate like this:
Dim Sig As New RSP.SignatureType
(...)
Sig.SignedInfo = Sig_info
(...)
Sig.SignatureValue = Sig_value
Dim rspKey_info As New RSP.KeyInfoType()
Dim rspX509 As New RSP.X509DataType()
Dim arrCertificate As X509Certificate2()
arrCertificate = myF.ReturnCertificateCC()
rspKey_info.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspKey_info.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspKey_info.Items = New Object(0) {}
rspX509.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
Sig.KeyInfo = rspKey_info
xmlString = myF.SerializeAnObject(Sig)
When I try to serialize the Signature Object, an error occur:
"Error generating the XML document."
InnerException:
"{ " The System.Security.Cryptography.X509Certificates.X509Certificate2 type was not expected . Use XmlInclude or
SoapInclude attribute to specify types that are not known statically. "}"
Public Function SerializeAnObject(ByVal obj As Object) As String
Dim doc As System.Xml.XmlDocument = New XmlDocument()
Dim serializer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(obj.GetType())
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
Try
serializer.Serialize(stream, obj)
stream.Position = 0
doc.Load(stream)
Return doc.InnerXml
Catch ex As Exception
Return ""
Finally
stream.Close()
stream.Dispose()
End Try
'#utilização
'dim xmlObject As string = SerializeAnObject(myClass)
End Function
Please help me...
I'm at several days trying to solve this...
Thanks in advance!
Regards!
rspX509.ItemsElementName = New RSP.ItemsChoiceType(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType.X509Certificate
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
rspKey_info.Items(0) = rspX509

getting an exception while using DirectoryServices object

I am using Active Directory to authenticate a user logging into an ASP.NET web site on a corporate intranet. I am getting an error of "handle is invalid" on the following line of code:
Dim entry As DirectoryEntry = New DirectoryEntry(path, domainAndUsername, Password)
Here is my code I am using to authenticate.
Dim entry As DirectoryEntry = New DirectoryEntry(path, domainAndUsername, Password)
Try
'Bind to the native AdsObject to force authentication.
Dim obj As Object = entry.NativeObject
Dim search As DirectorySearcher = New DirectorySearcher(entry)
search.Filter = "(SAMAccountName=" & Username & ")"
search.PropertiesToLoad.Add("cn")
Dim result As SearchResult = search.FindOne()
If (result Is Nothing) Then
Return False
End If
'Update the new path to the user in the directory.
'_path = result.Path
'_filterAttribute = CType(result.Properties("cn")(0), String)
Catch ex As Exception
Throw New Exception("Error authenticating user. " & ex.Message)
End Try
How do I track down this exception? Visual Studio says it is a CryptographicException
Thanks
Assuming you are on .NET 3.5.... and thinking the code translates well to VB you could use built-in method.
public bool isValidUser(string password,string username,string domain)
{
var isValid = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
{
isValid = pc.ValidateCredentials(username, password);
}
return isValid;
}
I know it does not answer question as such, but could avoid getting the exception in the first place

Getting Email address from Active Directory

All --
I am able to retieve the FullName value
I am trying to retrieve an email address from Active Directory but using the following code in my ASP.Net Web Forms project that is using Windows Authentication:
Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')
Dim ADEntry As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry(Convert.ToString("WinNT://" + a(0) + "/" + a(1)))
Dim Name As String = ADEntry.Properties("FullName").Value.ToString()
Dim Email As String = ADEntry.Properties("mail").Value.ToString()
when I get to the line of code where I'm try to retrieve the email address I get an "Object reference not set to an instance of an object." error. I have tried using EmailAddress, E-Mail. I think the problem is that I am simply using the wrong keyword. I am able to retrieve the FullName value.
Thanks to Davide Piras who send me this link, I found a suitable solution:
Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')
Dim dc As PrincipalContext = New PrincipalContext(ContextType.Domain, "DomainName")
Dim adUser As UserPrincipal = UserPrincipal.FindByIdentity(dc, a(1))
Dim Email As String = adUser.EmailAddress
This code works for me..
Reference to System.DirectoryServices.AccountManagement
static string GetADUserEmailAddress(string username)
{
using (var pctx = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, username))
{
return up != null && !String.IsNullOrEmpty(up.EmailAddress) ? up.EmailAddress : string.Empty;
}
}
}
to use it:
lblEmail.Text = GetADUserEmailAddress(Request.ServerVariables["AUTH_USER"]);

SQL Dataset to JSON

Alright I have been trying to figure this out and I read the MSDN page on the JavaScriptSerializer. However, I still can't figure out how to get this to work on an asp.net page. I want to convert my dataset into a json string so I can graph it using FLOT(graphing tool)
THIS MADE IT WORK THANKS FOR YOUR HELP GUYS: this is in vb.net for future people
Imports System.Web.Script.Serialization
....
Dim myObject = dataset.GetXml()
Dim jsonString = (New JavaScriptSerializer()).Serialize(myObject)
Reference the assembly System.Web.Extensions.dll and then do this:
using System.Web.Script.Serialization;
....
var myObject = ... your stuff ...
var jsonString = new JavaScriptSerializer().Serialize(myObject);
Check out the MSDN page for more info.
I did the following when I was working on a Project using PlotKit. I create a webservice to return the data and set the response format to Jason...this was while ago...should also work in 3.5
Here is a sample
<WebMethod()> _
<Script.Services.ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
Public Function GetSales(ByVal a As String) As Generic.List(Of Sale)
Dim _conn As SqlConnection = New SqlConnection(connstr)
Dim _dr As SqlDataReader
Try
Dim _cmd As SqlCommand = New SqlCommand("select * from sales", _conn)
_conn.Open()
_dr = _cmd.ExecuteReader(CommandBehavior.CloseConnection)
If _dr.HasRows Then
Dim s As Sale
Dim c As New Generic.List(Of Sale)
While _dr.Read
s = New Sale
With s
.Month = _dr("monthname")
.TheSale = _dr("sale")
End With
c.Add(s)
End While
Return c
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
_conn.Close()
End Try
End Function
End Class
Here is the object class...notice I am serializing the object.
<Serializable()> _
Public Class Sale
Private _month As String
Private _sale As String
Public Property Month() As String
Get
Return _month
End Get
Set(ByVal value As String)
_month = value
End Set
End Property
Public Property TheSale() As String
Get
Return _sale
End Get
Set(ByVal value As String)
_sale = value
End Set
End Property
End Class
Check out the DataContractJsonSerializer, and this article on MSDN
public static string DStoJSON(DataSet ds)
{
StringBuilder json = new StringBuilder();
foreach (DataRow dr in ds.Tables[0].Rows)
{
json.Append("{");
int i = 0;
int colcount = dr.Table.Columns.Count;
foreach (DataColumn dc in dr.Table.Columns)
{
json.Append("\"");
json.Append(dc.ColumnName);
json.Append("\":\"");
json.Append(dr[dc]);
json.Append("\"");
i++;
if (i < colcount) json.Append(",");
}
json.Append("\"}");
json.Append(",");
}
return json.ToString();
}
Probably most useful to you is the dataset loop instead of the stringbuilder. You could loop these into an object, then use the javascript serializer library.
Or even better, if you are using asp.net mvc, you can just do this:
return Json(List<myobject>, JsonRequestBehavior.AllowGet);
but this way is quick & easy! -- I didn't quite test this! the appended comma might be wrong (or code can be improved) and the final row comma needs to be handled
I use the mvc way & never looked back :)

Catching errors or exceptions

I built a mashup of google maps and weather.com and everytime one of these server is not responding my application hangs up too.What do you think I can do to prevent or minimize hanging up of my web apps?Hanging up like you can't navigate away from that page....
I got this code on my app code to access the weather service;
Public Class WeatherIn
Private _path As String
Private _cachedFile As String
Public Sub New(ByVal path As String)
_path = path
_cachedFile = String.Format("{0}\WeatherInCache.xml", _path)
End Sub
Public Function GetWeather(ByVal arg As String) As String
Return _getWebWeather(arg)
End Function
Private Function _getCachedWeather() As String
Dim str As String = String.Empty
Using reader As New StreamReader(_cachedFile)
str = reader.ReadToEnd()
End Using
Return str
End Function
Private Function _getWebWeather(ByVal arg As String) As String
Dim baseUrl As String = "http://xoap.weather.com/weather/local/{0}?cc=*&dayf=5&link=xoap&prod=xoap&par={1}&key={2}"
Dim jane As String = arg
Dim james As String = "api key"
Dim john As String = "another api key"
Dim url As String = String.Format(baseUrl, jane, james, john)
Using client As New WebClient()
Try
Dim xml As New XmlTextReader(client.OpenRead(url))
Dim xslt As New XslCompiledTransform()
xslt.Load(_path + "/Pathto.xslt")
Using writer As New StreamWriter(_cachedFile)
xslt.Transform(xml, Nothing, writer)
End Using
Return _getCachedWeather()
Catch exception As WebException
Dim xmlStr As String = "<errorDoc>"
xmlStr += "<alert>An Error Occurred!</alert>"
xmlStr += [String].Format("<message>{0}</message>", exception.Message)
xmlStr += "</errorDoc>"
Dim doc As New XmlDocument()
doc.LoadXml(xmlStr)
Dim reader As New XmlNodeReader(doc)
Dim xslt As New XslCompiledTransform()
xslt.Load(_path + "/Pathto.xslt")
Dim resultDocument As New XmlDocument()
Using writer As XmlWriter = resultDocument.CreateNavigator().AppendChild()
xslt.Transform(reader, DirectCast(Nothing, XsltArgumentList), writer)
End Using
Return resultDocument.OuterXml
End Try
End Using
End Function
Then I used the class above on my page where I display the weather like this:
'specific zip code or could be retrieved from querystring for dynamic retrieval
var jay="94576"
Dim weather As New WeatherIn(Server.MapPath(String.Empty))
Dim weatherData As String = weather.GetWeather(jay)
Response.ContentType = "text/xml"
Response.CacheControl = "no-cache"
Response.Write(weatherData)
which I retrieve the data and write on the page through javascript.Most of the time its the weather.com that goes down.I got no problem with google map its reliable....anybody got a solution why my page hangs up too if the remote server is not responding?The mashup is running smoothly if the remote server is responding...
When depending on external web services it is best to load asynchronously so that if one of them is slow you can show some kind of loading spinner to the page viewer. If it fails your page could simply report that reading from the web server failed and to try again later.
In this case I would load up the page with the Google map in place and then make an AJAX request for the Weather data.

Resources