public static DateTime CreateDateFromWhenCommand(IAuthenticatedWho authenticatedWho, String when, String adminEmail)
        {
            DateTime whenDate = DateTime.Now;
            String[] whenConfig = null;
            Int32 days = 0;

            // Supported when commands are "n days" or "n day" and "now"
            if (when.IndexOf("day", StringComparison.InvariantCultureIgnoreCase) > 0)
            {
                // Split the when by the space
                whenConfig = when.Split(' ');

                // Check to make sure the split was OK
                if (whenConfig.Length > 0)
                {
                    // Check to make sure the first parameter in the split is the number of days
                    if (Int32.TryParse(whenConfig[0], out days) == false)
                    {
                        // send the author an error message
                    }

                    // Add the days to our task
                    whenDate = whenDate.AddDays(days);
                }
            }
            else if (when.Trim().Equals("now", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                // Use the date as of right now
                whenDate = DateTime.Now;
            }
            else
            {
                // throw and error as this is not a supported command
                String errorMessage = "The provided 'when' command is not valid: " + when;

                ErrorUtils.SendAlert(authenticatedWho, ErrorUtils.ALERT_TYPE_FAULT, adminEmail, "SalesforcePlugin", errorMessage);

                throw ErrorUtils.GetWebException(HttpStatusCode.InternalServerError, errorMessage);
            }

            return whenDate;
        }
        public static ObjectAPI CreateUserObject(IAuthenticatedWho authenticatedWho)
        {
            ObjectAPI userObject = null;

            userObject = new ObjectAPI();
            userObject.developerName = ManyWhoConstants.MANYWHO_USER_DEVELOPER_NAME;
            userObject.properties = new List<PropertyAPI>();

            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_DIRECTORY_ID, authenticatedWho.DirectoryId));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_DIRECTORY_NAME, authenticatedWho.DirectoryName));

            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_COUNTRY, null));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_EMAIL, authenticatedWho.Email));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_USERNAME, authenticatedWho.Email));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_FIRST_NAME, null));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_LANGUAGE, null));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_LAST_NAME, null));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_LOCATION, null));
            userObject.properties.Add(CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_USER_ID, authenticatedWho.UserId));

            return userObject;
        }
Exemple #3
0
        public ServiceResponseAPI InvokeNotifyUsers(INotifier notifier, IAuthenticatedWho authenticatedWho, ServiceRequestAPI serviceRequest)
        {
            ChatterPostedMessage     chatterPostedMessage     = null;
            ChatterNewMessageSegment chatterNewMessageSegment = null;
            ServiceResponseAPI       serviceResponse          = null;
            SforceService            sforceService            = null;
            String groupAuthenticationToken = null;
            String authenticationUrl        = null;
            String username       = null;
            String password       = null;
            String securityToken  = null;
            String chatterBaseUrl = null;
            String adminEmail     = null;
            String endpointUrl    = null;
            String message        = null;

            // Grab the configuration values from the service request
            authenticationUrl = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_AUTHENTICATION_URL, serviceRequest.configurationValues, true);
            username          = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_USERNAME, serviceRequest.configurationValues, true);
            password          = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_PASSWORD, serviceRequest.configurationValues, true);
            securityToken     = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_SECURITY_TOKEN, serviceRequest.configurationValues, false);
            chatterBaseUrl    = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_CHATTER_BASE_URL, serviceRequest.configurationValues, true);
            adminEmail        = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_ADMIN_EMAIL, serviceRequest.configurationValues, true);

            if (serviceRequest.authorization != null)
            {
                Boolean postMade = false;

                // Get the message from the inputs
                message = ValueUtils.GetContentValue("Post", serviceRequest.inputs, true);

                // Check to see if we have any group authorization - if so, we post to those groups
                if (serviceRequest.authorization.groups != null &&
                    serviceRequest.authorization.groups.Count > 0)
                {
                    foreach (GroupAuthorizationGroupAPI groupAuthorization in serviceRequest.authorization.groups)
                    {
                        // For group posts, we post as the admin, not as the user - as it's very likely the user does not have permissions to post
                        if (groupAuthenticationToken == null ||
                            groupAuthenticationToken.Trim().Length == 0)
                        {
                            // Login as the API user
                            sforceService = SalesforceDataSingleton.GetInstance().Login(authenticatedWho, serviceRequest.configurationValues, true, false);

                            if (sforceService == null)
                            {
                                throw new ArgumentNullException("SalesforceService", "Unable to log into Salesforce.");
                            }

                            // Get the session id out as we'll use that for the oauth login
                            groupAuthenticationToken = sforceService.SessionHeaderValue.sessionId;
                        }

                        // Create the endpoint url for the group
                        endpointUrl = chatterBaseUrl + SalesforceServiceSingleton.CHATTER_URI_PART_API_VERSION + String.Format(SalesforceServiceSingleton.CHATTER_URI_PART_POSTS, groupAuthorization.authenticationId);

                        // Create a new chatter post
                        chatterPostedMessage      = new ChatterPostedMessage();
                        chatterPostedMessage.Body = new ChatterNewMessageBody();
                        chatterPostedMessage.Body.MessageSegments = new List <ChatterSegment>();

                        // Create a message segment for the actual post
                        chatterNewMessageSegment      = new ChatterNewMessageSegment();
                        chatterNewMessageSegment.Type = ChatterMessageSegmentType.Text.ToString();
                        chatterNewMessageSegment.Text = message;

                        // Add the segment to the post
                        chatterPostedMessage.Body.MessageSegments.Add(chatterNewMessageSegment);

                        // Post the message synchronously
                        SalesforceSocialSingleton.GetInstance().PostNotification(notifier, authenticatedWho, groupAuthenticationToken, serviceRequest, endpointUrl, serviceRequest.joinPlayerUri, chatterPostedMessage);

                        // Set the flag that we did in fact make a post
                        postMade = true;
                    }
                }

                // Check to see if we have any user authorization - if so, we post to those users
                if (serviceRequest.authorization.users != null &&
                    serviceRequest.authorization.users.Count > 0)
                {
                    // Create the endpoint url
                    endpointUrl = chatterBaseUrl + SalesforceServiceSingleton.CHATTER_URI_PART_API_VERSION + String.Format(SalesforceServiceSingleton.CHATTER_URI_PART_MY_FEED, authenticatedWho.UserId);

                    // Create a new chatter post
                    chatterPostedMessage      = new ChatterPostedMessage();
                    chatterPostedMessage.Body = new ChatterNewMessageBody();
                    chatterPostedMessage.Body.MessageSegments = new List <ChatterSegment>();

                    // Create a message segment for the actual post
                    chatterNewMessageSegment      = new ChatterNewMessageSegment();
                    chatterNewMessageSegment.Type = ChatterMessageSegmentType.Text.ToString();
                    chatterNewMessageSegment.Text = message;

                    // Add the segment to the post
                    chatterPostedMessage.Body.MessageSegments.Add(chatterNewMessageSegment);

                    // Rather than posting to each user, we do a joint post to all of the users that need to be notified
                    foreach (GroupAuthorizationUserAPI userAuthorization in serviceRequest.authorization.users)
                    {
                        ChatterMentionsSegment chatterMentionsSegment = null;

                        chatterMentionsSegment      = new ChatterMentionsSegment();
                        chatterMentionsSegment.Id   = userAuthorization.authenticationId;
                        chatterMentionsSegment.Type = ChatterMessageSegmentType.Mention.ToString();

                        // Add the user to the @mention
                        chatterPostedMessage.Body.MessageSegments.Add(chatterMentionsSegment);
                    }

                    // Post the message synchronously
                    SalesforceSocialSingleton.GetInstance().PostNotification(notifier, authenticatedWho, serviceRequest, endpointUrl, serviceRequest.joinPlayerUri, chatterPostedMessage);

                    // Set the flag that we did in fact make a post
                    postMade = true;
                }

                if (postMade == false)
                {
                    // Alert the admin that no message was sent
                    ErrorUtils.SendAlert(notifier, authenticatedWho, ErrorUtils.ALERT_TYPE_WARNING, "The service request does not have anything in the authorization context, so there's no one to notify.");
                }
            }
            else
            {
                // Alert the admin that no one is in the authorization context
                ErrorUtils.SendAlert(notifier, authenticatedWho, ErrorUtils.ALERT_TYPE_WARNING, "The service request does not have an authorization context, so there's no one to notify.");
            }

            // Construct the service response
            serviceResponse            = new ServiceResponseAPI();
            serviceResponse.invokeType = ManyWhoConstants.INVOKE_TYPE_FORWARD;
            serviceResponse.token      = serviceRequest.token;
            serviceResponse.outputs    = null;

            return(serviceResponse);
        }
        /// <summary>
        /// This method is used to invoke particular messages on the service.
        /// </summary>
        public async Task<ServiceResponseAPI> Invoke(IAuthenticatedWho authenticatedWho, String action, ServiceRequestAPI serviceRequest)
        {
            System.Diagnostics.Trace.TraceInformation("@start - public async Task<ServiceResponseAPI> Invoke(IAuthenticatedWho authenticatedWho, String action, ServiceRequestAPI serviceRequest)");
            Trace.TraceInformation(JsonConvert.SerializeObject(authenticatedWho));
            Trace.TraceInformation(JsonConvert.SerializeObject(action));
            Trace.TraceInformation(JsonConvert.SerializeObject(serviceRequest));

            ServiceResponseAPI serviceResponse = null;

            if (string.IsNullOrEmpty(action))
            {
                throw ErrorUtils.GetWebException(HttpStatusCode.BadRequest, "Action cannot be null or blank.");
            }

            if (serviceRequest == null)
            {
                throw ErrorUtils.GetWebException(HttpStatusCode.BadRequest, "ServiceRequest cannot be null.");
            }

            if (action.Equals(SERVICE_ACTION_LOGIN, StringComparison.InvariantCultureIgnoreCase) == true)
            {
                serviceResponse = await SalesforceInvokeSingleton.GetInstance().InvokeCreateMatter(authenticatedWho, serviceRequest);
            }
            else
            {
                // We don't have an action by that name
                throw ErrorUtils.GetWebException(HttpStatusCode.BadRequest, "Action cannot be found for name: " + action);
            }

            return serviceResponse;            
        }
 public MessageAPI PostNotification(INotifier notifier, IAuthenticatedWho authenticatedWho, ServiceRequestAPI serviceRequest, String endpointUrl, String flowLink, ChatterPostedMessage chatterPostedMessage)
 {
     return(PostNotification(notifier, authenticatedWho, SalesforceHttpUtils.GetAuthenticationDetails(authenticatedWho.Token).Token, serviceRequest, endpointUrl, flowLink, chatterPostedMessage));
 }
 public static void SendAlert(INotifier notifier, IAuthenticatedWho authenticatedWho, String alertType, String alertMessage)
 {
     SendAlert(notifier, authenticatedWho, alertType, alertMessage, null);
 }
 public static INotifier GetInstance(IAuthenticatedWho authenticatedWho, List <EngineValueAPI> configurationValues, String codeReference)
 {
     return(GetInstance(null, authenticatedWho, configurationValues, codeReference));
 }
        public static IAuthenticatedWho Deserialize(String token)
        {
            IAuthenticatedWho authenticatedWho = null;

            String[] parameters                = null;
            String   directoryIdParameter      = null;
            String   directoryNameParameter    = null;
            String   roleIdParameter           = null;
            String   roleNameParameter         = null;
            String   primaryGroupIdParameter   = null;
            String   primaryGroupNameParameter = null;
            String   identityProviderParameter = null;
            String   manywhoTenantIdParameter  = null;
            String   manywhoUserIdParameter    = null;
            String   manywhoTokenParameter     = null;
            String   tenantNameParameter       = null;
            String   tokenParameter            = null;
            String   userIdParameter           = null;
            String   usernameParameter         = null;
            String   emailParameter            = null;
            String   firstNameParameter        = null;
            String   lastNameParameter         = null;

            // Start by splitting the string so we have a complete key/value pairing
            parameters = token.Split('&');

            // Grab the parameters for each of the properties from the array
            manywhoTenantIdParameter  = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_MANYWHO_TENANT_ID, StringComparison.OrdinalIgnoreCase));
            manywhoUserIdParameter    = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_MANYWHO_USER_ID, StringComparison.OrdinalIgnoreCase));
            manywhoTokenParameter     = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_MANYWHO_TOKEN, StringComparison.OrdinalIgnoreCase));
            directoryIdParameter      = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_DIRECTORY_ID, StringComparison.OrdinalIgnoreCase));
            directoryNameParameter    = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_DIRECTORY_NAME, StringComparison.OrdinalIgnoreCase));
            roleIdParameter           = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_ROLE_ID, StringComparison.OrdinalIgnoreCase));
            roleNameParameter         = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_ROLE_NAME, StringComparison.OrdinalIgnoreCase));
            primaryGroupIdParameter   = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_PRIMARY_GROUP_ID, StringComparison.OrdinalIgnoreCase));
            primaryGroupNameParameter = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_PRIMARY_GROUP_NAME, StringComparison.OrdinalIgnoreCase));
            emailParameter            = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_EMAIL, StringComparison.OrdinalIgnoreCase));
            identityProviderParameter = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_IDENTITY_PROVIDER, StringComparison.OrdinalIgnoreCase));
            tenantNameParameter       = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_TENANT_NAME, StringComparison.OrdinalIgnoreCase));
            tokenParameter            = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_TOKEN, StringComparison.OrdinalIgnoreCase));
            userIdParameter           = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_USER_ID, StringComparison.OrdinalIgnoreCase));
            usernameParameter         = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_USERNAME, StringComparison.OrdinalIgnoreCase));
            firstNameParameter        = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_FIRST_NAME, StringComparison.OrdinalIgnoreCase));
            lastNameParameter         = parameters.Single(value => value.StartsWith(ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_LAST_NAME, StringComparison.OrdinalIgnoreCase));

            // Check to make sure we have all of the parameters
            Validation.Instance.IsNotNullOrWhiteSpace(manywhoTenantIdParameter, "ManyWhoTenantId", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_MANYWHO_TENANT_ID)
            .IsNotNullOrWhiteSpace(manywhoUserIdParameter, "ManyWhoUserId", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_MANYWHO_USER_ID)
            .IsNotNullOrWhiteSpace(manywhoTokenParameter, "ManyWhoToken", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_MANYWHO_TOKEN)
            .IsNotNullOrWhiteSpace(directoryIdParameter, "DirectoryId", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_DIRECTORY_ID)
            .IsNotNullOrWhiteSpace(directoryNameParameter, "DirectoryName", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_DIRECTORY_NAME)
            .IsNotNullOrWhiteSpace(emailParameter, "Email", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_EMAIL)
            .IsNotNullOrWhiteSpace(identityProviderParameter, "IdentityProvider", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_IDENTITY_PROVIDER)
            .IsNotNullOrWhiteSpace(tenantNameParameter, "TenantName", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_TENANT_NAME)
            .IsNotNullOrWhiteSpace(tokenParameter, "Token", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_TOKEN)
            .IsNotNullOrWhiteSpace(userIdParameter, "UserId", "Missing parameter: " + ManyWhoConstants.AUTHENTICATED_WHO_TOKEN_USER_ID);

            // Create our new authenticated who object
            authenticatedWho = new AuthenticatedWho();
            authenticatedWho.ManyWhoTenantId  = Guid.Parse(manywhoTenantIdParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1]);
            authenticatedWho.ManyWhoUserId    = Guid.Parse(manywhoUserIdParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1]);
            authenticatedWho.ManyWhoToken     = manywhoTokenParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.DirectoryId      = directoryIdParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.DirectoryName    = directoryNameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.Email            = emailParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.IdentityProvider = identityProviderParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.TenantName       = tenantNameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.Token            = tokenParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            authenticatedWho.UserId           = userIdParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];

            if (firstNameParameter != null &&
                firstNameParameter.Trim().Length > 0)
            {
                authenticatedWho.FirstName = firstNameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            if (lastNameParameter != null &&
                lastNameParameter.Trim().Length > 0)
            {
                authenticatedWho.LastName = lastNameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            if (usernameParameter != null &&
                usernameParameter.Trim().Length > 0)
            {
                authenticatedWho.Username = usernameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            if (!string.IsNullOrWhiteSpace(roleIdParameter))
            {
                authenticatedWho.RoleId = roleIdParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            if (!string.IsNullOrWhiteSpace(roleNameParameter))
            {
                authenticatedWho.RoleName = roleNameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            if (!string.IsNullOrWhiteSpace(primaryGroupIdParameter))
            {
                authenticatedWho.PrimaryGroupId = primaryGroupIdParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            if (!string.IsNullOrWhiteSpace(primaryGroupNameParameter))
            {
                authenticatedWho.PrimaryGroupName = primaryGroupNameParameter.Split(ManyWhoConstants.SERIALIZATION_DELIMITER_DELIMITER)[1];
            }

            // Finally, validate the object is OK
            ValidateAuthenticatedWho(authenticatedWho);

            return(authenticatedWho);
        }
        /// <summary>
        /// This method is used to get the list of stream messages in salesforce.
        /// </summary>
        public async Task<MessageListAPI> GetStreamMessages(IAuthenticatedWho authenticatedWho, String streamId, SocialServiceRequestAPI socialServiceRequest)
        {
            MessageListAPI messageList = null;

            return messageList;
        }
        public static WebException HandleUnsuccessfulHttpResponseMessage(INotifier notifier, IAuthenticatedWho authenticatedWho, Int32 iteration, HttpResponseMessage httpResponseMessage, String endpointUrl)
        {
            WebException webException = null;

            if (iteration >= (MAXIMUM_RETRIES - 1))
            {
                // The the alert email the fault
                ErrorUtils.SendAlert(notifier, authenticatedWho, "Fault", "The system has attempted multiple retries (" + MAXIMUM_RETRIES + ") with no luck on: " + endpointUrl + ". The status code is: " + httpResponseMessage.StatusCode + ". The reason is: " + httpResponseMessage.ReasonPhrase);

                // Throw the fault up to the caller
                webException = new WebException(httpResponseMessage.ReasonPhrase);
            }
            else
            {
                // Alert the admin that a retry has happened
                ErrorUtils.SendAlert(notifier, authenticatedWho, "Warning", "The system is attempting a retry (" + iteration + ") on: " + endpointUrl + ". The status code is: " + httpResponseMessage.StatusCode + ". The reason is: " + httpResponseMessage.ReasonPhrase);
            }

            return(webException);
        }
        /// <summary>
        /// This method is used to get the user info for the provided user id in docordo.
        /// </summary>
        public WhoAPI GetUserInfo(IAuthenticatedWho authenticatedWho, String streamId, String id, SocialServiceRequestAPI serviceRequest)
        {
            WhoAPI whoAPI = null;

            return whoAPI;
        }
        /// <summary>
        /// This method is used to get the list of stream followers in salesforce.
        /// </summary>
        public List<WhoAPI> GetStreamFollowers(IAuthenticatedWho authenticatedWho, String streamId, SocialServiceRequestAPI socialServiceRequest)
        {
            List<WhoAPI> whos = null;

            return whos;
        }
        /// <summary>
        /// This method is used to create a new activity stream in salesforce based on the provided configuration.
        /// </summary>
        public String CreateStream(IAuthenticatedWho authenticatedWho, SocialServiceRequestAPI socialServiceRequestAPI)
        {
            String streamId = null;

            return streamId;
        }
        /// <summary>
        /// This method is used to check to see if the user is in the provided authorization context.
        /// </summary>
        public ObjectDataResponseAPI GetUserInAuthorizationContext(IAuthenticatedWho authenticatedWho, ObjectDataRequestAPI objectDataRequestAPI)
        {
            System.Diagnostics.Trace.TraceInformation("@start - public ObjectDataResponseAPI GetUserInAuthorizationContext(IAuthenticatedWho authenticatedWho, ObjectDataRequestAPI objectDataRequestAPI)");
            Trace.TraceInformation(JsonConvert.SerializeObject(authenticatedWho));
            Trace.TraceInformation(JsonConvert.SerializeObject(objectDataRequestAPI));

            System.Diagnostics.Trace.TraceInformation("A");
            ObjectAPI userObject = DescribeUtils.CreateUserObject(authenticatedWho);

            System.Diagnostics.Trace.TraceInformation("B");
            userObject.properties.Add(DescribeUtils.CreateProperty(ManyWhoConstants.MANYWHO_USER_PROPERTY_STATUS,
                authenticatedWho.UserId == ManyWhoConstants.AUTHENTICATED_USER_PUBLIC_USER_ID ?
                    ManyWhoConstants.AUTHORIZATION_STATUS_NOT_AUTHORIZED : ManyWhoConstants.AUTHORIZATION_STATUS_AUTHORIZED));

            System.Diagnostics.Trace.TraceInformation("C");
            ObjectDataResponseAPI objectDataResponseAPI = new ObjectDataResponseAPI();
            objectDataResponseAPI.objectData = new List<ObjectAPI>();
            objectDataResponseAPI.objectData.Add(userObject);

            System.Diagnostics.Trace.TraceInformation("D");
            return objectDataResponseAPI;
        }
 /// <summary>
 /// This method is used to save data back to docordo.com.
 /// </summary>
 public ObjectDataResponseAPI Save(IAuthenticatedWho authenticatedWho, ObjectDataRequestAPI objectDataRequestAPI)
 {
     System.Diagnostics.Trace.TraceInformation("@start - public ObjectDataResponseAPI Save(IAuthenticatedWho authenticatedWho, ObjectDataRequestAPI objectDataRequestAPI)");
     Trace.TraceInformation(JsonConvert.SerializeObject(authenticatedWho));
     Trace.TraceInformation(JsonConvert.SerializeObject(objectDataRequestAPI));
     throw new NotImplementedException();
 }
        public Boolean SendEmail(INotifier notifier, IAuthenticatedWho authenticatedWho, ServiceRequestAPI serviceRequest, Boolean includeTracking)
        {
            SforceService sforceService                  = null;
            List <String> toEmails                       = null;
            Boolean       includeOutcomesAsButtons       = true;
            String        includeOutcomesAsButtonsString = null;
            String        toEmail           = null;
            String        fromEmail         = null;
            String        subject           = null;
            String        textBody          = null;
            String        htmlBody          = null;
            String        authenticationUrl = null;
            String        username          = null;
            String        password          = null;
            String        securityToken     = null;
            String        redirectUri       = null;

            // Get the configuration information for salesforce
            authenticationUrl = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_AUTHENTICATION_URL, serviceRequest.configurationValues, true);
            username          = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_USERNAME, serviceRequest.configurationValues, true);
            password          = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_PASSWORD, serviceRequest.configurationValues, true);
            securityToken     = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_SECURITY_TOKEN, serviceRequest.configurationValues, false);

            // Get the values from the incoming request
            toEmail     = ValueUtils.GetContentValue(SERVICE_VALUE_TO_EMAIL, serviceRequest.inputs, false);
            fromEmail   = ValueUtils.GetContentValue(SERVICE_VALUE_FROM_EMAIL, serviceRequest.inputs, false);
            subject     = ValueUtils.GetContentValue(SERVICE_VALUE_SUBJECT, serviceRequest.inputs, true);
            textBody    = ValueUtils.GetContentValue(SERVICE_VALUE_TEXT_BODY, serviceRequest.inputs, false);
            htmlBody    = ValueUtils.GetContentValue(SERVICE_VALUE_HTML_BODY, serviceRequest.inputs, false);
            redirectUri = ValueUtils.GetContentValue(SERVICE_VALUE_REDIRECT_URI, serviceRequest.inputs, false);
            includeOutcomesAsButtonsString = ValueUtils.GetContentValue(SERVICE_VALUE_INCLUDE_OUTCOMES_AS_BUTTONS, serviceRequest.inputs, false);

            // Create the to emails list
            toEmails = new List <String>();

            // Check to see if we have a value for including outcome buttons
            if (String.IsNullOrWhiteSpace(includeOutcomesAsButtonsString) == true)
            {
                // Default is true
                includeOutcomesAsButtons = true;
            }
            else
            {
                includeOutcomesAsButtons = Boolean.Parse(includeOutcomesAsButtonsString);
            }

            if (String.IsNullOrWhiteSpace(toEmail) == true)
            {
                if (serviceRequest.authorization == null)
                {
                    throw new ArgumentNullException("ServiceRequest.Authorization", "The ServiceRequest.Authorization property cannot be null as we will not know who to send the email to.");
                }

                if (serviceRequest.authorization.groups == null ||
                    serviceRequest.authorization.groups.Count == 0)
                {
                    throw new ArgumentNullException("ServiceRequest.Authorization.Groups", "The ServiceRequest.Authorization.Groups property cannot be null or empty as we will not know who to send the email to.");
                }

                if (serviceRequest.authorization.groups.Count > 1)
                {
                    throw new ArgumentNullException("ServiceRequest.Authorization.Groups", "The ServiceRequest.Authorization.Groups property cannot contain more than one group currently.");
                }

                // We need to get the users from salesforce
                sforceService = SalesforceDataSingleton.GetInstance().Login(authenticatedWho, serviceRequest.configurationValues, true, false);

                if (sforceService == null)
                {
                    throw new ArgumentNullException("SalesforceService", "Unable to log into Salesforce.");
                }

                // Get the to emails from Salesforce
                toEmails = SalesforceAuthenticationSingleton.GetInstance().GetGroupMemberEmails(notifier, sforceService, serviceRequest, serviceRequest.authorization.groups[0].authenticationId);

                if (toEmails == null ||
                    toEmails.Count == 0)
                {
                    throw new ArgumentNullException("ServiceRequest.Authorization.Groups", "The ServiceRequest.Authorization.Groups configuration is not returning any users to send the email to.");
                }
            }
            else
            {
                // The user is explicitly setting the to email
                toEmails.Add(toEmail);
            }

            if (includeOutcomesAsButtons == false)
            {
                // Null out any outcomes so we don't send them through
                serviceRequest.outcomes = null;
            }

            // Send the actual email
            this.SendEmail(serviceRequest.configurationValues, fromEmail, toEmails.ToArray(), null, subject, textBody, htmlBody, serviceRequest.token, redirectUri, serviceRequest.outcomes);

            return(includeOutcomesAsButtons);
        }
        /// <summary>
        /// This method allows the user to post a new message to the stream in chatter.
        /// </summary>
        public async Task<MessageAPI> PostNewMessage(IAuthenticatedWho authenticatedWho, String streamId, HttpContent httpContent)
        {
            MessageAPI message = null;

            return message;
        }
 public static HttpClient CreateHttpClient(IAuthenticatedWho authenticatedWho, String tenantId, String stateId)
 {
     return(CreateHttpClient(authenticatedWho, tenantId, stateId, TIMEOUT_SECONDS));
 }
        /// <summary>
        /// This method allows the user to like messages in the stream in chatter.
        /// </summary>
        public async Task<String> LikeMessage(IAuthenticatedWho authenticatedWho, String streamId, String messageId, Boolean like, SocialServiceRequestAPI socialServiceRequest)
        {
            String response = null;

            return response;
        }
 public void SendNotification(IAuthenticatedWho receivingAuthenticatedWho, String reason, String mediaType, String message)
 {
     this.Reason = reason;
     this.AddNotificationMessage(mediaType, message);
     this.SendNotification(receivingAuthenticatedWho);
 }
        /// <summary>
        /// This method allows the user to follow the stream in chatter.
        /// </summary>
        public async Task<String> FollowStream(IAuthenticatedWho authenticatedWho, String streamId, Boolean follow, SocialServiceRequestAPI socialServiceRequest)
        {
            String response = null;

            return response;
        }
 public EmailNotifier(IAuthenticatedWho receivingAuthenticatedWho)
 {
     this.ReceivingAuthenticatedWho = receivingAuthenticatedWho;
     this.NotificationMessages      = new List <INotificationMessage>();
     this.LogEntries = new List <String>();
 }
        /// <summary>
        /// This method allows the user to search for users by name in chatter.
        /// </summary>
        public async Task<List<MentionedWhoAPI>> SearchUsersByName(IAuthenticatedWho authenticatedWho, String streamId, String name, SocialServiceRequestAPI socialServiceRequest)
        {
            List<MentionedWhoAPI> mentionedUsers = null;

            return mentionedUsers;
        }
        /// <summary>
        /// This is a general purpose method for getting user information from chatter.
        /// </summary>
        public WhoAPI GetUserInfoById(INotifier notifier, IAuthenticatedWho authenticatedWho, String streamId, String id, SocialServiceRequestAPI socialServiceRequestAPI)
        {
            List <WhoAPI>       stuffAuthenticatedUserIsFollowing = null;
            ChatterUserInfo     chatterUserInfo     = null;
            HttpResponseMessage httpResponseMessage = null;
            HttpClient          httpClient          = null;
            WhoAPI who            = null;
            String chatterBaseUrl = null;
            String endpointUrl    = null;
            String adminEmail     = null;

            if (authenticatedWho == null)
            {
                throw new ArgumentNullException("BadRequest", "AuthenticatedWho is null.");
            }

            if (id == null ||
                id.Trim().Length == 0)
            {
                throw new ArgumentNullException("BadRequest", "Id for user is null or blank.");
            }

            if (streamId == null ||
                streamId.Trim().Length == 0)
            {
                throw new ArgumentNullException("BadRequest", "Stream identifier is null or blank.");
            }

            if (socialServiceRequestAPI == null)
            {
                throw new ArgumentNullException("BadRequest", "SocialServiceRequest is null.");
            }

            // We only need the chatter base url for this call
            chatterBaseUrl = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_CHATTER_BASE_URL, socialServiceRequestAPI.configurationValues, true);
            adminEmail     = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_ADMIN_EMAIL, socialServiceRequestAPI.configurationValues, true);

            // We enclose the request in a for loop to handle http errors
            for (int i = 0; i < SalesforceHttpUtils.MAXIMUM_RETRIES; i++)
            {
                try
                {
                    // Create a new client object
                    httpClient = SalesforceHttpUtils.CreateHttpClient(SalesforceHttpUtils.GetAuthenticationDetails(authenticatedWho.Token).Token);

                    // Create the endpoint url
                    endpointUrl = chatterBaseUrl + SalesforceServiceSingleton.CHATTER_URI_PART_API_VERSION + SalesforceServiceSingleton.CHATTER_URI_PART_USERS + "/" + id;

                    // Call the get method on the chatter API to grab the user information
                    httpResponseMessage = httpClient.GetAsync(endpointUrl).Result;

                    // Check the status of the response and respond appropriately
                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        // Grab the chatter user info from the result
                        chatterUserInfo = httpResponseMessage.Content.ReadAsAsync <ChatterUserInfo>().Result;

                        // Convert the chatter user info over to a who
                        who = this.ChatterUserInfoToWhoAPI(chatterUserInfo);

                        // Get the stuff this user is following
                        stuffAuthenticatedUserIsFollowing = this.GetStuffAuthenticatedUserIsFollowing(httpClient, chatterBaseUrl);

                        // Check to see if the authenticated user is also the id
                        if (id.Equals(SalesforceServiceSingleton.CHATTER_ME, StringComparison.InvariantCultureIgnoreCase) == false)
                        {
                            // Check to see if the currently authenticated user is following the provided user id
                            if (stuffAuthenticatedUserIsFollowing != null &&
                                stuffAuthenticatedUserIsFollowing.Any(x => x.id == id) == true)
                            {
                                // The authenticated user is following the provided user id
                                who.isFollower = true;
                            }
                        }
                        else
                        {
                            // If the authenticated user is the same as the provided id, the "is following" refers to the stream
                            if (stuffAuthenticatedUserIsFollowing != null &&
                                stuffAuthenticatedUserIsFollowing.Any(x => x.id == streamId) == true)
                            {
                                // We are following this stream
                                who.isFollower = true;
                            }
                        }

                        // We successfully executed the request, we can break out of the retry loop
                        break;
                    }
                    else
                    {
                        // Make sure we handle the lack of success properly
                        BaseHttpUtils.HandleUnsuccessfulHttpResponseMessage(notifier, authenticatedWho, i, httpResponseMessage, endpointUrl);
                    }
                }
                catch (Exception exception)
                {
                    // Make sure we handle the exception properly
                    BaseHttpUtils.HandleHttpException(notifier, authenticatedWho, i, exception, endpointUrl);
                }
                finally
                {
                    // Clean up the objects from the request
                    BaseHttpUtils.CleanUpHttp(httpClient, null, httpResponseMessage);
                }
            }

            return(who);
        }
Exemple #25
0
 public Validation AuthenticatedWho(IAuthenticatedWho authenticatedWho)
 {
     return(IsNotNull(authenticatedWho, "authenticatedWho"));
 }
        /// <summary>
        /// This method allows the user to share the flow app in salesforce with their friends.
        /// </summary>
        public MessageAPI PostNotification(INotifier notifier, IAuthenticatedWho authenticatedWho, String oauthToken, ServiceRequestAPI serviceRequest, String endpointUrl, String flowLink, ChatterPostedMessage chatterPostedMessage)
        {
            HttpResponseMessage      httpResponseMessage      = null;
            HttpClient               httpClient               = null;
            MediaTypeFormatter       jsonFormatter            = null;
            MultipartFormDataContent multipartFormDataContent = null;
            ChatterMessage           chatterMessage           = null;
            ChatterAttachmentLink    chatterAttachmentLink    = null;
            MessageAPI               message = null;
            String chatterBaseUrl            = null;
            String adminEmail = null;

            if (oauthToken == null ||
                oauthToken.Trim().Length == 0)
            {
                throw new ArgumentNullException("BadRequest", "OAuthToken cannot be null or blank.");
            }

            if (endpointUrl == null ||
                endpointUrl.Trim().Length == 0)
            {
                throw new ArgumentNullException("BadRequest", "EndpointUrl cannot be null or blank.");
            }

            // Grab the values necessary to post the message over to chatter
            chatterBaseUrl = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_CHATTER_BASE_URL, serviceRequest.configurationValues, true);
            adminEmail     = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_ADMIN_EMAIL, serviceRequest.configurationValues, true);

            // Now we can create the multipart form we're going to post over to salesforce
            multipartFormDataContent = new MultipartFormDataContent();

            if (flowLink != null &&
                flowLink.Trim().Length > 0)
            {
                // We also add the link to the app so the user has it
                chatterAttachmentLink = new ChatterAttachmentLink();
                chatterAttachmentLink.AttachmentType = "Link";
                chatterAttachmentLink.Url            = flowLink;
                chatterAttachmentLink.UrlName        = "Link to ManyWho Flow";

                chatterPostedMessage.Attachment = chatterAttachmentLink;
            }

            // We enclose the request in a for loop to handle http errors
            for (int i = 0; i < SalesforceHttpUtils.MAXIMUM_RETRIES; i++)
            {
                try
                {
                    // Create a new client object
                    httpClient = SalesforceHttpUtils.CreateHttpClient(oauthToken);

                    // Create a new json formatter so the request will be in the right format
                    jsonFormatter = new JsonMediaTypeFormatter();

                    // Use the JSON formatter to create the content of the chatter post
                    multipartFormDataContent.Add(new ObjectContent <ChatterPostedMessage>(chatterPostedMessage, jsonFormatter), "json");

                    // Post the message over to chatter
                    httpResponseMessage = httpClient.PostAsync(endpointUrl, multipartFormDataContent).Result;

                    // Check the status of the response and respond appropriately
                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        // Grab the chatter message from the post
                        chatterMessage = httpResponseMessage.Content.ReadAsAsync <ChatterMessage>().Result;

                        // Convert it over to a manywho message
                        message = SalesforceSocialSingleton.GetInstance().ChatterMessageToMessageAPI(chatterBaseUrl, null, chatterMessage);

                        // We successfully executed the request, we can break out of the retry loop
                        break;
                    }
                    else
                    {
                        // Make sure we handle the lack of success properly
                        BaseHttpUtils.HandleUnsuccessfulHttpResponseMessage(notifier, authenticatedWho, i, httpResponseMessage, endpointUrl);
                    }
                }
                catch (Exception exception)
                {
                    // Make sure we handle the exception properly
                    BaseHttpUtils.HandleHttpException(notifier, authenticatedWho, i, exception, endpointUrl);
                }
                finally
                {
                    // Clean up the objects from the request
                    BaseHttpUtils.CleanUpHttp(httpClient, null, httpResponseMessage);
                }
            }

            return(message);
        }
        public async Task<ServiceResponseAPI> InvokeCreateMatter(IAuthenticatedWho authenticatedWho, ServiceRequestAPI serviceRequest)
        {
            ServiceResponseAPI serviceResponse = null;
            DateTime whenDate = DateTime.Now;
            List<ObjectAPI> taskObjects = null;
            ObjectAPI taskObject = null;

            string authenticationUrl = null;
            string username = null;
            string password = null;

            string recordNumber = null;
            string description = null;

            string matterId = null;

            // Grab the configuration values from the service request
            authenticationUrl = SettingUtils.GetConfigurationValue(DocordoServiceSingleton.SERVICE_VALUE_DOCORDO_DOMAIN, serviceRequest.configurationValues, true);
            username = SettingUtils.GetConfigurationValue(DocordoServiceSingleton.SERVICE_VALUE_DOCORDO_USERNAME, serviceRequest.configurationValues, true);
            password = SettingUtils.GetConfigurationValue(DocordoServiceSingleton.SERVICE_VALUE_DOCORDO_PASSWORD, serviceRequest.configurationValues, true);            

            if (serviceRequest.authorization != null)
            {
                // Get the message from the inputs
                recordNumber = ValueUtils.GetContentValue(DocordoServiceSingleton.SERVICE_INPUT_RECORD_NUMBER, serviceRequest.inputs, true);
                description = ValueUtils.GetContentValue(DocordoServiceSingleton.SERVICE_INPUT_MATTER_DESCRIPTION, serviceRequest.inputs, true);

                // Create a task object to save back to the system
                taskObject = new ObjectAPI();
                taskObject.developerName = "Matter";
                taskObject.properties = new List<PropertyAPI>();
                taskObject.properties.Add(new PropertyAPI() { developerName = "RecordNumber", contentValue = description });                
                taskObject.properties.Add(new PropertyAPI() { developerName = "Description", contentValue = description });                

                // Add the object to the list of objects to save
                taskObjects = new List<ObjectAPI>();
                taskObjects.Add(taskObject);
                
                // Save the task object to docordo
                DocordoLoginResponse docordoLoginResponse = DocordoAPI.DocordoService.GetInstance().Login(authenticationUrl, username, password);

                taskObjects = DocordoDataSingleton.GetInstance().CreateMatter(authenticationUrl, docordoLoginResponse.EbikkoSessionId, docordoLoginResponse.CookieJSESSIONID, recordNumber, description);

                // Check to see if anything came back as part of the save - it should unless there was a fault
                if (taskObjects != null &&
                    taskObjects.Count > 0)
                {
                    // Grab the first object from the returned task objects
                    taskObject = taskObjects[0];

                    // Grab the id from that object - this needs to be returned in our outputs
                    matterId = taskObject.externalId;
                }
                else
                {
                    // If we didn't get any objects back, we need to throw an error
                    String errorMessage = "Task could not be created for an unknown reason.";

                    ErrorUtils.SendAlert(authenticatedWho, ErrorUtils.ALERT_TYPE_FAULT, "*****@*****.**", "DocordoPlugin", errorMessage);

                    throw ErrorUtils.GetWebException(HttpStatusCode.InternalServerError, errorMessage);
                }

            }
            else
            {
                // Alert the admin that no one is in the authorization context
                ErrorUtils.SendAlert(authenticatedWho, ErrorUtils.ALERT_TYPE_WARNING, "*****@*****.**", "DocordoPlugin", "The service request does not have an authorization context, so there's no one to notify.");
            }

            // Construct the service response
            serviceResponse = new ServiceResponseAPI();
            serviceResponse.invokeType = ManyWhoConstants.INVOKE_TYPE_FORWARD;
            serviceResponse.token = serviceRequest.token;
            serviceResponse.outputs = new List<EngineValueAPI>();
            serviceResponse.outputs.Add(new EngineValueAPI() { contentType = ManyWhoConstants.CONTENT_TYPE_STRING, contentValue = matterId, developerName = DocordoServiceSingleton.SERVICE_OUTPUT_ID });

            return serviceResponse;
        }
Exemple #28
0
        public ServiceResponseAPI InvokeCreateEvent(INotifier notifier, IAuthenticatedWho authenticatedWho, ServiceRequestAPI serviceRequest)
        {
            List <ObjectDataTypePropertyAPI> objectDataTypeProperties = null;
            ServiceResponseAPI serviceResponse   = null;
            DateTime           whenDate          = DateTime.Now;
            List <ObjectAPI>   eventObjects      = null;
            ObjectAPI          eventObject       = null;
            String             authenticationUrl = null;
            String             username          = null;
            String             password          = null;
            String             securityToken     = null;
            String             adminEmail        = null;
            String             when        = null;
            String             duration    = null;
            String             description = null;
            String             subject     = null;
            String             eventId     = null;

            // Grab the configuration values from the service request
            authenticationUrl = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_AUTHENTICATION_URL, serviceRequest.configurationValues, true);
            username          = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_USERNAME, serviceRequest.configurationValues, true);
            password          = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_PASSWORD, serviceRequest.configurationValues, true);
            securityToken     = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_SECURITY_TOKEN, serviceRequest.configurationValues, false);
            adminEmail        = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_ADMIN_EMAIL, serviceRequest.configurationValues, true);

            if (serviceRequest.authorization != null)
            {
                // Get the message from the inputs
                when        = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_INPUT_WHEN, serviceRequest.inputs, true);
                duration    = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_INPUT_DURATION, serviceRequest.inputs, true);
                description = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_INPUT_DESCRIPTION, serviceRequest.inputs, true);
                subject     = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_INPUT_SUBJECT, serviceRequest.inputs, true);

                // Get the when date for the provided command
                whenDate = DateUtils.CreateDateFromWhenCommand(notifier, authenticatedWho, when, adminEmail);
                // Set the calendar event for a day in the week at 10am
                whenDate = DateUtils.GetDayInWeek(whenDate, 10);

                // Add the link to the flow in the description
                description += "  Link to Flow: " + serviceRequest.joinPlayerUri;

                // Create a event object to save back to the system
                eventObject = new ObjectAPI();
                eventObject.developerName = "Event";
                eventObject.properties    = new List <PropertyAPI>();
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "ActivityDateTime", contentValue = whenDate.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffZ")
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "Description", contentValue = description
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "DurationInMinutes", contentValue = duration
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "Subject", contentValue = subject
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsAllDayEvent", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsArchived", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsChild", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsGroupEvent", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsPrivate", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsRecurrence", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsReminderSet", contentValue = "false"
                });
                eventObject.properties.Add(new PropertyAPI()
                {
                    developerName = "IsVisibleInSelfService", contentValue = "false"
                });

                // Add the object to the list of objects to save
                eventObjects = new List <ObjectAPI>();
                eventObjects.Add(eventObject);

                // Create the object data type properties for this object so the system knows what we're selecting
                objectDataTypeProperties = new List <ObjectDataTypePropertyAPI>();
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "ActivityDateTime"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "Description"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "DurationInMinutes"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "Subject"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsAllDayEvent"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsArchived"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsChild"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsGroupEvent"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsPrivate"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsRecurrence"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsReminderSet"
                });
                objectDataTypeProperties.Add(new ObjectDataTypePropertyAPI()
                {
                    developerName = "IsVisibleInSelfService"
                });

                // Save the event object to salesforce
                eventObjects = SalesforceDataSingleton.GetInstance().Save(notifier, authenticatedWho, serviceRequest.configurationValues, objectDataTypeProperties, eventObjects);

                // Check to see if anything came back as part of the save - it should unless there was a fault
                if (eventObjects != null &&
                    eventObjects.Count > 0)
                {
                    // Grab the first object from the returned event objects
                    eventObject = eventObjects[0];

                    // Grab the id from that object - this needs to be returned in our outputs
                    eventId = eventObject.externalId;
                }
                else
                {
                    // If we didn't get any objects back, we need to throw an error
                    String errorMessage = "Event could not be created for an unknown reason.";

                    ErrorUtils.SendAlert(notifier, authenticatedWho, ErrorUtils.ALERT_TYPE_FAULT, errorMessage);

                    throw new ArgumentNullException("BadRequest", errorMessage);
                }
            }
            else
            {
                // Alert the admin that no one is in the authorization context
                ErrorUtils.SendAlert(notifier, authenticatedWho, ErrorUtils.ALERT_TYPE_WARNING, "The service request does not have an authorization context, so there's no one to notify.");
            }

            // Construct the service response
            serviceResponse            = new ServiceResponseAPI();
            serviceResponse.invokeType = ManyWhoConstants.INVOKE_TYPE_FORWARD;
            serviceResponse.token      = serviceRequest.token;
            serviceResponse.outputs    = new List <EngineValueAPI>();
            serviceResponse.outputs.Add(new EngineValueAPI()
            {
                contentType = ManyWhoConstants.CONTENT_TYPE_STRING, contentValue = eventId, developerName = SalesforceServiceSingleton.SERVICE_OUTPUT_ID
            });

            return(serviceResponse);
        }
Exemple #29
0
 public static HttpClient CreateHttpClient(IAuthenticatedWho authenticatedWho, string tenantId, string stateId, int timeOut)
 {
     return(CreateHttpClient(Uri.EscapeDataString(AuthenticationUtils.Serialize(authenticatedWho)), tenantId, stateId, timeOut));
 }
        public HttpResponseMessage TaskEmailOutcomeResponse(String token, String selectedOutcomeId, String redirectUri = null)
        {
            IAuthenticatedWho   authenticatedWho = null;
            INotifier           notifier         = null;
            HttpResponseMessage response         = null;
            ServiceResponseAPI  serviceResponse  = null;
            ServiceRequestAPI   serviceRequest   = null;
            String invokeType      = null;
            String responseContent = null;

            try
            {
                if (String.IsNullOrWhiteSpace(token) == true)
                {
                    throw new ArgumentNullException("Token", "The token for the request is null or blank.");
                }

                if (String.IsNullOrWhiteSpace(selectedOutcomeId) == true)
                {
                    throw new ArgumentNullException("SelectedOutcomeId", "The selected outcome for the request is null or blank.");
                }

                // Get the email verification for this tracking code
                serviceRequest = JsonConvert.DeserializeObject <ServiceRequestAPI>(StorageUtils.GetStoredJson(token.ToLower()));

                if (serviceRequest == null)
                {
                    throw new ArgumentNullException("ServiceRequest", "The request has already been processed.");
                }

                // Get the notifier email
                authenticatedWho       = new AuthenticatedWho();
                authenticatedWho.Email = ValueUtils.GetContentValue(SalesforceServiceSingleton.SERVICE_VALUE_ADMIN_EMAIL, serviceRequest.configurationValues, true);

                // Create the notifier
                notifier = EmailNotifier.GetInstance(serviceRequest.tenantId, authenticatedWho, null, "TaskEmailOutcomeResponse");

                // Create the service response to send back to ManyWho based on this outcome click
                serviceResponse                   = new ServiceResponseAPI();
                serviceResponse.invokeType        = ManyWhoConstants.INVOKE_TYPE_FORWARD;
                serviceResponse.tenantId          = serviceRequest.tenantId;
                serviceResponse.token             = serviceRequest.token;
                serviceResponse.selectedOutcomeId = selectedOutcomeId;

                // Invoke the response on the manywho service
                invokeType = RunSingleton.GetInstance().Response(notifier, null, serviceRequest.tenantId, serviceRequest.callbackUri, serviceResponse);

                if (invokeType == null ||
                    invokeType.Trim().Length == 0)
                {
                    throw new ArgumentNullException("ServiceRequest", "The invokeType coming back from ManyWho cannot be null or blank.");
                }

                if (invokeType.IndexOf(ManyWhoConstants.INVOKE_TYPE_SUCCESS, StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    // The system has accepted our task email response so the token is now dead - we remove it from storage
                    StorageUtils.RemoveStoredJson(token.ToLower());
                }
                else
                {
                    // The system has not accepted our task email response, so we should simply keep waiting and responding to emails with this task token
                }

                // Tell the user the outcome selection was successful
                responseContent = "Your request has been successfully completed. Please close this window.";

                if (String.IsNullOrWhiteSpace(redirectUri) == false)
                {
                    // Redirect the user as specified
                    response = Request.CreateResponse(HttpStatusCode.RedirectMethod, redirectUri);
                    response.Headers.Add("Location", redirectUri);
                }
                else
                {
                    // Send the user a response page
                    response         = Request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(responseContent);
                }
            }
            catch (Exception exception)
            {
                throw BaseHttpUtils.GetWebException(HttpStatusCode.BadRequest, BaseHttpUtils.GetExceptionMessage(exception));
            }

            return(response);
        }
Exemple #31
0
        protected override System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            WorkflowRuleNotification receivedNotification = null;
            IAuthenticatedWho        authenticatedWho     = null;
            INotifier emailNotifier = null;
            Guid      tenantGuid    = Guid.Empty;
            String    tenantId      = null;
            String    mode          = null;
            String    email         = null;

            try
            {
                // Get the mode from the request uri
                mode = BaseHttpUtils.GetModeFromQuery(request.RequestUri);

                // Get any provided notification email
                email = BaseHttpUtils.GetEmailFromQuery(request.RequestUri);

                // Check to make sure the incoming request has enough segments
                // Deployed we have an extra segment for the deployment sub-directory, hence this is one more than you would have thought
                if (request.RequestUri.Segments.Length < 9)
                {
                    throw new ArgumentNullException("Request.Segments", "The incoming request is not a valid Url for outbound messages.");
                }

                // Get the segments from the call so we know which tenant we're executing against
                tenantId = request.RequestUri.Segments[8].Replace("/", "");

                // Check to make sure we've received valid guids
                if (Guid.TryParse(tenantId, out tenantGuid) == false)
                {
                    throw new ArgumentNullException("Request.Segments", "The incoming request does not contain a valid tenant identifier. You provided: " + tenantId);
                }

                // Create a basic authenticated who for the notifier
                authenticatedWho       = AuthenticationUtils.CreatePublicUser(tenantId);
                authenticatedWho.Email = email;

                // Create the notifier
                emailNotifier = EmailNotifier.GetInstance(tenantId, authenticatedWho, null, "WorkflowRuleListenerMessageHandler");

                // ExtractData would populate notification class' variables, which can be used to get desired data.
                receivedNotification = new WorkflowRuleNotification();
                receivedNotification.ExtractData(emailNotifier, request.Content.ReadAsStringAsync().Result, mode);

                // Now send ManyWho the notification that something has changed on a set of records, but only if ManyWho actually cares about them
                this.Execute(emailNotifier, tenantId, mode, receivedNotification);

                // Send the debug log if the user is running in debug mode
                if (SettingUtils.IsDebugging(mode))
                {
                    ErrorUtils.SendAlert(emailNotifier, null, ErrorUtils.ALERT_TYPE_WARNING, "Debug Log Entries");
                }

                // Send a response back to SFDC
                // Note: since we are not calling base class' SendAsync function, the request will return from here, and will not reach our POST function.
                return(Task.FromResult(receivedNotification.PrepareResponse(request)));
            }
            catch (Exception exception)
            {
                // Send the debug log if the user is running in debug mode
                if (SettingUtils.IsDebugging(mode))
                {
                    ErrorUtils.SendAlert(emailNotifier, null, ErrorUtils.ALERT_TYPE_WARNING, BaseHttpUtils.GetExceptionMessage(exception));
                }

                throw BaseHttpUtils.GetWebException(HttpStatusCode.BadRequest, BaseHttpUtils.GetExceptionMessage(exception));
            }
        }
Exemple #32
0
        public void RegisterListener(IAuthenticatedWho authenticatedWho, ListenerServiceRequestAPI listenerServiceRequest)
        {
            Dictionary <String, ListenerServiceRequestAPI> salesforceListenerEntries = null;
            String objectId     = null;
            Guid   externalGuid = Guid.Empty;

            if (authenticatedWho == null)
            {
                throw new ArgumentNullException("AuthenticatedWho", "The AuthenticatedWho object cannot be null.");
            }

            if (listenerServiceRequest == null)
            {
                throw new ArgumentNullException("ListenerServiceRequest", "The ListenerServiceRequest object cannot be null.");
            }

            if (String.IsNullOrWhiteSpace(listenerServiceRequest.listenType) == true)
            {
                throw new ArgumentNullException("ListenerServiceRequest.ListenType", "The ListenerServiceRequest.ListenType property cannot be null or blank.");
            }

            if (String.IsNullOrWhiteSpace(listenerServiceRequest.token) == true)
            {
                throw new ArgumentNullException("ListenerServiceRequest.Token", "The ListenerServiceRequest.Token property cannot be null or blank.");
            }

            if (listenerServiceRequest.valueForListening == null)
            {
                throw new ArgumentNullException("ListenerServiceRequest.ValueForListening", "The ListenerServiceRequest.ValueForListening property cannot be null.");
            }

            if (listenerServiceRequest.valueForListening.objectData == null ||
                listenerServiceRequest.valueForListening.objectData.Count == 0)
            {
                throw new ArgumentNullException("ListenerServiceRequest.ValueForListening.ObjectData", "The Salesforce Service cannot listen without any object records to listen to.");
            }

            if (listenerServiceRequest.valueForListening.objectData.Count > 1)
            {
                throw new ArgumentNullException("ListenerServiceRequest.ValueForListening.ObjectData", "The Salesforce Service cannot listen to more than one object record in a single request.");
            }

            if (String.IsNullOrWhiteSpace(listenerServiceRequest.valueForListening.objectData[0].externalId) == true ||
                Guid.TryParse(listenerServiceRequest.valueForListening.objectData[0].externalId, out externalGuid) == true)
            {
                throw new ArgumentNullException("ListenerServiceRequest.ValueForListening.ObjectData", "The Salesforce Service cannot listen to an object that has not been first saved or loaded from Salesforce.");
            }

            // Assign the object id from the external id
            objectId = listenerServiceRequest.valueForListening.objectData[0].externalId;

            // Try to get the listener requests out for this object
            salesforceListenerEntries = this.GetListenerRequests(listenerServiceRequest.tenantId, objectId);

            // Check to make sure we have something, or create a new list
            if (salesforceListenerEntries == null)
            {
                // This is the first time we're registering a listener for this object, so we create a new map
                salesforceListenerEntries = new Dictionary <String, ListenerServiceRequestAPI>();
            }

            // Now we have our list of listeners, we add this one based on the token
            salesforceListenerEntries[listenerServiceRequest.token.ToLower()] = listenerServiceRequest;

            // And we put the updated map, back into the data store
            StorageUtils.SetStoredJson((listenerServiceRequest.tenantId + objectId).ToLower(), JsonConvert.SerializeObject(salesforceListenerEntries));
        }
Exemple #33
0
        protected override System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            WorkflowRuleNotification receivedNotification = null;
            IAuthenticatedWho        authenticatedWho     = null;
            INotifier emailNotifier = null;
            Guid      tenantGuid    = Guid.Empty;
            Guid      flowGuid      = Guid.Empty;
            String    tenantId      = null;
            String    flowId        = null;
            String    player        = null;
            String    mode          = null;
            String    email         = null;
            String    reportingMode = null;

            try
            {
                // Get the mode from the request uri
                mode = BaseHttpUtils.GetModeFromQuery(request.RequestUri);

                // Get the reporting mode from the request uri
                reportingMode = BaseHttpUtils.GetReportingModeFromQuery(request.RequestUri);

                // Get any provided notification email
                email = BaseHttpUtils.GetEmailFromQuery(request.RequestUri);

                // Check to make sure the incoming request has enough segments
                if (request.RequestUri.Segments.Length < 9)
                {
                    throw new ArgumentNullException("Request.Segments", "The incoming request is not a valid Url for outbound messages.");
                }

                // Get the segments from the call so we know which tenant we're executing against
                tenantId = request.RequestUri.Segments[7].Replace("/", "");
                flowId   = request.RequestUri.Segments[8].Replace("/", "");
                player   = request.RequestUri.Segments[9];

                // Check to make sure we've received valid guids
                if (Guid.TryParse(tenantId, out tenantGuid) == false)
                {
                    throw new ArgumentNullException("Request.Segments", "The incoming request does not contain a valid tenant identifier.");
                }

                if (Guid.TryParse(flowId, out flowGuid) == false)
                {
                    throw new ArgumentNullException("Request.Segments", "The incoming request does not contain a valid flow identifier.");
                }

                // If a player has not been provided, we make it the default player
                if (String.IsNullOrWhiteSpace(player) == true)
                {
                    player = "default";
                }

                // Create a basic authenticated who for the notifier
                authenticatedWho       = AuthenticationUtils.CreatePublicUser(tenantId);
                authenticatedWho.Email = email;

                // Create the notifier
                emailNotifier = EmailNotifier.GetInstance(tenantId, authenticatedWho, null, "WorkflowRuleMessageHandler");

                //ExtractData would populate notification class' variables, which can be used to get desired data.
                receivedNotification = new WorkflowRuleNotification();
                receivedNotification.ExtractData(emailNotifier, request.Content.ReadAsStringAsync().Result, mode);

                if (SettingUtils.IsDebugging(mode))
                {
                    emailNotifier.AddLogEntry("Mode: " + mode);
                }
                if (SettingUtils.IsDebugging(mode))
                {
                    emailNotifier.AddLogEntry("Email: " + email);
                }
                if (SettingUtils.IsDebugging(mode))
                {
                    emailNotifier.AddLogEntry("Reporting Mode: " + reportingMode);
                }

                // Execute the notifications against ManyWho
                this.Execute(emailNotifier, tenantId, flowId, player, mode, reportingMode, receivedNotification);

                // Send the debug log if the user is running in debug mode
                if (SettingUtils.IsDebugging(mode))
                {
                    ErrorUtils.SendAlert(emailNotifier, null, ErrorUtils.ALERT_TYPE_WARNING, "Debug Log Entries");
                }

                //Send a response back to SFDC
                //Note: since we are not calling base class' SendAsync function, the request will return from here, and will not reach our POST function.
                return(Task.FromResult(receivedNotification.PrepareResponse(request)));
            }
            catch (Exception exception)
            {
                // Send the debug log if the user is running in debug mode
                if (SettingUtils.IsDebugging(mode))
                {
                    ErrorUtils.SendAlert(emailNotifier, null, ErrorUtils.ALERT_TYPE_WARNING, BaseHttpUtils.GetExceptionMessage(exception));
                }

                throw BaseHttpUtils.GetWebException(HttpStatusCode.BadRequest, BaseHttpUtils.GetExceptionMessage(exception));
            }
        }