Пример #1
0
 /// <inheritdoc />
 protected override void MergeData(MetadataResult <Video> source, MetadataResult <Video> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
 {
     ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
 }
Пример #2
0
 /// <exception cref="System.UriFormatException"/>
 /// <exception cref="System.IO.IOException"/>
 private static Path ExtractKMSPath(URI uri)
 {
     return(ProviderUtils.UnnestUri(uri));
 }
Пример #3
0
        public virtual HttpResponseMessage Post([FromUri] string serviceName, [FromUri] string jobName, [FromBody] jobType item, [MatrixParameter] string[] zone = null, [MatrixParameter] string[] context = null)
        {
            string sessionToken = CheckAuthorisation(serviceName, zone, context, new Right(RightType.CREATE, RightValue.APPROVED));

            HttpResponseMessage result;

            try
            {
                bool hasAdvisoryId    = ProviderUtils.IsAdvisoryId(item.id);
                bool?_mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);
                bool mustUseAdvisory  = _mustUseAdvisory.HasValue && _mustUseAdvisory.Value;

                IFunctionalService service = getService(serviceName);

                if (!service.AcceptJob(serviceName, jobName))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Service " + serviceName + " does not handle jobs named " + jobName));
                }

                if (hasAdvisoryId && !mustUseAdvisory)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request failed for creating job for " + serviceName + " as object ID provided (" + item.id + "), but mustUseAdvisory is not specified or is false.\n" +
                                                       !Guid.Empty.ToString().Equals(item.id)));
                }

                if (!hasAdvisoryId && mustUseAdvisory)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request requires use of advisory id, but none has been supplied."));
                }

                Guid id = service.Create(item, zone: (zone == null ? null : zone[0]), context: (context == null ? null : context[0]));

                if (SettingsManager.ProviderSettings.JobBinding)
                {
                    service.Bind(id, getOwnerId(sessionToken));
                }

                jobType job = service.Retrieve(id, zone: (zone == null ? null : zone[0]), context: (context == null ? null : context[0]));

                string uri = Url.Link("ServicesRoute", new { controller = serviceName, id = id });

                result = Request.CreateResponse <jobType>(HttpStatusCode.Created, job);
                result.Headers.Location = new Uri(uri);
            }
            catch (AlreadyExistsException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.Conflict, e);
            }
            catch (ArgumentException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Object to create Job is invalid.\n ", e);
            }
            catch (CreateException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request failed for Job.\n ", e);
            }
            catch (RejectedException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Create request rejected for Job" + (item.id == null ? "" : " with advisory id " + item.id) + ".\n", e);
            }
            catch (QueryException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request failed for Job.\n", e);
            }
            catch (Exception e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
            return(result);
        }
Пример #4
0
 protected override void MergeData(MetadataResult <MusicGenre> source, MetadataResult <MusicGenre> target, List <MetadataFields> lockedFields, bool replaceData, bool mergeMetadataSettings)
 {
     ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
 }
Пример #5
0
 private IWrapper DoCreateWrapper(bool forWrapping, WrapParameters parameters)
 {
     return(ProviderUtils.CreateWrapper("FipsTripleDes", parameters.Algorithm.Mode, parameters.IsUsingInverseFunction, forWrapping, desEdeEngineProvider));
 }
Пример #6
0
        public virtual HttpResponseMessage Post([FromUri] string serviceName, [FromBody] jobCollectionType items, [MatrixParameter] string[] zone = null, [MatrixParameter] string[] context = null)
        {
            string sessionToken = CheckAuthorisation(serviceName, zone, context, new Right(RightType.CREATE, RightValue.APPROVED));

            HttpResponseMessage result;

            try
            {
                IFunctionalService service = getService(serviceName);

                List <createType> creates = new List <createType>();
                foreach (jobType job in items.job)
                {
                    try
                    {
                        if (!service.AcceptJob(serviceName, job.name))
                        {
                            throw new ArgumentException("Service " + serviceName + " does not handle jobs named " + job.name);
                        }
                        Guid id = service.Create(job, zone: (zone == null ? null : zone[0]), context: (context == null ? null : context[0]));

                        if (SettingsManager.ProviderSettings.JobBinding)
                        {
                            service.Bind(id, getOwnerId(sessionToken));
                        }

                        creates.Add(ProviderUtils.CreateCreate(HttpStatusCode.Created, id.ToString(), job.id));
                    }
                    catch (CreateException e)
                    {
                        ProviderUtils.CreateCreate(HttpStatusCode.Conflict, job.id, error: ProviderUtils.CreateError(HttpStatusCode.Conflict, HttpStatusCode.Conflict.ToString(), e.Message));
                    }
                }

                createResponseType createResponse = ProviderUtils.CreateCreateResponse(creates.ToArray());

                result = Request.CreateResponse <createResponseType>(HttpStatusCode.Created, createResponse);
                string uri = Url.Link("ServicesRoute", new { controller = serviceName });
                result.Headers.Location = new Uri(uri);
            }
            catch (AlreadyExistsException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.Conflict, e);
            }
            catch (ArgumentException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Object to create Jobs is invalid.\n ", e);
            }
            catch (CreateException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request failed for creating Jobs.\n ", e);
            }
            catch (RejectedException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Create request rejected for creating Jobs.\n", e);
            }
            catch (QueryException e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request failed for Job.\n", e);
            }
            catch (Exception e)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
            return(result);
        }
Пример #7
0
        /// <exception cref="System.IO.IOException"/>
        private JavaKeyStoreProvider(URI uri, Configuration conf)
            : base(conf)
        {
            this.uri = uri;
            path     = ProviderUtils.UnnestUri(uri);
            fs       = path.GetFileSystem(conf);
            // Get the password file from the conf, if not present from the user's
            // environment var
            if (Runtime.GetEnv().Contains(KeystorePasswordEnvVar))
            {
                password = Runtime.Getenv(KeystorePasswordEnvVar).ToCharArray();
            }
            if (password == null)
            {
                string pwFile = conf.Get(KeystorePasswordFileKey);
                if (pwFile != null)
                {
                    ClassLoader cl      = Thread.CurrentThread().GetContextClassLoader();
                    Uri         pwdFile = cl.GetResource(pwFile);
                    if (pwdFile == null)
                    {
                        // Provided Password file does not exist
                        throw new IOException("Password file does not exists");
                    }
                    using (InputStream @is = pwdFile.OpenStream())
                    {
                        password = IOUtils.ToString(@is).Trim().ToCharArray();
                    }
                }
            }
            if (password == null)
            {
                password = KeystorePasswordDefault;
            }
            try
            {
                Path oldPath = ConstructOldPath(path);
                Path newPath = ConstructNewPath(path);
                keyStore = KeyStore.GetInstance(SchemeName);
                FsPermission perm = null;
                if (fs.Exists(path))
                {
                    // flush did not proceed to completion
                    // _NEW should not exist
                    if (fs.Exists(newPath))
                    {
                        throw new IOException(string.Format("Keystore not loaded due to some inconsistency "
                                                            + "('%s' and '%s' should not exist together)!!", path, newPath));
                    }
                    perm = TryLoadFromPath(path, oldPath);
                }
                else
                {
                    perm = TryLoadIncompleteFlush(oldPath, newPath);
                }
                // Need to save off permissions in case we need to
                // rewrite the keystore in flush()
                permissions = perm;
            }
            catch (KeyStoreException e)
            {
                throw new IOException("Can't create keystore", e);
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new IOException("Can't load keystore " + path, e);
            }
            catch (CertificateException e)
            {
                throw new IOException("Can't load keystore " + path, e);
            }
            ReadWriteLock Lock = new ReentrantReadWriteLock(true);

            readLock  = Lock.ReadLock();
            writeLock = Lock.WriteLock();
        }
 /// <summary>
 /// Check whether the specified type defines a Controller endpoint.
 /// </summary>
 /// <param name="type">Type to check.</param>
 /// <returns>True if the endpoint defines a Controller; false otherwise.</returns>
 internal static bool IsHttpEndpoint(Type type)
 {
     return(ProviderUtils.isController(type));
 }
Пример #9
0
        /// <summary>
        /// This function needs to process and returned message from the bank.
        /// This processing may vary widely between banks.
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var modCtrl = new NBrightBuyController();
            var info    = modCtrl.GetPluginSinglePageData("OSPayPalpayment", "OSPayPalPAYMENT", Utils.GetCurrentCulture());

            try
            {
                var ipn       = new PayPalIpnParameters(context.Request);
                var debugMode = info.GetXmlPropertyBool("genxml/checkbox/debug.mode");
                var debugMsg  = "START CALL" + DateTime.Now.ToString("s") + " </br>";
                var rtnMsg    = "version=2" + Environment.NewLine + "cdr=1";

                // ------------------------------------------------------------------------
                // In this case the payment provider passes back data via form POST.
                // Get the data we need.
                string returnmessage        = "";
                int    OSPayPalStoreOrderID = 0;
                string OSPayPalCartID       = "";
                string OSPayPalClientLang   = "";


                if (Utils.IsNumeric(ipn.item_number))
                {
                    var validateUrl = info.GetXmlProperty("genxml/textbox/paymenturl") + "?" + ipn.PostString;

                    // check the record exists
                    debugMsg += "OrderId: " + ipn.item_number + " </br>";
                    var nbi = modCtrl.Get(Convert.ToInt32(ipn.item_number), "ORDER");
                    if (nbi != null)
                    {
                        var orderData = new OrderData(nbi.ItemID);
                        debugMsg += "validateUrl: " + validateUrl + " </br>";
                        if (ProviderUtils.VerifyPayment(ipn, validateUrl))
                        {
                            //set order status to Payed
                            debugMsg += "PaymentOK </br>";
                            orderData.PaymentOk();
                        }
                        else
                        {
                            if (ipn.IsValid)
                            {
                                debugMsg += "NOT VALIDATED BY PAYPAL </br>";
                                //set order status to Not verified
                                orderData.PaymentOk("050");
                            }
                            else
                            {
                                if (orderData.OrderStatus == "020" || orderData.OrderStatus == "010" || orderData.OrderStatus == "030")
                                {
                                    debugMsg += "PAYMENT FAIL </br>";
                                    orderData.PaymentFail();
                                }
                                else
                                {
                                    debugMsg += "INVALID UPDATE ACTION</br>";
                                }
                            }
                        }
                    }
                    else
                    {
                        debugMsg += "ORDER does not exists";
                    }
                    if (debugMode)
                    {
                        info.SetXmlProperty("genxml/debugmsg", debugMsg);
                        modCtrl.Update(info);
                    }
                }

                if (debugMode)
                {
                    debugMsg += "Return Message: " + rtnMsg;
                    info.SetXmlProperty("genxml/debugmsg", debugMsg);
                    modCtrl.Update(info);
                }


                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write(rtnMsg);
                HttpContext.Current.Response.ContentType  = "text/plain";
                HttpContext.Current.Response.CacheControl = "no-cache";
                HttpContext.Current.Response.Expires      = -1;
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                if (!ex.ToString().StartsWith("System.Threading.ThreadAbortException")) // we expect a thread abort from the End response.
                {
                    info.SetXmlProperty("genxml/debugmsg", "OS_PayPal ERROR: " + ex.ToString());
                    modCtrl.Update(info);
                }
            }
        }
Пример #10
0
 static TaxProvider()
 {
     _info    = ProviderUtils.GetProviderSettings("tax");
     _taxType = _info.GetXmlProperty("genxml/radiobuttonlist/taxtype");
 }
Пример #11
0
            public IMacFactory <AuthenticationParametersWithIV> CreateMacFactory(AuthenticationParametersWithIV algorithmDetails)
            {
                IEngineProvider <IMac> macProvider = ProviderUtils.CreateMacProvider("FipsAES", algorithmDetails, aesEngineProvider);

                return(new MacFactory <AuthenticationParametersWithIV>(algorithmDetails, macProvider, (algorithmDetails.MacSizeInBits + 7) / 8));
            }
Пример #12
0
        /// <summary>
        /// <see cref="Provider{TSingle, TMultiple}.Post(TMultiple, string[], string[])">Post</see>
        /// </summary>
        public override IHttpActionResult Post(List <T> objs, [MatrixParameter] string[] zoneId = null, [MatrixParameter] string[] contextId = null)
        {
            if (!authService.VerifyAuthenticationHeader(Request.Headers))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest("Request failed for object " + typeof(T).Name + " as Zone and/or Context are invalid."));
            }

            IHttpActionResult        result;
            ICollection <createType> createStatuses = new List <createType>();

            try
            {
                foreach (T obj in objs)
                {
                    bool       hasAdvisoryId = !string.IsNullOrWhiteSpace(obj.RefId);
                    createType status        = new createType();
                    status.advisoryId = (hasAdvisoryId ? obj.RefId : null);

                    try
                    {
                        bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

                        if (hasAdvisoryId)
                        {
                            if (mustUseAdvisory.HasValue && mustUseAdvisory.Value == true)
                            {
                                status.id         = service.Create(obj, mustUseAdvisory, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0])).RefId;
                                status.statusCode = ((int)HttpStatusCode.Created).ToString();
                            }
                            else
                            {
                                status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(T).Name, "Create request failed as object ID provided (" + obj.RefId + "), but mustUseAdvisory is not specified or is false.");
                                status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                            }
                        }
                        else
                        {
                            if (mustUseAdvisory.HasValue && mustUseAdvisory.Value == true)
                            {
                                status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(T).Name, "Create request failed as object ID is not provided, but mustUseAdvisory is true.");
                                status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                            }
                            else
                            {
                                status.id         = service.Create(obj, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0])).RefId;
                                status.statusCode = ((int)HttpStatusCode.Created).ToString();
                            }
                        }
                    }
                    catch (AlreadyExistsException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.Conflict, typeof(T).Name, "Object " + typeof(T).Name + " with ID of " + obj.RefId + " already exists.\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.Conflict).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(T).Name, "Object to create of type " + typeof(T).Name + (hasAdvisoryId ? " with ID of " + obj.RefId : "") + " is invalid.\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (CreateException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(T).Name, "Request failed for object " + typeof(T).Name + (hasAdvisoryId ? " with ID of " + obj.RefId : "") + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (RejectedException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.NotFound, typeof(T).Name, "Create request rejected for object " + typeof(T).Name + " with ID of " + obj.RefId + ".\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.Conflict).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.InternalServerError, typeof(T).Name, "Request failed for object " + typeof(T).Name + (hasAdvisoryId ? " with ID of " + obj.RefId : "") + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    createStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            createResponseType createResponse = new createResponseType {
                creates = createStatuses.ToArray()
            };

            result = Ok(createResponse);

            return(result);
        }
 /// <exception cref="System.IO.IOException"/>
 protected internal virtual void InitFileSystem(URI keystoreUri, Configuration conf
                                                )
 {
     path = ProviderUtils.UnnestUri(keystoreUri);
 }
        /// <summary>
        /// <see cref="Provider{TSingle, TMultiple}.Post(TMultiple, string[], string[])">Post</see>
        /// </summary>
        public override IHttpActionResult Post(
            List <T> objs,
            [MatrixParameter] string[] zoneId    = null,
            [MatrixParameter] string[] contextId = null)
        {
            if (!AuthenticationService.VerifyAuthenticationHeader(Request.Headers, out string sessionToken))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.
            if (!AuthorisationService.IsAuthorised(Request.Headers, sessionToken, $"{TypeName}s", RightType.CREATE))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest($"Request failed for object {TypeName} as Zone and/or Context are invalid."));
            }

            ICollection <createType> createStatuses = new List <createType>();

            try
            {
                bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

                foreach (T obj in objs)
                {
                    bool hasAdvisoryId = !string.IsNullOrWhiteSpace(obj.RefId);
                    var  status        = new createType
                    {
                        advisoryId = (hasAdvisoryId ? obj.RefId : null)
                    };

                    try
                    {
                        if (mustUseAdvisory.HasValue)
                        {
                            if (mustUseAdvisory.Value && !hasAdvisoryId)
                            {
                                status.error = ProviderUtils.CreateError(
                                    HttpStatusCode.BadRequest,
                                    TypeName,
                                    "Create request failed as object ID is not provided, but mustUseAdvisory is true.");
                                status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                            }
                            else
                            {
                                status.id         = Service.Create(obj, mustUseAdvisory, zoneId?[0], contextId?[0]).RefId;
                                status.statusCode = ((int)HttpStatusCode.Created).ToString();
                            }
                        }
                        else
                        {
                            status.id         = Service.Create(obj, null, zoneId?[0], contextId?[0]).RefId;
                            status.statusCode = ((int)HttpStatusCode.Created).ToString();
                        }
                    }
                    catch (AlreadyExistsException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.Conflict,
                            TypeName,
                            $"Object {TypeName} with ID of {obj.RefId} already exists.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.Conflict).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.BadRequest,
                            TypeName,
                            $"Object to create of type {TypeName}" + (hasAdvisoryId ? $" with ID of {obj.RefId}" : "") + $" is invalid.\n {e.Message}");
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (CreateException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.BadRequest,
                            TypeName,
                            $"Request failed for object {TypeName}" + (hasAdvisoryId ? $" with ID of {obj.RefId}" : "") + $".\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (RejectedException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.NotFound,
                            TypeName,
                            $"Create request rejected for object {TypeName} with ID of {obj.RefId}.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.Conflict).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.InternalServerError,
                            TypeName,
                            $"Request failed for object {TypeName}" + (hasAdvisoryId ? $" with ID of {obj.RefId}" : "") + $".\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    createStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            var createResponse = new createResponseType {
                creates = createStatuses.ToArray()
            };

            return(Ok(createResponse));
        }
        /// <summary>
        /// <see cref="IProvider{TTSingle,TMultiple,TPrimaryKey}.Delete(deleteRequestType, string[], string[])">Delete</see>
        /// </summary>
        public virtual IHttpActionResult Delete(deleteRequestType deleteRequest, [MatrixParameter] string[] zoneId = null, [MatrixParameter] string[] contextId = null)
        {
            if (!authService.VerifyAuthenticationHeader(Request.Headers))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest("Request failed for object " + typeof(TSingle).Name + " as Zone and/or Context are invalid."));
            }

            IHttpActionResult          result;
            ICollection <deleteStatus> deleteStatuses = new List <deleteStatus>();

            try
            {
                foreach (deleteIdType deleteId in deleteRequest.deletes)
                {
                    deleteStatus status = new deleteStatus();
                    status.id = deleteId.id;

                    try
                    {
                        service.Delete(deleteId.id, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0]));
                        status.statusCode = ((int)HttpStatusCode.NoContent).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(TSingle).Name, "Invalid argument: id=" + deleteId.id + ".\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (DeleteException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(TSingle).Name, "Request failed for object " + typeof(TSingle).Name + " with ID of " + deleteId.id + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (NotFoundException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.NotFound, typeof(TSingle).Name, "Object " + typeof(TSingle).Name + " with ID of " + deleteId.id + " not found.\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.NotFound).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.InternalServerError, typeof(TSingle).Name, "Request failed for object " + typeof(TSingle).Name + " with ID of " + deleteId.id + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    deleteStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            deleteResponseType deleteResponse = new deleteResponseType {
                deletes = deleteStatuses.ToArray()
            };

            result = Ok(deleteResponse);

            return(result);
        }
Пример #16
0
        /// <summary>
        /// This function needs to process and returned message from the bank.
        /// This processing may vary widely between banks.
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var info = ProviderUtils.GetProviderSettings();

            var            objEventLog    = new EventLogController();
            PortalSettings portalsettings = new PortalSettings();

            try
            {
                var debugMode = info.GetXmlPropertyBool("genxml/checkbox/debugmode");
                var debugMsg  = "START CALL" + DateTime.Now.ToString("s") + " </br>";
                var rtnMsg    = "version=2" + Environment.NewLine + "cdr=1";

                var orderid = Utils.RequestQueryStringParam(context, "orderid");

                debugMsg += "orderid: " + orderid + "</br>";


                if (Utils.IsNumeric(orderid))
                {
                    var orderData = new OrderData(Convert.ToInt32(orderid));

                    PaymentResponse paymentClientResult = ProviderUtils.GetOrderPaymentResponse(orderData, "OS_MollieNotify.ProcessRequest");

                    objEventLog.AddLog("Mollie Webhook call for orderid: " + orderid, "Status: " + paymentClientResult.Status, portalsettings, -1, EventLogController.EventLogType.ADMIN_ALERT);

                    //Waiting for Payment 060
                    //Payment OK 040
                    //Incomplete 010
                    //Cancelled 030

                    switch (paymentClientResult.Status.ToString().ToLower())
                    {
                    case "paid":
                        orderData.PaymentOk("040", true);
                        rtnMsg = "OK";
                        break;

                    case "failed":
                        orderData.PaymentFail("010");
                        rtnMsg = "OK";
                        break;

                    case "canceled":
                        orderData.PaymentFail("030");
                        rtnMsg = "OK";
                        break;

                    case "expired":
                        orderData.PaymentFail("010");
                        rtnMsg = "OK";
                        break;

                    default:
                        orderData.PaymentFail("010");
                        rtnMsg = "OK";
                        break;
                    }
                }
                if (debugMode)
                {
                    debugMsg += "Return Message: " + rtnMsg;
                    info.SetXmlProperty("genxml/debugmsg", debugMsg);
                    var modCtrl = new NBrightBuyController();
                    modCtrl.Update(info);
                }

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write(rtnMsg);
                HttpContext.Current.Response.ContentType  = "text/plain";
                HttpContext.Current.Response.CacheControl = "no-cache";
                HttpContext.Current.Response.Expires      = -1;
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                objEventLog.AddLog("Mollie Webhook call failed", ex.Message + " " + ex.InnerException, portalsettings, -1, EventLogController.EventLogType.ADMIN_ALERT);

                if (!ex.ToString().StartsWith("System.Threading.ThreadAbortException")) // we expect a thread abort from the End response.
                {
                    info.SetXmlProperty("genxml/debugmsg", "OS_Mollie ERROR: " + ex.ToString());
                    var modCtrl = new NBrightBuyController();
                    modCtrl.Update(info);
                }
            }
        }
        /// <summary>
        /// <see cref="Provider{TSingle, TMultiple}.Put(TMultiple, string[], string[])">Put</see>
        /// </summary>
        public override IHttpActionResult Put(List <T> objs, [MatrixParameter] string[] zoneId = null, [MatrixParameter] string[] contextId = null)
        {
            if (!authService.VerifyAuthenticationHeader(Request.Headers))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest("Request failed for object " + typeof(T).Name + " as Zone and/or Context are invalid."));
            }

            IHttpActionResult        result;
            ICollection <updateType> updateStatuses = new List <updateType>();

            try
            {
                foreach (T obj in objs)
                {
                    updateType status = new updateType();
                    status.id = obj.RefId;

                    try
                    {
                        service.Update(obj, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0]));
                        status.statusCode = ((int)HttpStatusCode.NoContent).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(T).Name, "Object to update of type " + typeof(T).Name + " is invalid.\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (NotFoundException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.NotFound, typeof(T).Name, "Object " + typeof(T).Name + " with ID of " + obj.RefId + " not found.\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.NotFound).ToString();
                    }
                    catch (UpdateException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(T).Name, "Request failed for object " + typeof(T).Name + " with ID of " + obj.RefId + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.InternalServerError, typeof(T).Name, "Request failed for object " + typeof(T).Name + " with ID of " + obj.RefId + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    updateStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            updateResponseType updateResponse = new updateResponseType {
                updates = updateStatuses.ToArray()
            };

            result = Ok(updateResponse);

            return(result);
        }
Пример #18
0
        /// <summary>
        /// This function needs to process and returned message from the bank.
        /// Thsi processing may vary widely between banks.
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var modCtrl = new NBrightBuyController();
            var info    = modCtrl.GetPluginSinglePageData("OS_Sipspayment", "OS_SipsPAYMENT", Utils.GetCurrentCulture());

            try
            {
                var debugMode = info.GetXmlPropertyBool("genxml/checkbox/debugmode");
                var rtnMsg    = "version=2" + Environment.NewLine + "cdr=1";

                // ------------------------------------------------------------------------
                // In this case the payment provider passes back data via form POST.
                // Get the data we need.
                string returnmessage = "";
                int    NBrightBuySipsApiStoreOrderID = 0;
                string NBrightBuySipsApiCartID       = "";
                string NBrightBuySipsApiClientLang   = "";

                if ((context.Request.Form.Get("DATA") != null))
                {
                    returnmessage = "message=" + context.Request.Form.Get("DATA");

                    if (!string.IsNullOrEmpty(returnmessage))
                    {
                        // ------------------------------------------------------------------------
                        //var settings = ProviderUtils.GetProviderSettings("NBrightBuySipsApipayment");

                        var controlMapPath = HttpContext.Current.Server.MapPath("/DesktopModules/NBright/OS_Sips");
                        var pathfile       = "pathfile=" + PortalSettings.Current.HomeDirectoryMapPath.TrimEnd('\\') + "\\" + info.GetXmlProperty("genxml/textbox/paramfolder") + "\\pathfile";

                        var exepath  = controlMapPath.TrimEnd('\\') + "\\sipsbin\\response.exe";
                        var sipsdata = ProviderUtils.CallSipsExec(exepath, pathfile + " " + returnmessage);

                        if (debugMode)
                        {
                            info.SetXmlProperty("genxml/debugmsg", sipsdata);
                            modCtrl.Update(info);
                        }

                        var tableau = sipsdata.Split('!');

                        string code      = tableau[1];
                        string error_msg = tableau[2];

                        if (string.IsNullOrEmpty(code) | code == "-1")
                        {
                            info.SetXmlProperty("genxml/debugmsg", error_msg);
                            modCtrl.Update(info);
                        }
                        else
                        {
                            // L'execution s'est bien deroulee
                            // recuperation des donnees de la reponse

                            string merchant_id         = tableau[3];
                            string merchant_country    = tableau[4];
                            string amount              = tableau[5];
                            string transaction_id      = tableau[6];
                            string payment_means       = tableau[7];
                            string transmission_date   = tableau[8];
                            string payment_time        = tableau[9];
                            string payment_date        = tableau[10];
                            string response_code       = tableau[11];
                            string payment_certificate = tableau[12];
                            string authorisation_id    = tableau[13];
                            string currency_code       = tableau[14];
                            string card_number         = tableau[15];
                            string cvv_flag            = tableau[16];
                            string cvv_response_code   = tableau[17];
                            string bank_response_code  = tableau[18];
                            string complementary_code  = tableau[19];
                            string complementary_info  = tableau[20];
                            string return_context      = tableau[21];
                            string caddie              = tableau[22];
                            string receipt_complement  = tableau[23];
                            string merchant_language   = tableau[24];
                            string language            = tableau[25];
                            string customer_id         = tableau[26];
                            string order_id            = tableau[27];
                            string customer_email      = tableau[28];
                            string customer_ip_address = tableau[29];
                            string capture_day         = tableau[30];
                            string capture_mode        = tableau[31];
                            string data = tableau[32];

                            // Sauvegarde des champs de la reponse
                            string Lmsg = null;

                            Lmsg  = merchant_id + ",";
                            Lmsg += merchant_country + ",";
                            Lmsg += amount + ",";
                            Lmsg += transaction_id + ",";
                            Lmsg += transmission_date + ",";
                            Lmsg += payment_means + ",";
                            Lmsg += payment_time + ",";
                            Lmsg += payment_date + ",";
                            Lmsg += response_code + ",";
                            Lmsg += payment_certificate + ",";
                            Lmsg += authorisation_id + ",";
                            Lmsg += currency_code + ",";
                            Lmsg += card_number + ",";
                            Lmsg += cvv_flag + ",";
                            Lmsg += cvv_response_code + ",";
                            Lmsg += bank_response_code + ",";
                            Lmsg += complementary_code + ",";
                            Lmsg += complementary_info + ",";
                            Lmsg += return_context + ",";
                            Lmsg += caddie + ",";
                            Lmsg += receipt_complement + ",";
                            Lmsg += merchant_language + ",";
                            Lmsg += language + ",";
                            Lmsg += customer_id + ",";
                            Lmsg += order_id + ",";
                            Lmsg += customer_email + ",";
                            Lmsg += customer_ip_address + ",";
                            Lmsg += capture_day + ",";
                            Lmsg += capture_mode + ",";
                            Lmsg += data + ",";

                            //update database stuff
                            if (Utils.IsNumeric(order_id))
                            {
                                var orderData = new OrderData(Convert.ToInt32(order_id));
                                orderData.AddAuditMessage(Lmsg, "payment", "sipsapi", info.GetXmlProperty("genxml/checkbox/debugmode"));
                                // Status return "00" is payment successful
                                if (response_code == "00")
                                {
                                    //set order status to Payed
                                    orderData.PaymentOk();
                                }
                                else
                                {
                                    orderData.PaymentFail();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!ex.ToString().StartsWith("System.Threading.ThreadAbortException"))  // we expect a thread abort from the End response.
                {
                    info.SetXmlProperty("genxml/debugmsg", "NBrightBuySipsApi ERROR: " + ex.ToString());
                    modCtrl.Update(info);
                }
            }
        }
Пример #19
0
        public override IHttpActionResult Post(List <StudentPersonal> objs, [MatrixParameter] string[] zoneId = null, [MatrixParameter] string[] contextId = null)
        {
            foreach (KeyValuePair <string, IEnumerable <string> > nameValues in Request.Headers)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug($"*** Header field is [{nameValues.Key}:{string.Join(",", nameValues.Value)}]");
                }
            }

            //return base.Post(objs, zoneId, contextId);
            string sessionToken;

            if (!authenticationService.VerifyAuthenticationHeader(Request.Headers, out sessionToken))
            {
                return(Unauthorized());
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest("Request failed for object " + typeof(StudentPersonal).Name + " as Zone and/or Context are invalid."));
            }

            IHttpActionResult        result;
            ICollection <createType> createStatuses = new List <createType>();

            try
            {
                bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

                foreach (StudentPersonal obj in objs)
                {
                    bool       hasAdvisoryId = !string.IsNullOrWhiteSpace(obj.RefId);
                    createType status        = new createType();
                    status.advisoryId = (hasAdvisoryId ? obj.RefId : null);

                    try
                    {
                        if (mustUseAdvisory.HasValue && mustUseAdvisory.Value == true)
                        {
                            if (hasAdvisoryId)
                            {
                                status.id         = service.Create(obj, mustUseAdvisory, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0])).RefId;
                                status.statusCode = ((int)HttpStatusCode.Created).ToString();
                            }
                            else
                            {
                                status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(StudentPersonal).Name, "Create request failed as object ID is not provided, but mustUseAdvisory is true.");
                                status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                            }
                        }
                        else
                        {
                            status.id         = service.Create(obj, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0])).RefId;
                            status.statusCode = ((int)HttpStatusCode.Created).ToString();
                        }
                    }
                    catch (AlreadyExistsException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.Conflict, typeof(StudentPersonal).Name, "Object " + typeof(StudentPersonal).Name + " with ID of " + obj.RefId + " already exists.\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.Conflict).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(StudentPersonal).Name, "Object to create of type " + typeof(StudentPersonal).Name + (hasAdvisoryId ? " with ID of " + obj.RefId : "") + " is invalid.\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (CreateException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.BadRequest, typeof(StudentPersonal).Name, "Request failed for object " + typeof(StudentPersonal).Name + (hasAdvisoryId ? " with ID of " + obj.RefId : "") + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (RejectedException e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.NotFound, typeof(StudentPersonal).Name, "Create request rejected for object " + typeof(StudentPersonal).Name + " with ID of " + obj.RefId + ".\n" + e.Message);
                        status.statusCode = ((int)HttpStatusCode.Conflict).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error      = ProviderUtils.CreateError(HttpStatusCode.InternalServerError, typeof(StudentPersonal).Name, "Request failed for object " + typeof(StudentPersonal).Name + (hasAdvisoryId ? " with ID of " + obj.RefId : "") + ".\n " + e.Message);
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    createStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            createResponseType createResponse = new createResponseType {
                creates = createStatuses.ToArray()
            };

            result = Ok(createResponse);

            return(result);
        }
Пример #20
0
            public IMacFactory <AuthenticationParameters> CreateMacFactory(AuthenticationParameters algorithmDetails)
            {
                IEngineProvider <IMac> macProvider = ProviderUtils.CreateMacProvider("FipsTripleDes", algorithmDetails, desEdeEngineProvider);

                return(new MacFactory <AuthenticationParameters>(algorithmDetails, macProvider, (algorithmDetails.MacSizeInBits + 7) / 8));
            }
        /// <summary>
        /// Adds the specified user names to the specified roles for the configured applicationName.
        /// </summary>
        /// <param name="userNames">A string array of user names to be added to the specified roles.</param>
        /// <param name="roleNames">A string array of the role names to add the specified user names to.</param>
        public override void AddUsersToRoles(string[] userNames, string[] roleNames)
        {
            using (InventoryManagementEntities context = new InventoryManagementEntities())
            {
                IQueryable <aspnet_Roles> roles = context.aspnet_Roles.Where(MatchRoleApplication()).Where(ProviderUtils.BuildContainsExpression <aspnet_Roles, string>(r => r.RoleName, roleNames));
                if (roles.Count() != roleNames.Length)
                {
                    throw new ProviderException("Role not found.");
                }

                IQueryable <aspnet_Membership> users = context.aspnet_Membership.Where(MatchUserApplication()).Where(ProviderUtils.BuildContainsExpression <aspnet_Membership, string>(u => u.aspnet_Users.UserName, userNames));
                if (users.Count() != userNames.Length)
                {
                    throw new ProviderException("User not found.");
                }

                try
                {
                    foreach (aspnet_Membership user in users)
                    {
                        foreach (aspnet_Roles role in roles)
                        {
                            // Check whether user is already in role
                            if (IsUserInRole(user.aspnet_Users.UserName, role.RoleName))
                            {
                                throw new ProviderException(string.Format("User is already in role '{0}'.", role.RoleName));
                            }

                            user.aspnet_Users.aspnet_Roles.Add(role);
                        }
                    }

                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(ex, "AddUsersToRoles");
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    //context..Connection.Close();
                }
            }
        }
Пример #22
0
        public virtual HttpResponseMessage Delete([FromUri] string serviceName, [FromBody] deleteRequestType deleteRequest, [MatrixParameter] string[] zone = null, [MatrixParameter] string[] context = null)
        {
            string sessionToken = CheckAuthorisation(serviceName, zone, context, new Right(RightType.DELETE, RightValue.APPROVED));

            IFunctionalService         service  = getService(serviceName);
            ICollection <deleteStatus> statuses = new List <deleteStatus>();

            foreach (deleteIdType deleteId in deleteRequest.deletes)
            {
                try
                {
                    if (SettingsManager.ProviderSettings.JobBinding &&
                        !service.IsBound(Guid.Parse(deleteId.id), getOwnerId(sessionToken)))
                    {
                        throw new InvalidSessionException("Request failed as job does not belong to this consumer.");
                    }

                    service.Delete(Guid.Parse(deleteId.id), zone: (zone == null ? null : zone[0]), context: (context == null ? null : context[0]));

                    if (SettingsManager.ProviderSettings.JobBinding)
                    {
                        service.Unbind(Guid.Parse(deleteId.id));
                    }

                    statuses.Add(ProviderUtils.CreateDelete(HttpStatusCode.OK, deleteId.id));
                }
                catch (ArgumentException e)
                {
                    statuses.Add(ProviderUtils.CreateDelete(HttpStatusCode.BadRequest, deleteId.id, ProviderUtils.CreateError(HttpStatusCode.BadRequest, serviceName, "Invalid argument: id=" + deleteId.id + ".\n" + e.Message)));
                }
                catch (DeleteException e)
                {
                    statuses.Add(ProviderUtils.CreateDelete(HttpStatusCode.BadRequest, deleteId.id, ProviderUtils.CreateError(HttpStatusCode.BadRequest, serviceName, "Request failed for object " + serviceName + " with ID of " + deleteId.id + ".\n " + e.Message)));
                }
                catch (NotFoundException e)
                {
                    statuses.Add(ProviderUtils.CreateDelete(HttpStatusCode.NotFound, deleteId.id, ProviderUtils.CreateError(HttpStatusCode.BadRequest, serviceName, "Object " + serviceName + " with ID of " + deleteId.id + " not found.\n" + e.Message)));
                }
                catch (InvalidSessionException e)
                {
                    statuses.Add(ProviderUtils.CreateDelete(HttpStatusCode.BadRequest, deleteId.id, ProviderUtils.CreateError(HttpStatusCode.BadRequest, serviceName, "Request failed for object " + serviceName + " with ID of " + deleteId.id + ", job doesn't belong to this consumer.\n " + e.Message)));
                }
                catch (Exception e)
                {
                    statuses.Add(ProviderUtils.CreateDelete(HttpStatusCode.InternalServerError, deleteId.id, ProviderUtils.CreateError(HttpStatusCode.BadRequest, serviceName, "Request failed for object " + serviceName + " with ID of " + deleteId.id + ".\n " + e.Message)));
                }
            }

            return(Request.CreateResponse <deleteResponseType>(HttpStatusCode.OK, ProviderUtils.CreateDeleteResponse(statuses.ToArray())));
        }
        /// <summary>
        /// Removes the specified user names from the specified roles for the configured applicationName.
        /// </summary>
        /// <param name="userNames">A string array of user names to be removed from the specified roles.</param>
        /// <param name="roleNames">A string array of role names to remove the specified user names from.</param>
        public override void RemoveUsersFromRoles(string[] userNames, string[] roleNames)
        {
            using (InventoryManagementEntities context = new InventoryManagementEntities())
            {
                IQueryable <aspnet_Roles> roles = context.aspnet_Roles.Where(MatchRoleApplication()).Where(ProviderUtils.BuildContainsExpression <aspnet_Roles, string>(r => r.RoleName, roleNames));
                if (roles.Count() != roleNames.Length)
                {
                    throw new ProviderException("Role not found.");
                }

                IQueryable <aspnet_Membership> users = context.aspnet_Membership.Include("Role").Where(MatchUserApplication()).Where(ProviderUtils.BuildContainsExpression <aspnet_Membership, string>(u => u.aspnet_Users.UserName, userNames));
                if (users.Count() != userNames.Length)
                {
                    throw new ProviderException("User not found.");
                }

                try
                {
                    foreach (aspnet_Membership user in users)
                    {
                        foreach (aspnet_Roles role in roles)
                        {
                            /*if (!user.Role.IsLoaded)
                             * {
                             *  user.Role.Load();
                             * }*/

                            if (user.aspnet_Users.aspnet_Roles.Contains(role))
                            {
                                user.aspnet_Users.aspnet_Roles.Remove(role);
                            }
                        }
                    }

                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(ex, "RemoveUsersFromRoles");
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Пример #24
0
        public virtual void TestJksProvider()
        {
            Configuration conf    = new Configuration();
            Path          jksPath = new Path(testRootDir.ToString(), "test.jks");
            string        ourUrl  = JavaKeyStoreProvider.SchemeName + "://file" + jksPath.ToUri();
            FilePath      file    = new FilePath(testRootDir, "test.jks");

            file.Delete();
            conf.Set(KeyProviderFactory.KeyProviderPath, ourUrl);
            CheckSpecificProvider(conf, ourUrl);
            // START : Test flush error by failure injection
            conf.Set(KeyProviderFactory.KeyProviderPath, ourUrl.Replace(JavaKeyStoreProvider.
                                                                        SchemeName, FailureInjectingJavaKeyStoreProvider.SchemeName));
            // get a new instance of the provider to ensure it was saved correctly
            KeyProvider provider = KeyProviderFactory.GetProviders(conf)[0];
            // inject failure during keystore write
            FailureInjectingJavaKeyStoreProvider fProvider = (FailureInjectingJavaKeyStoreProvider
                                                              )provider;

            fProvider.SetWriteFail(true);
            provider.CreateKey("key5", new byte[] { 1 }, KeyProvider.Options(conf).SetBitLength
                                   (8));
            NUnit.Framework.Assert.IsNotNull(provider.GetCurrentKey("key5"));
            try
            {
                provider.Flush();
                NUnit.Framework.Assert.Fail("Should not succeed");
            }
            catch (Exception)
            {
            }
            // Ignore
            // SHould be reset to pre-flush state
            NUnit.Framework.Assert.IsNull(provider.GetCurrentKey("key5"));
            // Un-inject last failure and
            // inject failure during keystore backup
            fProvider.SetWriteFail(false);
            fProvider.SetBackupFail(true);
            provider.CreateKey("key6", new byte[] { 1 }, KeyProvider.Options(conf).SetBitLength
                                   (8));
            NUnit.Framework.Assert.IsNotNull(provider.GetCurrentKey("key6"));
            try
            {
                provider.Flush();
                NUnit.Framework.Assert.Fail("Should not succeed");
            }
            catch (Exception)
            {
            }
            // Ignore
            // SHould be reset to pre-flush state
            NUnit.Framework.Assert.IsNull(provider.GetCurrentKey("key6"));
            // END : Test flush error by failure injection
            conf.Set(KeyProviderFactory.KeyProviderPath, ourUrl.Replace(FailureInjectingJavaKeyStoreProvider
                                                                        .SchemeName, JavaKeyStoreProvider.SchemeName));
            Path       path = ProviderUtils.UnnestUri(new URI(ourUrl));
            FileSystem fs   = path.GetFileSystem(conf);
            FileStatus s    = fs.GetFileStatus(path);

            Assert.True(s.GetPermission().ToString().Equals("rwx------"));
            Assert.True(file + " should exist", file.IsFile());
            // Corrupt file and Check if JKS can reload from _OLD file
            FilePath oldFile = new FilePath(file.GetPath() + "_OLD");

            file.RenameTo(oldFile);
            file.Delete();
            file.CreateNewFile();
            Assert.True(oldFile.Exists());
            provider = KeyProviderFactory.GetProviders(conf)[0];
            Assert.True(file.Exists());
            Assert.True(oldFile + "should be deleted", !oldFile.Exists());
            VerifyAfterReload(file, provider);
            Assert.True(!oldFile.Exists());
            // _NEW and current file should not exist together
            FilePath newFile = new FilePath(file.GetPath() + "_NEW");

            newFile.CreateNewFile();
            try
            {
                provider = KeyProviderFactory.GetProviders(conf)[0];
                NUnit.Framework.Assert.Fail("_NEW and current file should not exist together !!");
            }
            catch (Exception)
            {
            }
            finally
            {
                // Ignore
                if (newFile.Exists())
                {
                    newFile.Delete();
                }
            }
            // Load from _NEW file
            file.RenameTo(newFile);
            file.Delete();
            try
            {
                provider = KeyProviderFactory.GetProviders(conf)[0];
                NUnit.Framework.Assert.IsFalse(newFile.Exists());
                NUnit.Framework.Assert.IsFalse(oldFile.Exists());
            }
            catch (Exception)
            {
                NUnit.Framework.Assert.Fail("JKS should load from _NEW file !!");
            }
            // Ignore
            VerifyAfterReload(file, provider);
            // _NEW exists but corrupt.. must load from _OLD
            newFile.CreateNewFile();
            file.RenameTo(oldFile);
            file.Delete();
            try
            {
                provider = KeyProviderFactory.GetProviders(conf)[0];
                NUnit.Framework.Assert.IsFalse(newFile.Exists());
                NUnit.Framework.Assert.IsFalse(oldFile.Exists());
            }
            catch (Exception)
            {
                NUnit.Framework.Assert.Fail("JKS should load from _OLD file !!");
            }
            finally
            {
                // Ignore
                if (newFile.Exists())
                {
                    newFile.Delete();
                }
            }
            VerifyAfterReload(file, provider);
            // check permission retention after explicit change
            fs.SetPermission(path, new FsPermission("777"));
            CheckPermissionRetention(conf, ourUrl, path);
            // Check that an uppercase keyname results in an error
            provider = KeyProviderFactory.GetProviders(conf)[0];
            try
            {
                provider.CreateKey("UPPERCASE", KeyProvider.Options(conf));
                NUnit.Framework.Assert.Fail("Expected failure on creating key name with uppercase "
                                            + "characters");
            }
            catch (ArgumentException e)
            {
                GenericTestUtils.AssertExceptionContains("Uppercase key names", e);
            }
        }
Пример #25
0
        public override NBrightInfo Calculate(NBrightInfo cartInfo)
        {
            var info    = ProviderUtils.GetProviderSettings("tax");
            var taxtype = info.GetXmlProperty("genxml/radiobuttonlist/taxtype");

            if (taxtype == "3") // no tax
            {
                cartInfo.SetXmlPropertyDouble("genxml/taxcost", 0);
                cartInfo.SetXmlPropertyDouble("genxml/appliedtax", 0);
                return(cartInfo);
            }


            var rateDic = GetRates();

            if (!rateDic.Any())
            {
                return(cartInfo);
            }

            // loop through each item and calc the tax for each.
            var nodList = cartInfo.XMLDoc.SelectNodes("genxml/items/*");

            if (nodList != null)
            {
                Double taxtotal = 0;

                foreach (XmlNode nod in nodList)
                {
                    var nbi = new NBrightInfo();
                    nbi.XMLData = nod.OuterXml;
                    taxtotal   += CalculateItemTax(nbi);
                }

                cartInfo.SetXmlPropertyDouble("genxml/taxcost", taxtotal);
                if (taxtype == "1")
                {
                    cartInfo.SetXmlPropertyDouble("genxml/appliedtax", 0);                 // tax already in total, so don't apply any more tax.
                }
                if (taxtype == "2")
                {
                    cartInfo.SetXmlPropertyDouble("genxml/appliedtax", taxtotal);
                }


                var taxcountry            = cartInfo.GetXmlProperty("genxml/billaddress/genxml/dropdownlist/country");
                var storecountry          = StoreSettings.Current.Get("storecountry");
                var valideutaxcountrycode = info.GetXmlProperty("genxml/textbox/valideutaxcountrycode");
                var isvalidEU             = false;
                valideutaxcountrycode = "," + valideutaxcountrycode.ToUpper().Replace(" ", "") + ",";
                if ((valideutaxcountrycode.Contains("," + taxcountry.ToUpper().Replace(" ", "") + ",")))
                {
                    isvalidEU = true;
                }

                // Check for EU tax number.
                var enabletaxnumber = info.GetXmlPropertyBool("genxml/checkbox/enabletaxnumber");
                if (enabletaxnumber)
                {
                    var taxnumber      = cartInfo.GetXmlProperty("genxml/extrainfo/genxml/textbox/taxnumber");
                    var storetaxnumber = StoreSettings.Current.Get("storetaxnumber");
                    if (storetaxnumber.Length >= 2)
                    {
                        storetaxnumber = storetaxnumber.Substring(0, 2).ToUpper();
                    }
                    if (taxnumber.Length >= 2)
                    {
                        taxnumber = taxnumber.Substring(0, 2).ToUpper();
                    }
                    if (taxnumber != storetaxnumber && taxnumber != "")
                    {
                        // not matching merchant country, so remove tax
                        if (taxtype == "1")
                        {
                            cartInfo.SetXmlPropertyDouble("genxml/taxcost", taxtotal * -1);
                            cartInfo.SetXmlPropertyDouble("genxml/appliedtax", taxtotal * -1);
                        }
                        if (taxtype == "2")
                        {
                            cartInfo.SetXmlPropertyDouble("genxml/taxcost", 0);
                            cartInfo.SetXmlPropertyDouble("genxml/appliedtax", 0);
                        }
                    }
                }

                // Check for country.
                var enabletaxcountry = info.GetXmlPropertyBool("genxml/checkbox/enabletaxcountry");
                if (enabletaxcountry)
                {
                    if (taxcountry != "")
                    {
                        if (taxcountry != storecountry && !isvalidEU)
                        {
                            // not matching merchant country, so remove tax
                            if (taxtype == "1")
                            {
                                cartInfo.SetXmlPropertyDouble("genxml/taxcost", taxtotal * -1);
                                cartInfo.SetXmlPropertyDouble("genxml/appliedtax", taxtotal * -1);
                            }
                            if (taxtype == "2")
                            {
                                cartInfo.SetXmlPropertyDouble("genxml/taxcost", 0);
                                cartInfo.SetXmlPropertyDouble("genxml/appliedtax", 0);
                            }
                        }
                    }
                }

                // check for region exempt (in same country)
                var taxexemptregions = info.GetXmlProperty("genxml/textbox/taxexemptregions");
                if (taxexemptregions != "" && taxcountry == storecountry)
                {
                    taxexemptregions = "," + taxexemptregions.ToUpper().Replace(" ", "") + ",";
                    var taxregioncode = cartInfo.GetXmlProperty("genxml/billaddress/genxml/dropdownlist/region");
                    if (taxregioncode == "")
                    {
                        taxregioncode = cartInfo.GetXmlProperty("genxml/billaddress/genxml/textbox/txtregion");
                    }
                    if (taxregioncode != "")
                    {
                        if (!taxexemptregions.Contains("," + taxregioncode.ToUpper().Replace(" ", "") + ","))
                        {
                            // not matching merchant region, so remove tax
                            if (taxtype == "1")
                            {
                                cartInfo.SetXmlPropertyDouble("genxml/taxcost", taxtotal * -1);
                                cartInfo.SetXmlPropertyDouble("genxml/appliedtax", taxtotal * -1);
                            }
                            if (taxtype == "2")
                            {
                                cartInfo.SetXmlPropertyDouble("genxml/taxcost", 0);
                                cartInfo.SetXmlPropertyDouble("genxml/appliedtax", 0);
                            }
                        }
                    }
                }
            }


            return(cartInfo);
        }
Пример #26
0
 /// <summary>
 /// Merges the specified source.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="target">The target.</param>
 /// <param name="lockedFields">The locked fields.</param>
 /// <param name="replaceData">if set to <c>true</c> [replace data].</param>
 protected override void MergeData(LiveTvProgram source, LiveTvProgram target, List <MetadataFields> lockedFields, bool replaceData, bool mergeMetadataSettings)
 {
     ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
 }
        /// <summary>
        /// <see cref="Provider{TSingle, TMultiple}.Put(TMultiple, string[], string[])">Put</see>
        /// </summary>
        public override IHttpActionResult Put(
            List <T> objs,
            [MatrixParameter] string[] zoneId    = null,
            [MatrixParameter] string[] contextId = null)
        {
            if (!AuthenticationService.VerifyAuthenticationHeader(Request.Headers, out string sessionToken))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.
            if (!AuthorisationService.IsAuthorised(Request.Headers, sessionToken, $"{TypeName}s", RightType.CREATE))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest($"Request failed for object {TypeName} as Zone and/or Context are invalid."));
            }

            ICollection <updateType> updateStatuses = new List <updateType>();

            try
            {
                foreach (T obj in objs)
                {
                    var status = new updateType
                    {
                        id = obj.RefId
                    };

                    try
                    {
                        Service.Update(obj, (zoneId?[0]), (contextId?[0]));
                        status.statusCode = ((int)HttpStatusCode.NoContent).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.BadRequest,
                            TypeName,
                            $"Object to update of type {TypeName} is invalid.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (NotFoundException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.NotFound,
                            TypeName,
                            $"Object {TypeName} with ID of {obj.RefId} not found.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.NotFound).ToString();
                    }
                    catch (UpdateException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.BadRequest,
                            TypeName,
                            $"Request failed for object {TypeName} with ID of {obj.RefId}.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.InternalServerError,
                            TypeName,
                            $"Request failed for object {TypeName} with ID of {obj.RefId}.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    updateStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            var updateResponse = new updateResponseType {
                updates = updateStatuses.ToArray()
            };

            return(Ok(updateResponse));
        }
Пример #28
0
        /// <summary>
        /// <see cref="IProvider{TTSingle,TMultiple,TPrimaryKey}.Delete(deleteRequestType, string[], string[])">Delete</see>
        /// </summary>
        public virtual IHttpActionResult Delete(
            deleteRequestType deleteRequest,
            [MatrixParameter] string[] zoneId    = null,
            [MatrixParameter] string[] contextId = null)
        {
            if (!AuthenticationService.VerifyAuthenticationHeader(Request.Headers, out string sessionToken))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.
            if (!AuthorisationService.IsAuthorised(Request.Headers, sessionToken, $"{TypeName}s", RightType.DELETE))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest($"Request failed for object {TypeName} as Zone and/or Context are invalid."));
            }

            ICollection <deleteStatus> deleteStatuses = new List <deleteStatus>();

            try
            {
                foreach (deleteIdType deleteId in deleteRequest.deletes)
                {
                    var status = new deleteStatus
                    {
                        id = deleteId.id
                    };

                    try
                    {
                        RequestParameter[] requestParameters = GetQueryParameters(Request);
                        Service.Delete(deleteId.id, zoneId?[0], contextId?[0], requestParameters);
                        status.statusCode = ((int)HttpStatusCode.NoContent).ToString();
                    }
                    catch (ArgumentException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.BadRequest,
                            TypeName,
                            $"Invalid argument: id={deleteId.id}.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (DeleteException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.BadRequest,
                            TypeName,
                            $"Request failed for object {TypeName} with ID of {deleteId.id}.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.BadRequest).ToString();
                    }
                    catch (NotFoundException e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.NotFound,
                            TypeName,
                            $"Object {TypeName} with ID of {deleteId.id} not found.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.NotFound).ToString();
                    }
                    catch (Exception e)
                    {
                        status.error = ProviderUtils.CreateError(
                            HttpStatusCode.InternalServerError,
                            TypeName,
                            $"Request failed for object {TypeName} with ID of {deleteId.id}.\n{e.Message}");
                        status.statusCode = ((int)HttpStatusCode.InternalServerError).ToString();
                    }

                    deleteStatuses.Add(status);
                }
            }
            catch (Exception)
            {
                // Need to ignore exceptions otherwise it would not be possible to return status records of processed objects.
            }

            var deleteResponse = new deleteResponseType {
                deletes = deleteStatuses.ToArray()
            };

            return(Ok(deleteResponse));
        }
Пример #29
0
        protected void BuildResult(NameValueCollection formVariables, string MD5secretKey, string callbackPW)
        {
            this.cartId  = formVariables["cartId"];
            this.desc    = formVariables["desc"];
            this.transId = formVariables["transId"];
            this.charenc = formVariables["charenc"];

            this.callbackPW = formVariables["callbackPW"];
            this.instId     = formVariables["instId"];
            this.testMode   = formVariables["testMode"];
            this.authMode   = formVariables["authMode"];

            this.amount       = formVariables["amount"];
            this.amountString = formVariables["amountString"];
            this.cost         = formVariables["cost"];
            this.currency     = formVariables["currency"];

            this.authAmount       = formVariables["authAmount"];
            this.authAmountString = formVariables["authAmountString"];
            this.authCost         = formVariables["authCost"];
            this.authCurrency     = formVariables["authCurrency"];

            this.transStatus    = formVariables["transStatus"];
            this.transTime      = formVariables["transTime"];
            this.rawAuthCode    = formVariables["rawAuthCode"];
            this.countryMatch   = formVariables["countryMatch"];
            this.rawAuthMessage = formVariables["rawAuthMessage"];
            this.msgType        = formVariables["msgType"];
            this.AVS            = formVariables["AVS"];
            this.cardType       = formVariables["cardType"];
            this.ipAddress      = formVariables["ipAddress"];

            this.name          = formVariables["name"];
            this.address1      = formVariables["address1"];
            this.address2      = formVariables["address2"];
            this.address3      = formVariables["address3"];
            this.region        = formVariables["region"];
            this.postcode      = formVariables["postcode"];
            this.country       = formVariables["country"];
            this.countryString = formVariables["countryString"];
            this.tel           = formVariables["tel"];
            this.fax           = formVariables["fax"];
            this.email         = formVariables["email"];

            this.delvName          = formVariables["delvName"];
            this.delvAddress1      = formVariables["delvAddress1"];
            this.delvAddress2      = formVariables["delvAddress2"];
            this.delvAddress3      = formVariables["delvAddress3"];
            this.delvTown          = formVariables["delvTown"];
            this.delvRegion        = formVariables["delvRegion"];
            this.delvPostcode      = formVariables["delvPostcode"];
            this.delvCountry       = formVariables["delvCountry"];
            this.delvCountryString = formVariables["delvCountryString"];

            this.MC_callbacksignature = formVariables["MC_callbacksignature"];

            var hashInputs = new StringBuilder();

            hashInputs.Append(MD5secretKey);
            hashInputs.Append(":");
            hashInputs.Append(this.currency);
            hashInputs.Append(":");
            hashInputs.Append(this.cartId);
            hashInputs.Append(":");
            hashInputs.Append(this.amount);

            byte[] hashDigest = new MD5CryptoServiceProvider().ComputeHash(ProviderUtils.StringToByteArray(hashInputs.ToString()));

            string newhash = ProviderUtils.ByteArrayToHexString(hashDigest);

            //Check if Callback Password matches
            if (newhash != this.MC_callbacksignature || this.callbackPW != callbackPW)
            {
                throw new Exception("Callback hash validation failed.");
            }
        }