DownloadString() public method

public DownloadString ( System address ) : string
address System
return string
        AuthenticationResult IAuthenticationClient.VerifyAuthentication(HttpContextBase context)
        {
            try {
                Context db = new Context();
                string code=context.Request["code"];
                AccessTokenDB token = new AccessTokenDB();
                var address = String.Format("https://oauth.vk.com/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}",this.appId,this.appSecret,code,this.redirectUri);
                WebClient client = new WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                Person person;

                var response = client.DownloadString(address);
                var access_token=JsonConvert.DeserializeObject<AccessTokenAndId>(response);
                token.AccessToken = access_token.accessToken;

                    db.AccessToken.Add(token);
                    db.SaveChanges();

                address = String.Format("https://api.vk.com/method/users.get?uids={0}&fields=nickname", access_token.userId);
                client.Encoding = System.Text.Encoding.UTF8;
                response = client.DownloadString(address);
                person = JsonConvert.DeserializeObject<Persons>(response).People[0];
                return new AuthenticationResult(true,(this as IAuthenticationClient).ProviderName,access_token.userId,person.FirstName + " " +person.LastName,new Dictionary<string,string>());
            }
            catch(Exception ex){
                return new AuthenticationResult(ex);
            }
        }
Example #2
0
        public void GetChannel()
        {
            List<Channel> list = new List<Channel>();

            WebClient client = new WebClient();
            string content = "";
            if (search_trial == true)
                content = client.DownloadString(AppConst.SERVER_ADDRESS + "/get_channel?search_trial=1");
            else
                content = client.DownloadString(AppConst.SERVER_ADDRESS + "/get_channel?session_id=" + Register.session_id + "&country=" + seaching_country + "&category=" + seaching_catagory + "&keyword=" + seaching_keyword);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(content);
            XmlNodeList nodeList = xmlDoc.GetElementsByTagName("channel");
            foreach (XmlNode node in nodeList)
            {
                Channel item = new Channel();
                item.channel_id = node.Attributes["channel_id"].Value;
                item.channel_name = Utility.URLDecode(node.Attributes["channel_name"].Value);
                item.channel_url = Utility.URLDecode(node.Attributes["channel_url"].Value);
                item.description = Utility.URLDecode(node.Attributes["description"].Value);
                item.channel_type = node.Attributes["channel_type"].Value;
                list.Add(item);
            }

            callback.FinishedLoadChannel(list);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // extract the MusixMatch song ID from the query string
            int trackId = Convert.ToInt32(Request.QueryString["id"]);

            // initialize web client
            WebClient client = new WebClient();
            string response1 = client.DownloadString("http://api.musixmatch.com/ws/1.1/track.get?track_id=" + trackId + "&apikey=" + apiKey);

            // fetch the track information from MusixMatch
            var track = Json.Decode(response1).message.body.track;

            // output the track and artist name
            this.lblTitle.Text = track.track_name;
            this.lblArtist.Text = track.artist_name;

            // read the previously downloaded lyrics from disk
            StreamReader sr = new StreamReader(Server.MapPath("~/Data/" + track.track_id + ".txt"));
            this.lblLyrics.Text = sr.ReadToEnd().Replace("\n", "<br />\n");

            // download the Spotify embed component
            string response2 = client.DownloadString("http://ws.spotify.com/search/1/track.json?q=" + track.track_name);

            if (Json.Decode(response2).tracks.Count > 0)
            {
                // parse the Spotify URI for this song
                var spotifyUri = Json.Decode(response2).tracks[0].href;

                // output the Spotify embed component
                this.litPlayButton.Text = "<iframe src='https://embed.spotify.com/?uri=" + spotifyUri + "' width='400' height='480' frameborder='0' allowtransparency='true'></iframe>";
            }
        }
        public static void Main()
        {
            Console.WriteLine("Connecting...");
            Console.WriteLine();
            var client = new WebClient();

            var albums = client.DownloadString("http://localhost:25099/api/albums/all");
            Console.WriteLine("Albums:");
            Console.WriteLine(albums);

            Console.WriteLine();
            Console.WriteLine("Adding albums...");
            Console.WriteLine();

            var albumPost = "{'Title': 'Nice Name', 'Year': '2014', 'Producer': 'Pesho'}";
            albumPost += "{'Title': 'Other Name', 'Year': '2013', 'Producer': 'Pesho'}";
            albumPost += "{'Title': 'Gosho ot po4ivka', 'Year': '2008', 'Producer': 'Pesho ot Pernik'}";
            albumPost += "{'Title': 'Zadushaam sa', 'Year': '2014', 'Producer': 'Bat Georgi'}";

            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.UploadString("http://localhost:25099/api/albums/create", albumPost);

            Console.WriteLine("Albums:");
            albums = client.DownloadString("http://localhost:25099/api/albums/all");
            Console.WriteLine(albums);

        }
Example #5
0
        /// <summary>
        /// The get html.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <param name="type">
        /// The type.
        /// </param>
        public static void GetHtml(int id, ResultType type)
        {
            var wc = new WebClient();
            var url1 = Utils.GetWebSiteUrl;
            var url2 = url1;
            switch (type)
            {
                case ResultType.Product:
                    url1 += "/Product/item/" + id;
                    url2 += "/Product/item-id-" + id + ".htm";
                    break;
                case ResultType.Team:
                    url1 += "/Home/TuanItem/" + id;
                    url2 += "/Home/TuanItem/" + id + ".htm";
                    break;
                case ResultType.LP:
                    url1 += "/LandingPage/" + id;
                    url2 += "/LandingPage/" + id + ".htm";
                    break;
                case ResultType.Acticle:
                    url1 += "/Acticle/" + id;
                    url2 += "/Acticle/" + id + ".htm";
                    break;
                case ResultType.Help:
                    url1 += "/Help/" + id;
                    url2 += "/Help/" + id + ".htm";
                    break;
            }

            wc.DownloadString(url1);
            wc.DownloadString(url2);
        }
        public static string GetExternalIP()
        {
            using (WebClient client = new WebClient()) {
                try {
                    string ip = client.DownloadString("http://canihazip.com/s");
                    if (ip == "77.174.16.28")
                        return "176.31.253.42";

                    return ip;
                }
                catch (WebException) {
                    // this one is offline
                }

                try {
                    return client.DownloadString("http://wtfismyip.com/text");
                }
                catch (WebException) {
                    // offline...
                }

                try {
                    return client.DownloadString("http://ip.telize.com/");
                }
                catch (WebException) {
                    // offline too...
                }

                // if we got here, all the websites are down, which is unlikely
                return "Check internet connection?";
            }
        }
Example #7
0
        static void buildJobInfo(uint messageId, int currentMessageInstanceId)
        {
            WebClient webClient = new WebClient();
            webClient.Proxy = null;

            //The currentMessageInstanceId was obtained from basicMessageInfo().
            // We use limit == 1 to get max and min.  Note: limit == 0 will return all list results (if the request doesn't time out).
            string lastBuildJobUrl = string.Format("{0}/build-job-import/list-build-job-message-instance/messageInstanceId/{1}/limit/1/format/xml/sortField/buildJobId/sortDirection/DESC", getLciBaseUrl(), currentMessageInstanceId);
            string firstBuildJobUrl = string.Format("{0}/build-job-import/list-build-job-message-instance/messageId/{1}/limit/1/format/xml/sortField/buildJobId/sortDirection/ASC", getLciBaseUrl(), messageId);

            string lastBuildJobXmlString = webClient.DownloadString(lastBuildJobUrl);
            XmlDocument lastBuildJobDoc = new XmlDocument();
            lastBuildJobDoc.LoadXml(lastBuildJobXmlString);
            XmlNode lastBuildJobRootNode = lastBuildJobDoc.DocumentElement;

            //The subcomponent listed on the view message web page comes from the last build job
            Console.WriteLine("Subcomponent: " + getStringValueFromXmlNode(lastBuildJobRootNode, "item/componentName"));
            Console.WriteLine(string.Format("Last Build: {0} ({1})",
                getStringValueFromXmlNode(lastBuildJobRootNode, "item/buildJob/mainBuildArtifact/label"),
                getStringValueFromXmlNode(lastBuildJobRootNode, "item/buildJob/created")));

            string firstBuildJobXmlString = webClient.DownloadString(firstBuildJobUrl);
            XmlDocument firstBuildJobDoc = new XmlDocument();
            firstBuildJobDoc.LoadXml(firstBuildJobXmlString);
            XmlNode firstBuildJobRootNode = firstBuildJobDoc.DocumentElement;

            Console.WriteLine(string.Format("First Build: {0} ({1})",
                getStringValueFromXmlNode(firstBuildJobRootNode, "item/buildJob/mainBuildArtifact/label"),
                getStringValueFromXmlNode(firstBuildJobRootNode, "item/buildJob/created")));
        }
Example #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a username");

            string username = Console.ReadLine();

            WebClient wc = new WebClient();

            wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            string json = wc.DownloadString("https://api.github.com/users/" + username);

            var o = JObject.Parse(json);

            Console.WriteLine(o["login"].ToString());
            Console.WriteLine(o["login"].ToString() + " has " + o["followers"].ToString() + " followers " + o["public_repos"].ToString() + " repositories");

            wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            json = wc.DownloadString(o["repos_url"].ToString());

            var oRepos = JArray.Parse(json);

            foreach (var repo in oRepos)
            {
                Console.WriteLine(repo["name"] + " " + repo["has_issues"].ToString());
            }

            Console.ReadLine();
        }
Example #9
0
        private void addInventories()
        {
            WebClient webClient = new WebClient();
            webClient.Encoding = System.Text.Encoding.UTF8;
            JArray characters = JArray.Parse(webClient.DownloadString("https://api.guildwars2.com/v2/characters?access_token=" + apiKey));

            foreach (String character in characters)
            {
                RootObject inventory = JsonConvert.DeserializeObject<RootObject>(webClient.DownloadString("https://api.guildwars2.com/v2/characters/" + character + "?access_token=" + apiKey));
                foreach (Bag bag in inventory.bags)
                {
                    if (bag != null)
                    {
                        foreach (Item item in bag.inventory)
                        {
                            try
                            {
                                ids.Add(new ListItem(item.id.ToString(), item.count, character));
                            }
                            catch { }
                        }
                    }
                }
            }
        }
        public void FindWord(string word)
        {
            using (DudenCacheModel mdl = new DudenCacheModel())
            {
                WordMatch match = mdl.WordMatches.Where(wm => wm.Word == word).FirstOrDefault();
                if (match == null)
                {
                    match = new WordMatch() { Word = word };
                    mdl.Add(match);
                    mdl.SaveChanges();
                }

                if (match.WordDefinition == null)
                {
                    try
                    {
                        WebClient client = new WebClient();
                        string searchResults = client.DownloadString(string.Format("http://www.duden.de/suchen/dudenonline/{0}", word));
                        var link = ParseSearchResults(searchResults, "relativeLink").OfType<string>().First(s => !string.IsNullOrWhiteSpace(s));
                        var worddef = ParseSearchResults(searchResults, "word").OfType<string>().First(s => !string.IsNullOrWhiteSpace(s));
                        string resultPage = client.DownloadString(string.Format("http://www.duden.de{0}", link));
                        var synonyms = ParsePage(resultPage, "synonym").OfType<string>().Where(s => !string.IsNullOrWhiteSpace(s));
                        var wortart = ParsePage(resultPage, "wortart").OfType<string>().First(s => !string.IsNullOrWhiteSpace(s));
                        var frequency = int.Parse(ParsePage(resultPage, "frequency").OfType<string>().First(s => !string.IsNullOrWhiteSpace(s)));
                    }
                    catch (WebException wex)
                    {

                    }
                }
            }
        }
        public SparkleInviteOpen(string url)
        {
            string safe_url   = url.Replace ("sparkleshare://", "https://");
            string unsafe_url = url.Replace ("sparkleshare://", "http://");
            string xml        = "";

            WebClient web_client = new WebClient ();

            try {
                xml = web_client.DownloadString (safe_url);

            } catch {
                Console.WriteLine ("Failed downloading invite: " + safe_url);

                try {
                    xml = web_client.DownloadString (safe_url);

                } catch {
                    Console.WriteLine ("Failed downloading invite: " + unsafe_url);
                }
            }

            string home_path   = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
            string target_path = Path.Combine (home_path, "SparkleShare");

            if (xml.Contains ("<sparkleshare>")) {
                File.WriteAllText (target_path, xml);
                Console.WriteLine ("Downloaded invite: " + safe_url);
            }
        }
        public GoogleCodeWebSniffer(string username)
        {
            Errors = new List<KeyValuePair<string, string>>();

            Projects = new List<Project>();

            var webClient = new WebClient();

            try
            {
                var pageSource = webClient.DownloadString(string.Format(profileLookupUri, username));
                Projects = Projects.ParseProjects(pageSource);
                 
                for (var i = 0 ; i < Projects.Count ; i++)
                {
                    var project = Projects[i];
                    
                    pageSource = webClient.DownloadString(project.Url);
                    project = project.ParseDetails(pageSource);

                    pageSource = webClient.DownloadString(string.Format(commitsLookupUri, project.Name.CleanName()));
                    project = project.ParseLastModifiedDate(pageSource);
                }

                Projects = GoogleCodeWebSnifferExtensions.Clean(Projects);
            }
            catch (Exception ex)
            {
                Errors.Add(new KeyValuePair<string, string>("GoogleCodeWebSniffer", string.Format("An error occured when looking up {0}. Error details: {1}", username, ex.Message)));
            }
        }
Example #13
0
 public string Authenticate()
 {
     string userName;
     string password;
     string url = BaseUrl + Authentication + newToken + ApiKey;
     using (WebClient wc = new WebClient())
     {
         var json = wc.DownloadString(url);
         JObject auth = JObject.Parse(json);
         token = (string)auth["request_token"];
         Console.Write("Please enter username: "******"Please enter password: "******"validate_with_login?api_key=" + ApiKey + "&request_token=" + token + "&username="******"&password="******"request_token"];
         url = BaseUrl + "/authentication/session/new?api_key=" + ApiKey + "&request_token=" + token;
         json = wc.DownloadString(url);
         auth = JObject.Parse(json);
         sessionID = (string)auth["session_id"];
     }
     if (sessionID != null)
     {
         return "OK";
     }
     else
     {
         return "FAIL";
     }
 }
Example #14
0
        private static void FindFollowers(String url)
        {
            using (var webClient = new WebClient())
            {
                string html = webClient.DownloadString(url);
                JavaScriptSerializer ser = new JavaScriptSerializer();
                var dict = ser.Deserialize<Dictionary<string, object>>(html);
                var ids = ((System.Collections.ArrayList)dict["ids"]);
                foreach (int id in ids)
                {
                    String screenNameURL = String.Format("https://api.twitter.com/1/users/show.json?user_id={0}&include_entities=true", id);
                    string html2 = webClient.DownloadString(screenNameURL);
                    var dict2 = ser.Deserialize<Dictionary<string, object>>(html2);
                    String screenName = (String) dict2["screen_name"];
                    Console.WriteLine(id + ": " + screenName);

                    if (_knownNames.Contains(screenName)) continue;

                    String profilPicURL = String.Format("https://api.twitter.com/1/users/profile_image?screen_name={0}&size=original", screenName);
                    MemoryStream ms = new MemoryStream(webClient.DownloadData(profilPicURL));
                    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                    img.Save(_picturesDirectory + "\\" + screenName + ".jpg");
                }
            }
        }
Example #15
0
        private const string _outputType = "csv"; // Available options: csv, xml, kml, json

        #endregion Fields

        #region Methods

        /// <summary>
        /// Gets a Coordinate from a address.
        /// </summary>
        /// <param name="address">An address.
        /// <remarks>
        /// <example>1600 Amphitheatre Parkway Mountain View, CA 94043</example>
        /// </remarks>
        /// </param>
        /// <returns>A spatial coordinate that contains the latitude and longitude of the address.</returns>
        public GeocodeResult GetCoordinates(string address)
        {
            var client = new WebClient();
            Uri uri = GetGeocodeUri(address);

            /* The first number is the status code,
             * the second is the accuracy,
             * the third is the latitude,
             * the fourth one is the longitude.
             */
            string[] geocodeInfo = client.DownloadString(uri).Split(',');
            GeocodeResult resultFromGoogleCsv = GeocodeResult.CreateResultFromGoogleCsv(geocodeInfo);
            while (resultFromGoogleCsv.ReturnCode == GeocodeReturnCode.UnknownAddress)
            {
                address = string.Join(",", address.Split(',').Skip(1).ToArray());
                if (string.IsNullOrWhiteSpace(address))
                {
                    break;
                }
                uri = GetGeocodeUri(address);
                geocodeInfo = client.DownloadString(uri).Split(',');
                resultFromGoogleCsv = GeocodeResult.CreateResultFromGoogleCsv(geocodeInfo);
            }
            return resultFromGoogleCsv;
        }
        public GitHubServiceTranslator(string username)
        {
            Errors = new List<KeyValuePair<string, string>>();
            Projects = new List<Project>();

            var webClient = new WebClient();

            try
            {
                var xmlSource = webClient.DownloadString(string.Format(userLookupUri, username));
                Projects = Projects.GetProjects(xmlSource);
                
                for (var i = 0 ; i < Projects.Count ; i++)
                {
                    var project = Projects[i];
                    var pageSource = webClient.DownloadString(string.Format(commitsLookupUri, username, project.Name));
                    project = project.GetDetails(pageSource);
                }

                Projects = GitHubServiceTranslatorExtensions.Clean(Projects);
            }
            catch (Exception ex)
            {
                Errors.Add(new KeyValuePair<string, string>("GitHubServiceTranslator", string.Format("Username {0} not found. Error: {1}", username, ex.Message)));
            }
        }
        private void pobierzdane(String wykonawca, String album)
        {
            WebClient klient = new WebClient();
            klient.Encoding = Encoding.UTF8;
            string content = "";
            string content2 = "";
            try
            {

                content = klient.DownloadString("http://en.wikipedia.org/wiki/" + album);
                //MessageBox.Show("http://en.wikipedia.org/wiki/" + album);
                content2 = klient.DownloadString("http://fm.tuba.pl/artysta/" + wykonawca);
                //MessageBox.Show("http://fm.tuba.pl/artysta/" + wykonawca);
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);
                IEnumerable<HtmlNode> links = from link in doc.DocumentNode.Descendants()
                                              where link.Name == "th" && link.Attributes["class"] != null && link.Attributes["class"].Value == "summary album"
                                              select link;
                string tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);
                label1.Text = tresc;
                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "span" && link.Attributes["class"] != null && link.Attributes["class"].Value == "bday dtstart published updated"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);
                label2.Text = tresc;
                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "span" && link.Attributes["class"] != null && link.Attributes["class"].Value == "duration"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);

                label3.Text = tresc;

                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "a" && link.Attributes["class"] != null && link.Attributes["class"].Value == "image"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerHtml;
                //MessageBox.Show(tresc);
                String[] temp = tresc.Split('"');
                //MessageBox.Show(temp[3]);
                temp[3] = temp[3].Substring(2);
                //MessageBox.Show(temp[3]);
                cover.Load("http://" + temp[3]);

                doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content2);
                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "p"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);
                label5.Text = tresc;
            }
            catch (Exception e)
            {
                MessageBox.Show("Próba znalezienia szczegółów pliku nie powiodła się.");
            }
        }
Example #18
0
        private static IEnumerator aSyncSearchForModel(string filename, string searchterm)
        {
            WebClient w = new WebClient();
            string htmlstring = w.DownloadString("http://sketchup.google.com/3dwarehouse/doadvsearch?title=" + searchterm.Replace(" ","+")
                                        + "&scoring=d&btnG=Search+3D+Warehouse&dscr=&tags=&styp=m&complexity=any_value&file="
                                        + "zip" + "&stars=any_value&nickname=&createtime=any_value&modtime=any_value&isgeo=any_value&addr=&clid=");
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlstring);

            //Grab a result from the search page
            HtmlAgilityPack.HtmlNodeCollection results = doc.DocumentNode.SelectNodes("//div[@class='searchresult']");
            string model_page_url = "http://sketchup.google.com" + results[0].SelectSingleNode(".//a").Attributes["href"].Value;
            htmlstring = w.DownloadString(model_page_url);
            doc.LoadHtml(htmlstring);

            //Find the downloadable zip file
            results = doc.DocumentNode.SelectNodes("//a[contains(@href,'rtyp=zip')]");
            foreach (HtmlNode r in results)
            {
                HtmlAttribute src = r.Attributes["href"];
                string url = "http://sketchup.google.com" + src.Value;
                url = url.Replace("&amp;", "&");
                string location = @"path to downloads folder" + filename + ".zip";
                System.Diagnostics.Debug.WriteLine(url+"\n"+location);
                w.DownloadFile(new Uri(url),location);
            }
            return null;
        }
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:5000/Service";
            ServiceHost host = new ServiceHost(typeof(TestService), new Uri(baseAddress));

            var webendpoint = host.AddServiceEndpoint(typeof(ITestService), new WebHttpBinding(), "");
            webendpoint.Behaviors.Add(new TypedUriTemplateBehavior());

            host.Open();
            Console.WriteLine("Host opened");

            WebClient c = new WebClient();

            #region Tests
            Console.WriteLine(c.DownloadString(baseAddress + "/" + Guid.NewGuid().ToString()));

            Console.WriteLine(c.DownloadString(baseAddress + "/Parent/" + 20));

            Console.WriteLine(c.DownloadString(baseAddress + "/" + Guid.NewGuid() + "/Current/" + 10));

            Console.WriteLine(c.DownloadString(baseAddress + "/Data/" + "Mein_name_ist_WCF"));
            #endregion

            Console.Read();
        }
Example #20
0
        //strIP为IP
        /// <summary>  
        /// 根据IP 获取物理地址  
        /// </summary>  
        /// <param name="strIP"></param>  
        /// <returns></returns>  
        public static string GetstringIpAddress(string strIP)
        {
            string m_IpAddress = strIP.Trim();

            //string[] ip = ipAddress.Split('.');
               // ipAddress = ip[0] + "." + ip[1] + ".1.1";

            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.GetEncoding("GB2312");
            string html;
            try
            {
                html = client.DownloadString("http://www.ip138.com/ips1388.asp?ip=" + m_IpAddress + "&action=2");

            }
            catch (Exception ex)
            {
                html = client.DownloadString("http://www.ip138.com/ips1388.asp?ip=" + m_IpAddress + "&action=2");
            }

            string p = @"<li>本站主数据:(?<location>[^<>]+?)</li>";

            Match match = Regex.Match(html, p);
            string m_Location = match.Groups["location"].Value.Trim();
            int index = m_Location.IndexOf(" ");
            if (index != -1)
            {
                m_Location = m_Location.Substring(0, index);
            }
            return m_Location;
        }
Example #21
0
        //public static string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        //public static string startPath = Application.StartupPath;
        public Form1()
        {
            InitializeComponent();

            // Declare And Initilize Set Build Number Variables to 0
            string wwivBuild5_1 = "0";
            string wwivBuild5_0 = "0";

            // Fetch Latest Build Number For WWIV 5.1
            // http://build.wwivbbs.org/jenkins/job/wwiv/label=windows/lastSuccessfulBuild/buildNumber
            // http://build.wwivbbs.org/jenkins/job/wwiv_5.0.0/label=windows/lastSuccessfulBuild/buildNumber
            WebClient wc = new WebClient();
            string htmlString1 = wc.DownloadString("http://build.wwivbbs.org/jenkins/job/wwiv/lastSuccessfulBuild/label=windows/");
            Match mTitle1 = Regex.Match(htmlString1, "(?:number.*?>)(?<buildNumber1>.*?)(?:<)");

            // Fetch Latest Build Number For WWIV 5.0
            string htmlString2 = wc.DownloadString("https://build.wwivbbs.org/jenkins/job/wwiv_5.0.0/lastSuccessfulBuild/label=windows/");
            Match mTitle2 = Regex.Match(htmlString2, "(?:number.*?>)(?<buildNumber2>.*?)(?:<)");
            {
                wwivBuild5_1 = mTitle1.Groups[1].Value;
                wwivBuild5_0 = mTitle2.Groups[1].Value;
            }
            version51.Text = wwivBuild5_1;
            version50.Text = wwivBuild5_0;
            currentVersion();
        }
Example #22
0
        private static UpdateResult CheckUpdatesThread()
        {
            string cver = CurrentVersion.major + "." + CurrentVersion.minor + "." + CurrentVersion.revision;
            Console.WriteLine("Check Updates.  Current Version: " + CurrentVersion.GetVersionString());
            System.Net.WebClient client = new WebClient();
            try
            {
                string response = client.DownloadString(updateDomain+"version.txt");
                Console.WriteLine("Got most recent version of flag '"+CurrentVersion.flags+"' from server: " + response);

                if (response.Trim() != cver.Trim()+CurrentVersion.flags)
                {
                    Console.WriteLine("New update available");
                    if(callback != null)
                        callback(UpdateResult.NewUpdate, client.DownloadString(updateDomain+"updatenotes.txt"), response.Trim());
                    return UpdateResult.NewUpdate;
                }
                else
                {
                    Console.WriteLine("No update available");
                    if (callback != null)
                        callback(UpdateResult.NoUpdates, "", "");
                    return UpdateResult.NoUpdates;
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("Update Check failed");
                Console.WriteLine(e.ToString());
                if (callback != null)
                    callback(UpdateResult.UnableToConnect, "", "");
                return UpdateResult.UnableToConnect;
            }
        }
Example #23
0
        private void LoadButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                using (var webClient = new WebClient())
                {
                    string xhtml = webClient.DownloadString("http://www.milovana.com/webteases/showflash.php?id=" + TeaseIdTextBox.Text);

                    var match = Regex.Match(xhtml, @"<div id=""headerbar"">\s*<div class=""title"">(?<title>.*?) by <a href=""webteases/#author=(?<authorid>\d+)"" [^>]*>(?<authorname>.*?)</a></div>", RegexOptions.Multiline | RegexOptions.Singleline);

                    TeaseTitleTextBox.Text = match.Groups["title"].Value;
                    AuthorNameTextBox.Text = match.Groups["authorname"].Value;
                    AuthorIdTextBox.Text = match.Groups["authorid"].Value;

                    string[] scriptLines = webClient.DownloadString("http://www.milovana.com/webteases/getscript.php?id=" + TeaseIdTextBox.Text).Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

                    SelectedTease = new FlashTeaseConverter().Convert(TeaseIdTextBox.Text, TeaseTitleTextBox.Text, AuthorIdTextBox.Text, AuthorNameTextBox.Text, scriptLines);

                    ConverionErrorTextBox.Visible = SelectedTease.Pages.Exists(page => !String.IsNullOrEmpty(page.Errors));

                    Cursor = Cursors.Default;
                }
            }
            catch (Exception err)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(err.Message, "Error while downloading tease", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public List<Blog> GetBlogs()
        {
            var token = GetToken();
            var url = GetReposUrl();

            var uriBuilder = new UriBuilder(url);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query["access_token"] = token;
            uriBuilder.Query = query.ToString();

            var client = new WebClient();
            client.Headers.Add("user-agent", "Engineer In Dev");

            // Get the directories within the Repos directory of the project
            var content = Json.Decode(client.DownloadString(uriBuilder.ToString()));

            // Iterate over each directory
            for (var i = 0; i < content.Length; i++)
            {
                var tempBuilder = uriBuilder;
                tempBuilder.
                tempBuilder.Fragment = content[i]["name"];
                var blogs = Json.Decode(client.DownloadString(tempBuilder.ToString()));
            }

            return new List<Blog>();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // delete previous Data directory and recreate
            if (Directory.Exists(Server.MapPath("~/Data")) == false)
                Directory.CreateDirectory(Server.MapPath("~/Data"));

            // delete previous Data directory and recreate
            if (Directory.Exists(Server.MapPath("~/Data/Output")) == false)
                Directory.CreateDirectory(Server.MapPath("~/Data/Output"));

            Response.Write("Downloading Billboard Top 100 chart.<br />\n");

            // clean data directory
            foreach (string path in Directory.GetFiles(Server.MapPath("~/Data"), "*.txt"))
            {
                File.Delete(path);
            }

            // initialize web client
            WebClient client = new WebClient();

            // download billboard top 100 songs
            string response1 = client.DownloadString("http://api.musixmatch.com/ws/1.1/chart.tracks.get?page=1&page_size=100&country=us&f_has_lyrics=1&apikey=" + apiKey);

            // parse songs from chart response
            var chart = Json.Decode(response1).message.body.track_list;

            StringBuilder sb = new StringBuilder();

            // loop through songs in chart
            int i = 1;
            foreach (var song in chart)
            {
                sb.AppendLine(song.track.track_id + ";" + song.track.track_name + ";" + song.track.artist_name);

                // download lyrics for this song
                Response.Write("Downloading lyrics for #" + i + " " + song.track.track_name + " by " + song.track.artist_name + ".<br />\n");
                string response2 = client.DownloadString("http://api.musixmatch.com/ws/1.1/track.lyrics.get?track_id=" + song.track.track_id + "&apikey=" + apiKey);

                if (song.track.has_lyrics == 1)
                {
                    // parse lyrics for track response
                    var lyrics = Json.Decode(response2).message.body.lyrics.lyrics_body;

                    // save lyrics to disk
                    File.WriteAllText(Server.MapPath("~/Data") + "\\" + song.track.track_id + ".txt", lyrics);
                }

                i++;
            }

            // save index to disk
            File.WriteAllText(Server.MapPath("~/Data") + "\\index.txt", sb.ToString());

            // dispose web client
            client.Dispose();

            Response.Write("Done.<br />\n");
        }
Example #26
0
        private static void CheckInternal()
        {
            UpdateInfo info = new UpdateInfo();
            try
            {
                using (WebClient client = new WebClient())
                {
#if DEBUG
                    client.Credentials = new NetworkCredential("sm", "sm_pw"); //heuheu :D 
                    string versionString = client.DownloadString("ftp://127.0.0.1/version_0.txt");
#else
                    string versionString = client.DownloadString("http://updater.spedit.info/version_0.txt");
#endif
                    string[] versionLines = versionString.Split('\n');
                    string version = (versionLines[0].Trim()).Trim('\r');
                    if (version != Program.ProgramInternalVersion)
                    {
                        string destinationFileName = "updater_" + version + ".exe";
                        string destinationFile = Path.Combine(Environment.CurrentDirectory, destinationFileName);
                        info.IsAvailable = true;
                        info.Updater_File = destinationFile;
                        info.Updater_FileName = destinationFileName;
#if DEBUG
                        info.Updater_DownloadURL = "ftp://127.0.0.1/" + destinationFileName;
#else
                        info.Updater_DownloadURL = "http://updater.spedit.info/" + destinationFileName;
#endif
                        info.Update_Version = version;
                        StringBuilder updateInfoString = new StringBuilder();
                        if (versionLines.Length > 1)
                        {
                            info.Update_StringVersion = versionLines[1];
                            for (int i = 1; i < versionLines.Length; ++i)
                            {
                                updateInfoString.AppendLine((versionLines[i].Trim()).Trim('\r'));
                            }
                        }
                        info.Update_Info = updateInfoString.ToString();
                    }
                    else
                    {
                        info.IsAvailable = false;
                    }
                }
            }
            catch (Exception e)
            {
                info.IsAvailable = false;
                info.GotException = true;
                info.ExceptionMessage = e.Message;
            }
            lock (Program.UpdateStatus) //since multiple checks can occur, we'll wont override another ones...
            {
                if (Program.UpdateStatus.WriteAble)
                {
                    Program.UpdateStatus = info;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="currentAddress">page address</param>
        /// <returns></returns>
        public static string[] GetAllFullImageLink(string currentAddress)
        {
            WebClient webClient = new WebClient();
            List<string> links = new List<string>();
            List<string> smallLinks = new List<string>();
            string result = "";

            bool timeout = true;
            while (timeout)
            {
                try
                {
                    result = webClient.DownloadString(currentAddress);
                    timeout = false;
                }
                catch (Exception e)
                {
                    Console.WriteLine(currentAddress);
                    Console.WriteLine(e);
                }
            }

            string getSrc = result;
            while (getSrc.IndexOf("<li >") != -1)
            {
                getSrc = getSrc.Substring(getSrc.IndexOf("<li >") + ("<li >").Length);
                string pattern = @"\/[0-9]\d*";
                Match mc;
                mc = Regex.Match(getSrc, pattern);
                if (mc.Success)
                {
                    smallLinks.Add(GetParentAddress(currentAddress) + mc.Value);
                }

            }
            for (int i = 0; i < smallLinks.Count; i++)
            {
                timeout = true;
                while (timeout)
                {
                    try
                    {
                        result = webClient.DownloadString(smallLinks[i]);
                        timeout = false;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(smallLinks[i]);
                        Console.WriteLine(e);
                    }
                }

                getSrc = result;
                getSrc = getSrc.Substring(getSrc.IndexOf("fullsizeUrl = '"));
                getSrc = getSrc.Substring(("fullsizeUrl = '").Length, getSrc.IndexOf("';") - ("fullsizeUrl = '").Length);
                links.Add(getSrc);
            }
            return links.ToArray();
        }
Example #28
0
        private static void Extract(string home, string subSite)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(home);
            List<string> hrefTags = new List<string>();
            hrefTags = ExtractAllAHrefTags(doc);

            string lastItem = string.Empty;
            foreach (string item in hrefTags)
            {
                if (item != lastItem)
                {
                    lastItem = item;
                    try
                    {
                        if (item.Contains(subSite) && item.Length > 12)
                        {
                            Console.Write(".");
                            WebClient adClient = new WebClient();
                            string ad = string.Empty;
                            try
                            {
                                if (item.Contains("http://"))
                                {
                                    ad = adClient.DownloadString(item);
                                }
                                else
                                {
                                    ad = adClient.DownloadString(rootUrl + item);
                                }

                                HtmlDocument adDoc = new HtmlDocument();
                                doc.LoadHtml(ad);
                                string text = GetPostingBody(doc);
                                if (!string.IsNullOrEmpty(text))
                                {
                                    text = text.Replace("#", "sharp");
                                    text = text.Replace("++", "plusplus");

                                    FindPhrases(text);
                                    FindWords(text);
                                }
                            }
                            catch (Exception xx)
                            {
                                Console.WriteLine("adClient.DownloadString, rootUrl = " + rootUrl + ", item = " + item + " - " + xx.Message);
                                continue;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Extract: " + ex.Message);
                        break;
                    }
                }
            }
        }
Example #29
0
 public static JsonUtils.JsonObject GetDynamicJsonObject(this Uri uri)
 {
     using (Net.WebClient wc = new Net.WebClient())
     {
         wc.Encoding = System.Text.Encoding.UTF8;
         wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
         return(JsonUtils.JsonObject.GetDynamicJsonObject(wc.DownloadString(uri.ToString())));
     }
 }
Example #30
0
    /// <summary>
    /// 获得远程字符串
    /// </summary>
    public static string GetDomainStr(string key, string uriPath)
    {
        string result = CacheUtils.Get(key) as string;

        if (result == null)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            try
            {
                client.Encoding = System.Text.Encoding.UTF8;
                result          = client.DownloadString(uriPath);
            }
            catch
            {
                result = "暂时无法连接!";
            }
            CacheUtils.Insert(key, result, 60);
        }

        return(result);
    }
Example #31
0
 public string status(string address, string api)
 // Requires web address and API key.
 // Expected return:
 // { "version": "2.0.0.5085", "buildTime": "2017-12-07T18:46:48Z", "isDebug": false, "isProduction": true, "isAdmin": true, "isUserInteractive": false, "startupPath": "C:\\ProgramData\\NzbDrone\\bin", "appData": "C:\\ProgramData\\NzbDrone", "osName": "Windows Server", "osVersion": "6.3.9600.0", "isMonoRuntime": false, "isMono": false, "isLinux": false, "isOsx": false, "isWindows": true, "branch": "master", "authentication": "none", "sqliteVersion": "3.8.7.2", "urlBase": "", "runtimeVersion": "4.5.1", "runtimeName": "dotNet" }
 {
     using (var webClient = new System.Net.WebClient())
     {
         //Attempt to connect to API -- If it fail's return failed.
         // http://192.168.1.73:8989/api/system/status?apikey=cd71f95019e6447a820fb3d8bd6fa8bb
         try
         {
             string fdn  = address + @"/api/system/status?apikey=" + api;
             var    json = webClient.DownloadString(fdn);
             return(json.ToString());
         }
         catch (Exception ex)
         {
             return(ex.ToString());  // Just pass the error back to the method that called it. Garbage in -- Garbage out let the controller figure it out.
         }
     }
 }
    public static Repeater LoadPublic(string repeaterId)
    {
        Repeater repeater = new Repeater();

        try
        {
            using (var webClient = new System.Net.WebClient())
            {
                // Call web service to get all data for the repeater with this ID
                string url  = String.Format(System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "GetRepeaterDetailsPublic?id={0}", repeaterId);
                string json = webClient.DownloadString(url);
                repeater = JsonConvert.DeserializeObject <Repeater>(json);
            }
        }
        catch (Exception ex)
        {
            new ExceptionReport(ex, "Exception while calling web service for repeater data", "Repeater ID: " + repeaterId);
        }

        return(repeater);
    }
Example #33
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            //Session["WebApiUrl"] = "http://aspnet-example-webapi.cloudapps.click2cloud.net/".ToString();
            Session["WebApiUrl"] = "http://aspnet-example-apiproj1.cloudapps.click2cloud.net/".ToString();
            //Session["WebApiUrl"] = "http://localhost:50104/".ToString();
            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
            string arr = client.DownloadString(string.Format("{0}api/User/{1}?&passWord={2}", Session["WebApiUrl"].ToString(), txtUserName.Text, txtPassword.Text));
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            tbl_User             user       = serializer.Deserialize <tbl_User>(arr);
            if (user != null)
            {
                Session["UserID"]   = user.Guid.ToString();
                Session["UserName"] = user.UserName.ToString();
                FailureText.Text    = "Login Success";
                client = new System.Net.WebClient();
                client.Headers.Add("content-type", "application/json");//set your header here, you can add mu
                arr        = client.DownloadString(string.Format("{0}api/Menu/", Session["WebApiUrl"].ToString()));
                serializer = new JavaScriptSerializer();
                IEnumerable <ADUserDetails> collection = serializer.Deserialize <IEnumerable <ADUserDetails> >(arr);
                DataTable dttable = new DataTable();
                dttable = ToDataTable(collection);

                Session["MenuDT"] = dttable;
                Response.Redirect("Default.aspx", false);
            }

            else
            {
                FailureText.Text = "Invalid Login Name/Password.";
            }
            //}
        }
        catch (Exception ex)
        {
            FailureText.Text = "Invalid Login Name/Password.";
        }
    }
    private decimal GetAltitude(string latitude, string longitude)
    {
        decimal output = 0M;
        string  url    = String.Format("https://api.opentopodata.org/v1/eudem25m?locations={0},{1}", latitude, longitude);

        try
        {
            using (var webClient = new System.Net.WebClient())
            {
                string  json = webClient.DownloadString(url);
                dynamic data = JsonConvert.DeserializeObject <dynamic>(json);

                decimal.TryParse(data.results[0].elevation.ToString(), out output);
            }
        }
        catch (Exception)
        {
        }


        return(output);
    }
Example #35
0
    private void LoadRepeaterNotes(string repeaterId)
    {
        using (var webClient = new System.Net.WebClient())
        {
            string  rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString();
            string  url     = String.Format("{0}GetRepeaterNotes?callsign={1}&password={2}&repeaterid={3}", rootUrl, creds.Username, creds.Password, repeaterId);
            string  json    = webClient.DownloadString(url);
            dynamic data    = JsonConvert.DeserializeObject <dynamic>(json);

            string output = "";
            foreach (dynamic obj in data)
            {
                string note = obj["ChangeDescription"].ToString();
                note = note.Replace("• ", "&bull;");
                note = note.Replace("•", "&bull;");
                note = note.Replace("\r\n", "<br>");

                output += String.Format("<div class='noteTop'>{0} - {1} ({2})</div><div class='noteBottom'>{3}</div>", obj["ChangeDateTime"], obj["FullName"], obj["callsign"], note);
            }
            lblNotes.Text = output;
        }
    }
Example #36
0
    protected void btnLoadLinks_Click(object sender, EventArgs e)
    {
        using (var webClient = new System.Net.WebClient())
        {
            string  rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString();
            string  url     = String.Format("{0}GetPossibleLinks_Json", rootUrl);
            string  json    = webClient.DownloadString(url);
            dynamic data    = JsonConvert.DeserializeObject <dynamic>(json);

            ddlLinks.Items.Clear();

            foreach (dynamic obj in data)
            {
                ListItem li = new ListItem(obj["Link"]["Description"].ToString(), obj["Link"]["Value"].ToString());
                ddlLinks.Items.Add(li);
            }

            pnlAddLink.Visible = true;
        }

        ScriptManager.RegisterStartupScript(this, typeof(Page), "alertScript", "$( '#tabs' ).tabs({ active: " + indexOfLinksTab.ToString() + " });", true);
    }
    protected string creaCuerpo()
    {
        string Url = "http://" + Request.Url.Authority + "/mailing/plantilla_contacto_administracion_mailing.html";

        System.Net.WebClient client = new System.Net.WebClient();
        String htmlCode             = client.DownloadString(Url);
        string newhtmlCode          = "";

        newhtmlCode = Regex.Replace(htmlCode, "src=\"images", "src=\"" + "http://" + Request.Url.Authority + "/mailing/images", RegexOptions.Multiline | RegexOptions.IgnoreCase);

        YouCom.DTO.Propietario.FamiliaDTO myFamiliaDTO = new YouCom.DTO.Propietario.FamiliaDTO();
        myFamiliaDTO = YouCom.bll.FamiliaBLL.detalleFamiliabyRut(myUsuario.Rut);

        newhtmlCode = Regex.Replace(newhtmlCode, "{Nombre}", myFamiliaDTO.NombreFamilia, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Apellido}", myFamiliaDTO.ApellidoPaternoFamilia + " " + myFamiliaDTO.ApellidoMaternoFamilia, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Telefono}", myFamiliaDTO.TelefonoFamilia, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Email}", myFamiliaDTO.EmailFamilia, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Categoria}", this.ddlCategoria.SelectedItem.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Asunto}", this.TxtAsunto.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Mensaje}", this.TxtComentarios.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        return(newhtmlCode);
    }
    public string getImageURL(string key_word)
    {
        string URL = "https://www.google.co.jp/search?safe=active&hl=ja&authuser=0&tbm=isch&sxsrf=ALeKk00Afoqg2HWrkekZJQDhKRDU3ymrnA%3A1605185150367&source=hp&biw=958&bih=927&ei=fi6tX56KFIvWmAWUkYD4BQ&q=" + key_word + "&oq=&gs_lcp=CgNpbWcQAxgAMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnMgcIIxDqAhAnUABYAGD7IGgBcAB4AIABAIgBAJIBAJgBAKoBC2d3cy13aXotaW1nsAEK&sclient=img";

        System.Net.WebClient web = new System.Net.WebClient();
        string html = web.DownloadString(URL);

        Debug.Log(html);

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);


        HtmlNodeCollection nodes =
            doc.DocumentNode
            .SelectNodes("html//body//div[not(@class)]//table[1]//tr[1]//td[1]//div[1]//div[1]//div[1]//div[1]//table[1]//tr[1]//td[1]//a[1]//div[1]//img");
        //.SelectNodes("html//body//div[2]//table[1]//tr[1]//td[1]//div[1]//div[1]//div[1]//table[1]//tr[1]//td[1]//a[1]//div[1]//img");
        string url = nodes[0].GetAttributeValue("src", "");

        Debug.Log(url);
        return(url);
    }
    public override void ModLoaded()
    {
#if DEBUG
        Log("Running in Debug Mode");
#else
        SoloTesting = false;
        Log("Running in Release Mode");
        System.Net.WebClient wc = new System.Net.WebClient();
        string webData          = wc.DownloadString(TesterURL + SteamUser.GetSteamID().m_SteamID);
        if (webData != "Y")
        {
            return;
        }
#endif

        Log("Valid User " + SteamUser.GetSteamID().m_SteamID);

        VTOLAPI.SceneLoaded += SceneLoaded;
        base.ModLoaded();
        CreateUI();
        gameObject.AddComponent <Networker>();
    }
Example #40
0
    protected void btnChangeTrustee_Click(object sender, EventArgs e)
    {
        ddlTrustee.Visible         = true;
        txtTrusteeCallsign.Visible = false;
        btnChangeTrustee.Visible   = false;
        ddlTrustee.Items.Clear();

        using (var webClient = new System.Net.WebClient())
        {
            string  url  = String.Format(System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "ListPossibleTrustees?callsign={0}&password={1}&repeaterid={2}", creds.Username, creds.Password, txtID.Text);
            string  json = webClient.DownloadString(url);
            dynamic data = JsonConvert.DeserializeObject <dynamic>(json);

            foreach (dynamic obj in data)
            {
                ListItem li = new ListItem(obj["Callsign"].ToString(), obj["ID"].ToString());
                ddlTrustee.Items.Add(li);
            }

            ddlTrustee.SelectedValue = hdnTrusteeId.Value;
        }
    }
    public void getImageURL(string htmlText)
    {
        string key_word = "bag";
        string URL      = "https://www.google.co.jp/search?q=" + key_word + "&tbm=isch&ved=2ahUKEwibvOTL3ufsAhWmzIsBHRqnBdMQ2-cCegQIABAA&oq=" + key_word + "&gs_lcp=CgNpbWcQAzIECAAQHjIECAAQHjIECAAQHjIECAAQHjIECAAQHjIECAAQHjIECAAQHjIECAAQHjIECAAQHjIECAAQHjoECCMQJzoFCAAQsQM6AggAOgQIABAEOgcIIxDqAhAnOgcIABCxAxAEOggIABCxAxCDAToECAAQEzoGCAAQHhATUICQGFiJzRhgz88YaANwAHgAgAHLAYgB4Q6SAQYwLjEzLjGYAQCgAQGqAQtnd3Mtd2l6LWltZ7ABCsABAQ&sclient=img&ei=_gOiX5vFOqaZr7wPms6WmA0&bih=977&biw=1858&hl=ja";

        System.Net.WebClient web = new System.Net.WebClient();
        string html = web.DownloadString(URL);

        Debug.Log(html);


        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(htmlText);


        HtmlNodeCollection nodes =
            doc.DocumentNode
            .SelectNodes("html//body//div[3]//table[1]//tr[1]//td[1]//div[1]//div[1]//div[1]//div[1]//table[1]//tr[1]//td[1]//a[1]//div[1]//img");

        //var htmlDoc = new HtmlAgilityPack.HtmlDocument();
        //htmlDoc.LoadHtml(htmlText);

        //foreach (HtmlNode node in nodes)
        //{
        //    string url = node.GetAttributeValue("src", "");
        //    Debug.Log("なんかな:"+url);
        //}

        string urls = nodes[0].GetAttributeValue("src", "");

        Debug.Log(urls);
        //string links = nodes.InnerHtml;
        //var articles =
        //htmlDoc.DocumentNode
        //.SelectNodes("/html/body/div[1]/table[1]/tr[1]/td[1]/div[1]/div[1]");
        //.SelectNodes(@"//div[@class='T1diZc KWE8qe']//c-wiz[@class='P3Xfjc SSPGKf BIdYQ']//div[@class='mJxzWe']//div[@class='OcgH4b']//div//div//div[@class='tmS4cc']//div[@class='gBPM8']//div[@id='islrg']//div[@class='islrc']//div[1]//a[@class='wXeWr islib nfEiy mM5pbd']//div[@class='bRMDJf islir']//img[1]");
        //Debug.Log(links);
    }
 private void threadMethod()
 {
     try
     {
         using (ProgressBlock progress = new ProgressBlock(_plugin, "Update Favorite for Netherlands, Belgium and Italy", "Downloading data from globalcaching.eu", 1, 0))
         {
             using (System.Net.WebClient wc = new System.Net.WebClient())
             {
                 string doc = wc.DownloadString(string.Format("https://www.4geocaching.eu/Service/CacheFavorites.aspx?token={0}", System.Web.HttpUtility.UrlEncode(_core.GeocachingComAccount.APIToken)));
                 if (doc != null)
                 {
                     string[] lines = doc.Replace("\r", "").Split(new char[] { '\n' });
                     progress.UpdateProgress("Update Favorite of geocaches", "Updating geocaches...", lines.Length, 0);
                     Geocache gc;
                     char[]   sep = new char[] { ',' };
                     string[] parts;
                     foreach (string s in lines)
                     {
                         parts = s.Split(sep);
                         if (parts.Length > 0)
                         {
                             gc = DataAccess.GetGeocache(_core.Geocaches, parts[0]);
                             if (gc != null)
                             {
                                 gc.Favorites = int.Parse(parts[1]);
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         _errormessage = e.Message;
     }
     _actionReady.Set();
 }
    protected string creaCuerpo()
    {
        string Url = "http://" + Request.Url.Authority + "/mailing/plantilla_contacto_mailing.htm";

        System.Net.WebClient client = new System.Net.WebClient();
        String htmlCode             = client.DownloadString(Url);
        string newhtmlCode          = "";

        newhtmlCode = Regex.Replace(htmlCode, "src=\"images", "src=\"" + "http://" + Request.Url.Authority + "/mailing/images", RegexOptions.Multiline | RegexOptions.IgnoreCase);

        newhtmlCode = Regex.Replace(newhtmlCode, "{Nombre}", this.TxtNombre.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Apellido}", this.TxtPaterno.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{Email}", this.TxtEmail.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);


        newhtmlCode = Regex.Replace(newhtmlCode, "{NombreNuevoIntegrante}", this.TxtNombreIntegrante.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{TelefonoNuevoIntegrante}", this.TxtTelefonoIntegrante.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        newhtmlCode = Regex.Replace(newhtmlCode, "{EmailNuevoIntegrante}", this.TxtEmailIntegrante.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);


        newhtmlCode = Regex.Replace(newhtmlCode, "{Mensaje}", this.TxtComentarios.Text, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        return(newhtmlCode);
    }
    private void SendEmail()
    {
        // Get the UserId of the newly added user
        MembershipUser newUser   = Membership.GetUser(CreateUserWizard1.UserName);
        Guid           newUserId = (Guid)newUser.ProviderUserKey;

        // Determine the full verification URL (i.e., http://yoursite.com/verification.aspx?ID=...)
        string urlBase   = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
        string verifyUrl = "/verification.aspx?ID=" + newUserId.ToString();
        string fullUrl   = urlBase + verifyUrl;

        fullUrl = System.Web.HttpContext.Current.Server.UrlEncode(fullUrl);


        // Replace <%VerificationUrl%> with the appropriate URL and querystring
        //e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", fullUrl);
        System.Net.WebClient client = new System.Net.WebClient();
        client.Headers[System.Net.HttpRequestHeader.ContentType] = "application/json";
        string emailTo = Request.Form["RegisterWithRole1$CreateUserWizard1$CreateUserStepContainer$Email"] as string;
        string body    = "Welcome to LinkView, please click the link <a href='" + fullUrl + "'>here</a> to complete your registration.";

        string response = client.DownloadString(ConfigurationManager.AppSettings["url"] + ConfigurationManager.AppSettings["Register"] + "?to=" + emailTo + "&link=" + body);
    }
Example #45
0
    private decimal GetAltitude(string latitude, string longitude)
    {
        decimal output = 0M;
        string  apiKey = System.Configuration.ConfigurationManager.AppSettings["googleMapApiKey"];
        string  url    = String.Format("https://maps.googleapis.com/maps/api/elevation/json?key={0}&locations={1},{2}", apiKey, latitude, longitude);

        try
        {
            using (var webClient = new System.Net.WebClient())
            {
                string  json = webClient.DownloadString(url);
                dynamic data = JsonConvert.DeserializeObject <dynamic>(json);

                decimal.TryParse(data.results[0].elevation.ToString(), out output);
            }
        }
        catch (Exception)
        {
        }


        return(output);
    }
Example #46
0
        public static bool Validate(string encodedResponse)
        {
            if (string.IsNullOrEmpty(encodedResponse))
            {
                return(false);
            }

            var client = new System.Net.WebClient();
            var secret = "6LdlNFYUAAAAALpyiHzEynrkY3HSEgYc8lXhIyxp";

            if (string.IsNullOrEmpty(secret))
            {
                return(false);
            }

            var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse));

            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            var reCaptcha = serializer.Deserialize <ReCaptcha>(googleReply);

            return(reCaptcha.Success);
        }
    public static bool Validate(string encodedResponse)
    {
        if (string.IsNullOrEmpty(encodedResponse))
        {
            return(false);
        }

        var client = new System.Net.WebClient();
        var secret = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"];

        if (string.IsNullOrEmpty(secret))
        {
            return(false);
        }

        var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse));

        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        var reCaptcha = serializer.Deserialize <ReCaptcha>(googleReply);

        return(reCaptcha.Success);
    }
Example #48
0
    private void LoadUsersRepeaters()
    {
        using (var webClient = new System.Net.WebClient())
        {
            string  url  = String.Format(System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "GetUsersRepeaters?callsign={0}&password={1}", creds.Username, creds.Password);
            string  json = webClient.DownloadString(url);
            dynamic data = JsonConvert.DeserializeObject <dynamic>(json);

            string[] fields = { "Callsign", "OutputFrequency", "City", "Status", "DateUpdated" };

            foreach (dynamic obj in data)
            {
                if (obj.ID > 0)
                {
                    TableRow  row  = new TableRow();
                    TableCell cell = new TableCell();
                    Button    btn  = new Button();
                    btn.Text             = "Update";
                    btn.CausesValidation = false;
                    btn.CommandArgument  = obj.ID;
                    btn.CommandName      = "getRepeater";
                    btn.Click           += Button_Click;
                    cell.Controls.Add(btn);
                    row.Cells.Add(cell);

                    for (int i = 0; i < fields.Length; i++)
                    {
                        cell      = new TableCell();
                        cell.Text = obj[fields[i]];
                        row.Cells.Add(cell);
                    }

                    RepeatersTable.Rows.Add(row);
                }
            }
        }
    }
Example #49
0
    /// <summary>
    /// 获取主机IP地址
    /// </summary>
    /// <returns></returns>
    public static string GetHostIp()
    {
        String url = "http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp";
        string IP  = "未获取到外网ip";

        try
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.Encoding = Encoding.Default;
            string str = client.DownloadString(url);
            client.Dispose();

            if (!str.Equals(""))
            {
                IP = str;
            }
        }
        catch (Exception e)
        {
            Debug.LogWarning(e.ToString());
        }
        Debug.Log("get host ip :" + IP);
        return(IP);
    }
Example #50
0
    /// <summary>
    /// 企业微信登录
    /// </summary>
    private void WeChatWorkLoad()
    {
        string accessToken = string.Empty;
        string DeBugMsg    = string.Empty;

        string AppId     = WebConfigurationManager.AppSettings["AgentId"];//与企业微信ID。
        string AppSecret = WebConfigurationManager.AppSettings["Secret"];

        var code    = string.Empty;
        var opentid = string.Empty;

        try
        {
            code      = Request.QueryString["code"];
            DeBugMsg += "code:" + code;
        }
        catch
        {
        }

        if (string.IsNullOrEmpty(code))
        {
        }
        else
        {
            string strWeixin_OpenID = string.Empty;

            string STRUSERID = string.Empty;

            if (strWeixin_OpenID == string.Empty || STRUSERID == string.Empty)
            {
                DeBugMsg += "<br> 没有所需的OPENID!";

                // this.Label1.Text = "没有所需的OPENID";
                var client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;

                var url        = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", AppId, AppSecret);
                var data       = client.DownloadString(url);
                var serializer = new JavaScriptSerializer();
                var obj        = serializer.Deserialize <Dictionary <string, string> >(data);

                if (!obj.TryGetValue("access_token", out accessToken))
                {
                    DeBugMsg += "<br> Token获取错误!";
                }
                else
                {
                    //opentid = obj["openid"];
                    //MessageBox("", "opentid:" + opentid);
                }

                // string tempToken = GetaccessWebToken(code);

                url  = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", accessToken, code);
                data = client.DownloadString(url);
                var userInfo = serializer.Deserialize <Dictionary <string, object> >(data);
                DeBugMsg += "userInfo:" + data.ToString();

                //                {
                //                    "errcode": 0,
                //   "errmsg": "ok",
                //   "UserId":"USERID",// 企业用户         OpenId// 非企业会员
                //   "DeviceId":"DEVICEID"
                //}



                try
                {
                    /// 企业用户
                    opentid     = userInfo["UserId"].ToString();
                    Label2.Text = opentid + "<br>";

                    url  = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={0}&userid={1}", accessToken, opentid);
                    data = client.DownloadString(url);
                    var userInfo2 = serializer.Deserialize <Dictionary <string, object> >(data);//gender 性别。0表示未定义,1表示男性,2表示女性
                    Label2.Text = "姓名:" + userInfo2["name"].ToString() + "<br>性别:" + userInfo2["gender"].ToString() + "<br>头像:" + userInfo2["thumb_avatar"].ToString();
                }
                catch
                {
                    Label2.Text = userInfo["OpenId"].ToString();
                    /// 出错了,则是非企业用户
                    //  MessageBox("", "您非企业员工!<br/>请先登陆!", "/Login.aspx");
                    return;
                }
            }
        }
    }
    private void threadMethod()
    {
        try
        {
            bool cancel = false;
            using (ProgressBlock progress = new ProgressBlock(_plugin, "Bijwerken van status en nieuwe geocaches", "Download gegevens van globalcaching.eu", 1, 0, true))
            {
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    string doc = wc.DownloadString(string.Format("http://www.globalcaching.eu/Service/GeocacheCodes.aspx?country=Belgium&token={0}", System.Web.HttpUtility.UrlEncode(_core.GeocachingComAccount.APIToken)));
                    if (doc != null)
                    {
                        List <string> gcList = new List <string>();

                        string[] lines = doc.Replace("\r", "").Split(new char[] { '\n' });
                        progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Bijwerken van de status...", lines.Length, 0);
                        Geocache gc;
                        char[]   sep = new char[] { ',' };
                        string[] parts;
                        foreach (string s in lines)
                        {
                            parts = s.Split(sep);
                            if (parts.Length > 2)
                            {
                                gc = DataAccess.GetGeocache(_core.Geocaches, parts[0]);
                                if (gc != null)
                                {
                                    gc.Archived  = parts[1] != "0";
                                    gc.Available = parts[2] != "0";
                                }
                                else if (parts[1] == "0") //add only none archived
                                {
                                    gcList.Add(parts[0]);
                                }
                            }
                        }

                        if (gcList.Count == 0)
                        {
                            System.Windows.Forms.MessageBox.Show("Er zijn geen nieuwe geocaches gevonden", "Bericht", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        }
                        else
                        {
                            if (System.Windows.Forms.MessageBox.Show(string.Format("Er zijn {0} nieuwe geocaches gevonden\r\nDeze downloaden?", gcList.Count), "Bericht", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                            {
                                progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Importeren van geocaches...", gcList.Count, 0);

                                using (GeocachingLiveV6 client = new GeocachingLiveV6(_core, string.IsNullOrEmpty(_core.GeocachingComAccount.APIToken)))
                                {
                                    int      index = 0;
                                    int      total = gcList.Count;
                                    int      gcupdatecount;
                                    TimeSpan interval = new TimeSpan(0, 0, 0, 2, 100);
                                    DateTime prevCall = DateTime.MinValue;
                                    bool     dodelay;
                                    gcupdatecount = 30;
                                    dodelay       = (gcList.Count > 30);
                                    while (gcList.Count > 0)
                                    {
                                        if (dodelay)
                                        {
                                            TimeSpan ts = DateTime.Now - prevCall;
                                            if (ts < interval)
                                            {
                                                Thread.Sleep(interval - ts);
                                            }
                                        }
                                        GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest req = new GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest();
                                        req.IsLite               = false;
                                        req.AccessToken          = client.Token;
                                        req.CacheCode            = new GlobalcachingApplication.Utils.API.LiveV6.CacheCodeFilter();
                                        req.CacheCode.CacheCodes = (from a in gcList select a).Take(gcupdatecount).ToArray();
                                        req.MaxPerPage           = gcupdatecount;
                                        req.GeocacheLogCount     = 5;
                                        index += req.CacheCode.CacheCodes.Length;
                                        gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                                        prevCall = DateTime.Now;
                                        var resp = client.Client.SearchForGeocaches(req);
                                        if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                                        {
                                            Import.AddGeocaches(_core, resp.Geocaches);
                                        }
                                        else
                                        {
                                            _errormessage = resp.Status.StatusMessage;
                                            break;
                                        }
                                        if (!progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Importeren van geocaches...", total, index))
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            _errormessage = e.Message;
        }
        _actionReady.Set();
    }
    void CheckReferralLinks()
    {
        // disabled in russian
        if (System.Configuration.ConfigurationManager.AppSettings.Get("WO_Region") == "RU")
        {
            return;
        }

        string CustomerID = web.CustomerID();

        string ReferralID = "";
        string reg_sid    = "";
        string pixelUrl   = "";

        // get pixel info
        {
            SqlCommand sqcmd = new SqlCommand();
            sqcmd.CommandType = CommandType.StoredProcedure;
            sqcmd.CommandText = "ECLIPSE_ReferralsGetUserInfo";
            sqcmd.Parameters.AddWithValue("@in_CustomerID", CustomerID);

            if (!CallWOApi(sqcmd))
            {
                return;
            }

            reader.Read();
            ReferralID = reader["ReferralID"].ToString();
            reg_sid    = reader["reg_sid"].ToString();
        }

        if (ReferralID == "1288929113")  // REFERID_radone1
        {
            pixelUrl = "http://panel.gwallet.com/network-node/postback/earthlink?sid=" + reg_sid;
        }

        if (ReferralID == "1288987160") // REFERID_tokenads
        {
            pixelUrl = string.Format(
                "http://offers.tokenads.com/pixel/401?remote_id={0}&tid={1}&amount=1&cur=USD",
                CustomerID, reg_sid);
        }

        if (ReferralID == "1288932284")  // REFERID_cpmstar
        {
            pixelUrl = string.Format(
                "https://server.cpmstar.com/action.aspx?advertiserid=2133&gif=1");
        }

        if (pixelUrl == "")
        {
            return;
        }

        // call pixel
        string ErrorMsg = "";

        try
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.DownloadString(pixelUrl);
        }
        catch (Exception e)
        {
            ErrorMsg = e.Message;
        }

        /*
         * //log to our server for test
         * try
         * {
         *  //client.DownloadString("https://api1.thewarinc.com/php/qq2.php?id=" + pixelUrl);
         * }
         * catch { }
         */

        // log pixel call result
        {
            SqlCommand sqcmd = new SqlCommand();
            sqcmd.CommandType = CommandType.StoredProcedure;
            sqcmd.CommandText = "ECLIPSE_ReferralsLogPixel";
            sqcmd.Parameters.AddWithValue("@in_CustomerID", CustomerID);
            sqcmd.Parameters.AddWithValue("@in_ReferralID", ReferralID);
            sqcmd.Parameters.AddWithValue("@in_PixelURL", pixelUrl);
            sqcmd.Parameters.AddWithValue("@in_ErrorMsg", ErrorMsg);

            if (!CallWOApi(sqcmd))
            {
                return;
            }
        }
    }
Example #53
0
    public ApiResult call(string method, Dictionary <string, dynamic> paramList)
    {
        try {
            var builder = new UriBuilder(this.baseUrl);
            builder.Path = "/api/" + this.version + "/" + method;
            var query = HttpUtility.ParseQueryString(builder.Query);

            query["token"] = this.token;
            foreach (KeyValuePair <string, dynamic> pair in paramList)
            {
                if (pair.Value.GetType() == typeof(System.Collections.Generic.List <string>))
                {
                    int multiValIndex = 0;
                    for (multiValIndex = 0; multiValIndex < pair.Value.Count; multiValIndex++)
                    {
                        query.Add(pair.Key + "[]", pair.Value[multiValIndex]);
                    }
                }
                else
                {
                    query[pair.Key] = pair.Value;
                }
            }

            builder.Query = query.ToString();
            string url = builder.ToString();

            if (debug)
            {
                Console.WriteLine(url);
            }

            var jsonString = @"{}";


            using (var webClient = new System.Net.WebClient()) {
                webClient.Encoding = System.Text.Encoding.UTF8;
                jsonString         = webClient.DownloadString(url);
            }

            if (debug)
            {
                var debugJsonString = jsonString;
                Console.WriteLine(debugJsonString);
                JsonTextReader reader = new JsonTextReader(new StringReader(debugJsonString));
                while (reader.Read())
                {
                    if (reader.Value != null)
                    {
                        Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
                    }
                    else
                    {
                        Console.WriteLine("Token: {0}", reader.TokenType);
                    }
                }
            }

            ApiResult result = new ApiResult(jsonString, method);
            return(result);
        } catch (Exception e) {
            ApiResult errorResult = new ApiResult("", method);
            errorResult.ErrorMessage = e.ToString();
            return(errorResult);
        }
    }
	protected void loadExpiredRepeatersReport()
	{
		System.Web.UI.ControlCollection pnl = pnlExpiredRepeaters.Controls;
		string json = "";

		if (ViewState["expiredRepeaters"] == null)
		{
			using (var webClient = new System.Net.WebClient())
			{
				string url = String.Format(System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "ReportExpiredRepeaters?callsign={0}&password={1}", creds.Username, creds.Password);
				json = webClient.DownloadString(url);
				ViewState["expiredRepeaters"] = json;
			}
		}
		else
		{
			json = ViewState["expiredRepeaters"].ToString();
		}

		dynamic data = JsonConvert.DeserializeObject<dynamic>(json);

		Table table = new Table();
		if ((data.Report != null) && (data.Report.Data != null))
		{
			foreach (dynamic item in data.Report.Data)
			{
				dynamic repeater = item.Repeater;
				
				if ((repeater.City == null) || (((string)repeater.City).Trim() == "")) {
					repeater.City = "[blank]";
				}

				using (TableRow headerRow = new TableRow())
				{
					headerRow.AddCell("Expired");
					headerRow.AddCell("ID");
					headerRow.AddCell("Callsign");
					headerRow.AddCell("Xmit freq");
					headerRow.AddCell("City");
					headerRow.AddCell("Sponsor");
					headerRow.AddCell("Trustee");
					headerRow.AddCell("Contact info");
					headerRow.CssClass = "expiredRepeaterHeader";
					table.Rows.Add(headerRow);
				}

				using (TableRow row = new TableRow())
				{
					row.AddCell((string)repeater.YearsExpired + " years");
					row.AddCell(string.Format("<a target='_blank' title='Update' href='/update/?id={0}'>{0}</a>", (string)repeater.ID));
					row.AddCell(string.Format("<a target='_blank' title='QRZ' href='https://qrz.com/db/{0}'>{0}</a>", (string)repeater.Callsign));
					row.AddCell(string.Format("<a target='_blank' title='RepeaterBook' href='https://repeaterbook.com/repeaters/msResult.php?state_id%5B%5D=05&band=%25&freq={0}&loc=&call=&features=%25&emcomm=%25&coverage=%25&status_id=%25&order=%60freq%60%2C+%60state_abbrev%60+ASC'>{0}</a>", (string)repeater.Output));
					row.AddCell(string.Format("<a target='_blank' href='https://www.google.com/maps/search/?api=1&query={1},{2}'>{0}</a>", (string)repeater.City, (string)repeater.Latitude, (string)repeater.Longitude));
					row.AddCell((string)repeater.Sponsor);
					row.AddCell(string.Format("<a target='_blank' title='QRZ' href='https://qrz.com/db/{0}'>{1}</a>", (string)repeater.Trustee.Callsign, (string)repeater.Trustee.Name));

					string strContact = string.Empty;
					if ((string)repeater.Trustee.Email != string.Empty)
					{
						if (strContact != string.Empty) { strContact += ", "; }
						strContact += "<a href='mailto:" + (string)repeater.Trustee.Email + "'>" + (string)repeater.Trustee.Email + "</a> ";
					}

                    string strPhone = string.Empty;
                    if ((string)repeater.Trustee.CellPhone != string.Empty)
                    {
                        if (strContact != string.Empty) { strContact += ", "; }
                        strPhone = (string)repeater.Trustee.CellPhone;
                        strContact += "<a href='tel:" + strPhone + "'>" + strPhone + "</a> (cell)";
                    }
                    if ((string)repeater.Trustee.HomePhone != string.Empty)
                    {
                        if (strContact != string.Empty) { strContact += ", "; }
                        strPhone = (string)repeater.Trustee.HomePhone;
                        strContact += "<a href='tel:" + strPhone + "'>" + strPhone + "</a> (home)";
                    }
                    if ((string)repeater.Trustee.WorkPhone != string.Empty)
                    {
                        if (strContact != string.Empty) { strContact += ", "; }
                        strPhone = (string)repeater.Trustee.WorkPhone;
                        strContact += "<a href='tel:" + strPhone + "'>" + strPhone + "</a> (work)";
                    }

                    row.AddCell(strContact);
					row.CssClass = "expiredRepeaterData";
					table.Rows.Add(row);
				}

				using (TableRow row = new TableRow())
				{
					string strNotes = "";
					if (repeater.Notes != null)
					{
						strNotes = "<ul>";
						foreach (dynamic obj in repeater.Notes)
						{
							strNotes += string.Format("<li>{0} - {1} ({2}, {3})</li>", obj.Note.Timestamp, obj.Note.Text, obj.Note.User.Name, obj.Note.User.Callsign);
						}
						strNotes += "</ul>";
					}
					else
					{
						strNotes = "<ul><li><em>There are no notes on record for this repeater.</em></li></ul>";
					}
					row.AddCell(strNotes, 8);
					row.CssClass = "expiredRepeaterNotes";
					table.Rows.Add(row);
				}

				using (TableRow row = new TableRow())
				{
					Label label = new Label();
					label.Text = "Note: ";
					TextBox textbox = new TextBox();
					textbox.ID = "txt" + repeater.ID;
					textbox.CssClass = "expiredRepeaterNote";
					Button button = new Button();
					button.CommandArgument = repeater.ID;
					button.CommandName = "saveNote";
					button.Click += Button_Click;
					button.Text = "Save";

					TableCell cell = new TableCell();
					cell.Controls.Add(label);
					cell.Controls.Add(textbox);
					cell.Controls.Add(button);
					cell.ColumnSpan = 8;
					row.Cells.Add(cell);
					row.CssClass = "expiredRepeaterNewNote";
					table.Rows.Add(row);
				}
			}
		}
		pnlExpiredRepeaters.Controls.Add(table);

	}
Example #55
0
    /// <summary>
    /// 微信登录
    /// </summary>
    private void WeChatLoad()
    {
        string accessToken = string.Empty;
        string DeBugMsg    = string.Empty;

        string AppId     = WebConfigurationManager.AppSettings["CorpId"];//与微信公众账号后台的AppId设置保持一致,区分大小写。
        string AppSecret = WebConfigurationManager.AppSettings["WeixinAppSecret"];

        var code    = string.Empty;
        var opentid = string.Empty;

        try
        {
            code      = Request.QueryString["code"];
            DeBugMsg += "code:" + code;
        }
        catch
        {
        }

        if (string.IsNullOrEmpty(code))
        {
        }
        else
        {
            string strWeixin_OpenID = string.Empty;

            string STRUSERID = string.Empty;

            if (strWeixin_OpenID == string.Empty || STRUSERID == string.Empty)
            {
                DeBugMsg += "<br> 没有所需的OPENID!";

                // this.Label1.Text = "没有所需的OPENID";
                var client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;

                var url        = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppId, AppSecret, code);
                var data       = client.DownloadString(url);
                var serializer = new JavaScriptSerializer();
                var obj        = serializer.Deserialize <Dictionary <string, string> >(data);

                if (!obj.TryGetValue("access_token", out accessToken))
                {
                    DeBugMsg += "<br> Token获取错误!";
                }
                else
                {
                    opentid = obj["openid"];
                    //MessageBox("", "opentid:" + opentid);
                }

                // string tempToken = GetaccessWebToken(code);

                url  = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid);
                data = client.DownloadString(url);
                var userInfo = serializer.Deserialize <Dictionary <string, object> >(data);
                DeBugMsg += "userInfo:" + data.ToString();
                int vsex = 2;

                var vcity = "中国";

                if (userInfo["sex"].ToString() == "1")
                {
                    vsex = 0;
                }

                vcity     = userInfo["country"].ToString() + userInfo["province"].ToString() + userInfo["city"].ToString();
                DeBugMsg += "城市:" + vcity;
                if (opentid.Length == 0)
                {
                    opentid = "test111";
                }
                string UserName    = "******";
                string HeadUserUrl = "";

                UserName    = userInfo["nickname"].ToString();
                DeBugMsg   += "昵称:" + UserName;
                HeadUserUrl = userInfo["headimgurl"].ToString();

                DeBugMsg += "头像:" + HeadUserUrl;


                string strSQL;
                strSQL = " Select * from S_USERINFO where COPENID='" + opentid.ToString() + "'";

                if (OP_Mode.SQLRUN(strSQL))
                {
                    if (OP_Mode.Dtv.Count > 0)
                    {
                        if (Convert.ToInt32(OP_Mode.Dtv[0]["flag"]) != 0)
                        {
                            MessageBox("", "您被禁止登陆!<br>请联系管理员。", "/Login.aspx");
                            return;
                        }
                        /// 如果数据库有ID,则直接登录。
                        Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_USERID] = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                        Response.Cookies["WeChat_Yanwo"]["USERID"]  = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                        Response.Cookies["WeChat_Yanwo"]["COPENID"] = opentid.ToString();
                        Response.Cookies["WeChat_Yanwo"]["CNAME"]   = HttpUtility.UrlEncode(UserName);
                        Response.Cookies["WeChat_Yanwo"]["LTIME"]   = OP_Mode.Dtv[0]["LTIME"].ToString().Trim();
                        Response.Cookies["WeChat_Yanwo"]["HEADURL"] = HeadUserUrl;

                        Response.Cookies["WeChat_Yanwo"]["LOGIN"] = "******";

                        Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CNAME] = UserName;
                        Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CTX]   = HeadUserUrl;

                        ///设置COOKIE最长时间
                        Response.Cookies["WeChat_Yanwo"].Expires = DateTime.MaxValue;

                        /// 更新登录时间
                        OP_Mode.SQLRUN("Update S_USERINFO set Ltime=getdate(),HEADURL='" + HeadUserUrl + "',XB=" + vsex + " where COPENID='" + opentid.ToString() + "'");

                        return;
                    }
                    else
                    {
                        try
                        {
                            strSQL = " INSERT INTO S_USERINFO (LOGINNAME,PASSWORD,COPENID,CNAME,HEADURL,XB) VALUES ('" + opentid + "','" + opentid + "','" + opentid + "','" + UserName + "','" + HeadUserUrl + "'," + vsex + ")";

                            strSQL += " Select * from S_USERINFO where COPENID='" + opentid + "'";

                            DeBugMsg += "+" + strSQL + "+";

                            if (OP_Mode.SQLRUN(strSQL))
                            {
                                if (OP_Mode.Dtv.Count > 0)
                                {
                                    Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_USERID] = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["USERID"]  = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["COPENID"] = OP_Mode.Dtv[0]["COPENID"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["CNAME"]   = HttpUtility.UrlEncode(OP_Mode.Dtv[0]["CNAME"].ToString()); //HttpUtility.UrlDecode(Request.Cookies["SK_WZGY"]["CNAME"].ToString().Trim(), Encoding.GetEncoding("UTF-8"))
                                    Response.Cookies["WeChat_Yanwo"]["LTIME"]   = OP_Mode.Dtv[0]["LTIME"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["HEADURL"] = OP_Mode.Dtv[0]["HEADURL"].ToString().Trim();

                                    Response.Cookies["WeChat_Yanwo"][Constant.COOKIENAMEUSER_CNAME]        = OP_Mode.Dtv[0]["CNAME"].ToString().Trim();
                                    Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CTX] = OP_Mode.Dtv[0]["HEADURL"].ToString().Trim();

                                    Response.Cookies["WeChat_Yanwo"]["LOGIN"] = "******";
                                    Response.Cookies[Constant.COOKIENAMEOPENDOOR][Constant.COOKIENAMEOPENDOOR_LGOIN] = "true";
                                    ///设置COOKIE最长时间  不设置时间,窗口关闭则丢失
                                    Response.Cookies["WeChat_Yanwo"].Expires = DateTime.MaxValue;

                                    string MSG = string.Empty;// string.Format("<img class=\"img-rounded\" src=\"{1}\" width=\"60PX\" />欢迎 {0} 注册成功。<br/>祝您生活愉快。", OP_Mode.Dtv[0]["CNAME"].ToString(), OP_Mode.Dtv[0]["HEADURL"].ToString());

                                    MSG = "<img class=\"img-rounded\" src=\"" + OP_Mode.Dtv[0]["HEADURL"].ToString() + "\" width=\"60PX\" />欢迎 " + OP_Mode.Dtv[0]["CNAME"].ToString() + " 注册成功。<br/>祝您生活愉快。";

                                    MessageBox("", MSG);

                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            DeBugMsg += "<br>" + ex.ToString();
                            MessageBox("", "4:" + DeBugMsg);
                        }
                    }
                }
                else
                {
                    DeBugMsg += OP_Mode.strErrMsg;
                    MessageBox("", "5:" + DeBugMsg);
                }
            }
        }
    }
Example #56
0
    /// <summary>
    /// 企业微信登录
    /// </summary>
    private void WeChatWorkLoad()
    {
        string accessToken = string.Empty;
        string DeBugMsg    = string.Empty;

        string AppId     = WebConfigurationManager.AppSettings["AgentId"];//与企业微信ID。
        string AppSecret = WebConfigurationManager.AppSettings["Secret"];

        var code    = string.Empty;
        var opentid = string.Empty;

        try
        {
            code      = Request.QueryString["code"];
            DeBugMsg += "code:" + code;
        }
        catch
        {
        }

        if (string.IsNullOrEmpty(code))
        {
        }
        else
        {
            string strWeixin_OpenID = string.Empty;

            string STRUSERID = string.Empty;

            if (strWeixin_OpenID == string.Empty || STRUSERID == string.Empty)
            {
                accessToken = GetWorkToken();

                if (accessToken.Length <= 0)
                {
                    MessageBox("", "您非企业员工!<br/>请先登陆!", "/Login.aspx");
                    return;
                }

                DeBugMsg += "<br> 没有所需的OPENID!";

                // this.Label1.Text = "没有所需的OPENID";
                var client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;

                //var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", AppId, AppSecret);
                //var data = client.DownloadString(url);
                var serializer = new JavaScriptSerializer();
                //var obj = serializer.Deserialize<Dictionary<string, string>>(data);

                //if (!obj.TryGetValue("access_token", out accessToken))
                //{
                //    DeBugMsg += "<br> Token获取错误!";
                //}
                //else
                //{
                //    //opentid = obj["openid"];
                //    //MessageBox("", "opentid:" + opentid);
                //}
                // string tempToken = GetaccessWebToken(code);

                var url      = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", accessToken, code);
                var data     = client.DownloadString(url);
                var userInfo = serializer.Deserialize <Dictionary <string, object> >(data);
                DeBugMsg += "userInfo:" + data.ToString();

                //                {
                //                    "errcode": 0,
                //   "errmsg": "ok",
                //   "UserId":"USERID",// 企业用户         OpenId// 非企业会员
                //   "DeviceId":"DEVICEID"
                //}

                string UserName    = "******";
                string HeadUserUrl = "";
                string Mobile      = "";
                int    vsex        = 2;
                try
                {
                    /// 企业用户
                    opentid = userInfo["UserId"].ToString();
                    url     = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={0}&userid={1}", accessToken, opentid);
                    data    = client.DownloadString(url);
                    var userInfo2 = serializer.Deserialize <Dictionary <string, object> >(data);//gender 性别。0表示未定义,1表示男性,2表示女性
                    UserName    = userInfo2["name"].ToString();
                    HeadUserUrl = userInfo2["thumb_avatar"].ToString();
                    Mobile      = userInfo2["mobile"].ToString();
                    vsex        = Convert.ToInt32(userInfo2["gender"]);

                    //         Label2.Text = "姓名:" + userInfo2["name"].ToString() + "<br>性别:" + userInfo2["gender"].ToString() + "<br>头像:" + userInfo2["thumb_avatar"].ToString();
                }
                catch
                {
                    /// 出错了,则是非企业用户
                    MessageBox("", "您非企业员工!<br/>请先登陆!", "/Login.aspx");
                    return;
                }



                //var vcity = "中国";

                //if (userInfo["sex"].ToString() == "1")
                //{
                //    vsex = 0;
                //}

                //vcity = userInfo["country"].ToString() + userInfo["province"].ToString() + userInfo["city"].ToString();
                //DeBugMsg += "城市:" + vcity;
                //if (opentid.Length == 0)
                //{
                //    opentid = "test111";
                //}

                //UserName = userInfo["nickname"].ToString();
                //DeBugMsg += "昵称:" + UserName;
                //HeadUserUrl = userInfo["headimgurl"].ToString();

                //DeBugMsg += "头像:" + HeadUserUrl;


                string strSQL;
                strSQL = " Select * from S_USERINFO where COPENID='" + opentid.ToString() + "'";

                if (OP_Mode.SQLRUN(strSQL))
                {
                    if (OP_Mode.Dtv.Count > 0)
                    {
                        if (Convert.ToInt32(OP_Mode.Dtv[0]["flag"]) != 0)
                        {
                            MessageBox("", "您被禁止登陆!<br>请联系管理员。", "/Login.aspx");
                            return;
                        }

                        /// 如果数据库有ID,则直接登录。
                        Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_USERID] = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                        Response.Cookies["WeChat_Yanwo"]["USERID"]  = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                        Response.Cookies["WeChat_Yanwo"]["COPENID"] = opentid.ToString();
                        Response.Cookies["WeChat_Yanwo"]["CNAME"]   = HttpUtility.UrlEncode(UserName);
                        Response.Cookies["WeChat_Yanwo"]["LTIME"]   = OP_Mode.Dtv[0]["LTIME"].ToString().Trim();
                        Response.Cookies["WeChat_Yanwo"]["HEADURL"] = HeadUserUrl;

                        Response.Cookies["WeChat_Yanwo"]["LOGIN"] = "******";

                        Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CNAME] = UserName;
                        Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CTX]   = HeadUserUrl;

                        ///设置COOKIE最长时间
                        Response.Cookies["WeChat_Yanwo"].Expires = DateTime.MaxValue;

                        /// 更新登录时间
                        OP_Mode.SQLRUN("Update S_USERINFO set Ltime=getdate(),SSDZ='" + Mobile + "',HEADURL='" + HeadUserUrl + "' where COPENID='" + opentid.ToString() + "'");

                        return;
                    }
                    else
                    {
                        try
                        {
                            strSQL = " INSERT INTO S_USERINFO (LOGINNAME,PASSWORD,COPENID,CNAME,HEADURL,XB,SSDZ,flag) VALUES ('" + opentid + "','" + opentid + "','" + opentid + "','" + UserName + "','" + HeadUserUrl + "'," + vsex + ",'" + Mobile + "',0)";

                            strSQL += " Select * from S_USERINFO where COPENID='" + opentid + "'";

                            DeBugMsg += "+" + strSQL + "+";

                            if (OP_Mode.SQLRUN(strSQL))
                            {
                                if (OP_Mode.Dtv.Count > 0)
                                {
                                    Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_USERID] = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["USERID"]  = OP_Mode.Dtv[0]["ID"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["COPENID"] = OP_Mode.Dtv[0]["COPENID"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["CNAME"]   = HttpUtility.UrlEncode(OP_Mode.Dtv[0]["CNAME"].ToString()); //HttpUtility.UrlDecode(Request.Cookies["SK_WZGY"]["CNAME"].ToString().Trim(), Encoding.GetEncoding("UTF-8"))
                                    Response.Cookies["WeChat_Yanwo"]["LTIME"]   = OP_Mode.Dtv[0]["LTIME"].ToString().Trim();
                                    Response.Cookies["WeChat_Yanwo"]["HEADURL"] = OP_Mode.Dtv[0]["HEADURL"].ToString().Trim();

                                    Response.Cookies["WeChat_Yanwo"][Constant.COOKIENAMEUSER_CNAME]        = OP_Mode.Dtv[0]["CNAME"].ToString().Trim();
                                    Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CTX] = OP_Mode.Dtv[0]["HEADURL"].ToString().Trim();

                                    Response.Cookies["WeChat_Yanwo"]["LOGIN"] = "******";
                                    Response.Cookies[Constant.COOKIENAMEOPENDOOR][Constant.COOKIENAMEOPENDOOR_LGOIN] = "true";
                                    ///设置COOKIE最长时间  不设置时间,窗口关闭则丢失
                                    Response.Cookies["WeChat_Yanwo"].Expires = DateTime.MaxValue;

                                    string MSG = string.Empty;// string.Format("<img class=\"img-rounded\" src=\"{1}\" width=\"60PX\" />欢迎 {0} 注册成功。<br/>祝您生活愉快。", OP_Mode.Dtv[0]["CNAME"].ToString(), OP_Mode.Dtv[0]["HEADURL"].ToString());

                                    MSG = "<img class=\"img-rounded\" src=\"" + OP_Mode.Dtv[0]["HEADURL"].ToString() + "\" width=\"60PX\" />欢迎 " + OP_Mode.Dtv[0]["CNAME"].ToString() + " 注册成功。<br/>祝您生活愉快。";

                                    MessageBox("", MSG);

                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            DeBugMsg += "<br>" + ex.ToString();
                            MessageBox("", "4:" + DeBugMsg);
                        }
                    }
                }
                else
                {
                    DeBugMsg += OP_Mode.strErrMsg;
                    MessageBox("", "5:" + DeBugMsg);
                }
            }
        }
    }
Example #57
0
    protected void FillControl()
    {
        Project_Master   plist        = new Project_Master();
        List <PI_Master> List_DEPT_PI = new List <PI_Master>();
        List <Project_Coordinator_Details> List_Co_Ord = new List <Project_Coordinator_Details>();

        try
        {
            ShowPanel("entry");
            // plist = cl.GetProject_MasterDetailsByID(Convert.ToInt32(Common.iffBlank(HdnId.Value, 0)));
            ProjectMasterModel   pmm    = new ProjectMasterModel();
            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
            string arr = client.DownloadString(string.Format("{0}api/ProjectMaster/{1}", Session["WebApiUrl"].ToString(), Convert.ToInt32(Common.iffBlank(HdnId.Value, 0))));
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            pmm = serializer.Deserialize <ProjectMasterModel>(arr);
            //  using (var client = new HttpClient())
            //{
            //    // client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiUrl"].ToString());
            //    client.BaseAddress = new Uri(Session["WebApiUrl"].ToString());
            //    client.DefaultRequestHeaders.Accept.Clear();
            //    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //    HttpResponseMessage response = await client.GetAsync(string.Format("api/ProjectMaster/{0}", Convert.ToInt32(Common.iffBlank(HdnId.Value, 0))));
            //    JavaScriptSerializer serializer = new JavaScriptSerializer();
            //    pmm = serializer.Deserialize<ProjectMasterModel>(response.Content.ReadAsStringAsync().Result);
            //}
            // BindCombo();
            BindCoOrdinator();
            plist = pmm._Project_Master;
            TxtDispProjId.Text      = Common.GetReplace(plist.s_Display_Project_ID);
            DispProjectId.InnerText = TxtDispProjId.Text;
            TxtstartDate.Text       = plist.Project_StartDate;
            TxtprojTitle.Text       = Common.GetReplace(plist.s_Project_Title);
            TxtShortTitle.Text      = Common.GetReplace(plist.s_Short_Title);
            TxtProjTitleAlias1.Text = Common.GetReplace(plist.s_Project_Alias1);
            TxtProjTitleAlias2.Text = Common.GetReplace(plist.s_Project_Alias2);
            TxtProjDescription.Text = Common.GetReplace(plist.s_Project_Desc);
            TxtIRBno.Text           = Common.GetReplace(plist.s_IRB_No);

            ddlProjCategory.SelectedIndex = ddlProjCategory.Items.IndexOf(ddlProjCategory.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_Project_Category_ID, ""))));
            ddlProjType.SelectedIndex     = ddlProjType.Items.IndexOf(ddlProjType.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_Project_Type_ID, ""))));
            ddlProjType_SelectedIndexChanged(null, null);
            ddlProjSubType.SelectedIndex       = ddlProjSubType.Items.IndexOf(ddlProjSubType.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_Project_Subtype_ID, ""))));
            ddlProjSubType.Enabled             = (ddlProjSubType.SelectedIndex > 0) ? true : false;
            ddlFeasibilityStatus.SelectedIndex = ddlFeasibilityStatus.Items.IndexOf(ddlFeasibilityStatus.Items.FindByValue(Convert.ToString(plist.b_IsFeasible)));
            HdnFeasibilityStatus.Value         = Convert.ToString(plist.b_IsFeasible);
            ddlselectedproject.SelectedIndex   = ddlselectedproject.Items.IndexOf(ddlselectedproject.Items.FindByValue(Convert.ToString(plist.b_Isselected_project == true ? "1" : "0")));
            ddlCollbrationInv.SelectedIndex    = ddlCollbrationInv.Items.IndexOf(ddlCollbrationInv.Items.FindByValue(Convert.ToString(plist.b_Collaboration_Involved == true ? "1" : "0")));
            if (ddlProjCategory.SelectedItem.Text.ToLower() == "pharma")
            {
                ddlCollbrationInv.Enabled = false;
            }
            ddlstartbyTTSH.SelectedIndex = ddlstartbyTTSH.Items.IndexOf(ddlstartbyTTSH.Items.FindByValue(Convert.ToString(plist.b_StartBy_TTSH == true ? "1" : "0")));
            ddlfundingReq.SelectedIndex  = ddlfundingReq.Items.IndexOf(ddlfundingReq.Items.FindByValue(Convert.ToString(plist.b_Funding_req == true ? "1" : "0")));
            ddlChildParent.SelectedIndex = ddlChildParent.Items.IndexOf(ddlChildParent.Items.FindByValue(Convert.ToString(plist.b_Ischild == true ? "0" : "1")));
            if (ddlChildParent.SelectedValue == "0")
            {
                ddlParentProjName.Enabled       = true; txtParentProjId.Enabled = true;
                ddlParentProjName.SelectedIndex = ddlParentProjName.Items.IndexOf(ddlParentProjName.Items.FindByValue(Convert.ToString(plist.i_Parent_ProjectID)));
                ddlParentProjName_SelectedIndexChanged(null, null);
            }
            else
            {
                ddlParentProjName.Enabled = false; txtParentProjId.Enabled = false;
            }

            //-------Newly Added 31-08-2015------------
            ddlProjectStatus.SelectedIndex = ddlProjectStatus.Items.IndexOf(ddlProjectStatus.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_ProjectStatus, ""))));
            TxtProjectEndDate.Text         = Convert.ToString(plist.Dt_ProjectEndDate);
            ddlEthicsNeeded.SelectedValue  = (plist.b_EthicsNeeded == true) ? "1" : "0";
            //---- END---------------------------------


            ScriptManager.RegisterStartupScript(Page, typeof(Page), "Enable", "BindDoObjects();", true);
            /*dataowner fill*/
            ddlDO_Ethics.SelectedIndex      = ddlDO_Ethics.Items.IndexOf(ddlDO_Ethics.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Ethics_DataOwner, ""))));
            ddlDO_Feasibility.SelectedIndex = ddlDO_Feasibility.Items.IndexOf(ddlDO_Feasibility.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Feasibility_DataOwner, ""))));
            ddlDO_Contract.SelectedIndex    = ddlDO_Contract.Items.IndexOf(ddlDO_Contract.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Contract_DataOwner, ""))));
            ddlDO_Selected.SelectedIndex    = ddlDO_Selected.Items.IndexOf(ddlDO_Ethics.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Selected_DataOwner, ""))));
            ddlDO_Regulatory.SelectedIndex  = ddlDO_Regulatory.Items.IndexOf(ddlDO_Regulatory.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Regulatory_DataOwner, ""))));
            ddlDO_Grant.SelectedIndex       = ddlDO_Grant.Items.IndexOf(ddlDO_Grant.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Grant_DataOwner, ""))));

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "enable", "alert('Hello!')", true);

            //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "enable", "BindDoObjects();", true);
            /**/

            List_DEPT_PI = pmm.DEPT_PI.ToList(); //plist.DEPT_PI.ToList();
            var q = (from i in List_DEPT_PI select new { i.i_Dept_ID, i.i_ID }).ToList().ListToDatatable();
            rptrPIDetails.DataSource = List_DEPT_PI;
            rptrPIDetails.DataBind();

            txtResearchOrder.Text    = Common.GetReplace(plist.s_Research_IO);
            txtReserchInsurance.Text = Common.GetReplace(plist.s_Research_IP);
            List_Co_Ord = pmm.pcd.ToList(); //plist.COORDINATOR.ToList();
            for (int j = 0; j < chkboxlist.Items.Count; j++)
            {
                for (int i = 0; i < List_Co_Ord.Count; i++)
                {
                    if (chkboxlist.Items[j].Value == Convert.ToString(List_Co_Ord[i].i_Coordinator_ID))
                    {
                        chkboxlist.Items[j].Selected = true;
                        TextSearch.Text += chkboxlist.Items[j].Text + ",";
                    }
                }
            }
            if (TextSearch.Text != "")
            {
                TextSearch.Text = TextSearch.Text.TrimEnd(',');
            }

            //	TxtDispProjId.Attributes.Add("onblur", "javascript:return GetValidatefrmDB('" + HdnError.ClientID + "','ValidateDispID' ,'" + TxtDispProjId.ClientID + "','" + HdnId.Value + "');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "ClearAll('" + HdnMode.Value + "');", true);

            if (HdnMode.Value.ToLower() == "update")
            {
                // String s = cl.GetValidate("RestrictChild", HdnId.Value, "", "", "");
                //if (s != "")
                //{
                //    ddlChildParent.Enabled = false;
                //    ddlChildParent.Attributes.Add("title", "Child Project is Created for this Project..!!");
                //}
            }
            ChangeButtonText();

            MakeControlValidate();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Example #58
0
    protected void getPublicRepeaterList()
    {
        int includeDecoordinated = 0;

        if (!chkIncludeDecoordinated.Checked)
        {
            includeDecoordinated = 6;  // 6 is the internet ID for repeater_status decoordinated. This is used to NOT include those in the dataset
        }

        string uri = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "ListPublicRepeaters?state=ar";

        Regex rxLatLon = new Regex(@"([-+]?(?:[0-9]|[1-9][0-9])\.\d+),\s*([-+]?(?:[0-9]|[1-9][0-9]|[1-9][0-9][0-9])\.\d+)");

        if (rxLatLon.IsMatch(txtSearch.Text))
        {
            MatchCollection matches = rxLatLon.Matches(txtSearch.Text);
            Match           match   = matches[0];
            GroupCollection groups  = match.Groups;
            orderBy = "Distance";
            uri    += string.Format("&latitude={0}&longitude={1}&miles={2}&orderBy={3}&includeDecoordinated={4}", groups[1], groups[2], "40", orderBy, includeDecoordinated);
        }
        else
        {
            uri += string.Format("&search={0}&pageNumber={1}&pageSize={2}&orderBy={3}&includeDecoordinated={4}", query, page.ToString(), "9", orderBy, includeDecoordinated);
        }

        using (var webClient = new System.Net.WebClient())
        {
            System.Diagnostics.Debug.WriteLine(uri);
            string  json = webClient.DownloadString(uri);
            dynamic data = JsonConvert.DeserializeObject <dynamic>(json);

            foreach (dynamic obj in data)
            {
                TableRow row = new TableRow();
                row.CssClass = "repeaterListTableRow " + obj.Status;

                using (TableCell cell = new TableCell())
                {
                    cell.Text = "<a href='details/?id=" + obj.ID + "'>Details</a>";
                    row.Cells.Add(cell);
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = obj.OutputFrequency;
                    row.Cells.Add(cell);
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = obj.Offset;
                    row.Cells.Add(cell);
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = string.Format("<a href='https://qrz.com/db/{0}' target='_blank'>{0}</a>", obj.Callsign);
                    row.Cells.Add(cell);
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = string.Format("<a href='https://qrz.com/db/{0}' target='_blank'>{0}</a>", obj.Trustee);
                    row.Cells.Add(cell);
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = obj.Status;
                    row.Cells.Add(cell);
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = obj.City;
                    row.Cells.Add(cell);
                }

                List <string> attributes = new List <string>();
                Utilities.GetValueIfNotNull(obj.Analog_InputAccess, "input tone: ", attributes);
                Utilities.GetValueIfNotNull(obj.Analog_OutputAccess, "output tone: ", attributes);
                Utilities.GetValueIfNotNull(obj.DSTAR_Module, "D-Star module: ", attributes);
                Utilities.GetValueIfNotNull(obj.DMR_ID, "DMR ID: ", attributes);
                Utilities.GetNameIfNotNull(obj.AutoPatch, "autopatch", attributes);
                Utilities.GetNameIfNotNull(obj.EmergencyPower, "emergency power", attributes);
                Utilities.GetNameIfNotNull(obj.Linked, "linked", attributes);
                Utilities.GetNameIfNotNull(obj.RACES, "RACES", attributes);
                Utilities.GetNameIfNotNull(obj.ARES, "ARES", attributes);
                Utilities.GetNameIfNotNull(obj.Weather, "weather net", attributes);

                string strAttributes = "";
                for (int index = 0; index < attributes.Count; index++)
                {
                    string attribute = attributes[index];
                    if (
                        (attribute.Trim() != "") &&
                        (attribute != "DMR ID: ") &&
                        (attribute != "D-Star module: ") &&
                        (attribute != "output tone: ") &&
                        (attribute != "input tone: None") &&
                        (attribute != "input tone: ")
                        )
                    {
                        if (strAttributes != "")
                        {
                            strAttributes += ", ";
                        }
                        strAttributes += attribute;
                    }
                }

                using (TableCell cell = new TableCell())
                {
                    cell.Text = strAttributes;
                    row.Cells.Add(cell);
                }

                tableRepeaters.Rows.Add(row);
            }
        }
    }
Example #59
-1
 public ArrayList findAddressesFromSite(String site)
 {
     WebClient client = new WebClient();
     ArrayList ret = new ArrayList();
     if(site == "https://free-proxy-list.net/" || site == "http://www.socks-proxy.net/" || site == "http://www.sslproxies.org/") // good proxies
     {
         String source = client.DownloadString(site);
         MatchCollection coll = Regex.Matches(source, @"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\<\/td\>\<td\>[0-9]{1,6}");
         foreach(Match m in coll)
         {
             String address = m.Value.Replace("</td><td>", ":");
             ret.Add(address);
         }
     }
     else if (site == "http://www.samair.ru/proxy/ip-port/56099619.html" || site == "https://proxy-list.org/english/index.php") // mostly transparent proxies
     {
         String source = client.DownloadString(site);
         MatchCollection coll = Regex.Matches(source, @"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}");
         foreach (Match m in coll)
         {
             String address = m.Value;
             ret.Add(address);
         }
     }
     else if (site == "http://www.freeproxylists.net/")
     {
         // TODO 
         
     }
     return ret;
 }
Example #60
-1
        public static void SetConsoleTitle()
        {
            using (WebClient wc = new WebClient())
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(wc.DownloadString("http://wiki.garrysmod.com/page/Category:Class_Functions"));
                var htmlNodes = doc.DocumentNode.Descendants("li").Where(node => node.Id == "").Reverse().Skip(2).Reverse().ToList();
                _maxFuncs += htmlNodes.Count;

                doc.LoadHtml(wc.DownloadString("http://wiki.garrysmod.com/page/Category:Panel_Functions"));
                htmlNodes = doc.DocumentNode.Descendants("li").Where(node => node.Id == "").Reverse().Skip(2).Reverse().ToList();
                _maxFuncs += htmlNodes.Count;

                doc.LoadHtml(wc.DownloadString("http://wiki.garrysmod.com/page/Category:Hooks"));
                htmlNodes = doc.DocumentNode.Descendants("li").Where(node => node.Id == "").Reverse().Skip(2).Reverse().ToList();
                _maxFuncs += htmlNodes.Count;

                doc.LoadHtml(wc.DownloadString("http://wiki.garrysmod.com/page/Category:Library_Functions"));
                htmlNodes = doc.DocumentNode.Descendants("li").Where(node => node.Id == "").Reverse().Skip(2).Reverse().ToList();
                _maxFuncs += htmlNodes.Count;

                Console.WriteLine($"Found {_maxFuncs} total Funcs, Let's go");
                Console.Title = $"Scraper | [0/{_maxFuncs}]";
            }
        }