Inheritance: System.Web.UI.Page
コード例 #1
0
        public override void ValidateLinks(Links.LinksValidationResult result)
       {           
            base.ValidateLinks(result);

            var document = new HtmlDocument();
            document.LoadHtml(this.Value);

            var htmlNodeCollection = document.DocumentNode.SelectNodes("//span[@itemid and @field]");
            if (htmlNodeCollection == null) return;

            var links = htmlNodeCollection.Select(n=> 
                new { ItemID=n.Attributes["itemid"].Value,Field=n.Attributes["field"].Value});
            
            foreach(var link in links)
            {                
                var item = this.InnerField.Database.GetItem(link.ItemID);                
                
                if (item != null && item.Fields.Any(f=> f.Key.Equals(link.Field,StringComparison.InvariantCultureIgnoreCase)))
                {
                    result.AddValidLink(item, string.Concat(link.ItemID,"^",link.Field,"^",this._innerField.Key));
                }
                else
                {
                    result.AddBrokenLink(link.ItemID);
                }
            }
          
        }
コード例 #2
0
    private void writeNaveLink(Links link)
    {
        String element = "<a href='" + link.getPath() + "'><div class='nav-item'>" + link.getLinkText() + "</div></a>";
        LiteralControl userLink = new LiteralControl(element);

        linksPlaceHolder.Controls.Add(userLink);
    }
コード例 #3
0
 protected void Page_Load(object sender, EventArgs e)
 {
     dbOps = (DBOperations)Application["dbOps"];
     log = (Logger)Application["log"];
     links = (Links)Application["links"];
     general = (General)Application["general"];
 }
コード例 #4
0
ファイル: SubmitRating.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        gui = GUIVariables.Instance;
        categories = Categories.Instance;
        engine = ProcessingEngine.Instance;
        imageEngine = ImageEngine.Instance;
        tagger = Tagger.Instance;
        log = Logger.Instance;

        seperator = gui.Seperator;

        //  QueryString Param Names.
        //  ratingID
        //  value

        string iid = string.Empty;
        string value = string.Empty;

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.

        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            UID = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (string.IsNullOrEmpty(UID))
        {

        }
        else
        {

        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        if (Request.QueryString != null && Request.QueryString.Count > 0)
        {
            //  ratingID is the Item IID.
            if (!string.IsNullOrEmpty(Request.QueryString["ratingID"]))
            {
                iid = Request.QueryString["ratingID"];
            }
            //  Value is the Rating given by the user. Value: [0, 1, 2, 3, 4]. So add +1 so as to convert Value: [1, 2, 3, 4, 5]
            if (!string.IsNullOrEmpty(Request.QueryString["value"]))
            {
                int intValue = -1;
                value = int.TryParse(Request.QueryString["value"], out intValue) ? (intValue + 1).ToString() : "-1";
            }
        }

        if (!string.IsNullOrEmpty(UID) && !string.IsNullOrEmpty(iid) && !string.IsNullOrEmpty(value))
        {
            UpdateRatings(UID, iid, value);
        }
    }
コード例 #5
0
ファイル: Commented.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        links = Links.Instance;
        gui = GUIVariables.Instance;
        dbOps = DBOperations.Instance;
        categories = Categories.Instance;
        log = Logger.Instance;
        engine = ProcessingEngine.Instance;
        general = General.Instance;
        imageEngine = ImageEngine.Instance;

        seperator = gui.Seperator;

        if (string.IsNullOrEmpty(Request.QueryString["UID"]))
        {

        }
        else
        {
            queryStringUID = Request.QueryString["UID"].Trim().ToLower();
        }

        if (string.IsNullOrEmpty(queryStringUID))
        {

        }
        else
        {
            LoadComments(queryStringUID);
        }
    }
コード例 #6
0
ファイル: SLogin.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        gui = GUIVariables.Instance;
        log = Logger.Instance;
        general = General.Instance;
        engine = ProcessingEngine.Instance;

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.
        string UID = string.Empty;
        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            UID = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (!string.IsNullOrEmpty(UID))
        {
            Response.Redirect(links.FrontPageLink, false);
        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        if (!IsPostBack)
        {
            Control MasterPageLoginTable = this.Master.FindControl("LoginTable");
            MasterPageLoginTable.Visible = false;
        }

        UsernameTB.Focus();
        Page.Form.DefaultButton = SLoginButton.UniqueID;
    }
コード例 #7
0
ファイル: RssWriter.cs プロジェクト: vatsal/getputs
    public RssWriter(XmlWriter tw)
    {
        m_writer = tw;

        links = Links.Instance;
        gui = GUIVariables.Instance;
    }
コード例 #8
0
ファイル: Folder.cs プロジェクト: Huddle/Puddle
 public Folder(string description, DateTime created, DateTime updated, string title, Links links)
 {
     Links = links;
     Title = title;
     Updated = updated;
     Created = created;
     Description = description;
 }
コード例 #9
0
ファイル: Footer.master.cs プロジェクト: vatsal/Stoocker
    protected void Page_Load(object sender, EventArgs e)
    {
        links = (Links)Application["links"];
        gui = (GUIVariables)Application["gui"];

        CopyrightLabel.Text = gui.SmallFontStart + gui.GrayFontStart
            + copyrightText
            + gui.GrayFontEnd + gui.SmallFontEnd;
    }
コード例 #10
0
ファイル: User.cs プロジェクト: Huddle/Puddle
 public User(Links links, dynamic personalProfile, IEnumerable<Workspace> workspaces)
 {
     base.Links = links;
     if (personalProfile != null)
     {
         DisplayName = personalProfile.displayname;
     }
     Workspaces = workspaces;
 }
コード例 #11
0
ファイル: Document.cs プロジェクト: Huddle/Puddle
 public Document(string description, DateTime created, DateTime updated, int size, string version, string title, Links links)
 {
     Links = links;
     Title = title;
     Version = version;
     Size = size;
     Updated = updated;
     Created = created;
     Description = description;
 }
コード例 #12
0
ファイル: RandomNews.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        engine = ProcessingEngine.Instance;
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        Random random = new Random();

        bool isDone = false;
        string link = string.Empty;

        //string queryString = "SELECT COUNT(*) FROM item WHERE Spam = 0;";
        //int retInt = dbOps.ExecuteScalar(queryString);

        int retInt = engine.ItemRowCount;

        if (retInt > 0)
        {
            int rowCount = retInt;
            int rowNumber = random.Next(0, rowCount);

            while (!isDone)
            {
                string queryString = "SELECT Link FROM item WHERE Spam = 0 AND IID = " + rowNumber + ";";
                MySqlDataReader retList = dbOps.ExecuteReader(queryString);

                if (retList != null && retList.HasRows)
                {
                    //   DB Hit.
                    while (retList.Read())
                    {
                        link = Convert.ToString(retList["Link"]);
                    }
                    retList.Close();
                    isDone = true;
                }
                else
                {
                    //   DB Miss. Select another random number.
                    rowNumber = random.Next(0, rowCount);
                }
            }

            if (isDone && !string.IsNullOrEmpty(link))
            {
                Response.Redirect(link, true);
            }
        }
        else
        {
            //  Not decided what to do.
            //  May be redirect back to getputs.
            Response.Redirect(links.FrontPageLink, true);
        }
    }
コード例 #13
0
ファイル: LinkBuilder.cs プロジェクト: adammflax/Puddle
        public static Links Build(dynamic response)
        {
            var listLinks = new List<Link>();
            foreach (dynamic li in response.link)
            {
                listLinks.Add(new Link(li.rel, li.href));
            }

            var links = new Links(listLinks);
            return links;
        }
コード例 #14
0
ファイル: RssPage.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        links = Links.Instance;
        gui = GUIVariables.Instance;
        dbOps = DBOperations.Instance;
        categories = Categories.Instance;
        log = Logger.Instance;
        engine = ProcessingEngine.Instance;

        WriteRSSFile();
        Response.Redirect(links.RssFeedLink, false);
    }
コード例 #15
0
ファイル: Registration.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        gui = GUIVariables.Instance;
        engine = ProcessingEngine.Instance;

        //  If not using ReCaptcha Project, but using the other Captcha Library.
        //if (!IsPostBack)
        //{
        //    HttpContext.Current.Session["CaptchaImageText"] = general.GenerateRandomCode();
        //}
    }
コード例 #16
0
ファイル: Registration.aspx.cs プロジェクト: vatsal/Stoocker
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = (DBOperations)Application["dbOps"];
        links = (Links)Application["links"];
        general = (General)Application["general"];
        gui = (GUIVariables)Application["gui"];
        engine = (ProcessingEngine)Application["engine"];

        AboutStoockerLabel.Text = gui.GrayFontStart
            + gui.StoocksFont + " is a Stock Recommendation Engine." + gui.LineBreak
            + "Maintain a " + gui.GreenFontStart + "Portfolio" + gui.GreenFontEnd + " of your stocks." + gui.LineBreak
            + "Get updated " + gui.GreenFontStart + "News" + gui.GreenFontEnd + " about the latest happenings in the Stock Market." + gui.LineBreak
            + gui.GreenFontStart + "Predict" + gui.GreenFontEnd + " tomorrows movement of your favorite stocks." + gui.LineBreak
            + "See what the other users " + gui.GreenFontStart + "Recommend" + gui.GreenFontEnd + " about the stock movement for tomorrow."
            + gui.GrayFontEnd;
    }
コード例 #17
0
ファイル: Uploader.cs プロジェクト: mard/Uploader
        static void Main(string[] args)
        {
            // Registering handler for unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

            // Fetching global configuration
            var general = new ConfigurationGeneral();
            general.LoadGeneral(Globals.SettingsFile);

            // Fetching data from command-line arguments
            var argumentdata = new ArgumentData(args);

            // Create temporary directory for copied files.
            Common.CreateTemporaryDirectory();

            // List of URLs to be copied to clipboard.
            Links links = new Links();

            for (int i = argumentdata.Files.Count - 1; i >= 0; i--)
            {
                var filename = Path.GetFileName(argumentdata.Files[i]);

                var currentclipboardurl = Common.ParseTemplate(argumentdata.Profile.ClipboardURL).Replace("%file%", HttpUtility.UrlPathEncode(filename));
                links.Add(currentclipboardurl);

                var newfilename = Path.Combine(Globals.TemporaryDirectory, filename);
                File.Copy(argumentdata.Files[i], newfilename, true);

                // TODO: touch or not? Store this preference in profile configuration
                System.IO.File.SetLastWriteTimeUtc(newfilename, DateTime.UtcNow.AddSeconds(i));
            }

            if (Directory.GetFileSystemEntries(Globals.TemporaryDirectory).Length > 0)
            {
                Upload.UploadFiles(argumentdata.Profile, Globals.TemporaryDirectory, argumentdata.Profile.RemoteDir);

                links.ToClipboard(argumentdata.Profile);
                Common.PlaySound(argumentdata.Profile);
            }
            Common.DeleteTemporaryDirectory();
            Environment.Exit(0);
        }
コード例 #18
0
ファイル: ForgotPassword.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        gui = GUIVariables.Instance;
        log = Logger.Instance;
        general = General.Instance;
        engine = ProcessingEngine.Instance;

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.
        string UID = string.Empty;
        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            UID = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (!string.IsNullOrEmpty(UID))
        {
            Response.Redirect(links.FrontPageLink, false);
        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists
    }
コード例 #19
0
ファイル: LinkTest.cs プロジェクト: iljafiers/FotoLab
        public void ConvertToJsonTest()
        {
            Links link = GetLinks();

            Assert.IsFalse(link.ConvertToJson().Length == 0);
        }
コード例 #20
0
ファイル: EditComment.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        gui = GUIVariables.Instance;
        engine = ProcessingEngine.Instance;
        imageEngine = ImageEngine.Instance;
        categories = Categories.Instance;
        tagger = new Tagger();

        seperator = gui.Seperator;

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.

        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            user = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (string.IsNullOrEmpty(user))
        {
            //  Response.Redirect(links.LoginLink, false);
            MessageLabel.Text = gui.RedFontStart + "Please login to enter a comment." + gui.RedFontEnd;
        }
        else
        {

        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        if (string.IsNullOrEmpty(Request.QueryString["uid"]) || string.IsNullOrEmpty(Request.QueryString["iid"]) || string.IsNullOrEmpty(Request.QueryString["cid"]))
        {
            Response.Redirect(links.FrontPageLink, true);
        }
        else
        {
            uid = Request.QueryString["uid"].Trim();
            iid = Request.QueryString["iid"].Trim();
            cid = Request.QueryString["cid"].Trim();
        }

        if (!general.IsValidInt(iid) || !general.IsValidInt(cid) || !uid.Equals(user))
        {
            Response.Redirect(links.FrontPageLink, true);
        }
        else
        {
            string comment = LoadComment(uid, iid, cid);

            if (string.IsNullOrEmpty(comment))
            {
                Response.Redirect(links.FrontPageLink, true);
            }
            else
            {
                MessageLabel.Text = gui.GreenFontStart + "Your comment cannot be edited."
                    + gui.LineBreak + "However, you can append more details to your previous comment." + gui.GreenFontEnd;

                CurrentCommentLabel.Text = gui.GreenFontStart + "Your comment: " + gui.GreenFontEnd + gui.LineBreak + comment;
            }
        }
    }
コード例 #21
0
ファイル: Save.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        categories = Categories.Instance;
        engine = ProcessingEngine.Instance;
        log = Logger.Instance;

        UID = string.Empty;
        url = string.Empty;

        //  log.Log("PathInfo: " + Request.PathInfo);

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.

        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            UID = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }

        if (string.IsNullOrEmpty(UID))
        {
            Response.Redirect(links.LoginLink);
        }
        else
        {

        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        //  Update the SavedItems DB
        if (!string.IsNullOrEmpty(UID) && !string.IsNullOrEmpty(Request.QueryString["iid"]))
        {
            string IID = Request.QueryString["iid"];

            //  Make sure that the IID is a valid integer.
            if (general.IsValidInt(IID))
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string queryString = "INSERT INTO saveditems VALUES ('" + UID + "' , " + IID + " , '" + date + "');";
                int retInt = dbOps.ExecuteNonQuery(queryString);

                //  Also update the getputs.item NSaved Field.
                queryString = "UPDATE item SET NSaved=NSaved+1 WHERE IID=" + IID + ";";
                retInt = dbOps.ExecuteNonQuery(queryString);

                Response.Redirect(Context.Request.UrlReferrer.OriginalString);
            }
            else
            {
                Response.Redirect(links.FrontPageLink);
            }
        }
        else
        {
            Response.Redirect(links.FrontPageLink);
        }
    }
コード例 #22
0
        public async Task ThenAValidResponseIsReturnedForAValidRequest()
        {
            string id = "1";

            Name name = new Name
            {
                NameLine1 = "Employer"
            };

            Employer employer = new Employer
            {
                Name = name
            };

            var links = new Links()
            {
                Declarations = new Declarations()
                {
                    Href = "testing/declarations/href"
                },
                Self = new Self()
                {
                    Href = "testing/self/href"
                },
                EmploymentCheck = new EmploymentCheck()
                {
                    Href = "testing/employmentcheck.href"
                },
                Fraction = new Fraction()
                {
                    Href = "testing/fraction/href"
                }
            };

            // Arrange
            employerReferenceRepository = new Mock <IEmployerReferenceRepository>(MockBehavior.Strict);
            employerReferenceRepository
            .Setup(x => x.GetEmployerReference(empRef))
            .ReturnsAsync(new EmployerReference()
            {
                Id       = id,
                Links    = links,
                EmpRef   = empRef,
                Employer = employer
            });

            var sut = new GetEmployerReferenceQuery(employerReferenceRepository.Object);

            // Act
            var result = await sut.Get(new GetEmployerReferenceRequest(empRef));

            // Assert
            result.Should().NotBeNull();
            result.EmployerReference.Should().NotBeNull();
            result.EmployerReference.Id.Should().Be(id);
            result.EmployerReference.EmpRef.Should().Be(empRef);
            result.EmployerReference.Employer.Should().NotBeNull();
            result.EmployerReference.Employer.Name.Should().Be(employer.Name);
            result.EmployerReference.Links.Should().NotBeNull();
            result.EmployerReference.Links.Self.Should().NotBeNull();
            result.EmployerReference.Links.Self.Href.Should().Be(links.Self.Href);
            result.EmployerReference.Links.Fraction.Should().NotBeNull();
            result.EmployerReference.Links.Fraction.Href.Should().Be(links.Fraction.Href);
            result.EmployerReference.Links.Declarations.Should().NotBeNull();
            result.EmployerReference.Links.Declarations.Href.Should().Be(links.Declarations.Href);
            result.EmployerReference.Links.EmploymentCheck.Should().NotBeNull();
            result.EmployerReference.Links.EmploymentCheck.Href.Should().Be(links.EmploymentCheck.Href);
        }
コード例 #23
0
        /// <summary>
        /// Metoda získá seznam kategorií chatovacích místností.
        /// </summary>
        public Links getChatRoomCategories()
        {
            Links kategorie = new Links();
            kategorie.Add(new CategoryLink("Města a kraje","modchat?op=roomlist&cid=1","info"));
            kategorie.Add(new CategoryLink("Pokec a klábosení","modchat?op=roomlist&cid=2","info"));
            kategorie.Add(new CategoryLink("Seznámení a flirt","modchat?op=roomlist&cid=4","info"));
            kategorie.Add(new CategoryLink("Lechtivá erotika","modchat?op=roomlist&cid=8","info"));
            kategorie.Add(new CategoryLink("Volný čas a sport","modchat?op=roomlist&cid=16","info"));
            kategorie.Add(new CategoryLink("Sex a neřesti do 18 let","modchat?op=roomlist&cid=32","info"));
            kategorie.Add(new CategoryLink("Hudební styly a kapely","modchat?op=roomlist&cid=64","info"));
            kategorie.Add(new CategoryLink("Filmy, knihy a počítače","modchat?op=roomlist&cid=128","info"));

            return kategorie;

            //možno řešit přes parsování html stránky - zatím zbytečně složité
            //metoda zatím vrátí jen seznam prvků [jméno,odkaz]
            //string httpContent = "";

            ////odpovědí na tuhle request je packet z html stránkou, pokud je ssk správně
            //HttpWebRequest request = makeRequest(XCHAT_URI + "/" + ssk + "/index.php",httpContent);

            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //if(response.StatusCode == HttpStatusCode.OK)
            //{
            //    //načtení html stránky ze streamu
            //    Stream stream = response.GetResponseStream();
            //    StreamReader sr = null;

            //    //kvůli kódování řetězců
            //    if(response.CharacterSet == null)
            //    {
            //        sr = new StreamReader(stream);
            //    }
            //    else
            //    {
            //        sr = new StreamReader(stream, Encoding.GetEncoding(response.CharacterSet));
            //    }

            //    //přečtení streamu
            //    string data = sr.ReadToEnd();

            //    WebBrowser wb = new WebBrowser();
            //    wb.NavigateToString(data);

            //    sr.Close();
            //    response.Close();

            //}
        }
コード例 #24
0
 public void Add(string pName, string pUrl)
 {
     Links.Add(new RibbonLink {
         Name = pName, Url = pUrl
     });
 }
コード例 #25
0
ファイル: Interests.aspx.cs プロジェクト: vatsal/Stoocker
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = (DBOperations)Application["dbOps"];
        gui = (GUIVariables)Application["gui"];
        links = (Links)Application["links"];
        engine = (ProcessingEngine)Application["engine"];

        //  username = Convert.ToString(Session["username"]);

        if (Request.Cookies["stoockerCookie"] != null)
        {
            HttpCookie stoockerCookie = Request.Cookies["stoockerCookie"];
            username = dbOps.Decrypt(stoockerCookie["username"].ToString().Trim());
        }

        if (string.IsNullOrEmpty(username))
        {
            Response.Redirect(links.SessionExpiredPageLink);
        }

        FindStockTB.Attributes.Add("onkeypress", "if ((event.which ? event.which : event.keyCode) == 13){document.getElementById('" + FindStockButton.UniqueID + "').click(); }");

        //  InterestsLabel.Text = "Select the Stocks you would like to <font color=\"Red\">Stoock!!<\font>";
        InterestsLabel.Text = "Other User's have been making predictions for the stocks shown."
            + "Select the Stocks you would like to " + gui.StoockFont
            + gui.LineBreak + "(Max. of " + gui.RedFontStart + maxStocksPerUser.ToString() + gui.RedFontEnd + " stocks allowed)";

        string findStockMessage = "Could not find the Symbol you were looking for?"
                + gui.LineBreak + gui.StoocksFont + " only shows the Stocks which other Stoockers have predicted."
                + gui.LineBreak  + "Type the Symbol of the Stock you want to analyze and " + gui.StoocksFont + " will add the Symbol for You.";
        FindStockLabel.Text = findStockMessage;

        if (!Page.IsPostBack)
        {
            FillStocksCBL();
            ShowAlreadySelectedStocks(username);

            //  AlphabeticButton.Attributes.Add("onmouseover", "this.style.backgroundColor='red'");
            //  AlphabeticButton.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
        }

        for (int i = 0; i < StocksCBL.Items.Count; i++)
        {
            StocksCBL.Items[i].Attributes.Add("onmouseover", "this.style.backgroundColor='red'");
            StocksCBL.Items[i].Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
        }

        FindStockTB.Attributes.Add("onkeypress", "if ((event.which ? event.which : event.keyCode) == 13){var sendElem = document.getElementById(\"FindStockButton\"); if(!sendElem.disabled) FindStockButton_Click(); }");
    }
コード例 #26
0
        public async Task <Response> Get(
            ReadAllStreamOperation operation,
            CancellationToken cancellationToken)
        {
            if (_useCanonicalUrls && !operation.IsUriCanonical)
            {
                return(new PermanentRedirectResponse(operation.Self));
            }

            var page = await operation.Invoke(_streamStore, cancellationToken);

            var streamMessages = page.Messages.OrderByDescending(m => m.Position).ToArray();

            var payloads = await Task.WhenAll(
                Array.ConvertAll(
                    streamMessages,
                    message => operation.EmbedPayload
                        ? message.GetJsonData(cancellationToken)
                        : SkippedPayload.Instance));

            var response = new HalJsonResponse(
                new HALResponse(new
            {
                page.FromPosition,
                page.NextPosition,
                page.IsEnd
            })
                .AddLinks(
                    Links
                    .FromOperation(operation)
                    .Index()
                    .Find()
                    .Browse()
                    .AllStreamNavigation(page, operation))
                .AddEmbeddedCollection(
                    Constants.Relations.Message,
                    streamMessages.Zip(
                        payloads,
                        (message, payload) => new StreamMessageHALResponse(message, payload)
                        .AddLinks(
                            Links
                            .FromOperation(operation)
                            .Add(
                                Constants.Relations.Message,
                                LinkFormatter.StreamMessageByStreamVersion(message.StreamId, message.StreamVersion),
                                $"{message.StreamId}@{message.StreamVersion}")
                            .Self()
                            .Add(
                                Constants.Relations.Feed,
                                LinkFormatter.Stream(message.StreamId),
                                message.StreamId)))));

            if (operation.FromPositionInclusive == Position.End)
            {
                var headPosition = streamMessages.Length > 0
                    ? streamMessages[0].Position
                    : Position.End;

                response.Headers[Constants.Headers.HeadPosition] = new[] { $"{headPosition}" };
            }

            if (page.TryGetETag(operation.FromPositionInclusive, out var eTag))
            {
                response.Headers.Add(eTag);
                response.Headers.Add(CacheControl.NoCache);
            }
            else
            {
                response.Headers.Add(CacheControl.OneYear);
            }

            return(response);
        }
コード例 #27
0
        // Public Methods (2) 

        public void Add(RibbonLink link)
        {
            Links.Add(link);
        }
コード例 #28
0
 /// <summary>
 /// Constructor for HypermediaObject which are acces using a query. Required to propperly build the self Link.
 /// </summary>
 protected HypermediaObject(IHypermediaQuery query)
 {
     Init();
     // hypemedia object is a queryresult so it needs a selflink with query
     Links.Add(DefaultHypermediaRelations.Self, new HypermediaObjectQueryReference(GetType(), query));
 }
コード例 #29
0
 internal Resource(TClass @class, Links links)
     : base(links) => this.@class = @class;
コード例 #30
0
        public void RemoveLinks(RiakObjectId riakObjectId)
        {
            var linksToRemove = Links.Where(l => l.Bucket == riakObjectId.Bucket && l.Key == riakObjectId.Key);

            linksToRemove.ForEach(l => Links.Remove(l));
        }
コード例 #31
0
        private RawlerBase CreateRawler(HtmlNode node)
        {
            RawlerBase rawler = null;

            bool flag次のノードを調べる = true;
            if (RawlerExpressLib.Automation.Extend.HTMLExtend.TargetAnalyzeTag.Contains(node.Name))
            {
                Tags tags = new Tags() { Tag = node.Name };
                if (node.Attributes.Where(n => n.Name == "class").Any())
                {
                    tags.ClassName = node.Attributes.Where(n => n.Name == "class").First().Value;
                }
                if (node.Attributes.Where(n => n.Name == "id").Any())
                {
                    tags.IdName = node.Attributes.Where(n => n.Name == "id").First().Value;
                }
                if (node.ChildNodes.Count() == 1 && node.ChildNodes.Where(n => n.Name == "#text").Any())
                {
                    tags.AddChildren(new DataWrite() { Attribute = GetCategoryName() + tags.ClassName });
                    flag次のノードを調べる = false;
                }
                if (node.Attributes.Where(n => n.Name == "style" && n.Value.Contains("background")).Any())
                {
                    tags.TagVisbleType = TagVisbleType.Outer;
                    rawler = tags.Add(new ImageLinks() { ImageType = ImageType.BackgroundImage }).DataWrite(CategoryName + "." + node.GetClassName() + "_Image", DataAttributeType.Image).GetRoot();
                }

                rawler = tags;
            }
            else if (node.Name == "a")
            {
                var url = node.OuterHtml.ToHtml(baseUrl).GetLink().FirstDefault<RawlerLib.Web.Link, string>(n => n.Url, null);
                if (url != null)
                {
                    {
                        rawler = new Links() { VisbleType = LinkVisbleType.Tag }.AddRange(
                            new Links() { VisbleType = LinkVisbleType.Url }.DataWrite(GetCategoryName() + node.GetClassName() + "_Link").GetRoot(),
                            new Links() { VisbleType = LinkVisbleType.Label }.DataWrite(GetCategoryName() + node.GetClassName() + "_Label").GetRoot()
                        );

                    }
                }
                else
                {
                    //URLがないAタグの場合。
                    Tags tags = new Tags() { Tag = node.Name };
                    if (node.Attributes.Where(n => n.Name == "class").Any())
                    {
                        tags.ClassName = node.Attributes.Where(n => n.Name == "class").First().Value;
                    }
                    if (node.Attributes.Where(n => n.Name == "id").Any())
                    {
                        tags.IdName = node.Attributes.Where(n => n.Name == "id").First().Value;
                    }
                    rawler = tags;
                }
                if (node.ChildNodes.Count == 1 && node.ChildNodes.Where(n => n.Name == "#text").Any())
                {
                    flag次のノードを調べる = false;
                }

            }
            else if (node.Name == "img")
            {

                var url = node.OuterHtml.ToHtml(baseUrl).GetImageLink().FirstDefault(n => n.Url, null);
                if (url != null)
                {
                    rawler = new ImageLinks().DataWrite(GetCategoryName() + node.GetClassName() + "_Image", DataAttributeType.Image).GetRoot();
                }

            }
            ///背景画像に反応させる。
            else if (node.Attributes.Where(n => n.Name == "style" && n.Value.Contains("background")).Any())
            {
                rawler = new ImageLinks() { ImageType = ImageType.BackgroundImage }.DataWrite(GetCategoryName() + node.GetClassName() + "_Image", DataAttributeType.Image).GetRoot();
            }
            else if (node.Name == "span")
            {
                Tags tags = new Tags() { Tag = node.Name };
                if (node.Attributes.Where(n => n.Name == "class").Any())
                {
                    tags.ClassName = node.Attributes.Where(n => n.Name == "class").First().Value;
                }
                if (node.ChildNodes.Count() == 1 && node.ChildNodes.Where(n => n.Name == "#text").Any())
                {
                    tags.AddChildren(new DataWrite() { Attribute = GetCategoryName() + tags.ClassName });
                    flag次のノードを調べる = false;
                }

                rawler = tags;
            }
            else
            {
                var t = node.OuterHtml.Replace("\n", "").Trim();
                if (t.Length > 0)
                {
                    rawler = new TagClear().Trim().Add(new DataWrite() { Attribute = GetCategoryName() + node.GetClassName() + "_" + node.Name }).GetRoot();
                    if (node.ChildNodes.Count == 1 && node.ChildNodes.Where(n => n.Name == "#text").Any())
                    {
                        flag次のノードを調べる = false;
                    }
                }
            }
            if (rawler != null && node.ChildNodes.Count == 1 && node.ChildNodes.Where(n => n.Name == "span").Any())
            {
                rawler.AddChildren(new DataWrite() { Attribute = GetCategoryName() + node.GetClassName() });
            }

            foreach (var item in node.ChildNodes)
            {
                if (flag次のノードを調べる)
                {
                    var r = CreateRawler(item);

                    if (r != null && rawler != null)
                    {
                        rawler.AddChildren(r);
                    }
                    else
                    {
                        if (r != null && rawler == null)
                        {
                            rawler = r;
                        }
                    }
                }

            }
            return rawler;
        }
コード例 #32
0
        //public ActionResult PaymentWithCreditCard()
        //{
        //    //create and item for which you are taking payment
        //    //if you need to add more items in the list
        //    //Then you will need to create multiple item objects or use some loop to instantiate object
        //    Item item = new Item();
        //    item.name = "Demo Item";
        //    item.currency = "USD";
        //    item.price = "5";
        //    item.quantity = "1";
        //    item.sku = "sku";

        //    //Now make a List of Item and add the above item to it
        //    //you can create as many items as you want and add to this list
        //    List<Item> itms = new List<Item>();
        //    itms.Add(item);
        //    ItemList itemList = new ItemList();
        //    itemList.items = itms;

        //    //Address for the payment
        //    Address billingAddress = new Address();
        //    billingAddress.city = "NewYork";
        //    billingAddress.country_code = "US";
        //    billingAddress.line1 = "23rd street kew gardens";
        //    billingAddress.postal_code = "43210";
        //    billingAddress.state = "NY";


        //    //Now Create an object of credit card and add above details to it
        //    CreditCard crdtCard = new CreditCard();
        //    crdtCard.billing_address = billingAddress;
        //    crdtCard.cvv2 = "874";
        //    crdtCard.expire_month = 1;
        //    crdtCard.expire_year = 2020;
        //    crdtCard.first_name = "Aman";
        //    crdtCard.last_name = "Thakur";
        //    crdtCard.number = "1234567890123456";
        //    crdtCard.type = "discover";

        //    // Specify details of your payment amount.
        //    Details details = new Details();
        //    details.shipping = "1";
        //    details.subtotal = "5";
        //    details.tax = "1";

        //    // Specify your total payment amount and assign the details object
        //    Amount amnt = new Amount();
        //    amnt.currency = "USD";
        //    // Total = shipping tax + subtotal.
        //    amnt.total = "7";
        //    amnt.details = details;

        //    // Now make a trasaction object and assign the Amount object
        //    Transaction tran = new Transaction();
        //    tran.amount = amnt;
        //    tran.description = "Description about the payment amount.";
        //    tran.item_list = itemList;
        //    tran.invoice_number = "your invoice number which you are generating";

        //    // Now, we have to make a list of trasaction and add the trasactions object
        //    // to this list. You can create one or more object as per your requirements

        //    List<Transaction> transactions = new List<Transaction>();
        //    transactions.Add(tran);

        //    // Now we need to specify the FundingInstrument of the Payer
        //    // for credit card payments, set the CreditCard which we made above

        //    FundingInstrument fundInstrument = new FundingInstrument();
        //    fundInstrument.credit_card = crdtCard;

        //    // The Payment creation API requires a list of FundingIntrument

        //    List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
        //    fundingInstrumentList.Add(fundInstrument);

        //    // Now create Payer object and assign the fundinginstrument list to the object
        //    Payer payr = new Payer();
        //    payr.funding_instruments = fundingInstrumentList;
        //    payr.payment_method = "credit_card";

        //    // finally create the payment object and assign the payer object & transaction list to it
        //    Payment pymnt = new Payment();
        //    pymnt.intent = "sale";
        //    pymnt.payer = payr;
        //    pymnt.transactions = transactions;

        //    try
        //    {
        //        //getting context from the paypal, basically we are sending the clientID and clientSecret key in this function
        //        //to the get the context from the paypal API to make the payment for which we have created the object above.

        //        //Code for the configuration class is provided next

        //        // Basically, apiContext has a accesstoken which is sent by the paypal to authenticate the payment to facilitator account. An access token could be an alphanumeric string

        //        APIContext apiContext = Configuration.GetAPIContext();

        //        // Create is a Payment class function which actually sends the payment details to the paypal API for the payment. The function is passed with the ApiContext which we received above.

        //        Payment createdPayment = pymnt.Create(apiContext);

        //        //if the createdPayment.State is "approved" it means the payment was successfull else not

        //        if (createdPayment.state.ToLower() != "approved")
        //        {
        //            return View("FailureView");
        //        }
        //    }
        //    catch (PayPal.PayPalException ex)
        //    {
        //        Logger.Log("Error: " + ex.Message);
        //        return View("FailureView");
        //    }

        //    return View("SuccessView");
        //}

        public ActionResult PaymentWithPaypal()
        {
            //getting the apiContext as earlier
            APIContext apiContext = Configuration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist

                    //it is returned by the create function call of the payment class

                    // Creating a payment

                    // baseURL is the url on which paypal sendsback the data.

                    // So we have provided URL of this controller only

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPayPal?";

                    //guid we are generating for storing the paymentID received in session

                    //after calling the create function and it is used in the payment execution

                    var guid = Convert.ToString((new Random()).Next(100000));

                    //CreatePayment function gives us the payment approval url

                    //on which payer is redirected for paypal acccount payment

                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //get links returned from paypal in response to Create function call

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

                    var guid = Request.Params["guid"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                //Logger.Log("Error"+ ex.Message);
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
コード例 #33
0
ファイル: UrlModule.cs プロジェクト: wbonekamp/DNNQA
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void OnBeginRequest(Object source, EventArgs e)
        {
            try
            {
                var                   app     = (HttpApplication)source;
                var                   context = app.Context;
                PortalSettings        portalSettings;
                PortalAliasController pac = new PortalAliasController();

                PortalInfo portalInfo;
                //var requestedPath = app.Request.Url.AbsoluteUri;
                PortalAliasInfo objPortalAlias;

                var url = context.Request.RawUrl.Replace("?" + context.Request.QueryString, "").ToLower();

                if (Utils.UseFriendlyUrls && (url.EndsWith(".aspx") || url.EndsWith("/")))
                {
                    var myAlias = DotNetNuke.Common.Globals.GetDomainName(app.Request, true);

                    do
                    {
                        objPortalAlias = PortalAliasController.GetPortalAliasInfo(myAlias);

                        if (objPortalAlias != null)
                        {
                            break;
                        }

                        var slashIndex = myAlias.LastIndexOf('/');
                        myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : "";
                    } while (myAlias.Length > 0);

                    if (objPortalAlias == null)
                    {
                        //portalSettings = new PortalSettings(Host.HostPortalID);
                        //var portalAlias = app.Request.Url.Host;
                        //objPortalAlias = PortalAliasController.GetPortalAliasInfo(portalAlias);
                        return;
                        //if (Host.HostPortalID > Null.NullInteger)
                        //{
                        //    var portalAliasInfo = new PortalAliasInfo
                        //                              {
                        //                                  PortalID = Host.HostPortalID,
                        //                                  HTTPAlias = portalAlias
                        //                              };
                        //    pac.AddPortalAlias(portalAliasInfo);

                        //objPortalAlias = PortalAliasController.GetPortalAliasInfo(portalAlias);
                        //}
                    }
                    else
                    {
                        portalInfo     = new PortalController().GetPortal(objPortalAlias.PortalID);
                        portalSettings = new PortalSettings(portalInfo.PortalID);
                    }

                    if (portalSettings != null)
                    {
                        portalSettings.PortalAlias = objPortalAlias;

                        Regex questionRegEx;
                        Regex tagRegEx;

                        questionRegEx = new Regex("/" + Utils.GetQuestionUrlName(portalSettings).ToLower() + "/([0-9]+)/(.+)(\\.aspx$|\\.aspx?.+)", RegexOptions.IgnoreCase);
                        tagRegEx      = new Regex("/" + Utils.GetTagUrlName(portalSettings).ToLower() + "/(.+)(\\.aspx$|\\.aspx?.+)", RegexOptions.IgnoreCase);

                        if ((questionRegEx.IsMatch(url.ToLower()) && !questionRegEx.Match(url.ToLower()).Groups[1].Value.Contains("/")) || (tagRegEx.IsMatch(url.ToLower()) && !tagRegEx.Match(url.ToLower()).Groups[1].Value.Contains("/")))
                        {
                            string questionTitle;
                            string tagName;


                            // JS 1/25/12: This check is for removing the .aspx from the question and tags.
                            //             There appears to be conflicts between IIS7.5 installations that need to be address
                            //if (HttpRuntime.UsingIntegratedPipeline)
                            //{
                            //    questionRegEx = new Regex("/Question/([0-9]+)/(.+)", RegexOptions.IgnoreCase);
                            //    tagRegEx = new Regex("/Tag/(.+)", RegexOptions.IgnoreCase);
                            //}
                            //else
                            //{
                            //    questionRegEx = new Regex("/Question/([0-9]+)/(.+)\\.aspx$", RegexOptions.IgnoreCase);
                            //    tagRegEx = new Regex("/Tag/(.+)\\.aspx$", RegexOptions.IgnoreCase);
                            //}

                            var dnnqa = new DnnqaController();
                            var tInfo = Utils.GetTabFromUrl(portalSettings);

                            if (tInfo != null && Utils.IsModuleOnTab(tInfo.TabID))
                            {
                                var    match = questionRegEx.Match(url);
                                String relativePath;
                                if (match.Success)
                                {
                                    var questionId = Int32.Parse(match.Groups[1].Value);
                                    questionTitle = match.Groups[2].Value;
                                    if (tInfo != null)
                                    {
                                        QuestionInfo qInfo = dnnqa.GetQuestion(questionId, portalSettings.PortalId);

                                        if (qInfo != null)
                                        {
                                            if (Utils.CreateFriendlySlug(qInfo.Title).ToLower() == questionTitle.ToLower())
                                            {
                                                relativePath = Links.ViewQuestion(questionId, tInfo.TabID, portalSettings).Replace("http://", "").Replace("https://", "").Replace(objPortalAlias.HTTPAlias.Contains("/") ? objPortalAlias.HTTPAlias.Substring(0, objPortalAlias.HTTPAlias.IndexOf("/")) : objPortalAlias.HTTPAlias, "");

                                                context.RewritePath(relativePath);
                                                return;
                                            }
                                            context.Response.Status           = "301 Moved Permanently";
                                            context.Response.RedirectLocation = Links.ViewQuestion(questionId, qInfo.Title, tInfo, portalSettings);
                                        }
                                    }
                                }

                                match = tagRegEx.Match(url);
                                if (match.Success)
                                {
                                    tagName      = match.Groups[1].Value;
                                    tagName      = tagName.Replace("-", " ");
                                    relativePath = Links.ViewTaggedQuestions(tagName, tInfo.TabID, portalSettings).Replace("http://", "").Replace("https://", "").Replace(objPortalAlias.HTTPAlias.Contains("/") ? objPortalAlias.HTTPAlias.Substring(0, objPortalAlias.HTTPAlias.IndexOf("/")) : objPortalAlias.HTTPAlias, "");

                                    context.RewritePath(relativePath);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
            }
        }
コード例 #34
0
        public ActionResult PaymentWithPaypal(string Cancel = null)
        {
            //getting the apiContext
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                //A resource representing a Payer that funds a payment Payment Method as paypal
                //Payer Id will be returned when payment proceeds or click to pay
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist
                    //it is returned by the create function call of the payment class
                    // Creating a payment
                    // baseURL is the url on which paypal sendsback the data.
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Home/PaymentWithPayPal?";
                    //here we are generating guid for storing the paymentID received in session
                    //which will be used in the payment execution
                    var guid = Convert.ToString((new Random()).Next(100000));
                    //CreatePayment function gives us the payment approval url
                    //on which payer is redirected for paypal account payment
                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                    //get links returned from paypal in response to Create function call
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This function exectues after receving all parameters for the payment
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    //If executed payment failed then we will show payment failure message to user
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("SuccessView"));
                        //System.Diagnostics.Debug.Write("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                        // return View("FailureView",new { s=10 });
                    }
                }
            }
            catch (Exception ex)
            {
                return(View("SuccessView"));
                //System.Diagnostics.Debug.Write("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
                //return View("FailureView", new { s = 20 });
            }
            //on successful payment, show success page to user.
            return(View("SuccessView"));
        }
コード例 #35
0
 public void RemoveLink(RiakLink link)
 {
     Links.Remove(link);
 }
コード例 #36
0
        public ActionResult PaymentWithPaypal(Order model, string Cancel = null)
        {
            SqlConnection con        = new SqlConnection("Data Source=NHU-QUYNH\\SQLEXPRESS;Database=MultiShop;Integrated Security=True;");
            SqlCommand    cmdf       = new SqlCommand("UPDATE Orders SET Result  = 'Failed' WHERE (CustomerId = @CustID) and (OrderDate = @date)", con);
            SqlCommand    cmds       = new SqlCommand("UPDATE Orders SET Result  = 'Success' WHERE (CustomerId = @CustID)  and (OrderDate = @date)", con);
            APIContext    apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                //A resource representing a Payer that funds a payment Payment Method as paypal
                //Payer Id will be returned when payment proceeds or click to pay
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist
                    //it is returned by the create function call of the payment class
                    // Creating a payment
                    // baseURL is the url on which paypal sendsback the data.
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Payment/PaymentWithPayPal?";
                    //here we are generating guid for storing the paymentID received in session
                    //which will be used in the payment execution
                    var guid = Convert.ToString((new Random()).Next(100000));
                    //CreatePayment function gives us the payment approval url
                    //on which payer is redirected for paypal account payment
                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                    //var createdPayment = this.CreatePayment(apiContext, baseURI);
                    //get links returned from paypal in response to Create function call
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    cmds.Parameters.AddWithValue("@CustID", model.CustomerId);
                    cmds.Parameters.AddWithValue("@date", model.OrderDate);
                    con.Open();
                    cmds.ExecuteNonQuery();
                    con.Close();

                    // saving the paymentID in the key guid
                    Session.Add("guid", createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This function exectues after receving all parameters for the payment
                    var guid = Request.Params["guid"];
                    // Session.Add("PayerId", payerId);
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    //If executed payment failed then we will show payment failure message to user
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        cmdf.Parameters.AddWithValue("@CustID", model.CustomerId);
                        cmdf.Parameters.AddWithValue("@date", model.OrderDate);
                        con.Open();
                        cmdf.ExecuteNonQuery();
                        con.Close();
                    }
                    cmds.Parameters.AddWithValue("@CustID", model.CustomerId);
                    cmds.Parameters.AddWithValue("@date", model.OrderDate);
                    con.Open();
                    cmds.ExecuteNonQuery();
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                Session.Remove("PayerID");
                Session.Remove("guid");



                cmdf.Parameters.AddWithValue("@CustID", model.CustomerId);
                cmdf.Parameters.AddWithValue("@date", model.OrderDate);
                con.Open();
                cmdf.ExecuteNonQuery();
                con.Close();


                return(View("FailureView"));
            }



            //on successful payment, show success page to user.
            return(View("SucessView"));
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: Hoheckell/desafiopokemon
        public static void GetHtmlCardsData(Links links, int numpaginas, int uniq)
        {
            List <Card>           cardsList      = new List <Card>();
            List <List <string> > cardsListmulti = new List <List <string> >();

            Parallel.ForEach(links.links,
                             link => {
                var webClient             = new System.Net.WebClient();
                string pagina             = webClient.DownloadString("https://www.pokemon.com" + link);
                HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
                htmlDocument.LoadHtml(pagina);
                Parallel.ForEach(htmlDocument.DocumentNode.SelectNodes("//div[@class='color-block color-block-gray']"),
                                 node =>
                {
                    var t = node.ChildNodes["h1"];
                    if (t != null && link != null)
                    {
                        Card c      = new Card();
                        c.Nome      = t.InnerText;
                        t           = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='stats-footer']/span");
                        c.Numerãção = t.InnerText;
                        t           = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='stats-footer']/h3");
                        c.Expansao  = t.InnerText;
                        c.Url       = "https://www.pokemon.com" + link;
                        c.Image     = links.images.FirstOrDefault(x => x.Key == link).Value;
                        cardsList.Add(c);
                    }
                });
            });
            if (uniq == 2)
            {
                for (var i = 0; i < numpaginas; i++)
                {
                    var      c    = 1;
                    string   path = @"C:\temp\cards" + i + ".json";
                    FileInfo fi   = new FileInfo(path);
                    string   json = string.Empty;
                    foreach (var card in cardsList)
                    {
                        if (c <= 12)
                        {
                            json += JsonConvert.SerializeObject(card) + ",";
                            c++;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (!fi.Exists && !string.IsNullOrEmpty(json))
                    {
                        using (StreamWriter file = fi.CreateText())
                        {
                            json = json.Remove(json.Length - 1);
                            file.WriteLine("[" + json + "]");
                            file.WriteLine();
                            file.Close();
                        }
                    }
                }
            }
            else
            {
                string   path = @"C:\temp\cards.json";
                FileInfo fi   = new FileInfo(path);
                string   json = string.Empty;
                foreach (var card in cardsList)
                {
                    json += JsonConvert.SerializeObject(card) + ",";
                }

                if (!fi.Exists && !string.IsNullOrEmpty(json))
                {
                    using (StreamWriter file = fi.CreateText())
                    {
                        json = json.Remove(json.Length - 1);
                        file.WriteLine("[" + json + "]");
                        file.WriteLine();
                        file.Close();
                    }
                }
            }
        }
コード例 #38
0
ファイル: IrrigationTests.cs プロジェクト: lie112/ApsimX
        private static Zone CreateZoneWithSoil()
        {
            var zone = new Zone()
            {
                Area     = 1,
                Children = new List <IModel>()
                {
                    new Irrigation(),
                    new Soil()
                    {
                        Children = new List <IModel>()
                        {
                            new Physical()
                            {
                                Thickness = new double[] { 100, 300, 300, 300, 300, 300 },
                                BD        = new double[] { 1.36, 1.216, 1.24, 1.32, 1.372, 1.368 },
                                AirDry    = new double[] { 0.135, 0.214, 0.253, 0.261, 0.261, 0.261 },
                                LL15      = new double[] { 0.27, 0.267, 0.261, 0.261, 0.261, 0.261 },
                                DUL       = new double[] { 0.365, 0.461, 0.43, 0.412, 0.402, 0.404 },
                                SAT       = new double[] { 0.400, 0.481, 0.45, 0.432, 0.422, 0.424 },
                                Children  = new List <IModel>()
                                {
                                    new SoilCrop()
                                    {
                                        Name = "WheatSoil",
                                        KL   = new double[] { 0.06, 0.060, 0.060, 0.060, 0.060, 0.060 },
                                        LL   = new double[] { 0.27, 0.267, 0.261, 0.315, 0.402, 0.402 }
                                    }
                                }
                            },
                            new Organic()
                            {
                                Thickness = new double[] { 100, 300, 300, 300, 300, 300 },
                                Carbon    = new double[] { 2, 1, 0.5, 0.4, 0.3, 0.2 }
                            },
                            new Chemical()
                            {
                                Thickness = new double[] { 100, 300, 300, 300, 300, 300 },
                                CL        = new double[] { 38, double.NaN, 500, 490, 500, 500 }
                            },
                            new Sample()
                            {
                                Thickness = new double[] { 100, 300, 300, 300, 300, 300 },
                                SW        = new double[] { 0.103, 0.238, 0.253, 0.261, 0.261, 0.261 },
                                NO3       = new double[] { 23, 7, 2, 1, 1, 1 },
                                OC        = new double[] { 1.35, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN },
                                SWUnits   = Sample.SWUnitsEnum.Gravimetric
                            },
                            new Models.WaterModel.WaterBalance()
                            {
                                Thickness    = new double[] { 100, 300, 300, 300, 300, 300 },
                                SummerCona   = 6,
                                WinterCona   = 3,
                                SummerU      = 6,
                                WinterU      = 3,
                                CN2Bare      = 60,
                                CNCov        = 10,
                                CNRed        = 10,
                                DiffusConst  = 10,
                                DiffusSlope  = 10,
                                Salb         = 10,
                                ResourceName = "WaterBalance"
                            },
                            new Nutrient()
                            {
                                Children = new List <IModel>()
                                {
                                    new MockNutrientPool()
                                    {
                                        Name = "Inert"
                                    },
                                    new MockNutrientPool()
                                    {
                                        Name = "Microbial"
                                    },
                                    new MockNutrientPool()
                                    {
                                        Name = "Humic"
                                    },
                                    new MockNutrientPool()
                                    {
                                        Name = "FOMCellulose"
                                    },
                                    new MockNutrientPool()
                                    {
                                        Name = "FOMCarbohydrate"
                                    },
                                    new MockNutrientPool()
                                    {
                                        Name = "FOMLignin"
                                    },
                                    new MockNutrientPool()
                                    {
                                        Name = "SurfaceResidue"
                                    },
                                    new Solute()
                                    {
                                        Name = "NO3"
                                    },
                                    new Solute()
                                    {
                                        Name = "NH4"
                                    },
                                    new Solute()
                                    {
                                        Name = "Urea"
                                    }
                                }
                            },
                            new MockSoilTemperature(),
                        }
                    },
                    new MockClock()
                    {
                        Today = new DateTime(2019, 1, 1),
                    },
                    new Weather.MockWeather()
                    {
                        Latitude = 10.2,
                        MaxT     = 30,
                        MinT     = 15,
                        Radn     = 20
                    },
                    new MockSummary(),
                    new SurfaceOrganicMatter()
                    {
                        ResourceName       = "SurfaceOrganicMatter",
                        InitialResidueName = "Wheat",
                        InitialResidueType = "Wheat",
                    }
                }
            };

            zone.ParentAllDescendants();
            foreach (IModel model in zone.FindAllDescendants())
            {
                model.OnCreated();
            }
            var links = new Links();

            links.Resolve(zone, true);
            var events = new Events(zone);

            events.ConnectEvents();
            return(zone);
        }
コード例 #39
0
        /// <summary>
        /// Metoda slouží pro získání seznamu místností v kategorii, která je zadná linkem.
        /// Odkaz na místnost je ve formátu /modchat?op=mainframeset&rid=*******&js=0&nonjs=1
        /// </summary>
        /// <param name="link">Link z kategorie</param>
        /// <returns>Seznam položek ve tvaru [název,link]</returns>
        public Links getChatRoomsList(String link)
        {
            Links chatRooms = new Links();

            //uri na response se skládá z XCHAT_URI/ssk/link
            String uri = XCHAT_URI + "/" + SessionKey + "/" + link;

            //pro parsování
            HtmlDocument page = new HtmlDocument();

            //načtení stránky
            WebClient wc = new WebClient();
            String htmlString = wc.DownloadString(uri);

            //parsování
            page.LoadHtml(htmlString);
            //vybrat všechny td které mají id=c2
            //z nich pak vybrat <a> -> href, který začíná na XCHAT_URI
            //HtmlNodeCollection tds = page.DocumentNode.SelectNodes("//a[contains(@href,'" + XCHAT_URI + "/" + SessionKey + "/room" + "')]");

            //místnosti jsou v tabulce, v každém tr je kompletní záznam o místnosti
            HtmlNodeCollection tds = page.DocumentNode.SelectNodes("//tr");
            bool first = true;  //kvůli detekci prvního prvku, trochu prasárna

            /*
             * Přímej link na místnost má tvar
             * http://xchat.centrum.cz/ssk/modchat/room/nazev-mistnosti
             *
             * nazev-mistnosti je skutečnej název místnosti, bez diakritiky, s pomlčkama místo mezer.
             * Neni tedy nutný parsovat odkazy, stačí pouze získat jména místností a ty přeformátovat.
             *
             * Pokud chce uživatel domístnosti vstoupit poprvé, je odkázán na intro stránku, kde musí souhlasit s podmínkama.
             * To se dá přeskočit, když odešlu POST packet s disclaim=on. Budu muset použít předchozí verzi a vrátit se rid.
             */

            foreach (HtmlNode node in tds)
            {
                //první tr je hlavička tabulky => ignorovat
                if (!first)
                {
                    //potom u td.id:
                    //c2 => link+jméno
                    //c3 => info

                    //výběr správného td a z tohoto td výběr správného odkazu ve tvaru <a href=....>JMÉNO MÍSTNOSTI</a>
                    HtmlNode linkNameNode = node.SelectSingleNode(".//td[contains(@id,'c2')]").SelectSingleNode(".//a[contains(@href,'" + XCHAT_URI + "/" + SessionKey + "/room" + "')]");
                    HtmlNode infoNode = node.SelectSingleNode("//td[contains(@id,'c3')]");

                    //rid pres regex "rid=(\d{7})"
                    String url = linkNameNode.GetAttributeValue("href", "nic").ToString();
                    Regex reg = new Regex("(?<rid>rid=[\\d]*)&");
                    Match rid = reg.Match(url);

                    //name
                    String name = linkNameNode.InnerText;

                    //link name - zde se skutecne jmeno mistnosti preformatuje na jmeno mistnosti do odkazu
                    String linkName = name.ToLower().Replace(' ', '-');
                    //odstranění diakritiky
                    char[] diakritika = new char[] { 'á', 'č', 'ď', 'ě', 'é', 'í', 'ó', 'ř', 'š', 'ú', 'ů', 'ý', 'ž' };
                    char[] normalne = new char[] { 'a', 'c', 'd', 'e', 'e', 'i', 'o', 'r', 's', 'u', 'u', 'y', 'z' };
                    for(int i=0;i<diakritika.Length;i++)
                    {
                        linkName = linkName.Replace(diakritika[i], normalne[i]);
                    }

                    //info
                    String info = infoNode.InnerText;
                    //odebrání " &nbsp;"
                    info = info.Substring(0, info.Length - 6);

                    //info o místnosti zatím nepoužito
                    chatRooms.Add(new RoomLink(name, "/modchat?op=mainframeset&"+rid.Value.ToString()+"&js=0&nonjs=1", info, rid.Groups["rid"].ToString()));
                }
                else
                {
                    first = false;
                }
            }

            return chatRooms;
        }
コード例 #40
0
        private void ProcessLink(Regex r, string path, string href, Packages package)
        {
            Console.WriteLine(path + href);
            var text      = File.ReadAllText(path + href);
            var matchList = r.Matches(text);
            var source    = Service.Source("Package Uploads", Models.Admin.SearchType.SourceName);

            if (matchList.Count > 0)
            {
                // One or more links were found so we'll include each in the bulk update
                foreach (Match m in matchList)
                {
                    // Allow send through URLs up to 1024 in length to avoid errors
                    string url = m.Groups[1].Value;
                    url = (url.Length >= MaxUrlLength ? url.Substring(0, MaxUrlLength - 1) : url);

                    // Check the link for existance
                    var link = Service.LinkFromUrl(url);
                    if (link == null)
                    {
                        Console.WriteLine($"Adding link {url}");
                        var now = DateTime.Now;
                        link = new Links
                        {
                            AllTimeMaxDownloadTime    = 0,
                            AllTimeMinDownloadTime    = 0,
                            AllTimeStdDevDownloadTime = 0,
                            AttemptCount    = 0,
                            DateFirstFound  = now,
                            DateLastChecked = null,
                            DateLastFound   = null,
                            DateUpdated     = null,
                            DisabledDate    = null,
                            DisabledUser    = null,
                            Id = Guid.NewGuid().ToString(),
                            PastWeekMaxDownloadTime    = 0,
                            PastWeekMinDownloadTime    = 0,
                            PastWeekStdDevDownloadTime = 0,
                            ReportNotBeforeDate        = null,
                            Source = source.Id,
                            Url    = url,
                            Valid  = true
                        };

                        Service.AddLink(link);
                    }

                    var    uri    = new Uri(url);
                    var    split  = href.Split(Path.DirectorySeparatorChar);
                    string parent = null;
                    if (split != null && split.Length > 1)
                    {
                        parent = split[split.Length - 2];
                    }

                    // Add the link package course location
                    var newFile = new PackageFiles
                    {
                        CourseLocation = href,
                        Id             = Guid.NewGuid().ToString(),
                        Link           = link.Id,
                        LinkName       = m.Groups[2].Value,
                        PackageId      = package.Id,
                        ParentFolder   = parent,
                        Protocol       = uri.Scheme
                    };

                    Service.AddPackageFile(newFile);
                }
            }
            else
            {
                // No links found but we'll include the object in the update without a url (maybe?)
            }
        }
コード例 #41
0
ファイル: HomeController.cs プロジェクト: tzobell/photoweb
        public string Purchase(string photoname, string size, string cost)
        {
            //Dictionary<string, string> sdkConfig = new Dictionary<string, string>();                      
            //sdkConfig.Add("mode", "sandbox");
            //string accessToken = new OAuthTokenCredential("Ae2ZWMxCl_ueuNy87vcg52hTjX9aVWfnvLQSMjDuTn2sj0crrWYIWwPseO_6H4nLpXKcHE9_DjtrmDEC", "EEmZr7iiuNCksXtPh5NjcVcguVGic0TwCW-f7GFmgfmrG8wBUhn_UJj53OxraTkKijC4UYQHv-fzlH7z", sdkConfig).GetAccessToken();
            //APIContext apiContext = new APIContext(accessToken);
            APIContext apiContext = GetAPIContext();
            Amount amnt = new Amount();
            amnt.currency = "USD";
            amnt.total = cost;

            List<Transaction> transactionList = new List<Transaction>();
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "Photo";
            tran.description = "creating a payment";
            tran.item_list = new ItemList();
            tran.item_list.items = new List<Item>();
            tran.item_list.items.Add(new Item());

            Item item = new Item();

            tran.item_list.items[0].currency = "USD";
            tran.item_list.items[0].description = size;
            tran.item_list.items[0].name = photoname;
            string price = cost;
            tran.item_list.items[0].price = price;// "12";
            tran.item_list.items[0].quantity = 1.ToString();// "1";
            tran.item_list.items[0].sku = photoname + " " + size;
            tran.item_list.items[0].tax = "0";
            transactionList.Add(tran);

            Payer payr = new Payer();
            payr.payment_method = "paypal";
            payr.payer_info = new PayerInfo();
            RedirectUrls redirUrls = new RedirectUrls();
            redirUrls.cancel_url = Request.Url + ""; 
            string tempurl = "http://" + Request.Url.Authority + "/Home/Confirm";
            redirUrls.return_url = tempurl;

            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactionList;
            pymnt.redirect_urls = redirUrls;
            Payment createdPayment = pymnt.Create(apiContext);

            Links approvalURL = new Links();
            for (int i = 0; i < createdPayment.links.Count; ++i)
            {
                if (createdPayment.links[i].rel == "approval_url")
                {
                    approvalURL = createdPayment.links[i];
                    i = createdPayment.links.Count;
                }
            }


            return approvalURL.href;

        }       
コード例 #42
0
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment     pymnt       = null;

            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext..
            APIContext apiContext = Configuration.GetAPIContext();

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];
                }
                try
                {
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext, pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Items
                // Items within a transaction.
                Item item = new Item();
                item.name     = "Item Name";
                item.currency = "USD";
                item.price    = "15";
                item.quantity = "5";
                item.sku      = "sku";

                List <Item> itms = new List <Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var    guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax      = "15";
                details.shipping = "10";
                details.subtotal = "75";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total   = "100";
                amnt.details = details;

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it.
                List <Transaction> transactionList = new List <Transaction>();
                Transaction        tran            = new Transaction();
                tran.description = "Transaction description.";
                tran.amount      = amnt;
                tran.item_list   = itemList;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                pymnt               = new Payment();
                pymnt.intent        = "sale";
                pymnt.payer         = payr;
                pymnt.transactions  = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // Create a payment using a valid APIContext
                    Payment createdPayment = pymnt.Create(apiContext);

                    CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
コード例 #43
0
ファイル: SendItemMail.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        gui = GUIVariables.Instance;
        engine = ProcessingEngine.Instance;
        imageEngine = ImageEngine.Instance;

        seperator = gui.Seperator;

        if (string.IsNullOrEmpty(Request.QueryString["IID"]))
        {
            EMailDiv.Visible = false;
            ItemTitleLabel.Text = "No such item found.";
        }
        else
        {
            iid = Request.QueryString["IID"].Trim().ToLower();
        }

        if (!general.IsValidInt(iid))
        {
            EMailDiv.Visible = false;
        }
        else
        {
            item = new Item();

            string queryString = "SELECT Title, Link, Text, Date, UID, NComments, Category FROM item WHERE IID=" + iid + ";";
            MySqlDataReader retList;

            retList = dbOps.ExecuteReader(queryString);

            if (retList != null && retList.HasRows)
            {
                while (retList.Read())
                {
                    item.IID = Convert.ToInt32(iid);
                    item.UID = Convert.ToString(retList["UID"]);
                    item.Title = Convert.ToString(retList["Title"]);
                    item.Link = Convert.ToString(retList["Link"]);
                    item.Text = Convert.ToString(retList["Text"]);
                    item.Date = Convert.ToString(retList["Date"]);
                    item.NComments = Convert.ToInt32(retList["NComments"]);
                    item.Category = Convert.ToString(retList["Category"]);

                    if (!string.IsNullOrEmpty(item.Link))
                    {
                        item.Text = string.Empty;
                    }
                }
                retList.Close();
            }
            ItemTitleLabel.Text = "Title: " + gui.GrayFontStart + item.Title + gui.GrayFontEnd;
        }

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.

        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            user = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (string.IsNullOrEmpty(user))
        {

        }
        else
        {

        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        //  If the user has logged in, populate the 'EMail From' TextBox.
        //  The variable 'user' = Logged in User.

        EMailOutputMessageLabel.Text = string.Empty;
        if (!string.IsNullOrEmpty(user))
        {
            string queryString = "SELECT EMail FROM user WHERE UID='" + user + "';";
            MySqlDataReader retList = dbOps.ExecuteReader(queryString);
            if (retList != null && retList.HasRows)
            {
                while (retList.Read())
                {
                    FromTB.Text = Convert.ToString(retList["EMail"]);
                }
                retList.Close();
            }
        }

        //  If not using ReCaptcha Project, but using the Captcha Library.
        //if (!IsPostBack)
        //{
        //    HttpContext.Current.Session["CaptchaImageText"] = general.GenerateRandomCode();
        //}
    }
コード例 #44
0
ファイル: Links.cs プロジェクト: supercontact/MagicMotion
 void Awake()
 {
     links = this;
 }
コード例 #45
0
ファイル: LinkTest.cs プロジェクト: iljafiers/FotoLab
        public void ToStringTest()
        {
            Links link = GetLinks();

            Assert.IsFalse(link.ToString().Length == 0);
        }
コード例 #46
0
 public void AddLink(BSLink link)
 {
     Links.Add(link);
 }
コード例 #47
0
ファイル: TestPage.aspx.cs プロジェクト: vatsal/getputs
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            OutputTB.Text = string.Empty;

            dbOps = DBOperations.Instance;
            links = Links.Instance;
            general = General.Instance;
            gui = GUIVariables.Instance;
            engine = ProcessingEngine.Instance;
            categories = Categories.Instance;
            imageEngine = ImageEngine.Instance;
        }
        catch (Exception ex)
        {
            OutputTB.Text = "Error in PageLoad: " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
        }
    }
コード例 #48
0
        /// <summary>Main program</summary>
        static int Main(string[] args)
        {
            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += Manager.ResolveManagerAssembliesEventHandler;

                // Send a command to socket server to get the job to run.
                object response = GetNextJob();
                while (response != null)
                {
                    JobRunnerMultiProcess.GetJobReturnData job = response as JobRunnerMultiProcess.GetJobReturnData;

                    // Run the simulation.
                    Exception         error          = null;
                    string            simulationName = null;
                    StorageViaSockets storage        = new StorageViaSockets(job.key);
                    object[]          services       = new object[] { storage };

                    try
                    {
                        IRunnable jobToRun = job.job;
                        if (jobToRun is RunSimulation)
                        {
                            RunSimulation simulationRunner = job.job as RunSimulation;

                            // Replace datastore with a socket writer
                            simulationRunner.Services = services;
                            simulationName            = simulationRunner.simulationToRun.Name;
                        }
                        else
                        {
                            Links links = new Links(services);
                            links.Resolve(jobToRun);
                        }

                        jobToRun.Run(new CancellationTokenSource());
                    }
                    catch (Exception err)
                    {
                        error = err;
                    }

                    // Signal we have completed writing data for this sim.
                    storage.WriteAllData();

                    // Signal end of job.
                    JobRunnerMultiProcess.EndJobArguments endJobArguments = new JobRunnerMultiProcess.EndJobArguments();
                    endJobArguments.key = job.key;
                    if (error != null)
                    {
                        endJobArguments.errorMessage = error.ToString();
                    }
                    endJobArguments.simulationName = simulationName;
                    SocketServer.CommandObject endJobCommand = new SocketServer.CommandObject()
                    {
                        name = "EndJob", data = endJobArguments
                    };
                    SocketServer.Send("127.0.0.1", 2222, endJobCommand);

                    // Get next job.
                    response = GetNextJob();
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                return(1);
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= Manager.ResolveManagerAssembliesEventHandler;
            }
            return(0);
        }
コード例 #49
0
ファイル: Workspace.cs プロジェクト: adammflax/Puddle
 public Workspace(string type, string title, Links links)
 {
     Links = links;
     Title = title;
     Type = type;
 }
コード例 #50
0
 public void Delete(Links record)
 {
     this.repository.Delete(record);
 }
コード例 #51
0
ファイル: Saved.aspx.cs プロジェクト: vatsal/getputs
    //  ItemDisplayer.ItemLayoutOptions itemLayoutOptions = ItemDisplayer.ItemLayoutOptions.Columns;
    //  ItemDisplayer.ItemLayoutOptions itemLayoutOptions = ItemDisplayer.ItemLayoutOptions.Categorized;
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        gui = GUIVariables.Instance;
        categories = Categories.Instance;
        engine = ProcessingEngine.Instance;
        imageEngine = ImageEngine.Instance;
        itemDisplayer = ItemDisplayer.Instance;

        seperator = gui.Seperator;

        if (!string.IsNullOrEmpty(Request.QueryString["startItem"]))
        {
            bool isStartItemInt = int.TryParse(Request.QueryString["startItem"].Trim(), out startItem);
            if (!isStartItemInt)
            {
                startItem = 0;
            }

            if (startItem < 0)
            {
                startItem = 0;
            }
        }
        else
        {
            startItem = 0;
        }

        if (!string.IsNullOrEmpty(Request.QueryString["sort"]))
        {
            string sortStr = Convert.ToString(Request.QueryString["sort"]);
            sort = engine.GetSortType(sortStr);
        }

        if (Request.Cookies["getputsLayoutCookie"] != null)
        {
            HttpCookie getputsLayoutCookie = Request.Cookies["getputsLayoutCookie"];
            itemLayoutOptions = itemDisplayer.GetItemLayoutOptionsType(dbOps.Decrypt(getputsLayoutCookie["layout"].ToString().Trim()));
        }

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.

        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            UID = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (string.IsNullOrEmpty(UID))
        {
            Response.Redirect(links.LoginLink, false);
        }
        else
        {
            MessageLabel.Text = gui.GreenFontStart + UID + "'s Saved Items" + gui.GreenFontEnd;
        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        LoadItemDB(sort);
    }
コード例 #52
0
 public void LinkTo(string bucket, string key, string tag)
 {
     Links.Add(new RiakLink(bucket, key, tag));
 }
コード例 #53
0
        public Links Get(int id)
        {
            Links links = db.Links.FirstOrDefault(x => x.Id == id);

            return(links);
        }
コード例 #54
0
 public void LinkTo(RiakObject riakObject, string tag)
 {
     Links.Add(riakObject.ToRiakLink(tag));
 }
コード例 #55
0
 public Links Update(Links record)
 {
     return(this.repository.Update(record));
 }
コード例 #56
0
 public void LinkTo(UnitGraphNode otherNode, double multiplier)
 {
     Links.Add(otherNode, new UnitGraphLink(otherNode, multiplier));
     otherNode.Links.Add(this, new UnitGraphLink(this, 1.0 / multiplier));
 }
コード例 #57
0
 public Links Insert(Links record)
 {
     return(this.repository.Insert(record));
 }
コード例 #58
0
 public void FreeIDictionaryInInlineObject()
 {
     Func<IObjectDBTransaction, ILinksWithNodes> creator;
     using (var tr = _db.StartTransaction())
     {
         creator = tr.InitRelation<ILinksWithNodes>("IDictObjLinksRelation");
         var links = creator(tr);
         var link = new Links
         {
             Id = 1,
             Nodes = new Nodes { Edges = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 } }
         };
         links.Insert(link);
         tr.Commit();
     }
     AssertNoLeaksInDb();
     using (var tr = _db.StartTransaction())
     {
         var links = creator(tr);
         var l = links.FindByIdOrDefault(1);
         Assert.Equal(2ul, l.Nodes.Edges[1]);
         Assert.True(links.RemoveById(1));
         tr.Commit();
     }
     AssertNoLeaksInDb();
 }
コード例 #59
0
        /// <summary>
        /// Compile the expression and return the compiled function.
        /// </summary>
        public void CompileExpression()
        {
            // From a list of visible models in scope, create [Link] lines e.g.
            //    [Link] Clock Clock;
            //    [Link] Weather Weather;
            // and namespace lines e.g.
            //    using Models.Clock;
            //    using Models;
            var models = Parent.FindAllInScope().ToList().Where(model => !model.IsHidden &&
                                                                model.GetType() != typeof(Graph) &&
                                                                model.GetType() != typeof(Series) &&
                                                                model.GetType().Name != "StorageViaSockets");
            var linkList      = new List <string>();
            var namespaceList = new SortedSet <string>();

            foreach (var model in models)
            {
                if (Expression.Contains(model.Name))
                {
                    linkList.Add($"        [Link(ByName=true)] {model.GetType().Name} {model.Name};");
                    namespaceList.Add("using " + model.GetType().Namespace + ";");
                }
            }
            var namespaces = StringUtilities.BuildString(namespaceList.Distinct(), Environment.NewLine);
            var links      = StringUtilities.BuildString(linkList.Distinct(), Environment.NewLine);

            // Get template c# script.
            var template = ReflectionUtilities.GetResourceAsString("Models.Resources.Scripts.CSharpExpressionTemplate.cs");

            // Replace the "using Models;" namespace place holder with the namesspaces above.
            template = template.Replace("using Models;", namespaces);

            template = template.Replace("class Script", $"class {Name}Script");

            // Replace the link place holder in the template with links created above.
            template = template.Replace("        [Link] Clock Clock = null;", links.ToString());

            // Replace the expression place holder in the template with the real expression.
            template = template.Replace("return Clock.FractionComplete;", "return " + Expression + ";");

            // Create a new manager that will compile the expression.
            var result = Compiler().Compile(template, this);

            if (result.ErrorMessages == null)
            {
                if (expressionFunction == null || result.WasCompiled)
                {
                    expressionFunction = result.Instance as IFunction;
                    (expressionFunction as IModel).Parent = this;

                    // Resolve links
                    var linkResolver = new Links();
                    linkResolver.Resolve(expressionFunction as IModel, true);
                }
            }
            else
            {
                var st = $"Cannot compile expression: {Expression}{Environment.NewLine}" +
                         $"{result.ErrorMessages}{Environment.NewLine}" +
                         $"Generated code: {Environment.NewLine}{template}";
                throw new Exception(st);
            }
        }
コード例 #60
0
        /// <summary>
        /// 申请友链
        /// </summary>
        /// <param name="links"></param>
        /// <returns></returns>
        public async Task <ActionResult> Apply(Links links)
        {
            if (!links.Url.MatchUrl())
            {
                return(ResultData(null, false, "添加失败!链接非法!"));
            }

            var host = new Uri(links.Url).Host;

            if (LinksService.Any(l => l.Url.Contains(host)))
            {
                return(ResultData(null, false, "添加失败!检测到您的网站已经是本站的友情链接了!"));
            }

            Uri uri = new Uri(links.Url);

            using (HttpClient client = new HttpClient()
            {
                BaseAddress = uri,
                Timeout = TimeSpan.FromSeconds(10)
            })
            {
                client.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0"));
                client.DefaultRequestHeaders.Referrer = new Uri(Request.Scheme + "://" + Request.Host.ToString());
                return(await await client.GetAsync(uri.PathAndQuery).ContinueWith(async t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        return ResultData(null, false, "添加失败!检测到您的网站疑似挂了,或者连接到你网站的时候超时,请检查下!");
                    }

                    var res = await t;
                    if (res.IsSuccessStatusCode)
                    {
                        var s = await res.Content.ReadAsStringAsync();
                        if (s.Contains(CommonHelper.SystemSettings["Domain"]))
                        {
                            var entry = LinksService.GetFirstEntity(l => l.Url.Equals(links.Url));
                            bool b;
                            if (entry is null)
                            {
                                b = LinksService.AddEntitySaved(links) != null;
                            }
                            else
                            {
                                entry.Url = links.Url;
                                entry.Except = links.Except;
                                entry.Name = links.Name;
                                entry.Recommend = links.Recommend;
                                b = LinksService.UpdateEntitySaved(entry);
                            }

                            return ResultData(null, b, b ? "添加成功!这可能有一定的延迟,如果没有看到您的链接,请稍等几分钟后刷新页面即可,如有疑问,请联系站长。" : "添加失败!这可能是由于网站服务器内部发生了错误,如有疑问,请联系站长。");
                        }

                        return ResultData(null, false, $"添加失败!检测到您的网站上未将本站设置成友情链接,请先将本站主域名:{CommonHelper.SystemSettings["Domain"]}在您的网站设置为友情链接,并且能够展示后,再次尝试添加即可!");
                    }

                    return ResultData(null, false, "添加失败!检测到您的网站疑似挂了!返回状态码为:" + res.StatusCode);
                }));
            }
        }