public ActionResult Index()
        {
            PostClient        postClient        = new PostClient();
            UserPosterClient  userPoster        = new UserPosterClient();
            CategoriaClient   categoriaClient   = new CategoriaClient();
            CiudadClient      ciudadClient      = new CiudadClient();
            PaisClient        paisClient        = new PaisClient();
            TipoTrabajoClient tipoTrabajoClient = new TipoTrabajoClient();
            var elementos = postClient.GetAll();
            var i         = new List <Post>();

            if (elementos != null)
            {
                foreach (var e in elementos)
                {
                    e.Posters      = userPoster.FindPost(e.Poster);
                    e.Categorias   = categoriaClient.FindCategory(e.NombreCategoria);
                    e.Ciudades     = ciudadClient.FindCiudad(e.NombreCiudad);
                    e.Paises       = paisClient.FindPais(e.NombrePais);
                    e.TipoTrabajos = tipoTrabajoClient.FindTipoTrabajo(e.NombreTipoTrabajo);
                    i.Add(e);
                }
                var v = (from a in i

                         select a);


                ViewBag.ListCategories = categoriaClient.GetAll().OrderBy(p => p.Nombre);
                v = v.OrderBy(p => p.Categorias);
                return(View(v));
            }

            return(View());
        }
        public void get_chengjiu_list()
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("username", "8785169");

            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    JObject userobj = JObject.Parse(e.Result);

                    JArray             userdata_info = (JArray)userobj["detail"];
                    my_chengjiu_detile a             = new my_chengjiu_detile()
                    {
                        achiname = userdata_info[0]["achiname"].Value <string>(),
                        amount   = userdata_info[0]["amount"].Value <string>(),
                        outline  = "折翼天使"
                    };
                    detail.Add(a);

                    listbox_chengjiu.ItemsSource = detail;
                }
            };
            proxy.DownloadStringAsync(new Uri("http://cxds.sysu.me/user/achievement", UriKind.Absolute));
        }
Example #3
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (answer == userAns)
            {
                ToastPhoto.Source     = new BitmapImage(new Uri("images/correct.png", UriKind.Relative));
                ToastPhoto.Visibility = Visibility.Visible;
                Story.Begin();
            }
            else
            {
                ToastPhoto.Source     = new BitmapImage(new Uri("images/incorrect.png", UriKind.Relative));
                ToastPhoto.Visibility = Visibility.Visible;
                Story.Begin();
            }
            postAnswer.Add("uid", userAns);
            postAnswer.Add("publish", App.Check);
            PostClient pc = new PostClient(postAnswer);

            pc.DownloadStringCompleted += pc_DownloadStringCompleted;
            pc.DownloadStringAsync(new Uri("http://facebookfriendsquiz.appspot.com/choose", UriKind.Absolute));
            VarOneFrame.Source   = new BitmapImage(new Uri("images/photo.png", UriKind.Relative));
            VarTwoFrame.Source   = new BitmapImage(new Uri("images/photo.png", UriKind.Relative));
            VarThreeFrame.Source = new BitmapImage(new Uri("images/photo.png", UriKind.Relative));
            nextButton.IsEnabled = false;
            postAnswer.Clear();
            getQuestions();
        }
Example #4
0
        public void login_message()
        {
            this.progressBar1.IsIndeterminate = true;
            this.progressBar1.Visibility      = System.Windows.Visibility.Visible;
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("username", "8785169");
            parameters.Add("password", password.Text);
            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    JObject userobj = JObject.Parse(e.Result);
                    if (userobj["info"].ToString() == "success")
                    {
                        //NavigationService.Navigate(new Uri("/mail.xaml", UriKind.Relative));
                        this.progressBar1.IsIndeterminate = false;
                        this.progressBar1.Visibility      = System.Windows.Visibility.Collapsed;
                        NavigationService.GoBack();
                    }
                }
            };
            proxy.DownloadStringAsync(new Uri("http://cxds.sysu.me/user/login", UriKind.Absolute));
        }
Example #5
0
        public ActionResult GestionUserPoster(int id, int idCiudad, int idPais, string nombreEmpresa, string contra, string email, DateTime fechaCreacion, string calle, string ciudad, string pais)
        {
            PostClient        posts         = new PostClient();
            var               elementoPosts = posts.GetUserPoster(id);
            TipoTrabajoClient tipo          = new TipoTrabajoClient();
            CategoriaClient   categoria     = new CategoriaClient();
            CiudadClient      ciudadClient  = new CiudadClient();
            PaisClient        paisClient    = new PaisClient();
            var               e             = new List <Post>();

            foreach (var i in elementoPosts)
            {
                i.TipoTrabajos = tipo.Get(i.NombreTipoTrabajo).Nombre;
                i.Categorias   = categoria.Get(i.NombreCategoria).Nombre;
                i.Ciudades     = ciudadClient.Get(i.NombreCiudad).Nombre;
                i.Paises       = paisClient.Get(i.NombrePais).Nombre;
                e.Add(i);
            }

            ViewBag.IdPais        = idPais;
            ViewBag.IdCiudad      = idCiudad;
            ViewBag.Contra        = contra;
            ViewBag.Empresa       = nombreEmpresa;
            ViewBag.Pais          = pais;
            ViewBag.Ciudad        = ciudad;
            ViewBag.Fecha         = fechaCreacion;
            ViewBag.Calle         = calle;
            ViewBag.IdPoster      = id;
            ViewBag.Correo        = email;
            ViewBag.ListPosts     = e.OrderByDescending(p => p.FechaCreacion);
            ViewBag.CantidadPosts = elementoPosts.Count();
            return(View(ViewBag.ListPosts));
        }
        public ActionResult ProfileAcc()
        {
            UserPosterClient poster    = new UserPosterClient();
            CategoriaClient  categoria = new CategoriaClient();
            PostClient       post      = new PostClient();
            PaisClient       pais      = new PaisClient();
            CiudadClient     ciudad    = new CiudadClient();
            var elementoPais           = pais.GetAll();
            var elementoCiudad         = ciudad.GetAll();
            var elementoPoster         = poster.GetAll();
            var elementoCategoria      = categoria.GetAll();
            var elementov     = elementoPoster.Single(x => x.Email == User.Identity.Name);
            var elementoposts = post.GetAll().Where(c => c.Poster == elementov.Id);

            ViewBag.Cuenta     = elementov;
            ViewBag.CountPosts = elementoposts.Count();

            elementoCategoria = elementoCategoria.OrderByDescending(x => x.Cantidad);
            var e = new List <Post>();

            foreach (var i in elementoposts)
            {
                i.Categorias = elementoCategoria.Single(x => x.Id == i.NombreCategoria).Nombre;
            }

            elementov.Paises   = elementoPais.Single(x => x.Id == elementov.NombrePais).Nombre;
            elementov.Ciudades = elementoCiudad.Single(x => x.Id == elementov.NombreCiudad).Nombre;

            ViewBag.ListPosts = elementoposts;
            ViewBag.Country   = elementov.Paises;
            ViewBag.City      = elementov.Ciudades;
            return(View());
        }
Example #7
0
        /// <summary>
        /// Request a new device key registered to a specific API key.
        /// </summary>
        /// <param name="apiKey">The API key.</param>
        /// <returns>
        /// <c>true</c>: When request suceeded
        /// <c>false</c>: When request failed
        /// </returns>
        public void RequestDevKey()
        {
            string uriPath        = settings.mainServer + "/api/service/request-device-key";
            string responseResult = null;
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("api_key", this.apiKey);

            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    //save the response/result
                    responseResult = e.Result;
                    if (responseResult != null)
                    {
                        //store the device key
                        settings.DeviceKey = responseResult;
                        DeviceKeyStatus(this, new GeopAppApiEventArgs("Device Key reccieved"));
                    }
                    else
                    {
                        DeviceKeyStatus(this, new GeopAppApiEventArgs(new Exception("Error retrieving device key")));
                    }
                }
                else
                {
                    DeviceKeyStatus(this, new GeopAppApiEventArgs(new Exception("Error retrieving device key")));
                }
            };
            proxy.DownloadStringAsync(new Uri(uriPath, UriKind.Absolute));
        }
Example #8
0
        public void TestInitialize()
        {
            TestName = TestContext.TestName;
            Browser  = new Browser();
            Browser.StartWebDriver();
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TestLogPath")))
            {
                Logger = new LoggerHelper(@"C:\TestResults", $"/file{TestName}");
            }
            else
            {
                Logger = new LoggerHelper(Environment.GetEnvironmentVariable("TestLogPath"), $"/file{TestName}");
            }
            Pages        = new Pages(Browser, Logger);
            AssertHelper = new AssertHelper(Logger);
            PostClient   = PostClient.GetInstance(Logger);

            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TestLogPath")))
            {
                if (File.Exists(@"C:\TestResults" + $"/file{TestName}.txt"))
                {
                    File.Delete(@"C:\TestResults" + $"/file{TestName}.txt");
                }
            }
            else
            {
                File.Delete(Environment.GetEnvironmentVariable("TestLogPath") + $"/file{TestName}.txt");
            }
        }
        private void ProcessOutgoingMessageChat2Desk(OutgoingMessage request)
        {
            var chat2deskToken = WebConfigurationManager.AppSettings["chat2deskToken"];

            if (request.ClientId == null)
            {
                //post client with phone
                if (request.Phone != null && request.ContactId != null)
                {
                    using (WebClient client = new WebClient())
                    {
                        var postClient = new PostClient()
                        {
                            Phone     = request.Phone,
                            Transport = request.Transport
                        };

                        client.Encoding = Encoding.UTF8;
                        client.Headers["Content-type"]  = "application/json";
                        client.Headers["Authorization"] = chat2deskToken;
                        var urlString = "https://api.chat2desk.com/v1/clients";

                        var responseJson = client.UploadString(urlString, "POST", postClient.ToJson());

                        var response = PostClientResponse.FromJson(responseJson);

                        if (response.Status == "success")
                        {
                            var newClientId = response.Data.Id;

                            request.ClientId = newClientId.ToString();

                            var crmHelper = new CRM.CrmHelper();
                            crmHelper.UpdateContactWithClientId(request.ContactId, newClientId.ToString());
                        }
                    }
                }
            }


            if (request.ClientId != null)
            {
                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    client.Headers["Content-type"]  = "application/json";
                    client.Headers["Authorization"] = chat2deskToken;
                    var urlString = "https://api.chat2desk.com/v1/messages";

                    var responseJson = client.UploadString(urlString, "POST", request.ToJson());

                    var response = PostMessageChat2DeskResponse.FromJson(responseJson);
                }
            }
            else
            {
                throw new Exception("Сообщение не может быть отправлено, отсутствует ID клиента");
            }
        }
Example #10
0
 public Servico(PerfilClient perfilClient,
                PostClient postClient,
                CompartilhamentoClient compartilhamentoClient)
 {
     this.perfilClient           = perfilClient;
     this.postClient             = postClient;
     this.compartilhamentoClient = compartilhamentoClient;
 }
Example #11
0
        private void iconSend_Click(object sender, EventArgs e)
        {
            string title   = txtTitle.Text.Trim( );
            string content = txtContent.Text.Trim( );

            if (title.Length == 0)
            {
                MessageBox.Show("标题请不要为空");
                return;
            }
            if (content.Length == 0)
            {
                MessageBox.Show("问题内容请不要为空");
                return;
            }
            (this as WP7_ControlsLib.Controls.ProgressTrayPage).LoadingText = "正在提交";
            (this as WP7_ControlsLib.Controls.ProgressTrayPage).ProgressIndicatorIsVisible = true;
            Dictionary <string, object> parameters = new Dictionary <string, object>
            {
                { "uid", Config.UID },
                { "title", title },
                { "catalog", this.pickerPostType.SelectedIndex + 1 },
                { "content", content },
                { "isNoticeMe", (bool)this.checkEmailNoticeMe.IsChecked ? "1" : "0" },
            };
            PostClient client = Tool.SendPostClient(Config.api_post_pub, parameters);

            client.DownloadStringCompleted += (s, e1) =>
            {
                (this as WP7_ControlsLib.Controls.ProgressTrayPage).ProgressIndicatorIsVisible = false;
                if (e1.Error != null)
                {
                    System.Diagnostics.Debug.WriteLine("发表问题时网络错误: {0}", e1.Error.Message);
                    return;
                }
                else
                {
                    ApiResult result = Tool.GetApiResult(e1.Result);
                    if (result != null)
                    {
                        switch (result.errorCode)
                        {
                        case 1:
                            Config.ClearCacheQuestion( );
                            MessageBox.Show("问答发布成功");
                            Tool.To(string.Format("/PostsPage.xaml?catalog={0}", this.pickerPostType.SelectedIndex + 1));
                            break;

                        case 0:
                        case -1:
                        case -2:
                            MessageBox.Show(result.errorMessage, "温馨提示", MessageBoxButton.OK);
                            break;
                        }
                    }
                }
            };
        }
Example #12
0
        // 心路历程信息获取
        public void get_message()
        {
            List <user> xinlu_list = new List <user>();
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("username", "8785169");
            parameters.Add("date", "2011/12/16");

            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    JObject userobj       = JObject.Parse(e.Result);
                    int     i             = 2;
                    JObject userdata_info = (JObject)userobj["detail"];
                    JArray  mess2011      = (JArray)userdata_info["1"];
                    JArray  mess2012      = (JArray)userdata_info["2"];
                    int     p             = 0;
                    foreach (var obj in mess2011)
                    {
                        i = (i + 2) % 4;
                        user a = new user()
                        {
                            pid      = obj["id"].Value <string>(),
                            content  = obj["content"].Value <string>(),
                            posttime = obj["posttime"].Value <string>(),
                            source   = "",
                            source2  = "",
                            title    = obj["title"].Value <string>(),
                            color1   = col[i],
                            color2   = col[i + 1]
                        };
                        if (mess2012.Count == 0 || p > mess2012.Count - 1)
                        {
                            a.pid2      = "";
                            a.posttime2 = obj["posttime"].Value <string>();
                            a.content2  = "今天没有消息";
                        }
                        else
                        {
                            a.pid2      = mess2012[p]["id"].Value <string>();
                            a.posttime2 = mess2012[p]["posttime"].Value <string>();
                            a.content2  = mess2012[p]["content"].Value <string>();
                        }
                        p++;

                        xinlu_list.Add(a);
                    }

                    listBox_xinlu.ItemsSource = xinlu_list;
                }
            };
            proxy.DownloadStringAsync(new Uri("http://cxds.sysu.me/post/get", UriKind.Absolute));
        }
Example #13
0
        static void Main(string[] args)
        {
            #region Take() Explained
            //List<string> names = new List<string>
            //{
            //    "Martin",
            //    "Ivo",
            //    "Dejan",
            //    "Stefan",
            //    "Irina",
            //    "Mimi",
            //    "Marko",
            //};

            //var namesStartWithM = names.Where(x => x.StartsWith('M'))
            //                                    .OrderByDescending(x => x)
            //                                    .Take(1)
            //                                    .FirstOrDefault();
            //Console.WriteLine(namesStartWithM);
            #endregion

            try
            {
                string allPostsUrl   = "https://api.posts/posts/all";
                string singlePostUrl = "https://api.posts/posts/martin";

                List <Post> allPosts = PostClient.GetAll(allPostsUrl);

                Post singlePost = PostClient.Get(singlePostUrl);

                allPosts.ForEach(x => Console.WriteLine(x.Title));
                Console.WriteLine("________________________________");
                Console.WriteLine($"Single post: {singlePost.Title}");
            }
            catch (BadRequestException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Message: {ex.Message} | StatusCode: {ex.StatusCode}");
            }
            catch (NotFoundException ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine($"Message: {ex.Message} | StatusCode: {ex.StatusCode}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Message: {ex.Message}");
            }


            Console.WriteLine("This will work after the exception is thrown!");

            Console.ReadLine();
        }
        public ActionResult Busqueda(string buscar, string sortOrder, string sortBy, int pageNumber = 1)
        {
            PostClient        postClient        = new PostClient();
            CategoriaClient   categoriaClient   = new CategoriaClient();
            UserPosterClient  userPoster        = new UserPosterClient();
            CiudadClient      ciudad            = new CiudadClient();
            PaisClient        pais              = new PaisClient();
            TipoTrabajoClient tipoTrabajoClient = new TipoTrabajoClient();
            var elementos = postClient.GetAll();
            var e         = new List <Post>();
            var j         = new Post();
            var lista     = e;

            if (elementos != null)
            {
                foreach (var i in elementos)
                {
                    i.Posters      = userPoster.FindPost(i.Poster);
                    i.Categorias   = categoriaClient.FindCategory(i.NombreCategoria);
                    i.Ciudades     = ciudad.FindCiudad(i.NombreCiudad);
                    i.Paises       = pais.FindPais(i.NombrePais);
                    i.TipoTrabajos = tipoTrabajoClient.FindTipoTrabajo(i.NombreTipoTrabajo);
                    e.Add(i);
                }



                if (buscar != null)
                {
                    buscar = buscar.ToUpper();
                    var v = (from a in e
                             where a.Categorias.ToUpper().Contains(buscar) ||
                             a.Posters.ToUpper().Contains(buscar) ||
                             a.NombrePosicion.ToUpper().Contains(buscar) ||
                             a.Paises.ToUpper().Contains(buscar) ||
                             a.Ciudades.ToUpper().Contains(buscar)
                             select a);
                    lista = v.ToList();
                    lista = ApplySorting(sortOrder, sortBy, lista);
                    lista = ApplyPagination(pageNumber, lista);
                }
                else
                {
                    lista = ApplySorting(sortOrder, sortBy, lista);
                    lista = ApplyPagination(pageNumber, lista);
                }
            }


            ViewBag.Buscar = buscar;

            return(View(lista));
        }
Example #15
0
        void weibolongin(string user, string password)
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("username", "8785169");
            parameters.Add("password", "8785169");
            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    if (e.Result == "")
                    {
                        MessageBox.Show("亲,你的网络可能有问题了。");
                        this.progressBar1.IsIndeterminate = false;
                    }
                    else
                    {
                        try {
                            JObject userobj = JObject.Parse(e.Result);
                            if (userobj["info"].ToString() == "success")
                            {
                                this.progressBar1.IsIndeterminate = false;
                                this.progressBar1.Visibility      = System.Windows.Visibility.Collapsed;
                                //if (((JObject)((JObject)userobj["detail"])["detail"]).ToString() == "[]")
                                //{
                                NavigationService.Navigate(new Uri("/daohang/weiboshouquan.xaml", UriKind.Relative));
                                //}
                                //else
                                //{
                                //    NavigationService.Navigate(new Uri("/main.xaml", UriKind.Relative));
                                //}
                            }
                            else
                            {
                                this.progressBar1.IsIndeterminate = false;
                                this.progressBar1.Visibility      = System.Windows.Visibility.Collapsed;
                                MessageBox.Show("用户名或密码错误");
                            }
                        }
                        catch
                        {
                            MessageBox.Show("亲,你的网络可能有问题了。");

                            this.progressBar1.IsIndeterminate = false;
                            this.progressBar1.Visibility      = System.Windows.Visibility.Collapsed;
                        }
                    }
                }
            };
            proxy.DownloadStringAsync(new Uri("http://cxds.sysu.me/user/login", UriKind.Absolute));
        }
        public ActionResult EliminarPost(int id)
        {
            PostClient postClient = new PostClient();

            postClient.Delete(id);
            if (User.IsInRole("Admin"))
            {
                return(RedirectToAction("BusquedaUserPoster", "UserAdmin"));
            }
            else
            {
                return(RedirectToAction("ProfileAcc"));
            }
        }
        public ActionResult GetImage(int id)
        {
            PostClient post   = new PostClient();
            var        imagen = post.Get(id);

            try
            {
                return(File(imagen.Logo, "image/jpg"));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #18
0
        public void CRUD()
        {
            //À noter que je n'ai encore jamais développé sérieusement d'application en utilisant Visual Studio
            //Ce problème est donc assez peu représentatif de mon niveau en C#, ayant été majoritairement bloqué par la systémique de cette application.
            //Explications:
            //1) J'ai réussi à installer correctement ServiceStack et ormlite (à partir du PMC que je ne connaissais pas)
            //2) Je ne peux pas suivre le tutoriel ServiceStack correctement puisqu'une erreur m'empêche de créer un nouveau projet servicestack complet, le premier projet refusant de se créer.
            //(après 10 - 15 minutes de recherche sur l'erreur j'ai préféré abadonner et essayer de comprendre moi même l'arborescence).
            //3) De ce que j'ai compris:
            // -La classe "Client" de .ServiceModel comporte toutes les informations d'un client. Son constructeur permet de renseigner le nom et prénom, l'ID et la date de création devant être déterminée par le code.
            // -La classe "GetClient" de .ServiceModel sert à récupérer une ID (pour la comparer avec une ID client plus tard dans la méthode CRUD je suppose)
            //4) Je n'arrive pas à comprendre comment modifier l'interface client, je ne vois aucun fichier html/js et ne sait pas où en créer. La documentation ( http://docs.servicestack.net/csharp-client#jsonhttpclient ) ne m'aide pas à cet égard
            //5) De fait, je ne peux pas tester le fait de rentrer un nom/prénom et comprendre comment les infos s'agencent dans le code.
            //6) J'ai tenté de partiellement répondre au problème en implémentant les algorithmes de manière artificielle ci dessous. Je ne suis pas sûr de ce que représentent les étapes ci dessous

            // !! Je suis conscient que les classes que j'instancie ici sont vides, mais je ne sais pas comment récupérer les informations rentrées à partir de l'application elle même !!
            // Tester le post
            Client     NvClient   = new Client();
            PostClient PostClient = new PostClient();

            if (NvClient.FirstName == PostClient.FirstName && NvClient.LastName == PostClient.LastName)
            {
                //validation
            }
            else
            {
                //erreur
            }

            // Vérfier l'identifiant retourné
            GetClient getclient = new GetClient(NvClient.ID);

            if (NvClient.ID == getclient.ID)
            {
                //validation
            }
            else
            {
                //erreur
            }

            // Tester le put

            // Tester le get

            // Vérifier que le put a bien été appliqué

            // Test le delete
        }
        public ActionResult EditarPost(Post c, HttpPostedFileBase imagenSisi)
        {
            PostClient postClient = new PostClient();

            if (imagenSisi != null && imagenSisi.ContentLength > 0)
            {
                byte[] imagenData = null;
                using (var bynaryImage = new BinaryReader(imagenSisi.InputStream))
                {
                    imagenData = bynaryImage.ReadBytes(imagenSisi.ContentLength);
                }
                c.Logo = imagenData;
            }
            else
            {
                var imagen = postClient.Get(c.Id);
                c.Logo = imagen.Logo;
            }

            if (c.NombreCategoria == 0)
            {
                return(EditarPost("Debes seleccionar una Categoria."));
            }
            else if (c.NombrePais == 0 || c.NombreCiudad == 0)
            {
                return(EditarPost("Debes seleccionar un pais y su ciudad correspondiente."));
            }
            else if (c.NombreTipoTrabajo == 0)
            {
                return(EditarPost("Debes seleccionar un tipo de Trabajo."));
            }
            else
            {
                if (ModelState.IsValid)
                {
                    postClient.Update(c);
                    return(RedirectToAction("ProfileAcc"));
                }
                else
                {
                    return(View(c));
                }
            }
        }
Example #20
0
        /// <summary>
        /// Registers the specified device.
        /// </summary>
        /// <param name="deviceKey">The device key.</param>
        /// <param name="deviceName">Name of the device.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        public void RegisterDevice(string deviceName, string username, string password)
        {
            string uriPath        = settings.mainServer + "/api/device/register";
            string responseResult = null;
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            if (this.deviceKey != null)
            {
                parameters.Add("device_key", this.deviceKey);
            }
            else
            {
                return;
            }

            parameters.Add("device_name", deviceName);
            parameters.Add("username", username);
            parameters.Add("password", password);

            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    //save the response/result
                    responseResult = e.Result;
                    if (responseResult != null)
                    {
                        settings.DeviceId = responseResult;
                        RegisterStatus(this, new GeopAppApiEventArgs("Successfully Registered"));
                    }
                    else
                    {
                        RegisterStatus(this, new GeopAppApiEventArgs(new Exception("Failed to register")));
                    }
                }
                else
                {
                    RegisterStatus(this, new GeopAppApiEventArgs(new Exception("Failed to register")));
                }
            };
            proxy.DownloadStringAsync(new Uri(uriPath, UriKind.Absolute));
        }
Example #21
0
        /// <summary>
        /// Adds a location region with an associated name.
        /// </summary>
        /// <param name="deviceId">A 32-character device API key assigned to the device when it was registered.</param>
        /// <param name="latitude">The latitude of the location region.</param>
        /// <param name="longitude">The longitude of the location region.</param>
        /// <param name="name">The given name to this region.</param>
        /// <param name="time">(OPTIONAL, NULLABLE)The time the update took place.</param>
        /// <param name="radius">(OPTIONAL, NULLABLE)The radius of the circular area which should be considered part of this region.</param>
        /// <returns>
        /// <c>true</c>: When request suceeded
        /// <c>false</c>: When request failed
        /// </returns>
        public void AddRegion(string latitude, string longitude, string name, string time, string radius)
        {
            string uriPath        = settings.mainServer + "/api/device/add-region";
            string responseResult = null;
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("device_id", this.deviceId);
            parameters.Add("latitude", latitude);
            parameters.Add("longitude", longitude);
            parameters.Add("name", name);
            //Check for optinal values (NULLABLE)
            if (time != null)
            {
                parameters.Add("time", time);
            }
            if (radius != null)
            {
                parameters.Add("radius", radius);
            }

            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    //Process the result
                    responseResult = e.Result;
                    if (responseResult.Contains("OK"))
                    {
                        AddRegionStatus(this, new GeopAppApiEventArgs("Added Region"));
                    }
                    else
                    {
                        AddRegionStatus(this, new GeopAppApiEventArgs(new Exception("Failed to add region")));
                    }
                }
                else
                {
                    AddRegionStatus(this, new GeopAppApiEventArgs(new Exception("Failed to add region")));
                }
            };
            proxy.DownloadStringAsync(new Uri(uriPath, UriKind.Absolute));
        }
        public void SendRequest()
        {
            PostClient proxy = new PostClient(this.PrepareParams());

            proxy.Method = this.Method;
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    string data = e.Result;
                    this.OnRequestComplete.Invoke(this, data);
                }
                else
                {
                    this.OnRequestComplete.Invoke(this, null);
                }
            };
            proxy.DownloadStringAsync(new Uri(this.GetServerName(), UriKind.Absolute));
        }
        public ActionResult CrearPost(Post c, HttpPostedFileBase imagenSisi)
        {
            UserPosterClient posterClient = new UserPosterClient();
            var elemento = posterClient.FindByCorreo(User.Identity.Name);

            c.Poster = elemento.Id;
            PostClient postClient = new PostClient();

            if (imagenSisi != null && imagenSisi.ContentLength > 0)
            {
                byte[] imagenData = null;
                using (var bynaryImage = new BinaryReader(imagenSisi.InputStream))
                {
                    imagenData = bynaryImage.ReadBytes(imagenSisi.ContentLength);
                }
                c.Logo = imagenData;
            }

            if (c.NombreCategoria == 0)
            {
                return(CrearPost("Debes seleccionar una Categoria."));
            }
            else if (c.NombrePais == 0 || c.NombreCiudad == 0)
            {
                return(CrearPost("Debes seleccionar un pais y su ciudad correspondiente."));
            }
            else if (c.NombreTipoTrabajo == 0)
            {
                return(CrearPost("Debes seleccionar un tipo de Trabajo."));
            }
            else
            {
                if (ModelState.IsValid)
                {
                    postClient.Add(c);
                    return(RedirectToAction("ProfileAcc"));
                }
                else
                {
                    return(View(c));
                }
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            try
            {
                string allPostUrl    = "https://api.posts/posts/all";
                string singlePostUrl = "https://api.posts/posts/martin";

                List <Post> allPosts = PostClient.GetAll(allPostUrl);

                Post singlePost = PostClient.Get(singlePostUrl);

                allPosts.ForEach(x =>
                {
                    Console.WriteLine($"Title: {x.Title}");
                    Console.WriteLine($"Content: {x.Content}");
                    Console.WriteLine($"Post by: {x.CreatedBy}");
                    Console.WriteLine("--------------------------------");
                });

                Console.WriteLine("---------------- Single post with id: 1 -------------------");
                Console.WriteLine($"Title: {singlePost.Title}");
                Console.WriteLine($"Content: {singlePost.Content}");
                Console.WriteLine($"Post by: {singlePost.CreatedBy}");
                Console.WriteLine("--------------------------------");
            }
            catch (BadRequestException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Message: {ex.Message} | StatusCode: {ex.StatusCode}");
            }
            catch (NotFoundException ex)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"Message: {ex.Message} | StatusCode: {ex.StatusCode}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Message: {ex.Message}");
            }


            Console.ReadLine();
        }
        protected void Button1Click(object sender, EventArgs e)
        {
            var p = new PostClient();

            var c = (from ListItem item in CheckBoxList1.Items where item.Selected select new Categoria {Codigo= Int32.Parse(item.Value), Descricao = item.Text}).ToArray();

            var obj = new Post
                          {
                              Titulo = TextBox1.Text,
                              Conteudo = Editor1.Content,
                              CodigoUsuario = Convert.ToInt32(((Usuario)Session["USUARIO"]).Codigo),
                              DataLiberacao = Convert.ToDateTime(TextBox2.Text),
                              Categorias = c,
                              Privado = CheckBox1.Checked ? 'S' : 'N'
                          };

            p.Inserir(obj);

            Response.Redirect("~/Default.aspx");
        }
Example #26
0
 public static PostClient SendPostClient(string urlPrefix, Dictionary<string, object> parameters)
 {
     /*
      * WP7 会缓存相同url 的返回结果 所以这里需要添加 guid 参数
      */
     if ( parameters != null && parameters.ContainsKey("guid") == false)
     {
         parameters. Add( "guid", Guid. NewGuid( ). ToString( ) );
     }
     PostClient client = new PostClient( parameters )
     {
         UserAgent = Config. UserAgent,
     };
     //抓取到 Cookie
     client. OnGetCookie += (cookie) =>
     {
         Config. Cookie = cookie;
     };
     client. DownloadStringAsync( new Uri( urlPrefix, UriKind. Absolute ), Config. Cookie.EnsureNotNull() );
     return client;
 }
        protected void Button1Click(object sender, EventArgs e)
        {
            var p = new PostClient();

            var c = (from ListItem item in CheckBoxList1.Items where item.Selected select new Categoria {
                Codigo = Int32.Parse(item.Value), Descricao = item.Text
            }).ToArray();

            var obj = new Post
            {
                Titulo        = TextBox1.Text,
                Conteudo      = Editor1.Content,
                CodigoUsuario = Convert.ToInt32(((Usuario)Session["USUARIO"]).Codigo),
                DataLiberacao = Convert.ToDateTime(TextBox2.Text),
                Categorias    = c,
                Privado       = CheckBox1.Checked ? 'S' : 'N'
            };

            p.Inserir(obj);

            Response.Redirect("~/Default.aspx");
        }
Example #28
0
        public void TestInitialize()
        {
            TestName = TestContext.TestName;
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TestLogPath")))
            {
                Logger = new LoggerHelper(@"C:\TestResults", $"/{TestName}");
            }
            else
            {
                Logger = new LoggerHelper(Environment.GetEnvironmentVariable("TestLogPath"), $"/{TestName}");
            }
            AssertHelper = new AssertHelper(Logger);
            PostClient   = PostClient.GetInstance(Logger);

            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TestLogPath")))
            {
                File.Delete(@"C:\TestResults" + $"/{TestName}.txt");
            }
            else
            {
                File.Delete(Environment.GetEnvironmentVariable("TestLogPath") + $"/{TestName}.txt");
            }
        }
Example #29
0
        public ActionResult ProfileAcc()
        {
            UserPosterClient poster    = new UserPosterClient();
            UserAdminClient  admin     = new UserAdminClient();
            CategoriaClient  categoria = new CategoriaClient();
            PostClient       post      = new PostClient();
            CiudadClient     ciudad    = new CiudadClient();
            var elementoCiudad         = ciudad.GetAll();
            var elementoPoster         = poster.GetAll();
            var elementoCategoria      = categoria.GetAll();
            var elementoAdmin          = admin.GetAll();

            ViewBag.Cuenta = elementoAdmin.Single(x => x.Usuario == User.Identity.Name);

            ViewBag.CountPosters    = elementoPoster.Count();
            ViewBag.CountAdmins     = admin.GetAll().Count();
            ViewBag.CountCategorias = elementoCategoria.Count();
            ViewBag.CountPosts      = post.GetAll().Count();

            elementoCategoria      = elementoCategoria.OrderByDescending(x => x.Cantidad);
            ViewBag.ListCategorias = elementoCategoria;
            ViewBag.MaxCategoria   = elementoCategoria.First().Nombre;

            var v = (from a in elementoPoster
                     where a.FechaCreacion.Day == DateTime.Now.Day
                     select a
                     );

            ViewBag.CountRPostersT = v.Count();
            elementoCiudad         = elementoCiudad.OrderByDescending(x => x.Cantidad);
            ViewBag.MaxCityPosters = elementoCiudad.First().Nombre;



            return(View());
        }
Example #30
0
        /// <summary>
        /// Checkins the specified latitude.
        /// </summary>
        /// <param name="latitude">The latitude.</param>
        /// <param name="longitude">The longitude.</param>
        /// <param name="time">The time.</param>
        /// <param name="devId">The dev id.</param>
        /// <returns>
        /// <c>true</c>: When request suceeded
        /// <c>false</c>: When request failed
        /// </returns>
        public void CheckIn(string latitude, string longitude, string time)
        {
            string responseResult = null;
            string uriPath        = settings.mainServer + "/api/device/check-in";

            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("device_id", this.deviceId);
            parameters.Add("latitude", latitude);
            parameters.Add("longitude", longitude);
            parameters.Add("time", time);

            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    //Process the result
                    responseResult = e.Result;
                    if (responseResult.Contains("OK"))
                    {
                        CheckInStatus(this, new GeopAppApiEventArgs("Sucessfully Checked In"));
                    }
                    else
                    {
                        CheckInStatus(this, new GeopAppApiEventArgs(new Exception("Failed to Check-in")));
                    }
                }
                else
                {
                    CheckInStatus(this, new GeopAppApiEventArgs(new Exception("Failed to Check-in")));
                }
            };
            proxy.DownloadStringAsync(new Uri(uriPath, UriKind.Absolute));
        }
        void weibolongin(string user, string password)
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("username", "8785169");
            parameters.Add("type", "weibo");
            parameters.Add("token", App.AccessToken);
            PostClient proxy = new PostClient(parameters);

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    if (e.Result == "")
                    {
                        MessageBox.Show("亲,你的网络可能有问题了。");
                    }
                    else
                    {
                        try
                        {
                            JObject userobj = JObject.Parse(e.Result);
                            if (userobj["info"].ToString() == "success")
                            {
                                MessageBox.Show("微博授权成功,可以进入应用了,也可以进行人人授权");
                            }
                        }
                        catch
                        {
                            MessageBox.Show("亲,你的网络可能有问题了。");
                        }
                    }
                }
            };
            proxy.DownloadStringAsync(new Uri("http://cxds.sysu.me/user/impower", UriKind.Absolute));
        }
        public void Test_PostAndRead()
        {
            StartWebApplication ();

            var folderName = "myFolder";
            var securityKey = "myKey";

            InsertKey (folderName, securityKey);

            var host = "localhost";
            var port = AppStarter.Port;

            var client = new PostClient (host, port);

            var content = "Hello world";

            var fileName = "TestFile.txt";

            client.Post (content, fileName, folderName, securityKey);

            var foundContent = client.Read (fileName, folderName);

            Assert.AreEqual (content, foundContent);
        }
Example #33
0
 public void PostCheck()
 {
     PostClient.Auth();
 }