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); }
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); }