コード例 #1
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     _OrderStatusId = AlwaysConvert.ToInt(Request.QueryString["OrderStatusId"]);
     _OrderStatus   = OrderStatusDataSource.Load(_OrderStatusId);
     AbleCommerce.Code.PageHelper.ConvertEnterToTab(Name);
     AbleCommerce.Code.PageHelper.ConvertEnterToTab(DisplayName);
     Caption.Text = string.Format(Caption.Text, _OrderStatus.Name);
     if (!Page.IsPostBack)
     {
         // LOAD TRIGGERS SELECT BOX
         foreach (int storeEventId in Enum.GetValues(typeof(StoreEvent)))
         {
             if ((storeEventId >= 100) && (storeEventId < 200))
             {
                 StoreEvent storeEvent = (StoreEvent)storeEventId;
                 Triggers.Items.Add(new ListItem(StringHelper.SpaceName(storeEvent.ToString()), storeEventId.ToString()));
             }
         }
         // INITIALIZE FORM
         Name.Text = _OrderStatus.Name;
         Name.Focus();
         DisplayName.Text              = _OrderStatus.DisplayName;
         Report.Checked                = _OrderStatus.IsActive;
         Cancelled.Checked             = !_OrderStatus.IsValid;
         InventoryAction.SelectedIndex = (int)_OrderStatus.InventoryActionId;
         foreach (OrderStatusTrigger trigger in _OrderStatus.Triggers)
         {
             ListItem item = Triggers.Items.FindByValue(trigger.StoreEventId.ToString());
             if (item != null)
             {
                 item.Selected = true;
             }
         }
     }
 }
コード例 #2
0
        public static PersistentCollection <EmailTemplateTrigger> LoadForStoreEvent(StoreEvent storeEvent)
        {
            PersistentCollection <EmailTemplateTrigger> EmailTemplateTriggerCollection = new PersistentCollection <EmailTemplateTrigger>();
            //CREATE THE DYNAMIC SQL TO LOAD OBJECT
            StringBuilder selectQuery = new StringBuilder();

            //GET RECORDS STARTING AT FIRST ROW
            selectQuery.Append("SELECT StoreEventId, EmailTemplateId");
            selectQuery.Append(" FROM ac_EmailTemplateTriggers");
            selectQuery.Append(" WHERE StoreEventId = @storeEventId");
            Database  database      = Token.Instance.Database;
            DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString());

            database.AddInParameter(selectCommand, "@storeEventId", System.Data.DbType.Int32, (int)storeEvent);
            //EXECUTE THE COMMAND
            using (IDataReader dr = database.ExecuteReader(selectCommand))
            {
                while (dr.Read())
                {
                    EmailTemplateTrigger storeEventTrigger = new EmailTemplateTrigger();
                    //SET FIELDS FROM ROW DATA
                    storeEventTrigger.StoreEventId    = dr.GetInt32(0);
                    storeEventTrigger.EmailTemplateId = dr.GetInt32(1);
                    storeEventTrigger.IsDirty         = false;
                    EmailTemplateTriggerCollection.Add(storeEventTrigger);
                }
                dr.Close();
            }
            return(EmailTemplateTriggerCollection);
        }
コード例 #3
0
        private void SaveEmailTemplate()
        {
            String oldName = _EmailTemplate.Name;

            _EmailTemplate.Name        = Name.Text;
            _EmailTemplate.ToAddress   = ToAddress.Text;
            _EmailTemplate.FromAddress = FromAddress.Text;
            _EmailTemplate.CCList      = CCAddress.Text;
            _EmailTemplate.BCCList     = BCCAddress.Text;
            _EmailTemplate.Subject     = Subject.Text;
            _EmailTemplate.Body        = Message.Text;
            _EmailTemplate.IsHTML      = (MailFormat.SelectedIndex == 0);
            _EmailTemplate.Save();

            // UPDATE TRIGGERS
            _EmailTemplate.Triggers.DeleteAll();
            foreach (GridViewRow row in TriggerGrid.Rows)
            {
                CheckBox selected = row.FindControl("Selected") as CheckBox;
                if (selected.Checked)
                {
                    StoreEvent storeEvent = AlwaysConvert.ToEnum <StoreEvent>(TriggerGrid.DataKeys[row.RowIndex].Value.ToString(), StoreEvent.None);
                    _EmailTemplate.Triggers.Add(new EmailTemplateTrigger(_EmailTemplate, storeEvent));
                }
            }
            _EmailTemplate.Save();


            // SEE IF NAME WAS UPDATED
            if (_EmailTemplate.Name != oldName)
            {
                // SEE IF FILE NAME NEEEDS TO BE CHANGED
                string generatedFileName = Regex.Replace(Name.Text, "[^a-zA-Z0-9 _-]", "") + " ID" + _EmailTemplate.Id + ".html";
                if (_EmailTemplate.ContentFileName != generatedFileName)
                {
                    // INITIATE FILE NAME CHANGE
                    string templatesPath = Path.Combine(FileHelper.ApplicationBasePath, "App_Data\\EmailTemplates\\" + AbleContext.Current.StoreId);
                    string sourceFile    = Path.Combine(templatesPath, _EmailTemplate.ContentFileName);
                    string targetFile    = Path.Combine(templatesPath, generatedFileName);
                    try
                    {
                        if (File.Exists(targetFile))
                        {
                            File.Delete(targetFile);
                        }
                        File.Move(sourceFile, targetFile);
                        _EmailTemplate.ContentFileName = generatedFileName;
                    }
                    catch (Exception ex)
                    {
                        string error = "Could not update the content file name for email template '{0}'.  Failed to rename file from {1} to {2}.";
                        Logger.Warn(string.Format(error, _EmailTemplate.Name, _EmailTemplate.ContentFileName, generatedFileName), ex);
                    }

                    // SAVE IN CASE THE RENAME WAS SUCCESSFUL
                    // (IF RENAME FAILED, ISDIRTY FLAG WILL BE FALSE AND SAVE CALL WILL BE IGNORED)
                    _EmailTemplate.Save();
                }
            }
        }
コード例 #4
0
ファイル: QueueContainer.cs プロジェクト: angshuman/hexadb
        public void Send(StoreEvent storeEvent)
        {
            // todo: Add a max size of the queue then fail
            var partitionId = Math.Abs(Hasher.GetFnvHash32(storeEvent.PartitionId) % _count);

            _queueWriters[partitionId].Send(storeEvent);
        }
コード例 #5
0
        public static string GetFriendlyStoreEventName(StoreEvent storeEvent)
        {
            switch (storeEvent)
            {
            case StoreEvent.OrderPlaced: return("Order was placed");

            case StoreEvent.OrderPaid: return("Order with shippable items was fully paid");

            case StoreEvent.OrderPaidNoShipments: return("Order without shippable items was fully paid");

            case StoreEvent.OrderPaidPartial: return("Order was partially paid (balance remains)");

            case StoreEvent.OrderPaidCreditBalance: return("Order was overpaid (credit remains)");

            case StoreEvent.OrderShipped: return("Order was fully shipped");

            case StoreEvent.OrderShippedPartial: return("Order was partially shipped");

            case StoreEvent.ShipmentShipped: return("Shipment was shipped");

            case StoreEvent.OrderNoteAddedByMerchant: return("Order note was added by merchant");

            case StoreEvent.OrderNoteAddedByCustomer: return("Order note was added by customer");

            case StoreEvent.OrderStatusUpdated: return("Order status was updated");

            case StoreEvent.OrderCancelled: return("Order was cancelled");

            case StoreEvent.GiftCertificateValidated: return("Pending gift certificate validated");

            case StoreEvent.PaymentAuthorized: return("Payment authorization succeeded");

            case StoreEvent.PaymentAuthorizationFailed: return("Payment authorization failed");

            case StoreEvent.PaymentCaptured: return("Payment was fully captured");

            case StoreEvent.PaymentCapturedPartial: return("Payment was partially captured");

            case StoreEvent.PaymentCaptureFailed: return("Payment capture failed");

            case StoreEvent.CustomerPasswordRequest: return("Customer requested password assistance");

            case StoreEvent.LowInventoryItemPurchased: return("Product with low inventory was purchased");

            case StoreEvent.SubscriptionActivated: return("Subscription is activated");

            case StoreEvent.SubscriptionDeactivated: return("Subscription is deactivated");

            case StoreEvent.SubscriptionCancelled: return("Subscription is cancelled");

            case StoreEvent.SubscriptionExpired: return("Subscription is expired");

            case StoreEvent.ProductReviewSubmitted: return("New product review submitted");

            case StoreEvent.ProductReviewApproved: return("Product review approved");

            default: return(string.Empty);
            }
        }
コード例 #6
0
 public void Send(StoreEvent storeEvent)
 {
     if (_queue.Count > _maxQueueSize)
     {
         throw _storeError.MaxQueueSize;
     }
     _queue.Add(storeEvent);
 }
コード例 #7
0
        /// <summary>
        /// Updates status of an order based on the store event
        /// </summary>
        /// <param name="storeEvent">StoreEvent to determine the new order status</param>
        /// <param name="order">Order to update status of</param>
        public static void UpdateOrderStatus(StoreEvent storeEvent, Order order)
        {
            OrderStatus newStatus = OrderStatusTriggerDataSource.LoadForStoreEvent(storeEvent);

            if (newStatus != null)
            {
                OrderDataSource.UpdateOrderStatus(order, newStatus);
            }
        }
コード例 #8
0
        public void Save <T>(T theEvent) where T : Event
        {
            var serializedData = JsonConvert.SerializeObject(theEvent);
            var storedEvent    = new StoreEvent(
                theEvent,
                serializedData,
                "zhangyang");

            _eventStoreRepository.Store(storedEvent);
        }
コード例 #9
0
        private void SaveOrderStatuses()
        {
            _OrderStatus.Name        = Name.Text;
            _OrderStatus.DisplayName = DisplayName.Text;
            //ACTIVE FLAG IS USED TO DETERMINE VALID SALES FOR REPORTING
            _OrderStatus.IsActive = Report.Checked;
            //VALID FLAG IS USED TO DERMINE WHICH ORDERS ARE BAD
            _OrderStatus.IsValid         = (!Cancelled.Checked);
            _OrderStatus.InventoryAction = (CommerceBuilder.Orders.InventoryAction)InventoryAction.SelectedIndex;
            _OrderStatus.Triggers.DeleteAll();
            foreach (ListItem item in Triggers.Items)
            {
                if (item.Selected)
                {
                    StoreEvent  thisEvent      = AlwaysConvert.ToEnum <StoreEvent>(item.Value, StoreEvent.None);
                    OrderStatus oldOrderStatus = OrderStatusTriggerDataSource.LoadForStoreEvent(thisEvent);
                    if (oldOrderStatus != null)
                    {
                        List <OrderStatusTrigger> triggers = (from t in oldOrderStatus.Triggers
                                                              where t.StoreEvent == thisEvent
                                                              select t).ToList <OrderStatusTrigger>();
                        triggers.DeleteAll <OrderStatusTrigger>();
                    }

                    // DROP EXISTING TRIGGERS FOR THIS EVENT
                    (from t in _OrderStatus.Triggers where t.StoreEvent == thisEvent select t).ToList <OrderStatusTrigger>().DeleteAll <OrderStatusTrigger>();
                    _OrderStatus.Triggers.Add(new OrderStatusTrigger(thisEvent, _OrderStatus));
                }
            }
            _OrderStatus.EmailTemplates.Clear();
            _OrderStatus.Save();

            foreach (ListItem item in EmailTemplates.Items)
            {
                var tempalte = EntityLoader.Load <EmailTemplate>(AlwaysConvert.ToInt(item.Value));
                int index    = tempalte.OrderStatuses.IndexOf(_OrderStatus.Id);
                if (item.Selected)
                {
                    if (index < 0)
                    {
                        tempalte.OrderStatuses.Add(_OrderStatus);
                    }
                }
                else
                {
                    if (index >= 0)
                    {
                        tempalte.OrderStatuses.RemoveAt(index);
                    }
                }

                tempalte.Save();
            }
        }
コード例 #10
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            EmailTemplate template = new EmailTemplate();

            template.Name        = Name.Text;
            template.ToAddress   = ToAddress.Text;
            template.FromAddress = FromAddress.Text;
            template.CCList      = CCAddress.Text;
            template.BCCList     = BCCAddress.Text;
            template.Subject     = Subject.Text;
            string temporaryFileName = Guid.NewGuid().ToString();

            template.ContentFileName = temporaryFileName;
            template.IsHTML          = (MailFormat.SelectedIndex == 0);
            foreach (GridViewRow row in TriggerGrid.Rows)
            {
                CheckBox selected = row.FindControl("Selected") as CheckBox;
                if (selected.Checked)
                {
                    StoreEvent storeEvent = AlwaysConvert.ToEnum <StoreEvent>(TriggerGrid.DataKeys[row.RowIndex].Value.ToString(), StoreEvent.None);
                    template.Triggers.Add(new EmailTemplateTrigger(template, storeEvent));
                }
            }
            template.Save();

            // RENAME THE FILE AND SAVE
            template.Body            = Message.Text;
            template.ContentFileName = Regex.Replace(Name.Text, "[^a-zA-Z0-9 _-]", "") + " ID" + template.Id + ".html";
            template.Save();

            // DELETE TEMPORARY CONTENT FILE
            string templatesPath = "App_Data\\EmailTemplates\\" + AbleContext.Current.StoreId;

            templatesPath = Path.Combine(FileHelper.ApplicationBasePath, templatesPath);
            string tempFilePath = Path.Combine(templatesPath, temporaryFileName);

            try
            {
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }
            }
            catch (Exception ex)
            {
                Logger.Warn("Error deleting temporary email template content file '" + tempFilePath + "'.", ex);
            }

            Response.Redirect("Default.aspx");
        }
コード例 #11
0
        public async Task <IActionResult> Ingest(string storeId, [FromBody] UpdateRequest req)
        {
            _logger.LogInformation(LoggingEvents.ControllerIngest, "INGEST: store: {store} partition: {partitionId}", storeId, req.PartitionKey);
            string url = req.Data?["url"]?.ToString();

            if (string.IsNullOrEmpty(url))
            {
                return(BadRequest());
            }
            try {
                var(_, expand, level, _) = GetParams();
                using (var client = new HttpClient()) {
                    var response = await client.GetStringAsync(url);

                    var data = JArray.Parse(response);

                    var batch = new JArray();
                    foreach (var item in data)
                    {
                        batch.Add(item);

                        if (batch.Count == 1000)
                        {
                            var e = new StoreEvent {
                                Operation   = EventType.POST,
                                Strict      = true,
                                Data        = batch,
                                PartitionId = req.PartitionKey
                            };
                            await SendEvent(storeId, e);

                            _logger.LogInformation("Batch ingestion", batch.Count);
                            batch = new JArray();
                        }
                    }

                    if (batch.Count > 0)
                    {
                        var e = new StoreEvent {
                            Operation   = EventType.POST,
                            Strict      = true,
                            Data        = batch,
                            PartitionId = req.PartitionKey
                        };
                        await SendEvent(storeId, e);

                        _logger.LogInformation("Batch ingestion", batch.Count);
                    }
                    return(Accepted());
                }
            } catch (Exception e) {
                return(HandleException(e));
            }
        }
コード例 #12
0
        protected Task SendEvent(string storeId, StoreEvent payload)
        {
            var guid = Guid.NewGuid().ToString();

            payload.OperationId = guid;
            payload.StoreId     = storeId;

            var tc = new TaskCompletionSource <bool>();

            _receiver.SetCompletion(guid, tc);
            _ = _eventProcessor.SendMessage(payload);
            return(tc.Task);
        }
コード例 #13
0
        public async Task <IActionResult> Delete(string storeId, [FromBody] JObject data)
        {
            _logger.LogInformation(LoggingEvents.ControllerDelete, "DELETE: store {store}", storeId);
            try {
                var e = new StoreEvent
                {
                    Operation = EventType.DELETE,
                    Data      = data.ToString(Formatting.None)
                };
                await SendEvent(storeId, e);

                return(Accepted());
            } catch (Exception e) {
                return(HandleException(e));
            }
        }
コード例 #14
0
        public async Task <IActionResult> PatchJson(string storeId, [FromBody] JToken data)
        {
            _logger.LogInformation(LoggingEvents.ControllerPatchJson, "PATCH JSON: store {storeId}", storeId);
            try {
                var e = new StoreEvent
                {
                    Operation = EventType.PATCH_JSON,
                    Data      = data.ToString(Formatting.None)
                };
                await SendEvent(storeId, e);

                return(Accepted());
            } catch (Exception e) {
                return(HandleException(e));
            }
        }
コード例 #15
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     AbleCommerce.Code.PageHelper.ConvertEnterToTab(Name);
     AbleCommerce.Code.PageHelper.ConvertEnterToTab(DisplayName);
     if (!Page.IsPostBack)
     {
         // LOAD TRIGGERS SELECT BOX
         foreach (int storeEventId in Enum.GetValues(typeof(StoreEvent)))
         {
             if ((storeEventId >= 100) && (storeEventId < 200))
             {
                 StoreEvent storeEvent = (StoreEvent)storeEventId;
                 Triggers.Items.Add(new ListItem(StringHelper.SpaceName(storeEvent.ToString()), storeEventId.ToString()));
             }
         }
     }
 }
コード例 #16
0
 public async Task <IActionResult> Delete(string storeId, [FromBody] UpdateRequest[] batch)
 {
     _logger.LogInformation(LoggingEvents.ControllerDelete, "DELETE: store: {store} parition: {partitionId}", storeId, batch.Length);
     try {
         foreach (var req in batch)
         {
             var e = new StoreEvent {
                 Operation   = EventType.DELETE,
                 Data        = req.Data,
                 PartitionId = req.PartitionKey
             };
             await SendEvent(storeId, e);
         }
         return(Accepted());
     } catch (Exception e) {
         return(HandleException(e));
     }
 }
コード例 #17
0
        public async Task <IActionResult> Post(string storeId, [FromBody] JToken data)
        {
            _logger.LogInformation(LoggingEvents.ControllerPost, "POST: store {store}", storeId);
            try {
                var(_, _, _, strict) = GetParams();
                var e = new StoreEvent
                {
                    Operation = EventType.POST,
                    Strict    = strict,
                    Data      = data.ToString(Formatting.None)
                };
                await SendEvent(storeId, e);

                return(Accepted());
            } catch (Exception e) {
                return(HandleException(e));
            }
        }
コード例 #18
0
 public async Task <IActionResult> PatchTriple(string storeId, [FromBody] UpdateRequest[] batch)
 {
     _logger.LogInformation(LoggingEvents.ControllerPatchTriple, "PATCH TRIPLE: store: {store} batch size: {size}", storeId, batch.Length);
     try {
         foreach (var req in batch)
         {
             var e = new StoreEvent {
                 Operation   = EventType.PATCH_TRIPLE,
                 Data        = req.Data,
                 PartitionId = req.PartitionKey
             };
             await SendEvent(storeId, e);
         }
         return(Accepted());
     } catch (Exception e) {
         return(HandleException(e));
     }
 }
コード例 #19
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            OrderStatus _OrderStatus = new OrderStatus();

            _OrderStatus.Name        = Name.Text;
            _OrderStatus.DisplayName = DisplayName.Text;
            //ACTIVE FLAG IS USED TO DETERMINE VALID SALES FOR REPORTING
            _OrderStatus.IsActive = Report.Checked;
            //VALID FLAG IS USED TO DERMINE WHICH ORDERS ARE BAD
            _OrderStatus.IsValid         = (!Cancelled.Checked);
            _OrderStatus.InventoryAction = (CommerceBuilder.Orders.InventoryAction)InventoryAction.SelectedIndex;
            foreach (ListItem item in Triggers.Items)
            {
                if (item.Selected)
                {
                    StoreEvent  thisEvent      = AlwaysConvert.ToEnum <StoreEvent>(item.Value, StoreEvent.None);
                    OrderStatus oldOrderStatus = OrderStatusTriggerDataSource.LoadForStoreEvent(thisEvent);
                    if (oldOrderStatus != null)
                    {
                        List <OrderStatusTrigger> triggers = (from t in oldOrderStatus.Triggers
                                                              where t.StoreEvent == thisEvent
                                                              select t).ToList <OrderStatusTrigger>();
                        triggers.DeleteAll <OrderStatusTrigger>();
                    }

                    // DROP EXISTING TRIGGERS FOR THIS EVENT
                    (from t in _OrderStatus.Triggers where t.StoreEvent == thisEvent select t).ToList <OrderStatusTrigger>().DeleteAll <OrderStatusTrigger>();
                    _OrderStatus.Triggers.Add(new OrderStatusTrigger(thisEvent, _OrderStatus));
                }
            }
            _OrderStatus.Save();

            foreach (ListItem item in EmailTemplates.Items)
            {
                var tempalte = EntityLoader.Load <EmailTemplate>(AlwaysConvert.ToInt(item.Value));
                if (item.Selected)
                {
                    tempalte.OrderStatuses.Add(_OrderStatus);
                }

                tempalte.Save();
            }
            Response.Redirect("Default.aspx");
        }
コード例 #20
0
ファイル: GoodsDAL.cs プロジェクト: zhengqiao520/PosSystem
        public static int AddStoreEvent(StoreEvent entity)
        {
            var trans = utity.BeginTransaction();
            var res   = utity.ExecuteScalarSp(trans, "usp_MoneyOffAdd", new object[] {
                entity.Name,
                entity.EventTag,
                entity.RangeFlag,
                entity.StoreIds,
                entity.StoreName,
                entity.StartTime,
                entity.EndTime,
                entity.EventType,
                entity.Remark,
                entity.RecordStatus
            });

            trans.Commit();
            return(int.Parse(res.ToString()));
        }
コード例 #21
0
        /// <summary>
        /// Processes emails for the given store event using the given parameters
        /// </summary>
        /// <param name="storeEvent">StoreEvent object for which to process the emails</param>
        /// <param name="parameters">The parameters to be used in nVelocity email templates</param>
        public static void ProcessEmails(StoreEvent storeEvent, Hashtable parameters)
        {
            parameters["store"] = Token.Instance.Store;
            //NEED TO GET THE EMAIL TEMPLATE FOR THE ORDER
            PersistentCollection <EmailTemplateTrigger> emailTriggers = EmailTemplateTriggerDataSource.LoadForStoreEvent(storeEvent);

            foreach (EmailTemplateTrigger trigger in emailTriggers)
            {
                EmailTemplate template = trigger.EmailTemplate;
                if (template != null)
                {
                    foreach (string key in parameters.Keys)
                    {
                        template.Parameters[key] = parameters[key];
                    }
                    template.Send();
                }
            }
        }
コード例 #22
0
 public async Task <IActionResult> Post(string storeId, [FromBody] UpdateRequest[] batch)
 {
     _logger.LogInformation(LoggingEvents.ControllerPost, "POST: store: {store} batch size: {size}", storeId, batch.Length);
     try {
         var(_, _, _, strict) = GetParams();
         foreach (var req in batch)
         {
             var e = new StoreEvent {
                 Operation   = EventType.POST,
                 Strict      = strict,
                 Data        = req.Data,
                 PartitionId = req.PartitionKey
             };
             await SendEvent(storeId, e);
         }
         return(Accepted());
     } catch (Exception e) {
         return(HandleException(e));
     }
 }
コード例 #23
0
        public ActionResult SubmitWholeDiscountEvent(Pagination pagination, StoreEvent entity, string keyValue = "")
        {
            var result = false;

            if (string.IsNullOrEmpty(keyValue))
            {
                entity.EventType = 1;
                int res = GoodsBLL.instance.AddStoreEvent(entity);
                if (!string.IsNullOrEmpty(entity.EventConfigString))
                {
                    StoreEventConfig cfg = new StoreEventConfig
                    {
                        ConditionName  = "",
                        ConditionValue = entity.EventConfigString,
                        Description    = "整单折扣",
                        StoreEventID   = res.ToString()
                    };
                    result = SysBLL.Instance.Insert(cfg);
                }
            }
            else
            {
                StoreEvent evt = SysBLL.Instance.GetALL <StoreEvent>(where : $"ID='{keyValue}'").FirstOrDefault();
                evt.StartTime = entity.StartTime;
                evt.EndTime   = entity.EndTime;
                evt.Name      = entity.Name;
                evt.Remark    = entity.Remark;
                evt.StoreIds  = entity.StoreIds;
                var res = SysBLL.Instance.UpdateByKey(evt);
                if (res)
                {
                    StoreEventConfig evtConfig = SysBLL.Instance.GetALL <StoreEventConfig>(where : $"StoreEventID='{keyValue}'").FirstOrDefault();
                    evtConfig.ConditionValue = entity.EventConfigString;
                    result = SysBLL.Instance.UpdateByKey(evtConfig);
                }
                return(result ? Success("更新成功!") : Error("更新失败!"));
            }
            return(result ? Success("操作成功!") : Error("操作失败!"));
        }
コード例 #24
0
 protected async Task SendEvent(string storeId, StoreEvent payload)
 {
     // todo: resolve the promise when all messages are roundtripped from EH
     payload.StoreId = storeId;
     await _eventProcessor.SendMessage(payload);
 }
コード例 #25
0
ファイル: FlatModelTest.cs プロジェクト: angshuman/hexadb
        public static void RunTest(int appCount, int deviceCount, int devicePropertyCount, int sendCount, int senderThreadCount, bool tryOptimizeRocks)
        {
            Console.WriteLine("Creating Messages");
            var apps                = new List <string>(appCount);
            var deviceIds           = new List <string>(deviceCount);
            var devicePropertyNames = new List <string>(devicePropertyCount);
            var tasks               = new List <Task>();
            var sendQueue           = new ConcurrentQueue <StoreEvent>();

            while (apps.Count < appCount)
            {
                apps.Add(Guid.NewGuid().ToString());
            }

            while (deviceIds.Count < deviceCount)
            {
                deviceIds.Add(Guid.NewGuid().ToString());
            }

            while (devicePropertyNames.Count < devicePropertyCount)
            {
                devicePropertyNames.Add(Guid.NewGuid().ToString());
            }

            using (var testFolder = new TestFolder())
            {
                var factory     = LoggerFactory.Create(builder => builder.AddConsole());
                var logger      = factory.CreateLogger <RocksGraphProvider>();
                var storeLogger = factory.CreateLogger <StoreProcessor>();

                var dbOptions = new DbOptions();
                var provider  = !tryOptimizeRocks ?
                                new RocksGraphProvider(logger, testFolder) :
                                new RocksGraphProvider(logger, testFolder, dbOptions.SetCreateIfMissing(true)
                                                       .SetAllowConcurrentMemtableWrite(true)
                                                       //.SetAllowMmapReads(true)
                                                       //.SetAllowMmapWrites(true)
                                                       //.SetUseFsync(0)
                                                       .IncreaseParallelism(Environment.ProcessorCount)
                                                       .SetMaxBackgroundCompactions(Environment.ProcessorCount)
                                                       .SetMaxBackgroundFlushes(Environment.ProcessorCount));

                var storeProvider  = new SetProvider(provider);
                var storeProcessor = new StoreProcessor(storeProvider, new Reasoner(), storeLogger);
                var storeConfig    = new StoreConfig();
                var storeError     = new StoreError();
                var eventReceiver  = new EventReceiver(storeProcessor, null, storeConfig, factory.CreateLogger <EventReceiver>());
                var queueContainer = new QueueContainer(eventReceiver, factory.CreateLogger <QueueContainer>(), storeError, 1_000_000);
                var eventSender    = new EventSender(queueContainer, null, null, storeConfig);

                for (var i = 0; i < sendCount; i++)
                {
                    foreach (var id in deviceIds)
                    {
                        foreach (var app in apps)
                        {
                            var points = GetPropertyValues(devicePropertyNames, _random);
                            var e      = new StoreEvent
                            {
                                Operation   = EventType.PATCH_JSON,
                                Data        = JsonGenerator.GenerateTelemetry(id, points),
                                PartitionId = id,
                                StoreId     = app
                            };
                            sendQueue.Enqueue(e);
                        }
                    }
                }

                Console.WriteLine($"Starting send of {sendQueue.Count} messages");

                var timer = Stopwatch.StartNew();

                for (var i = 0; i < senderThreadCount; i++)
                {
                    tasks.Add(Task.Run(() => RunSender(eventSender, sendQueue)));
                }

                Task.WhenAll(tasks).Wait();

                Console.WriteLine($"Completed writing to queues in {timer.Elapsed}");

                while (queueContainer.Count() > 0)
                {
                    Thread.Sleep(1000);
                }
                Console.WriteLine($"Completed writing to storage in {timer.Elapsed}");
            }
        }
コード例 #26
0
 public int AddStoreEvent(StoreEvent entity)
 {
     return(GoodsDAL.AddStoreEvent(entity));
 }
コード例 #27
0
 public void Store(StoreEvent theEvent)
 {
     _context.StoredEvent.Add(theEvent);
     _context.SaveChanges();
 }
コード例 #28
0
        public ActionResult SubmitFreeGoodsEvent(Pagination pagination, StoreEvent entity, string keyValue = "")
        {
            var result = false;
            var func   = new Func <string, string>(s =>
            {
                var tag = '|';
                if (s.IndexOf(tag) == -1)
                {
                    return(s);
                }
                var str   = s.Replace(" ", "");
                var list  = str.Split(tag).ToList();
                var qData = list.GroupBy(q => q).Select(q => new { item = q.Key, cnt = q.Count() });
                var dict  = new Dictionary <string, int>();
                foreach (var t in qData)
                {
                    if (t.item.Contains("*"))
                    {
                        var p0    = t.item.Split(new[] { "*" }, StringSplitOptions.RemoveEmptyEntries);
                        var p0Num = 0;
                        if (int.TryParse(p0[1], out p0Num))
                        {
                            var p0Str = p0[0].Trim();
                            if (dict.ContainsKey(p0Str))
                            {
                                dict[p0Str] += p0Num * t.cnt;
                            }
                            else
                            {
                                dict.Add(p0Str, p0Num * t.cnt);
                            }
                        }
                    }
                    else
                    {
                        dict.Add(t.item, t.cnt);
                    }
                }
                if (dict.Any())
                {
                    return(string.Join(tag.ToString(), dict.Select(k => k.Key + (k.Value > 1 ? ("*" + k.Value) : "")).ToList()));
                }
                return(s);
            });
            var dt              = DateTime.Now;
            var msg0            = "当前购买的商品已存在买赠设置,请修改或删除原买赠设置";
            var msg1            = "当前赠品已绑定到一条已存在的买赠设置";
            var storeEventQuery = SysBLL.Instance.GetALL <StoreEvent>().Where(s => (s.StoreIds.Contains(entity.StoreIds) || entity.StoreIds.Contains(s.StoreIds)) &&
                                                                              s.EventType == 2 && s.StartTime <= dt && s.EndTime >= dt);
            var storeEventTags = new List <int>();

            if (string.IsNullOrEmpty(keyValue))
            {
                entity.EventType = 2;
                if (!string.IsNullOrEmpty(entity.StoreEventConfig.ConditionName) && !string.IsNullOrEmpty(entity.StoreEventConfig.ConditionValue))
                {
                    StoreEventConfig cfg = new StoreEventConfig
                    {
                        ConditionName  = func(entity.StoreEventConfig.ConditionName.Trim().Replace("\n", "").Replace("\r", "")),
                        ConditionValue = entity.StoreEventConfig.ConditionValue.Trim().Replace("\n", "").Replace("\r", ""),
                        Description    = "买赠设置"
                    };
                    if (storeEventQuery.Any())
                    {
                        storeEventTags = storeEventQuery.Select(p => p.ID).ToList();
                        var storeEventConfig = SysBLL.Instance.GetALL <StoreEventConfig>().Where(q => storeEventTags.Any(k => k.ToString() == q.StoreEventID));
                        if (storeEventConfig.Any(p => p.ConditionName.Contains(cfg.ConditionName) || cfg.ConditionName.Contains(p.ConditionName)))
                        {
                            return(Error(msg0));
                        }
                        if (storeEventConfig.Any(p => p.ConditionValue.Contains(cfg.ConditionValue) || cfg.ConditionValue.Contains(p.ConditionValue)))
                        {
                            return(Error(msg1));
                        }
                    }
                    int res = GoodsBLL.instance.AddStoreEvent(entity);
                    cfg.StoreEventID = res.ToString();
                    result           = SysBLL.Instance.Insert(cfg);
                }
            }
            else
            {
                StoreEvent evt = SysBLL.Instance.GetALL <StoreEvent>(where : $"ID='{keyValue}'").FirstOrDefault();
                evt.StartTime = entity.StartTime.Date;
                evt.EndTime   = entity.EndTime.Date;
                evt.Name      = entity.Name;
                evt.Remark    = entity.Remark;
                evt.StoreIds  = entity.StoreIds;

                StoreEventConfig evtConfig = SysBLL.Instance.GetALL <StoreEventConfig>(where : $"StoreEventID='{keyValue}'").FirstOrDefault();
                evtConfig.ConditionValue = entity.StoreEventConfig.ConditionValue.Trim().Replace("\n", "").Replace("\r", "");
                evtConfig.ConditionName  = func(entity.StoreEventConfig.ConditionName.Trim().Replace("\n", "").Replace("\r", ""));

                var t_storeEventQuery = storeEventQuery.Where(y => y.ID != evt.ID);
                if (t_storeEventQuery.Any())
                {
                    storeEventTags = t_storeEventQuery.Select(p => p.ID).ToList();
                    var t_storeEventConfig = SysBLL.Instance.GetALL <StoreEventConfig>().Where(q => storeEventTags.Any(k => k.ToString() == q.StoreEventID));
                    if (t_storeEventConfig.Any(p => p.ConditionName.Contains(evtConfig.ConditionName) || evtConfig.ConditionName.Contains(p.ConditionName)))
                    {
                        return(Error(msg0));
                    }
                    if (t_storeEventConfig.Any(p => p.ConditionValue.Contains(evtConfig.ConditionValue) || evtConfig.ConditionValue.Contains(p.ConditionValue)))
                    {
                        return(Error(msg1));
                    }
                }

                var res = SysBLL.Instance.UpdateByKey(evt);
                if (res)
                {
                    result = SysBLL.Instance.UpdateByKey(evtConfig);
                }
                return(result ? Success("更新成功!") : Error("更新失败!"));
            }
            return(result ? Success("操作成功!") : Error("操作失败!"));
        }
コード例 #29
0
 public ActionResult SubmitStoreEvent(StoreEvent entity, string keyValue = "")
 {
     if (entity.EventConfigString.Equals("[[]]"))
     {
         return(Error("满减条件不可为空!"));
     }
     if (string.IsNullOrEmpty(keyValue))
     {
         entity.EventType = 0;
         int res = GoodsBLL.instance.AddStoreEvent(entity);
         if (!string.IsNullOrEmpty(entity.EventConfigString))
         {
             var json = Newtonsoft.Json.JsonConvert.DeserializeObject(entity.EventConfigString);
             Newtonsoft.Json.Linq.JArray arr = json as Newtonsoft.Json.Linq.JArray;
             if (res > 0 && arr.Count > 0)
             {
                 arr.ToList().ForEach(item =>
                 {
                     StoreEventConfig cfg = new StoreEventConfig
                     {
                         ConditionName  = item["ConditionName"].ToString(),
                         ConditionValue = item["ConditionValue"].ToString(),
                         StoreEventID   = res.ToString()
                     };
                     cfg.Description = $"满{cfg.ConditionName},减{cfg.ConditionValue}";
                     SysBLL.Instance.Insert(cfg);
                 });
             }
         }
     }
     else
     {
         StoreEvent evt = SysBLL.Instance.GetALL <StoreEvent>(where : $"ID='{keyValue}'").FirstOrDefault();
         evt.StartTime = entity.StartTime;
         evt.EndTime   = entity.EndTime;
         evt.Name      = entity.Name;
         evt.Remark    = entity.Remark;
         evt.StoreIds  = entity.StoreIds;
         var res = SysBLL.Instance.UpdateByKey(evt);
         if (res)
         {
             if (!string.IsNullOrEmpty(entity.EventConfigString))
             {
                 var effectRow = 0;
                 var json      = Newtonsoft.Json.JsonConvert.DeserializeObject(entity.EventConfigString);
                 Newtonsoft.Json.Linq.JArray arr = json as Newtonsoft.Json.Linq.JArray;
                 if (arr.Count > 0)
                 {
                     SysBLL.Instance.DeleteByWhere <StoreEventConfig>($"StoreEventID='{keyValue}'");
                     arr.ToList().ForEach(item =>
                     {
                         StoreEventConfig cfg = new StoreEventConfig
                         {
                             ConditionName  = item["ConditionName"].ToString(),
                             ConditionValue = item["ConditionValue"].ToString(),
                             StoreEventID   = evt.ID.ToString()
                         };
                         cfg.Description = $"满{cfg.ConditionName},减{cfg.ConditionValue}";
                         bool result     = SysBLL.Instance.Insert(cfg);
                         effectRow      += (result ? 1 : 0);
                     });
                 }
                 return(effectRow > 0 ? Success("更新成功!") : Error("更新失败!"));
             }
         }
     }
     return(Success("操作成功!"));
 }