private static string BlocksListSerializer(List <Block> blocks, Formatting formatting, uint tabulationsCount)
        {
            string outerTabulationBuilder = string.Empty;
            string innerTabulationBuilder = string.Empty;

            if (formatting == Formatting.Indented)
            {
                SerializationTools.InitTabulations(out outerTabulationBuilder, out innerTabulationBuilder, tabulationsCount);
            }
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("[");
            for (int i = 0; i < blocks.Count; ++i)
            {
                builder.AppendLine($"{innerTabulationBuilder}(block:{i})={(formatting == Formatting.Indented ? Block.SerializeToString(blocks[i], formatting, tabulationsCount + 1) : Block.SerializeToString(blocks[i]))}{(i == blocks.Count-1 ? ";" : ",")}");
            }
            builder.Append($"{outerTabulationBuilder}]");
            return(builder.ToString());
        }
        public void LoadCertificateCache()
        {
            _dictionaryCache = new Dictionary <string, CertCacheEntry>();

            if (!File.Exists(CacheFilename))
            {
                return;
            }

            try
            {
                _dictionaryCache = SerializationTools.DeserializeDictionary <string, CertCacheEntry>(CacheFilename);
            }
            catch (SystemException e)
            {
                Console.WriteLine(e);
                File.Delete(CacheFilename);
            }
        }
Example #3
0
        /// <summary>
        ///   Serializes passed hypermedia to string using passed encoding.
        /// </summary>
        /// <param name="hypermedia">
        ///   Hypermedia to be serialized.
        /// </param>
        /// <param name="formatting">
        ///   <see cref="Formatting">Formatting</see> options for serialization.
        /// </param>
        /// <param name="tabulationCount">
        ///   Internal argument for count of tabulations.
        /// </param>
        public string SerializeToString(Hypermedia hypermedia, Formatting formatting, uint tabulationsCount)
        {
            string outerTabulationBuilder = string.Empty;
            string innerTabulationBuilder = string.Empty;

            if (formatting == Formatting.Indented)
            {
                SerializationTools.InitTabulations(out outerTabulationBuilder, out innerTabulationBuilder, tabulationsCount);
            }
            StringBuilder builder = new StringBuilder();

            SerializationTools.InitStartBaseHypermediaSerializationStrings(ref builder, hypermedia, outerTabulationBuilder, innerTabulationBuilder);
            builder.AppendLine($"{innerTabulationBuilder}(string:comment)={(hypermedia.Comment is null ? "null" : EncodingTools.EncodeString(hypermedia.Comment, hypermedia.Encoding is null ? Encoding.UTF8 : hypermedia.Encoding))},");
            builder.AppendLine($"{innerTabulationBuilder}(encoding:encoding)={(hypermedia.Encoding is null ? "utf-8" : hypermedia.Encoding.WebName)},");
            builder.AppendLine($"{innerTabulationBuilder}(date_time:created_date_time)={((DateTimeOffset)hypermedia.CreatedDateTime).ToUnixTimeSeconds()},");
            builder.AppendLine($"{innerTabulationBuilder}(string:created_by)={hypermedia.CreatedBy},");
            builder.AppendLine($"{innerTabulationBuilder}(string:creator_peer)={(hypermedia.CreatorPeer is null ? "null" : hypermedia.CreatorPeer)},");
            if (hypermedia.Entities.Count <= 0)
            {
                throw new ArgumentException("Hypermedia entities list can not be empty", nameof(hypermedia));
            }
            builder.AppendLine($"{innerTabulationBuilder}{_startOfEntityListDeclaration}{hypermedia.Entities.Count}]:entities)=" + "{" +
                               (formatting == Formatting.Indented
                ? EntityListSerializer(
                                    hypermedia.Entities, hypermedia.Encoding is null
                    ? Encoding.UTF8
                    : hypermedia.Encoding, formatting, tabulationsCount + 1
                                    )
                : EntityListSerializer(
                                    hypermedia.Entities, hypermedia.Encoding is null
                    ? Encoding.UTF8
                    : hypermedia.Encoding
                                    )
                               ) + $"{_endOfEntityListDeclaration}");
            builder.AppendLine($"{innerTabulationBuilder}(boolean:is_directory_wrapped)={(hypermedia.IsDirectoryWrapped ? "true" : "false")},");
            builder.AppendLine($"{innerTabulationBuilder}(boolean:is_raw_ipfs)={(hypermedia.IsRawIPFS ? "true" : "false")},");
            builder.AppendLine($"{innerTabulationBuilder}(string:topic)={(hypermedia.Topic is null ? "null" : hypermedia.Topic)},");
            builder.AppendLine($"{innerTabulationBuilder}(string:default_subscription_message)={(hypermedia.DefaultSubscriptionMessage is null ? "subscribed" : hypermedia.DefaultSubscriptionMessage)},");
            builder.AppendLine($"{innerTabulationBuilder}(string:default_seeding_message)={(hypermedia.DefaultSeedingMessage is null ? "seeding" : hypermedia.DefaultSeedingMessage)},");
            builder.AppendLine($"{innerTabulationBuilder}(string:version)={hypermedia.Version},");
            SerializationTools.InitEndBaseSerializationStrings(ref builder, hypermedia, outerTabulationBuilder, innerTabulationBuilder);
            return(builder.ToString());
        }
        public static DataGridResult GetDataInfo(string serializeObject, string c, string _search, string nd, int rows, int page, string sidx, string sord)
        {
            int pageControl = GetPageAssemblyValue(c);

            if (!CheckUserLogin(Helper.GetString(pageControl)))
            {
                Session["SessionExpired"] = true;
                throw new Exception("[{(SessionExpired)}]");
            }

            DataGrid dataGrid = ((DataGridSchema)SerializationTools.DeserializeXml(Helper.Decrypt(serializeObject, HttpContext.Current.Session), typeof(DataGridSchema))).GetDataGrid();

            string searchFiletrs  = string.Empty;
            string toolbarFilters = string.Empty;

            if (_search == "True")
            {
                string searchOptions = "[" + Helper.GetStreamContent(System.Web.HttpContext.Current.Request.InputStream) + "]";
                JArray array         = JArray.Parse(searchOptions);
                foreach (JObject content in array.Children <JObject>())
                {
                    foreach (JProperty prop in content.Properties())
                    {
                        if (prop.Name == "filters")
                        {
                            toolbarFilters = JObject.Parse(prop.Value.ToString())["rules"].ToString();
                        }
                        if (prop.Name == "SearchFiletrs")
                        {
                            searchFiletrs = prop.Value.ToString();
                        }
                    }
                }
            }

            Assembly currentAssembly   = Assembly.GetExecutingAssembly();
            string   pageName          = string.Format("{0}.{1}", currentAssembly.GetName().Name, ((Business.UserControls)pageControl).ToString().Replace('_', '.'));
            Delegate dataBinderHandler = ((UIUserControlBase)Activator.CreateInstance(currentAssembly.GetType(pageName))).GetDataBinder(dataGrid.ID);
            Delegate dataRenderEvent   = ((UIUserControlBase)Activator.CreateInstance(currentAssembly.GetType(pageName))).GetDataRenderHandler(dataGrid.ID);

            return(dataGrid.DataBind(sidx, sord, page, rows, searchFiletrs, toolbarFilters, dataBinderHandler, dataRenderEvent));
        }
        /// <summary>
        ///   Serializes passed file to string using passed encoding.
        /// </summary>
        /// <param name="file">
        ///   File to be serialized.
        /// </param>
        /// <param name="encoding">
        ///   Encoding used for serialization of file name.
        ///   Usually passed from parent <see cref="Hypermedia">hypermedia</see> where file resides.
        /// </param>
        /// <param name="formatting">
        ///   <see cref="Formatting">Formatting</see> options for serialization.
        /// </param>
        /// <param name="tabulationCount">
        ///   Internal argument for count of tabulations.
        /// </param>
        public static string SerializeToString(File file, Encoding encoding, Formatting formatting, uint tabulationsCount)
        {
            string outerTabulationBuilder = string.Empty;
            string innerTabulationBuilder = string.Empty;

            if (formatting == Formatting.Indented)
            {
                SerializationTools.InitTabulations(out outerTabulationBuilder, out innerTabulationBuilder, tabulationsCount);
            }
            StringBuilder builder = new StringBuilder();

            SerializationTools.InitStartBaseSystemEntitySerializationStrings(ref builder, file, encoding, outerTabulationBuilder, innerTabulationBuilder);
            builder.AppendLine($"{innerTabulationBuilder}(string:extension)={file.Extension},");
            builder.AppendLine($"{innerTabulationBuilder}(file_attributes_null:attributes)={FileAttributesSerializer(file.Attributes)},");
            builder.AppendLine($"{innerTabulationBuilder}(date_time_null:last_modified_date_time)={(file.LastModifiedDateTime is null?"null":((DateTimeOffset)file.LastModifiedDateTime.Value).ToUnixTimeSeconds().ToString())},");
            builder.AppendLine($"{innerTabulationBuilder}{_startOfBlockListDeclaration}{file.Blocks.Count}]:blocks)=" + "{" + (file.IsSingleBlock ? "empty;" : (formatting == Formatting.Indented ? BlocksListSerializer(file.Blocks, formatting, tabulationsCount + 1) : BlocksListSerializer(file.Blocks))) + $"{_endOfBlockListDeclaration}");
            builder.AppendLine($"{innerTabulationBuilder}(boolean:is_single_block)={(file.IsSingleBlock ? "true" : "false")},");
            SerializationTools.InitEndBaseSerializationStrings(ref builder, file, outerTabulationBuilder, innerTabulationBuilder);
            return(builder.ToString());
        }
Example #6
0
        public void Read()
        {
            var result = SerializationTools.DeserializeFromXml <List <CacheEntry> >(Filename);

            Cache.Clear();
            foreach (var cacheEntry in result)
            {
                var id = cacheEntry.Entry.GetCacheId();
                if (id == null)
                {
                    continue;
                }

                if (SerializeIcons && cacheEntry.Icon != null)
                {
                    cacheEntry.Entry.IconBitmap = DeserializeIcon(cacheEntry.Icon);
                }

                Cache.Add(id, cacheEntry.Entry);
            }
        }
        public void Read()
        {
            var result = SerializationTools.DeserializeFromXml <List <CacheEntry> >(Filename);

            Cache.Clear();

            // Ignore entries if more than 1 have the same cache id
            foreach (var group in result
                     .GroupBy(x => x.Entry.GetCacheId())
                     .Where(g => g.Key != null && g.CountEquals(1)))
            {
                var cacheEntry = group.Single();

                if (SerializeIcons && cacheEntry.Icon != null)
                {
                    cacheEntry.Entry.IconBitmap = DeserializeIcon(cacheEntry.Icon);
                }

                Cache.Add(group.Key, cacheEntry.Entry);
            }
        }
        public string Serialize(bool throwException = false)
        {
            var result = "";

            try
            {
                result = SerializationTools.SerializeDataContract(this);
            }
            catch (Exception ex)
            {
                if (throwException)
                {
                    throw;
                }

                LogService.LogError(
                    $"Произошла ошибка при попытке сериализовать сообщение: {nameof(ToMsrFromTUResponse)}. Ошибка - {ex.Message}");
            }

            return(result);
        }
        /// <summary>
        /// Erstellt für alle noch nicht berücksichtigten Aufzeichnungen Auszüge aus der Programmzeitschrift.
        /// </summary>
        /// <param name="recordings">Die Liste der Aufzeichnungen, die bearbeitet werden sollen.</param>
        private void RecordingPostProcessing(params VCRRecordingInfo[] recordings)
        {
            // Process all
            foreach (var recording in recordings)
            {
                // Report
                Tools.ExtendedLogging("Extracting EPGINFO for {0}", recording.Name);

                // Load bounds
                var from = recording.PhysicalStart.Value;
                var to   = DateTime.UtcNow;

                // Create guide
                var entries = new ProgramGuideEntries();

                // Fill it
                entries.AddRange(
                    ProfileState
                    .ProgramGuide
                    .GetEntries(recording.Source.Source)
                    .TakeWhile(e => e.StartTime < to)
                    .Where(e => e.EndTime > from));

                // Write it out
                SerializationTools.SafeSave(entries, Path.ChangeExtension(recording.FileName, "epginfo"));
            }

            // Detect all files related to the recordings
            var scheduleIdentifiers = new HashSet <Guid>(recordings.Select(recording => recording.ScheduleUniqueID.Value));
            var files = m_files.Where(file => scheduleIdentifiers.Contains(new Guid(file.ScheduleIdentifier)));

            // Clone current environment
            var environment = new Dictionary <string, string>(ExtensionEnvironment);

            // Fill
            AddFilesToEnvironment(environment, "Recorded", files);

            // Process extensions
            FireRecordingFinishedExtensions(environment);
        }
Example #10
0
        public void LoadCertificateCache()
        {
            _dictionaryCahe = new Dictionary <string, X509Certificate2>();

            if (!File.Exists(CacheFilename))
            {
                return;
            }

            try
            {
                var l = SerializationTools.DeserializeDictionary <string, byte[]>(CacheFilename);

                _dictionaryCahe = l.ToDictionary(x => x.Key, x => x.Value != null ? new X509Certificate2(x.Value) : null);
            }
            catch (SystemException e)
            {
                Console.WriteLine(e);
                File.Delete(CacheFilename);
                _dictionaryCahe.Clear();
            }
        }
        /// <summary>
        ///   Serializes passed directory to string using passed encoding.
        /// </summary>
        /// <param name="directory">
        ///   Directory to be serialized.
        /// </param>
        /// <param name="encoding">
        ///   Encoding used for serialization of directory name.
        ///   Usually passed from parent <see cref="Hypermedia">hypermedia</see> where directory resides.
        /// </param>
        /// <param name="formatting">
        ///   <see cref="Formatting">Formatting</see> options for serialization.
        /// </param>
        /// <param name="tabulationCount">
        ///   Internal argument for count of tabulations.
        /// </param>
        public static string SerializeToString(Directory directory, Encoding encoding, Formatting formatting, uint tabulationsCount)
        {
            string outerTabulationBuilder = string.Empty;
            string innerTabulationBuilder = string.Empty;

            if (formatting == Formatting.Indented)
            {
                SerializationTools.InitTabulations(out outerTabulationBuilder, out innerTabulationBuilder, tabulationsCount);
            }
            StringBuilder builder = new StringBuilder();

            SerializationTools.InitStartBaseSystemEntitySerializationStrings(ref builder, directory, encoding, outerTabulationBuilder, innerTabulationBuilder);
            builder.AppendLine($"{innerTabulationBuilder}(file_attributes_null:attributes)={FileAttributesSerializer(directory.Attributes)},");
            builder.AppendLine($"{innerTabulationBuilder}(date_time_null:last_modified_date_time)={(directory.LastModifiedDateTime is null ? "null" : ((DateTimeOffset)directory.LastModifiedDateTime.Value).ToUnixTimeSeconds().ToString())},");
            if (directory.Entities.Count <= 0)
            {
                throw new ArgumentException("Directory entities list can not be empty", nameof(directory));
            }
            builder.AppendLine($"{innerTabulationBuilder}{_startOfSystemEntityListDeclaration}{directory.Entities.Count}]:entities)=" + "{" + (directory.Entities.Count <= 0 ? "empty;" : (formatting == Formatting.Indented ? SystemEntitiesListSerializer(directory.Entities, encoding, formatting, tabulationsCount + 1) : SystemEntitiesListSerializer(directory.Entities, encoding))) + $"{_endOfSystemEntityListDeclaration}");
            SerializationTools.InitEndBaseSerializationStrings(ref builder, directory, outerTabulationBuilder, innerTabulationBuilder);
            return(builder.ToString());
        }
Example #12
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Common.RegularContent regularContent = new Common.RegularContent();
            Business.RegularContentSerialization regularContentSerialization = new RegularContentSerialization();
            try
            {
                regularContent.Type = Helper.GetInt(drpType.SelectedValue);
                switch (regularContent.Type)
                {
                case (int)RegularContentType.URL:
                    if (string.IsNullOrEmpty(txtUrl.Text))
                    {
                        throw new Exception(Language.GetString("CompleteURLField"));
                    }

                    regularContentSerialization.URL = txtUrl.Text;
                    break;

                case (int)RegularContentType.DB:
                    if (string.IsNullOrEmpty(txtConnectionString.Text))
                    {
                        throw new Exception(Language.GetString("CompleteConnectionStringField"));
                    }
                    if (string.IsNullOrEmpty(txtQuery.Text))
                    {
                        throw new Exception(Language.GetString("CompleteQueryField"));
                    }
                    if (string.IsNullOrEmpty(txtField.Text))
                    {
                        throw new Exception(Language.GetString("CompleteColumnField"));
                    }

                    regularContentSerialization.ConnectionString = txtConnectionString.Text;
                    regularContentSerialization.Query            = txtQuery.Text;
                    regularContentSerialization.Field            = txtField.Text;
                    break;
                }

                regularContent.Title       = txtTitle.Text;
                regularContent.Type        = Helper.GetInt(drpType.SelectedValue);
                regularContent.IsActive    = chbIsActive.Checked;
                regularContent.PeriodType  = Helper.GetInt(drpPeriodType.SelectedValue);
                regularContent.Period      = Helper.GetInt(drpPeriodType.SelectedValue);
                regularContent.WarningType = Helper.GetInt(drpWatningType.SelectedValue);
                regularContent.CreateDate  = DateTime.Now;
                //regularContent.StartDateTime = DateManager.GetChristianDateTimeForDB(dtpStartDateTime.FullDateTime);
                //regularContent.EndDateTime = DateManager.GetChristianDateTimeForDB(dtpEndDateTime.FullDateTime);
                var dateTime    = dtpStartDateTime.FullDateTime;
                var dateTimeEnd = dtpEndDateTime.FullDateTime;
                if (Session["Language"].ToString() == "fa")
                {
                    regularContent.StartDateTime = DateManager.GetChristianDateTimeForDB(dateTime);
                    regularContent.EndDateTime   = DateManager.GetChristianDateTimeForDB(dateTimeEnd);
                }
                else
                {
                    regularContent.StartDateTime = DateTime.Parse(dateTime);
                    regularContent.StartDateTime = DateTime.Parse(dateTimeEnd);
                }
                regularContent.EffectiveDateTime = regularContent.StartDateTime;
                regularContent.PrivateNumberGuid = Helper.GetGuid(drpSenderNumber.SelectedValue);
                regularContent.UserGuid          = UserGuid;
                regularContent.Config            = SerializationTools.SerializeToXml(regularContentSerialization, regularContentSerialization.GetType());

                if (regularContent.HasError)
                {
                    throw new Exception(regularContent.ErrorMessage);
                }

                switch (ActionType)
                {
                case "insert":
                    if (!Facade.RegularContent.Insert(regularContent))
                    {
                        throw new Exception(Language.GetString("ErrorRecord"));
                    }
                    break;

                case "edit":
                    regularContent.RegularContentGuid = RegularContentGuid;
                    if (!Facade.RegularContent.Update(regularContent))
                    {
                        throw new Exception(Language.GetString("ErrorRecord"));
                    }
                    break;
                }
                Response.Redirect(string.Format("/PageLoader.aspx?c={0}", Helper.Encrypt((int)Arad.SMS.Gateway.Business.UserControls.UI_RegularContents_RegularContent, Session)));
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message, string.Empty, "danger");
            }
        }
Example #13
0
 public static void SerializeApplicationEntries(string filename, IEnumerable <ApplicationUninstallerEntry> items)
 {
     SerializationTools.SerializeToXml(filename, new ApplicationEntrySerializer(items));
 }
Example #14
0
        public void Dispose()
        {
            if (dispose)
            {
                object value = Object.GetType().GetProperty(PropertyName).GetValue(Object, null);
                NewValue = _IsValueType ? value : _IsString?string.Copy(value as string) : SerializationTools.GetCopyOfAObject(value);

                URD.AddChange(this);
                dispose = false;
            }
        }
Example #15
0
        /// <summary>
        ///     Принять сообщение из шины.
        /// </summary>
        /// <param name="message">Сообщение.</param>
        public void AcceptMessage([MessageParameter(Name = "msg")] MessageFromESB message)
        {
            LogService.LogInfo($"BusListenerService: Принял соообщение - {message.MessageTypeID}!");

            // Ищем в конфиг файле, привязку между типов сообщения и xml-классом этого сообщения.
            var xmlClassName = Context.GetMessageXMLClassNameByMessageID(message.MessageTypeID);

            if (!string.IsNullOrEmpty(xmlClassName))
            {
                // Получаем тип по названию класса из конфиг файла.
                var messageType = Type.GetType(xmlClassName);
                if (messageType != null)
                {
                    try
                    {
                        ICommonMessage messageObj = null;
                        if (!string.IsNullOrEmpty(message.Body))
                        {
                            // Проверка валидация по XSD-схеме полученного xml.
                            if (Context.EnableXSDValidation)
                            {
                                var pathToXSD = Path.Combine(HttpRuntime.AppDomainAppPath,
                                                             $"{Context.XSDSchemasPath}{message.MessageTypeID}.xsd");
                                if (File.Exists(pathToXSD))
                                {
                                    XMLTools.CheckXMLFromStringtoXSD(message.Body, pathToXSD);
                                }
                                else
                                {
                                    LogService.LogWarn(
                                        $"BusListenerService: При получении сообщения включена проверка валидности сообщения XSD-схеме, но XSD-схема для сообщения типа {message.MessageTypeID} не найдена!{Environment.NewLine} Путь для ожидаемой XSD-схемы - {pathToXSD}");
                                }
                            }

                            // Десериализуем сообщение для его сохранения.
                            messageObj =
                                SerializationTools.DeserialiseDataContract(messageType, message.Body) as ICommonMessage;
                        }

                        if (messageObj != null)
                        {
                            // Сохранение сообщения в SyncLogItem.
                            messageObj.Save(message.SenderName, message.Body, true);
                        }
                        else
                        {
                            LogService.LogWarn(
                                $"BusListenerService: Получено пустое сообщение типа {message.MessageTypeID}. Сообщение не будет сохранено в БД!");
                        }
                    }
                    catch (XmlSchemaValidationException ex)
                    {
                        LogService.LogError(
                            $"{MessageErrorHeader} Не пройдена валидация XSD-схемы для сообщения типа {message.MessageTypeID}",
                            ex);
                        throw;
                    }
                    catch (Exception ex)
                    {
                        LogService.LogError($"{MessageErrorHeader}", ex);
                        throw;
                    }
                }
                else
                {
                    var errorMessage =
                        $"{MessageErrorHeader} Не найден XML-класс типа сообщения с названием {xmlClassName}";
                    LogService.LogError(errorMessage);
                    throw new InvalidOperationException(errorMessage);
                }
            }
            else
            {
                var errorMessage =
                    $"{MessageErrorHeader} Неизвестный тип сообщения - {message.MessageTypeID}. Проверьте настройки секции {Context.CustomSBListenerConfigSectionName} в конфигурационном файле.";
                LogService.LogError(errorMessage);
                throw new UnknowMessageTypeException(errorMessage);
            }
        }
Example #16
0
        private void InitializePage()
        {
            btnSave.Attributes["onclick"] = "return submitValidation();";
            btnSave.Text   = Language.GetString(btnSave.Text);
            btnCancel.Text = Language.GetString(btnCancel.Text);

            drpNumber.DataSource     = Facade.PrivateNumber.GetUserPrivateNumbersForReceive(UserGuid);
            drpNumber.DataTextField  = "Number";
            drpNumber.DataValueField = "Guid";
            drpNumber.DataBind();

            foreach (SmsFilterSenderNumber senderNumber in Enum.GetValues(typeof(SmsFilterSenderNumber)))
            {
                drpTypeConditionSender.Items.Add(new ListItem(Language.GetString(senderNumber.ToString()), ((int)senderNumber).ToString()));
            }
            drpTypeConditionSender.Items.Insert(0, new ListItem(string.Empty, string.Empty));

            foreach (SmsFilterConditions condition in Enum.GetValues(typeof(SmsFilterConditions)))
            {
                drpConditions.Items.Add(new ListItem(Language.GetString(condition.ToString()), ((int)condition).ToString()));
            }

            foreach (SmsFilterOperations operation in Enum.GetValues(typeof(SmsFilterOperations)))
            {
                drpOperations.Items.Add(new ListItem(Language.GetString(operation.ToString()), ((int)operation).ToString()));
            }
            drpOperations.Items.Insert(0, new ListItem(string.Empty, string.Empty));

            drpSenderNumber.DataSource     = Facade.PrivateNumber.GetUserPrivateNumbersForSend(UserGuid);
            drpSenderNumber.DataTextField  = "Number";
            drpSenderNumber.DataValueField = "Guid";
            drpSenderNumber.DataBind();
            drpSenderNumber.Items.Insert(0, new ListItem(Language.GetString("SenderNumber"), string.Empty));

            DataTable dtUserFormats = Facade.SmsFormat.GetUserSmsFormats(UserGuid);

            drpAccpetFormat.DataSource     = dtUserFormats;
            drpAccpetFormat.DataTextField  = "FormatName";
            drpAccpetFormat.DataValueField = "FormatGuid";
            drpAccpetFormat.DataBind();
            drpAccpetFormat.Items.Insert(0, new ListItem(Language.GetString("UseFormatIfMatching"), string.Empty));

            drpRejectFormat.DataSource     = dtUserFormats;
            drpRejectFormat.DataTextField  = "FormatName";
            drpRejectFormat.DataValueField = "FormatGuid";
            drpRejectFormat.DataBind();
            drpRejectFormat.Items.Insert(0, new ListItem(Language.GetString("UseFormatIncompatibility"), string.Empty));

            int resultCount = 0;

            drpTrafficRelay.DataSource     = Facade.TrafficRelay.GetPagedTrafficRelays(UserGuid, "CreateDate", 0, 0, ref resultCount);
            drpTrafficRelay.DataTextField  = "Url";
            drpTrafficRelay.DataValueField = "Guid";
            drpTrafficRelay.DataBind();

            dtpStartDate.Date = DateManager.GetSolarDate(DateTime.Now);
            dtpStartDate.Time = DateTime.Now.TimeOfDay.ToString();

            dtpEndDate.Date = DateManager.GetSolarDate(DateTime.Now);
            dtpEndDate.Time = DateTime.Now.TimeOfDay.ToString();

            if (ActionType == "edit")
            {
                Common.SmsParser           smsParser = Facade.SmsParser.LoadSmsParser(SmsParserGuid);
                ParserFormulaSerialization parserFormulaSerialization = new ParserFormulaSerialization();

                drpNumber.SelectedValue = smsParser.PrivateNumberGuid.ToString();
                txtTitle.Text           = smsParser.Title;
                dtpStartDate.Date       = DateManager.GetSolarDate(smsParser.FromDateTime);
                dtpStartDate.Time       = smsParser.FromDateTime.TimeOfDay.ToString();
                dtpEndDate.Date         = DateManager.GetSolarDate(smsParser.ToDateTime);
                dtpEndDate.Time         = smsParser.ToDateTime.TimeOfDay.ToString();
                hdnScopeGuid.Value      = smsParser.Scope.ToString();
                drpTypeConditionSender.SelectedValue = smsParser.TypeConditionSender.ToString();
                txtConditionSender.Text = smsParser.ConditionSender;

                DataTable dataTableParserFormulas = Facade.ParserFormula.GetParserFormulas(SmsParserGuid);
                if (dataTableParserFormulas.Rows.Count > 0)
                {
                    DataRow row = dataTableParserFormulas.Rows[0];
                    drpConditions.SelectedValue = row["Condition"].ToString();
                    txtCondition.Text           = row["Key"].ToString();

                    string reactionExtension = row["ReactionExtention"].ToString();
                    parserFormulaSerialization  = (ParserFormulaSerialization)SerializationTools.DeserializeXml(reactionExtension, typeof(ParserFormulaSerialization));
                    drpOperations.SelectedValue = parserFormulaSerialization.Condition.ToString();
                    switch (parserFormulaSerialization.Condition)
                    {
                    case (int)SmsFilterOperations.AddToGroup:
                    case (int)SmsFilterOperations.RemoveFromGroup:
                        hdnOperationGroupGuid.Value   = parserFormulaSerialization.ReferenceGuid.ToString();
                        drpSenderNumber.SelectedValue = parserFormulaSerialization.Sender.ToString();
                        txtSmsBody.Text = parserFormulaSerialization.Text;
                        txtUrl.Text     = parserFormulaSerialization.VasURL;
                        break;

                    case (int)SmsFilterOperations.SendSmsToGroup:
                        txtSmsBody.Text = parserFormulaSerialization.Text;
                        drpSenderNumber.SelectedValue = parserFormulaSerialization.Sender.ToString();
                        hdnGroupGuid.Value            = parserFormulaSerialization.ReferenceGuid.ToString();
                        break;

                    case (int)SmsFilterOperations.SendSmsToSender:
                        txtSmsBody.Text = parserFormulaSerialization.Text;
                        drpSenderNumber.SelectedValue = parserFormulaSerialization.Sender.ToString();
                        break;

                    case (int)SmsFilterOperations.TransferToUrl:
                        drpTrafficRelay.SelectedValue = parserFormulaSerialization.ReferenceGuid.ToString();
                        break;

                    case (int)SmsFilterOperations.TransferToMobile:
                        txtOpration.Text = parserFormulaSerialization.Text;
                        drpSenderNumber.SelectedValue = parserFormulaSerialization.Sender.ToString();
                        break;

                    case (int)SmsFilterOperations.SendSmsFromFormat:
                        drpRejectFormat.SelectedValue = parserFormulaSerialization.RejectFormatGuid.ToString();
                        drpAccpetFormat.SelectedValue = parserFormulaSerialization.AcceptFormatGuid.ToString();
                        drpSenderNumber.SelectedValue = parserFormulaSerialization.Sender.ToString();
                        break;

                    case (int)SmsFilterOperations.ForwardSmsToGroup:
                        drpSenderNumber.SelectedValue = parserFormulaSerialization.Sender.ToString();
                        hdnOperationGroupGuid.Value   = parserFormulaSerialization.ReferenceGuid.ToString();
                        break;

                    default:
                        txtOpration.Text = parserFormulaSerialization.Text;
                        break;
                    }
                }

                ClientSideScript = "setOption();setCondition('edit');";
            }
        }
Example #17
0
 /// <summary>
 /// Serializable constructor for deserialization
 /// </summary>
 /// <param name="info"></param>
 /// <param name="context"></param>
 public QuestionModel(SerializationInfo info, StreamingContext context)
 {
     Image        = SerializationTools.ByteArreyToBitmapImage(info.GetValue("Image", typeof(byte[])) as byte[]);
     QuestionText = info.GetString("QuestionText");
     Options      = (OptionsModel)info.GetValue("Options", typeof(OptionsModel));
 }
Example #18
0
        /// <summary>
        ///     Обработать сообщение.
        /// </summary>
        /// <param name="logItem">Сообщение из журнала синхронизации.</param>
        public void HandleDataChangeMessage <TMessage, TItem>(SyncLogItem logItem)
            where TMessage : IDataChangeMessageResponse <TItem>
            where TItem : IChangedItem
        {
            if (!string.IsNullOrEmpty(logItem.DataSet))
            {
                var doc = new XmlDocument();
                doc.LoadXml(logItem.DataSet);

                var xmlClassName = Settings.GetMessageClassTypeName(logItem.Description);
                if (!string.IsNullOrEmpty(xmlClassName))
                {
                    // Получаем тип по названию класса из конфиг файла.
                    var messageType = Type.GetType(xmlClassName);
                    if (messageType != null)
                    {
                        TMessage response;
                        try
                        {
                            response =
                                SerializationTools.DeserialiseDataContract <TMessage>(logItem.DataSet);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(
                                      $"Ошибка десерилизации объекта SyncLogItem.Pk = {logItem.__PrimaryKey}, тип ToMsrFromTUResponse.", ex);
                        }

                        if (response?.Items == null)
                        {
                            LogService.LogWarnFormat(
                                "В сообщениии SyncLogItem.Pk = {0}, отсутствуют объекты для обработки.",
                                logItem.__PrimaryKey);
                            return;
                        }

                        var arrToUpdate   = new List <DataObject>();
                        var arrConformity = new Dictionary <string, List <DataObject> >
                        {
                            { sObjectType, new List <DataObject>() },
                            { sSource, new List <DataObject>() },
                            { sConformity, new List <DataObject>() }
                        };

                        Source source = null;
                        try
                        {
                            source = _syncDS.Query <Source>(Source.Views.SourceE)
                                     .FirstOrDefault(x => x.name == logItem.DataSource);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(
                                      $"Произошла ошибка при вычитке источника из БД Source.Name = '{logItem.DataSource}'.", ex);
                        }

                        if (source == null)
                        {
                            source = new Source {
                                name = logItem.DataSource
                            };
                            arrConformity[sSource].Add(source);
                        }

                        foreach (var item in response.Items)
                        {
                            var obj = GetXMLDataObjInChangedItem(item);
                            //Получаем настройки для обработки типа сообщения.
                            GetSyncSettings(obj, out var destType, out var mapper);
                            ProcessObject(obj, item.State, destType, mapper,
                                          item.СhangedAttributes?.Select(x => x.Name).ToList(), source, ref arrToUpdate,
                                          ref arrConformity);
                        }

                        var listSync = new List <DataObject>();
                        listSync.AddRange(arrConformity[sObjectType]);
                        listSync.AddRange(arrConformity[sSource]);
                        var objectsDef  = arrToUpdate.ToArray();
                        var objectsSync = listSync.ToArray();

                        try
                        {
                            _defDS.UpdateObjectsOrdered(ref objectsDef);

                            _syncDS.UpdateObjects(ref objectsSync);
                            objectsSync = arrConformity[sConformity].ToArray();
                            _syncDS.UpdateObjects(ref objectsSync);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception($"Произошла ошибка при сохранении объектов в БД. {ex.InnerException?.Message ?? ex.Message}");
                        }
                    }
                    else
                    {
                        var errorMessage = $" Не найден XML-класс типа сообщения с названием {xmlClassName}";
                        throw new InvalidOperationException(errorMessage);
                    }
                }
                else
                {
                    var errorMessage =
                        $"Незаполнен тип xml-класса, для сообщения {logItem.Description}. Проверьте настройки секции messageHandlers в конфигурационном файле.";
                    throw new Exception(errorMessage);
                }
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Common.SmsParser smsParser = new Common.SmsParser();

                #region Create Table Of Options
                string keywords = hdnKeywords.Value;
                Business.ParserFormulaSerialization parserFormulaSerialization = new Business.ParserFormulaSerialization();

                DataTable dtSmsParserOptions = new DataTable();
                DataRow   row;
                dtSmsParserOptions.Columns.Add("Guid", typeof(Guid));
                dtSmsParserOptions.Columns.Add("IsCorrect", typeof(bool));
                dtSmsParserOptions.Columns.Add("Title", typeof(string));
                dtSmsParserOptions.Columns.Add("Key", typeof(string));
                dtSmsParserOptions.Columns.Add("ReactionExtention", typeof(string));

                int countOptions = Helper.GetInt(Helper.ImportData(keywords, "resultCount"));
                for (int counterOptions = 0; counterOptions < countOptions; counterOptions++)
                {
                    row = dtSmsParserOptions.NewRow();

                    row["Guid"]      = Guid.NewGuid();
                    row["IsCorrect"] = Helper.ImportBoolData(keywords, ("CorrectKey" + counterOptions).ToString());
                    row["Title"]     = Helper.ImportData(keywords, ("Title" + counterOptions).ToString());
                    row["Key"]       = Helper.ImportData(keywords, ("Key" + counterOptions).ToString());

                    parserFormulaSerialization.ReferenceGuid = Helper.GetGuid(Helper.ImportData(keywords, ("ReferenceGuid" + counterOptions).ToString()));
                    row["ReactionExtention"] = SerializationTools.SerializeToXml(parserFormulaSerialization, parserFormulaSerialization.GetType());
                    dtSmsParserOptions.Rows.Add(row);
                }

                if (dtSmsParserOptions.Rows.Count == 0)
                {
                    throw new Exception(Language.GetString("SelcectCompetitionOptions"));
                }
                #endregion

                smsParser.PrivateNumberGuid = Helper.GetGuid(drpSenderNumber.SelectedValue);
                smsParser.Title             = txtTitle.Text;
                smsParser.Type         = (int)Arad.SMS.Gateway.Business.SmsParserType.Competition;
                smsParser.CreateDate   = DateTime.Now;
                smsParser.FromDateTime = DateManager.GetChristianDateTimeForDB(dtpStartDate.FullDateTime);
                smsParser.ToDateTime   = DateManager.GetChristianDateTimeForDB(dtpEndDate.FullDateTime);
                var dateTime    = dtpStartDate.FullDateTime;
                var dateTimeEnd = dtpEndDate.FullDateTime;
                if (Session["Language"].ToString() == "fa")
                {
                    smsParser.FromDateTime = DateManager.GetChristianDateTimeForDB(dateTime);
                    smsParser.ToDateTime   = DateManager.GetChristianDateTimeForDB(dateTimeEnd);
                }
                else
                {
                    smsParser.FromDateTime = DateTime.Parse(dateTime);
                    smsParser.ToDateTime   = DateTime.Parse(dateTimeEnd);
                }
                smsParser.Scope    = Helper.GetGuid(drpScope.SelectedValue);
                smsParser.UserGuid = UserGuid;
                smsParser.ReplyPrivateNumberGuid     = Helper.GetGuid(drpReplyPrivateNumber.SelectedValue);
                smsParser.ReplySmsText               = txtReplySmsText.Text;
                smsParser.DuplicatePrivateNumberGuid = Helper.GetGuid(drpDuplicatePrivateNumber.SelectedValue);
                smsParser.DuplicateUserSmsText       = txtDuplicateUserSmsText.Text;

                if (smsParser.HasError)
                {
                    throw new Exception(smsParser.ErrorMessage);
                }

                switch (ActionType)
                {
                case "insert":
                    if (!Facade.SmsParser.InsertCompetition(smsParser, dtSmsParserOptions))
                    {
                        throw new Exception(Language.GetString("ErrorRecord"));
                    }

                    break;

                case "edit":
                    smsParser.SmsParserGuid = SmsParserGuid;
                    if (!Facade.SmsParser.UpdateCompetition(smsParser, dtSmsParserOptions))
                    {
                        throw new Exception(Language.GetString("ErrorRecord"));
                    }
                    break;
                }

                Response.Redirect(string.Format("/PageLoader.aspx?c={0}", Helper.Encrypt((int)Arad.SMS.Gateway.Business.UserControls.UI_SmsParsers_Competitions_Competition, Session)));
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message, string.Empty, "danger");
            }
        }
Example #20
0
        /// <summary>
        /// Returns an HTML Table listing all the objects in the Cache, and when requested their bytesize in memory.
        /// </summary>
        public static string GetCacheReport(bool boolGetBytes)
        {
            if (System.Web.HttpContext.Current == null)
            {
                throw new Exception("Cache not available outside of web contest");
            }

            StringBuilder sb            = new StringBuilder();
            int           intCount      = 1;
            long          intTotalBytes = 0;

            sb.Append("<table border=1 cellspacing=2 cellpadding=1>");
            sb.Append("<tr><td  colspan=3>Cache Report</td></tr>");
            sb.Append("<tr>");
            sb.Append("<td>");
            sb.Append("Count");
            sb.Append("</td>");
            sb.Append("<td>");
            sb.Append("Key");
            sb.Append("</td>");
            if (boolGetBytes)
            {
                sb.Append("<td>");
                sb.Append("ByteSize");
                sb.Append("</td>");
            }
            sb.Append("</tr>");
            System.Web.Caching.Cache GlobalCache = System.Web.HttpContext.Current.Cache;
            foreach (System.Collections.DictionaryEntry o in GlobalCache)
            {
                long intByteSize = 0;
                if (boolGetBytes)
                {
                    intByteSize    = SerializationTools.GetObjectByteSize(o.Value);
                    intTotalBytes += intByteSize;
                }
                sb.Append("<tr>");
                sb.Append("<td>");
                sb.Append(intCount);
                sb.Append("</td>");
                sb.Append("<td>");
                sb.Append(o.Key.ToString());
                sb.Append("</td>");
                if (boolGetBytes)
                {
                    sb.Append("<td>");
                    sb.Append(SerializationTools.FormatSize(intByteSize));
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
                intCount++;
            }
            if (boolGetBytes)
            {
                sb.Append("<tr>");
                sb.Append("<td colspan=3 align=right>");
                sb.Append("Total Bytes: ");
                sb.Append(SerializationTools.FormatSize(intTotalBytes));
                sb.Append("</td>");
                sb.Append("</tr>");
            }
            sb.Append("</table>");

            return(sb.ToString());
        }
Example #21
0
 /// <summary>
 /// Instructions what to serialize.
 /// BitmapImage is skiped becouse of its inability to serialization.
 /// </summary>
 /// <param name="info"></param>
 /// <param name="context"></param>
 public void GetObjectData(SerializationInfo info, StreamingContext context)
 {
     info.AddValue("Image", SerializationTools.BitmapImageToByteArrey(Image));
     info.AddValue("QuestionText", QuestionText);
     info.AddValue("Options", Options);
 }
Example #22
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Common.SmsParser           smsParser     = new Common.SmsParser();
                Common.ParserFormula       parserFormula = new Common.ParserFormula();
                ParserFormulaSerialization parserFormulaSerialization = new ParserFormulaSerialization();

                smsParser.SmsParserGuid     = SmsParserGuid;
                smsParser.PrivateNumberGuid = Helper.GetGuid(drpNumber.SelectedValue);
                smsParser.Title             = txtTitle.Text;
                smsParser.Type                = (int)SmsParserType.Filter;
                smsParser.CreateDate          = DateTime.Now;
                smsParser.FromDateTime        = DateManager.GetChristianDateTimeForDB(dtpStartDate.FullDateTime);
                smsParser.ToDateTime          = DateManager.GetChristianDateTimeForDB(dtpEndDate.FullDateTime);
                smsParser.Scope               = Helper.GetGuid(hdnScopeGuid.Value.Trim('\''));
                smsParser.UserGuid            = UserGuid;
                smsParser.ConditionSender     = Helper.GetLocalMobileNumber(txtConditionSender.Text);
                smsParser.TypeConditionSender = Helper.GetInt(drpTypeConditionSender.SelectedValue);
                parserFormula.Condition       = Helper.GetInt(drpConditions.SelectedValue);
                switch (parserFormula.Condition)
                {
                case (int)SmsFilterConditions.EqualWithPhoneBookField:
                    parserFormula.Key = string.Format("{0}/{1}", hdnConditionGroupGuid.Value, hdnConditionField.Value);
                    break;

                default:
                    parserFormula.Key = txtCondition.Text;
                    break;
                }

                switch (parserFormula.Condition)
                {
                case (int)SmsFilterConditions.NationalCode:
                    break;

                default:
                    if (Facade.SmsParser.IsDuplicateSmsParserKey(SmsParserGuid, smsParser.PrivateNumberGuid, parserFormula.Key))
                    {
                        throw new Exception(Language.GetString("DuplicateKeyword"));
                    }
                    break;
                }

                parserFormulaSerialization.Condition = Helper.GetInt(drpOperations.SelectedValue);
                switch (parserFormulaSerialization.Condition)
                {
                case (int)SmsFilterOperations.AddToGroup:
                case (int)SmsFilterOperations.RemoveFromGroup:
                    parserFormulaSerialization.ReferenceGuid = Helper.GetGuid(hdnOperationGroupGuid.Value.Trim('\''));
                    parserFormulaSerialization.Text          = txtSmsBody.Text;
                    parserFormulaSerialization.Sender        = Helper.GetGuid(drpSenderNumber.SelectedValue);
                    parserFormulaSerialization.VasURL        = txtUrl.Text;
                    break;

                case (int)SmsFilterOperations.SendSmsToGroup:
                    parserFormulaSerialization.Sender        = Helper.GetGuid(drpSenderNumber.SelectedValue);
                    parserFormulaSerialization.Text          = txtSmsBody.Text;
                    parserFormulaSerialization.ReferenceGuid = Helper.GetGuid(hdnGroupGuid.Value.Trim('\''));
                    break;

                case (int)SmsFilterOperations.ForwardSmsToGroup:
                    parserFormulaSerialization.Sender        = Helper.GetGuid(drpSenderNumber.SelectedValue);
                    parserFormulaSerialization.ReferenceGuid = Helper.GetGuid(hdnOperationGroupGuid.Value.Trim('\''));
                    break;

                case (int)SmsFilterOperations.SendSmsToSender:
                    parserFormulaSerialization.Sender        = Helper.GetGuid(drpSenderNumber.SelectedValue);
                    parserFormulaSerialization.Text          = txtSmsBody.Text;
                    parserFormulaSerialization.ReferenceGuid = Guid.Empty;
                    break;

                case (int)SmsFilterOperations.TransferToUrl:
                    parserFormulaSerialization.ReferenceGuid = Helper.GetGuid(drpTrafficRelay.SelectedValue);
                    break;

                case (int)SmsFilterOperations.TransferToMobile:
                    parserFormulaSerialization.Sender = Helper.GetGuid(drpSenderNumber.SelectedValue);
                    parserFormulaSerialization.Text   = txtOpration.Text;
                    break;

                case (int)SmsFilterOperations.SendSmsFromFormat:
                    parserFormulaSerialization.Sender           = Helper.GetGuid(drpSenderNumber.SelectedValue);
                    parserFormulaSerialization.AcceptFormatGuid = Helper.GetGuid(drpAccpetFormat.SelectedValue);
                    parserFormulaSerialization.RejectFormatGuid = Helper.GetGuid(drpRejectFormat.SelectedValue);
                    break;

                default:
                    parserFormulaSerialization.Text = txtOpration.Text;
                    break;
                }
                parserFormula.ReactionExtention = SerializationTools.SerializeToXml(parserFormulaSerialization, parserFormulaSerialization.GetType());

                if (smsParser.HasError)
                {
                    throw new Exception(smsParser.ErrorMessage);
                }

                switch (ActionType)
                {
                case "insert":
                    if (!Facade.SmsParser.InsertFilter(smsParser, parserFormula))
                    {
                        throw new Exception(Language.GetString("ErrorRecord"));
                    }

                    break;

                case "edit":
                    if (!Facade.SmsParser.UpdateFilter(smsParser, parserFormula))
                    {
                        throw new Exception(Language.GetString("ErrorRecord"));
                    }
                    break;
                }

                Response.Redirect(string.Format("/PageLoader.aspx?c={0}", Helper.Encrypt((int)UserControls.UI_SmsParsers_Filters_SmsFilter, Session)));
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message, string.Empty, "danger");
            }
        }