Example #1
0
        static void Main(string[] args)
        {
            InMemoryCacheService inMemoryCacheService = new InMemoryCacheService(new MemoryCache(new MemoryCacheOptions()));

            inMemoryCacheService.Put <string>("a1", "hello");
            var datain = inMemoryCacheService.Get <string>("a1");


            var hash = ZNxt.Net.Core.Helpers.CommonUtility.Sha256Hash("21AFF254AE134F3F843D176100715C6F");

            var rv = new RazorTemplateEngine();

            Func <string, string> getAppSetting =
                (string key) =>
            {
                //var response = AppSettingService.Instance.GetAppSettingData(key);
                //if (string.IsNullOrEmpty(response))
                //{
                //    response = ConfigurationManager.AppSettings[key];
                //}
                //return response;
                return(key);
            };

            Dictionary <string, dynamic> dataModel = new Dictionary <string, dynamic>();

            dataModel["Name"]          = "Khanin";
            dataModel["getAppSetting"] = getAppSetting;
            var data = rv.Compile($"Hello -- {DateTime.Now.ToString()} @Raw((1+1).ToString()) @Model[\"Name\"] @Model[\"getAppSetting\"](\"Hello 1111\")", "aa", dataModel);

            Console.WriteLine("Hello World!" + data);
            Console.Read();
        }
Example #2
0
        private void RunAsync(Action callback)
        {
            var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "BackgroundDifferenceLoader", _id);
            var eventAggregator     = new TelegramEventAggregator();
            var cacheService        = new InMemoryCacheService(eventAggregator);
            var updatesService      = new UpdatesService(cacheService, eventAggregator);
            var transportService    = new TransportService();
            var connectionService   = new ConnectionService(deviceInfoService);
            var publicConfigService = new MockupPublicConfigService();

            var manualResetEvent = new ManualResetEvent(false);
            var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);

            mtProtoService.Initialized += (o, e) =>
            {
                var lastTime = TLUtils.OpenObjectFromMTProtoFile <TLInt>(_differenceTimeSyncRoot, Constants.DifferenceTimeFileName);
                if (lastTime != null)
                {
                    var now = TLUtils.DateToUniversalTimeTLInt(mtProtoService.ClientTicksDelta, DateTime.Now);

                    if (lastTime.Value + Constants.DifferenceMinInterval > now.Value)
                    {
                        manualResetEvent.Set();
                        return;
                    }
                }

                var clientState = TLUtils.OpenObjectFromMTProtoFile <TLState>(_stateRoot, Constants.StateFileName);
                _results = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLDifference> >(_differenceFileSyncRoot, Constants.DifferenceFileName) ?? new TLVector <TLDifference>();
                var state = GetState(clientState, _results);

                if (state != null)
                {
                    GetDifferenceAsync(mtProtoService, state, () => manualResetEvent.Set());
                }
                else
                {
                    manualResetEvent.Set();
                }
            };
            mtProtoService.InitializationFailed += (o, e) =>
            {
                manualResetEvent.Set();
            };
            mtProtoService.Initialize();

#if DEBUG
            manualResetEvent.WaitOne(15000);
#else
            manualResetEvent.WaitOne(15000);
#endif

            callback.SafeInvoke();
        }
        public override void Setup()
        {
            container = new UnityContainer();
            mockDataCache=new Mock<IDataCache>();
            var inmemorycache = new InMemoryCacheService("xyz");
            var mockRepository =new Mock<ICacheRepository>();
            container.RegisterInstance(mockRepository.Object);
            var testAppfabricCache= new TestAppFabricClass();

            mockRepository.Setup(a => a.GetNamedCache(It.IsAny<string>())).Returns<string>(regionName => new AppFabricCacheService("Test", regionName, testAppfabricCache));
            mockDataCache.Setup(a => a.Get<string>(It.IsAny<string>())).Returns<string>(inmemorycache.Get<string>);
        }
 public WooCommerceClient(string url, ICacheService cache)
 {
     Version                = DefaultVersion;
     appUrl                 = url;
     httpClient             = new HttpClient();
     httpClient.BaseAddress = new Uri(appUrl);
     Currency               = "€";
     if (cache == null)
     {
         cache = new InMemoryCacheService();
     }
     cacheService = cache;
 }
 public ICacheService GetNamedCache(string cacheName)
 {
     InMemoryCacheService cacheObj;
     lock (caches)
     {
         if (!caches.TryGetValue(cacheName, out cacheObj))
         {
             cacheObj = new InMemoryCacheService(cacheName);
             caches.Add(cacheName, cacheObj);
         }
     }
     return cacheObj;
 }
        public override void Setup()
        {
            container     = new UnityContainer();
            mockDataCache = new Mock <IDataCache>();
            var inmemorycache  = new InMemoryCacheService("xyz");
            var mockRepository = new Mock <ICacheRepository>();

            container.RegisterInstance(mockRepository.Object);
            var testAppfabricCache = new TestAppFabricClass();

            mockRepository.Setup(a => a.GetNamedCache(It.IsAny <string>())).Returns <string>(regionName => new AppFabricCacheService("Test", regionName, testAppfabricCache));
            mockDataCache.Setup(a => a.Get <string>(It.IsAny <string>())).Returns <string>(inmemorycache.Get <string>);
        }
Example #7
0
        public void Initialize(BackgroundTaskDeferral deferral)
        {
            if (_connection == null & _protoService == null)
            {
                VoIPCallTask.Log("Mediator initialized", "Creating proto service");

                var deviceInfoService = new DeviceInfoService();
                var eventAggregator   = new TelegramEventAggregator();
                var cacheService      = new InMemoryCacheService(eventAggregator);
                var updatesService    = new UpdatesService(cacheService, eventAggregator);
                var transportService  = new TransportService();
                var connectionService = new ConnectionService(deviceInfoService);
                var statsService      = new StatsService();
                var protoService      = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, statsService);

                protoService.Initialized += (s, args) =>
                {
                    VoIPCallTask.Log("ProtoService initialized", "waiting for updates");

                    updatesService.LoadStateAndUpdate(() =>
                    {
                        VoIPCallTask.Log("Difference processed", "Difference processed");

                        if (_phoneCall == null)
                        {
                            VoIPCallTask.Log("Difference processed", "No call found in difference");

                            if (_systemCall != null)
                            {
                                _systemCall.NotifyCallEnded();
                            }
                        }
                    });
                };

                eventAggregator.Subscribe(this);
                protoService.Initialize();
                _protoService     = protoService;
                _transportService = transportService;
            }
            else
            {
                VoIPCallTask.Log("Mediator initialized", "_connection is null: " + (_connection == null));
            }

            _deferral    = deferral;
            _initialized = true;

            ProcessUpdates();
        }
        public InMemoryCacheServiceTests()
        {
            _memoryCacheMock = new Mock <IMemoryCache>();
            var hostEnvironmentMock = new Mock <IHostEnvironment>();

            hostEnvironmentMock.SetupGet(e => e.ApplicationName).Returns(_applicationName);
            hostEnvironmentMock.SetupGet(e => e.EnvironmentName).Returns(_environmentName);

            _colidCacheOptions = new ColidCacheOptions();
            _colidCacheOptions.AbsoluteExpirationRelativeToNow = 1337;

            var optionMonitorMock = Mock.Of <IOptionsMonitor <ColidCacheOptions> >(_ => _.CurrentValue == _colidCacheOptions);
            var loggerMock        = new Mock <ILogger <InMemoryCacheService> >();

            _cacheService = new InMemoryCacheService(_memoryCacheMock.Object, hostEnvironmentMock.Object, optionMonitorMock, loggerMock.Object);
        }
        public override void Setup()
        {
            container = new UnityContainer();
            mockDataCache = new Mock<IDataCache>();
            var inmemorycache = new InMemoryCacheService("xyz");
            var mockRepository = new Mock<ICacheRepository>();
            container.RegisterInstance(mockRepository.Object);

            var testAppfabricCacheCollection = new ConcurrentDictionary<string, TestAppFabricClass>();

            mockRepository.Setup(a => a.GetNamedCache(It.IsAny<string>())).Returns<string>(regionName =>
                      new AppFabricCacheService("Test", regionName, testAppfabricCacheCollection.GetOrAdd(regionName, (a) => new TestAppFabricClass())));
            mockRepository.Setup(a => a.ClearNamedCache(It.IsAny<string>())).Returns<string>(regionName =>
                                                                                             {
                                                                                                 testAppfabricCacheCollection[regionName].ClearCache();
                                                                                                 return true;
                                                                                             });

            mockDataCache.Setup(a => a.Get<string>(It.IsAny<string>())).Returns<string>(inmemorycache.Get<string>);
        }
        public override void Setup()
        {
            container     = new UnityContainer();
            mockDataCache = new Mock <IDataCache>();
            var inmemorycache  = new InMemoryCacheService("xyz");
            var mockRepository = new Mock <ICacheRepository>();

            container.RegisterInstance(mockRepository.Object);

            var testAppfabricCacheCollection = new ConcurrentDictionary <string, TestAppFabricClass>();

            mockRepository.Setup(a => a.GetNamedCache(It.IsAny <string>())).Returns <string>(regionName =>
                                                                                             new AppFabricCacheService("Test", regionName, testAppfabricCacheCollection.GetOrAdd(regionName, (a) => new TestAppFabricClass())));
            mockRepository.Setup(a => a.ClearNamedCache(It.IsAny <string>())).Returns <string>(regionName =>
            {
                testAppfabricCacheCollection[regionName].ClearCache();
                return(true);
            });

            mockDataCache.Setup(a => a.Get <string>(It.IsAny <string>())).Returns <string>(inmemorycache.Get <string>);
        }
Example #11
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            var data = Toast.GetData(taskInstance);

            if (data != null)
            {
                if (data.ContainsKey("QuickMessage"))
                {
                    var deviceInfoService = new DeviceInfoService();
                    var eventAggregator   = new TelegramEventAggregator();
                    var cacheService      = new InMemoryCacheService(eventAggregator);
                    var updatesService    = new UpdatesService(cacheService, eventAggregator);
                    var transportService  = new TransportService();
                    var connectionService = new ConnectionService(deviceInfoService);
                    var statsService      = new StatsService();
                    var manualResetEvent  = new ManualResetEvent(false);
                    var protoService      = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, statsService);

                    protoService.Initialized += (s, args) =>
                    {
                        var text         = data["QuickMessage"];
                        var messageText  = text.Replace("\r\n", "\n").Replace('\v', '\n').Replace('\r', '\n');
                        var entitiesBase = Utils.GetEntities(ref messageText);

                        var replyToMsgId = 0;
                        var inputPeer    = default(TLInputPeerBase);
                        if (data.ContainsKey("from_id"))
                        {
                            inputPeer = new TLInputPeerUser {
                                UserId = int.Parse(data["from_id"]), AccessHash = long.Parse(data["access_hash"])
                            };
                        }
                        else if (data.ContainsKey("channel_id"))
                        {
                            inputPeer = new TLInputPeerChannel {
                                ChannelId = int.Parse(data["channel_id"]), AccessHash = long.Parse(data["access_hash"])
                            };
                            replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : 0;
                        }
                        else if (data.ContainsKey("chat_id"))
                        {
                            inputPeer = new TLInputPeerChat {
                                ChatId = int.Parse(data["chat_id"])
                            };
                            replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : 0;
                        }

                        TLVector <TLMessageEntityBase> entities = null;
                        if (entitiesBase != null)
                        {
                            entities = new TLVector <TLMessageEntityBase>(entitiesBase);
                        }

                        var obj = new TLMessagesSendMessage {
                            Peer = inputPeer, ReplyToMsgId = replyToMsgId, Message = messageText, Entities = entities, IsBackground = true, RandomId = TLLong.Random()
                        };

                        protoService.SendInformativeMessageInternal <TLUpdatesBase>("messages.sendMessage", obj, result =>
                        {
                            manualResetEvent.Set();
                        },
                                                                                    faultCallback: fault =>
                        {
                            // TODO: alert user?
                            manualResetEvent.Set();
                        },
                                                                                    fastCallback: () =>
                        {
                            manualResetEvent.Set();
                        });

                        //var date = TLUtils.DateToUniversalTimeTLInt(protoService.ClientTicksDelta, DateTime.Now);
                        //var message = TLUtils.GetMessage(SettingsHelper.UserId, inputPeer, TLMessageState.Sending, true, true, date, text, new TLMessageMediaEmpty(), TLLong.Random(), replyToMsgId);
                        //var history = cacheService.GetHistory(inputPeer, 1);

                        //cacheService.SyncSendingMessage(message, null, async (m) =>
                        //{
                        //    await protoService.SendMessageAsync(message, () =>
                        //    {
                        //        // TODO: fast callback
                        //    });
                        //    manualResetEvent.Set();
                        //});
                    };
                    protoService.InitializationFailed += (s, args) =>
                    {
                        manualResetEvent.Set();
                    };

                    //cacheService.Init();
                    protoService.Initialize();

                    manualResetEvent.WaitOne(15000);
                }
            }

            deferral.Complete();
        }
        private void SendReply(TLInputPeerBase inputPeer, TLString message, TLInt msgId)
        {
            if (msgId == null)
            {
                return;
            }
            if (TLString.IsNullOrEmpty(message))
            {
                return;
            }

            var actionInfo = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLActionInfo> >(_actionInfoSyncRoot, Constants.ActionQueueFileName) ?? new TLVector <TLActionInfo>();

            var count = actionInfo.Count;

            Log("send count=" + count);

            var peerChannel = inputPeer as TLInputPeerChannel;
            var readHistory = peerChannel != null
                ? (TLObject) new TLReadChannelHistory {
                Channel = new TLInputChannel {
                    ChannelId = peerChannel.ChatId, AccessHash = peerChannel.AccessHash
                }, MaxId = msgId
            }
                : new TLReadHistory {
                Peer = inputPeer, MaxId = msgId
            };

            var readHistoryActionInfo = new TLActionInfo();

            readHistoryActionInfo.SendBefore = new TLInt(0);
            readHistoryActionInfo.Action     = readHistory;

            actionInfo.Add(readHistoryActionInfo);

            var sendMessage = new TLSendMessage();

            sendMessage.Flags    = new TLInt(0);
            sendMessage.Peer     = inputPeer;
            sendMessage.Message  = message;
            sendMessage.RandomId = TLLong.Random();

            var sendMessageActionInfo = new TLActionInfo();

            sendMessageActionInfo.SendBefore = new TLInt(0);
            sendMessageActionInfo.Action     = sendMessage;

            actionInfo.Add(sendMessageActionInfo);

            TLUtils.SaveObjectToMTProtoFile(new object(), Constants.ActionQueueFileName, actionInfo);

            if (actionInfo.Count > 0)
            {
                var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "InteractiveNotificationsBackgroundTask", _id);
                var eventAggregator     = new TelegramEventAggregator();
                var cacheService        = new InMemoryCacheService(eventAggregator);
                var updatesService      = new UpdatesService(cacheService, eventAggregator);
                var transportService    = new TransportService();
                var connectionService   = new ConnectionService(deviceInfoService);
                var publicConfigService = new MockupPublicConfigService();

                var manualResetEvent = new ManualResetEvent(false);
                Log("before init");
                var requestsToRemove = new List <TLObject>();
                var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);
                mtProtoService.Initialized += async(o, e) =>
                {
                    Log("init completed");

                    var actionsString = new StringBuilder();
                    foreach (var info in actionInfo)
                    {
                        actionsString.AppendLine(info.ToString());
                    }
                    Log(actionsString.ToString());

                    var       sendMessageActions = new List <TLObject>();
                    const int maxActionCount     = 10;
                    var       currentCount       = 0;
                    foreach (var ai in actionInfo)
                    {
                        if (TLUtils.IsValidAction(ai.Action) && currentCount < maxActionCount)
                        {
                            currentCount++;
                            sendMessageActions.Add(ai.Action);
                        }
                    }

                    if (sendMessageActions.Count > 0)
                    {
                        mtProtoService.SendActionsAsync(sendMessageActions,
                                                        (request, result) => // will be invoked for each sent action
                        {
                            requestsToRemove.Add(request);
                            var sendingMessages = mtProtoService.SendingMessages;
                            Log("send completed count=" + sendingMessages, () =>
                            {
                                if (sendingMessages == 0)
                                {
                                    _clearActionInfoFile = true;

                                    manualResetEvent.Set();
                                }
                            });
                        },
                                                        error =>
                        {
                            Log(string.Format("send error={0}\n{1}", error, error.Exception),
                                async() =>
                            {
                                await Task.Delay(TimeSpan.FromSeconds(1.0));
                                manualResetEvent.Set();
                            });
                        });
                    }
                    else
                    {
                        manualResetEvent.Set();
                    }
                };
                mtProtoService.InitializationFailed += (o, e) =>
                {
                    Log("init failed");

                    manualResetEvent.Set();
                };
                mtProtoService.Initialize();
#if DEBUG
                manualResetEvent.WaitOne();
#else
                manualResetEvent.WaitOne(15000);
#endif
                if (_clearActionInfoFile)
                {
                    Log("clear");
                    lock (_actionInfoSyncRoot)
                    {
                        var actions = actionInfo;

                        foreach (var o in requestsToRemove)
                        {
                            MTProtoService.RemoveActionInfoCommon(actions, o);
                        }

                        TLUtils.SaveObjectToMTProtoFile(_actionInfoSyncRoot, Constants.ActionQueueFileName, actions);
                    }
                }
            }
        }
        private void UpdateNotifySettings(TLInputPeerBase inputPeer, TLInt muteUntil)
        {
            var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "InteractiveNotificationsBackgroundTask", _id);
            var eventAggregator     = new TelegramEventAggregator();
            var cacheService        = new InMemoryCacheService(eventAggregator);
            var updatesService      = new UpdatesService(cacheService, eventAggregator);
            var transportService    = new TransportService();
            var connectionService   = new ConnectionService(deviceInfoService);
            var publicConfigService = new MockupPublicConfigService();

            var manualResetEvent = new ManualResetEvent(false);

            Log("before init");
            var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);

            mtProtoService.Initialized += (o, e) =>
            {
                Log("init completed");

                mtProtoService.GetNotifySettingsAsync(new TLInputNotifyPeer {
                    Peer = inputPeer
                },
                                                      result =>
                {
                    Log("getNotifySettings completed", () =>
                    {
                        var peerNotifySettings = result as TLPeerNotifySettings;
                        if (peerNotifySettings != null)
                        {
                            if (muteUntil.Value < int.MaxValue)
                            {
                                muteUntil = TLUtils.DateToUniversalTimeTLInt(mtProtoService.ClientTicksDelta, DateTime.Now.AddSeconds(muteUntil.Value));
                            }

                            var inputPeerNotifySettings = new TLInputPeerNotifySettings78
                            {
                                Flags     = new TLInt(0),
                                MuteUntil = muteUntil,
                                Sound     = peerNotifySettings.Sound,
                            };

                            mtProtoService.UpdateNotifySettingsAsync(new TLInputNotifyPeer {
                                Peer = inputPeer
                            },
                                                                     inputPeerNotifySettings,
                                                                     result2 =>
                            {
                                Log("setNotifySettings completed", () =>
                                {
                                    manualResetEvent.Set();
                                });
                            },
                                                                     error2 =>
                            {
                                Log(string.Format("setNotifySettings error={0}\n{1}", error2, error2.Exception),
                                    async() =>
                                {
                                    await Task.Delay(TimeSpan.FromSeconds(1.0));
                                    manualResetEvent.Set();
                                });
                            });
                        }
                        else
                        {
                            manualResetEvent.Set();
                        }
                    });
                },
                                                      error =>
                {
                    Log(string.Format("getNotifySettings error={0}\n{1}", error, error.Exception),
                        async() =>
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1.0));
                        manualResetEvent.Set();
                    });
                });
            };
            mtProtoService.InitializationFailed += (o, e) =>
            {
                Log("init failed");

                manualResetEvent.Set();
            };
            mtProtoService.Initialize();
#if DEBUG
            manualResetEvent.WaitOne();
#else
            manualResetEvent.WaitOne(15000);
#endif
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Telegram.Logs.Log.WriteSync = true;

            taskInstance.Canceled += OnTaskCanceled;
            var deferral = taskInstance.GetDeferral();

            var stopwatch = Stopwatch.StartNew();
            var task      = taskInstance.Task;
            var name      = task != null ? task.Name : null;

            Log("start " + name);
            if (!_appOpenMutex.WaitOne(0))
            {
                Log("cancel", deferral.Complete);

                return;
            }
            _appOpenMutex.ReleaseMutex();
            Log("release mutex");
            var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey);

            if (!isAuthorized)
            {
                Log("cancel isAuthorized=false", deferral.Complete);

                return;
            }
            Log("isAuthorized=true");

            var deviceInfoService = new DeviceInfoService(GetInitConnection(), true, "MessageSchedulerBackgroundTask", _id);
            var eventAggregator   = new TelegramEventAggregator();
            var cacheService      = new InMemoryCacheService(eventAggregator);
            var updatesService    = new UpdatesService(cacheService, eventAggregator);
            var transportService  = new TransportService();
            var connectionService = new ConnectionService(deviceInfoService);

            var manualResetEvent = new ManualResetEvent(false);

            Log("before init");
            var requestsToRemove = new List <TLObject>();
            var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService);

            mtProtoService.Initialized += async(o, e) =>
            {
                Log("init completed");

                var actionInfos = mtProtoService.GetActionInfoFromFile();
                var count       = actionInfos != null ? actionInfos.Count : 0;
                Log("send count=" + count);

                if (actionInfos != null &&
                    actionInfos.Count > 0)
                {
                    var actionsString = new StringBuilder();
                    foreach (var info in actionInfos)
                    {
                        actionsString.AppendLine(info.ToString());
                    }
                    Log(actionsString.ToString());

                    var       sendMessageActions = new List <TLObject>();
                    const int maxActionCount     = 10;
                    var       currentCount       = 0;
                    foreach (var actionInfo in actionInfos)
                    {
                        if (TLUtils.IsValidAction(actionInfo.Action) && currentCount < maxActionCount)
                        {
                            currentCount++;
                            sendMessageActions.Add(actionInfo.Action);
                        }
                    }

                    if (sendMessageActions.Count > 0)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(3.0));

                        mtProtoService.SendActionsAsync(sendMessageActions,
                                                        (request, result) => // will be invoked for each sent action
                        {
                            requestsToRemove.Add(request);
                            var sendingMessages = mtProtoService.SendingMessages;
                            Log("send completed count=" + sendingMessages, () =>
                            {
                                if (sendingMessages == 0)
                                {
                                    _clearActionInfoFile = true;

                                    manualResetEvent.Set();
                                }
                            });
                        },
                                                        error =>
                        {
                            Log(string.Format("send error={0}\n{1}", error, error.Exception),
                                async() =>
                            {
                                await Task.Delay(TimeSpan.FromSeconds(1.0));
                                manualResetEvent.Set();
                            });
                        });
                    }
                    else
                    {
                        manualResetEvent.Set();
                    }
                }
                else
                {
                    manualResetEvent.Set();
                }
            };
            mtProtoService.InitializationFailed += (o, e) =>
            {
                Log("init failed");

                manualResetEvent.Set();
            };
            mtProtoService.Initialize();
#if DEBUG
            manualResetEvent.WaitOne();
#else
            manualResetEvent.WaitOne(15000);
#endif
            if (_clearActionInfoFile)
            {
                Log("clear");
                mtProtoService.RemoveActionInfoFromFile(requestsToRemove);
            }

            Log("stop " + stopwatch.Elapsed, deferral.Complete);
        }
Example #15
0
        static void Main(string[] args)
        {
            var manualResetEvent = new ManualResetEvent(false);

            ////var transport = new HttpTransport(string.Empty);
            ////transport.SetAddress("http://95.142.192.65/api", 80, () => manualResetEvent.Set());
            //var transport = new TcpTransport();
            //transport.SetAddress("95.142.192.65", 80, () => manualResetEvent.Set());
            //manualResetEvent.WaitOne();


            //IAuthorizationHelper authHelper = new AuthorizationHelper(Transport);
            //authHelper.InitAsync(res =>{});
            manualResetEvent.Reset();

            var cacheService   = new InMemoryCacheService(null);
            var updatesService = new UpdatesService(cacheService, null);

            MTProtoService.Salt = new TLLong(0);
            var service = new MTProtoService(updatesService, cacheService, new TransportService());

            service.Initialized += (o, e) => manualResetEvent.Set();

            manualResetEvent.WaitOne();
            var phoneNumber = new TLString("79996610000");

            service.SendCodeAsync(phoneNumber, TLSmsType.Code,
                                  sentCode =>
            {
                var phoneCodeHash = sentCode.PhoneCodeHash;
                service.SignInAsync(phoneNumber, phoneCodeHash, new TLString("11111"),
                                    authorization =>
                {
                    //TLUtils.WriteLine("Auth: " + TLUtils.MessageIdString(authorization.Expires));
                    service.GetDialogsAsync(new TLInt(0), new TLInt(0), new TLInt(int.MaxValue),
                                            dialogs =>
                    {
                    },
                                            er2 =>
                    {
                    });

                    //service.GetContactsAsync(
                    //    new TLString(""),
                    //    contactsResult =>
                    //    {
                    //        var contacts = contactsResult as TLContacts;
                    //        if (contacts != null)
                    //        {
                    //            var contact = contacts.Contacts[0];

                    //            service.GetHistoryAsync(new TLInputPeerContact{UserId = contact.UserId}, new TLInt(0), new TLInt(0), new TLInt(int.MaxValue),
                    //                messagesResult =>
                    //                {

                    //                },
                    //                er2 => { });
                    //        }
                    //    },
                    //    er =>
                    //    {
                    //    });
                });
            });

            Console.ReadKey();
        }