Create an Appointment with EWS in VB.NET, what am i missing? - asp.net

Hello i want to send a calendar invite to other members, how can i do that in vb.net,
i added the exchange webreference and can send a normal mail to other people.
here is what i have so far
Public Sub Einladungen()
Dim esb As New ExchangeServer.ExchangeServiceBinding
esb.Credentials = New NetworkCredential(Session("EX_UserName").ToString, Session("EX_Password").ToString)
esb.Url = Session("EX_DomainURL")
Dim appointment As CalendarItemType = New CalendarItemType
' Set properties on the appointment.
appointment.Subject = "Dentist Appointment"
appointment.Body = New BodyType
appointment.Body.BodyType1 = BodyTypeType.Text
appointment.Body.Value = "Agenda Items...."
appointment.Start = New DateTime(2012, 3, 1, 9, 0, 0)
appointment.End = appointment.Start.AddHours(2)
appointment.Location = "Conf Room"
appointment.RequiredAttendees.Add("user1#contoso.com")
appointment.RequiredAttendees.Add("user2#contoso.com")
appointment.OptionalAttendees.Add("user3#contoso.com")
' Save the appointment.
appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy)
End Sub
Visual Studio tells me that:
Add is not a member of "System.Array"
and
"Save" is not a member of "ExchangeServer.CalendarItemType"
and
The name "SendInvitationMode" is not declared
What am i missing?
Thanks in advance for your help

The problem is that you have created your own EWS proxy classes by referencing your Exchange web service directly but the sample code you have found is built using the Exchange Web Service Managed API.
So what you should do is to download the EWS Managed API, add a reference to Microsoft.Exchange.WebServices.dll, and change the beginning of your code into something similar to this:
Dim esb As New ExchangeService(ExchangeVersion.Exchange2007_SP1);
esb.Credentials = New NetworkCredential(Session("EX_UserName").ToString, Session("EX_Password").ToString)
esb.Url = Session("EX_DomainURL")
Dim appointment As new Appointment(esb);
// ... the rest of your code here.
You might want to have a look at this example:
http://msdn.microsoft.com/en-us/library/exchange/dd633661(v=exchg.80).aspx

Related

Basic Authentication with asmx web service

I'm trying to implement Basic Authorization for an ASMXweb service. I created the client as a service reference in VS2015. I'm using code in Asmx web service basic authentication as an example.
I'm entering login info in ClientCredentials as below
Dim svc As New WebServiceSoapClient()
svc.ClientCredentials.UserName.UserName = "userId"
svc.ClientCredentials.UserName.Password = "i2awTieS0mdO"
My problem is that in the Authorization HttpModule in the web service, these credentials are not being passed to module. Is there an alternate way to do this?
I found the parts answer at How to add HTTP Header to SOAP Client. I had to combine a couple of answers on that page to get it to work.
Dim svc As New WebServiceSoapClient()
Dim responseService As SoapResponseObject
Using (new OperationContextScope(svc.InnerChannel))
Dim auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("userId:i2awTieS0mdO"))
Dim requestMessage = New HttpRequestMessageProperty()
requestMessage.Headers("Authorization") = auth
OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = requestMessage
dim aMessageHeader = MessageHeader.CreateHeader("Authorization", "http://tempuri.org", auth)
OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader)
responseService = svc.ListDistricts(requestService)
End Using
One key thing to be aware of is that the soap client call has to be inside the Using statement. In the above code, this is the next to last line.

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).

Batch processing with Google Calendar V3 API

I've been working with the new google Calendar V3 API and I've coded all my class methods to process Adds, Updates, retrievals etc but I was wondering if there is a way to send a batch of adds + updates + deletes all at once rather than sending each request separately and possible exceeding the trans/sec threshold. I understand the .Batch method has been depreciated in V3 and I found another methodology that uses web services that will notify a client that changes are ready but I'm trying to do this from a .NET Winform application so it needs to be something initiated from the client and not dependent upon online services or a PUSH methodology.
Regards,
Kerry
I got this to work using the BatchRequest object:
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "My App"
Dim service = New CalendarService(initializer)
'fetch the calendars
Dim list = service.CalendarList.List().Execute().Items()
'get the calendar you want to work with
Dim calendar = list.First(Function(x) x.Summary = "{Calendar Name}")
Dim br As New Google.Apis.Requests.BatchRequest(service)
'make 5 events
For i = 1 To 5
'create a new event
Dim e As New [Event]
'set the event properties
e.Summary = "Test Event"
e.Description = "Test Description"
e.Location = "Test Location"
...
'make a request to insert the event
Dim ins As New InsertRequest(service, e, calendar.Id)
'queue the request
br.Queue(Of Dummy)(ins, AddressOf OnResponse)
Next
'execute the batch request
Dim t = br.ExecuteAsync()
'wait for completion
t.Wait()
For some reason, you can't have a deferred request without specifying a callback to the Queue method, and that method requires a generic type parameter. So I defined the following:
Class Dummy
End Class
Sub OnResponse(content As Dummy, err As Google.Apis.Requests.RequestError, index As Integer, message As System.Net.Http.HttpResponseMessage)
End Sub
With this in place, the batch inserts worked fine.

Exception thrown when using GData .NET Analytics API

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.

CA service desk web service visual basic experts

I'm working on a form that uses CA service desk web service request system, but am having trouble finding any assistance or coding examples for the service with asp.net and visual basic. I contacted their technical support, but no one on their staff has experience using it. Do you know where I could get help?
Just finished doing a vb.net webservice to CA service desk. Hopefully some of the code below can be used in your project.
Imports System.Xml
Imports Microsoft.Web.Services3
Imports Microsoft.Web.Services3.Messaging
Imports Microsoft.Web.Services3.Addressing
Partial Class _Default
Inherits System.Web.UI.Page
Dim ws1 As New USD_WebService.USD_WebService
Public sid As Integer
Public userhandle, username, password As String
Public summary, description, incident, MH, SUN As String
Public group, category, uammsg, handle As String
Dim attrVal(5), attr(1), prop(1) As String
Public requestHandle, requestNumber As String
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
ws1.Url = "http://"YOUR SERVER":8080/axis/services/USD_R11_WebService?wsdl"
'Get the Field values for the ticket (Could be done connecting to LDAP server)
username = userid1.Value 'Name from form field
password = pass1.Value 'Windows Password from form field
summary = Summary1.Value 'Summary from form field
description = desc1.Value 'Description from form field
'Get the SID from the CA Server
sid = ws1.login(username, password)
If (sid <= 0) Then
Response.Write("login failed")
Else
Response.Write("login succeeded")
End If
'Get the User ID from the CA Server
userhandle = ws1.getHandleForUserid(sid, username)
'Set the Field values to create the ticket.
'The AttrVal must be in pairs or the call will fail
'e.g. header & header details
attrVal = New String() {"customer", userhandle, "category", category, "group", group, "description", description, "summary", summary, "ZReporting_Method", "400001", "impact", "5", "type", "R"}
prop = New String() {""}
attr = New String() {"persistent_id"}
'Returned data from the CA server
requestHandle = ""
requestNumber = ""
'Send the request with the details from the form
ws1.createRequest(sid, userhandle, attrVal, prop, "", attr, requestHandle, requestNumber)
Response.Write("Ticket Number: " + requestNumber + " Created Successfully.")
'MsgBox("Ticket Number: " + requestNumber + " Created Successfully.")
MsgBox(requestHandle, 3)
'Log off the server using the SID
ws1.logout(sid)
Just remember, the attributes need to be in pairs, Label & Label Data e.g."SUMMARY" & "Summary text". You will need to import the CA WebService into the project. I'm using MS Visual Web Developer 2008 Express to create my project.
I don't use VB.net actual but this is C# code that might help you understand how you can access to CA web-service and perform select quires directly to it. you can translate to VB.net it works the same way
You can find how to use web service as pdf here
and
You can find CA Reference to web-service here it contains description on all objects you might need
webServiceName.USD_WebService wsUSD = new webServiceName.USD_WebService();
string username = "user1" , password = "password";
int sid = 0;
string userhandle = null;
XmlDocument xDoc = new XmlDocument();
sid = wsUSD.login(username, password);
userhandle = wsUSD.getHandleForUserid(sid, username);
string userEmailID = "myMail#company.com";
string[] attrs = new string[7];
attrs[0] = "type.sym";
attrs[1] = "ref_num";
attrs[2] = "open_date";
attrs[3] = "description";
attrs[4] = "status.sym";
attrs[5] = "last_mod_dt";
attrs[6] = "persistent_id";
//here is the important part
//note: 'CL' means closed
//where the cr is Object ref to SQL database
xDoc.LoadXml(wsUSD.doSelect(sid, "cr", " customer.email_address = '" + userEmailID + "' AND status != 'CL'", -1, attrs));
//here is other queries you can use the same way
xDoc.LoadXml(wsUSD.doSelect(sid, "cr", " customer.userid = '" + userEmailID + "'", -1, attrs));
wsUSD.logout(sid);
Add a web reference to the web services wsdl in Visual Studio (under Solutions Explorer, right click on References and click Add Web Reference).
If you are moving across environments I would recommend a .xml config file to specify the endpoint url to the WSDL.
Here is what it might look like in C# based on my use of it:
using webreference1;
public class WSExample
{
USD_WebService ws = new USD_WebService();
//set url when creating web reference to avoid this step
ws.Url = "http://yoursite.com/webservice?wsdl";
}
Now the ws object will allow you to access all of the methods specified in the wsdl. You can use the createRequest() method to create a request.
CA provides a Technical Reference guide, which includes web service methods. Consult their support site. If this is something you use frequently, I would recommend creating wrappers to abstract away the use of blank arrays.
Feel free to contact me if you need any additional support
A few months ago I wrote some PowerShell functions to look at CA Service Catalog and tell me basic things, like requests that were pending my actions, update request form details, etc. To do that I saved the wsdl xml file, cooked a .cs and then a compiled a .dll file.
Normally, I'd use this PowerShell function to compile a dll:
function get-freshDll {
param($url,$outDir)
$wsdl = #(Resolve-Path "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\x64\wsdl.exe")[0].Path
$cscPath = #(Resolve-Path "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe")[0].Path
& $wsdl $url /out:$outDir"\WebService.cs"
& $cscPath /t:library /out:WebService.dll $outDir"\WebService.cs"
}
which works for the other CA stuff, just not Service Catalog (which is what I care about). For Service Catalog you have to save the wsdl file and chop out the DataHandler node (maybe someone else knows how to work with it, I gave up). After that the basic flow to create the dll is the same (just point wsdl.exe at the saved/edited wsdl file instead of the url) and then compile the dll with csc.exe. Add a reference for this dll to your C#/VB project. Working in Service Desk the PowerShell function above should work just like it is, just feed it the wsdl url and the dir where you want the dll to end up (you may also need to change the directories for your specific versions of netfx and .net).
Once the dll is mounted in your project you can use the Object Browser to see the methods that it contains. I'm still working it out myself (hence I found this post, and if you think Service Desk is hard to find examples for, try Service Catalog!). I don't have a good reference for Service Desk, sorry, but this is the .cs code (almost literally) that got the getRequests and getPendingActions methods to populate a GridView from the Service Catalog API. The aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</asp:Content>
Keep in mind this is from a web app so there's a line missing from above:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" .... blahblah #%>
The .cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net.Http.Formatting;
namespace MyNamespace
{
public partial class MyRequestStuff : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
RequestServiceImplService reqService = new RequestServiceImplService();
reqService.CookieContainer = new System.Net.CookieContainer();
string user = "userid", password = "password", unit = "Unit";
reqService.Url = "http://servicecatalog/usm/services/RequestService?wsdl";
string session = reqService.logIn(user, password, unit);
var myRequests = reqService.getRequests(session);
var myPending = reqService.getPendingActions(session, user);
reqService.logOut(session);
GridView1.DataSource = myPending;
GridView1.DataBind();
GridView2.DataSource = myRequests;
GridView2.DataBind();
}
}
}
Like baultista and za7ef mention in their code, you'll need to create an USD_WebService object (instead of RequestServiceImplService) and use the methods available there (like getStatuses()), the functionality will be pretty similar (they are in PowerShell). I know it's not quite on point (e.g. SC instead of SD) but I hope that you or someone else finds this example useful.

Resources