public void Start()
        {
            IList <RestData> all = GetAll();

            foreach (RestData data in all)
            {
                Console.WriteLine(data);
            }

            RestData one = GetOne(12);

            Console.WriteLine("ONE \n" + one);

            bool resultat = Post(new RestData(555, 555, "peter was here", true));

            Console.WriteLine("Post result = " + resultat);

            bool putResultat = Put(3, new RestData(555, 555, "peter was here", true));

            Console.WriteLine("Put result = " + putResultat);

            bool deleteResultat = Delete(12);

            Console.WriteLine("Delete result = " + deleteResultat);
        }
Esempio n. 2
0
 /// <summary>
 /// 记录复位信息
 /// </summary>
 /// <param name="en"></param>
 /// <param name="data"></param>
 public void RecordResetPos(RestData data)
 {
     if (!_listRestData.Exists(x => x.en == data.en))
     {
         _listRestData.Add(data);
     }
 }
 public RestData <TDestination> Convert(RestData <TSource> source, RestData <TDestination> destination, ResolutionContext context)
 {
     destination = destination ?? new RestData <TDestination>();
     destination.SetData(context.Mapper.Map <TDestination>(source.Data));
     destination.SetPaging(source.Paging);
     return(destination);
 }
 internal NowPlaying(RestData.NowPlaying restData)
     : base(restData)
 {
     UserName = restData.UserName ?? "";
     MinutesAgo = restData.MinutesAgo ?? -1;
     PlayerId = new SubsonicId(restData.PlayerId ?? "");
     PlayerName = restData.PlayerName ?? "";
 }
 private RestData GetOne(int id)
 {
     using (HttpClient client = new HttpClient())
     {
         string   jsonContent = client.GetStringAsync(URI + "/" + id).Result;
         RestData data        = JsonConvert.DeserializeObject <RestData>(jsonContent);
         return(data);
     }
 }
 internal SubsonicResponse(RestData.SubsonicResponse restData)
 {
     Ok = restData.IsOk;
     Version = SubsonicVersion.Parse(restData.Version);
     _nowPlayingList = restData.NowPlaying.Select(nowPlaying => new NowPlaying(nowPlaying)).ToList();
     _shares = restData.Shares.Select(share => new Share(share)).ToList();
     _playlists = restData.Playlists.Select(playlist => new Playlist(playlist)).ToList();
     SearchResult2 = new SearchResult2(restData.SearchResult2);
     User = new User(restData.User);
 }
Esempio n. 7
0
        /// <summary>
        /// Выполнить запрос
        /// </summary>
        /// <typeparam name="T">Тип</typeparam>
        /// <param name="url">URL</param>
        /// <param name="requestData">Сериализованные данные</param>
        /// <param name="httpMethod">Метод запроса (post, get)</param>
        /// <returns>Десериализованный ответ с сервера</returns>
        private T RestExecute <T>(string url, object requestData, string httpMethod, Dictionary <string, string> addHeaders = null)
        {
            RestData g;

            if (requestData is Stream)
            {
                g = new RestData(url, requestData as Stream, httpMethod);
            }
            else
            {
                var serializedObject = JsonConvert.SerializeObject(requestData);
                g = new RestData(url, serializedObject, httpMethod);
            }

            HttpWebResponse httpWResp = null;

            try
            {
                httpWResp = DoRestExecute(g, addHeaders);
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Response);
            }

            var result = "";

            if (httpWResp != null && httpWResp.StatusCode == HttpStatusCode.OK)
            {
                using (var sr = new StreamReader(httpWResp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();

                    //debugView.AppendText(Environment.NewLine);
                    //debugView.AppendText(string.Format("Ответ сервера: {0}", result), Color.Black);
                    //debugView.AppendText(Environment.NewLine);
                }
            }
            else
            {
                if (httpWResp != null)
                {
                    Console.WriteLine("ERROR STATUS CODE:{0}, MESSAGE: {1}", httpWResp.StatusCode,
                                      httpWResp.StatusDescription);
                }
                else
                {
                    //debugView.AppendText(Environment.NewLine);
                    //debugView.AppendText("Ошибка при выполнении запроса", Color.Red);
                    //debugView.AppendText(Environment.NewLine);
                    //throw new WebException("httpWResp == null");
                }
            }
            return(JsonConvert.DeserializeObject <T>(result, JsonSettings));
        }
Esempio n. 8
0
 internal Album(RestData.Album restData)
 {
     Id = new SubsonicId(restData.Id ?? "");
     Parent = new SubsonicId(restData.Parent ?? "");
     Title = restData.Title ?? "";
     Artist = restData.Artist ?? "";
     IsDirectory = restData.IsDir ?? false;
     CoverArt = new SubsonicId(restData.CoverArt ?? "");
     UserRating = restData.UserRating;
     AverageRating = restData.AverageRating ?? 0.0;
 }
Esempio n. 9
0
 internal Share(RestData.Share restData)
 {
     Id = new SubsonicId(restData.Id ?? "");
     Url = restData.Url;
     Description = restData.Description ?? "";
     UserName = restData.UserName ?? "";
     Created = restData.Created;
     LastVisited = restData.LastVisited;
     Expires = restData.Expires;
     VisitCount = restData.VisitCount ?? 0;
     _entries = restData.Entries.Select(entry => new Entry(entry)).ToList();
 }
Esempio n. 10
0
 internal Playlist(RestData.Playlist playlist)
 {
     Id = new SubsonicId(playlist.Id ?? "");
     Name = playlist.Name ?? "";
     Comment = playlist.Comment ?? "";
     Owner = playlist.Owner ?? "";
     Public = playlist.Public ?? false;
     SongCount = playlist.SongCount ?? 0;
     Duration = playlist.Duration ?? 0;
     Created = playlist.Created;
     _allowedUsers = playlist.AllowedUsers.Select(allowedUser => allowedUser.Value).ToList();
 }
Esempio n. 11
0
    public void Reset(Enum en)
    {
        if (!_listRestData.Exists(x => x.en == en))
        {
            OnLeftRest();
            return;
        }

        RestData data = _listRestData.First(x => x.en == en);

        transform.localEulerAngles = data.angle;
        transform.localPosition    = data.pos;
        transform.localScale       = data.zoom;
        //int index=  _listRestData.FindIndex(x => x.en == en);
        //  _listRestData.RemoveAt(index);
    }
Esempio n. 12
0
 internal User(RestData.User restData)
 {
     UserName = restData.UserName ?? "";
     Email = restData.Email ?? "";
     ScrobblingEnabled = restData.ScrobblingEnabled ?? false;
     AdminRole = restData.AdminRole ?? false;
     SettingsRole = restData.SettingsRole ?? false;
     DownloadRole = restData.DownloadRole ?? false;
     UploadRole = restData.UploadRole ?? false;
     PlaylistRole = restData.PlaylistRole ?? false;
     CoverArtRole = restData.CoverArtRole ?? false;
     CommentRole = restData.CommentRole ?? false;
     PodcastRole = restData.PodcastRole ?? false;
     StreamRole = restData.StreamRole ?? false;
     JukeboxRole = restData.JukeboxRole ?? false;
     ShareRole = restData.ShareRole ?? false;
 }
Esempio n. 13
0
        /// <summary>
        /// 上传文件-自动选择上传方式
        /// </summary>
        /// <param name="bucket">上传到的桶</param>
        /// <param name="uploadPath">上传到的目录包含文件名</param>
        /// <param name="localFile">要上传的文件路径</param>
        /// <returns>上传成功的地址</returns>
        public static async Task <string> UploadFileAsync(string bucket, string key, string localFile)
        {
            // 生成(上传)凭证时需要使用此Mac
            // 这个示例单独使用了一个Settings类,其中包含AccessKey和SecretKey
            // 实际应用中,请自行设置您的AccessKey和SecretKey
            Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey);

            //string bucket = "test";
            //string saveKey = bucket + uploadPath;
            //string localFile = "D:\\QFL\\1.png";

            Config.AutoZone(Settings.AccessKey, bucket, false);//自动配置机房区域

            // 上传策略,参见
            // https://developer.qiniu.com/kodo/manual/put-policy
            PutPolicy putPolicy = new PutPolicy();

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;
            putPolicy.Scope = bucket;
            // 上传策略有效期(对应于生成的凭证的有效期)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除
            //putPolicy.DeleteAfterDays = 1;
            // 生成上传凭证,参见
            // https://developer.qiniu.com/kodo/manual/upload-token
            string jstr  = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);

            UploadManager um = new UploadManager();
            //Qiniu.Http.HttpResult uploadFile = um.UploadFile(localFile, saveKey, token);
            HttpResult result = await um.UploadFileAsync(localFile, key, token);

            Console.WriteLine(result);
            if (result.Code == (int)HttpCode.OK)
            {
                RestData restData = JsonConvert.DeserializeObject <RestData>(result.Text);
                string   restUrl  = "http://" + Settings.Domain + "/" + restData.key;

                return(restUrl);
            }
            throw new Exception("上传文件出错!!!");
            //return new Exception("");
        }
Esempio n. 14
0
 /// <summary>
 /// 重置
 /// </summary>
 public void OnLeftRest()
 {
     if (_listRestData.Count == 0)
     {
         transform.localEulerAngles = localRoatation;
         transform.localPosition    = localPos;
         transform.localScale       = localSacle;
         Debug.Log("OnLeftRest" + localPos);
     }
     else
     {
         int      cout = _listRestData.Count - 1;
         RestData data = _listRestData[cout];
         transform.localEulerAngles = data.angle;
         transform.localPosition    = data.pos;
         transform.localScale       = data.zoom;
         Debug.Log("OnLeftRest" + data.pos);
         //_listRestData.RemoveAt(cout);
     }
 }
Esempio n. 15
0
 internal Child(RestData.Child restData)
 {
     Id = new SubsonicId(restData.Id ?? "");
     Parent = new SubsonicId(restData.Parent ?? "");
     Title = restData.Title ?? "";
     IsDirectory = restData.IsDir ?? false;
     Album = restData.Album ?? "";
     Artist = restData.Artist ?? "";
     Track = restData.Track ?? "";
     Year = restData.Year ?? -1;
     Genre = restData.Genre ?? "";
     CoverArt = new SubsonicId(restData.CoverArt ?? "");
     Size = restData.Size ?? -1;
     ContentType = restData.ContentType ?? "";
     Suffix = restData.Suffix ?? "";
     TranscodedContentType = restData.TranscodedContentType ?? "";
     TranscodedSuffix = restData.TranscodedSuffix ?? "";
     Duration = restData.Duration ?? -1;
     Bitrate = restData.BitRate ?? -1;
     Path = restData.Path ?? "";
 }
        public bool Put(int id, RestData restData)
        {
            // laver body
            String        json    = JsonConvert.SerializeObject(restData);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            //content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            using (HttpClient client = new HttpClient())
            {
                // sender
                HttpResponseMessage resultMessage = client.PutAsync(URI + "/" + id, content).Result;


                // optional if any result to unpack
                string jsonResult = resultMessage.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Json svar string = " + jsonResult);
                // ingen rigtig svar
                //var result = JsonConvert.DeserializeObject<TReturnType>(jsonResult);

                return(resultMessage.IsSuccessStatusCode);
            }
        }
Esempio n. 17
0
 public Entry(RestData.Entry entry)
     : base(entry)
 {
 }
Esempio n. 18
0
        /// <summary>
        /// Выполнить запрос на основании данных
        /// </summary>
        /// <param name="restData">Данные</param>
        /// <returns>Ответ сервера</returns>
        private HttpWebResponse DoRestExecute(RestData restData, Dictionary <string, string> headers = null)
        {
            //Создаем экземпляр запроса по URL
            var HttpWReq = (HttpWebRequest)WebRequest.Create(restData.Url);

            //Указываем метод запроса
            HttpWReq.Method      = restData.HTTPMethod;
            HttpWReq.Credentials = CredentialCache.DefaultCredentials;
            //Добавляем токен приложения
            HttpWReq.Headers.Add("ApplicationToken", ApplicationToken);
            //Добавляем токен авторизации, если есть
            if (!string.IsNullOrWhiteSpace(AuthToken))
            {
                HttpWReq.Headers.Add("AuthToken", AuthToken);
            }
            //Добавляем токен сессии, если есть
            if (!string.IsNullOrEmpty(SessionToken))
            {
                HttpWReq.Headers.Add("SessionToken", SessionToken);
            }
            HttpWReq.Accept = "application/json; charset=utf-8";
            HttpWReq.Headers.Add("WebData-Version", "2.0");
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    HttpWReq.Headers.Add(header.Key, header.Value);
                }
            }
            var encoding = new UTF8Encoding();

            //Если метод POST, тогда добавляем тип контента и вставляем данные
            if (restData.HTTPMethod == WebRequestMethods.Http.Post)
            {
                if (!string.IsNullOrWhiteSpace(restData.Data))
                {
                    var byteData = encoding.GetBytes(restData.Data);
                    HttpWReq.ContentType = "application/json; charset=utf-8";

                    HttpWReq.ContentLength = byteData.Length;
                    using (Stream requestStream = HttpWReq.GetRequestStream())
                    {
                        requestStream.Write(byteData, 0, byteData.Length);
                    }
                }

                if (restData.Stream != null)
                {
                    HttpWReq.ContentType   = "application/json; charset=utf-8";
                    HttpWReq.ContentLength = restData.Stream.Length;

                    using (Stream requestStream = HttpWReq.GetRequestStream())
                    {
                        byte[] buffer = new byte[restData.Stream.Length];
                        restData.Stream.Read(buffer, 0, (int)restData.Stream.Length);
                        requestStream.Write(buffer, 0, (int)restData.Stream.Length);
                    }
                }
            }
            return((HttpWebResponse)HttpWReq.GetResponse());
        }
Esempio n. 19
0
 internal Artist(RestData.Artist restData)
 {
     Id = new SubsonicId(restData.Id ?? "");
     Name = restData.Name ?? "";
 }
 internal SearchResult2(RestData.SearchResult2 restData)
 {
     _artists = restData.Artists.Select(artist => new Artist(artist)).ToList();
     _albums = restData.Albums.Select(album => new Album(album)).ToList();
     _songs = restData.Songs.Select(song => new Song(song)).ToList();
 }
        //Populate the database from webservice if there are no rows
        public void PopulateDatabase()
        {
            if (DataCount())
            {
                using var connection = new SqlConnection(connectionString);
                connection.Open();

                RestData        rd        = new RestData();
                List <Customer> customers = rd.GetCustomers();
                List <Login>    logins    = rd.GetLogins();

                foreach (var customer in customers)
                {
                    var command = new SqlCommand("CreateCustomer", connection);
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.AddWithValue("@CUSTOMERID", customer.CustomerID);
                    command.Parameters.AddWithValue("@NAME", customer.Name);
                    command.Parameters.AddWithValue("@ADDRESS", customer.Address);
                    command.Parameters.AddWithValue("@CITY", customer.City);
                    command.Parameters.AddWithValue("@POSTCODE", customer.PostCode);

                    command.ExecuteNonQuery();

                    foreach (var account in customer.Accounts)
                    {
                        var accountCommand = new SqlCommand("CreateAccount", connection);
                        accountCommand.CommandType = CommandType.StoredProcedure;

                        accountCommand.Parameters.AddWithValue("@AccountNumber", account.AccountNumber);
                        accountCommand.Parameters.AddWithValue("@AccountType", account.AccountType);
                        accountCommand.Parameters.AddWithValue("@CustomerID", account.CustomerID);
                        accountCommand.Parameters.AddWithValue("@Balance", account.Balance);

                        accountCommand.ExecuteNonQuery();

                        foreach (var transaction in account.Transactions)
                        {
                            var transCommand = new SqlCommand("CreateTransaction", connection);
                            transCommand.CommandType = CommandType.StoredProcedure;

                            transaction.TransactionType          = 'D';
                            transaction.AccountNumber            = account.AccountNumber;
                            transaction.DestinationAccountNumber = account.AccountNumber;
                            transaction.Amount = account.Balance;

                            transaction.Comment = "Initial Deposit";

                            transCommand.Parameters.AddWithValue("@TransactionType", transaction.TransactionType);
                            transCommand.Parameters.AddWithValue("@AccountNumber", transaction.AccountNumber);
                            transCommand.Parameters.AddWithValue("@DestinationAccountNumber", transaction.DestinationAccountNumber);
                            transCommand.Parameters.AddWithValue("@Amount", transaction.Amount);
                            transCommand.Parameters.AddWithValue("@Comment", transaction.Comment);
                            transCommand.Parameters.AddWithValue("@TransactionTimeUtc", transaction.TransactionTimeUtc);

                            transCommand.ExecuteNonQuery();
                        }
                    }
                }

                foreach (var login in logins)
                {
                    var command = new SqlCommand("CreateLogin", connection);
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.AddWithValue("@LoginID", login.LoginID);
                    command.Parameters.AddWithValue("@CustomerID", login.CustomerID);
                    command.Parameters.AddWithValue("@PasswordHash", login.PasswordHash);

                    command.ExecuteNonQuery();
                }
            }
        }