Example #1
0
        public static TransferCheckpoint SaveAndReloadCheckpoint(TransferCheckpoint checkpoint)
        {
            //return checkpoint;
            Test.Info("Save and reload checkpoint");
#if BINARY_SERIALIZATION
            IFormatter formatter = new BinaryFormatter();
#else
            var formatter = new DataContractSerializer(typeof(TransferCheckpoint));
#endif
            TransferCheckpoint reloadedCheckpoint;

            string tempFileName = Guid.NewGuid().ToString();

            using (var stream = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                formatter.Serialize(stream, checkpoint);
            }

            using (var stream = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                reloadedCheckpoint = formatter.Deserialize(stream) as TransferCheckpoint;
            }

            File.Delete(tempFileName);

            return(reloadedCheckpoint);
        }
Example #2
0
 public static void TestDataContractSerializing()
 {
     var dcs = new DataContractSerializer<Test<string>>();
     using (var fileStream = File.Create(Path.Combine("save", "test.dc")))
     {
         dcs.Serialize(fileStream, Program.GetTest());
     }
     using (var fileStream = File.OpenRead(Path.Combine("save", "test.dc")))
     {
         var test = dcs.Deserialize(fileStream);
         Debug.Assert(test.SequenceEqual(Program.GetTest()));
     }
 }
Example #3
0
        private object ReadObject(DataContractSerializer serializer)
        {
            long serializerLength = this.ReadLong();

            this.serializerStream.SetLength(serializerLength);

            if (this.stream.Read(this.serializerBuffer, 0, (int)serializerLength) < (int)serializerLength)
            {
#if !NO_FILEFORMAT_EX
                throw new FileFormatException(Resources.RestartableLogCorrupted);
#else
                throw new InvalidOperationException(Resources.RestartableLogCorrupted);
#endif
            }

            this.serializerStream.Position = 0;
            return(serializer.Deserialize(this.serializerStream));
        }
Example #4
0
        /// <summary>
        /// Processes the received message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="serializedMessage">The serialized message.</param>
        protected override void ProcessReceivedMessage(byte[] serializedMessage)
        {
            var message = DataContractSerializer.Deserialize <MessageBus>(MessageBusParser.GetMessageFromBytes(serializedMessage));

            Logger.Debug("OnMessageBusReceived");
            var split = message.Header.BodyType.Split(',');

            if (split.Length < 2)
            {
                Logger.Error(string.Format("El mensaje no tiene el bodytype correcto {0}", serializedMessage));
                return;
            }

            var bodyType     = split[0];
            var assemblyName = split[1];

            var type = TypeFinder.GetType(bodyType, assemblyName);
            var body = MessageBuilder.Instance.CreateInstance(DataContractSerializer, type, message.Body,
                                                              Encoding.GetEncoding(message.Header.EncodingCodePage));

            InvokeOnMessage((TMessage)body, serializedMessage, message.Header);

            InvokeReceivedMessage(message.Header.BodyType, serializedMessage.Length, message.Header.CreatedAt);
        }
Example #5
0
        public static RoaminSMPP.SMPPCommunicator GetConnection(Guid providerId, string senderName)
        {
            RoaminSMPP.SMPPCommunicator connection = null;
            string key = GenerateKey(providerId, senderName);

            lock (_syncLock)
            {
                if (_connections.ContainsKey(key))
                {
                    connection = _connections[key].Connection;
                }
                else
                {
                    Providers provider = Context.GetProvider(providerId).FirstOrDefault();
                    if (provider != null)
                    {
                        ProviderConfiguration conf       = _providerConfigurationSerializer.Deserialize <ProviderConfiguration>(provider.Configuration);
                        TonNpiPair            senderPlan = conf.SourceNumberings.GetNpiTonPair(senderName);
                        if (senderPlan == null)
                        {
                            throw new InvalidOperationException(Resources.Error_NumberTypeNotSupported);
                        }
                        KeyedTimer <string> connectionTimer = new KeyedTimer <string>(conf.EnqureLinkInterval, key);
                        connectionTimer.Elapsed += new ElapsedEventHandler(connectionTimer_Elapsed);
                        connection = new RoaminSMPP.SMPPCommunicator()
                        {
                            BindType                    = conf.BindingTypes.FirstOrDefault(),
                            AddressRange                = conf.AddressRange,
                            Version                     = conf.SupportedSMPPVersions.Max(),
                            Host                        = conf.Host,
                            Port                        = (short)conf.Port,
                            EnquireLinkInterval         = (int)conf.EnqureLinkInterval.TotalSeconds,
                            TonType                     = senderPlan.Ton,
                            NpiType                     = senderPlan.Npi,
                            SystemType                  = conf.SystemType,
                            SystemId                    = conf.SystemId,
                            Password                    = conf.Password,
                            SleepTimeAfterSocketFailure = (int)Settings.Default.SleepTimeAfterSocketFailure.TotalSeconds,
                            Username                    = conf.UserName,
                            ProviderId                  = provider.Id
                        };
                        connection.OnSubmitMultiResp += new RoaminSMPP.SMPPCommunicator.SubmitMultiRespEventHandler(connection_OnSubmitMultiResp);
                        connection.OnSubmitSmResp    += new RoaminSMPP.SMPPCommunicator.SubmitSmRespEventHandler(connection_OnSubmitSmResp);
                        connection.OnQuerySmResp     += new RoaminSMPP.SMPPCommunicator.QuerySmRespEventHandler(connection_OnQuerySmResp);
                        connection.OnDeliverSm       += new RoaminSMPP.SMPPCommunicator.DeliverSmEventHandler(connection_OnDeliverSm);
                        connection.OnError           += new RoaminSMPP.SMPPCommunicator.ErrorEventHandler(connection_OnError);
                        _connections.Add(key, new ConnectionItem
                        {
                            Connection             = connection,
                            ConnectionRefreshTimer = connectionTimer,
                            ReconnectAttempts      = 0
                        });
                        try
                        {
                            connection.Bind();
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.ToString());
                        }
                        finally
                        {
                            connectionTimer.Enabled = true;
                        }
                    }
                }
            }
            return(connection);
        }
Example #6
0
        public List <SMSSeriesId> SendSms(Guid userId, string senderName, List <string> addresses, string message,
                                          bool transliterate           = false,
                                          bool alertOnDelivery         = false,
                                          bool registredDelivery       = true,
                                          bool replaceIfPresent        = true,
                                          string callbackNumber        = null,
                                          string callbackNumberDisplay = null,
                                          Pdu.PriorityType priority    = Pdu.PriorityType.Level2,
                                          Pdu.PrivacyType privacy      = Pdu.PrivacyType.Nonrestricted,
                                          string clientId             = null,
                                          string distributionId       = null,
                                          string smsId                = null,
                                          DateTime?deliveryTime       = null,
                                          TimeSpan?validalityPeriod   = null,
                                          ushort smsSignal            = 0,
                                          ushort sourcePort           = 0,
                                          ushort userMessageReference = 0,
                                          Dictionary <string, string> customParameters = null)
        {
            if (validalityPeriod == null)
            {
                validalityPeriod = TimeSpan.FromMinutes(10);
            }

            List <SMSSeriesId> result = new List <SMSSeriesId>();
            //Здесь будет получение провайдера для данного пользователя, исходя из имени отправителя, требуемого качества канала, жизни поставщика, статуса пользователя, клиента
            bool useRussian = true;
            //---------------------------------------------------------
            SenderNames sName = Context.GetSenderNames(userId).Where(sn => sn.Name == senderName).OrderByDescending(sn => sn.Providers.ChannelBrandwidth).FirstOrDefault();

            if (sName != null)
            {
                //---------------------------------------------------------
                //--Конфигурация провайдера, должна покрыть некоторые опции----
                ProviderConfiguration configuration = _providerConfigurationSerializer.Deserialize <ProviderConfiguration>(sName.Providers.Configuration);
                Pdu.SmppVersionType   smppVersion   = configuration.SupportedSMPPVersions.First();
                Pdu.PayloadTypeType   payloadType   = configuration.PayloadType;

                TonNpiPair outNumbering = sName.Name.IsDigital()?
                                          configuration.SourceNumberings.Where(sn => sn.Ton == Pdu.TonType.International).First():
                                          outNumbering = configuration.SourceNumberings.Where(sn => sn.Ton == Pdu.TonType.Alphanumeric).First();
                TonNpiPair destinationNumbering = configuration.DestinationNumberings
                                                  .Where(dn => dn.Ton == Pdu.TonType.International).First();
                //-------------------------------------------------------------
                string[] messages;
                if (!message.ContainsNonASCII() || transliterate)
                {
                    if (transliterate)
                    {
                        message = message.Unidecode();
                    }
                    if (configuration.Support7Bit)
                    {
                        if (message.Length > SMS_7BIT_LENGTH)
                        {
                            messages = message.SplitByLength(SMS_7BIT_CONCAT_LENGTH);
                        }
                        else
                        {
                            messages = message.SplitByLength(SMS_7BIT_LENGTH);
                        }
                    }
                    else
                    {
                        if (message.Length > SMS_8BIT_LENGTH)
                        {
                            messages = message.SplitByLength(SMS_8BIT_CONCAT_LENGTH);
                        }
                        else
                        {
                            messages = message.SplitByLength(SMS_8BIT_LENGTH);
                        }
                    }
                    useRussian = false;
                }
                else
                {
                    if (message.Length > SMS_UNICODE_LENGTH)
                    {
                        messages = message.SplitByLength(SMS_UNICODE_CONCAT_LENGTH);
                    }
                    else
                    {
                        messages = message.SplitByLength(SMS_UNICODE_LENGTH);
                    }
                }
                bool concatenated = messages.Length > 1;
                if (concatenated)
                {
                    concatRefNum = concatRefNum.CycleInc();
                }
                for (byte i = 0; i < messages.Length; ++i)
                {
                    MessageLcd2 req;

                    if (addresses.Count > 1)
                    {
                        req = new SmppSubmitMulti();
                    }
                    else
                    {
                        req = new SmppSubmitSm();
                    }

                    byte[] bMessage;

                    if (configuration.Support7Bit && !useRussian)
                    {
                        bMessage = new GSMEncoding().GetBytes(messages[i]);
                        if (configuration.Need7BitPacking)
                        {
                            bMessage = GSMEncoding.Encode7Bit(bMessage, concatenated ? 5 : 0);
                        }
                    }
                    else if (!useRussian)
                    {
                        bMessage = Encoding.ASCII.GetBytes(messages[i]);
                    }
                    else
                    {
                        bMessage = Encoding.UTF8.GetBytes(messages[i].Endian2UTF());
                    }
                    if (useRussian)
                    {
                        req.DataCoding = RoaminSMPP.Packet.Pdu.DataCodingType.Unicode;
                    }
                    else
                    {
                        req.DataCoding = Pdu.DataCodingType.SMSCDefault;
                    }
                    req.AlertOnMsgDelivery = Convert.ToByte(alertOnDelivery);
                    if (useRussian)
                    {
                        req.LanguageIndicator = Pdu.LanguageType.UCS2_16Bit;
                    }
                    else if (configuration.Support7Bit)
                    {
                        req.LanguageIndicator = Pdu.LanguageType.GSM7BitDefaultAlphabet;
                    }
                    else
                    {
                        req.LanguageIndicator = Pdu.LanguageType.Unspecified;
                    }
                    req.PayloadType        = payloadType;
                    req.PriorityFlag       = priority;
                    req.PrivacyIndicator   = privacy;
                    req.ProtocolId         = smppVersion;
                    req.RegisteredDelivery = registredDelivery?
                                             Pdu.RegisteredDeliveryType.OnSuccessOrFailure:
                                             Pdu.RegisteredDeliveryType.None;
                    req.ReplaceIfPresentFlag = replaceIfPresent;
                    req.ScheduleDeliveryTime = deliveryTime == null ? null : deliveryTime.Value.GetDateString(configuration.TimeShift);
                    req.SmsSignal            = smsSignal;
                    req.SourceAddress        = sName.Name;
                    req.SourceAddressTon     = outNumbering.Ton;
                    req.SourceAddressNpi     = outNumbering.Npi;
                    req.SourceAddressSubunit = RoaminSMPP.Packet.Pdu.AddressSubunitType.MobileEquipment;
                    req.SourcePort           = sourcePort;
                    req.UserMessageReference = userMessageReference;
                    req.ValidityPeriod       = validalityPeriod == null ? null : validalityPeriod.Value.GetDateString();
                    if (!string.IsNullOrEmpty(callbackNumber))
                    {
                        req.CallbackNum = callbackNumber;
                        if (string.IsNullOrEmpty(callbackNumberDisplay))
                        {
                            req.CallbackNumAtag = callbackNumberDisplay;
                        }
                        req.CallbackNumPresInd = 1;
                    }
                    if (concatenated)
                    {
                        //Добавляем EI UDH для сочленяемых сообщений
                        byte[] concatBytes = new byte[6];
                        concatBytes[0] = 5;
                        concatBytes[1] = 0;
                        concatBytes[2] = 3;
                        concatBytes[3] = concatRefNum;
                        concatBytes[4] = (byte)messages.Length;
                        concatBytes[5] = (byte)(i + 1);
                        byte[] resulting = new byte[bMessage.Length + concatBytes.Length];
                        concatBytes.CopyTo(resulting, 0);
                        bMessage.CopyTo(resulting, concatBytes.Length);
                        bMessage = resulting;
                    }
                    req.ShortMessage = bMessage;
                    if (req is SmppSubmitSm)
                    {
                        SmppSubmitSm simple = req as SmppSubmitSm;
                        simple.DestinationAddress    = addresses[0];
                        simple.DestinationAddressTon = destinationNumbering.Ton;
                        simple.DestinationAddressNpi = destinationNumbering.Npi;
                    }
                    if (req is SmppSubmitMulti)
                    {
                        SmppSubmitMulti complex = req as SmppSubmitMulti;
                        complex.DestinationAddresses = addresses.Select
                                                       (
                            address => new DestinationAddress(destinationNumbering.Ton, destinationNumbering.Npi, address)
                                                       ).ToArray();
                    }
                    if (concatenated && !string.IsNullOrEmpty(callbackNumber))
                    {
                        req.EsmClass = 195;
                    }
                    else if (concatenated)
                    {
                        req.EsmClass = 67;
                    }
                    else if (!string.IsNullOrEmpty(callbackNumber))
                    {
                        req.EsmClass = 131;
                    }
                    else
                    {
                        req.EsmClass = 3;
                    }
                    SMSSeriesId id = EnqueueSMS(userId, sName.Id, sName.ProviderId, req, clientId, distributionId, smsId, customParameters);
                    if (!id.Equals(SMSSeriesId.Empty))
                    {
                        result.Add(id);
                    }
                }
            }
            return(result);
        }
Example #7
0
 public static object Deserialize(this DataContractSerializer serializer, string data)
 {
     return(serializer.Deserialize(Encoding.UTF8.GetBytes(data)));
 }
Example #8
0
        private void CompareDeserializes <T>(T obj, int runs)
        {
            var objType = obj.GetType();

            //warm-up

            byte[] protobufData, binaryData, dataContractData, soapData, netData;

#if NETFULL || NETCOREAPP3_1
            var jilSerializedText = jilserializer.SerializeToString(obj);
            using (MemoryStream mem = new MemoryStream())
            {
                binaryserializer.Serialize(obj, mem);
                binaryData = mem.ToArray();
            }

            using (MemoryStream mem = new MemoryStream())
            {
                datacontractserializer.Serialize(obj, mem);
                dataContractData = mem.ToArray();
            }
#endif

#if NETFULL
            using (MemoryStream mem = new MemoryStream())
            {
                soapserializer.Serialize(obj, mem);
                soapData = mem.ToArray();
            }
#endif

            var netserializer = SerializerFactory.Get("NET");
            using (MemoryStream mem = new MemoryStream())
            {
                netserializer.Serialize(obj, mem);
                netData = mem.ToArray();
            }

            var jsonnetSerializedText  = jsonnetserializer.SerializeToString(obj);
            var textjsonSerializedText = textjsonserializer.SerializeToString(obj);
            var xmlSerializedText      = xmlserializer.SerializeToString(obj);
            using (MemoryStream mem = new MemoryStream())
            {
                protobufserializer.Serialize(obj, mem);
                protobufData = mem.ToArray();
            }

            var keys = serializer.Keys.ToList();

#if NETFULL || NETCOREAPP3_1
            serializer["Jil"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["Jil"].Score = Helper.AverageRuntime(() =>
                {
                    jilserializer.DeserializeFromString(jilSerializedText, objType);
                }, runs);
            };
            serializer["Binary"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["Binary"].Score = Helper.AverageRuntime(() =>
                {
                    using (MemoryStream mem = new MemoryStream(binaryData))
                    {
                        binaryserializer.Deserialize(mem, objType);
                    }
                }, runs);
            };

            serializer["DataContract"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["DataContract"].Score = Helper.AverageRuntime(() =>
                {
                    using (MemoryStream mem = new MemoryStream(dataContractData))
                    {
                        datacontractserializer.Deserialize(mem, objType);
                    }
                }, runs);
            };
#endif

#if NETFULL
            serializer["Soap"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["Soap"].Score = Helper.AverageRuntime(() =>
                {
                    using (MemoryStream mem = new MemoryStream(soapData))
                    {
                        soapserializer.Deserialize(mem, objType);
                    }
                }, runs);
            };
#endif

            serializer["NET"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["NET"].Score = Helper.AverageRuntime(() =>
                {
                    using (MemoryStream mem = new MemoryStream(netData))
                    {
                        netserializer.Deserialize(mem, objType);
                    }
                }, runs);
            };

            serializer["Json"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["Json"].Score = Helper.AverageRuntime(() =>
                {
                    jsonnetserializer.DeserializeFromString(jsonnetSerializedText, objType);
                }, runs);
            };

            serializer["TextJson"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["TextJson"].Score = Helper.AverageRuntime(() =>
                {
                    textjsonserializer.DeserializeFromString(textjsonSerializedText, objType);
                }, runs);
            };

            serializer["Xml"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["Xml"].Score = Helper.AverageRuntime(() =>
                {
                    xmlserializer.DeserializeFromString(xmlSerializedText, objType);
                }, runs);
            };

            serializer["Protobuf"].Act = () =>
            {
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                serializer["Protobuf"].Score = Helper.AverageRuntime(() =>
                {
                    using (MemoryStream mem = new MemoryStream(protobufData))
                    {
                        protobufserializer.Deserialize(mem, objType);
                    }
                }, runs);
            };

            keys.ForEach(k =>
            {
                serializer[k].Act();
            });
        }