コード例 #1
0
        public async Task <IActionResult> SearchCities(string country, string province, string searchVal, int limit)
        {
            try
            {
                string requestBody = "";
                if (!string.IsNullOrEmpty(country))
                {
                    requestBody += "\"Country\":\"" + country + "\",";
                }
                if (!string.IsNullOrEmpty(province))
                {
                    requestBody += "\"Province\":\"" + province + "\",";
                }
                if (!string.IsNullOrEmpty(searchVal))
                {
                    requestBody += "\"City\":\"" + searchVal + "\",";
                }
                requestBody += "\"TopCount\":" + limit + "";

                string requestJson = "{" + requestBody + "}";
                string endpointUrl = "vsd_GetCities";

                // get the response
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, requestJson);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #2
0
        private async Task <DynamicsResult> DynamicsResultAsync(HttpMethod method, string endpointUrl, string requestJson)
        {
            endpointUrl = _configuration["DYNAMICS_ODATA_URI"] + endpointUrl;
            requestJson = requestJson.Replace("fortunecookie", "@odata.");

            Console.WriteLine(endpointUrl);
            Console.WriteLine(requestJson);

            HttpRequestMessage _httpRequest = new HttpRequestMessage(method, endpointUrl);

            _httpRequest.Content = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json");

            var _httpResponse = await _client.SendAsync(_httpRequest);

            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            var _responseContent = await _httpResponse.Content.ReadAsStringAsync();

            var result = new DynamicsResult();

            result.statusCode      = _statusCode;
            result.responseMessage = _httpResponse;
            var clean = _responseContent.Replace("@odata.", "fortunecookie");

            result.result = Newtonsoft.Json.Linq.JObject.Parse(clean);

            Console.WriteLine(result.result);

            return(result);
        }
コード例 #3
0
        public async Task <IActionResult> GetCities()
        {
            try
            {
                // set the endpoint action
                string endpointUrl = "vsd_cities?$select=_vsd_countryid_value,vsd_name,_vsd_stateid_value&$filter=statecode eq 0";

                // get the response
                DynamicsResult result = await _dynamicsResultService.Get(endpointUrl);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #4
0
        public async Task <IActionResult> GetProgramSurplus(string businessBceid, string userBceid, string surplusId)
        {
            try
            {
                // convert the parameters to a json string
                string requestJson = "{\"UserBCeID\":\"" + userBceid + "\",\"BusinessBCeID\":\"" + businessBceid + "\"}";
                // set the endpoint action
                string endpointUrl = "vsd_surplusplanreports(" + surplusId + ")/Microsoft.Dynamics.CRM.vsd_GetCPUSurplusPlan";

                // get the response
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, requestJson);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #5
0
        public async Task <IActionResult> GetBlob(string userBceid, string businessBceid)
        {
            try
            {
                // convert the parameters to a json string
                string requestJson = "{\"UserBCeID\":\"" + userBceid + "\",\"BusinessBCeID\":\"" + businessBceid + "\"}";
                // set the endpoint action
                string endpointUrl = "vsd_GetCPUOrgContracts";

                // get the response
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, requestJson);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #6
0
        public async Task <IActionResult> GetCitiesByCountry(string country)
        {
            try
            {
                string requestJson = "{\"Country\":\"" + country + "\"}";
                // set the endpoint action
                string endpointUrl = $"vsd_cities?$select=_vsd_countryid_value,vsd_name,_vsd_stateid_value&$filter=statecode eq 0 and _vsd_countryid_value eq {country}";
                // string endpointUrl = "vsd_GetCities";

                // get the response
                DynamicsResult result = await _dynamicsResultService.Get(endpointUrl);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #7
0
        public async Task <IActionResult> SetStaff([FromBody] OrganizationPost model)
        {
            if (model == null)
            {
                return(StatusCode(502));
            }

            string endpointUrl = "vsd_SetCPUOrgContracts";
            string modelString = System.Text.Json.JsonSerializer.Serialize(model);

            modelString = Helpers.Helpers.updateFortunecookieBindNull(modelString);
            modelString = Helpers.Helpers.removeNullsForStaffUpdate(modelString);
            DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString);

            return(StatusCode((int)result.statusCode, result.result.ToString()));
        }
コード例 #8
0
        public async Task <IActionResult> GetSubmittedReport(string businessBceid, string userBceid, string dataCollectionId)
        {
            try
            {
                // convert the parameters to a json string
                string requestJson = "{\"UserBCeID\":\"" + userBceid + "\",\"BusinessBCeID\":\"" + businessBceid + "\"}";
                // set the endpoint action
                string endpointUrl = "vsd_datacollections(" + dataCollectionId + ")/Microsoft.Dynamics.CRM.vsd_GetCPUMonthlyStatisticsAnswers";

                // get the response
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, requestJson);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #9
0
        public async Task <IActionResult> AnswerQuestions([FromBody] MonthlyStatisticsAnswers model, string taskId)
        {
            try
            {
                string endpointUrl = "tasks(" + taskId + ")/Microsoft.Dynamics.CRM.vsd_SetCPUMonthlyStatisticsAnswers";
                // make options for the json serializer
                // JsonSerializerOptions options = new JsonSerializerOptions();
                // options.IgnoreNullValues = true;
                // turn the model into a string
                string modelString = System.Text.Json.JsonSerializer.Serialize(model);
                modelString = Helpers.Helpers.updateFortunecookieBindNull(modelString);
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #10
0
        public async Task <IActionResult> DownloadDocument(string userBceid, string businessBceid, string docId)
        {
            try
            {
                // convert the parameters to a json string
                // string requestJson = "{\"UserBCeID\":\"" + userBceid + "\",\"BusinessBCeID\":\"" + businessBceid + "\"}";
                // set the endpoint action
                string endpointUrl = "vsd_sharepointurls(" + docId + ")/Microsoft.Dynamics.CRM.vsd_DownloadDocumentFromSharePoint";

                // get the response
                //requestJson
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, "");

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #11
0
        public async Task <IActionResult> UploadContractDocument([FromBody] FilePost model, string contractId)
        {
            // return null because this needs to be handled as files.
            try
            {
                string endpointUrl = endpointUrl = "vsd_contracts(" + contractId + ")/Microsoft.Dynamics.CRM.vsd_UploadCPUContractDocuments";

                // make options for the json serializer
                JsonSerializerOptions options = new JsonSerializerOptions();
                options.IgnoreNullValues = true;
                // turn the model into a string
                string         modelString = System.Text.Json.JsonSerializer.Serialize(model, options);
                DynamicsResult result      = await _dynamicsResultService.Post(endpointUrl, modelString);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #12
0
        public async Task <IActionResult> SetExpenseReport([FromBody] ExpenseReportPost model)
        {
            try
            {
                if (model == null)
                {
                    return(StatusCode(502));
                }

                string endpointUrl = "vsd_SetCPUOrgContracts";
                // turn the model into a string
                string modelString = System.Text.Json.JsonSerializer.Serialize(model);
                modelString = Helpers.Helpers.updateFortunecookieBindNull(modelString);

                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #13
0
        public async Task <IActionResult> SetProgramSurplus([FromBody] ProgramSurplusPost model)
        {
            try
            {
                if (model == null)
                {
                    return(StatusCode(502));
                }

                string endpointUrl            = "vsd_SetCPUOrgContracts";
                JsonSerializerOptions options = new JsonSerializerOptions();
                options.IgnoreNullValues = true;
                // turn the model into a string
                string modelString = System.Text.Json.JsonSerializer.Serialize(model, options);
                modelString = Helpers.Helpers.updateFortunecookieBindNull(modelString);
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #14
0
        public async Task <IActionResult> SetProgramApplication([FromBody] ProgramApplicationPost model)
        {
            try
            {
                if (model == null)
                {
                    return(StatusCode(502));
                }

                string endpointUrl = "vsd_SetCPUOrgContracts";
                // turn the model into a string
                string modelString = System.Text.Json.JsonSerializer.Serialize(model);
                modelString = Helpers.Helpers.updateFortunecookieBindNull(modelString);
                modelString = Helpers.Helpers.removeNullsForProgramApplication(modelString);
                //_ownerid_value on the Organization is already ignored by the CRM API, so don't need to remove it
                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            finally { }
        }
コード例 #15
0
        /// <summary>
        /// Process Authentication Request
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            //         // get siteminder headers
            _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential");
            _logger.LogInformation("Test information");
            _logger.LogTrace("Test Trace");


            SiteMinderAuthOptions options = new SiteMinderAuthOptions();
            bool isDeveloperLogin         = false;
            bool isBCSCDeveloperLogin     = false;

            try
            {
                //             IDynamicsClient _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));
                ClaimsPrincipal     principal;
                HttpContext         context    = Request.HttpContext;
                IHostingEnvironment hostingEnv = (IHostingEnvironment)context.RequestServices.GetService(typeof(IHostingEnvironment));

                UserSettings userSettings = new UserSettings();

                string userId                 = null;
                string devCompanyId           = null;
                string siteMinderGuid         = "";
                string siteMinderBusinessGuid = "";
                string siteMinderUserType     = "";

                // **************************************************
                // If this is an Error or Authentiation API - Ignore
                // **************************************************
                string url = context.Request.GetDisplayUrl().ToLower();
                if (url.Contains(".js"))
                {
                    return(AuthenticateResult.NoResult());
                }


                // **************************************************
                // Check if the user session is already created
                // **************************************************
                try
                {
                    _logger.LogInformation("Checking user session");
                    userSettings = UserSettings.ReadUserSettings(context);
                    _logger.LogDebug("UserSettings found: " + userSettings.GetJson());
                }
                catch
                {
                    //do nothing
                    _logger.LogDebug("No UserSettings found");
                }

                // is user authenticated - if so we're done
                if ((userSettings.UserAuthenticated && string.IsNullOrEmpty(userId)) ||
                    (userSettings.UserAuthenticated && !string.IsNullOrEmpty(userId) &&
                     !string.IsNullOrEmpty(userSettings.UserId) && userSettings.UserId == userId))
                {
                    _logger.LogDebug("User already authenticated with active session: " + userSettings.UserId);
                    // Console.WriteLine("User already authenticated with active session: " + userSettings.GetJson());
                    principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                    return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                }

                string smgov_userdisplayname = context.Request.Headers["smgov_userdisplayname"];
                if (!string.IsNullOrEmpty(smgov_userdisplayname))
                {
                    userSettings.UserDisplayName = smgov_userdisplayname;
                }

                string smgov_businesslegalname = context.Request.Headers["smgov_businesslegalname"];
                if (!string.IsNullOrEmpty(smgov_businesslegalname))
                {
                    userSettings.BusinessLegalName = smgov_businesslegalname;
                }

                // **************************************************
                // Authenticate based on SiteMinder Headers
                // **************************************************

                if (string.IsNullOrEmpty(userId))
                {
                    _logger.LogDebug("Getting user data from headers");

                    userId = context.Request.Headers[options.SiteMinderUserNameKey];
                    if (string.IsNullOrEmpty(userId))
                    {
                        userId = context.Request.Headers[options.SiteMinderUniversalIdKey];
                    }

                    siteMinderGuid         = context.Request.Headers[options.SiteMinderUserGuidKey];
                    siteMinderBusinessGuid = context.Request.Headers[options.SiteMinderBusinessGuidKey];
                    siteMinderUserType     = context.Request.Headers[options.SiteMinderUserTypeKey];


                    // **************************************************
                    // Validate credentials
                    // **************************************************
                    if (string.IsNullOrEmpty(userId))
                    {
                        _logger.LogDebug(options.MissingSiteMinderUserIdError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError));
                    }

                    if (string.IsNullOrEmpty(siteMinderGuid))
                    {
                        _logger.LogDebug(options.MissingSiteMinderGuidError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError));
                    }
                    if (string.IsNullOrEmpty(siteMinderUserType))
                    {
                        _logger.LogDebug(options.MissingSiteMinderUserTypeError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderUserTypeError));
                    }
                }
                else // DEV user, setup a fake session and SiteMinder headers.
                {
                    if (isDeveloperLogin && _dynamicsResultService != null)
                    {
                        _logger.LogError("Generating a Development user");
                        userSettings.BusinessLegalName = devCompanyId + " BusinessProfileName";
                        userSettings.UserDisplayName   = userId + " BCeIDContactType";

                        siteMinderGuid         = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString();
                        siteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString();
                        siteMinderUserType     = "Business";
                    }
                    else if (isBCSCDeveloperLogin)
                    {
                        _logger.LogError("Generating a Development BC Services user");
                        userSettings.BusinessLegalName = null;
                        userSettings.UserDisplayName   = userId + " Associate";
                        siteMinderGuid         = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString();
                        siteMinderBusinessGuid = null;
                        siteMinderUserType     = "VerifiedIndividual";
                    }
                }

                if (_dynamicsResultService != null)
                {
                    var businessBceid = siteMinderBusinessGuid;

                    _logger.LogDebug("We're \"Logged in\", businessBCeID: " + siteMinderBusinessGuid + ", UserBCeID: " + siteMinderGuid);

                    userSettings.AuthenticatedUser = new User(new Guid(siteMinderGuid), "Bill", "Octoroc", true, "BO", "*****@*****.**", siteMinderGuid, siteMinderBusinessGuid, siteMinderUserType, null);
                    userSettings.UserAuthenticated = true;

                    string requestJson = "{\"UserBCeID\":\"" + siteMinderGuid + "\",\"BusinessBCeID\":\"" + siteMinderBusinessGuid + "\"}";
                    // set the endpoint action
                    string         endpointUrl = "vsd_GetCPUOrgContracts";
                    DynamicsResult result      = await _dynamicsResultService.Post(endpointUrl, requestJson);

                    // Console.WriteLine("Dynamics result info:");
                    string resultString  = result.ToString();
                    string resultResult  = result.result.ToString();
                    string messageString = result.responseMessage.ToString();
                    int    code          = (int)result.statusCode;

                    // Console.WriteLine("resultResult");
                    // Console.WriteLine(resultResult);
                    // Console.WriteLine("messageString");
                    // Console.WriteLine(messageString);

                    userSettings.UserType  = siteMinderUserType;
                    userSettings.UserId    = siteMinderGuid;
                    userSettings.AccountId = siteMinderBusinessGuid;

                    //Error: No contact found with the supplied BCeID

                    string NEW_USER = "******";
                    string NEW_USER_AND_NEW_ORGANIZATION = "No organization and contact found with the supplied BCeID";
                    string CONTACT_NOT_APPROVED          = "Contact is not approved for portal access";
                    string CONTACT_NOT_CPU = "Contact doesn't belong to CPU";

                    if (resultResult.Contains(NEW_USER))
                    {
                        // Console.WriteLine("New User Registration");

                        userSettings.IsNewUserRegistration = true;
                        userSettings.IsNewUserAndNewOrganizationRegistration = false;
                        principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                        UserSettings.SaveUserSettings(userSettings, context);
                        return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                    }
                    else if (resultResult.Contains(NEW_USER_AND_NEW_ORGANIZATION))
                    {
                        // Console.WriteLine("New User and New Organization Registration");

                        userSettings.IsNewUserRegistration = false;
                        userSettings.IsNewUserAndNewOrganizationRegistration = true;
                        principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                        UserSettings.SaveUserSettings(userSettings, context);
                        return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                    }
                    else if (resultResult.Contains(CONTACT_NOT_APPROVED))
                    {
                        //error state - should hopefully never happen
                        // Console.WriteLine("Error, contact already exists but is not approved");

                        userSettings.ContactExistsButNotApproved = true;
                        principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                        UserSettings.SaveUserSettings(userSettings, context);
                        return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                    }
                    else if (resultResult.Contains(CONTACT_NOT_CPU))
                    {
                        //error state - should hopefully never happen
                        // Console.WriteLine("Error, contact does not belong to CPU...");

                        userSettings.ContactExistsButNotApproved = true;
                        principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                        UserSettings.SaveUserSettings(userSettings, context);
                        return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                    }
                    else
                    {
                        //TODO - should verify we did in fact get a success response

                        // Console.WriteLine("Found User Data");
                        // Console.WriteLine("We're \"Logged in\", businessBCeID: " + siteMinderBusinessGuid + ", UserBCeID: " + siteMinderGuid);
                        userSettings.IsNewUserRegistration = false;
                        userSettings.IsNewUserAndNewOrganizationRegistration = false;
                        // Console.WriteLine("UserSettings: " + userSettings.GetJson());
                        principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                        UserSettings.SaveUserSettings(userSettings, context);

                        return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                Console.WriteLine(exception);
                throw;
            }
            return(AuthenticateResult.NoResult());
        }
コード例 #16
0
        public async Task <DynamicsResult> Post(string endpointUrl, string modelJson)
        {
            DynamicsResult blob = await DynamicsResultAsync(HttpMethod.Post, endpointUrl, modelJson);

            return(blob);
        }
コード例 #17
0
        public async Task <DynamicsResult> Get(string endpointUrl)
        {
            DynamicsResult blob = await DynamicsResultAsync(HttpMethod.Get, endpointUrl, "");

            return(blob);
        }
コード例 #18
0
        public async Task <IActionResult> UploadSignedContract([FromBody] SignedContractPostFromPortal portalModel, string taskId)
        {
            // return null because this needs to be handled as files.
            try
            {
                if (portalModel == null)
                {
                    return(StatusCode(502));
                }

                string endpointUrl = "tasks(" + taskId + ")/Microsoft.Dynamics.CRM.vsd_UploadCPUContractPackage";


                SignedContractPostToDynamics data = new SignedContractPostToDynamics();
                data.BusinessBCeID = portalModel.BusinessBCeID;
                data.UserBCeID     = portalModel.UserBCeID;

                List <byte[]> byteArray         = new List <byte[]>();
                int           signaturePosition = -1;

                for (int i = 0; i < portalModel.DocumentCollection.Length - 1; ++i)
                {
                    byteArray.Add(System.Convert.FromBase64String(portalModel.DocumentCollection[i].body));
                    if (portalModel.DocumentCollection[i].filename.Contains("TUA"))
                    {
                        signaturePosition = i;
                    }
                }

                if (signaturePosition < 0)
                {
                    signaturePosition = portalModel.DocumentCollection.Length - 1;
                }

                byte[] signaturePage = System.Convert.FromBase64String(portalModel.DocumentCollection[portalModel.DocumentCollection.Length - 1].body);

                string signatureString = portalModel.Signature.vsd_authorizedsigningofficersignature;
                signatureString = signatureString.Replace("data:image/png;base64,", "");
                var offset         = signatureString.IndexOf(',') + 1;
                var signatureImage = System.Convert.FromBase64String(signatureString.Substring(offset));

                byte[] combinedArray = concatAndAddContent(byteArray, signaturePage, signaturePosition, signatureImage, portalModel.Signature.vsd_signingofficersname, portalModel.Signature.vsd_signingofficertitle);

                string combinedDoc = System.Convert.ToBase64String(combinedArray);

                data.SignedContract          = new DynamicsDocumentPost();
                data.SignedContract.body     = combinedDoc;
                data.SignedContract.filename = "Contract Package Signed by Service Provider.pdf";

                //for testing the document combining
                // return StatusCode((int)result.statusCode, data);

                //make options for the json serializer
                JsonSerializerOptions options = new JsonSerializerOptions();
                options.IgnoreNullValues = true;
                //turn the model into a string
                string modelString = System.Text.Json.JsonSerializer.Serialize(data, options);

                DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString);

                return(StatusCode((int)result.statusCode, result.result.ToString()));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
            finally { }
        }