VS 2010 WPF Google API Calender V3 Insert Events - wpf

I have created a WPF Application in VS 2010 and user the Google API V3
I am facing the issue in
var CalEvt = mCalendarService.Events.Insert(new Event()
{
Description = item.Body.Substring(0, Math.Min(30, item.Body.Length)),
Start = new EventDateTime { DateTime = item.DueDateStart.ToString("o") },
End = new EventDateTime { DateTime = item.DueDateEnd.ToString("o") },
ETag = item.ExtractItemID.ToString(),
Reminders = new Event.RemindersData() { Overrides = l, UseDefault = false }
}, item.ExtractItemID.ToString()).Execute();
I am getting exception specified value is not in valid quoted string.
For Authentication I have used the below code
var auth = new OAuth2Authenticator(provider, GetAuthorization);
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.Authenticator = auth;
mCalendarService = new Google.Apis.Calendar.v3.CalendarService(initializer);

Related

How to add attributes for custom claims types for IdP Saml2 response

I converted the IdPInitiatedController example code for my WebForms project. Although I don't get compiler or runtime error, I still cannot seem to get the manually created claims added to the Saml2AuthnResponse object after setting the claims identity. Is there another way to add attributes to the SAML response? The app uses forms authentication; and the credentials are in a SQL database. That's why I don't have Windows Identity.
' SSO CODE BEHIND
...
Dim binding = New Saml2PostBinding With {
.RelayState = String.Format("RPID={0}", Uri.EscapeDataString(serviceProviderRealm))
}
Dim config = New Saml2Configuration With {
.Issuer = "company.stage.app",
.SingleSignOnDestination = New Uri(ConfigurationManager.AppSettings.Get("appValue")),
.SigningCertificate = CertificateUtil.Load(X509Certificates.StoreName.TrustedPeople, X509Certificates.StoreLocation.LocalMachine, X509Certificates.X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ThatKey")),
.SignatureAlgorithm = Saml2SecurityAlgorithms.RsaSha256Signature
}
Dim samlResponse = New Saml2AuthnResponse(config) With {
.Status = Saml2StatusCodes.Success
}
_ssoService.AddAttributes(samlResponse, currentUser)
binding.Bind(samlResponse) ' NO ATTRIBUTES WERE ADDED
Me.SAMLResponse.Value = binding.XmlDocument.InnerXml
Me.RelayState.Value = binding.RelayState
frmSSO.Action = config.SingleSignOnDestination.AbsoluteUri()
frmSSO.Method = "POST"
Public Sub AddAttributes(ByRef samlResponse As Saml2AuthnResponse, ByVal currentUser As CurrentUser)
Dim acctContact As CoveredInsuredDto = _coveragesService.GetAccountPointOfContact(currentUser.getControlNo())
If Not IsNothing(acctContact) Then
' Adding Attributes as claims
Dim claimIdentity = New ClaimsIdentity(Me.BuildClaims(currentUser, acctContact))
samlResponse.NameId = New IdentityModel.Tokens.Saml2NameIdentifier(acctContact.Name)
samlResponse.ClaimsIdentity = claimIdentity
End If
End Sub
Private Function BuildClaims(ByVal currentUser As CurrentUser, ByVal acctContact As CoveredInsuredDto) As IEnumerable(Of Claim)
Dim claims = New List(Of Claim)
If Not IsNothing(acctContact) Then
claims.Add(New Claim("FIRST_NAME", acctContact.FirstName))
claims.Add(New Claim("LAST_NAME", acctContact.LastName))
End If
Return claims.ToList()
End Function
The problem is that you have forgot the var token = response.CreateSecurityToken(appliesToAddress); line which is actually the line creating the token.
The ASP.NET Core IdP Initiated sample code:
public IActionResult Initiate()
{
var serviceProviderRealm = "https://some-domain.com/some-service-provider";
var binding = new Saml2PostBinding();
binding.RelayState = $"RPID={Uri.EscapeDataString(serviceProviderRealm)}";
var config = new Saml2Configuration();
config.Issuer = "http://some-domain.com/this-application";
config.SingleSignOnDestination = new Uri("https://test-adfs.itfoxtec.com/adfs/ls/");
config.SigningCertificate = CertificateUtil.Load(Startup.AppEnvironment.MapToPhysicalFilePath("itfoxtec.identity.saml2.testwebappcore_Certificate.pfx"), "!QAZ2wsx");
config.SignatureAlgorithm = Saml2SecurityAlgorithms.RsaSha256Signature;
var appliesToAddress = "https://test-adfs.itfoxtec.com/adfs/services/trust";
var response = new Saml2AuthnResponse(config);
response.Status = Saml2StatusCodes.Success;
var claimsIdentity = new ClaimsIdentity(CreateClaims());
response.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent);
response.ClaimsIdentity = claimsIdentity;
var token = response.CreateSecurityToken(appliesToAddress);
return binding.Bind(response).ToActionResult();
}
private IEnumerable<Claim> CreateClaims()
{
yield return new Claim(ClaimTypes.NameIdentifier, "some-user-identity");
yield return new Claim(ClaimTypes.Email, "some-user#domain.com");
}

Programming c# code to create a SSRS data driven subscription

I have SSRS report with parameters under SQL Reporting service 2012 standard edition. I like to export to excel and send as an attachment in the email to different receipt and receipt comes from some SQL query that means it is dynamic.
Data-driven subscription can do this but I have SQL Server 2012 Standard edition which does not support data-driven subscription and I can not upgrade, so I am looking for any code which can do the similar job like a data-driven subscription.
I found this link which has the solution to my issue.
http://jaliyaudagedara.blogspot.com/2012/10/creating-data-driven-subscription.html
when I try this code under visual studio 2015 "Class Library" project by adding service reference "http://mylocalserver:81/reportserver/ReportService2010.asmx" I am getting an error on this line of code.
ReportingService2010SoapClient rs= new ReportingService2010SoapClient();
Additional information about the error: Could not find default endpoint element that references contract 'ReportService2010.ReportingService2010Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
After spending enough time to make it work with "Class Library" project, I decided to do the code under web service project by adding the web service reference. with some trial and error finally, I got the working code here under web service project. below code works on my local machine which has Sql server 2012 enterprise edition but it gives me the same error saying "Data-driven subscriptions to reports" is not supported in this edition of Reporting Services" on my company server which has SQL server 2012 standard edition.
public void DoWork()
{
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = CredentialCache.DefaultCredentials;
// rs.Url = "http://mylocalserver:81/reportserver/ReportService2010.asmx";
rs.Url = "http://companyserver/reportserver/ReportService2010.asmx";
var reportPath = "/CYTYC Reports/";
string report = $"{reportPath}AllContactCIPPointsReport";
string description = "Programmatic Data Driven Subscription \"Report Server Email\" ";
//set extension as Windows File Share
ExtensionSettings settings = new ExtensionSettings();
settings.Extension = "Report Server Email";
// Set the extension parameter values.
var extensionParams = new ParameterValueOrFieldReference[8];
// var to = new ParameterFieldReference { ParameterName = "TO", FieldAlias = "PARAMS" }; // Data-driven.
var to = new ParameterValue { Name = "TO", Value = "example#gmail.com" }; // Data-driven.
extensionParams[0] = to;
var replyTo = new ParameterValue { Name = "ReplyTo", Value = "example#gmail.com" };
extensionParams[1] = replyTo;
var includeReport = new ParameterValue { Name = "IncludeReport", Value = "False" };
extensionParams[2] = includeReport;
var renderFormat = new ParameterValue { Name = "RenderFormat", Value = "HTML4.0" };
extensionParams[3] = renderFormat;
var priority = new ParameterValue { Name = "Priority", Value = "NORMAL" };
extensionParams[4] = priority;
var subject = new ParameterValue { Name = "Subject", Value = "Subsribed Report" };
extensionParams[5] = subject;
var comment = new ParameterValue { Name = "Comment", Value = "Here is the link to your report." };
extensionParams[6] = comment;
var includeLink = new ParameterValue { Name = "IncludeLink", Value = "True" };
extensionParams[7] = includeLink;
settings.ParameterValues = extensionParams;
// Create the data source for the delivery query.
var delivery = new DataSource { Name = "" };
var dataSourceDefinition = new DataSourceDefinition
{
ConnectString = "Data Source=CYTYC-LIVE;Initial Catalog=yourdatabasename",
CredentialRetrieval = CredentialRetrievalEnum.Store,
Enabled = true,
EnabledSpecified = true,
Extension = "SQL",
ImpersonateUserSpecified = false,
UserName = "username",
Password = "password"
};
delivery.Item = dataSourceDefinition;
// Create the data set for the delivery query.
var dataSetDefinition = new DataSetDefinition
{
AccentSensitivitySpecified = false,
CaseSensitivitySpecified = false,
KanatypeSensitivitySpecified = false,
WidthSensitivitySpecified = false
};
var queryDefinition = new QueryDefinition
{
CommandText = #"Your select * from Query",
CommandType = "Text",
Timeout = 45,
TimeoutSpecified = true
};
dataSetDefinition.Query = queryDefinition;
var results = new DataSetDefinition();
var oServerInfoHeader = new ServerInfoHeader();
var oTrustedUserHeader = new TrustedUserHeader();
bool changed;
string[] paramNames;
try
{
results = rs.PrepareQuery(delivery, dataSetDefinition, out changed, out paramNames);//.PrepareQuery(oTrustedUserHeader, delivery, dataSetDefinition, out results, out changed,out paramNames);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var dataRetrieval = new DataRetrievalPlan { DataSet = results, Item = dataSourceDefinition };
// Set the event type and match data for the delivery.
const string eventType = "TimedSubscription";
const string matchData = "<ScheduleDefinition><StartDateTime>2018-06-01T14:00:00-07:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Monday>True</Monday><Tuesday>True</Tuesday><Wednesday>True</Wednesday><Thursday>True</Thursday><Friday>True</Friday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>";
//const string eventType = "SnapshotUpdated";
//const string matchData = null;
//// Set the report parameter values.
//var parameters = new ParameterValueOrFieldReference[1];
//// i am retrieving value EMAIL from database and I am passing that value as my report parameter value
//var reportparam = new ParameterFieldReference { ParameterName = "yourreportparametername", FieldAlias = "PARAMS" }; // Data-driven.
//parameters[0] = reportparam;
var parameters = new ParameterValue[1];
var reportparam = new ParameterValue {Name = "yourreportparametername", Value = "yourreportparametervalue"};
parameters[0] = reportparam;
string subscriptionId = "";
try
{
subscriptionId = rs.CreateDataDrivenSubscription(report, settings, dataRetrieval, description, eventType, matchData, parameters);
//(oTrustedUserHeader, report, settings, dataRetrieval,description, eventType, matchData, parameters,out subscriptionId);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(ex.Detail.InnerText.ToString(CultureInfo.InvariantCulture));
}
}
You don't say why you need the Data Driven subscriptions - a regular SSRS subscription can e-mail an Excel report with set or default parameters.
There aren't any third party tools that I know of that emulates the Data Driven subscriptions but there have been some users who have created their own.
If you just want to trigger a subscription based on criteria, you could just use an SSIS job to run the query to determine whether to send or not and trigger the subscription if so.
Something like Data Driven Subscriptions SSRS Standard Edition 2008
If you need something more complicated (like varying TO/CC recipients, changing parameter values...), you'll need to do a bit more programming. Here's a couple things to get started with the theory and code:
https://www.mssqltips.com/sqlservertip/4249/simulate-reporting-services-data-driven-subscriptions-on-unsupported-editions/
http://www.sqlservercentral.com/articles/Reporting+Services+(SSRS)/163119/

google calendar v3 api with OAuth 2.0 service account return empty result

I got zero results from Calendar EventsResource.ListRequest with ServiceAccountCredential. And same code works properly with UserCredential. I don't get any exception or error, just the Events.Items count is always zero when I try to auth with key.p12 file.
I also set up the API client access for https://www.googleapis.com/auth/calendar on the clientID of this service account in domain admin security setting.
Any ideas? Thanks
--------------------------------Here is my code:
static UserCredential getUserCredential()
{
UserCredential credential;
using (var stream = new FileStream(#"client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { CalendarService.Scope.CalendarReadonly },
"user", CancellationToken.None, new FileDataStore("carol test")).Result;
}
return credential;
}
static ServiceAccountCredential getServiceAccountCredential()
{
//Google authentication using OAuth for single calendar
string serviceAccountEmail = "xx...#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"clientPrivateKey.p12", "notasecret",
X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new
ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes =
new[] { CalendarService.Scope.Calendar }
}.FromCertificate(certificate));
return credential;
}
static void Main(string[] args)
{
// Create the service.
BaseClientService.Initializer initializer = new
BaseClientService.Initializer();
//initializer.HttpClientInitializer = getUserCredential();
initializer.HttpClientInitializer = getServiceAccountCredential();
initializer.ApplicationName = "Google Calendar Sample";
CalendarService calservice = new CalendarService(initializer);
List<CalendarEvent> calendarEvents = new List<CalendarEvent>();
try
{
EventsResource.ListRequest req = calservice.Events.List("primary"); // Is it correct to use "primary" as calendarID?
req.TimeMin = new DateTime(2014, 12, 1);
req.TimeMax = new DateTime(2014, 12, 6);
req.SingleEvents = true;
req.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Events events = req.Execute(); // always empty for ServiceAccount auth, but getting results for user credential auth
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // didnot get exception either way
}
}
Value for events (When use UserCredential)
{Google.Apis.Calendar.v3.Data.Events}
AccessRole: "owner"
DefaultReminders: Count = 1
Description: null
ETag: "\"1417813280083000\""
Items: Count = 2
Kind: "calendar#events"
NextPageToken: null
NextSyncToken: null
Summary: "myemail#mydomain.net"
TimeZone: "America/Los_Angeles"
Updated: {12/5/2014 1:01:20 PM}
UpdatedRaw: "2014-12-05T21:01:20.083Z"
Value for events (when use service account key.p12 auth)
{Google.Apis.Calendar.v3.Data.Events}
AccessRole: "owner"
DefaultReminders: Count = 0
Description: null
ETag: "\"1417747728066000\""
Items: Count = 0
Kind: "calendar#events"
NextPageToken: null
NextSyncToken: null
Summary: "xxxx#developer.gserviceaccount.com"
TimeZone: "UTC"
Updated: {12/4/2014 6:48:48 PM}
UpdatedRaw: "2014-12-05T02:48:48.066Z"

How to unit test Soap service access from Crm 2011 Silverlight application?

In a Silverlight 5 application in Dynamics CRM 2011 I access the Organization Service of the CRM to query for entity Metadata. I wrote a service that takes an entity name and returns a list of all its fields.
How can I test this service method automatically? The main problem is how to obtain a reference to the organization service from a Silverlight app that does not run in the context of the CRM.
My Service method looks like this:
public IOrganizationService OrganizationService
{
get
{
if (_organizationService == null)
_organizationService = SilverlightUtility.GetSoapService();
return _organizationService;
}
set { _organizationService = value; }
}
public async Task<List<string>> GetAttributeNamesOfEntity(string entityName)
{
// build request
OrganizationRequest request = new OrganizationRequest
{
RequestName = "RetrieveEntity",
Parameters = new ParameterCollection
{
new XrmSoap.KeyValuePair<string, object>()
{
Key = "EntityFilters",
Value = EntityFilters.Attributes
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "RetrieveAsIfPublished",
Value = true
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "LogicalName",
Value = "avobase_tradeorder"
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "MetadataId",
Value = new Guid("00000000-0000-0000-0000-000000000000")
}
}
};
// fire request
IAsyncResult result = OrganizationService.BeginExecute(request, null, OrganizationService);
// wait for response
TaskFactory<OrganizationResponse> tf = new TaskFactory<OrganizationResponse>();
OrganizationResponse response = await tf.FromAsync(
OrganizationService.BeginExecute(request, null, null), iar => OrganizationService.EndExecute(result));
// parse response
EntityMetadata entities = (EntityMetadata)response["EntityMetadata"];
return entities.Attributes.Select(attr => attr.LogicalName).ToList();
}
Edit:
I can create and execute unit tests with Resharper and AgUnit. Thus, the problem is not how to write a unit test in general.
I have tweaked the GetSoapService from the standard Microsoft SDK to accept a fall back value. This means no codes changes are needed when debugging in visual studio and running in CRM. Anyway here it is
public static IOrganizationService GetSoapService(string FallbackValue = null)
{
Uri serviceUrl = new Uri(GetServerBaseUrl(FallbackValue)+ "/XRMServices/2011/Organization.svc/web");
BasicHttpBinding binding = new BasicHttpBinding(Uri.UriSchemeHttps == serviceUrl.Scheme
? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.SendTimeout = TimeSpan.FromMinutes(20);
IOrganizationService ser =new OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
return ser;
}
public static string GetServerBaseUrl(string FallbackValue = null)
{
try
{
string serverUrl = (string)GetContext().Invoke("getClientUrl");
//Remove the trailing forwards slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
{
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
}
return serverUrl;
}
catch
{
//Try the old getServerUrl
try
{
string serverUrl = (string)GetContext().Invoke("getServerUrl");
//Remove the trailing forwards slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
{
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
}
return serverUrl;
}
catch
{
return FallbackValue;
}
}

Exchange Web Services Create Meeting Request Working Example

Is there a working example anywhere of how to create a meeting request using EWS for Exchange 2007 using C#? Which properties are required? I have added a web service reference and can connect to create and send various items but keep getting the error "Set action is invalid for property." on the response messages. It never says what property is invalid
var ews = new ExchangeServiceBinding {
Credentials = new NetworkCredential("user", "pass"),
Url = "https://servername/ews/exchange.asmx",
RequestServerVersionValue = new RequestServerVersion {
Version = ExchangeVersionType.Exchange2007}
};
var startDate = new DateTime(2010, 9, 18, 16, 00, 00);
var meeting = new CalendarItemType {
IsMeeting = true,
IsMeetingSpecified = true,
Subject = "test EWS",
Body = new BodyType {Value = "test body", BodyType1 = BodyTypeType.HTML},
Start = startDate,
StartSpecified = true,
End = startDate.AddHours(1),
EndSpecified = true,
MeetingTimeZone = new TimeZoneType{
TimeZoneName = TimeZone.CurrentTimeZone.StandardName, BaseOffset = "PT0H"},
Location = "Meeting",
RequiredAttendees = new [] {
new AttendeeType{Mailbox =new EmailAddressType{
EmailAddress ="test1#domain.com",RoutingType = "SMTP"}},
new AttendeeType{Mailbox =new EmailAddressType{
EmailAddress ="test2#domain.com",RoutingType = "SMTP"}}
}
};
var request = new CreateItemType {
SendMeetingInvitations =
CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy,
SendMeetingInvitationsSpecified = true,
SavedItemFolderId = new TargetFolderIdType{Item = new DistinguishedFolderIdType{
Id=DistinguishedFolderIdNameType.calendar}},
Items = new NonEmptyArrayOfAllItemsType {Items = new ItemType[] {meeting}}
};
CreateItemResponseType response = ews.CreateItem(request);
var responseMessage = response.ResponseMessages.Items[0];
Microsoft provides an XML example at http://msdn.microsoft.com/en-us/library/aa494190(EXCHG.140).aspx of what the message item should look like. Just setting these properties does not seem to be enough. Can someone tell me what I'm missing or point me to some better examples or documentation?
<CreateItem
xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"
SendMeetingInvitations="SendToAllAndSaveCopy" >
<SavedItemFolderId>
<t:DistinguishedFolderId Id="calendar"/>
</SavedItemFolderId>
<Items>
<t:CalendarItem>
<t:Subject>Meeting with attendee0, attendee1, attendee2</t:Subject>
<t:Body BodyType="Text">CalendarItem:TextBody</t:Body>
<t:Start>2006-06-25T10:00:00Z</t:Start>
<t:End>2006-06-25T11:00:00Z</t:End>
<t:Location>CalendarItem:Location</t:Location>
<t:RequiredAttendees>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>attendee0#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>attendee1#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:RequiredAttendees>
<t:OptionalAttendees>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>attendee2#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:OptionalAttendees>
<t:Resources>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>room0#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:Resources>
</t:CalendarItem>
</Items>
</CreateItem>
This is probably too late for you, but this for anyone else trying this.
The issue seems to be with providing the Is-Specified params. I deleted the IsMeetingSpecified and the request worked. Here's the revised CalendarItemType.
var meeting = new CalendarItemType
{
IsMeeting = true,
Subject = "test EWS",
Body = new BodyType { Value = "test body", BodyType1 = BodyTypeType.HTML },
Start = startDate,
StartSpecified = true,
End = startDate.AddHours(1),
EndSpecified = true,
MeetingTimeZone = new TimeZoneType
{
TimeZoneName = TimeZone.CurrentTimeZone.StandardName,
BaseOffset = "PT0H"
},
Location = "Room 1",
RequiredAttendees = new[] {
new AttendeeType
{
Mailbox =new EmailAddressType
{
EmailAddress ="test#test.com"
}
},
}
};

Resources