Exemplo n.º 1
0
 public static ISchemaGenerator Create(DataClient client)
 {
     switch (client)
     {
         case DataClient.SqlClient:
             return new Sql2005Schema();
         case DataClient.MySqlClient:
             return new MySqlSchema();
         case DataClient.SQLite:
             return new SQLiteSchema();
         default:
             throw new ArgumentOutOfRangeException(client.ToString(), "There is no generator for this client");
     }
 }
 public PSAutoCompleteResourceV3Provider(DataClient client)
     : base(typeof(PSAutoCompleteResource), "PSAutoCompleteResourceV3Provider", "V2PSAutoCompleteResourceProvider")
 {
     _client = client;
 }
Exemplo n.º 3
0
 internal DataServer(DataClient client)
 {
     this.Client = client;
 }
Exemplo n.º 4
0
        /// <summary>
        /// Seeds Transient Data
        /// </summary>
        /// <param name="dataClientConfig"></param>
        /// <returns></returns>
        private async Task TransientDataDemoAsync(Config.DataClientConfig dataClientConfig)
        {
            try
            {
                using (DataClient dataClient = new DataClient(dataClientConfig))
                {
                    if (dataClient.TransientData != null)
                    {
                        TransientData transientData = dataClient.TransientData;


                        ///////// DB seeding with demo content /////////

                        var dCL = await transientData.ObtainDisplayConcurrentListAsync();

                        var zCL = await transientData.ObtainZoneConcurrentListAsync();

                        // Look for any item (DisplaySession & ZoneSession) in DisplayConcurrentList and ZoneConcurrentList Table
                        try
                        {
                            if ((dCL?.DisplaySessions?.Any() ?? false) && (zCL?.ZoneSessions?.Any() ?? false))
                            {
                                string log1 = JsonConvert.SerializeObject(dCL);
                                string log2 = JsonConvert.SerializeObject(zCL);
                                Context.Logger.LogLine("[TransientData Summary]");
                                Context.Logger.LogLine($"Found {dCL.DisplaySessions.Count} DisplaySession(s) in DisplayConcurrentList");
                                Context.Logger.LogLine(log1);
                                Context.Logger.LogLine($"Found {zCL.ZoneSessions.Count} ZoneSession(s) in ZoneConcurrentList");
                                Context.Logger.LogLine(log2);
                                return;  // DB has been seeded already
                            }
                        }
                        catch (Exception ex)
                        {
                            Context.Logger.LogLine("TransientData scan ERROR: " + ex.Message);
                        }

                        // DB save operation
                        Context.Logger.LogLine("[Adding contents for TransientData]");

                        try
                        {
                            if ((!dCL?.DisplaySessions?.Any()) ?? false)
                            {
                                dCL.DisplaySessions.Add(new DisplaySession(1)
                                {
                                    IsUserExists = true,
                                    BufferedShowNotificationID      = 1,
                                    CurrentShowNotificationExpireAt = DateTime.UtcNow.AddSeconds(10),
                                    DisplayTouchedNotificationID    = 1,
                                    DisplayTouchedAt           = DateTime.UtcNow.AddSeconds(5),
                                    LocationDeviceID           = 1,
                                    LocationDeviceRegisteredAt = DateTime.UtcNow
                                });
                                dCL.LastFlushedAt = DateTime.UtcNow;

                                // SAVING the DisplaySession into physical DisplayConcurrentList DB Table
                                Context.Logger.LogLine("Saving a DisplaySession to DisplayConcurrentList Table");
                                await transientData.SaveDisplayConcurrentListAsync();
                            }

                            if (!zCL.ZoneSessions.Any())
                            {
                                var zoneSession = new ZoneSession(1);
                                zoneSession.UserConcurrentList.UserSessions.Add(new UserSession(1)
                                {
                                    EnteredIntoZoneAt = DateTime.UtcNow,
                                    LastSeenInZoneAt  = DateTime.UtcNow,
                                    ReceivedCouponIDs = new List <long> {
                                        1
                                    }
                                });
                                zoneSession.UserConcurrentList.LastFlushedAt = DateTime.UtcNow;
                                zCL.ZoneSessions.Add(zoneSession);

                                // SAVING the ZoneSession into physical ZoneConcurrentList DB Table
                                Context.Logger.LogLine("Saving a ZoneSession with an UserSession to ZoneConcurrentList Table");
                                await transientData.SaveZoneConcurrentListAsync();
                            }
                        }
                        catch (Exception ex)
                        {
                            Context.Logger.LogLine("TransientData save ERROR: " + ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Context.Logger.LogLine("TransientData ERROR: " + ex.Message);
            }
        }
Exemplo n.º 5
0
 protected override void ExecuteInternal()
 {
     DataClient.AddColumn(TableNames[0], _column);
 }
Exemplo n.º 6
0
        public static async Task <Img> CreateAsync(HttpPostedFileBase image, string codeName, string artistName, FileStorage fs, DataClient dc)
        {
            var lookupId = Guid.NewGuid().ToString().Substring(0, 8);
            var url      = await fs.UploadBlobAsync(image.InputStream, lookupId);

            var img = new Img(url, codeName, artistName, image.ContentType, image.FileName, lookupId);

            //dc.Imgs.Add(img);
            return(img);
        }
Exemplo n.º 7
0
 protected override void ExecuteInternal()
 {
     DataClient.AddIndex(IndexKeyName, TableNames[0], ColumnNames);
 }
Exemplo n.º 8
0
        public V3SourceRepository(PackageSource source, string host)
        {
            _source = source;
            _root = new Uri(source.Url);

            // TODO: Get context from current UI activity (PowerShell, Dialog, etc.)
            _userAgent = UserAgentUtil.GetUserAgent("NuGet.Client", host);

            _http = new System.Net.Http.HttpClient(
                new TracingHttpHandler(
                    NuGetTraceSources.V3SourceRepository,
                    new SetUserAgentHandler(
                        _userAgent,
                        new HttpClientHandler())));

            // Check if we should disable the browser file cache
            FileCacheBase cache = new BrowserFileCache();
            if (String.Equals(Environment.GetEnvironmentVariable("NUGET_DISABLE_IE_CACHE"), "true", StringComparison.OrdinalIgnoreCase))
            {
                cache = new NullFileCache();
            }

            cache = new NullFileCache(); // +++ Disable caching for testing

            _client = new DataClient(
                _http,
                cache);
        }
Exemplo n.º 9
0
 public BaseRepository()
 {
     dataClient = new DataClient <T>();
 }
Exemplo n.º 10
0
        public static IForm <MessageModel> BuildForm()
        {
            return(new FormBuilder <MessageModel>()
                   .Message("Welcome to ChatCode")
                   .Field(nameof(AnalysisText))
                   .Field(nameof(Email))
                   .Field(nameof(Age))
                   .Field(nameof(Gender))
                   .Field(nameof(Description))
                   .Field(nameof(Image))
                   .Field(nameof(Facebook))
                   .Field(nameof(Twitter))
                   .Field(nameof(LinkedIn))
                   .Field(nameof(IsPublish))
                   .Field(nameof(Star))
                   .OnCompletion(async(context, state) =>
            {
                var client = new DataClient();

                if (state.IsPublish == PublishEnum.Yes)
                {
                    var analysis = new CreateAnalysisModel()
                    {
                        Text = state.AnalysisText
                    };

                    var textAnalaysisKeyword = await client.RequestAnalysis(analysis);

                    var model = new CreateAboutMeModel()
                    {
                        Email = state.Email,
                        NameSurname = MessagesController.UserName,
                        Age = "23",
                        Gender = state.Gender.Value.ToString(),
                        Description = state.Description,
                        ImageUrl = "image-url",
                        Background = "#ffffff",
                        Foreground = "#000000",
                        AnalysisText = textAnalaysisKeyword
                    };

                    var response = await client.SendInformation(model);

                    if (response.IsSuccess == true)
                    {
                        await context.PostAsync("https://chatcode.blob.core.windows.net/chatcodecontainer/aboutme.html");

                        var social = new CreateSocialMediaModel()
                        {
                            Email = state.Email,
                            Facebook = state.Facebook,
                            Twitter = state.Twitter,
                            LinkedIn = state.LinkedIn
                        };
                        var socialResponse = client.AddSocialMedia(social);

                        int websiteId = Convert.ToInt32(socialResponse.Result.Message);
                        var star = new CreateStartModel()
                        {
                            WebsiteId = websiteId,
                            Rate = (int)state.Star.Value
                        };

                        await context.PostAsync("https://chatcode.blob.core.windows.net/chatcodecontainer/aboutme.html");
                    }

                    else
                    {
                        await context.PostAsync("https://chatcode.blob.core.windows.net/chatcodecontainer/aboutme.html");
                    }
                }

                else
                {
                    await context.PostAsync("You gave up");
                }
            })
                   .Build());
        }
Exemplo n.º 11
0
 public V3UIMetadataResource(DataClient client, V3RegistrationResource regResource)
     : base()
 {
     _regResource = regResource;
     _client      = client;
 }
Exemplo n.º 12
0
 protected override void ExecuteInternal()
 {
     DataClient.AddForeignKey(ForeignKeyName, TableNames[0], Column, ReferencingTable, ReferencingColumnName, OnDelete);
 }
Exemplo n.º 13
0
 internal DataCache(DataClient client)
 {
     this.Client = client;
 }
Exemplo n.º 14
0
        public void UserData_0通常データ()
        {
            var ret = DataClient.ParseDataData(TestHelper.Load(@"Images/Users/Data/default.xml"));

            Assert.AreEqual(3u, ret.ImageCount);

            Assert.AreEqual(3, ret.Images.Count);

            Assert.AreEqual("im3937109", ret.Images[0].Id);
            Assert.AreEqual(27849771u, ret.Images[0].UserId);
            Assert.AreEqual("カゼ", ret.Images[0].Title);
            Assert.AreEqual(string.Empty, ret.Images[0].Description);
            Assert.AreEqual(1399u, ret.Images[0].ViewCount);
            Assert.AreEqual(8u, ret.Images[0].CommentCount);
            Assert.AreEqual(79u, ret.Images[0].ClipCount);
            Assert.AreEqual("かわいい・・・ 幼い肢体の太股… あらきれい いいわぁ・・・ 淡い塗りがいいですね やわらかい(確信) ぺろりてぇ・・・ ふぅ・・・", ret.Images[0].LastCommentBody);
            Assert.AreEqual(Genre.Popular, ret.Images[0].Genre);
            Assert.AreEqual(Site.Illust, ret.Images[0].Site);
            Assert.AreEqual(1u, ret.Images[0].ImageType);
            Assert.AreEqual(0u, ret.Images[0].IllustType);
            Assert.AreEqual(1u, ret.Images[0].InspectionStatus);
            Assert.IsFalse(ret.Images[0].IsAnonymous);
            Assert.AreEqual(0u, ret.Images[0].PublicStatus);
            Assert.IsFalse(ret.Images[0].IsDeleted);
            Assert.AreEqual(0u, ret.Images[0].DeleteType);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 14, 27, 28, TimeSpan.FromHours(9)), ret.Images[0].PostedAt);

            Assert.AreEqual("im3937107", ret.Images[1].Id);
            Assert.AreEqual(27849771u, ret.Images[1].UserId);
            Assert.AreEqual("マリー", ret.Images[1].Title);
            Assert.AreEqual("5月4日カゲプロオンリーでの、まにおさんの個人イラスト本にゲスト寄稿したものの一部です。(一部と見せかけてほとんど見せている)", ret.Images[1].Description);
            Assert.AreEqual(107u, ret.Images[1].ViewCount);
            Assert.AreEqual(0u, ret.Images[1].CommentCount);
            Assert.AreEqual(1u, ret.Images[1].ClipCount);
            Assert.AreEqual(string.Empty, ret.Images[1].LastCommentBody);
            Assert.AreEqual(Genre.FanArt, ret.Images[1].Genre);
            Assert.AreEqual(Site.Illust, ret.Images[1].Site);
            Assert.AreEqual(1u, ret.Images[1].ImageType);
            Assert.AreEqual(0u, ret.Images[1].IllustType);
            Assert.AreEqual(1u, ret.Images[1].InspectionStatus);
            Assert.IsFalse(ret.Images[1].IsAnonymous);
            Assert.AreEqual(0u, ret.Images[1].PublicStatus);
            Assert.IsFalse(ret.Images[1].IsDeleted);
            Assert.AreEqual(0u, ret.Images[1].DeleteType);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 14, 25, 10, TimeSpan.FromHours(9)), ret.Images[1].PostedAt);

            Assert.AreEqual("im3937098", ret.Images[2].Id);
            Assert.AreEqual(27849771u, ret.Images[2].UserId);
            Assert.AreEqual("咲", ret.Images[2].Title);
            Assert.AreEqual("おなにーするぞ", ret.Images[2].Description);
            Assert.AreEqual(253u, ret.Images[2].ViewCount);
            Assert.AreEqual(0u, ret.Images[2].CommentCount);
            Assert.AreEqual(2u, ret.Images[2].ClipCount);
            Assert.AreEqual(string.Empty, ret.Images[2].LastCommentBody);
            Assert.AreEqual(Genre.Adult, ret.Images[2].Genre);
            Assert.AreEqual(Site.Adult, ret.Images[2].Site);
            Assert.AreEqual(1u, ret.Images[2].ImageType);
            Assert.AreEqual(1u, ret.Images[2].IllustType);
            Assert.AreEqual(1u, ret.Images[2].InspectionStatus);
            Assert.IsFalse(ret.Images[2].IsAnonymous);
            Assert.AreEqual(0u, ret.Images[2].PublicStatus);
            Assert.IsFalse(ret.Images[2].IsDeleted);
            Assert.AreEqual(0u, ret.Images[2].DeleteType);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 14, 19, 24, TimeSpan.FromHours(9)), ret.Images[2].PostedAt);

            Assert.AreEqual(8, ret.Comments.Count);

            Assert.AreEqual(18534505u, ret.Comments[0].Id);
            Assert.AreEqual("im3937109", ret.Comments[0].ImageId);
            Assert.AreEqual(0u, ret.Comments[0].ResId);
            Assert.AreEqual("ふぅ・・・", ret.Comments[0].Value);
            Assert.AreEqual(string.Empty, ret.Comments[0].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 15, 25, 53, TimeSpan.FromHours(9)), ret.Comments[0].PostedAt);
            Assert.AreEqual(-1, ret.Comments[0].Frame);
            Assert.AreEqual("3rP8+l9ny9Y/iKhs8r9vSn/+jQA", ret.Comments[0].UserHash);
            Assert.IsTrue(ret.Comments[0].IsAnonymous);

            Assert.AreEqual(18534610u, ret.Comments[1].Id);
            Assert.AreEqual("im3937109", ret.Comments[1].ImageId);
            Assert.AreEqual(0u, ret.Comments[1].ResId);
            Assert.AreEqual("ぺろりてぇ・・・", ret.Comments[1].Value);
            Assert.AreEqual(string.Empty, ret.Comments[1].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 15, 33, 18, TimeSpan.FromHours(9)), ret.Comments[1].PostedAt);
            Assert.AreEqual(-1, ret.Comments[1].Frame);
            Assert.AreEqual("RT4Uif3Ry5bDGAcRhin5orV/HHs", ret.Comments[1].UserHash);
            Assert.IsTrue(ret.Comments[1].IsAnonymous);

            Assert.AreEqual(18535030u, ret.Comments[2].Id);
            Assert.AreEqual("im3937109", ret.Comments[2].ImageId);
            Assert.AreEqual(0u, ret.Comments[2].ResId);
            Assert.AreEqual("やわらかい(確信)", ret.Comments[2].Value);
            Assert.AreEqual(string.Empty, ret.Comments[2].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 16, 27, 1, TimeSpan.FromHours(9)), ret.Comments[2].PostedAt);
            Assert.AreEqual(-1, ret.Comments[2].Frame);
            Assert.AreEqual("9qiGEltBimLXeoC3e34PbQAloDE", ret.Comments[2].UserHash);
            Assert.IsTrue(ret.Comments[2].IsAnonymous);

            Assert.AreEqual(18535065u, ret.Comments[3].Id);
            Assert.AreEqual("im3937109", ret.Comments[3].ImageId);
            Assert.AreEqual(0u, ret.Comments[3].ResId);
            Assert.AreEqual("淡い塗りがいいですねー", ret.Comments[3].Value);
            Assert.AreEqual(string.Empty, ret.Comments[3].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 16, 32, 25, TimeSpan.FromHours(9)), ret.Comments[3].PostedAt);
            Assert.AreEqual(-1, ret.Comments[3].Frame);
            Assert.AreEqual("yIPiLKswUDzzOrf9mPCNQpKvYNw", ret.Comments[3].UserHash);
            Assert.IsTrue(ret.Comments[3].IsAnonymous);

            Assert.AreEqual(18535187u, ret.Comments[4].Id);
            Assert.AreEqual("im3937109", ret.Comments[4].ImageId);
            Assert.AreEqual(0u, ret.Comments[4].ResId);
            Assert.AreEqual("いいわぁ・・・", ret.Comments[4].Value);
            Assert.AreEqual(string.Empty, ret.Comments[4].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 16, 50, 57, TimeSpan.FromHours(9)), ret.Comments[4].PostedAt);
            Assert.AreEqual(-1, ret.Comments[4].Frame);
            Assert.AreEqual("fzOgikO+edl+vnjOJHmKbO3B3MI", ret.Comments[4].UserHash);
            Assert.IsTrue(ret.Comments[4].IsAnonymous);

            Assert.AreEqual(18535527u, ret.Comments[5].Id);
            Assert.AreEqual("im3937109", ret.Comments[5].ImageId);
            Assert.AreEqual(0u, ret.Comments[5].ResId);
            Assert.AreEqual("あらきれい", ret.Comments[5].Value);
            Assert.AreEqual(string.Empty, ret.Comments[5].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 17, 31, 56, TimeSpan.FromHours(9)), ret.Comments[5].PostedAt);
            Assert.AreEqual(-1, ret.Comments[5].Frame);
            Assert.AreEqual("26751669", ret.Comments[5].UserHash);
            Assert.IsFalse(ret.Comments[5].IsAnonymous);

            Assert.AreEqual(18535595u, ret.Comments[6].Id);
            Assert.AreEqual("im3937109", ret.Comments[6].ImageId);
            Assert.AreEqual(0u, ret.Comments[6].ResId);
            Assert.AreEqual("幼い肢体の太股…", ret.Comments[6].Value);
            Assert.AreEqual(string.Empty, ret.Comments[6].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 17, 42, 19, TimeSpan.FromHours(9)), ret.Comments[6].PostedAt);
            Assert.AreEqual(-1, ret.Comments[6].Frame);
            Assert.AreEqual("iRATiyaRxT904yOlMBjjXqLsBCQ", ret.Comments[6].UserHash);
            Assert.IsTrue(ret.Comments[6].IsAnonymous);

            Assert.AreEqual(18536848u, ret.Comments[7].Id);
            Assert.AreEqual("im3937109", ret.Comments[7].ImageId);
            Assert.AreEqual(0u, ret.Comments[7].ResId);
            Assert.AreEqual("かわいい・・・", ret.Comments[7].Value);
            Assert.AreEqual(string.Empty, ret.Comments[7].Command);
            Assert.AreEqual(new DateTimeOffset(2014, 4, 19, 19, 40, 45, TimeSpan.FromHours(9)), ret.Comments[7].PostedAt);
            Assert.AreEqual(-1, ret.Comments[7].Frame);
            Assert.AreEqual("PeeZ+d6n55NtgkVX2Yc9fdmns04", ret.Comments[7].UserHash);
            Assert.IsTrue(ret.Comments[7].IsAnonymous);
        }
Exemplo n.º 15
0
 protected override void ExecuteInternal()
 {
     AfectedRows = DataClient.UpdateSql(TableNames[0], Columns, Values, Filter);
 }
Exemplo n.º 16
0
        public ReqData GetData(int millisec, byte[] input_data, string commonData_dataClientId, long responseSize, DateTime sendStart)
        {
            DateTime start = DateTime.Now;
            ReqData  rtn   = new ReqData();

            if (!string.IsNullOrEmpty(commonData_dataClientId))
            {
#if HPCPACK
                try
                {
                    if (data == null)
                    {
                        lock (syncObj)
                        {
                            if (data == null)
                            {
                                DateTime openStart = DateTime.UtcNow;
                                rtn.commonDataAccessStartTime = openStart;
                                Console.WriteLine("{0}: Start open", openStart.ToLongTimeString());
                                using (DataClient dataClient = ServiceContext.GetDataClient(commonData_dataClientId))
                                {
                                    DateTime openEnd = DateTime.UtcNow;
                                    Console.WriteLine("{0}: Open finished", openEnd.ToLongTimeString());
                                    Console.WriteLine("{0}: Open time: {1} millisec.", DateTime.UtcNow.ToLongTimeString(), openEnd.Subtract(openStart).TotalMilliseconds);

                                    DateTime readStart = DateTime.UtcNow;
                                    Console.WriteLine("{0}: Start read", openStart.ToLongTimeString());
                                    data = dataClient.ReadRawBytesAll();
                                    DateTime readEnd = DateTime.UtcNow;
                                    Console.WriteLine("{0}: Read finshed", readEnd.ToLongTimeString());
                                    Console.WriteLine("{0}: Read time: {1} millisec.", DateTime.UtcNow.ToLongTimeString(), readEnd.Subtract(readStart).TotalMilliseconds);

                                    rtn.commonDataAccessStopTime = readEnd;
                                    Console.WriteLine("{0}: Common data access time: {1} millisec.", DateTime.UtcNow.ToLongTimeString(), rtn.commonDataAccessStopTime.Subtract(rtn.commonDataAccessStartTime).TotalMilliseconds);
                                }
                            }
                        }
                    }
                    if (data != null)
                    {
                        rtn.commonDataSize = data.Length;
                    }
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("dataclient exception: {0}", e.ToString());
                }
#endif
                throw new NotSupportedException("No common data support yet.");
            }

            int userTraceCount = 0;
            int.TryParse(Environment.GetEnvironmentVariable("UserTraceCount"), out userTraceCount);
            StringBuilder usertracedata = new StringBuilder();
            // Per PM, we test each user trace with 64 chars
            for (int i = 0; i < 64; i++)
            {
                usertracedata.Append('0');
            }
            for (int i = 0; i < userTraceCount; i++)
            {
                ServiceContext.Logger.TraceInformation(usertracedata.ToString());
            }

            Thread.Sleep(millisec);

            bool throwRetryOperationError = false;
            bool.TryParse(Environment.GetEnvironmentVariable("RetryRequest"), out throwRetryOperationError);
            if (throwRetryOperationError)
            {
                throw new FaultException <RetryOperationError>(new RetryOperationError("RetryRequest"));
            }

            DateTime end = DateTime.Now;

            rtn.CCP_TASKINSTANCEID = System.Environment.GetEnvironmentVariable("CCP_TASKINSTANCEID");
            if (responseSize < 0)
            {
                throw new FaultException <ArgumentException>(new ArgumentException("responseSize should not be less than zero."));
            }
            else if (responseSize > 0)
            {
                rtn.responseData = new byte[responseSize];
                (new Random()).NextBytes(rtn.responseData);
            }
            rtn.requestStartTime = start;
            rtn.requestEndTime   = end;
            rtn.sendStart        = sendStart;
            return(rtn);
        }
Exemplo n.º 17
0
 protected override void ExecuteInternal()
 {
     DataClient.RemoveColumn(TableNames[0], ItemName);
 }
Exemplo n.º 18
0
        /// <summary>
        /// Task that uploads queue to server
        /// </summary>
        private async void UploadTask(Page sender)
        {
            try
            {
                while (ConnectionStatus)
                {
                    if (TransferQueue.Count != 0)
                    {
                        TransferQueue[0].Stream.Position = 0;
                        BinaryReader r = new BinaryReader(TransferQueue[0].Stream);
                        //Message format (datasize FILENAME/DATASIZE DATA) without spaces and  brackets

                        //Byte representation of filename
                        byte[] name = Encoding.ASCII.GetBytes(TransferQueue[0].Name + '/');

                        //Byte respresentation of image data
                        byte[] imageData;
                        using (var memoryStream = new MemoryStream())
                        {
                            TransferQueue[0].Stream.CopyTo(memoryStream);
                            imageData = memoryStream.ToArray();
                        }
                        //byte representation of package size
                        byte[] totalLen = BitConverter.GetBytes(name.Length + imageData.Length + 4);

                        byte[] package = new byte[name.Length + imageData.Length + 4];
                        System.Array.Copy(totalLen, 0, package, 0, totalLen.Length);
                        System.Array.Copy(name, 0, package, totalLen.Length, name.Length);
                        System.Array.Copy(imageData, 0, package, totalLen.Length + name.Length, imageData.Length);
                        NetworkStream s = DataClient.GetStream();
                        int           totalSentBytes = 0;
                        int           packetSize     = 4096;
                        while (totalSentBytes != package.Length)
                        {
                            int leftToSend = package.Length - totalSentBytes;
                            if (leftToSend > packetSize)
                            {
                                s.Write(package, totalSentBytes, packetSize);
                                totalSentBytes += packetSize;
                            }
                            else
                            {
                                s.Write(package, totalSentBytes, leftToSend);
                                totalSentBytes += leftToSend;
                            }
                        }
                        string n = TransferQueue[0].Stream.Name;
                        TransferQueue.RemoveAt(0);
                        File.Delete(n);
                    }
                    await Task.Delay(20);
                }
            }
            catch
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await sender.DisplayAlert("Error", "Server is not responding", "OK");
                    ConnectionStatus = false;
                });
            }
        }
Exemplo n.º 19
0
        // TODO: refresh the file when it gets old
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            ServiceIndexResourceV3 index = null;

            var url = source.PackageSource.Source;

            // the file type can easily rule out if we need to request the url
            if (source.PackageSource.ProtocolVersion == 3 ||
                (source.PackageSource.IsHttp &&
                 url.EndsWith(".json", StringComparison.OrdinalIgnoreCase)))
            {
                ServiceIndexCacheInfo cacheInfo;
                // check the cache before downloading the file
                if (!_cache.TryGetValue(url, out cacheInfo) ||
                    UtcNow - cacheInfo.CachedTime > MaxCacheDuration)
                {
                    var messageHandlerResource = await source.GetResourceAsync <HttpHandlerResource>(token);

                    var client = new DataClient(messageHandlerResource.MessageHandler);

                    JObject json;

                    try
                    {
                        json = await client.GetJObjectAsync(new Uri(url), token);
                    }
                    catch (JsonReaderException)
                    {
                        _cache.TryAdd(url, new ServiceIndexCacheInfo {
                            CachedTime = UtcNow
                        });
                        return(new Tuple <bool, INuGetResource>(false, null));
                    }
                    catch (HttpRequestException)
                    {
                        _cache.TryAdd(url, new ServiceIndexCacheInfo {
                            CachedTime = UtcNow
                        });
                        return(new Tuple <bool, INuGetResource>(false, null));
                    }

                    if (json != null)
                    {
                        // Use SemVer instead of NuGetVersion, the service index should always be
                        // in strict SemVer format
                        SemanticVersion version;
                        JToken          versionToken;
                        if (json.TryGetValue("version", out versionToken) &&
                            versionToken.Type == JTokenType.String &&
                            SemanticVersion.TryParse((string)versionToken, out version) &&
                            version.Major == 3)
                        {
                            index = new ServiceIndexResourceV3(json, UtcNow);
                        }
                    }
                }
                else
                {
                    index = cacheInfo.Index;
                }

                // cache the value even if it is null to avoid checking it again later
                _cache.TryAdd(url, new ServiceIndexCacheInfo {
                    CachedTime = UtcNow, Index = index
                });
            }

            return(new Tuple <bool, INuGetResource>(index != null, index));
        }
Exemplo n.º 20
0
 protected override void ExecuteInternal()
 {
     DataClient.AddUniqueKey(UniqueKeyName, TableNames[0], ColumnNames);
 }
Exemplo n.º 21
0
        public static async Task <IActionResult> GetUsersByIDAsync(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users/get/users/id")] HttpRequest req,
            ILogger log)
        {
            // set up connection
            DataClient client             = new DataClient();
            IMongoCollection <User> users = client.GetCollection <User>("users");

            string reqBody;

            try
            {
                reqBody = await new StreamReader(req.Body).ReadToEndAsync();
                if (string.IsNullOrEmpty(reqBody))
                {
                    return(new BadRequestObjectResult(new
                    {
                        message = "No request body supplied"
                    }));
                }
            }
            catch (Exception e)
            {
                return(new BadRequestObjectResult(new
                {
                    message = e.Message
                }));
            }

            List <string> uidsRaw    = JsonConvert.DeserializeObject <List <string> >(reqBody);
            List <string> uidsPoison = new List <string>();
            List <string> uids       = new List <string>();

            if (uidsRaw.Count == 0)
            {
                return(new NotFoundObjectResult(new
                {
                    message = "No search terms specified"
                }));
            }

            // try creating a list of object ids
            foreach (string id in uidsRaw)
            {
                try
                {
                    uids.Add(id);
                }
                catch
                {
                    uidsPoison.Add(id);
                }
            }

            FilterDefinition <User> filter = Builders <User> .Filter.Where(x => x.when_deleted == null) &
                                             Builders <User> .Filter.In(x => x.id, uids);

            List <User> userResults = (await(await users.FindAsync(filter)).ToListAsync());

            if (userResults.Count == 0)
            {
                return(new NotFoundObjectResult(new
                {
                    message = "No users found"
                }));
            }

            uids.RemoveAll(x => userResults.Select(j => j.id).ToList().Contains(x));

            return(new OkObjectResult(new
            {
                message = "Found users",
                users_found = userResults,
                users_notfound = uids,
                users_poison = uidsPoison
            }));
        }
 public UIMetadataResourceV3Provider(DataClient client)
     : base(typeof(UIMetadataResource), "UIMetadataResourceV3Provider", "UIMetadataResourceV2Provider")
 {
     _client = client;
 }
Exemplo n.º 23
0
 protected override void ExecuteInternal()
 {
     DataClient.RenameColumn(TableNames[0], _columnName, _newName);
 }
Exemplo n.º 24
0
        /// <summary>
        /// Seeds Transactional Data
        /// </summary>
        /// <param name="dataClientConfig"></param>
        /// <returns></returns>
        private async Task TransactionalDataDemoAsync(Config.DataClientConfig dataClientConfig)
        {
            try
            {
                using (DataClient dataClient = new DataClient(dataClientConfig))
                {
                    if (dataClient.TransactionalData != null)
                    {
                        TransactionalData transactionalData = dataClient.TransactionalData;

                        // Explicit loading. When the entity is first read, related data isn't retrieved.
                        // Example code that retrieves the related data. It impacts retrieval performance hence only use if it's needed.
                        await transactionalData.ClientUsers.Include(clientUser => clientUser.Client)
                        .Include(clientUser => clientUser.User).LoadAsync();

                        await transactionalData.UserCoupons.Include(userCoupon => userCoupon.User)
                        .Include(userCoupon => userCoupon.Coupon).LoadAsync();


                        ///////// DB seeding with demo content /////////

                        // Look for any Clients
                        if (transactionalData.ClientUsers.Any())
                        {
                            string log = "Total ClientUsers found: " + transactionalData.ClientUsers.LongCount() + " | " +
                                         "Total UserCoupons found: " + transactionalData.UserCoupons.LongCount();
                            Context.Logger.LogLine("[TransactionalData Summary]");
                            Context.Logger.LogLine(log);
                            return;   // DB has been seeded already
                        }

                        // DB save operation
                        Context.Logger.LogLine("[Adding contents for TransactionalData]");

                        // Adding ClientUsers
                        var clientUsers = new ClientUser[]
                        {
                            new ClientUser {
                                ClientID = 1, UserID = 1
                            }
                        };
                        foreach (ClientUser clientUser in clientUsers)
                        {
                            transactionalData.ClientUsers.Add(clientUser);
                        }
                        Context.Logger.LogLine("1 ClientUser added");

                        // Adding UserCoupons
                        var userCoupons = new UserCoupon[]
                        {
                            new UserCoupon {
                                UserID = 1, CouponID = 1
                            }
                        };
                        foreach (UserCoupon userCoupon in userCoupons)
                        {
                            transactionalData.UserCoupons.Add(userCoupon);
                        }
                        Context.Logger.LogLine("1 UserCoupon added");

                        // SAVING the changes into physical DB
                        await transactionalData.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Context.Logger.LogLine("TransactionalData ERROR: " + ex.Message);
            }
        }
Exemplo n.º 25
0
 public void InitServiceClient(string accessToken)
 {
     serviceClient = new DataClient(accessToken);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Seeds Configuration Data
        /// </summary>
        /// <param name="dataClientConfig"></param>
        /// <returns></returns>
        private async Task ConfigurationDataDemoAsync(Config.DataClientConfig dataClientConfig)
        {
            try
            {
                using (DataClient dataClient = new DataClient(dataClientConfig))
                {
                    if (dataClient.ConfigurationData != null)
                    {
                        ConfigurationData configurationData = dataClient.ConfigurationData;

                        // Explicit loading. When the entity is first read, related data isn't retrieved.
                        // Example code that retrieves the related data. It impacts retrieval performance hence only use if it's needed.
                        await configurationData.Clients.Include(client => client.ClientSpots).LoadAsync();

                        await configurationData.ClientSpots.Include(clientSpot => clientSpot.Zones)
                        .Include(clientSpot => clientSpot.LocationDevices)
                        .Include(clientSpot => clientSpot.DisplayEndpoints)
                        .Include(clientSpot => clientSpot.Notifications)
                        .Include(clientSpot => clientSpot.Coupons).LoadAsync();

                        await configurationData.Zones.Include(zone => zone.LocationDevices)
                        .Include(zone => zone.DisplayEndpoints).LoadAsync();

                        await configurationData.LocationDevices.Include(locationDevice => locationDevice.LocationDeviceNotifications).LoadAsync();

                        await configurationData.DisplayEndpoints.Include(displayEndpoint => displayEndpoint.DisplayEndpointNotifications).LoadAsync();

                        await configurationData.Notifications.Include(notification => notification.Coupons)
                        .Include(notification => notification.LocationDeviceNotifications)
                        .Include(notification => notification.DisplayEndpointNotifications).LoadAsync();


                        ///////// DB seeding with demo content /////////

                        // Look for any Clients
                        if (configurationData.Clients.Any())
                        {
                            string log = "Total Client found: " + configurationData.Clients.LongCount() + " | " +
                                         "Total ClientSpot found: " + configurationData.ClientSpots.LongCount() + " | " +
                                         "Total Zone found: " + configurationData.Zones.LongCount() + " | " +
                                         "Total LocationDevice found: " + configurationData.LocationDevices.LongCount() + " | " +
                                         "Total DisplayEndpoint found: " + configurationData.DisplayEndpoints.LongCount() + " | " +
                                         "Total Notification found: " + configurationData.Notifications.LongCount() + " | " +
                                         "Total Coupon found: " + configurationData.Coupons.LongCount() + " | " +
                                         "Total User found: " + configurationData.Users.LongCount();
                            Context.Logger.LogLine("[ConfigurationData Summary]");
                            Context.Logger.LogLine(log);
                            return;   // DB has been seeded already
                        }

                        // DB save operation
                        Context.Logger.LogLine("[Adding contents for ConfigurationData]");

                        // Adding Clients
                        var clients = new Client[]
                        {
                            new Client {
                                Name = "Demo Mart", PhoneNumber = "001-123-4567", Address = "US"
                            }
                        };
                        foreach (Client client in clients)
                        {
                            configurationData.Clients.Add(client);
                        }
                        Context.Logger.LogLine("1 Client added");

                        // Adding ClientSpots
                        var clientSpots = new ClientSpot[]
                        {
                            new ClientSpot {
                                ClientID = clients[0].ClientID, Name = "DemoMart Seattle Store", PhoneNumber = "001-123-4567", Address = "Seattle, US"
                            },
                            new ClientSpot {
                                ClientID = clients[0].ClientID, Name = "DemoMart LA Store", PhoneNumber = "001-123-4567", Address = "LA, US"
                            }
                        };
                        foreach (ClientSpot clientSpot in clientSpots)
                        {
                            configurationData.ClientSpots.Add(clientSpot);
                        }
                        Context.Logger.LogLine("2 ClientSpots added");

                        // Adding Zones
                        var zones = new Zone[]
                        {
                            new Zone {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Pseudo Zone"
                            },
                            new Zone {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Entrance Zone (Scenario #1)"
                            },
                            new Zone {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Bakery Zone (Scenario #2)"
                            },
                            new Zone {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Electronics Zone (Scenario #3)"
                            }
                        };
                        foreach (Zone zone in zones)
                        {
                            configurationData.Zones.Add(zone);
                        }
                        Context.Logger.LogLine("4 Zones added");

                        // SAVING the changes into physical DB
                        await configurationData.SaveChangesAsync();

                        // Adding LocationDevices
                        var locationDevices = new LocationDevice[]
                        {
                            new LocationDevice {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[0].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "pseudo-uuid"
                            },
                            new LocationDevice {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[1].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "11111111-1111-1111-1111-111111111111"
                            },
                            new LocationDevice {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[2].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "22222222-2222-2222-2222-222222222222"
                            },
                            new LocationDevice {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[3].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "33333333-3333-3333-3333-333333333333"
                            },
                            new LocationDevice {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[3].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "44444444-4444-4444-4444-444444444444"
                            }
                        };
                        foreach (LocationDevice locationDevice in locationDevices)
                        {
                            configurationData.LocationDevices.Add(locationDevice);
                        }
                        Context.Logger.LogLine("5 LocationDevices added");

                        // Adding DisplayEndpoints
                        var displayEndpoints = new DisplayEndpoint[]
                        {
                            new DisplayEndpoint {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[0].ZoneID, Name = "Pseudo Display"
                            },
                            new DisplayEndpoint {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[1].ZoneID, Name = "Demo Display 1"
                            },
                            new DisplayEndpoint {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[2].ZoneID, Name = "Demo Display 2"
                            },
                            new DisplayEndpoint {
                                ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[3].ZoneID, Name = "Demo Display 3"
                            }
                        };
                        foreach (DisplayEndpoint displayEndpoint in displayEndpoints)
                        {
                            configurationData.DisplayEndpoints.Add(displayEndpoint);
                        }
                        Context.Logger.LogLine("4 DisplayEndpoints added");

                        // Adding Notifications
                        var notifications = new Notification[]
                        {
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Pseduo Notification", Timeout = 10, ContentMimeType = MimeType.ImagePng, ContentSubject = "Pseduo Notification", ContentCaption = "Pseduo advertisement", ContentBody = "http://www.abc.com/images/img1.png"
                            },
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 1 (Scenario #1)", SortOrder = 1, Timeout = 20, ShowProgressBar = false, ContentMimeType = MimeType.ImagePng, ContentSubject = "Welcome Greetings", ContentCaption = "Welcome to DemoMart Seattle Store!", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/welcome.png"
                            },
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 2 (Scenario #2)", SortOrder = 1, Timeout = 10, ContentMimeType = MimeType.ImageJpg, ContentSubject = "Advertisement for Doughnut", ContentCaption = "4 Delicious Doughnuts", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/doughnut.jpg"
                            },
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 3 (Scenario #2)", SortOrder = 2, Timeout = 10, ContentMimeType = MimeType.ImageJpg, ContentSubject = "Advertisement for Croissant", ContentCaption = "Croissant for breakfast needs", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/croissant.jpg"
                            },
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 4 (Scenario #2)", SortOrder = 3, Timeout = 10, ContentMimeType = MimeType.VideoMp4, ContentSubject = "Advertisement for Coke", ContentCaption = "Taste the Feeling", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/coke.mp4"
                            },
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 5 (Scenario #3)", Timeout = 10, ContentMimeType = MimeType.ImageJpeg, ContentSubject = "Advertisement for Iron", ContentCaption = "Steam Iron", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/iron.jpeg"
                            },
                            new Notification {
                                ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 6 (Scenario #3)", Timeout = 10, ContentMimeType = MimeType.ImageJpeg, ContentSubject = "Advertisement for Smartphone", ContentCaption = "Extraordinary performance", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/smart-phone.jpeg"
                            }
                        };
                        foreach (Notification notification in notifications)
                        {
                            configurationData.Notifications.Add(notification);
                        }
                        Context.Logger.LogLine("7 Notifications added");

                        // SAVING the changes into physical DB
                        await configurationData.SaveChangesAsync();

                        // Adding LocationDeviceNotifications
                        var displayEndpointNotifications = new DisplayEndpointNotification[]
                        {
                            new DisplayEndpointNotification {
                                DisplayEndpointID = displayEndpoints[0].DisplayEndpointID, NotificationID = notifications[0].NotificationID
                            },
                            new DisplayEndpointNotification {
                                DisplayEndpointID = displayEndpoints[1].DisplayEndpointID, NotificationID = notifications[1].NotificationID
                            },
                            new DisplayEndpointNotification {
                                DisplayEndpointID = displayEndpoints[2].DisplayEndpointID, NotificationID = notifications[2].NotificationID
                            },
                            new DisplayEndpointNotification {
                                DisplayEndpointID = displayEndpoints[2].DisplayEndpointID, NotificationID = notifications[3].NotificationID
                            },
                            new DisplayEndpointNotification {
                                DisplayEndpointID = displayEndpoints[2].DisplayEndpointID, NotificationID = notifications[4].NotificationID
                            }
                        };
                        foreach (DisplayEndpointNotification displayEndpointNotification in displayEndpointNotifications)
                        {
                            configurationData.DisplayEndpointNotifications.Add(displayEndpointNotification);
                        }
                        Context.Logger.LogLine("5 DisplayEndpointNotifications added");

                        // Adding LocationDeviceNotifications
                        var locationDeviceNotifications = new LocationDeviceNotification[]
                        {
                            new LocationDeviceNotification {
                                LocationDeviceID = locationDevices[3].LocationDeviceID, NotificationID = notifications[5].NotificationID
                            },
                            new LocationDeviceNotification {
                                LocationDeviceID = locationDevices[4].LocationDeviceID, NotificationID = notifications[6].NotificationID
                            }
                        };
                        foreach (LocationDeviceNotification locationDeviceNotification in locationDeviceNotifications)
                        {
                            configurationData.LocationDeviceNotifications.Add(locationDeviceNotification);
                        }
                        Context.Logger.LogLine("2 LocationDeviceNotifications added");

                        // Adding Coupons
                        var coupons = new Coupon[]
                        {
                            new Coupon {
                                ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[0].NotificationID, Name = "Pseduo Coupon", CouponCode = "00000000000", Description = "Save $0.00", DiscountCents = 0.0
                            },
                            new Coupon {
                                ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[2].NotificationID, Name = "Doughnut Coupon", CouponCode = "09876543210", Description = "SAVE $1.99", DiscountCents = 199.0
                            },
                            new Coupon {
                                ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[3].NotificationID, Name = "Croissant Coupon", CouponCode = "92186293264", Description = "SAVE $0.49", DiscountCents = 49.0
                            },
                            new Coupon {
                                ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[4].NotificationID, Name = "Coke Coupon", CouponCode = "97294957293", Description = "SAVE $0.20", DiscountCents = 20.0
                            }
                        };
                        foreach (Coupon coupon in coupons)
                        {
                            configurationData.Coupons.Add(coupon);
                        }
                        Context.Logger.LogLine("4 Coupons added");

                        // Adding Users
                        var users = new User[]
                        {
                            new User {
                                Type = UserType.Registered, Name = "Pseduo User", Email = "*****@*****.**"
                            },
                            new User {
                                Type = UserType.Registered, Name = "Demo User", Email = "*****@*****.**"
                            },
                            new User {
                                Type = UserType.Guest
                            }
                        };
                        foreach (User user in users)
                        {
                            configurationData.Users.Add(user);
                        }
                        Context.Logger.LogLine("3 Users added");

                        // SAVING the changes into physical DB
                        await configurationData.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Context.Logger.LogLine("ConfigurationData ERROR: " + ex.Message);
            }
        }
Exemplo n.º 27
0
 private void ResetDataMembers()
 {
     _displayEndpointID = null;
     _dataClient        = null;
 }
Exemplo n.º 28
0
 protected override void ExecuteInternal()
 {
     DataClient.RemoveUniqueKey(ItemName, TableNames[0]);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Processes the input request
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private async Task <APIGatewayProxyResponse> ProcessRequestAsync(APIGatewayProxyRequest request)
        {
            APIGatewayProxyResponse response = new APIGatewayProxyResponse();

            // Retrieve DisplayEndpointID from request path-parameters
            string displayEndpointIdRequestPathName = "display-endpoint-id";

            if (request?.PathParameters?.ContainsKey(displayEndpointIdRequestPathName) ?? false)
            {
                // Try to parse the provided UserID from string to long
                try
                {
                    _displayEndpointID = Convert.ToInt64(request.PathParameters[displayEndpointIdRequestPathName]);
                }
                catch (Exception ex)
                {
                    Context.Logger.LogLine("DisplayEndpointID conversion ERROR: " + ex.Message);
                }
            }

            // Validate the DisplayEndpointID
            if (1 > (_displayEndpointID ?? 0))
            {
                // Respond error
                Error error = new Error((int)HttpStatusCode.BadRequest)
                {
                    Description  = "Invalid ID supplied",
                    ReasonPharse = "Bad Request"
                };
                response.StatusCode = error.Code;
                response.Body       = JsonConvert.SerializeObject(error);
                Context.Logger.LogLine(error.Description);
            }
            else
            {
                // Initialize DataClient
                Config.DataClientConfig dataClientConfig = new Config.DataClientConfig(Config.DataClientConfig.RdsDbInfrastructure.Aws);
                using (_dataClient = new DataClient(dataClientConfig))
                {
                    // Check if DisplayEndpoint exists in DB
                    if (await IsDisplayEndpointExistsAsync())
                    {
                        Event  e = null;
                        string eventSerialized = request?.Body;
                        // Try to parse the provided json serialzed event into Event object
                        try
                        {
                            e = JsonConvert.DeserializeObject <Event>(eventSerialized);
                        }
                        catch (Exception ex)
                        {
                            Context.Logger.LogLine("Event deserialization ERROR: " + ex.Message);
                        }

                        // Validate the Event
                        if (!(e == null || e.Type != EventType.DisplayEndpoint_Touch || e.SourceType != EventSourceType.Notification || e.SourceID < 1))
                        {
                            // Register the DisplayEndpoint's touch event
                            await RegisterDisplayEndpointTouchEvent(e);

                            // Respond OK
                            response.StatusCode = (int)HttpStatusCode.OK;
                            response.Headers    = new Dictionary <string, string>()
                            {
                                { "Access-Control-Allow-Origin", "'*'" }
                            };
                            response.Body = JsonConvert.SerializeObject(new Empty());
                        }
                        else
                        {
                            // Respond error
                            Error error = new Error((int)HttpStatusCode.NotAcceptable)
                            {
                                Description  = "Invalid Event input",
                                ReasonPharse = "Not Acceptable Event"
                            };
                            response.StatusCode = error.Code;
                            response.Body       = JsonConvert.SerializeObject(error);
                            Context.Logger.LogLine(error.Description);
                        }
                    }
                    else
                    {
                        // Respond error
                        Error error = new Error((int)HttpStatusCode.NotFound)
                        {
                            Description  = "DisplayEndpoint not found",
                            ReasonPharse = "DisplayEndpoint Not Found"
                        };
                        response.StatusCode = error.Code;
                        response.Body       = JsonConvert.SerializeObject(error);
                        Context.Logger.LogLine(error.Description);
                    }
                }
            }

            return(response);
        }
Exemplo n.º 30
0
        public static async Task <IActionResult> DoRegisterUserAsync(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users/do/register")] HttpRequest req,
            ILogger log)
        {
            // set up connection
            DataClient client             = new DataClient();
            IMongoCollection <User> users = client.GetCollection <User>("users");

            // deserialise body input into class
            string reqBody;

            try
            {
                reqBody = await new StreamReader(req.Body).ReadToEndAsync();
                if (string.IsNullOrEmpty(reqBody))
                {
                    return(new BadRequestObjectResult(new
                    {
                        message = "No request body supplied"
                    }));
                }
            }
            catch (Exception e)
            {
                return(new BadRequestObjectResult(new
                {
                    message = e.Message
                }));
            }

            User registrant = JsonConvert.DeserializeObject <User>(reqBody);

            // valid input
            bool input_valid = true;

            if (string.IsNullOrEmpty(registrant.name_user))
            {
                input_valid = false;
            }
            if (string.IsNullOrEmpty(registrant.name_given))
            {
                input_valid = false;
            }
            if (string.IsNullOrEmpty(registrant.name_family))
            {
                input_valid = false;
            }

            // put the pins in if invalid input
            if (!input_valid)
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Invalid input"
                }));
            }

            // filter non-alphanumeric characters
            Regex alphanum = new Regex("[^a-zA-Z0-9 -]");

            registrant.name_user   = alphanum.Replace(registrant.name_user, "");
            registrant.name_given  = alphanum.Replace(registrant.name_given, "");
            registrant.name_family = alphanum.Replace(registrant.name_family, "");

            registrant.when_created = DateTime.UtcNow;
            registrant.when_deleted = null;

            // check username doesn't already exist
            if (await users.CountDocumentsAsync(x =>
                                                x.name_user == registrant.name_user && !x.when_deleted.HasValue) > 0)
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Username already exists"
                }));
            }

            await users.InsertOneAsync(registrant);

            return(new OkObjectResult(new
            {
                message = "Successfully registered user",
                user = registrant
            }));
        }
Exemplo n.º 31
0
        private static async Task Run()
        {
            Stopwatch timer = new Stopwatch();

            timer.Start();

            try
            {
                JObject context = JObject.Parse(@"{
                                ""@context"": {
                                ""@vocab"": ""http://schema.nuget.org/schema#"",
                                ""nuget"": ""http://schema.nuget.org/schema#"",
                                ""catalog"": ""http://schema.nuget.org/catalog#"",
                                ""items"": {
                                    ""@id"": ""catalog:item"",
                                    ""@container"": ""@set""
                                },
                                ""url"": ""@id"",
                                ""commitTimeStamp"": {
                                    ""@id"": ""catalog:commitTimeStamp"",
                                    ""@type"": ""http://www.w3.org/2001/XMLSchema#dateTime""
                                },
                                ""commitId"": {
                                    ""@id"": ""catalog:commitId""
                                },
                                ""count"": {
                                    ""@id"": ""catalog:count""
                                },
                                ""packageTargetFrameworks"": {
                                    ""@container"": ""@set"",
                                    ""@id"": ""packageTargetFramework""
                                },
                                ""dependencyGroups"": {
                                    ""@container"": ""@set"",
                                    ""@id"": ""dependencyGroup""
                                },
                                ""dependencies"": {
                                    ""@container"": ""@set"",
                                    ""@id"": ""dependency""
                                },
                                ""nupkgUrl"": {
                                    ""@type"": ""@id""
                                },
                                ""registration"": {
                                    ""@type"": ""@id""
                                }
                                }}");

                System.Net.ServicePointManager.DefaultConnectionLimit = 8;

                DataClient cache = new DataClient(new CacheHttpClient(), new MemoryFileCache());

                //Uri packageInfoUri = new Uri("http://nugetjohtaylo.blob.core.windows.net/ver3/registration/microsoft.bcl/index.json");
                Uri packageInfoUri = new Uri("http://nugetjohtaylo.blob.core.windows.net/ver3/registration/newtonsoft.json/index.json");

                var task  = cache.GetFile(packageInfoUri);
                var task2 = cache.GetFile(packageInfoUri);
                var task3 = cache.GetFile(packageInfoUri);
                var task4 = cache.GetFile(packageInfoUri);
                var task5 = cache.GetFile(packageInfoUri);

                var jObj  = await task2;
                var jObj2 = await task;

                EntityCache ec = new EntityCache();
                ec.Add(jObj, packageInfoUri);

                var entity = await cache.GetEntity(new Uri("http://nugetjohtaylo.blob.core.windows.net/ver3/registration/newtonsoft.json/index.json"));

                var blah = await cache.Ensure(entity, new Uri[] { new Uri("http://schema.nuget.org/schema#commitId") });

                var id = blah["commitId"];

                var search = await cache.GetFile(new Uri("http://preview-search.nuget.org/search/query"));

                var newtonsoft = search["data"].First;

                var ensureBlank = await cache.Ensure(newtonsoft, new Uri[] { });

                var ensureProp = await cache.Ensure(newtonsoft, new Uri[] { new Uri("http://schema.nuget.org/schema#commitId") });

                var id2 = ensureProp["commitId"];


                var rootUri = new Uri("http://nugetjohtaylo.blob.core.windows.net/ver33/registrations/newtonsoft.json/index.json");

                var rootEntity = await cache.GetEntity(rootUri);

                var rootEnsure = await cache.Ensure(rootEntity, new Uri[] { new Uri("http://schema.nuget.org/schema#commitId") });

                var rootCommitId = rootEnsure["commitId"];

                var rootEnsure2 = await cache.Ensure(rootEntity, new Uri[] { new Uri("http://schema.nuget.org/schema#nonexistant") });

                Uri root = new Uri("http://nugetjohtaylo.blob.core.windows.net/ver33/registrations/newtonsoft.json/index.json");

                var rootJObj = await cache.GetFile(root);

                foreach (var token in rootJObj["items"])
                {
                    JObject child = token as JObject;

                    JToken typeToken = null;
                    if (child.TryGetValue("@type", out typeToken) && typeToken.ToString() == "catalog:CatalogPage")
                    {
                        Parallel.ForEach(child["items"], packageToken =>
                        {
                            var catalogEntry = packageToken["catalogEntry"];

                            var w = cache.Ensure(catalogEntry, new Uri[] { new Uri("http://schema.nuget.org/schema#tag") });
                            w.Wait();

                            Console.WriteLine(w.Result["tag"]);
                        });
                    }
                }

                Console.WriteLine(timer.Elapsed);
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.ToString());
            }
        }
Exemplo n.º 32
0
        public static async Task <IActionResult> DoCreateEventAsync(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "events/do/create/object/{eventSession}")] HttpRequest req,
            string eventSession,
            ILogger log)
        {
            // set up connection
            DataClient client = new DataClient();
            IMongoCollection <Event> events = client.GetCollection <Event>("events");

            // deserialise body input into class
            string      reqBody;
            EventObject @event;

            try
            {
                reqBody = await new StreamReader(req.Body).ReadToEndAsync();
                if (string.IsNullOrEmpty(reqBody))
                {
                    return(new BadRequestObjectResult(new
                    {
                        message = "No request body supplied"
                    }));
                }

                @event = JsonConvert.DeserializeObject <EventObject>(reqBody);
            }
            catch (Exception e)
            {
                return(new BadRequestObjectResult(new
                {
                    message = e.Message
                }));
            }

            // valid input
            bool input_valid = true;

            if (string.IsNullOrEmpty(eventSession))
            {
                input_valid = false;
            }

            if (!(@event.type == "transform" || @event.type == "perception" || @event.type == "reaction"))
            {
                input_valid = false;
            }

            // put the pins in if invalid input
            if (!input_valid)
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Invalid input"
                }));
            }

            @event.when_occured = DateTime.UtcNow;
            EventObject eventBuilt = new EventObject()
            {
                id                 = ObjectId.GenerateNewId().ToString(),
                type               = @event.type.ToLower(),
                user               = null,
                when_occured       = DateTime.UtcNow,
                contact_duration   = @event.contact_duration,
                result             = @event.result,
                object_coordinator = @event.object_coordinator,
                objects_involved   = @event.objects_involved
            };

            FilterDefinition <Event> filter = Builders <Event>
                                              .Filter.Eq(x => x.id, eventSession);

            UpdateDefinition <Event> update = Builders <Event> .Update
                                              .Push <EventObject>(x => x.events, eventBuilt);

            await events.UpdateOneAsync(filter, update);

            return(new OkObjectResult(new
            {
                message = "Successfully created an event",
                @event = eventBuilt
            }));
        }
Exemplo n.º 33
0
 public MatchesController(DataClient dataClient)
 {
     this.dataClient = dataClient;
 }
Exemplo n.º 34
0
 protected override void ExecuteInternal()
 {
     DataClient.AddNamedPrimaryKey(TableNames[0], PrimaryKeyName, ColumnNames);
 }
        /// <summary>
        /// 指定一个 <see cref="DataClient"/> 的其中之一的值、一个对应的连接字符串,以创建一个新的 <see cref="NkjSoft.ORM.Data.DbEntityProvider"/> 对象。
        /// </summary>
        /// <param name="providerType">实体查询提供程序类型</param>
        /// <param name="connnectionString">连接字符串</param>
        /// <param name="mappingKeyName">对象映射方式</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException"> 应用程序配置文件节点未找到。</exception>
        public static DbEntityProvider FromApplicationSettings(DataClient providerType, string connnectionString)
        {
            DbEntityProvider _temp = null;
            var mp = new ImplicitMapping();

            DbConnection conn = null;
            var t = typeof(NkjSoft.ORM.Data.SqlClient.SqlDbProvider);
            switch (providerType)
            {
                default:
                case DataClient.SqlDbProvider:
                    // m_provider = new Data.SqlClient.SqlDbProvider((System.Data.SqlClient.SqlConnection)conn, mp, QueryPolicy.Default); 
                    conn = System.Data.SqlClient.SqlClientFactory.Instance.CreateConnection();
                    break;
#if OtherSQLProvider
                case DataClient.MySqlDbProvider:
                    //m_provider = new Data.MySqlClient.MySqlDbProvider((MySql.Data.MySqlClient.MySqlConnection)conn, mp, QueryPolicy.Default);
                    t = typeof(NkjSoft.ORM.Data.MySqlClient.MySqlDbProvider);
                    conn = MySql.Data.MySqlClient.MySqlClientFactory.Instance.CreateConnection();
                    break;
                case DataClient.OracleProvider:
                    //m_provider = new Datarovider((System.Data.)conn, mp, QueryPolicy.Default);
                    //UNDONE : 暂时未实现 Oracle 版本
                    break;
                case DataClient.SQLiteDbProvider:
                    //m_provider = new Data.SQLite.SQLiteDbProvider((System.Data.SQLite.SQLiteConnection)conn, mp, QueryPolicy.Default);    
                    t = typeof(NkjSoft.ORM.Data.SQLite.SQLiteDbProvider);
                    conn = System.Data.SQLite.SQLiteFactory.Instance.CreateConnection();
                    break;
#endif
                case DataClient.OleDbProvider:
                    //m_provider = new Data.Access.OleDbProvider((System.Data.OleDb.OleDbConnection)conn, mp, QueryPolicy.Default);
                    t = typeof(NkjSoft.ORM.Data.Access.OleDbProvider);
                    conn = System.Data.OleDb.OleDbFactory.Instance.CreateConnection();
                    break;
            }
            conn.ConnectionString = connnectionString;

            _temp = Activator.CreateInstance(t, conn, mp, QueryPolicy.Default) as DbEntityProvider;

            return _temp;
        }