상속: System.Web.UI.Page
예제 #1
0
        private WebCall(string url, Cookies cookies, string host = null, int? port = null)
        {
            Request = (HttpWebRequest)WebRequest.Create(url);
            Request.Accept = "text/html";
            Request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
            Request.CookieContainer = cookies.Container;

            if (host != null && port != null)
                Request.Proxy = new WebProxy(host, port.Value);

            Result = new WebCallResult(url, cookies);
        }
예제 #2
0
 public void SetMessage(string message)
 {
     Cookies.SetValue("message", Data.Base64Encode(message));
 }
예제 #3
0
 public MedicalHistoryRepository()
 {
     _communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #4
0
        /// <summary>
        /// 运行QQClient主逻辑,推荐放在独立的线程中执行这个方法
        /// </summary>

        // ----------0.利用cookie文件登录

        public void ReLink()
        {
            string loginuser = api.ReadTextFile(Environment.CurrentDirectory, "user\\user.ini");

            Debug.Write(loginuser);

            if (!string.IsNullOrEmpty(loginuser))
            {
                if (File.Exists(Path.Combine(Environment.CurrentDirectory + "\\user\\" + loginuser, cookiesFileName)))
                {
                    LoginCookies = JsonConvert.DeserializeObject <Cookies>(File.ReadAllText(Path.Combine(Environment.CurrentDirectory + "\\user\\" + loginuser, cookiesFileName)));
                    BeginReLogin?.Invoke();
                    string Ptwebqq = LoginCookies.ptwebqq;
                    string Status  = LoginCookies.status;
                    string Skey    = LoginCookies.skey;
                    string Uin     = LoginCookies.uin;
                    string P_skey  = LoginCookies.p_skey;
                    string P_uin   = LoginCookies.p_uin;

                    if (Ptwebqq != "")
                    {
                        string ReLoginResult = api._login_by_cookie(Ptwebqq, Status, Skey, Uin, P_skey, P_uin);
                        if (ReLoginResult != null)
                        {
                            JObject ReLogin = (JObject)JsonConvert.DeserializeObject(ReLoginResult);
                            if (ReLogin["retcode"].ToString() == "0")
                            {
                                LoginResult.psessionid = ReLogin["result"]["psessionid"].ToString();
                                Debug.Write("psessionid=" + LoginResult.psessionid);

                                LoginResult.qq = ReLogin["result"]["uin"].ToString();
                                Debug.Write("uin=" + LoginResult.qq);

                                LoginResult.ptwebqq = Ptwebqq;

                                string[] namelist = { "skey", "uin", "p_skey", "p_uin" };

                                List <string> CookieList = api.GetCookies(namelist);


                                LoginCookies.skey = CookieList[0].ToString();
                                Debug.Write("skey=" + LoginCookies.skey);

                                LoginCookies.uin = CookieList[1].ToString();
                                Debug.Write("uin=" + LoginCookies.uin);

                                LoginCookies.p_skey = CookieList[2].ToString();
                                Debug.Write("p_skey=" + LoginCookies.p_skey);

                                LoginCookies.p_uin = CookieList[3].ToString();
                                Debug.Write("p_uin=" + LoginCookies.p_uin);

                                api.CookieProxy(LoginCookies.p_skey, LoginCookies.p_uin);
                                IsLogin = true;
                                OnLoginSucess?.Invoke();
                            }
                            else
                            {
                                Debug.Write("返回值错误 errmsg:error!!!,retcode:100001");
                                ReLoginFail?.Invoke();

                                Login();
                            }
                        }
                        else
                        {
                            Debug.Write("服务器无返回");
                        }
                    }
                    else
                    {
                        Debug.Write("Cookie文件无效");
                        ReLoginFail?.Invoke();

                        Login();
                    }
                }
                else
                {
                    Debug.Write("Cookie文件不存在");
                    ReLoginFail?.Invoke();

                    Login();
                }
            }
            else
            {
                Debug.Write("user.ini文件无效");
                ReLoginFail?.Invoke();
                Login();
            }
        }
예제 #5
0
 /// <summary>
 /// Evento que se lanza al cargar la página
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void Page_Load(object sender, EventArgs e)
 {
     //UsuarioBusiness.checkValidSession(this);
     Cookies.Set("osefTheme", ConfigurationManager.AppSettings["osefTheme"].ToString(), DateTime.Now.AddDays(30), "/", null, false);
 }
 /// <summary>
 /// Appends the specified <paramref name="cookie"/> to the cookies sent with the response.
 /// </summary>
 /// <param name="cookie">
 /// A <see cref="Cookie"/> to append.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="cookie"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// The response has already been sent.
 /// </exception>
 /// <exception cref="ObjectDisposedException">
 /// This object is closed.
 /// </exception>
 public void AppendCookie(Cookie cookie)
 {
     checkDisposedOrHeadersSent();
     Cookies.Add(cookie);
 }
예제 #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDirectReportsRepository"/> class.
 /// </summary>
 /// <param name="communicationManager">The communication manager.</param>
 public UserDirectReportsRepository()
 {
     _communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #8
0
        private void ReadSnackType(string path)
        {
            string line;
            bool finished = false;
            string[] lineValue;
            StreamReader sr = null;
            ISnacks snack = null;

            try
            {
                using (sr = new StreamReader(path))
                {
                    while (!(finished))
                    {
                        line = sr.ReadLine();

                        if (line != null)
                        {
                            lineValue = line.Split(',');

                            if (path == filePaths[0])
                                snack = new Chips(lineValue[0], lineValue[1], Convert.ToInt32(lineValue[2]), Convert.ToDouble(lineValue[3]));
                            else if (path == filePaths[1])
                                snack = new Chocolate(lineValue[0], lineValue[1], Convert.ToInt32(lineValue[2]), Convert.ToDouble(lineValue[3]));
                            else if (path == filePaths[2])
                                snack = new Cookies(lineValue[0], lineValue[1], Convert.ToInt32(lineValue[2]), Convert.ToDouble(lineValue[3]));
                            else if (path == filePaths[3])
                                snack = new Gum(lineValue[0], lineValue[1], Convert.ToInt32(lineValue[2]), Convert.ToDouble(lineValue[3]));

                            SnacksPresent.Add(snack);
                        }
                        else
                            finished = true;
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #9
0
        public ActionResult PostPolymericList()
        {
            string subject   = DoRequest.GetFormString("subject").Trim();
            string excelPath = DoRequest.GetFormString("excel").Trim();

            string   sdate     = DoRequest.GetFormString("sdate").Trim();
            int      shours    = DoRequest.GetFormInt("shours");
            int      sminutes  = DoRequest.GetFormInt("sminutes");
            DateTime startDate = Utils.IsDateString(sdate) ? DateTime.Parse(sdate + " " + shours + ":" + sminutes + ":00") : DateTime.Now;

            string   edate    = DoRequest.GetFormString("edate").Trim();
            int      ehours   = DoRequest.GetFormInt("ehours");
            int      eminutes = DoRequest.GetFormInt("eminutes");
            DateTime endDate  = Utils.IsDateString(edate) ? DateTime.Parse(edate + " " + ehours + ":" + eminutes + ":59") : DateTime.Now.AddDays(7);

            string summary = DoRequest.GetFormString("summary").Trim();

            if (subject.Length < 1)
            {
                return(Json(new { error = true, message = "请填写主题..." }));
            }
            if (subject.Length > 50)
            {
                return(Json(new { error = true, message = "主题不能超过50个字符..." }));
            }
            if (summary.Length > 500)
            {
                return(Json(new { error = true, message = "摘要不能超过500个字符..." }));
            }

            Robots _rbt = new Robots();

            System.Text.StringBuilder url = new System.Text.StringBuilder();
            url.Append(base._config.UrlHome + "Tools/ImportFromExcel?");
            url.Append(Cookies.CreateVerifyString());

            System.Text.StringBuilder postData = new System.Text.StringBuilder();
            postData.Append("subject=" + DoRequest.UrlEncode(AES.Encode(subject)));
            postData.Append("&excel=" + DoRequest.UrlEncode(AES.Encode(excelPath)));
            postData.Append("&sdate=" + startDate.ToString("yyyy-MM-dd HH:mm:ss"));
            postData.Append("&edate=" + endDate.ToString("yyyy-MM-dd HH:mm:ss"));
            postData.Append("&summary=" + DoRequest.UrlEncode(AES.Encode(summary)));

            string html = _rbt.Post(url.ToString(), postData.ToString(), "utf-8");

            if (_rbt.IsError)
            {
                return(Json(new { error = true, message = _rbt.ErrorMsg }));
            }
            if (string.IsNullOrEmpty(html))
            {
                return(Json(new { error = true, message = "远程页面无响应..." }));
            }

            ParseJson pJson = new ParseJson();
            SortedDictionary <string, string> list = pJson.Parse(html);
            bool isError = false;

            if (pJson.GetJsonValue(list, "error") == "true")
            {
                isError = true;
            }
            return(Json(new { error = isError, message = pJson.GetJsonValue(list, "message") }));
        }
예제 #10
0
        //--- Methods ---
        protected override Yield Start(XDoc config, Result result)
        {
            yield return(Coroutine.Invoke(base.Start, config, new Result()));

            // get the apikey, which we will need as a subscription auth token for subscriptions not done on behalf of a user
            _apikey = config["apikey"].AsText;

            // capture the wikiId of the wiki starting us
            string wikiId = config["wikiid"].AsText ?? "default";

            // set up plug deki, so we can validate users
            XUri dekiUri = config["uri.deki"].AsUri ?? new XUri("http://localhost:8081/deki");

            _deki = Plug.New(dekiUri).With("apikey", _apikey).WithHeader("X-Deki-Site", "id=" + wikiId);

            // get ajax polling interval
            _pollInterval = TimeSpan.FromSeconds(config["poll-interval"].AsDouble ?? 60);

            // set up subscription reaper
            TaskTimer.New(TimeSpan.FromSeconds(60), timer => {
                lock (_subscriptions) {
                    var staleSubs = new List <uint>();
                    foreach (KeyValuePair <uint, Subscription> pair in _subscriptions)
                    {
                        if (pair.Value.LastTouched.Add(_pollInterval).Add(TimeSpan.FromSeconds(10)) < DateTime.UtcNow)
                        {
                            staleSubs.Add(pair.Key);
                        }
                    }
                    foreach (uint pageId in staleSubs)
                    {
                        _log.DebugFormat("removing subscription for {0}", pageId);
                        _subscriptions.Remove(pageId);
                    }
                }
                timer.Change(TimeSpan.FromSeconds(60), TaskEnv.None);
            }, null, TaskEnv.None);


            // set up subscription for pubsub
            XDoc subscription = new XDoc("subscription-set")
                                .Elem("uri.owner", Self.Uri.AsServerUri().ToString())
                                .Start("subscription")
                                .Elem("channel", string.Format("event://{0}/deki/pages/update", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/revert", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/tags/update", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/comments/create", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/comments/update", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/comments/delete", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/create", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/update", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/delete", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/properties/*", wikiId))
                                .Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/restore", wikiId))
                                .Add(DreamCookie.NewSetCookie("service-key", InternalAccessKey, Self.Uri).AsSetCookieDocument)
                                .Start("recipient")
                                .Attr("authtoken", _apikey)
                                .Elem("uri", Self.Uri.AsServerUri().At("notify").ToString())
                                .End()
                                .End();
            Result <DreamMessage> subscribe;

            yield return(subscribe = PubSub.At("subscribers").PostAsync(subscription));

            string accessKey = subscribe.Value.ToDocument()["access-key"].AsText;
            XUri   location  = subscribe.Value.Headers.Location;

            Cookies.Update(DreamCookie.NewSetCookie("access-key", accessKey, location), null);
            _subscriptionLocation = Plug.New(location.AsLocalUri().WithoutQuery());
            _log.DebugFormat("set up initial subscription location at {0}", _subscriptionLocation.Uri);
            result.Return();
        }
예제 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ReferralHeaderRepository" /> class.
 /// </summary>
 public ReferralHeaderRepository()
 {
     communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #12
0
        private void InitializePreMadeSnacks()
        {
            for(int x = 0; x < amountOfColumns; x++)
            {
                preMadeChips[x] = new Chips(chipsCompany, fritoLaysBrands[x], 0, fritoLaysPrice[x]);

                preMadeChocolate[x] = new Chocolate(chocolateCompany, marsBrands[x], 0, marsPrice[x]);

                preMadeCookies[x] = new Cookies(cookiesCompany, nabiscoBrands[x], 0, nabiscoPrice[x]);

                preMadeGum[x] = new Gum(gumCompany, wrigleyBrands[x], 0, wrigleyPrice[x]);
            }
        }
예제 #13
0
        public void ReadFromStream(NetworkStream stream)
        {
            //wait for data avalability
            while (!stream.DataAvailable)
            {
                ;
            }

            var sb = new StringBuilder();

            while (stream.DataAvailable)
            {
                var c = (char)(byte)stream.ReadByte();
                if (c == '\n')
                {
                    var x = sb.ToString();
                    if (string.IsNullOrEmpty(x.Trim()))
                    {
                        break;
                    }

                    var header = HttpHeader.Parse(x);
                    if (header != null)
                    {
                        Headers.Add(header);
                        if (header is CookieHeader ch)
                        {
                            foreach (var cookie in ch.Cookies)
                            {
                                Cookies.Add(cookie.Key, cookie.Value);
                            }
                        }

                        if (header is ContentLengthHeader cl)
                        {
                            BodySize = cl.Length;
                        }

                        if (header is ForwardedForHeader ff)
                        {
                            ForwardIp = ff.Ip;
                        }
                    }

                    sb.Clear();
                }
                else
                {
                    sb.Append(c);
                }
            }

            try
            {
                //@Hack this feels wrong so probably a @CleanUp to lol
                if (Headers.Count != 0)
                {
                    var meth = Headers.First(x => x is RequestMethodHeader) as RequestMethodHeader;

                    Url = meth?.Url;

                    Path = Url?.Split('?')[0];

                    if (Url != null && Url.Contains("?"))
                    {
                        var qry = Url?.Split('?')[1];
                        if (!string.IsNullOrEmpty(qry))
                        {
                            foreach (var s in qry.Split('&'))
                            {
                                var segs = s.Split('=');
                                Query.Add(segs[0], HttpUtility.UrlDecode(segs[1]));
                            }
                        }
                    }

                    Method = meth.Method;
                    //Logger.Debug(Method.ToString());
                }
            }
            catch (Exception e)
            {
                Logger.Debug(e.ToString());
            }

            if (Method == RequestMethod.Post)
            {
                Body = stream;
            }
        }
예제 #14
0
 public EmergencyContactRepository()
 {
     communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
 public void AppendCookie(HttpCookie cookie)
 {
     Cookies.Add(cookie);
 }
예제 #16
0
 public static void Import(this HttpCookieCollection http_cookies, Cookies cookies)
 {
     throw new NotImplementedException();
 }
예제 #17
0
            public static void VendorBeg(Mobile m, object targeted, double chance)
            {
                //Console.WriteLine("Chance: {0}", chance);
                Mobile t          = (Mobile)targeted;
                Item   reward     = null;
                string rewardName = "";


                if (chance > .99 && m.Skills.Begging.Base >= 100)     //Vendor Only (1 hour cooldown)
                {
                    int rand = Utility.Random(9);                     //0-9 (10 Total) (40% chance for a item)
                    if (rand == 0)
                    {
                        reward     = new RockArtifact();                     //Rock Artifact
                        rewardName = "A rock";
                    }
                    else if (rand == 2)
                    {
                        reward     = new BeggerCoins(24);                     //Special Coins
                        rewardName = "24 dull slver coins.";
                    }
                    else if (rand == 4)                     //Fur Boots
                    {
                        reward     = new FurBoots();
                        rewardName = "a pair of Fur Boots";
                    }
                    else if (rand == 6)
                    {
                        reward     = new FlowerGarland();
                        rewardName = "a flower Garland";
                    }
                }
                Console.WriteLine("RewardName (1) {0}", reward);
                if (chance > .95 && m.Skills.Begging.Base >= 90 && reward == null)
                {
                    int rand = Utility.Random(9);
                    Console.WriteLine("Random 2 is {0}", rand);
                    if (rand == 0)
                    {
                        reward     = new BegBedRoll();
                        rewardName = "Bedroll";
                    }
                    else if (rand == 1)
                    {
                        reward     = new Cookies();
                        rewardName = "Cookies";
                    }
                    else if (rand == 3)
                    {
                        reward     = new FishSteak();
                        rewardName = "Fish Steaks";
                    }
                    else if (rand == 4)
                    {
                        reward     = new FishingPole();
                        rewardName = "Fishing Pole";
                    }
                    else if (rand == 6)
                    {
                        reward     = new BeggerCoins(12);
                        rewardName = "12 Dull Silver Coins.";
                    }
                    else if (rand == 7)
                    {
                        reward     = new Turnip();
                        rewardName = "Turnip";
                    }
                    else if (rand == 9)
                    {
                        reward     = new CeramicMug();
                        rewardName = "Ceramic Mug";
                    }
                }
                Console.WriteLine("RewardName (2) {0}", reward);
                if (reward == null)
                {
                    JunkBeg(m, t, chance);
                }
                else
                {
                    Reward(m, t, reward, rewardName);
                }
            }
예제 #18
0
파일: HttpRequest.cs 프로젝트: tezli/Doofy
        public bool TryParseRequest(MemoryStream m)
        {
            RequestStream = m;
            RawContent    = m.GetBuffer();
            var p = UTF8Encoding.UTF8.GetString(RawContent);

            string[] HeaderAndData = p.Split(new String[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                var headerFields = HeaderAndData[0].Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                var MethodResourceversion         = headerFields[0];
                var MethodResourceversionSplitted = MethodResourceversion.Split(' ');

                Method   = MethodResourceversionSplitted[0];
                Resource = MethodResourceversionSplitted[1];
                Version  = Version.Parse(MethodResourceversionSplitted[2].ToLower().Replace("http/", ""));

                for (int i = 1; i < headerFields.Length; i++)
                {
                    var PropertyValue = headerFields[i].Split(new String[] { ": " }, StringSplitOptions.RemoveEmptyEntries);

                    var key   = PropertyValue[0].Trim().ToLower();
                    var value = PropertyValue[1].Trim();

                    if (Headers.Any(v => v.Key.ToLower().Equals(key)) && !string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                    {
                        Headers[key] = value;
                    }

                    if (!Headers.ContainsKey(key))
                    {
                        HttpHandler.Log(LogLevel.Warning, "Key \"" + key + "\" is missing in header list");
                    }
                }

                if (!string.IsNullOrEmpty(Headers["Content-Type"]))
                {
                    ContentType = Headers["Content-Type"];
                }
                if (!string.IsNullOrEmpty(Headers["Content-Length"]))
                {
                    ContentLength = Convert.ToInt32(Headers["Content-Length"]);
                }

                if (!string.IsNullOrEmpty(Headers["Cookie"]))
                {
                    if (Cookies == null)
                    {
                        Cookies = new CookieContainer();
                    }

                    var cookies = Headers["Cookie"].Split(';');
                    foreach (var cookie in cookies)
                    {
                        var keyValue = cookie.Trim().Split(':');
                        if (keyValue.Length >= 2)
                        {
                            Cookies.Add(new Cookie()
                            {
                                Name   = keyValue[0],
                                Value  = keyValue[1],
                                Domain = Domain
                            });
                        }
                    }
                }


                if (HeaderAndData.Length >= 2)
                {
                    HasPayload = true;
                    var contentLength = RawContent.Length - HeaderAndData[0].Length - 4;
                    Content = new byte[contentLength];
                    Array.Copy(RawContent, RawContent.Length - contentLength, Content, 0, contentLength);
                }
                return(true);
            }
            catch (Exception e)
            {
                HttpHandler.Log(LogLevel.Error, "Http request parsing error : " + e.Message);
                return(false);
            }
        }
예제 #19
0
        /// <summary>
        /// Evento de clic del botón Guardar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgbtnGuardar_Click(object sender, DirectEventArgs e)
        {
            //1. Obtener datos de la Forma y saber si es edición o nuevo
            string strRegistro                    = e.ExtraParams["registro"];
            string strcookieEditarSucursal        = Cookies.GetCookie("cookieEditarSucursal").Value;
            Dictionary <string, string> dRegistro = JSON.Deserialize <Dictionary <string, string> >(strRegistro);
            Sucursal oSucursal                    = new Sucursal();

            oSucursal.FechaAlta = DateTime.Now;

            //2. Por cada elemento del submit de la Forma detectar el campo y asignarlo al objeto correspondiente
            foreach (KeyValuePair <string, string> sd in dRegistro)
            {
                switch (sd.Key)
                {
                //3. Datos del proveedor
                case "nfCR":
                    oSucursal.CR = Convert.ToInt16(sd.Value);
                    break;

                case "txtfNombre":
                    oSucursal.Nombre = sd.Value;
                    break;

                case "txtfGerenteBBVANombre":
                    oSucursal.GerenteBBVANombre = sd.Value;
                    break;

                case "txtfGerenteBBVAAPaterno":
                    oSucursal.GerenteBBVAAPaterno = sd.Value;
                    break;

                case "txtfGerenteBBVAAMaterno":
                    oSucursal.GerenteBBVAAMaterno = sd.Value;
                    break;

                case "txtfSupervisorNombre":
                    oSucursal.SupervisorNombre = sd.Value;
                    break;

                case "txtfSupervisorAPaterno":
                    oSucursal.SupervisorAPaterno = sd.Value;
                    break;

                case "txtfSupervisorAMaterno":
                    oSucursal.SupervisorAMaterno = sd.Value;
                    break;

                case "txtfProveedorEnergia":
                    oSucursal.ProveedorEnergia = sd.Value;
                    break;

                case "nfSuperficie":
                    oSucursal.Superficie = Convert.ToInt32(sd.Value);
                    break;

                case "txtfCoordinadorNombre":
                    oSucursal.CoordinadorNombre = sd.Value;
                    break;

                case "txtfCoordinadorAPaterno":
                    oSucursal.CoordinadorAPaterno = sd.Value;
                    break;

                case "txtfCoordinadorAMaterno":
                    oSucursal.CoordinadorAMaterno = sd.Value;
                    break;

                case "txtfCalle":
                    oSucursal.Calle = sd.Value;
                    break;

                case "txtfEntreCalles":
                    oSucursal.EntreCalles = sd.Value;
                    break;

                case "txtfNoExterior":
                    oSucursal.NoExterior = sd.Value;
                    break;

                case "txtfNoInterior":
                    oSucursal.NoInterior = sd.Value;
                    break;

                case "txtfCodigoPostal":
                    oSucursal.CodigoPostal = Convert.ToInt32(sd.Value);
                    break;

                case "txtfColonia":
                    oSucursal.Colonia = sd.Value;
                    break;

                case "cmbEstado":
                    oSucursal.Estado = sd.Value;
                    break;

                case "cmbMunicipio":
                    oSucursal.Municipio = sd.Value;
                    break;

                case "txtfContratista":
                    oSucursal.Contratista = sd.Value;
                    break;

                case "dfTerminoContrato":
                    oSucursal.TerminoContrato = Convert.ToDateTime(sd.Value);
                    break;

                case "dfInicioObra":
                    oSucursal.InicioObra = Convert.ToDateTime(sd.Value);
                    break;

                case "dfFinObra":
                    oSucursal.FinObra = Convert.ToDateTime(sd.Value);
                    break;

                case "nfSemanasObra":
                    oSucursal.SemanasObra = Convert.ToInt16(sd.Value);
                    break;

                case "dfFechaAlta":
                    oSucursal.FechaAlta = Convert.ToDateTime(sd.Value);
                    break;

                case "cmbEstatus":
                    oSucursal.Estatus = sd.Value;
                    break;
                }
            }

            //4. Validar si es nuevo o es uno existente
            if (strcookieEditarSucursal.Equals("Nuevo"))
            {
                //5. Insertar en la base de datos
                oSucursal.FechaAlta = DateTime.Now;
                oSucursal.Estatus   = "ALTA";
                oSucursal.ID        = SucursalBusiness.Insertar(oSucursal);
                //6. Mandar mensaje con el código del proveedor
                var success = new JFunction {
                    Fn = "imgbtnGuardar_Click_Success"
                };
                X.Msg.Alert("Registro completo", "<p align='center'>Sucursal registrada con ID: <br/>" + oSucursal.ID + ".</p>", success).Show();
            }
            else
            {
                oSucursal.ID = strcookieEditarSucursal;
                //7. Actualizar los datos del proveedor
                SucursalBusiness.Actualizar(oSucursal);
                //8. Mandar mensaje con el código del proveedor
                var success = new JFunction {
                    Fn = "imgbtnGuardar_Click_Success"
                };
                X.Msg.Alert("Actualización completa", "<p align='center'>Se han actualizado los datos de la sucursal <br/>" + oSucursal.ID + ".</p>", success).Show();
            }
        }
 /// <summary>
 /// Constructor
 /// </summary>
 public ESignatureRepository()
 {
     _communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #21
0
 public void ResetCookies(Cookies cookies)
 {
 }
예제 #22
0
        ////////////////////////////////////////////////////
        // STEAM WEB INTERFACE
        ////////////////////////////////////////////////////

        public override async void LoginWebInterface(ulong steamID)
        {
            if (!IsAuthenticated)
            {
                SteamUser.WebAPIUserNonceCallback callback;

                try
                {
                    callback = await _steamUser.RequestWebAPIUserNonce();
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Unable to request Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                if (string.IsNullOrWhiteSpace(callback?.Nonce))
                {
                    _log.Error("Received empty Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                var    sessionID  = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));
                var    sessionKey = CryptoHelper.GenerateRandomBlock(32);
                byte[] cryptedSessionKey;

                using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(_steamClient.Universe)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                var loginKey = new byte[callback.Nonce.Length];
                Array.Copy(Encoding.ASCII.GetBytes(callback.Nonce), loginKey, callback.Nonce.Length);

                // AES encrypt the login key with our session key
                var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                if (!Titan.Instance.WebHandle.AuthentificateUser(
                        steamID, cryptedLoginKey, cryptedSessionKey, out var result
                        ))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                var token       = result["token"].Value;
                var secureToken = result["tokensecure"].Value;

                if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secureToken))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                Cookies.Add("sessionid", sessionID);
                Cookies.Add("steamLogin", token);
                Cookies.Add("steamLoginSecure", secureToken);

                if (!Titan.Instance.Options.Secure)
                {
                    _log.Debug("Authorized with Steam Web API. Session ID: {id}", sessionID);
                }

                _log.Information("Successfully authorized with Steam Web API.");

                IsAuthenticated = true;
            }
        }
예제 #23
0
        /// <summary>
        /// Evento de clic del botón Guardar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgbtnGuardar_Click(object sender, DirectEventArgs e)
        {
            //1. Obtener datos de la Forma y saber si es edición o nuevo
            string strRegistro = e.ExtraParams["registro"];

            //2. Por cada elemento del submit de la Forma detectar el campo y asignarlo al objeto correspondiente
            Dictionary <string, string> dRegistro = JSON.Deserialize <Dictionary <string, string> >(strRegistro);
            CodigoFalla cf = new CodigoFalla();

            foreach (KeyValuePair <string, string> sd in dRegistro)
            {
                switch (sd.Key)
                {
                case "txtCodigoMainSaver":
                    cf.CodigoMainSaver = sd.Value;
                    break;

                //case "cmbEspecialidad":
                //    cf.Especialidad = sd.Value;
                //    break;

                //case "cmbFamilia":
                //    cf.Familia = sd.Value;
                //    break;

                //case "cmbSubEspecialidad":
                //    cf.Subespecialidad = sd.Value;
                //    break;

                //case "txtDescripcion":
                //    cf.Descripcion = sd.Value;
                //    break;

                case "txtDias":
                    cf.Dias = sd.Value;
                    break;

                    //case "txtPrioridad":
                    //    cf.Prioridad = sd.Value;
                    //    break;

                    //case "txtTiempoEstimado":
                    //    cf.TiempoEstimado = sd.Value;
                    //    break;
                }
            }
            string strcookieEditarCodigoPPTA = Cookies.GetCookie("cookieEditarCodigoPPTA").Value;

            if (strcookieEditarCodigoPPTA.Equals("Nuevo"))
            {
                if (CodigoFallasBusiness.ObtenerMainSaverEnCodigoPPTA(cf.CodigoMainSaver))
                {
                    var success = new JFunction {
                        Fn = "imgbtnGuardar_Click_SuccessCR"
                    };
                    X.Msg.Alert("Alerta", "<p align='center'>El Main Saver ya se encuentra registrado: <br/>" + cf.CodigoMainSaver + ".</p>", success).Show();
                }
                else
                {
                    //3. Insertar en la base de datos
                    cf.CodigoMainSaver = CodigoFallasBusiness.Insertar(cf);
                    //4. Mandar mensaje con el código del codigo ppta
                    e.ExtraParamsResponse.Add(new Ext.Net.Parameter("data", cf.CodigoMainSaver, ParameterMode.Value));
                }
            }
            else
            {
                CodigoFallasBusiness.Actualizar(cf);
                cf.CodigoMainSaver = strcookieEditarCodigoPPTA;
                e.ExtraParamsResponse.Add(new Ext.Net.Parameter("data", cf.CodigoMainSaver, ParameterMode.Value));
            }
        }
예제 #24
0
        public void Login()
        {
            // 启动流程
            // 1.获取二维码
            // 2.检查扫描
            // 3.获取ptwebqq
            // 4.获取vfwebqq
            // 5.获取psessionid和uin、skey
            LoginCookies = new Cookies();

            Debug.Write("清除Cookies.");
            api.ClearCookies();

            do
            {
                // ----------1.获取二维码

                Debug.Write("[*] 正在生成二维码 ....");
                var QRImg = api._get_qrcode_image();
                if (QRImg != null)
                {
                    Debug.Write("成功\n");
                }

                Debug.Write("[*] 正在等待扫码 ....");
                OnGetQRCodeImage?.Invoke(QRImg);
                //----------2.检查扫描
                while (true)
                {
                    Thread.Sleep(1000);
                    var authresult = api._get_authstatus();

                    if (authresult.Contains("成功"))
                    {
                        // 扫描成功
                        string redirect_url = authresult.Split(new string[] { "\'" }, StringSplitOptions.None)[5];
                        Debug.Write("跳转URL");
                        Debug.Write(redirect_url);

                        //----------2.获取ptwebqq
                        LoginCookies.ptwebqq = api._get_ptwebqq(redirect_url);
                        LoginResult.ptwebqq  = LoginCookies.ptwebqq;

                        Debug.Write("ptwebqq=" + LoginResult.ptwebqq);

                        Debug.Write("已获授权\n");
                        //IsLogin = true;

                        OnVerifySucess?.Invoke();
                        break;
                    }
                    else if (authresult.Contains("二维码认证中"))
                    {
                        OnVerifyImage?.Invoke();
                    }
                    else if (authresult.Contains("二维码未失效"))
                    {
                        OnScanImage?.Invoke();
                    }
                    else if (authresult.Contains("二维码已失效") || authresult == null)
                    {
                        Debug.Write("[*] 重新生成二维码 ....");
                        var QRImgReGet = api._get_qrcode_image();
                        if (QRImg != null)
                        {
                            Debug.Write("成功\n");
                        }

                        OnGetQRCodeImage?.Invoke(QRImgReGet);
                    }
                }
                //----------2.获取vfwebqq

                JObject Jovfwebqq = (JObject)JsonConvert.DeserializeObject(api._get_vfwebqq(LoginResult.ptwebqq));

                LoginCookies.vfwebqq = Jovfwebqq["result"]["vfwebqq"].ToString();
                LoginResult.vfwebqq  = LoginCookies.vfwebqq;

                Debug.Write("vfwebqq=" + LoginResult.vfwebqq);
                if (LoginResult.vfwebqq == null)
                {
                    return;
                }
                //----------登录

                string strLoginCallback = api._login(LoginResult.ptwebqq);
                if (strLoginCallback != null && strLoginCallback.Contains("psessionid"))
                {
                    JObject JoUinAndPsessionid = (JObject)JsonConvert.DeserializeObject(strLoginCallback);

                    LoginResult.psessionid = JoUinAndPsessionid["result"]["psessionid"].ToString();
                    Debug.Write("psessionid=" + LoginResult.psessionid);
                    LoginResult.qq = JoUinAndPsessionid["result"]["uin"].ToString();
                    Debug.Write("uin=" + LoginResult.qq);

                    string[] namelist = { "skey", "uin", "p_skey", "p_uin" };

                    List <string> CookieList = api.GetCookies(namelist);


                    LoginCookies.skey = CookieList[0].ToString();
                    Debug.Write("skey=" + LoginCookies.skey);

                    LoginCookies.uin = CookieList[1].ToString();
                    Debug.Write("uin=" + LoginCookies.uin);

                    LoginCookies.p_skey = CookieList[2].ToString();
                    Debug.Write("p_skey=" + LoginCookies.p_skey);

                    LoginCookies.p_uin = CookieList[3].ToString();
                    Debug.Write("p_uin=" + LoginCookies.p_uin);


                    if (!Directory.Exists(Environment.CurrentDirectory + "\\user\\" + LoginResult.qq))
                    {
                        Directory.CreateDirectory(Environment.CurrentDirectory + "\\user\\" + LoginResult.qq);
                    }

                    File.WriteAllText(Path.Combine(Environment.CurrentDirectory + "\\user\\" + LoginResult.qq, cookiesFileName), JsonConvert.SerializeObject(LoginCookies, Formatting.Indented));

                    Debug.Write("跨域共享cookie");
                    //跨域共享cookie
                    api.CookieProxy(LoginCookies.p_skey, LoginCookies.p_uin);
                    IsLogin = true;
                }
            } while (!IsLogin);
            OnLoginSucess?.Invoke();
        }
 public PresentIllnessRepository()
 {
     _communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #26
0
        public async Task <IActionResult> Booking(int totalSeats, string seatIds)
        {
            if (!Cookies.CheckFbLogIn(Request))
            {
                return(RedirectToAction("LogIn", "Authentication"));
            }

            var seats = seatIds;

            string bookedBy = HttpContext.Request.Cookies["fbLogIn"].ToString();

            //set json for Api
            string jsonBooked = @"
            {
                'seatIds':{0},
                'total':{1},    
                'booking':
                    {
                        '$set':
                            {
                                'bookingStatus': 
                                    {  '_id':'bs02','name':'Sold Out', 
                                        'isActive': true,
                                        'bookedDate':'{2}',
                                        'bookedBy':'{3}'
                                    }
                            }
                    }
                    
            }";
            string bookedDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            jsonBooked = jsonBooked.Replace("{0}", seatIds);
            jsonBooked = jsonBooked.Replace("{1}", totalSeats.ToString());
            jsonBooked = jsonBooked.Replace("{2}", bookedDate);
            jsonBooked = jsonBooked.Replace("{3}", bookedBy);


            RestApi api = new RestApi("https://localhost:5003/api/concertSeats/BookingSeats");

            api.SetHeader("Authorization", Cookies.GetToken(Request));

            var data = await api.AddAsync(jsonBooked);

            var responseBody = await data.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <Result>(responseBody);

            if (result.Status == Puppy.Model.Business.BusinessStatus.Completed)
            {
                return(RedirectToAction("MyTicket", "Customer"));
            }
            else
            {
                byte[] values; string zoneId = "";
                HttpContext.Session.TryGetValue("ZoneId", out values);
                if (values != null)
                {
                    zoneId = Encoding.ASCII.GetString(values);
                }
                return(RedirectToAction("LayoutBooking", "Concert", zoneId));
            }
        }
예제 #27
0
        protected override Yield Start(XDoc config, IContainer container, Result result)
        {
            yield return(Coroutine.Invoke(base.Start, config, new Result()));

            // ensure imagemagick is setup correctly.
            if (string.IsNullOrEmpty(ImageMagickConvertPath))
            {
                throw new NotImplementedException("Please set 'imagemagick-convert-path' in config to path of ImageMagick's 'convert'");
            }
            if (!File.Exists(ImageMagickIdentifyPath))
            {
                throw new FileNotFoundException("Cannot find ImagicMagick 'identify' binary: ", ImageMagickIdentifyPath);
            }
            if (string.IsNullOrEmpty(ImageMagickIdentifyPath))
            {
                throw new NotImplementedException("Please set 'imagemagick-identify-path' in config to path of ImageMagick's 'identify'");
            }
            if (!File.Exists(ImageMagickConvertPath))
            {
                throw new FileNotFoundException("Cannot find ImagicMagick 'convert' binary: ", ImageMagickConvertPath);
            }

            // check for 'apikey'
            _apikey = Config["api-key"].AsText ?? Config["apikey"].AsText;
            if (string.IsNullOrEmpty(_apikey))
            {
                throw new ArgumentNullException("apikey", "The global apikey is not defined. Please ensure that you have a global <apikey> defined in the MindTouch Core service settings xml file.");
            }
            InitializeContainer(container);

            // intialize instance manager
            _instanceManager = InstanceManager.New(this, this.TimerFactory);

            // setup resource manager
            lock (SyncRoot) {
                if (ResourceManager == null)
                {
                    ResourceManager = new PlainTextResourceManager(ResourcesPath);
                    ScreenFont      = new DekiFont(Plug.New("resource://mindtouch.deki/MindTouch.Deki.Resources.Arial.mtdf").Get().AsBytes());
                }
            }

            // initialize scripting engine
            XDoc scripting = Config["scripting"];

            DekiScriptLibrary.InsertTextLimit = scripting["max-web-response-length"].AsLong ?? DekiScriptLibrary.InsertTextLimit;
            DekiScriptLibrary.MinCacheTtl     = scripting["min-web-cache-ttl"].AsDouble ?? DekiScriptLibrary.MinCacheTtl;

            // set up deki pub sub (by default we override uri.publish with our own service, unless @must-use=true is specified)
            if (!(Config["uri.publish/@must-use"].AsBool ?? false))
            {
                Result <Plug> pubsubResult;
                XDoc          pubsubConfig = new XDoc("config")
                                             .Elem("uri.deki", Self.Uri.With("apikey", MasterApiKey))
                                             .Start("downstream")
                                             .Elem("uri", PubSub.At("publish").Uri.WithoutLastSegment().At("subscribers"))
                                             .End()
                                             .Start("components")
                                             .Start("component")
                                             .Attr("type", typeof(IPubSubDispatcher).AssemblyQualifiedName)
                                             .Attr("implementation", typeof(DekiDispatcher).AssemblyQualifiedName)
                                             .End()
                                             .End()
                                             .Elem("authtoken", MasterApiKey);
                foreach (var cookie in Cookies.Fetch(PubSub.Uri))
                {
                    pubsubConfig.Add(cookie.AsSetCookieDocument);
                }
                var messageQueuePath = config["publish/queue-path"].AsText;
                if (!string.IsNullOrEmpty(messageQueuePath))
                {
                    pubsubConfig.Elem("queue-path", messageQueuePath);
                }
                yield return(pubsubResult = CreateService(
                                 "pubsub",
                                 "sid://mindtouch.com/dream/2008/10/pubsub",
                                 pubsubConfig,
                                 new Result <Plug>()));

                PubSub = pubsubResult.Value;
            }

            // set up package updater service (unless it was passed in)
            XUri packageUpdater;

            if (config["packageupdater/@uri"].IsEmpty)
            {
                var packageConfig = config["packageupdater"];
                packageConfig = packageConfig.IsEmpty ? new XDoc("config") : packageConfig.Clone();
                if (packageConfig["package-path"].IsEmpty)
                {
                    packageConfig.Elem("package-path", Path.Combine(Path.Combine(config["deki-path"].AsText, "packages"), "default"));
                }
                yield return(CreateService(
                                 "packageupdater",
                                 "sid://mindtouch.com/2010/04/packageupdater",
                                 new XDoc("config")
                                 .Elem("apikey", MasterApiKey)
                                 .AddNodes(packageConfig),
                                 new Result <Plug>()
                                 ));

                packageUpdater = Self.Uri.At("packageupdater");
            }
            else
            {
                packageUpdater = config["packageupdater/@uri"].AsUri;
            }
            _packageUpdater = Plug.New(packageUpdater);

            // set up emailer service (unless it was passed in)
            XUri mailerUri;

            if (config["uri.mailer"].IsEmpty)
            {
                yield return(CreateService(
                                 "mailer",
                                 "sid://mindtouch.com/2009/01/dream/email",
                                 new XDoc("config")
                                 .Elem("apikey", MasterApiKey)
                                 .AddAll(Config["smtp/*"]),
                                 new Result <Plug>()
                                 ));

                mailerUri = Self.Uri.At("mailer");
            }
            else
            {
                mailerUri = config["uri.mailer"].AsUri;
            }
            _mailer = Plug.New(mailerUri);

            // set up the email subscription service (unless it was passed in)
            XUri pageSubscription;

            if (config["uri.page-subscription"].IsEmpty)
            {
                XDoc pagesubserviceConfig = new XDoc("config")
                                            .Elem("uri.deki", Self.Uri)
                                            .Elem("uri.emailer", mailerUri.At("message"))
                                            .Elem("resources-path", ResourcesPath)
                                            .Elem("apikey", MasterApiKey)
                                            .Start("components")
                                            .Start("component")
                                            .Attr("scope", "factory")
                                            .Attr("type", typeof(IPageSubscriptionDataSessionFactory).AssemblyQualifiedName)
                                            .Attr("implementation", "MindTouch.Deki.Data.MySql.UserSubscription.MySqlPageSubscriptionSessionFactory, mindtouch.deki.data.mysql")
                                            .End()
                                            .End()
                                            .AddAll(Config["page-subscription/*"]);
                foreach (var cookie in Cookies.Fetch(mailerUri))
                {
                    pagesubserviceConfig.Add(cookie.AsSetCookieDocument);
                }
                yield return(CreateService(
                                 "pagesubservice",
                                 "sid://mindtouch.com/deki/2008/11/changesubscription",
                                 pagesubserviceConfig,
                                 new Result <Plug>()
                                 ));

                pageSubscription = Self.Uri.At("pagesubservice");
                config.Elem("uri.page-subscription", pageSubscription);
            }
            else
            {
                pageSubscription = config["uri.page-subscription"].AsUri;
            }
            _pageSubscription = Plug.New(pageSubscription);

            // set up package importer, if not provided
            if (Config["uri.package"].IsEmpty)
            {
                yield return(CreateService(
                                 "package",
                                 "sid://mindtouch.com/2009/07/package",
                                 new XDoc("config").Elem("uri.deki", Self.Uri),
                                 new Result <Plug>()));

                Config.Elem("uri.package", Self.Uri.At("package"));
            }

            // set up lucene
            _luceneIndex = Plug.New(Config["indexer/@src"].AsUri);
            if (_luceneIndex == null)
            {
                // create the indexer service
                XDoc luceneIndexConfig = new XDoc("config")
                                         .AddNodes(Config["indexer"])
                                         .Start("apikey").Attr("hidden", true).Value(MasterApiKey).End();
                if (luceneIndexConfig["path.store"].IsEmpty)
                {
                    luceneIndexConfig.Elem("path.store", Path.Combine(Path.Combine(config["deki-path"].AsText, "luceneindex"), "$1"));
                }
                yield return(CreateService("luceneindex", SID_FOR_LUCENE_INDEX, luceneIndexConfig, new Result <Plug>()).Set(v => _luceneIndex = v));

                _isLocalLuceneService = true;
            }
            else
            {
                // push our host's pubsub service to lucene, to keep it up to date on our changes
                var pubsub = new XDoc("pubsub").Attr("href", PubSub);
                foreach (var cookie in PubSub.CookieJar.Fetch(PubSub.Uri))
                {
                    pubsub.Add(cookie.AsSetCookieDocument);
                }
                yield return(_luceneIndex.At("subscriptions").PostAsync(pubsub));
            }

            // configure indexing whitelist
            _indexNamespaceWhitelist = new[] { NS.MAIN, NS.PROJECT, NS.USER, NS.TEMPLATE, NS.HELP, NS.MAIN_TALK, NS.PROJECT_TALK, NS.USER_TALK, NS.TEMPLATE_TALK, NS.HELP_TALK, NS.SPECIAL, NS.SPECIAL_TALK };
            if (!string.IsNullOrEmpty(Config["indexer/namespace-whitelist"].AsText))
            {
                List <NS> customWhitelist = new List <NS>();
                foreach (string item in Config["indexer/namespace-whitelist"].AsText.Split(','))
                {
                    NS ns;
                    if (SysUtil.TryParseEnum(item, out ns))
                    {
                        customWhitelist.Add(ns);
                    }
                }
                _indexNamespaceWhitelist = customWhitelist.ToArray();
            }

            if (!Config["wikis/globalconfig/cache/varnish"].IsEmpty)
            {
                // create the varnish service

                // TODO (petee): getting the varnish config from wikis/globalconfig/cache is a hack
                // The frontend needs to get the max-age to send out the cache headers but we currently have no way
                // of getting the DekiWikiService config so we'll hack it so it comes back in GET:site/settings.
                XDoc varnishConfig = new XDoc("config")
                                     .Elem("uri.deki", Self.Uri.With("apikey", MasterApiKey))
                                     .Elem("uri.varnish", Config["wikis/globalconfig/cache/varnish"].AsUri)
                                     .Elem("varnish-purge-delay", Config["wikis/globalconfig/cache/varnish-purge-delay"].AsInt ?? 10)
                                     .Elem("varnish-max-age", Config["wikis/globalconfig/cache/varnish-max-age"].AsInt ?? 300)
                                     .Start("apikey").Attr("hidden", true).Value(MasterApiKey).End();
                yield return(CreateService("varnish", SID_FOR_VARNISH_SERVICE, varnishConfig, new Result <Plug>()));
            }
            _isInitialized = true;
            result.Return();
        }
예제 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdminRepository"/> class.
 /// </summary>
 public AdminRepository()
 {
     communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #29
0
 public GroupSchedulingSearchRepository()
 {
     _communicationManager = new CommunicationManager(ApplicationSettings.Token, Cookies.GetCookies(ApplicationSettings.Token));
 }
예제 #30
0
        //--- Methods ---
        protected override Yield Start(XDoc config, Result result)
        {
            yield return(Coroutine.Invoke(base.Start, config, new Result()));

            // set up cache reaper
            _ttl = TimeSpan.FromSeconds(Config["news-ttl"].AsDouble ?? 60 * 60);
            double?checkInterval = Config["check-interval"].AsDouble;

            if (checkInterval.HasValue)
            {
                _checkInterval = TimeSpan.FromSeconds(checkInterval.Value);
            }
            else
            {
                double checkInterval2 = _ttl.TotalSeconds / 10;
                if (_ttl.TotalSeconds < 30 || checkInterval2 < 30)
                {
                    checkInterval2 = 30;
                }
                _checkInterval = TimeSpan.FromSeconds(checkInterval2);
            }
            TaskTimer.New(_ttl, delegate(TaskTimer timer) {
                lock (_pageViews) {
                    View next;
                    do
                    {
                        if (_pageViews.Count == 0)
                        {
                            break;
                        }
                        next = _pageViews.Peek();
                        if (next != null)
                        {
                            if (next.Time.Add(_ttl) < DateTime.UtcNow)
                            {
                                _pageViews.Dequeue();
                            }
                            else
                            {
                                break;
                            }
                        }
                    } while(next != null);
                }
                timer.Change(_checkInterval, TaskEnv.None);
            }, null, TaskEnv.None);

            // get the apikey, which we will need as a subscription auth token for subscriptions not done on behalf of a user
            _apikey = config["apikey"].AsText;

            // build ignore list
            string ignore = config["ignore"].AsText;

            if (!string.IsNullOrEmpty(ignore))
            {
                foreach (string page in ignore.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    _ignore[page] = null;
                }
            }
            // set up subscription for page views
            XDoc subscription = new XDoc("subscription-set")
                                .Elem("uri.owner", Self.Uri.AsServerUri().ToString())
                                .Start("subscription")
                                .Elem("channel", "event://*/deki/pages/view")
                                .Add(DreamCookie.NewSetCookie("service-key", InternalAccessKey, Self.Uri).AsSetCookieDocument)
                                .Start("recipient")
                                .Attr("authtoken", _apikey)
                                .Elem("uri", Self.Uri.AsServerUri().At("notify", "view").ToString())
                                .End()
                                .End();
            Result <DreamMessage> subscribe;

            yield return(subscribe = PubSub.At("subscribers").PostAsync(subscription));

            string accessKey = subscribe.Value.ToDocument()["access-key"].AsText;
            XUri   location  = subscribe.Value.Headers.Location;

            Cookies.Update(DreamCookie.NewSetCookie("access-key", accessKey, location), null);
            _subscriptionLocation = Plug.New(location.AsLocalUri().WithoutQuery());
            _log.DebugFormat("set up initial subscription location at {0}", _subscriptionLocation.Uri);
            result.Return();
        }
예제 #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        shsiteconfig.Visible = false;

        if (!Page.IsPostBack)
        {
            ((Literal)Master.FindControl("breadcrumbs")).Text = "<span class=\"home\">系统基本设置</span>";
            string checklogin = new AdminBll().CheckLogin("0");
            if (checklogin != "true")
            {
                BasePage.Alertback(checklogin);
                Response.End();
            }
            if (BasePage.ArrayExist(Cookies.GetCookie("ModelPower"), "6"))
            {
                shsiteconfig.Visible = true;
            }
            WebConfigModel wm = new WebConfigBll().GetModel(1);
            txtSiteName.Text    = wm.SiteName;
            txtsitetitle.Text   = wm.SiteTitle;
            txtsitetitleen.Text = wm.SiteTitleEn;
            txtSiteUrl.Text     = wm.SiteUrl;
            txticp.Text         = wm.SiteICP;

            txtSiteKeyword.Text       = wm.SiteKeyword;
            txtSiteKeyworden.Text     = wm.SiteKeywordEn;
            txtSiteDescription.Text   = wm.SiteDescription;
            txtSiteDescriptionen.Text = wm.SiteDescriptionEn;
            txtsiteemail.Text         = wm.SiteMail;
            txtEmailsmtp.Text         = wm.EmailSMTP;
            txtSmtpName.Text          = wm.EmailName;
            txtsitecnzz.Text          = wm.Sitecnzz;
            txtfax.Text     = wm.SiteFax;
            txttel.Text     = wm.SiteTel;
            txtaddress.Text = wm.SiteAddress;
            txtqq.Text      = wm.SiteQQ;
            txtaddress.Text = wm.SiteAddress;
            txtother.Text   = wm.Other;
            txtSmtpPassword.Attributes.Add("value", wm.EmailPassword);
            txtidnum.Text = BasePage.SiteId();
            if (!String.IsNullOrEmpty(wm.SiteConfig))
            {
                string   siteconfig = wm.SiteConfig;
                string[] a          = siteconfig.Split('|');
                if (a.Length > 0)
                {
                    SetCheckedBox.SetChecked(this.CheckBoxList1, a[0], ","); //基本配置
                    SetCheckedBox.SetChecked(this.CheckBoxList2, a[1], ","); //留言内容
                    SetCheckedBox.SetChecked(this.CheckBoxList3, a[2], ","); //留言列表
                    RadioButtonList1.SelectedValue = a[3];                   //单页显示可选
                    showhide = a[0];
                }
            }
            //序列号
            //string word = GreateFiles.Read_File(Server.MapPath("~/id.txt"));
            //if (!String.IsNullOrEmpty(word))
            //{
            //    txtidnum.Text = word.Trim();
            //}
        }
    }
예제 #32
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            CommonDataService cds = new CommonDataService();

            CommonModel cm = new CommonModel();

            cm = cds.GenerateCommonModel();
            Session["FaceBook"]      = cm.FaceBook;
            Session["Twitter"]       = cm.Twitter;
            Session["Youtube"]       = cm.Youtube;
            Session["Instagram"]     = cm.Instagram;
            Session["PhoneNumber"]   = cm.PhoneNumber;
            Session["Email"]         = cm.Email;
            Session["ShoppingHours"] = cm.ShoppingHours;
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            UserDataService userDataService = new UserDataService();

            DataSet ds = new DataSet();

            ds = userDataService.GetUsersByUserName(model.UserName);
            if (ds != null)
            {
                if (ds.Tables[0] != null)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (model.Password == Convert.ToString(ds.Tables[0].Rows[0]["UserPassword"]) &&
                            model.UserName == Convert.ToString(ds.Tables[0].Rows[0]["UserName"]))
                        {
                            HttpCookie FormsCookie = Cookies.CreateAuthenticationCookie(model.UserName, model.LastName);
                            Response.Cookies.Add(FormsCookie);
                            Session.Remove("UserName");
                            Session.Remove("FirstName");
                            Session.Remove("LastName");
                            Session["UserName"]  = model.UserName;
                            Session["FirstName"] = model.FirstName;
                            Session["LastName"]  = model.LastName;
                            return(RedirectToLocal(returnUrl));
                        }
                        else
                        {
                            ModelState.AddModelError("", "Invalid login attempt.");
                            return(View(model));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid login attempt.");
                        return(View(model));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return(View(model));
                }
            }
            else
            {
                ModelState.AddModelError("", "User does not exists!");
                return(View(model));
            }
        }
예제 #33
0
파일: Users.cs 프로젝트: liuchengsgit/Keep
        public void Init()
        {
            var user = new User(this.userName, this.password);

            this.cookieContainer = Cookies.GetCookieContainer(user);
        }
예제 #34
0
 public static void Import(this HttpResponse resp, Cookies cookies)
 {
     throw new NotImplementedException();
 }
예제 #35
0
 /// <inheritdoc/>
 public bool Equals(StorageState other)
 => other != null &&
 Cookies.SequenceEqual(other.Cookies) &&
 Origins.SequenceEqual(other.Origins);