Пример #1
0
        private void RecordAuditEventLog(string query)
        {
            var props = new LogProperties {new LogDetailInfo("User", UserInfo.Username), new LogDetailInfo("SQL Query", query)};

            var elc = new EventLogController();
            elc.AddLog(props, PortalSettings, UserId, EventLogController.EventLogType.HOST_SQL_EXECUTED.ToString(), true);
        }
        public JObject Get()
        {
            JObject Config = new JObject();

            try
            {
                String SocketUrl = _configuration.GetValue <string>("RequestUrls:WebSocketSubscribe");

                Config.Add(new JProperty("Success", true));
                Config.Add(new JProperty("Message", "Success"));
                Config.Add(new JProperty("SocketSubscribeUrl", SocketUrl));
            }
            catch (Exception ex)
            {
                LogProperties.error("Exception at configuration keys: " + ex.ToString());

                Config.Add(new JProperty("Success", false));
                Config.Add(new JProperty("Message", ex.ToString()));
            }



            return(Config);


            //return new string[] { "value1", "value2" };
        }
Пример #3
0
        public void Dispose()
        {
            EventsHelper.CanRaiseEvent = false;

            CompositionTarget.Rendering -= CompositionTargetRendering;

            Dispatcher.BeginInvoke(
                new Action(
                    delegate
            {
                FreeEvents();
                if (IsPlaying)
                {
                    Stop();
                }
                AudioProperties.Dispose();
                VideoProperties.Dispose();
                LogProperties.Dispose();
                AudioOutputDevices.Dispose();
                VlcContext.InteropManager.MediaPlayerInterops.ReleaseInstance.Invoke(VlcContext.HandleManager.MediaPlayerHandles[this]);
                VlcContext.HandleManager.MediaPlayerHandles.Remove(this);

                myVideoLockCallbackHandle.Free();
                myVideoSetFormatHandle.Free();
                myVideoCleanupHandle.Free();
            }));
        }
        private string ExecuteScriptInternal(string connectionString, string script, int timeoutSec = 0)
        {
            string exceptions = "";

            var sqlDelimiterRegex = RegexUtils.GetCachedRegex(ScriptDelimiter, RegexOptions.IgnoreCase | RegexOptions.Multiline);

            string[] sqlStatements = sqlDelimiterRegex.Split(script);
            foreach (string statement in sqlStatements)
            {
                var sql = statement.Trim();
                if (!String.IsNullOrEmpty(sql))
                {
                    // script dynamic substitution
                    sql = DataUtil.ReplaceTokens(sql);

                    //Clean up some SQL Azure incompatabilities
                    var query = GetAzureCompactScript(sql);

                    if (query != sql)
                    {
                        var props = new LogProperties {
                            new LogDetailInfo("SQL Script Modified", query)
                        };

                        EventLogController.Instance.AddLog(props,
                                                           PortalController.Instance.GetCurrentPortalSettings(),
                                                           UserController.Instance.GetCurrentUserInfo().UserID,
                                                           EventLogController.EventLogType.HOST_ALERT.ToString(),
                                                           true);
                    }

                    try
                    {
                        Logger.Trace("Executing SQL Script " + query);

                        //Create a new connection
                        using (var connection = new SqlConnection(connectionString))
                        {
                            //Create a new command
                            using (var command = new SqlCommand(query, connection)
                            {
                                CommandTimeout = timeoutSec
                            })
                            {
                                connection.Open();
                                command.ExecuteNonQuery();
                                connection.Close();
                            }
                        }
                    }
                    catch (SqlException objException)
                    {
                        Logger.Error(objException);
                        exceptions += objException + Environment.NewLine + Environment.NewLine + query + Environment.NewLine + Environment.NewLine;
                    }
                }
            }

            return(exceptions);
        }
Пример #5
0
        public void Log(string dataBaseName)
        {
            var dataBase       = this.GetDataBase(dataBaseName);
            var authentication = this.CommandContext.GetAuthentication(this);
            var logs           = dataBase.Dispatcher.Invoke(() => dataBase.GetLog(authentication));

            LogProperties.Print(this.Out, logs);
        }
Пример #6
0
        public void LogCategory(string categoryPath)
        {
            var category       = this.GetCategory(categoryPath);
            var authentication = this.CommandContext.GetAuthentication(this);
            var logs           = category.Dispatcher.Invoke(() => category.GetLog(authentication));

            LogProperties.Print(this.Out, logs);
        }
Пример #7
0
        public void Log(string tableName)
        {
            var table          = this.GetTable(tableName);
            var authentication = this.CommandContext.GetAuthentication(this);
            var logs           = table.Dispatcher.Invoke(() => table.GetLog(authentication));

            LogProperties.Print(this.Out, logs);
        }
Пример #8
0
        private void LogSMTPError(string email, string message)
        {
            string        smtpError   = Localization.GetString("SMTPError", LocalResourceFile);
            string        smtpMessage = Localization.GetString("SMTPMessage", LocalResourceFile);
            LogProperties properties  = new LogProperties();

            properties.Add(new LogDetailInfo(smtpError, email));
            properties.Add(new LogDetailInfo(smtpMessage, message));
            AddEventLog(EventLogController.EventLogType.ADMIN_ALERT.ToString(), properties, true);
        }
Пример #9
0
        public override void Remove(int tabId)
        {
            try
            {
                Dictionary <int, int> portals = PortalController.GetPortalDictionary();
                if (portals.ContainsKey(tabId) && portals[tabId] > Null.NullInteger)
                {
                    var    filesNotDeleted = new StringBuilder();
                    int    i           = 0;
                    string cacheFolder = GetCacheFolder(portals[tabId]);

                    if (!string.IsNullOrEmpty(cacheFolder))
                    {
                        foreach (string file in Directory.GetFiles(cacheFolder, string.Concat(tabId, "_*.*")))
                        {
                            if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200))
                            {
                                filesNotDeleted.Append(string.Concat(file, ";"));
                            }
                            else
                            {
                                i += 1;
                            }
                        }

                        if (filesNotDeleted.Length > 0)
                        {
                            var log = new LogInfo {
                                LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()
                            };

                            var logDetail = new LogDetailInfo
                            {
                                PropertyName  = "FileOutputCacheProvider",
                                PropertyValue =
                                    string.Format(
                                        "Deleted {0} files, however, some files are locked.  Could not delete the following files: {1}",
                                        i, filesNotDeleted),
                            };
                            var properties = new LogProperties {
                                logDetail
                            };
                            log.LogProperties = properties;

                            LogController.Instance.AddLog(log);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.Exceptions.LogException(ex);
            }
        }
Пример #10
0
        protected virtual void AddEventLog(string logType, LogProperties properties, bool bypassBuffering)
        {
            LogInfo logInfo = new LogInfo();

            logInfo.LogPortalID     = PortalSettings.PortalId;
            logInfo.LogTypeKey      = logType;
            logInfo.LogProperties   = properties;
            logInfo.BypassBuffering = bypassBuffering;
            EventLogController logControler = new EventLogController();

            logControler.AddLog(logInfo);
        }
Пример #11
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         AudioProperties.Dispose();
         VideoProperties.Dispose();
         LogProperties.Dispose();
         AudioOutputDevices.Dispose();
         FreeEvents();
         VlcContext.InteropManager.MediaPlayerInterops.ReleaseInstance.Invoke(VlcContext.HandleManager.MediaPlayerHandles[this]);
         VlcContext.HandleManager.MediaPlayerHandles.Remove(this);
     }
 }
Пример #12
0
        private void LogIt(LogProperties properties)
        {
            string messageTemplateDefault   = "{RemoteIpAddress} - {AuthUser} [{Date}] \"{Method} {Path} {Protocol}\" {StatusCode} {ContentLength} {ElapsedMs} {Identifier}";
            string messageTemplateStrictW3c = "{RemoteIpAddress} - {AuthUser} [{Date}] \"{Method} {Path} {Protocol}\" {StatusCode} {ContentLength}";

            if (Options.StrictW3C)
            {
                Log.Information(messageTemplateStrictW3c, properties.RemoteIpAddress, properties.AuthUser, properties.Date, properties.Method, properties.Path, properties.Protocol, properties.StatusCode, properties.ContentLength);
            }
            else
            {
                Log.Information(messageTemplateDefault, properties.RemoteIpAddress, properties.AuthUser, properties.Date, properties.Method, properties.Path, properties.Protocol, properties.StatusCode, properties.ContentLength, properties.ElapsedMs, properties.Identifier);
            }
        }
Пример #13
0
        /// <inheritdoc />
        public virtual ILog <TCategoryName> Property(string propertyName, string propertyValue)
        {
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                return(this);
            }
            if (LogProperties.ContainsKey(propertyName))
            {
                LogProperties[propertyName] += propertyValue;
                return(this);
            }

            LogProperties.Add(propertyName, propertyValue);
            return(this);
        }
Пример #14
0
        /// <summary>
        /// 将状态对象转换到日志内容字典中
        /// </summary>
        protected virtual void ConvertStateToContent()
        {
            if (LogState == null)
            {
                return;
            }
            var state = Conv.ToDictionary(LogState);

            foreach (var item in state)
            {
                if (item.Value.SafeString().IsEmpty())
                {
                    continue;
                }
                LogProperties.Add(item);
            }
        }
        private void RecordAuditEventLog(string query)
        {
            var props = new LogProperties {
                new LogDetailInfo("User", UserInfo.Username), new LogDetailInfo("SQL Query", query)
            };

            //Add the event log with host portal id.
            var log = new LogInfo
            {
                LogUserID       = UserInfo.UserID,
                LogTypeKey      = EventLogController.EventLogType.HOST_SQL_EXECUTED.ToString(),
                LogProperties   = props,
                BypassBuffering = true,
                LogPortalID     = Null.NullInteger
            };

            LogController.Instance.AddLog(log);
        }
Пример #16
0
        public string GetPropertiesText(object obj)
        {
            LogInfo objLogInfo = (LogInfo)obj;

            LogProperties objLogProperties = objLogInfo.LogProperties;
            StringBuilder str = new StringBuilder();

            int i;

            for (i = 0; i <= objLogProperties.Count - 1; i++)
            {
                // display the values in the Panel child controls.
                LogDetailInfo ldi = (LogDetailInfo)objLogProperties[i];
                str.Append("<b>" + ldi.PropertyName + "</b>: " + Server.HtmlEncode(ldi.PropertyValue) + "<br>");
            }
            str.Append(Localization.GetString("ServerName", this.LocalResourceFile) + Server.HtmlEncode(objLogInfo.LogServerName) + "<br>");
            return(str.ToString());
        }
Пример #17
0
        /// <summary> Loads the extra configuration items that are necessary for configuring the log4net framework. </summary>
        /// <param name="factoryData"> The innerXml from the &lt;factory-data> element from the configuration section. </param>
        /// <exception cref="System.XmlException"> This means there was a problem with the configuration section. </exception>
        public void Init(string factoryData)
        {
            foreach (string key in LogProperties.Keys)
            {
                GlobalContext.Properties[key] = LogProperties.Get(key);
            }

            GlobalContext.Properties["MachineName"] = Environment.MachineName;
            GlobalContext.Properties["UserName"]    = Environment.UserName;
            GlobalContext.Properties["ProcessId"]   = Process.GetCurrentProcess().Id;

            if (!string.IsNullOrEmpty(factoryData))
            {
                XmlDocument config = new XmlDocument();
                try
                {
                    config.LoadXml(factoryData);
                    var configFileElement = config.SelectSingleNode("parameters/configFile");
                    if (configFileElement != null)
                    {
                        var configFileAttribute = configFileElement.Attributes["value"];
                        if (configFileAttribute != null)
                        {
                            string fileName = configFileAttribute.Value;
                            if (fileName.StartsWith(".\\"))
                            {
                                string appFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                                fileName = Path.Combine(appFolder, fileName.Replace(".\\", string.Empty));
                            }
                            FileInfo configFileName = new FileInfo(fileName);
                            XmlConfigurator.Configure(configFileName);
                            return;
                        }
                    }
                }
                catch (XmlException)
                {
                    XmlConfigurator.Configure();
                }
            }
            // load the log4net configuration from the application configuration.
            XmlConfigurator.Configure();
        }
Пример #18
0
        public async Task Invoke(HttpContext context)
        {
            if (Options.StrictW3C && Options.DisplayBefore)
            {
                throw new ArgumentException("Can not set both StrictW3C and DisplayBefore");
            }

            long start = Stopwatch.GetTimestamp();

            LogProperties logProperties = new LogProperties();

            // https://en.wikipedia.org/wiki/Common_Log_Format
            try {
                DateTime now = DateTime.Now;

                logProperties.RemoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "-";
                logProperties.AuthUser        = context.User.Identity.Name ?? "-";
                logProperties.Date            = $"{now.ToString("dd/MMM/yyyy:HH:MM:ss ")}{now.ToString("zzz").Replace(":", "")}";
                logProperties.Method          = context.Request.Method;
                logProperties.Path            = context.Request.Path;
                logProperties.Protocol        = context.Request.Protocol;
                logProperties.StatusCode      = "000";
                logProperties.ContentLength   = "0";
                logProperties.ElapsedMs       = "0";
                logProperties.Identifier      = $"begin:{context.TraceIdentifier}";

                if (Options.DisplayBefore)
                {
                    LogIt(logProperties);
                }

                await Next.Invoke(context);

                if (Options.DisplayAfter)
                {
                    now = DateTime.Now;

                    logProperties.Date          = $"{now.ToString("dd/MMM/yyyy:HH:MM:ss ")}{now.ToString("zzz").Replace(":", "")}";
                    logProperties.StatusCode    = context.Response.StatusCode.ToString();
                    logProperties.ContentLength = $"{context.Response?.ContentLength ?? -1}";
                    logProperties.ElapsedMs     = GetElapsedMilliseconds(start, Stopwatch.GetTimestamp()).ToString();
                    logProperties.Identifier    = $"end:{context.TraceIdentifier}";

                    LogIt(logProperties);
                }
            } catch (Exception ex) {
                if (Options.DisplayAfter)
                {
                    DateTime now = DateTime.Now;

                    logProperties.Date          = $"{now.ToString("dd/MMM/yyyy:HH:MM:ss ")}{now.ToString("zzz").Replace(":", "")}";
                    logProperties.StatusCode    = "500";
                    logProperties.ContentLength = $"{context.Response?.ContentLength ?? -1}";
                    logProperties.ElapsedMs     = GetElapsedMilliseconds(start, Stopwatch.GetTimestamp()).ToString();
                    logProperties.Identifier    = $"end:{context.TraceIdentifier}";

                    LogIt(logProperties);
                }

                if (Options.DisplayExceptions)
                {
                    Log.Error(ex, $"Exception during \"{logProperties.Method} {logProperties.Path} {logProperties.Protocol}\"");
                }

                if (Options.RethrowExceptions)
                {
                    throw;
                }
            }
        }
Пример #19
0
 public IEnumerable <string> Get()
 {
     LogProperties.info("Whats api get called");
     return(new string[] { "value1", "value2" });
 }
Пример #20
0
        private PaymentStatus VerifyPayment(SystempayIPNParameters ipn)
        {
            bool          restoreStock = false;
            PaymentStatus status       = PaymentStatus.Invalid;
            // Default Alert Reason
            string alertReason = Localization.GetString("InvalidIPN", LocalResourceFile, _portalLanguage);

            // Security cheking: Validate signature with the current certificate
            if (ipn.IsValid)
            {
                // Security checking: is this request come from right Systempay account ID
                if (IsFromSite(ipn.vads_site_id))
                {
                    // Security checking: compares some Systempay fields with order fields
                    alertReason = Localization.GetString("WrongOrderInfos", LocalResourceFile, _portalLanguage);
                    OrderController orderController = new OrderController();
                    OrderInfo       order           = orderController.GetOrder(PortalSettings.PortalId, ipn.vads_order_id);
                    // If this order exist
                    if (order != null)
                    {
                        // Currency MUST BE the same!
                        if (_settings.Currency == ipn.vads_currency)
                        {
                            // Everything looks good, validate the transaction!
                            switch (ipn.vads_trans_status.ToLower())
                            {
                            case "abandoned":
                                restoreStock = true;
                                status       = PaymentStatus.Abandoned;
                                break;

                            case "authorised":
                            case "authorised_to_validate":
                                // Grand Total MUST BE the same!
                                if (Math.Round(order.GrandTotal, 2, MidpointRounding.AwayFromZero) == ipn.vads_amount)
                                {
                                    status = PaymentStatus.Authorised;
                                }
                                break;

                            case "canceled":
                                restoreStock = true;
                                status       = PaymentStatus.Canceled;
                                break;

                            case "captured":
                                // Grand Total MUST BE the same!
                                if (Math.Round(order.GrandTotal, 2, MidpointRounding.AwayFromZero) == ipn.vads_amount)
                                {
                                    status = PaymentStatus.Captured;
                                }
                                break;

                            case "expired":
                                restoreStock = true;
                                status       = PaymentStatus.Expired;
                                break;

                            case "refused":
                                restoreStock = true;
                                status       = PaymentStatus.Refused;
                                break;

                            case "under_verification":
                            case "waiting_authorisation":
                            case "waiting_authorisation_to_validate":
                                // Grand Total MUST BE the same!
                                if (Math.Round(order.GrandTotal, 2, MidpointRounding.AwayFromZero) == ipn.vads_amount)
                                {
                                    status = PaymentStatus.Pending;
                                }
                                break;

                            default:
                                status = PaymentStatus.Unattended;
                                break;
                            }

                            if (restoreStock)
                            {
                                List <OrderDetailInfo> orderDetails = orderController.GetOrderDetails(order.OrderID);
                                if (orderDetails != null)
                                {
                                    foreach (OrderDetailInfo detail in orderDetails)
                                    {
                                        orderController.UpdateStockQuantity(detail.ProductID, detail.Quantity);
                                    }
                                    ProductController productController = new ProductController();
                                    productController.ClearAllCaches();
                                }
                            }
                        }
                    }
                }
                else
                {
                    alertReason = Localization.GetString("DifferentReceiverEmail", LocalResourceFile, _portalLanguage);
                }
            }

            // If the transaction is invalid
            if ((status == PaymentStatus.Invalid) || (status == PaymentStatus.Unattended))
            {
                // Add an Admin Alert to the DNN Log
                string        systempayGateway = Localization.GetString("StoreSystempayGateway", LocalResourceFile, _portalLanguage);
                string        adminAlert       = Localization.GetString("SecurityAlert", LocalResourceFile, _portalLanguage);
                LogProperties properties       = new LogProperties
                {
                    new LogDetailInfo(systempayGateway, adminAlert),
                    new LogDetailInfo(Localization.GetString("AlertReason", LocalResourceFile, _portalLanguage), alertReason),
                    new LogDetailInfo(Localization.GetString("FromIP", LocalResourceFile, _portalLanguage), Request.UserHostAddress),
                    new LogDetailInfo(Localization.GetString("IPNPayload", LocalResourceFile, _portalLanguage), ipn.Payload)
                };
                AddEventLog(EventLogController.EventLogType.ADMIN_ALERT.ToString(), properties, true);
                // Send an email to the store admin
                SendEmailToAdmin(systempayGateway + " " + adminAlert, Localization.GetString("EmailAlert", LocalResourceFile, _portalLanguage) + "\r\n\r\n" + alertReason);
            }

            return(status);
        }
Пример #21
0
        public string ConstructMediaMessage(string AttachmentUrl, string type, string Message, ref string MdeiaType)
        {
            string MediaMessage = "";

            try
            {
                JArray  MediaArray  = new JArray();
                JObject MediaJobj   = new JObject();
                JObject PayloadJobj = new JObject();

                MdeiaType = "1";

                string   FileType      = type;
                string   FileExtension = "";
                string[] FilePartArray = AttachmentUrl.Split('.');

                FileExtension = FilePartArray[FilePartArray.Length - 1];

                //if (jsonData.type == "1") image
                //else if (jsonData.type == "2") video
                //else if (jsonData.type == "6") doc
                //else if (jsonData.type == "0") text

                //if (jsonData.type == "1" || jsonData.type == "6" || jsonData.type == "2")
                //{

                //         jsonObj = {
                //             "conversationId": conversationId, "from": fromId, "to": agentId, "messageType": msgType,
                //"message": "", "mediaUrl": filePath };
                if (type == "image")
                {
                    MdeiaType = "1";
                    FileType  = "image";
                }
                else if (type == "video" || type == "audio")
                {
                    MdeiaType = "2";
                    FileType  = type;
                }
                //else if (type == "audio")
                //{
                //    MdeiaType = "2";
                //    FileType = "audio";
                //}
                else if (type == "document")
                {
                    MdeiaType = "6";

                    if (FileExtension == "xls" || FileExtension == "xlsx" || FileExtension == "csv")
                    {
                        FileType = "excel";
                    }
                    else if (FileExtension == "pdf" || FileExtension == "docx" || FileExtension == "doc")
                    {
                        FileType = "pdf";
                    }
                    else
                    {
                        FileType = "excel";
                    }
                }
                else
                {
                    MdeiaType = "0";
                }

                if (type != "video")
                {
                    JArray MediaJobjArray = new JArray();



                    PayloadJobj.Add(new JProperty("payload", FileType));
                    PayloadJobj.Add(new JProperty("text", AttachmentUrl));
                    PayloadJobj.Add(new JProperty("message", Message));

                    MediaJobjArray.Add(PayloadJobj);


                    MediaJobj.Add(new JProperty("custom", MediaJobjArray));


                    //PayloadJobj["payload"] = type;
                    //MediaJobj["text"] = AttachmentUrl;
                    //MediaJobj["message"] = Message;
                    //MediaMessage = @"[{"custom":[{"payload":"image","text":"' + filePath + '"}]}]";
                }
                else
                {
                    // MessageType = "2";

                    JObject SrcJobj = new JObject();


                    SrcJobj.Add(new JProperty("src", AttachmentUrl));

                    PayloadJobj.Add(new JProperty("payload", SrcJobj));
                    PayloadJobj.Add(new JProperty("type", FileType));

                    MediaJobj.Add(new JProperty("attachment", PayloadJobj));
                }

                MediaArray.Add(MediaJobj);

                MediaMessage = MediaArray.ToString();

                //   [{"attachment":{"payload":{"src":"http://staging-ping.telebu.com/uploads/chat/3180-1601296120820.mp3"},"type":"video"}}]


                //if (msgType == "1")
                //    hitMsg = '[{"custom":[{"payload":"image","text":"' + filePath + '"}]}]';
                //else if (msgType == "2")
                //    hitMsg = '[{"attachment":{"payload":{"src":"' + filePath + '"},"type":"video"}}]';
                //else if (msgType == "6" && (extnsn == "xls" || extnsn == "xlsx"))
                //    hitMsg = '[{"custom":[{"payload":"excel","text":"' + filePath + '"}]}]';
                //else if (msgType == "6" && extnsn == "pdf")
                //    hitMsg = '[{"custom":[{"payload":"pdf","text":"' + filePath + '"}]}]';
            }
            catch (Exception ex)
            {
                LogProperties.error("Exception at ConstructMediaMessage " + ex.ToString());
            }

            return(MediaMessage);
        }
Пример #22
0
        public async Task PostAsync([FromBody] JObject MessageJobj)
        {
            bool   outgoing;
            string ChannelUUId = "";

            string SocketPublishUrl = _configuration.GetValue <string>("RequestUrls:WebSocketPublish");

            string MdeiaType = "0";

            LogProperties.info("Whats api called");


            try

            {
                outgoing = (bool)MessageJobj["outgoing"];
                //               "sender": "919966226645",
                //"recipient": "2df4b63c-135a-4206-91d3-8132dfe64f22",
                if (!outgoing)
                {
                    ChannelUUId = Convert.ToString(MessageJobj["recipient"]);
                }

                WidgetChannels widgetChannel = null;
                Widgets        widget        = null;
                try
                {
                    widgetChannel = _context.WidgetChannels.Where(wc => wc.ChanneUUID == ChannelUUId && wc.ConversationTypeId == 2).FirstOrDefault();
                    LogProperties.info("widgetChannel for message: " + widgetChannel.WidgetId);

                    widget = _context.Widgets.Where(w => w.Id == widgetChannel.WidgetId).FirstOrDefault();
                    LogProperties.info("widget for message: " + widgetChannel.WidgetId);
                }
                catch (Exception dbEx)
                {
                    widgetChannel = _context.WidgetChannels.Where(wc => wc.Id == 2).FirstOrDefault();
                    LogProperties.info("widgetChannel for message catch: " + widgetChannel.WidgetId);

                    widget = _context.Widgets.Where(w => w.Id == 6).FirstOrDefault();
                    LogProperties.info("widget for message catch: " + widget.Id);
                }
                // var widgetChannel = _context.WidgetChannels.Where(wc => wc.ChanneUUID == ChannelUUId && wc.ConversationTypeId == 2).FirstOrDefault();
                // LogProperties.info("widgetChannel for message: " + widgetChannel.WidgetId );



                //[HttpPost("{account_id}/widgets/{widget_id}/conversations/{conversation_id}/{is_endchat}/replies")]
                if (widget != null)
                {
                    if (!outgoing)
                    {
                        JObject jObject = new JObject();
                        jObject = JObject.Parse(MessageJobj.ToString());
                        //    await ProcessIncomingMessageAsync(widget, MessageJobj);

                        LogProperties.info("Whats api ougoing enter");
                        string CustomerMobile       = "";
                        string CustomerName         = "";
                        string CustomerProfileImage = "";

                        int     AccountId              = widget.AccountId;
                        int     WidgetId               = widget.Id;
                        int     ConverstationId        = 0;
                        long    ConverstationMessageId = 0;
                        int     CustomerId             = 0;
                        JObject CustJobj               = new JObject();

                        CustomerMobile       = Convert.ToString(MessageJobj["sender"]);
                        ChannelUUId          = Convert.ToString(MessageJobj["recipient"]);
                        CustomerName         = Convert.ToString(MessageJobj["payload"]["user"]["name"]);
                        CustomerProfileImage = Convert.ToString(MessageJobj["payload"]["user"]["image"]);

                        ConversationsController conController = new ConversationsController(_context, _configuration);



                        CustJobj   = GetCustomerId(AccountId, CustomerName, CustomerMobile, CustomerProfileImage);
                        CustomerId = Convert.ToBoolean(CustJobj["Success"]) ? Convert.ToInt32(CustJobj["CustomerId"]) : -1;
                        LogProperties.info("Whats api after get customer");
                        var PrevConverstations = (from Con in _context.Conversations
                                                  where Con.WidgetId == WidgetId && Con.CustomerId == CustomerId
                                                  orderby Con.Id descending
                                                  select new {
                            Con.Id,
                            Con.AgentId
                        }).FirstOrDefault();

                        if (PrevConverstations != null)
                        {
                            ConverstationId = PrevConverstations.Id;
                        }
                        LogProperties.info("Whats api after Conversations");
                        var PrevConMessages = (from ConMess in _context.ConversationMessages
                                               where ConMess.ConversationId == ConverstationId
                                               orderby ConMess.Id descending
                                               select new
                        {
                            ConMess.Id,
                            ConMess.CreatedTimeUTC,
                            ConMess.AgentId
                        }).FirstOrDefault();

                        DateTime RecentMsgTime;
                        if (PrevConMessages != null && PrevConMessages.Id > 0)
                        {
                            ConverstationMessageId = PrevConMessages.Id;
                            RecentMsgTime          = PrevConMessages.CreatedTimeUTC;
                        }
                        else
                        {
                            RecentMsgTime = DateTime.Today.AddDays(-10);
                        }

                        LogProperties.info("Whats api after Conversation messages");

                        DateTime CurrentUtcNow = DateTime.UtcNow;
                        TimeSpan MessageSpan   = CurrentUtcNow - RecentMsgTime;


                        double totalSecForDay = 3 * 60 * 60;           // Static condiftion
                        bool   IsNewChat      = false;
                        if (MessageSpan.TotalSeconds > totalSecForDay) // create new conversations after 24 hours
                        {
                            Conversations conversations = new Conversations()
                            {
                                StatusId           = 1,
                                CustomerId         = CustomerId,
                                Mobile             = CustomerMobile,
                                ConversationTypeId = 2
                            };


                            ActionResult <Conversations> newCon = await conController.PostConversations(AccountId, WidgetId, conversations);

                            // JObject Con = await CreateConversation(AccountId, WidgetId, conversations);

                            OkObjectResult okResult = newCon.Result as OkObjectResult;

                            if (okResult.StatusCode == 200)
                            {
                                Conversations NewConversation = okResult.Value as Conversations;
                                ConverstationId = NewConversation.Id;
                            }



                            IsNewChat = true;
                        }
                        LogProperties.info("Whats api after Conversation save");
                        ConversationMessages conversationMessages = new ConversationMessages();
                        int IsBotEnd = 0;
                        //"MessageTypeId": "1",
                        //    "Message":msg
                        conversationMessages.ConversationId     = ConverstationId;
                        conversationMessages.MessageTypeId      = 1;
                        conversationMessages.ConversationTypeId = 2;

                        if (IsNewChat == false)
                        {
                            conversationMessages.AgentId = PrevConverstations.AgentId;
                        }
                        //message payload table
                        conversationMessages.Message = Convert.ToString(MessageJobj["payload"]["text"]);
                        string CustomerMessage = Convert.ToString(MessageJobj["payload"]["text"]);

                        string MessageType = Convert.ToString(MessageJobj["payload"]["type"]);


                        if (MessageType != "text")
                        {
                            //attachment

                            conversationMessages.AttachmentUrl = Convert.ToString(MessageJobj["payload"]["attachment"]);

                            conversationMessages.Message = ConstructMediaMessage(conversationMessages.AttachmentUrl, MessageType, conversationMessages.Message, ref MdeiaType);
                        }


                        var ConInfo = _context.ConversationInfo.Where(w => w.ConversationId == ConverstationId).FirstOrDefault();
                        if (ConInfo != null)
                        {
                            IsBotEnd = ConInfo.IsBotEnd;
                        }
                        if (IsBotEnd > 0)
                        {
                            conversationMessages.MessageTypeId = 3;
                        }
                        ActionResult <ConversationMessages> newConMsg = await conController.PostConversationMessages(AccountId, WidgetId, ConverstationId, IsBotEnd, conversationMessages);



                        OkObjectResult okResultMesg = newConMsg.Result as OkObjectResult;

                        if (okResultMesg.StatusCode == 200)
                        {
                            ConversationMessages NewConvMsg = okResultMesg.Value as ConversationMessages;
                        }

                        LogProperties.info("Whats api after Conversation message save");

                        if (IsBotEnd > 0)
                        {
                            // table for botend

                            //if (IsPingAgent == "true")
                            //{
                            //    cust_jsonObj = { "conversationId": conversationId, "from": conversationId, "to": agentId, "messageType": "0", "message": "Customer OnBoard" };
                            //}
                            //else
                            //{
                            //    cust_jsonObj = { "conversationId": conversationId, "from": fromId, "to": agentId, "messageType": "0", "message": "Customer OnBoard" };
                            //}
                            if (IsNewChat == false && IsBotEnd > 0) // send message to agent through socket
                            {
                                //JObject jobj = new JObject();
                                //jobj.Add(new JProperty("conversationId", conversationMessages.ConversationId));
                                //jobj.Add(new JProperty("from", "WhatsApp_"+ conversationMessages.ConversationId));
                                //jobj.Add(new JProperty("to", "Hub_" + conversationMessages.AgentId));
                                //jobj.Add(new JProperty("message", conversationMessages.Message));
                                //jobj.Add(new JProperty("messageType", "0"));

                                //WebSocketSubscriber.Send(jobj);

                                JObject jobjs        = new JObject();
                                JObject wsMessageObj = new JObject();


                                JObject CustomerDetails = new JObject();

                                //                "data":{"fromName" :"" ,"fromMobile",""}

                                CustomerDetails.Add(new JProperty("fromName", CustomerName));
                                CustomerDetails.Add(new JProperty("fromMobile", CustomerMobile));

                                jobjs.Add(new JProperty("conversationId", Convert.ToString(ConverstationId)));
                                jobjs.Add(new JProperty("from", "WhatsApp_5f2d3a8e31197a445686653b"));
                                jobjs.Add(new JProperty("to", "Hub_" + PrevConverstations.AgentId));
                                jobjs.Add(new JProperty("message", CustomerMessage));
                                jobjs.Add(new JProperty("mediaUrl", conversationMessages.AttachmentUrl));
                                jobjs.Add(new JProperty("type", MdeiaType));
                                jobjs.Add(new JProperty("data", CustomerDetails));
                                jobjs.Add(new JProperty("messageType", "0"));
                                jobjs.Add(new JProperty("ConversationTypeId", 2));

                                wsMessageObj = new JObject(new JProperty("Module", "Chat"),
                                                           new JProperty("Event", "NewChat"),
                                                           new JProperty("Channel_Name", "WhatsApp_Hub_" + PrevConverstations.AgentId),
                                                           new JProperty("Data", jobjs));


                                // WebSocketSubscriber wb = new WebSocketSubscriber();
                                WebSocketSubscriber.pushSocket(SocketPublishUrl, wsMessageObj);

                                LogProperties.info("Whats api after websocket publish");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogProperties.error("expection at WhatsApp Handler: " + ex.ToString());
            }
        }
        public IActionResult Post()
        {
            int WidgetId = Convert.ToInt32(HttpContext.Request.Query["WidgetId"]);

            try
            {
                WidgetChannels WidgetChannels = (from Wchannel in _context.WidgetChannels
                                                 where Wchannel.WidgetId == WidgetId &&
                                                 Wchannel.ConversationTypeId == 2 select Wchannel).FirstOrDefault();

                WidgetAuthkeys WidgetAuthKeys = (from Auth in _context.WidgetAuthkeys
                                                 where Auth.WidgetChannelId == WidgetChannels.Id
                                                 select Auth).FirstOrDefault();

                string AuthKey, AuthToken;
                string Authorization;

                AuthKey   = WidgetAuthKeys.AuthKey;
                AuthToken = WidgetAuthKeys.AuthToken;
                var AuthBytes = System.Text.Encoding.UTF8.GetBytes(AuthKey + ":" + AuthToken);
                Authorization = "Basic " + Convert.ToBase64String(AuthBytes);

                string url = _configuration.GetValue <string>("RequestUrls:BluekiteUrl");
                url += AuthKey + "/SocialMediaFiles/";
                // url += ChannelUUId + "/Messages/";



                //var uri = new Uri("https://restapi.smscountry.com/v0.1/Accounts/sIkXPrYqDPe6xxjZgT1z/SocialMediaFiles/");

                var uri = new Uri(url);



                var ms = new MemoryStream();
                //var formFile = Request.Form.Files[0];
                Request.Form.Files[0].CopyTo(ms);
                var fileBytes = ms.ToArray();

                var client = new RestClient(uri);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", Authorization);
                request.AddHeader("Content-Type", "multipart/form-data");
                request.AddFileBytes("attach", fileBytes, Request.Form.Files[0].FileName);
                //request.AddFile("", "/C:/Users/Administrator/Pictures/Screenshots/Screenshot_2.png");



                IRestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);


                var res = JObject.Parse(response.Content);

                return(Ok(res));
            }
            catch (Exception ex)
            {
                LogProperties.error("Exception at while uploading file to server " + ex.ToString());
                JObject res = new JObject();
                res.Add(new JProperty("Success", "False"));
                res.Add(new JProperty("Message", ex.ToString()));

                return(Ok(res));
            }
        }
Пример #24
0
        private PaymentStatus VerifyPayment(PayPalIPNParameters ipn)
        {
            PaymentStatus status = PaymentStatus.Invalid;
            // Default Alert Reason
            string alertReason = Localization.GetString("InvalidIPN", LocalResourceFile, _portalLanguage);

            if (ipn.IsValid)
            {
                // Process notification validation
                HttpWebRequest request = WebRequest.Create(_verificationURL) as HttpWebRequest;
                if (request != null)
                {
                    request.Method        = "POST";
                    request.ContentLength = ipn.PostString.Length;
                    request.ContentType   = "application/x-www-form-urlencoded";

                    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                    {
                        writer.Write(ipn.PostString);
                        writer.Close();
                    }

                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    if (response != null)
                    {
                        string responseString;
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            responseString = reader.ReadToEnd();
                            reader.Close();
                        }

                        // If the transaction is VERIFIED by PayPal
                        if (string.Compare(responseString, "VERIFIED", true) == 0)
                        {
                            // Security checking: is this request come from right PayPal account ID
                            if (IsFromReceiver(ipn))
                            {
                                // Security checking: compares some PayPal fields with order fields
                                alertReason = Localization.GetString("WrongOrderInfos", LocalResourceFile, _portalLanguage);
                                OrderController orderController = new OrderController();
                                OrderInfo       order           = orderController.GetOrder(PortalSettings.PortalId, ipn.invoice);
                                // If this order exist
                                if (order != null)
                                {
                                    // Currency MUST BE the same!
                                    if (_settings.Currency == ipn.mc_currency)
                                    {
                                        // Everything looks good, validate the transaction!
                                        switch (ipn.payment_status.ToLower())
                                        {
                                        case "completed":
                                            // Grand Total MUST BE the same!
                                            if (Math.Round(order.GrandTotal, 2, MidpointRounding.AwayFromZero) == ipn.mc_gross)
                                            {
                                                status = PaymentStatus.Payed;
                                            }
                                            break;

                                        case "pending":
                                        case "in-progress":
                                            // Grand Total MUST BE the same!
                                            if (Math.Round(order.GrandTotal, 2, MidpointRounding.AwayFromZero) == ipn.mc_gross)
                                            {
                                                status = PaymentStatus.Pending;
                                            }
                                            break;

                                        case "refunded":
                                            status = PaymentStatus.Refunded;
                                            break;

                                        case "reversed":
                                            status = PaymentStatus.Reversed;
                                            break;

                                        default:
                                            status = PaymentStatus.Unattended;
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                alertReason = Localization.GetString("DifferentReceiverEmail", LocalResourceFile, _portalLanguage);
                            }
                        }
                        else
                        {
                            alertReason = Localization.GetString("VerificationFailed", LocalResourceFile, _portalLanguage);
                        }
                    }
                }
            }

            // If the transaction is invalid
            if ((status == PaymentStatus.Invalid) || (status == PaymentStatus.Unattended))
            {
                // Add an Admin Alert to the DNN Log
                string        paypalGateway = Localization.GetString("StorePayPalGateway", LocalResourceFile, _portalLanguage);
                string        adminAlert    = Localization.GetString("SecurityAlert", LocalResourceFile, _portalLanguage);
                LogProperties properties    = new LogProperties
                {
                    new LogDetailInfo(paypalGateway, adminAlert),
                    new LogDetailInfo(Localization.GetString("AlertReason", LocalResourceFile, _portalLanguage), alertReason),
                    new LogDetailInfo(Localization.GetString("FromIP", LocalResourceFile, _portalLanguage), Request.UserHostAddress),
                    new LogDetailInfo(Localization.GetString("IPNPOSTString", LocalResourceFile, _portalLanguage), ipn.PostString)
                };
                AddEventLog(EventLogController.EventLogType.ADMIN_ALERT.ToString(), properties, true);
                // Send an email to the store admin
                SendEmailToAdmin(paypalGateway + " " + adminAlert, Localization.GetString("EmailAlert", LocalResourceFile, _portalLanguage) + "\r\n\r\n" + alertReason);
            }

            return(status);
        }
Пример #25
0
 public string GetWelcomeMsg()
 {
     LogProperties.info("Application started");
     return("!!!Welcome to TelebuHubChat!!!");
 }
Пример #26
0
        public JObject GetCustomerId(int AccountId, string callerName, string callerMobile, string ProfilePic)
        {
            JObject res        = new JObject();
            int     CustomerId = 0;

            try
            {
                CustomerId = (from Cust in _context.MasterCustomers
                              where Cust.AccountId == AccountId && Cust.Mobile == callerMobile
                              select Cust.AccountCustomerId).FirstOrDefault();

                if (CustomerId == 0)
                {
                    JObject cust = new JObject();
                    cust.Add(new JProperty("Name", callerName));
                    cust.Add(new JProperty("Mobile", callerMobile));
                    //cust.Add(new JProperty("ProfilePic", ProfilePic));


                    string url = _configuration.GetValue <string>("RequestUrls:CustomerApiUrl");
                    url += Convert.ToString(AccountId) + "&Name=" + callerName + "&Mobile=" + callerMobile + "&Details=" + Convert.ToString(cust);
                    var    request  = (HttpWebRequest)WebRequest.Create(url);
                    var    response = (HttpWebResponse)request.GetResponse();
                    string responseString;

                    using (var stream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            responseString = reader.ReadToEnd();
                        }
                    }
                    if (responseString != "")
                    {
                        res = JObject.Parse(responseString);
                    }

                    MasterCustomers Mc = new MasterCustomers();

                    Mc.AccountId         = AccountId;
                    Mc.CustomerName      = callerName;
                    Mc.Mobile            = callerMobile;
                    Mc.AccountCustomerId = Convert.ToInt32(res["customerId"]);


                    CustomerId = Mc.AccountCustomerId;

                    _context.MasterCustomers.Add(Mc);
                    _context.SaveChanges();
                }

                res.Add(new JProperty("Success", true));
                res.Add(new JProperty("Message", "Succes"));
                res.Add(new JProperty("CustomerId", CustomerId));
            }
            catch (Exception ex)
            {
                res.Add(new JProperty("Success", false));
                res.Add(new JProperty("Message", ex.ToString()));
                LogProperties.error("expection at get Customer: " + ex.ToString());
            }

            return(res);
        }